From 11ebcd5af24679dde2adfe72434ad89adb1b6eda Mon Sep 17 00:00:00 2001 From: des Date: Wed, 11 Nov 2026 20:16:24 +0100 Subject: [PATCH 1/2] Record the visitor's IP in download_history, not the ingress pod's GET /dl stored r.RemoteAddr as client_ip. Behind Cloudflare -> Hetzner LB -> Traefik that is the Traefik pod IP:port, so every row had the same useless address. X-Real-IP is no better: Traefik sets it to its own peer (the Cloudflare edge). The new internal/clientip package takes the IP from CF-Connecting-IP, then the first X-Forwarded-For entry, then X-Real-IP, then RemoteAddr. Values that are empty, "unknown" or not an IP are skipped and ports are stripped. CLIENT_IP_HEADERS overrides the header order. --- README.md | 2 + internal/clientip/clientip.go | 99 +++++++++++++++++++ internal/clientip/clientip_test.go | 153 +++++++++++++++++++++++++++++ 3 files changed, 254 insertions(+) create mode 100644 internal/clientip/clientip.go create mode 100644 internal/clientip/clientip_test.go diff --git a/README.md b/README.md index 5e98e34..f845f11 100644 --- a/README.md +++ b/README.md @@ -507,6 +507,8 @@ s3: If `s3` is not configured, only the original text-based tools are registered — no S3 dependency. Partial S3 config (e.g. region set but no bucket, or missing credentials) does **not** fail startup — Watchword logs a warning and continues with the file tools disabled. To explicitly disable S3 in environments where partial `WORDSTORE_S3_*` env vars may leak in (e.g. shared k8s ConfigMaps), set `s3.enabled: false` (or `WORDSTORE_S3_ENABLED=false`) — the entire S3 block is then discarded after config load. +**Client IP in `download_history`**: proxied downloads (`GET /dl`) record the client IP. Behind a reverse proxy the socket address is the proxy, so the IP is taken from request headers, in the order given by `CLIENT_IP_HEADERS` (default `cf-connecting-ip,x-forwarded-for,x-real-ip`; comma-separated, case-insensitive). For each header the first comma-separated entry is used (for `X-Forwarded-For` that is the original client); empty, `unknown` and non-IP values are skipped and ports are stripped. The socket address is the final fallback. Only trust these headers when every request reaches Watchword through a proxy that sets or overwrites them. + ### Expiration | Setting | Env var | Default | Description | diff --git a/internal/clientip/clientip.go b/internal/clientip/clientip.go new file mode 100644 index 0000000..633d8e7 --- /dev/null +++ b/internal/clientip/clientip.go @@ -0,0 +1,99 @@ +// Package clientip determines the visitor's IP address for a request that +// reached the server through Cloudflare -> load balancer -> Traefik. +// +// The socket address (r.RemoteAddr) is the ingress pod, and X-Real-IP is set +// by Traefik to its own peer (the Cloudflare edge), so neither identifies the +// visitor. The sources are tried in this order by default: +// +// 1. CF-Connecting-IP +// 2. X-Forwarded-For (first entry only) +// 3. X-Real-IP +// 4. r.RemoteAddr (always the final fallback) +// +// The header list can be overridden with the CLIENT_IP_HEADERS environment +// variable (comma-separated, case-insensitive). For every header, including +// X-Forwarded-For, the first comma-separated entry is used. Values that are +// empty, "unknown" or not an IP address are skipped; ports are stripped. +package clientip + +import ( + "net" + "net/http" + "net/netip" + "os" + "strings" + "sync" +) + +// EnvVar is the environment variable that overrides the header order. +const EnvVar = "CLIENT_IP_HEADERS" + +// DefaultHeaders is the header order used when CLIENT_IP_HEADERS is unset. +var DefaultHeaders = []string{"cf-connecting-ip", "x-forwarded-for", "x-real-ip"} + +var ( + envOnce sync.Once + envHeaders []string +) + +// FromRequest returns the client IP for r using the header order from +// CLIENT_IP_HEADERS (read once) or DefaultHeaders. +func FromRequest(r *http.Request) string { + envOnce.Do(func() { envHeaders = ParseHeaders(os.Getenv(EnvVar)) }) + return FromRequestWith(r, envHeaders) +} + +// ParseHeaders turns a comma-separated header list into header names. An +// empty or blank list yields DefaultHeaders. +func ParseHeaders(s string) []string { + var out []string + for _, h := range strings.Split(s, ",") { + if h = strings.TrimSpace(h); h != "" { + out = append(out, h) + } + } + if len(out) == 0 { + return DefaultHeaders + } + return out +} + +// FromRequestWith returns the first valid IP found in the given headers, in +// order, falling back to r.RemoteAddr. If even RemoteAddr is not a valid IP +// it is returned unchanged. +func FromRequestWith(r *http.Request, headers []string) string { + for _, name := range headers { + // Join repeated header lines so "first entry" means the first value + // overall, not the first value of the last line. + if ip, ok := parse(firstEntry(strings.Join(r.Header.Values(name), ","))); ok { + return ip + } + } + if ip, ok := parse(r.RemoteAddr); ok { + return ip + } + return r.RemoteAddr +} + +func firstEntry(v string) string { + first, _, _ := strings.Cut(v, ",") + return strings.TrimSpace(first) +} + +// parse validates s as an IP address, accepting "ip", "ip:port", +// "[ipv6]" and "[ipv6]:port". IPv4-mapped IPv6 addresses are unmapped. +func parse(s string) (string, bool) { + s = strings.TrimSpace(s) + if s == "" || strings.EqualFold(s, "unknown") { + return "", false + } + if addr, err := netip.ParseAddr(strings.TrimSuffix(strings.TrimPrefix(s, "["), "]")); err == nil { + return addr.Unmap().WithZone("").String(), true + } + if host, _, err := net.SplitHostPort(s); err == nil { + if addr, err := netip.ParseAddr(host); err == nil { + return addr.Unmap().WithZone("").String(), true + } + } + return "", false +} diff --git a/internal/clientip/clientip_test.go b/internal/clientip/clientip_test.go new file mode 100644 index 0000000..c0999e7 --- /dev/null +++ b/internal/clientip/clientip_test.go @@ -0,0 +1,153 @@ +package clientip + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestFromRequestWith(t *testing.T) { + tests := []struct { + name string + headers map[string][]string + remote string + order []string + want string + }{ + { + name: "cf-connecting-ip wins", + headers: map[string][]string{ + "Cf-Connecting-Ip": {"198.51.100.1"}, + "X-Forwarded-For": {"198.51.100.2, 104.16.0.1"}, + "X-Real-Ip": {"104.16.0.1"}, + }, + remote: "10.42.0.5:51234", + want: "198.51.100.1", + }, + { + name: "x-forwarded-for first entry when no cf header", + headers: map[string][]string{ + "X-Forwarded-For": {"198.51.100.2, 104.16.0.1"}, + "X-Real-Ip": {"104.16.0.1"}, + }, + remote: "10.42.0.5:51234", + want: "198.51.100.2", + }, + { + name: "x-forwarded-for first entry across repeated header lines", + headers: map[string][]string{ + "X-Forwarded-For": {"198.51.100.2", "104.16.0.1"}, + }, + remote: "10.42.0.5:51234", + want: "198.51.100.2", + }, + { + name: "x-real-ip last", + headers: map[string][]string{"X-Real-Ip": {"198.51.100.3"}}, + remote: "10.42.0.5:51234", + want: "198.51.100.3", + }, + { + name: "unknown, empty and garbage skipped", + headers: map[string][]string{ + "Cf-Connecting-Ip": {"unknown"}, + "X-Forwarded-For": {" , 198.51.100.9"}, + "X-Real-Ip": {"not-an-ip"}, + }, + remote: "10.42.0.5:51234", + want: "10.42.0.5", + }, + { + name: "ipv4 port stripped", + headers: map[string][]string{"Cf-Connecting-Ip": {"198.51.100.1:5678"}}, + want: "198.51.100.1", + }, + { + name: "bracketed ipv6 port stripped", + headers: map[string][]string{"X-Forwarded-For": {"[2001:db8::1]:443, 104.16.0.1"}}, + want: "2001:db8::1", + }, + { + name: "plain ipv6", + headers: map[string][]string{"Cf-Connecting-Ip": {" 2001:db8::2 "}}, + want: "2001:db8::2", + }, + { + name: "ipv4-mapped ipv6 unmapped", + headers: map[string][]string{"Cf-Connecting-Ip": {"::ffff:198.51.100.4"}}, + want: "198.51.100.4", + }, + { + name: "socket fallback strips port", + remote: "203.0.113.7:4321", + want: "203.0.113.7", + }, + { + name: "socket fallback ipv6", + remote: "[2001:db8::7]:4321", + want: "2001:db8::7", + }, + { + name: "invalid socket address returned as is", + remote: "pipe", + want: "pipe", + }, + { + name: "custom order changes priority", + headers: map[string][]string{ + "Cf-Connecting-Ip": {"198.51.100.1"}, + "X-Real-Ip": {"198.51.100.3"}, + }, + order: []string{"X-Real-IP", "cf-connecting-ip"}, + want: "198.51.100.3", + }, + { + name: "headers not in custom order are ignored", + headers: map[string][]string{"Cf-Connecting-Ip": {"198.51.100.1"}}, + remote: "203.0.113.7:4321", + order: []string{"x-real-ip"}, + want: "203.0.113.7", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := httptest.NewRequest(http.MethodGet, "/", nil) + r.RemoteAddr = tt.remote + for k, vs := range tt.headers { + for _, v := range vs { + r.Header.Add(k, v) + } + } + order := tt.order + if order == nil { + order = DefaultHeaders + } + if got := FromRequestWith(r, order); got != tt.want { + t.Errorf("FromRequestWith() = %q, want %q", got, tt.want) + } + }) + } +} + +func TestParseHeaders(t *testing.T) { + if got := ParseHeaders(""); len(got) != 3 || got[0] != "cf-connecting-ip" { + t.Errorf("ParseHeaders(\"\") = %v, want defaults", got) + } + if got := ParseHeaders(" , "); len(got) != 3 { + t.Errorf("ParseHeaders(blank) = %v, want defaults", got) + } + got := ParseHeaders(" X-Real-IP , ,True-Client-IP") + if len(got) != 2 || got[0] != "X-Real-IP" || got[1] != "True-Client-IP" { + t.Errorf("ParseHeaders() = %v", got) + } +} + +func TestFromRequestReadsEnv(t *testing.T) { + t.Setenv(EnvVar, "x-real-ip") + r := httptest.NewRequest(http.MethodGet, "/", nil) + r.Header.Set("Cf-Connecting-Ip", "198.51.100.1") + r.Header.Set("X-Real-Ip", "198.51.100.3") + if got := FromRequest(r); got != "198.51.100.3" { + t.Errorf("FromRequest() = %q, want X-Real-IP value from env override", got) + } +} From 2755aabe3573017530dcfbc64f3b0fdb87c32a97 Mon Sep 17 00:00:00 2001 From: des Date: Wed, 11 Nov 2026 20:31:39 +0100 Subject: [PATCH 2/2] Route /dl through clientip, treat an empty CLIENT_IP_HEADERS as default The previous commit added internal/clientip but left the handler on r.RemoteAddr: the handler and test edits were not in it. /dl now calls clientip.FromRequest, and handler_stream_test sends the proxy headers with a pod RemoteAddr and expects the visitor's IP. HeadersFromEnv makes the env handling testable. New tests cover an empty or blank env var falling back to the default order. The README has a Client IP table, and docker-compose.yml lists the variable commented out with its default. Claude-Session: https://claude.ai/code/session_017KnhgEygVgyfHhD87euSMC --- README.md | 11 ++++++++- docker-compose.yml | 2 ++ internal/clientip/clientip.go | 13 +++++++--- internal/clientip/clientip_test.go | 34 +++++++++++++++++++++++++++ internal/proxy/handler.go | 4 +++- internal/proxy/handler_stream_test.go | 7 ++++-- 6 files changed, 64 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index f845f11..a1b6233 100644 --- a/README.md +++ b/README.md @@ -507,7 +507,6 @@ s3: If `s3` is not configured, only the original text-based tools are registered — no S3 dependency. Partial S3 config (e.g. region set but no bucket, or missing credentials) does **not** fail startup — Watchword logs a warning and continues with the file tools disabled. To explicitly disable S3 in environments where partial `WORDSTORE_S3_*` env vars may leak in (e.g. shared k8s ConfigMaps), set `s3.enabled: false` (or `WORDSTORE_S3_ENABLED=false`) — the entire S3 block is then discarded after config load. -**Client IP in `download_history`**: proxied downloads (`GET /dl`) record the client IP. Behind a reverse proxy the socket address is the proxy, so the IP is taken from request headers, in the order given by `CLIENT_IP_HEADERS` (default `cf-connecting-ip,x-forwarded-for,x-real-ip`; comma-separated, case-insensitive). For each header the first comma-separated entry is used (for `X-Forwarded-For` that is the original client); empty, `unknown` and non-IP values are skipped and ports are stripped. The socket address is the final fallback. Only trust these headers when every request reaches Watchword through a proxy that sets or overwrites them. ### Expiration @@ -526,6 +525,16 @@ To disable expiration entirely, set `expiration.enabled: false` and `expiration. | `logging.level` | `WORDSTORE_LOGGING_LEVEL` | `info` | `debug`, `info`, `warn`, `error` | | `logging.format` | `WORDSTORE_LOGGING_FORMAT` | `json` | `json` or `text` | +### Client IP + +Proxied downloads (`GET /dl`) record the client IP in `download_history`. Behind a reverse proxy the socket address is the proxy, so the IP comes from request headers. + +| Setting | Env var | Default | Description | +|---------|---------|---------|-------------| +| | `CLIENT_IP_HEADERS` | `cf-connecting-ip,x-forwarded-for,x-real-ip` | Headers to read, in order (comma-separated, case-insensitive). Unset or empty means the default. For each header the first comma-separated entry is used (for `X-Forwarded-For` that is the original client). Empty, `unknown` and non-IP values are skipped, and ports are stripped. The socket address is the final fallback. | + +The default is correct behind Cloudflare. Only trust these headers when every request reaches Watchword through a proxy that sets or overwrites them. + ## Health endpoints Available on a separate port (default `8081`) for monitoring and Kubernetes probes. diff --git a/docker-compose.yml b/docker-compose.yml index d73a153..7edb32d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -32,6 +32,8 @@ services: WORDSTORE_LOGGING_FORMAT: "text" WORDSTORE_LOGGING_LEVEL: "debug" WORDSTORE_LOGGING_FILE: "/data/watchword.log" + # Client IP for download_history: headers tried in order (unset/empty = this default) + # CLIENT_IP_HEADERS: "cf-connecting-ip,x-forwarded-for,x-real-ip" volumes: - ./data:/data diff --git a/internal/clientip/clientip.go b/internal/clientip/clientip.go index 633d8e7..3608735 100644 --- a/internal/clientip/clientip.go +++ b/internal/clientip/clientip.go @@ -11,7 +11,8 @@ // 4. r.RemoteAddr (always the final fallback) // // The header list can be overridden with the CLIENT_IP_HEADERS environment -// variable (comma-separated, case-insensitive). For every header, including +// variable (comma-separated, case-insensitive); unset, empty or only +// whitespace/commas means the default. For every header, including // X-Forwarded-For, the first comma-separated entry is used. Values that are // empty, "unknown" or not an IP address are skipped; ports are stripped. package clientip @@ -39,12 +40,18 @@ var ( // FromRequest returns the client IP for r using the header order from // CLIENT_IP_HEADERS (read once) or DefaultHeaders. func FromRequest(r *http.Request) string { - envOnce.Do(func() { envHeaders = ParseHeaders(os.Getenv(EnvVar)) }) + envOnce.Do(func() { envHeaders = HeadersFromEnv() }) return FromRequestWith(r, envHeaders) } +// HeadersFromEnv returns the header order from CLIENT_IP_HEADERS, or +// DefaultHeaders when it is unset or empty. +func HeadersFromEnv() []string { + return ParseHeaders(os.Getenv(EnvVar)) +} + // ParseHeaders turns a comma-separated header list into header names. An -// empty or blank list yields DefaultHeaders. +// empty list, or one of only whitespace and commas, yields DefaultHeaders. func ParseHeaders(s string) []string { var out []string for _, h := range strings.Split(s, ",") { diff --git a/internal/clientip/clientip_test.go b/internal/clientip/clientip_test.go index c0999e7..ec5d549 100644 --- a/internal/clientip/clientip_test.go +++ b/internal/clientip/clientip_test.go @@ -3,6 +3,7 @@ package clientip import ( "net/http" "net/http/httptest" + "strings" "testing" ) @@ -151,3 +152,36 @@ func TestFromRequestReadsEnv(t *testing.T) { t.Errorf("FromRequest() = %q, want X-Real-IP value from env override", got) } } + +func TestHeadersFromEnv(t *testing.T) { + tests := []struct { + name string + env string + want []string + }{ + {"empty env var means default", "", DefaultHeaders}, + {"blank env var means default", " , ,", DefaultHeaders}, + {"custom order", "x-real-ip, CF-Connecting-IP", []string{"x-real-ip", "CF-Connecting-IP"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Setenv(EnvVar, tt.env) + got := HeadersFromEnv() + if strings.Join(got, ",") != strings.Join(tt.want, ",") { + t.Errorf("HeadersFromEnv() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestEmptyEnvVarUsesDefaultOrder(t *testing.T) { + t.Setenv(EnvVar, "") + r := httptest.NewRequest(http.MethodGet, "/", nil) + r.RemoteAddr = "10.42.0.5:51234" + r.Header.Set("Cf-Connecting-Ip", "198.51.100.1") + r.Header.Set("X-Forwarded-For", "198.51.100.2, 104.16.0.1") + r.Header.Set("X-Real-Ip", "104.16.0.1") + if got := FromRequestWith(r, HeadersFromEnv()); got != "198.51.100.1" { + t.Errorf("got %q, want CF-Connecting-IP value", got) + } +} diff --git a/internal/proxy/handler.go b/internal/proxy/handler.go index a179448..28e2de1 100644 --- a/internal/proxy/handler.go +++ b/internal/proxy/handler.go @@ -12,6 +12,7 @@ import ( "github.com/google/uuid" + "github.com/watchword/watchword/internal/clientip" "github.com/watchword/watchword/internal/domain" "github.com/watchword/watchword/internal/repository" s3client "github.com/watchword/watchword/internal/s3" @@ -119,7 +120,8 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Record download best-effort in background. The request context is // cancelled as soon as ServeHTTP returns, so detach from its cancellation // (keeping its values) and bound the write with its own timeout. - clientIP := r.RemoteAddr + // r.RemoteAddr is the ingress pod; take the visitor from the proxy headers. + clientIP := clientip.FromRequest(r) userAgent := r.UserAgent() recordCtx := context.WithoutCancel(r.Context()) go func() { diff --git a/internal/proxy/handler_stream_test.go b/internal/proxy/handler_stream_test.go index b648131..f60b35e 100644 --- a/internal/proxy/handler_stream_test.go +++ b/internal/proxy/handler_stream_test.go @@ -180,7 +180,10 @@ func TestHandler_RecordDownloadSurvivesRequestCancel(t *testing.T) { signedURL := SignDownloadURL("http://localhost", secret, entryID.String(), "guide.zip", 5*time.Minute) ctx, cancel := context.WithCancel(context.Background()) req := httptest.NewRequest(http.MethodGet, signedURL, nil).WithContext(ctx) - req.RemoteAddr = "203.0.113.7:4321" + req.RemoteAddr = "10.42.0.5:4321" // ingress pod + req.Header.Set("Cf-Connecting-Ip", "203.0.113.7") + req.Header.Set("X-Forwarded-For", "203.0.113.7, 104.16.0.1") + req.Header.Set("X-Real-Ip", "104.16.0.1") // Cloudflare edge req.Header.Set("User-Agent", "curl/8") handler.ServeHTTP(httptest.NewRecorder(), req) @@ -198,7 +201,7 @@ func TestHandler_RecordDownloadSurvivesRequestCancel(t *testing.T) { if !c.hasDeadline { t.Error("RecordDownload ctx has no deadline; want a bounded timeout") } - if c.clientIP != "203.0.113.7:4321" || c.userAgent != "curl/8" { + if c.clientIP != "203.0.113.7" || c.userAgent != "curl/8" { t.Errorf("client info = %q / %q", c.clientIP, c.userAgent) } case <-time.After(5 * time.Second):