Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: honour the trusted-proxy model when resolving the client IP (PIN-281)

Luigi Agosti19fcf7d0ab71
diff --git a/docs/reference/config.md b/docs/reference/config.md
index b567a273..05d83305 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -720,7 +720,7 @@ on stderr when you run `config set`, `config patch` or `config validate` — and
blocks anything. There is nothing to fix and nothing to remove; the value simply has no
effect. Validation errors, such as an out-of-range `server.port`, still block a save.
-`server.trustProxyHeaders` should stay `false` unless PinchTab is behind a trusted reverse proxy that overwrites `Forwarded` and `X-Forwarded-*` headers. Do not enable it on direct-exposure deployments or behind proxies that pass client-supplied forwarding headers through unchanged.
+`server.trustProxyHeaders` should stay `false` unless PinchTab is behind a trusted reverse proxy that overwrites `Forwarded` and `X-Forwarded-*` headers. Do not enable it on direct-exposure deployments or behind proxies that pass client-supplied forwarding headers through unchanged. When it is enabled, the client-most forwarded address is also the client identity: rate-limit buckets, the concurrent-stream cap and every audit line are keyed on it rather than on the proxy's address.
## Legacy Flat Format
diff --git a/internal/authn/client_ip.go b/internal/authn/client_ip.go
new file mode 100644
index 00000000..b93c1f34
--- /dev/null
+++ b/internal/authn/client_ip.go
@@ -0,0 +1,64 @@
+package authn
+
+import (
+ "context"
+ "net"
+ "net/http"
+ "strings"
+)
+
+const forwardedForDirective = "for"
+
+type clientIPKey struct{}
+
+// resolvedClientIP distinguishes "the chain resolved a value" from "nothing ran",
+// which a bare string on the context cannot: absent must fall back to the peer
+// address, and a resolved empty value must not be mistaken for it.
+type resolvedClientIP struct{ value string }
+
+// ResolveClientIP adjudicates the client identity for a request. It is the one
+// place a forwarding header is read for that decision; every consumer reads the
+// answer back through ClientIP.
+func ResolveClientIP(r *http.Request, trustProxy bool) string {
+ if r == nil {
+ return ""
+ }
+ if trustProxy {
+ if forwarded := forwardedClientIP(r); forwarded != "" {
+ return forwarded
+ }
+ }
+ return peerIP(r)
+}
+
+func WithClientIP(ctx context.Context, ip string) context.Context {
+ return context.WithValue(ctx, clientIPKey{}, resolvedClientIP{value: ip})
+}
+
+func forwardedClientIP(r *http.Request) string {
+ if header := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); header != "" {
+ if ip := forwardedIP(firstForwardedValue(header)); ip != "" {
+ return ip
+ }
+ }
+ return forwardedIP(forwardedDirective(r.Header.Get("Forwarded"), forwardedForDirective))
+}
+
+func forwardedIP(value string) string {
+ value = strings.Trim(strings.TrimSpace(value), `"`)
+ if value == "" {
+ return ""
+ }
+ if host, _, err := net.SplitHostPort(value); err == nil && host != "" {
+ value = host
+ }
+ return strings.Trim(value, "[]")
+}
+
+func peerIP(r *http.Request) string {
+ host, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
+ if err == nil && host != "" {
+ return host
+ }
+ return strings.TrimSpace(r.RemoteAddr)
+}
diff --git a/internal/authn/client_ip_test.go b/internal/authn/client_ip_test.go
new file mode 100644
index 00000000..5b76367a
--- /dev/null
+++ b/internal/authn/client_ip_test.go
@@ -0,0 +1,122 @@
+package authn
+
+import (
+ "context"
+ "net/http/httptest"
+ "sort"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/srccensus"
+)
+
+func TestResolveClientIPIgnoresForwardingHeadersWhenProxyIsUntrusted(t *testing.T) {
+ req := httptest.NewRequest("GET", "/", nil)
+ req.RemoteAddr = "198.51.100.10:43123"
+ req.Header.Set("X-Forwarded-For", "203.0.113.9, 10.0.0.1")
+ req.Header.Set("Forwarded", "for=203.0.113.7")
+
+ if got := ResolveClientIP(req, false); got != "198.51.100.10" {
+ t.Fatalf("ResolveClientIP(untrusted) = %q, want the peer address", got)
+ }
+}
+
+func TestResolveClientIPTakesTheClientMostForwardedEntryWhenProxyIsTrusted(t *testing.T) {
+ cases := []struct {
+ name string
+ headers map[string]string
+ want string
+ }{
+ {"x-forwarded-for chain", map[string]string{"X-Forwarded-For": "203.0.113.9, 10.0.0.1"}, "203.0.113.9"},
+ {"x-forwarded-for with port", map[string]string{"X-Forwarded-For": "203.0.113.9:51234"}, "203.0.113.9"},
+ {"forwarded directive", map[string]string{"Forwarded": `for=203.0.113.7;proto=https`}, "203.0.113.7"},
+ {"forwarded client-most element", map[string]string{"Forwarded": `for=203.0.113.7, for=10.0.0.1`}, "203.0.113.7"},
+ {"forwarded quoted ipv6 with port", map[string]string{"Forwarded": `for="[2001:db8::1]:8080"`}, "2001:db8::1"},
+ {"x-forwarded-for preferred over forwarded", map[string]string{"X-Forwarded-For": "203.0.113.9", "Forwarded": "for=203.0.113.7"}, "203.0.113.9"},
+ {"no forwarding header", nil, "198.51.100.10"},
+ {"empty forwarding header", map[string]string{"X-Forwarded-For": " "}, "198.51.100.10"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ req := httptest.NewRequest("GET", "/", nil)
+ req.RemoteAddr = "198.51.100.10:43123"
+ for name, value := range tc.headers {
+ req.Header.Set(name, value)
+ }
+
+ if got := ResolveClientIP(req, true); got != tc.want {
+ t.Fatalf("ResolveClientIP(trusted) = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestClientIPReadsTheResolvedValueFromTheContext(t *testing.T) {
+ req := httptest.NewRequest("GET", "/", nil)
+ req.RemoteAddr = "198.51.100.10:43123"
+ req = req.WithContext(WithClientIP(req.Context(), "203.0.113.9"))
+
+ if got := ClientIP(req); got != "203.0.113.9" {
+ t.Fatalf("ClientIP() = %q, want the resolved value", got)
+ }
+}
+
+// Absent is not empty: a request that ran through no resolving chain must answer
+// the peer address, which is what every audit line and limiter did before the
+// trusted-proxy model reached client identity.
+func TestClientIPFallsBackToThePeerWhenNothingResolvedOne(t *testing.T) {
+ req := httptest.NewRequest("GET", "/", nil)
+ req.RemoteAddr = "198.51.100.10:43123"
+ req.Header.Set("X-Forwarded-For", "203.0.113.9")
+
+ if got := ClientIP(req); got != "198.51.100.10" {
+ t.Fatalf("ClientIP() = %q, want the peer address", got)
+ }
+
+ resolved := req.WithContext(WithClientIP(context.Background(), ""))
+ if got := ClientIP(resolved); got != "" {
+ t.Fatalf("ClientIP() = %q; a resolved empty value must not be re-read as absent", got)
+ }
+}
+
+// clientIdentityHeaders are the headers a caller can set to claim an identity.
+// Exactly one file may read one: a second reader is a second trust decision, and
+// the two drift the moment trustProxyHeaders means different things to each.
+var clientIdentityHeaders = []string{`"X-Forwarded-For"`, `"X-Real-Ip"`, `"X-Real-IP"`, `"X-Client-Ip"`}
+
+func TestOneFileReadsAForwardingHeaderForClientIdentity(t *testing.T) {
+ files := srccensus.Tree(t, "../..", 200)
+
+ var readers []string
+ for _, file := range files {
+ for _, header := range clientIdentityHeaders {
+ if strings.Contains(file.Text, header) {
+ readers = append(readers, file.Name+" ("+header+")")
+ break
+ }
+ }
+ }
+
+ want := []string{`internal/authn/client_ip.go ("X-Forwarded-For")`}
+ sort.Strings(readers)
+ if strings.Join(readers, "\n ") != strings.Join(want, "\n ") {
+ t.Fatalf("client-identity header readers are:\n %s\nwant exactly:\n %s\nresolve the identity in ResolveClientIP and read it back with ClientIP rather than adding a second reader",
+ strings.Join(readers, "\n "), strings.Join(want, "\n "))
+ }
+}
+
+func TestOnlyTheClientIPResolverReadsTheForwardedForDirective(t *testing.T) {
+ pkg := srccensus.Load(t, ".", 5)
+
+ var callers []string
+ for _, site := range pkg.Calls(t, "forwardedDirective") {
+ callers = append(callers, site.Func)
+ }
+ sort.Strings(callers)
+
+ want := "RequestHost,RequestScheme,forwardedClientIP"
+ if got := strings.Join(callers, ","); got != want {
+ t.Fatalf("forwardedDirective is called from %q, want %q; the Forwarded 'for' directive is client identity and forwardedClientIP owns it", got, want)
+ }
+}
diff --git a/internal/authn/forwarded.go b/internal/authn/forwarded.go
index 578922a5..3840658b 100644
--- a/internal/authn/forwarded.go
+++ b/internal/authn/forwarded.go
@@ -54,9 +54,9 @@ func firstForwardedValue(header string) string {
}
// forwardedDirective extracts a single directive (e.g. "proto" or "host") from
-// the RFC 7239 Forwarded header, returning the first match unquoted.
+// the client-most element of the RFC 7239 Forwarded header, unquoted.
func forwardedDirective(header, name string) string {
- header = strings.TrimSpace(header)
+ header = firstForwardedValue(header)
if header == "" {
return ""
}
diff --git a/internal/authn/request.go b/internal/authn/request.go
index bc11d880..bb61a676 100644
--- a/internal/authn/request.go
+++ b/internal/authn/request.go
@@ -1,7 +1,6 @@
package authn
import (
- "net"
"net/http"
"net/url"
"strings"
@@ -61,18 +60,17 @@ func TokenFromRequest(r *http.Request) string {
return CredentialsFromRequest(r).Value
}
-// ClientIP returns the immediate peer IP address for audit and rate-limiting
-// decisions. Reverse proxy headers are ignored unless a trusted-proxy model is
-// added explicitly.
+// ClientIP returns the client IP for audit and rate-limiting decisions: the
+// value ResolveClientIP put on the request context, or the immediate peer
+// address when nothing resolved one.
func ClientIP(r *http.Request) string {
if r == nil {
return ""
}
- host, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
- if err == nil && host != "" {
- return host
+ if resolved, ok := r.Context().Value(clientIPKey{}).(resolvedClientIP); ok {
+ return resolved.value
}
- return strings.TrimSpace(r.RemoteAddr)
+ return peerIP(r)
}
func parseAuthorizationHeader(auth string) (bearer, session string) {
diff --git a/internal/dashboard/auth_api_test.go b/internal/dashboard/auth_api_test.go
index 308c46f2..e76b2d6e 100644
--- a/internal/dashboard/auth_api_test.go
+++ b/internal/dashboard/auth_api_test.go
@@ -352,6 +352,38 @@ func TestAuthAPIHandleLoginRateLimitsRepeatedFailures(t *testing.T) {
}
}
+// The sibling of the spoofed-headers test, on the other side of the flag: behind a
+// trusted proxy every request carries the proxy's peer address, so bucketing by it
+// lets one client failing its attempts lock every dashboard user out.
+func TestAuthAPIHandleLoginRateLimitsEachForwardedClientSeparatelyWhenProxyIsTrusted(t *testing.T) {
+ api := newAuthAPIForTest(&config.RuntimeConfig{Token: "secret-token", TrustProxyHeaders: true}, browsersession.NewManager(browsersession.Config{}))
+ api.loginLimiter = authn.NewAttemptLimiter(authn.AttemptLimiterConfig{
+ Window: time.Minute,
+ MaxAttempts: 1,
+ })
+
+ login := func(forwardedFor string) int {
+ req := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"token":"wrong"}`))
+ req.RemoteAddr = "198.51.100.10:41000"
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Forwarded-For", forwardedFor)
+ req = req.WithContext(authn.WithClientIP(req.Context(), authn.ResolveClientIP(req, true)))
+ w := httptest.NewRecorder()
+ api.HandleLogin(w, req)
+ return w.Code
+ }
+
+ if code := login("203.0.113.1"); code != http.StatusUnauthorized {
+ t.Fatalf("first client status = %d, want %d", code, http.StatusUnauthorized)
+ }
+ if code := login("203.0.113.1"); code != http.StatusTooManyRequests {
+ t.Fatalf("same client repeating status = %d, want %d", code, http.StatusTooManyRequests)
+ }
+ if code := login("203.0.113.2"); code != http.StatusUnauthorized {
+ t.Fatalf("second client status = %d, want %d; one client's failures must not lock out everyone behind the proxy", code, http.StatusUnauthorized)
+ }
+}
+
func TestAuthAPIHandleLoginRateLimitIgnoresSpoofedForwardedHeaders(t *testing.T) {
api := newAuthAPIForTest(&config.RuntimeConfig{Token: "secret-token"}, browsersession.NewManager(browsersession.Config{}))
api.loginLimiter = authn.NewAttemptLimiter(authn.AttemptLimiterConfig{
diff --git a/internal/handlers/middleware_clientip.go b/internal/handlers/middleware_clientip.go
new file mode 100644
index 00000000..259595b8
--- /dev/null
+++ b/internal/handlers/middleware_clientip.go
@@ -0,0 +1,19 @@
+package handlers
+
+import (
+ "net/http"
+
+ "github.com/pinchtab/pinchtab/internal/authn"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// ClientIPMiddleware makes the trusted-proxy decision once, above every consumer
+// of it — the activity recorder, the limiters and every audit line — and carries
+// the answer on the request context.
+func ClientIPMiddleware(live *config.Live, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ cfg := live.Get()
+ ip := authn.ResolveClientIP(r, cfg != nil && cfg.TrustProxyHeaders)
+ next.ServeHTTP(w, r.WithContext(authn.WithClientIP(r.Context(), ip)))
+ })
+}
diff --git a/internal/handlers/middleware_clientip_test.go b/internal/handlers/middleware_clientip_test.go
new file mode 100644
index 00000000..6f30a874
--- /dev/null
+++ b/internal/handlers/middleware_clientip_test.go
@@ -0,0 +1,109 @@
+package handlers
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/authn"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func fillRateBucket(host string) {
+ now := time.Now()
+ hits := make([]time.Time, rateLimitMaxReq)
+ for i := range hits {
+ hits[i] = now
+ }
+ rateMu.Lock()
+ rateBuckets[host] = hits
+ rateMu.Unlock()
+}
+
+func clientIPChain(trustProxy bool, seen *string) http.Handler {
+ live := config.NewLive(&config.RuntimeConfig{TrustProxyHeaders: trustProxy})
+ return ClientIPMiddleware(live, RateLimitMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if seen != nil {
+ *seen = authn.ClientIP(r)
+ }
+ w.WriteHeader(http.StatusOK)
+ })))
+}
+
+func requestThrough(handler http.Handler, path, peer, forwardedFor string) int {
+ req := httptest.NewRequest(http.MethodGet, path, nil)
+ req.RemoteAddr = peer
+ if forwardedFor != "" {
+ req.Header.Set("X-Forwarded-For", forwardedFor)
+ }
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+ return w.Code
+}
+
+func TestUntrustedProxyBucketsRequestsByPeerWhateverForwardingHeadersArrive(t *testing.T) {
+ resetRateLimitStateForTests()
+ t.Cleanup(resetRateLimitStateForTests)
+
+ fillRateBucket("198.51.100.10")
+ handler := clientIPChain(false, nil)
+
+ for _, forwarded := range []string{"203.0.113.1", "203.0.113.2"} {
+ if code := requestThrough(handler, "/test", "198.51.100.10:41000", forwarded); code != http.StatusTooManyRequests {
+ t.Fatalf("X-Forwarded-For %s got %d, want %d; an untrusted forwarding header must not mint a bucket", forwarded, code, http.StatusTooManyRequests)
+ }
+ }
+}
+
+func TestUntrustedProxyBucketsStreamsByPeerWhateverForwardingHeadersArrive(t *testing.T) {
+ resetRateLimitStateForTests()
+ t.Cleanup(resetRateLimitStateForTests)
+
+ streamMu.Lock()
+ streamConnections["198.51.100.10"] = maxConcurrentStreamRequestsPerHost
+ streamMu.Unlock()
+ handler := clientIPChain(false, nil)
+
+ for _, forwarded := range []string{"203.0.113.1", "203.0.113.2"} {
+ if code := requestThrough(handler, "/api/events", "198.51.100.10:41000", forwarded); code != http.StatusTooManyRequests {
+ t.Fatalf("X-Forwarded-For %s got %d, want %d; an untrusted forwarding header must not mint a stream slot", forwarded, code, http.StatusTooManyRequests)
+ }
+ }
+}
+
+func TestTrustedProxyBucketsRequestsByTheClientMostForwardedAddress(t *testing.T) {
+ resetRateLimitStateForTests()
+ t.Cleanup(resetRateLimitStateForTests)
+
+ fillRateBucket("203.0.113.1")
+ var seen string
+ handler := clientIPChain(true, &seen)
+
+ if code := requestThrough(handler, "/test", "198.51.100.10:41000", "203.0.113.1, 10.0.0.1"); code != http.StatusTooManyRequests {
+ t.Fatalf("the exhausted client got %d, want %d", code, http.StatusTooManyRequests)
+ }
+ if code := requestThrough(handler, "/test", "198.51.100.10:41001", "203.0.113.2, 10.0.0.1"); code != http.StatusOK {
+ t.Fatalf("a second client behind the same proxy got %d, want %d; the two share the proxy's peer address and must not share its bucket", code, http.StatusOK)
+ }
+ if seen != "203.0.113.2" {
+ t.Fatalf("ClientIP() inside the chain = %q, want %q; audit lines record whatever this answers", seen, "203.0.113.2")
+ }
+}
+
+func TestTrustedProxyBucketsStreamsByTheClientMostForwardedAddress(t *testing.T) {
+ resetRateLimitStateForTests()
+ t.Cleanup(resetRateLimitStateForTests)
+
+ streamMu.Lock()
+ streamConnections["203.0.113.1"] = maxConcurrentStreamRequestsPerHost
+ streamMu.Unlock()
+ handler := clientIPChain(true, nil)
+
+ if code := requestThrough(handler, "/api/events", "198.51.100.10:41000", "203.0.113.1"); code != http.StatusTooManyRequests {
+ t.Fatalf("the exhausted client got %d, want %d", code, http.StatusTooManyRequests)
+ }
+ if code := requestThrough(handler, "/api/events", "198.51.100.10:41001", "203.0.113.2"); code != http.StatusOK {
+ t.Fatalf("a second client behind the same proxy got %d, want %d; eight streams belong to a client, not to the deployment", code, http.StatusOK)
+ }
+}
diff --git a/internal/server/bridge.go b/internal/server/bridge.go
index 3e63e9c4..b9651143 100644
--- a/internal/server/bridge.go
+++ b/internal/server/bridge.go
@@ -93,13 +93,13 @@ func RunBridgeServer(cfg *config.RuntimeConfig, version string) {
Addr: listenAddr,
Handler: handlers.TrustedInternalProxyStripMiddleware(os.Getenv("PINCHTAB_INTERNAL_TOKEN"))(
handlers.RequestIDMiddleware(
- activity.Middleware(
+ handlers.ClientIPMiddleware(live, activity.Middleware(
actStore,
"bridge",
handlers.SecurityHeadersMiddleware(live,
handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.AuthMiddleware(live, mux))),
),
- ),
+ )),
),
),
MaxHeaderBytes: maxHeaderBytes,
diff --git a/internal/server/front_door_metrics.go b/internal/server/front_door_metrics.go
index 99cfb82a..57dbc554 100644
--- a/internal/server/front_door_metrics.go
+++ b/internal/server/front_door_metrics.go
@@ -32,13 +32,13 @@ func FrontDoorHandler(
) http.Handler {
return handlers.StripInternalHeadersMiddleware(
handlers.RequestIDMiddleware(
- activity.Middleware(
+ handlers.ClientIPMiddleware(live, activity.Middleware(
recorder,
"server",
handlers.SecurityHeadersMiddleware(live,
handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(live, handlers.AuthMiddlewareWithSessions(live, sessions, sessionStore, mux)))),
),
- ),
+ )),
),
)
}