gateway.go131 lines, 5.2 KB
| 1 | // Package gateway is the payments API's front door. It routes requests to |
| 2 | // our services, and holds no business rules: the services decide everything. |
| 3 | package gateway |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "log/slog" |
| 8 | "net/http" |
| 9 | "net/url" |
| 10 | "time" |
| 11 | |
| 12 | "github.com/fiston-user/payments/internal/platform/authn" |
| 13 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 14 | "github.com/fiston-user/payments/internal/wallet/walletclient" |
| 15 | "github.com/redis/go-redis/v9" |
| 16 | "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" |
| 17 | ) |
| 18 | |
| 19 | // Config is what the gateway needs: services, token checks and limits. |
| 20 | type Config struct { |
| 21 | AuthURL *url.URL // the auth service, over HTTP |
| 22 | Transfers *url.URL // the transfer service, over HTTP |
| 23 | Webhooks *url.URL // the webhook service, over HTTP |
| 24 | WalletAPI *url.URL // the wallet's REST API, for conversions |
| 25 | Wallet *walletclient.Client // the wallet service, over gRPC |
| 26 | Verifier *authn.Verifier |
| 27 | Redis *redis.Client // the rate limiters' buckets |
| 28 | IPLimit int // requests per minute from one IP address, to public routes |
| 29 | UserLimit int // requests per minute from one user |
| 30 | Origins []string // browser apps that may call us |
| 31 | Logger *slog.Logger |
| 32 | } |
| 33 | |
| 34 | // How long each service gets to answer. Auth hashes passwords, slowly. |
| 35 | const ( |
| 36 | authTimeout = 5 * time.Second |
| 37 | walletTimeout = 3 * time.Second |
| 38 | transferTimeout = 3 * time.Second |
| 39 | webhookTimeout = 3 * time.Second |
| 40 | reportTimeout = time.Minute // a year of entries |
| 41 | ) |
| 42 | |
| 43 | // New returns the gateway's handler. |
| 44 | func New(cfg Config) http.Handler { |
| 45 | byIP := NewLimiter(cfg.Redis, cfg.IPLimit, time.Minute).Middleware(clientIP) |
| 46 | byUser := NewLimiter(cfg.Redis, cfg.UserLimit, time.Minute).Middleware(userID) |
| 47 | // Public routes are limited per IP. Private ones need a token first. |
| 48 | public := func(d time.Duration, h http.Handler) http.Handler { |
| 49 | return httpx.Chain(h, byIP, timeout(d)) |
| 50 | } |
| 51 | private := func(d time.Duration, h http.Handler) http.Handler { |
| 52 | return httpx.Chain(h, cfg.Verifier.Require, byUser, timeout(d)) |
| 53 | } |
| 54 | |
| 55 | mux := http.NewServeMux() |
| 56 | |
| 57 | auth := newProxy(cfg.AuthURL) |
| 58 | mux.Handle("POST /v1/auth/register", public(authTimeout, auth)) |
| 59 | mux.Handle("POST /v1/auth/login", public(authTimeout, auth)) |
| 60 | mux.Handle("POST /v1/auth/refresh", public(authTimeout, auth)) |
| 61 | mux.Handle("/v1/auth/", private(authTimeout, auth)) |
| 62 | |
| 63 | wallet := &walletAPI{client: cfg.Wallet} |
| 64 | mux.Handle("POST /v1/wallets", private(walletTimeout, rpc(wallet.create))) |
| 65 | mux.Handle("GET /v1/wallets/{id}", private(walletTimeout, rpc(wallet.get))) |
| 66 | mux.Handle("GET /v1/wallets/{id}/balance", private(walletTimeout, rpc(wallet.balance))) |
| 67 | mux.Handle("POST /v1/wallets/{id}/deposits", private(walletTimeout, rpc(wallet.deposit))) |
| 68 | // Statements are files, not messages: the wallet's REST API streams them. |
| 69 | mux.Handle("GET /v1/wallets/{id}/statement.csv", private(reportTimeout, newProxy(cfg.WalletAPI))) |
| 70 | // Quotes and conversions: only our users call them, so they stay REST. |
| 71 | mux.Handle("/v1/fx/", private(walletTimeout, newProxy(cfg.WalletAPI))) |
| 72 | |
| 73 | // Transfers are sagas now: the transfer service runs them. |
| 74 | transfers := newProxy(cfg.Transfers) |
| 75 | mux.Handle("POST /v1/transfers", private(transferTimeout, transfers)) |
| 76 | mux.Handle("GET /v1/transfers/{id}", private(transferTimeout, transfers)) |
| 77 | |
| 78 | // Webhook endpoints and their deliveries: the webhook service checks the rest. |
| 79 | mux.Handle("/v1/webhooks/", private(webhookTimeout, newProxy(cfg.Webhooks))) |
| 80 | mux.HandleFunc("/", httpx.NotFound) |
| 81 | |
| 82 | // Observe goes first. We face the internet, so a client's trace context |
| 83 | // is only linked, never continued: nobody outside decides what we sample. |
| 84 | edge := otelhttp.WithPublicEndpointFn(func(*http.Request) bool { return true }) |
| 85 | return httpx.Chain(httpx.Routes(mux), |
| 86 | httpx.Observe(edge), |
| 87 | httpx.RequestID, |
| 88 | httpx.AccessLog(cfg.Logger), |
| 89 | httpx.Recover(cfg.Logger), |
| 90 | secureHeaders, |
| 91 | cors(cfg.Origins), |
| 92 | limitBody(64<<10), |
| 93 | ) |
| 94 | } |
| 95 | |
| 96 | // secureHeaders asks browsers to be strict with our answers: never sniff JSON |
| 97 | // into HTML, never frame it, run nothing in it, keep our URLs to ourselves, |
| 98 | // and only ever talk to us over HTTPS. |
| 99 | func secureHeaders(next http.Handler) http.Handler { |
| 100 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 101 | h := w.Header() |
| 102 | h.Set("X-Content-Type-Options", "nosniff") |
| 103 | h.Set("X-Frame-Options", "DENY") |
| 104 | h.Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'") |
| 105 | h.Set("Referrer-Policy", "no-referrer") |
| 106 | // Browsers only heed it over HTTPS, which our load balancer serves. |
| 107 | h.Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains") |
| 108 | next.ServeHTTP(w, r) |
| 109 | }) |
| 110 | } |
| 111 | |
| 112 | // timeout gives each request a deadline, which its context carries upstream. |
| 113 | func timeout(d time.Duration) httpx.Middleware { |
| 114 | return func(next http.Handler) http.Handler { |
| 115 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 116 | ctx, cancel := context.WithTimeout(r.Context(), d) |
| 117 | defer cancel() |
| 118 | next.ServeHTTP(w, r.WithContext(ctx)) |
| 119 | }) |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | // limitBody caps request bodies at n bytes, the proxied ones too. |
| 124 | func limitBody(n int64) httpx.Middleware { |
| 125 | return func(next http.Handler) http.Handler { |
| 126 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 127 | r.Body = http.MaxBytesReader(w, r.Body, n) |
| 128 | next.ServeHTTP(w, r) |
| 129 | }) |
| 130 | } |
| 131 | } |