feat(deploy): restrict the public perimeter and resolve the client address

This commit is contained in:
shira committed 2026-10-06 21:32:03 +03:00
1 parent e52ffe7bcb
commit 57174dffba
25 files changed
+1224 -25

No files matched your search

+9
View File
@@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"net"
"net/netip"
"os"
"strconv"
"strings"
@@ -118,6 +119,11 @@ type Config struct {
// PasswordHashConcurrency is the number of password hash derivations
// that may run at once; further logins and registrations wait.
PasswordHashConcurrency int
// TrustedProxyCIDRs are the reverse proxies in front of the API. The
// client address is taken from X-Forwarded-For only through them (see
// middleware.ClientIP). Empty trusts no proxy.
TrustedProxyCIDRs []netip.Prefix
}
type LookupEnv func(string) (string, bool)
@@ -167,6 +173,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) {
if err := config.loadPasswordHash(lookup); err != nil {
return Config{}, err
}
if err := config.loadTrustedProxies(lookup); err != nil {
return Config{}, err
}
var err error
config.DatabaseMigrateOnStart, err = boolOrDefault(lookup, "DATABASE_MIGRATE_ON_START", defaultDatabaseMigrateOnStart)
+48
View File
@@ -0,0 +1,48 @@
package config
import (
"fmt"
"net/netip"
"strings"
)
// loadTrustedProxies reads TRUSTED_PROXY_CIDRS, a comma-separated list of
// CIDR prefixes or single addresses of the reverse proxies in front of the
// API. Unset or empty means no proxy is trusted: the client address is the
// connecting peer and X-Forwarded-For is ignored.
func (config *Config) loadTrustedProxies(lookup LookupEnv) error {
value, _ := lookup("TRUSTED_PROXY_CIDRS")
for entry := range strings.SplitSeq(value, ",") {
entry = strings.TrimSpace(entry)
if entry == "" {
continue
}
prefix, err := parseProxyPrefix(entry)
if err != nil {
return fmt.Errorf("Config.loadTrustedProxies - TRUSTED_PROXY_CIDRS entry %q: %w", entry, err)
}
config.TrustedProxyCIDRs = append(config.TrustedProxyCIDRs, prefix)
}
return nil
}
func parseProxyPrefix(entry string) (netip.Prefix, error) {
if !strings.Contains(entry, "/") {
addr, err := netip.ParseAddr(entry)
if err != nil {
return netip.Prefix{}, fmt.Errorf("must be an IP address or a CIDR prefix")
}
addr = addr.Unmap()
return netip.PrefixFrom(addr, addr.BitLen()), nil
}
prefix, err := netip.ParsePrefix(entry)
if err != nil {
return netip.Prefix{}, fmt.Errorf("must be an IP address or a CIDR prefix")
}
if prefix.Bits() == 0 {
// A prefix that matches every address would trust every client and
// let it choose its own address.
return netip.Prefix{}, fmt.Errorf("must not match every address")
}
return prefix.Masked(), nil
}
+45
View File
@@ -0,0 +1,45 @@
package config
import (
"strings"
"testing"
)
func TestLoadFromEnvTrustedProxyCIDRs(t *testing.T) {
tests := map[string]struct {
value string
want []string
}{
"unset": {value: "", want: nil},
"list": {value: " 172.16.0.0/12, 10.79.0.1 ,fd00::/8", want: []string{"172.16.0.0/12", "10.79.0.1/32", "fd00::/8"}},
"masked": {value: "10.79.0.1/30", want: []string{"10.79.0.0/30"}},
"empty items": {value: ",,10.0.0.0/8,", want: []string{"10.0.0.0/8"}},
}
for name, test := range tests {
settings, err := LoadFromEnv(testEnvironment(map[string]string{"TRUSTED_PROXY_CIDRS": test.value}))
if err != nil {
t.Fatalf("LoadFromEnv(%s) error = %v", name, err)
}
got := make([]string, 0, len(settings.TrustedProxyCIDRs))
for _, prefix := range settings.TrustedProxyCIDRs {
got = append(got, prefix.String())
}
if strings.Join(got, ";") != strings.Join(test.want, ";") {
t.Fatalf("LoadFromEnv(%s) TrustedProxyCIDRs = %v, want %v", name, got, test.want)
}
}
}
func TestLoadFromEnvRejectsTrustedProxyCIDRs(t *testing.T) {
for name, value := range map[string]string{
"not an address": "proxy.internal",
"bad prefix": "10.0.0.0/33",
"match all v4": "0.0.0.0/0",
"match all v6": "::/0",
} {
_, err := LoadFromEnv(testEnvironment(map[string]string{"TRUSTED_PROXY_CIDRS": value}))
if err == nil || !strings.Contains(err.Error(), "Config.loadTrustedProxies - TRUSTED_PROXY_CIDRS") {
t.Fatalf("LoadFromEnv(%s) error = %v, want a TRUSTED_PROXY_CIDRS error", name, err)
}
}
}
@@ -0,0 +1,134 @@
package middleware
import (
"context"
"net"
"net/http"
"net/netip"
"strings"
)
// maxForwardedEntries bounds the X-Forwarded-For entries that are examined. A
// longer chain is not a legitimate proxy chain here (edge, app Nginx, backend);
// the entries beyond the bound, which sit furthest from this server, are
// ignored.
const maxForwardedEntries = 16
type clientAddrKey struct{}
// ResolveClientAddr returns the address of the client that made a request, for
// rate limiting and other in-memory decisions. It never logs or stores it.
//
// remoteAddr is the connecting peer (http.Request.RemoteAddr), forwardedFor
// holds every X-Forwarded-For header line, and trusted lists the proxies this
// server runs behind. The rules:
// - A peer outside trusted is the client, and the header is ignored whole:
// anyone can send it.
// - For a trusted peer, the entries are read from the right, which is the
// side that the nearest proxy wrote. Each trusted entry is another proxy
// and is skipped; the first entry that is not trusted is the client. A
// value a client put to the left of the first untrusted entry is never
// reached.
// - An entry that is not an IP address stops the walk, and the last
// address that was already proven (the nearest trusted hop) is returned.
// - When every entry is trusted, the leftmost one is returned.
//
// The result is unmapped (an IPv4-mapped IPv6 address becomes IPv4) and has
// no zone. It is invalid only when remoteAddr is not an IP address.
func ResolveClientAddr(remoteAddr string, forwardedFor []string, trusted []netip.Prefix) netip.Addr {
peer, ok := parseAddr(hostOf(remoteAddr))
if !ok {
return netip.Addr{}
}
if !isTrusted(peer, trusted) {
return peer
}
entries := forwardedEntries(forwardedFor)
hop := peer
for index := len(entries) - 1; index >= 0; index-- {
candidate, ok := parseAddr(entries[index])
if !ok {
return hop
}
if !isTrusted(candidate, trusted) {
return candidate
}
hop = candidate
}
return hop
}
// ClientIP resolves the client address with ResolveClientAddr and stores it in
// the request context for ClientAddr. With no trusted proxies configured the
// client is always the connecting peer.
func ClientIP(trusted []netip.Prefix) func(http.Handler) http.Handler {
trusted = append([]netip.Prefix(nil), trusted...)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
addr := ResolveClientAddr(r.RemoteAddr, r.Header.Values("X-Forwarded-For"), trusted)
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), clientAddrKey{}, addr)))
})
}
}
// ClientAddr returns the client address that the ClientIP middleware stored.
// The second result is false when the middleware did not run or the peer
// address was not an IP address; a caller must then fail closed, for example
// by sharing one limiter bucket, instead of skipping its limit.
func ClientAddr(ctx context.Context) (netip.Addr, bool) {
addr, ok := ctx.Value(clientAddrKey{}).(netip.Addr)
return addr, ok && addr.IsValid()
}
// LimiterKey is the key under which a rate limiter counts a client: an IPv4
// address as is and an IPv6 address reduced to its /64 network, because one
// subscriber commonly controls a whole /64 and could otherwise pick a new
// bucket per request. The key lives only in limiter memory (or a Redis key
// with a window-length expiry); it must not be logged or stored longer.
func LimiterKey(addr netip.Addr) string {
addr = addr.Unmap()
if addr.Is6() {
prefix, err := addr.Prefix(64)
if err == nil {
return prefix.String()
}
}
return addr.String()
}
func forwardedEntries(lines []string) []string {
var entries []string
for _, line := range lines {
for part := range strings.SplitSeq(line, ",") {
entries = append(entries, strings.TrimSpace(part))
}
}
if len(entries) > maxForwardedEntries {
entries = entries[len(entries)-maxForwardedEntries:]
}
return entries
}
func hostOf(remoteAddr string) string {
if host, _, err := net.SplitHostPort(remoteAddr); err == nil {
return host
}
return remoteAddr
}
func parseAddr(value string) (netip.Addr, bool) {
addr, err := netip.ParseAddr(strings.TrimSpace(value))
if err != nil {
return netip.Addr{}, false
}
return addr.WithZone("").Unmap(), true
}
func isTrusted(addr netip.Addr, trusted []netip.Prefix) bool {
for _, prefix := range trusted {
if prefix.Contains(addr) {
return true
}
}
return false
}
@@ -0,0 +1,145 @@
package middleware
import (
"net/http"
"net/http/httptest"
"net/netip"
"testing"
)
func prefixes(t *testing.T, values ...string) []netip.Prefix {
t.Helper()
result := make([]netip.Prefix, 0, len(values))
for _, value := range values {
prefix, err := netip.ParsePrefix(value)
if err != nil {
t.Fatalf("ParsePrefix(%q) error = %v", value, err)
}
result = append(result, prefix)
}
return result
}
func TestResolveClientAddr(t *testing.T) {
// The deployed chain: client -> edge (10.79.0.1) -> app Nginx container
// (172.18.0.5) -> backend. Nginx sends one entry, the client address.
trusted := prefixes(t, "172.16.0.0/12", "10.79.0.0/30")
tests := []struct {
name string
remoteAddr string
forwarded []string
trusted []netip.Prefix
want string
}{
{"trusted chain returns the client", "172.18.0.5:41234", []string{"203.0.113.9"}, trusted, "203.0.113.9"},
{"edge entry is skipped", "172.18.0.5:1", []string{"203.0.113.9, 10.79.0.1"}, trusted, "203.0.113.9"},
{"client value left of the proven client is ignored", "172.18.0.5:1", []string{"198.51.100.7, 203.0.113.9, 10.79.0.1"}, trusted, "203.0.113.9"},
{"spoofed first entry cannot replace the real client", "172.18.0.5:1", []string{"1.2.3.4, 203.0.113.9"}, trusted, "203.0.113.9"},
{"untrusted peer ignores the header", "198.51.100.20:5555", []string{"1.2.3.4"}, trusted, "198.51.100.20"},
{"untrusted peer with a trusted looking entry", "198.51.100.20:5555", []string{"10.79.0.1"}, trusted, "198.51.100.20"},
{"no trusted proxies means the peer", "172.18.0.5:1", []string{"203.0.113.9"}, nil, "172.18.0.5"},
{"no header means the proxy itself", "172.18.0.5:1", nil, trusted, "172.18.0.5"},
{"all entries trusted returns the leftmost", "172.18.0.5:1", []string{"172.18.0.1, 10.79.0.1"}, trusted, "172.18.0.1"},
{"several header lines are one list", "172.18.0.5:1", []string{"1.2.3.4", "203.0.113.9"}, trusted, "203.0.113.9"},
{"garbage entry stops at the proven hop", "172.18.0.5:1", []string{"203.0.113.9, not-an-ip"}, trusted, "172.18.0.5"},
{"entry with a port is not an address", "172.18.0.5:1", []string{"203.0.113.9:80"}, trusted, "172.18.0.5"},
{"IPv4-mapped IPv6 is unmapped", "172.18.0.5:1", []string{"::ffff:203.0.113.9"}, trusted, "203.0.113.9"},
{"IPv6 client", "172.18.0.5:1", []string{"2001:db8::1"}, trusted, "2001:db8::1"},
{"peer without a port", "172.18.0.5", []string{"203.0.113.9"}, trusted, "203.0.113.9"},
{"IPv6 peer in brackets", "[::1]:80", []string{"203.0.113.9"}, prefixes(t, "::1/128"), "203.0.113.9"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := ResolveClientAddr(test.remoteAddr, test.forwarded, test.trusted)
if got.String() != test.want {
t.Fatalf("ResolveClientAddr() = %s, want %s", got, test.want)
}
})
}
}
func TestResolveClientAddrInvalidPeer(t *testing.T) {
if got := ResolveClientAddr("pipe", []string{"203.0.113.9"}, prefixes(t, "0.0.0.0/0")); got.IsValid() {
t.Fatalf("ResolveClientAddr() = %s, want an invalid address", got)
}
}
func TestResolveClientAddrLongChainIsBounded(t *testing.T) {
// A client cannot push the real entry out of the examined window: the
// bound keeps the entries nearest to this server.
entries := "9.9.9.9"
for range 40 {
entries += ", 8.8.8.8"
}
entries += ", 203.0.113.9"
got := ResolveClientAddr("172.18.0.5:1", []string{entries}, prefixes(t, "172.16.0.0/12"))
if got.String() != "203.0.113.9" {
t.Fatalf("ResolveClientAddr() = %s, want 203.0.113.9", got)
}
}
func TestClientIPMiddleware(t *testing.T) {
trusted := prefixes(t, "172.16.0.0/12")
handler := ClientIP(trusted)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
addr, ok := ClientAddr(r.Context())
if !ok {
t.Error("ClientAddr() reported no address")
}
_, _ = w.Write([]byte(addr.String()))
}))
tests := []struct {
name, remote, forwarded, want string
}{
{"trusted chain", "172.18.0.5:1", "203.0.113.9", "203.0.113.9"},
{"spoof from an untrusted peer", "198.51.100.20:1", "203.0.113.9", "198.51.100.20"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "/", nil)
request.RemoteAddr = test.remote
request.Header.Set("X-Forwarded-For", test.forwarded)
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Body.String() != test.want {
t.Fatalf("client = %s, want %s", recorder.Body.String(), test.want)
}
})
}
}
func TestClientIPDoesNotAliasTrustedList(t *testing.T) {
trusted := prefixes(t, "172.16.0.0/12")
handler := ClientIP(trusted)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
addr, _ := ClientAddr(r.Context())
_, _ = w.Write([]byte(addr.String()))
}))
trusted[0] = netip.MustParsePrefix("198.51.100.0/24")
request := httptest.NewRequest(http.MethodGet, "/", nil)
request.RemoteAddr = "172.18.0.5:1"
request.Header.Set("X-Forwarded-For", "203.0.113.9")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Body.String() != "203.0.113.9" {
t.Fatalf("client = %s, want the list copied at construction", recorder.Body.String())
}
}
func TestClientAddrWithoutMiddleware(t *testing.T) {
if _, ok := ClientAddr(httptest.NewRequest(http.MethodGet, "/", nil).Context()); ok {
t.Fatal("ClientAddr() reported an address without the middleware")
}
}
func TestLimiterKey(t *testing.T) {
tests := map[string]string{
"203.0.113.9": "203.0.113.9",
"::ffff:203.0.113.9": "203.0.113.9",
"2001:db8:1:2:3:4:5:6": "2001:db8:1:2::/64",
"2001:db8:1:2:ffff:ffff::abc": "2001:db8:1:2::/64",
}
for input, want := range tests {
if got := LimiterKey(netip.MustParseAddr(input)); got != want {
t.Errorf("LimiterKey(%s) = %s, want %s", input, got, want)
}
}
}