Skip to content
This repository has been archived by the owner on Jul 12, 2023. It is now read-only.

https -> ens protocol redirect service #546

Merged
merged 5 commits into from
Sep 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions cmd/enx-redirect/assets/404.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{{define "404"}}
<!doctype html>
<html lang="en">
<head>
{{template "head" .}}
</head>

<body>
<main role="main" class="container mt-5">
<h1>Not found.</h1>
<p>
<code>{{.requestURI}}</code> was not found on this server.
</p>
<p>
If you are trying to submit your anonymous data for exposure notifications,
please contact the public health authority that issued your verification code.
</p>
</main>
</body>
</html>
{{end}}
17 changes: 17 additions & 0 deletions cmd/enx-redirect/assets/500.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{{define "500"}}
<!doctype html>
<html lang="en">
<head>
{{template "head" .}}
</head>

<body>
<main role="main" class="container mt-5">
<h1>Internal server error</h1>
<p>
{{.error}}
</p>
</main>
</body>
</html>
{{end}}
39 changes: 39 additions & 0 deletions cmd/enx-redirect/assets/header.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{{define "head"}}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta data-build-id="{{.build_id}}" data-build-tag="{{.build_tag}}">

<link rel="apple-touch-icon" sizes="180x180" href="/static/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png">
<link rel="manifest" href="/static/site.webmanifest">
<link rel="mask-icon" href="/static/safari-pinned-tab.svg" color="#5bbad5">
<link rel="shortcut icon" href="/static/favicon.ico">
<meta name="msapplication-TileColor" content="#ff0554">
<meta name="msapplication-config" content="/static/browserconfig.xml">
<meta name="theme-color" content="#ffffff">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/open-iconic/1.1.1/font/css/open-iconic-bootstrap.min.css"
integrity="sha256-BJ/G+e+y7bQdrYkS2RBTyNfBHpA9IuGaPmf9htub5MQ=" crossorigin="anonymous">

<title>Exposure Notifications Express Redirect Service</title>

<style type="text/css">
nav.navbar {
margin-bottom: 40px;
}

div.realm-header {
background-color: #0055b1;
}

a.input-group-text:hover {
cursor: pointer;
text-decoration: none;
}

</style>
{{end}}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

line ending?

109 changes: 109 additions & 0 deletions cmd/enx-redirect/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
"context"
"fmt"
"net/http"
"os"
"strconv"

"github.com/google/exposure-notifications-verification-server/pkg/buildinfo"
"github.com/google/exposure-notifications-verification-server/pkg/config"
"github.com/google/exposure-notifications-verification-server/pkg/controller/middleware"
"github.com/google/exposure-notifications-verification-server/pkg/controller/redirect"
"github.com/google/exposure-notifications-verification-server/pkg/render"

"github.com/google/exposure-notifications-server/pkg/logging"
"github.com/google/exposure-notifications-server/pkg/observability"
"github.com/google/exposure-notifications-server/pkg/server"

"github.com/gorilla/mux"
"github.com/sethvargo/go-signalcontext"
)

func main() {
ctx, done := signalcontext.OnInterrupt()

debug, _ := strconv.ParseBool(os.Getenv("LOG_DEBUG"))
logger := logging.NewLogger(debug)
logger = logger.With("build_id", buildinfo.BuildID)
logger = logger.With("build_tag", buildinfo.BuildTag)

ctx = logging.WithLogger(ctx, logger)

err := realMain(ctx)
done()

if err != nil {
logger.Fatal(err)
}
logger.Info("successful shutdown")
}

func realMain(ctx context.Context) error {
logger := logging.FromContext(ctx)

config, err := config.NewRedirectConfig(ctx)
if err != nil {
return fmt.Errorf("failed to process config: %w", err)
}

// Setup monitoring
logger.Info("configuring observability exporter")
oeConfig := config.ObservabilityExporterConfig()
oe, err := observability.NewFromEnv(ctx, oeConfig)
if err != nil {
return fmt.Errorf("unable to create ObservabilityExporter provider: %w", err)
}
if err := oe.StartExporter(); err != nil {
return fmt.Errorf("error initializing observability exporter: %w", err)
}
defer oe.Close()
logger.Infow("observability exporter", "config", oeConfig)

// Create the router
r := mux.NewRouter()

// Create the renderer
h, err := render.New(ctx, config.AssetsPath, config.DevMode)
if err != nil {
return fmt.Errorf("failed to create renderer: %w", err)
}

// Install common security headers
r.Use(middleware.SecureHeaders(ctx, config.DevMode, "html"))

// Enable debug headers
processDebug := middleware.ProcessDebug(ctx)
r.Use(processDebug)

redirectController, err := redirect.New(ctx, config, h)
if err != nil {
return err
}
r.Handle("/", redirectController.HandleIndex()).Methods("GET")

mux := http.NewServeMux()
mikehelmick marked this conversation as resolved.
Show resolved Hide resolved
mux.Handle("/", r)

srv, err := server.New(config.Port)
if err != nil {
return fmt.Errorf("failed to create server: %w", err)
}
logger.Infow("server listening", "port", config.Port)
return srv.ServeHTTPHandler(ctx, mux)
}
82 changes: 82 additions & 0 deletions pkg/config/redirect_config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package config

import (
"context"
"fmt"
"strings"

"github.com/google/exposure-notifications-verification-server/pkg/ratelimit"

"github.com/google/exposure-notifications-server/pkg/observability"

"github.com/sethvargo/go-envconfig"
)

// RedirectConfig represents the environment based config for the redirect server.
type RedirectConfig struct {
Observability observability.Config

Port string `env:"PORT, default=8080"`

AssetsPath string `env:"ASSETS_PATH, default=./cmd/enx-redirect/assets"`

// If Dev mode is true, extended logging is enabled and template
// auto-reload is enabled.
DevMode bool `env:"DEV_MODE"`

// A list of prefixes to match.
// "region.example.com,otherregion.example.com"
// all prefixes are redirected to
// "ens://"
// The append region is added to the end
// "US-AA,US-BB"
//
// As an example, if the redirect service receives a request like
// https://region.example.com/v?c=1234
// Will result in a redict to (based on the above configuration)
// ens://v?c=1234&r=US-AA
Hostnames []string `env:"HOSTNAME"`
RegionCodes []string `env:"REGION_CODE"`

// Rate limiting configuration
RateLimit ratelimit.Config
}

// NewRedirectConfig initializes and validates a RedirectConfig struct.
func NewRedirectConfig(ctx context.Context) (*RedirectConfig, error) {
var config RedirectConfig
if err := ProcessWith(ctx, &config, envconfig.OsLookuper()); err != nil {
return nil, err
}
return &config, nil
}

func (c *RedirectConfig) ObservabilityExporterConfig() *observability.Config {
return &c.Observability
}

func (c *RedirectConfig) HostnameToRegion() (map[string]string, error) {
if len(c.Hostnames) != len(c.RegionCodes) {
return nil, fmt.Errorf("HOSTNAME and REGION_CODE must be lists of the same length")
}

hostnameToRegion := make(map[string]string, len(c.Hostnames))
for i, prefix := range c.Hostnames {
hostnameToRegion[prefix] = strings.ToUpper(c.RegionCodes[i])
}
return hostnameToRegion, nil
}
50 changes: 50 additions & 0 deletions pkg/controller/redirect/index.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package redirect

import (
"fmt"
"net/http"
"strings"

"github.com/google/exposure-notifications-verification-server/pkg/controller"
)

func (c *Controller) HandleIndex() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

path := r.URL.RequestURI()
host := r.Host
// Strip of the port if that was passed along in the host header.
if i := strings.Index(host, ":"); i > 0 {
host = host[0:i]
}

for hostname, region := range c.hostnameToRegion {
if host == hostname {
sendTo := fmt.Sprintf("ens:/%s&r=%s", path, region)
http.Redirect(w, r, sendTo, http.StatusSeeOther)
return
}
}

c.logger.Warnw("unknown host", "host", host)

ctx := r.Context()
m := controller.TemplateMapFromContext(ctx)
m["requestURI"] = fmt.Sprintf("https://%s%s", host, path)
c.h.RenderHTMLStatus(w, http.StatusNotFound, "404", m)
})
}
52 changes: 52 additions & 0 deletions pkg/controller/redirect/redirect.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package redirect defines the controller for the deep link redirector.
package redirect

import (
"context"
"fmt"

"github.com/google/exposure-notifications-verification-server/pkg/config"
"github.com/google/exposure-notifications-verification-server/pkg/render"

"github.com/google/exposure-notifications-server/pkg/logging"

"go.uber.org/zap"
)

type Controller struct {
config *config.RedirectConfig
h *render.Renderer
logger *zap.SugaredLogger
hostnameToRegion map[string]string
}

// New creates a new login controller.
func New(ctx context.Context, config *config.RedirectConfig, h *render.Renderer) (*Controller, error) {
logger := logging.FromContext(ctx).Named("login")

cfgMap, err := config.HostnameToRegion()
if err != nil {
return nil, fmt.Errorf("invalid config: %w", err)
}

return &Controller{
config: config,
h: h,
logger: logger,
hostnameToRegion: cfgMap,
}, nil
}