← Back to Pull requests

fix(config): reject trust-all proxy CIDR combinations in production #518

Merged
rupayon123 merged 3 files (127 lines) on Oct 03, 2026 03:37 UTC
View on GitHub
rupayon123 rupayon123 commented on Sep 28, 2026 13:02 UTC
Author

Summary

Production validation now parses trusted-proxy CIDRs rather than comparing three literal strings. It rejects equivalent zero-prefix spellings and combinations of ranges that together trust every IPv4 or IPv6 peer, closing the forwarded-IP spoofing gap reported in #500. Limited proxy ranges remain valid. The configuration guide explains the production guard and the need to list only controlled proxies.

Closes #500

Acceptance criteria

  • Reject single CIDRs with a zero-length prefix, including 10.0.0.0/0, 0.0.0.0/00, and ::0/0.

  • Reject combined ranges covering all peers in either address family, including both /1 halves.

  • Preserve limited trusted-proxy ranges; cover rejection and acceptance with regression tests.
  • Scope notes

    This changes production configuration validation only. It does not change how Gin handles trusted peers after valid configuration is accepted. No database, generated API, or frontend code changes.

    Validation

  • New regression cases failed before the implementation and pass afterward.

  • go test -p 1 ./config ./framework -run 'Test(Validate|TrustedProxies)' -count=1

  • go build -p 1 ./...

  • go vet -p 1 ./config ./framework; git diff --check

  • go test ./...: attempted twice; the full parallel run exhausted local disk while compiling/linking. A narrower serial run passed config and client, but unrelated framework tests failed on sync /dev/stderr: bad file descriptor. The focused proxy tests passed.

  • go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.12.2 run: not run because the local volume lacked space for another toolchain build; CI remains needed.

  • Project code-review skill: not available in this Codex environment; reviewed the diff and affected validation/router paths manually.
  • Working agreement checklist

  • New behavior has tests. No DB code changed, so the DB matrix is not applicable.

  • Stable behavior is documented in docs/config.md. No example app change is needed for a validation guard.

  • Scope stays within #500 and the existing config API.

  • This PR links its issue and states the acceptance criteria it satisfies.

  • Extraction, generators, API generation, and frontend secret checks are not applicable to this config-only change.
  • Diff: 127 lines (+122 / -5) across 3 files Reviewer: leo-aa88 Review duration: 6634m
    All Vouch review confidence checks passed
    Residual risk 0.19 = Change Risk (0.58) × (1 − Review Confidence (0.68)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.58 · 127 lines diff across 3 files
    0.58
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.51 · 5 substantive comment(s)
    0.51
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    68%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.290
    Sensitive Paths sensitive_paths
    0.058
    Real PR Conversation Timeline
    9 items
    leo-aa88 leo-aa88 commented on code on Sep 28, 2026 16:26 UTC
    Code Review
    config/config.go:1
    @@ -1109,12 +1120,64 @@ func applyBool(lookup EnvLookup, key string, field string, dest *bool, errs *Fie
     }
     
     func isUnsafeTrustedProxy(proxy string) bool {
    -	switch strings.TrimSpace(proxy) {
    -	case "*", "0.0.0.0/0", "::/0":
    +	proxy = strings.TrimSpace(proxy)
    +	if proxy == "*" {
     		return true
    -	default:
    +	}
    +	_, network, err := net.ParseCIDR(proxy)
    +	if err != nil {
     		return false
     	}
    +	ones, _ := network.Mask.Size()
    +	return ones == 0
    +}
    +
    +// trustedProxyRangesCoverAll detects a set of CIDRs that jointly trusts every
    +// IPv4 or IPv6 peer. Each family has its own prefix tree, so a partial range
    +// in one family cannot make a partial range in the other appear complete.
    +func trustedProxyRangesCoverAll(proxies []string) bool {
    +	var ipv4, ipv6 trustedProxyRangeNode
    +	for _, proxy := range proxies {
    +		_, network, err := net.ParseCIDR(strings.TrimSpace(proxy))
    +		if err != nil {
    +			continue // Gin reports invalid addresses when configuring its router.
    +		}
    +		bits, _ := network.Mask.Size()
    +		if address := network.IP.To4(); address != nil {

    BLOCKING: every IPv4-mapped CIDR panics Validate in production, and the mapped trust-all form still needs rejecting.

    For ::ffff:a.b.c.d/N, net.ParseCIDR returns a 16-byte network.IP and a 16-byte mask. To4() succeeds, so a 4-byte address goes into the IPv4 tree. Mask.Size() still reports bits in 128-bit terms (96 or more), so the recursion goes past depth 31 and address[depth/8] reads address[4]. I confirmed this against this branch:

    ::ffff:0.0.0.0/96    Validate PANIC: runtime error: index out of range [4] with length 4
    ::ffff:10.0.0.0/104  Validate PANIC: runtime error: index out of range [4] with length 4
    

    The second value is a legitimate way to write 10.0.0.0/8, and Gin accepts it. With this PR, a production app configured that way crashes at startup with a stack trace instead of starting, or instead of getting a config error.

    The first value is the reason #500 exists. Gin matches peers with net.IPNet.Contains (gin.go isTrustedProxy). For a mapped network, networkNumberAndMask compares only the last 4 bytes of the mask, and a /96 leaves all 32 IPv4 bits unmasked:

    ::ffff:0.0.0.0/96 contains 203.0.113.9 = true, 8.8.8.8 = true
    

    So ::ffff:0.0.0.0/96 trusts every IPv4 peer, just like 0.0.0.0/0. A fix that only stops the panic, for example by sending mapped addresses to the IPv6 tree, would still accept it in production.

    Fix: normalise to Gin's view before inserting. When network.IP.To4() != nil && len(network.Mask) == net.IPv6len, insert into the IPv4 tree with bits - 96. Validation already guarantees bits >= 96 whenever To4() succeeds on a masked mapped address. netip.ParsePrefix + Addr().Is4In6() / Unmap() expresses this more directly. isUnsafeTrustedProxy should use the same normalised prefix length, so that ::ffff:0.0.0.0/96 gets the per-entry error like 0.0.0.0/0 does. Please add both mapped values above to the reject/accept tables. /104 belongs in the accept table.

    leo-aa88 leo-aa88 commented on code on Sep 28, 2026 16:26 UTC
    Code Review
    config/config_test.go:1
    @@ -561,6 +561,49 @@ func TestValidateRejectsUnsafeTrustedProxyInProduction(t *testing.T) {
     	}
     }
     
    +func TestValidateRejectsEquivalentTrustAllProxyRanges(t *testing.T) {

    The accept and reject tables only use native IPv4 and native IPv6 CIDRs, so the family routing in trustedProxyRangesCoverAll is never tested at the mapped-address boundary where it breaks (see the config.go comment). Add ::ffff:0.0.0.0/96 here, {"::ffff:0.0.0.0/97", "::ffff:128.0.0.0/97"} (the mapped version of the two halves), and ::ffff:10.0.0.0/104 to the accept table.

    leo-aa88 leo-aa88 requested changes on Sep 28, 2026 16:26 UTC
    Changes Requested Reviewer

    REQUEST CHANGES

    Parsing the CIDRs instead of matching three literal strings is the right fix. The per-family prefix tree is a correct way to detect ranges that together cover everything: an insert is skipped once a covered ancestor exists, and two covered siblings collapse into their parent. It also suppresses the duplicate error when a single entry is already flagged. The tests cover the spellings from #500 and the two-halves case.

    There is one blocking problem, and it sits in the IPv4/IPv6 split this approach relies on. IPv4-mapped IPv6 CIDRs are routed into the IPv4 tree with a 128-bit prefix length, which panics. The mapped form of "trust everyone" also needs to be classified as such. Details are inline.

    rupayon123 rupayon123 commented on code on Oct 01, 2026 08:18 UTC
    Code Review
    config/config.go:1
    @@ -1109,12 +1120,64 @@ func applyBool(lookup EnvLookup, key string, field string, dest *bool, errs *Fie
     }
     
     func isUnsafeTrustedProxy(proxy string) bool {
    -	switch strings.TrimSpace(proxy) {
    -	case "*", "0.0.0.0/0", "::/0":
    +	proxy = strings.TrimSpace(proxy)
    +	if proxy == "*" {
     		return true
    -	default:
    +	}
    +	_, network, err := net.ParseCIDR(proxy)
    +	if err != nil {
     		return false
     	}
    +	ones, _ := network.Mask.Size()
    +	return ones == 0
    +}
    +
    +// trustedProxyRangesCoverAll detects a set of CIDRs that jointly trusts every
    +// IPv4 or IPv6 peer. Each family has its own prefix tree, so a partial range
    +// in one family cannot make a partial range in the other appear complete.
    +func trustedProxyRangesCoverAll(proxies []string) bool {
    +	var ipv4, ipv6 trustedProxyRangeNode
    +	for _, proxy := range proxies {
    +		_, network, err := net.ParseCIDR(strings.TrimSpace(proxy))
    +		if err != nil {
    +			continue // Gin reports invalid addresses when configuring its router.
    +		}
    +		bits, _ := network.Mask.Size()
    +		if address := network.IP.To4(); address != nil {

    Fixed in e519aff2a904b6a654dcb9b8a9d8130caeafe815. IPv4-mapped networks are now normalized to Gin’s IPv4 prefix length before both coverage insertion and the trust-all check, so mapped /96 is rejected and mapped /104 is treated as IPv4 /8. The focused reject/allow tests and full config package pass, and go vet passes for config and framework. I also ran the repository-wide suite; unrelated framework tests fail locally on stderr sync and one shutdown timeout, so I’m keeping that limitation explicit while exact-head Actions run.

    rupayon123 rupayon123 commented on code on Oct 01, 2026 08:18 UTC
    Code Review
    config/config_test.go:1
    @@ -561,6 +561,49 @@ func TestValidateRejectsUnsafeTrustedProxyInProduction(t *testing.T) {
     	}
     }
     
    +func TestValidateRejectsEquivalentTrustAllProxyRanges(t *testing.T) {

    Added regression cases for ::ffff:0.0.0.0/96, the two mapped /97 halves, and the valid ::ffff:10.0.0.0/104 range. They pass with the config package tests on e519aff2a904b6a654dcb9b8a9d8130caeafe815. The broader local suite currently has unrelated framework stderr-sync/shutdown failures; exact-head CI is still the check for the complete repository matrix.

    leo-aa88 leo-aa88 requested changes on Oct 01, 2026 17:53 UTC
    Changes Requested Reviewer

    Please solve the merge conflicts on config/config.go

    rupayon123 rupayon123 commented on Oct 03, 2026 01:53 UTC
    Author

    Resolved the merge conflict in config/config.go by merging the current main branch and retaining both imports: net for CIDR parsing in trusted-proxy validation and net/url for the storage URL configuration. Merge commit 11304b839f2d21cbfab6cb0d02a9271952d27a67 is pushed on this PR branch. Focused config/framework validation tests, go vet -p 1 ./config ./framework, go build -p 1 ./..., and git diff --check pass on the merged tree. Please re-review. I will inspect the exact-head CI when it finishes.

    leo-aa88 leo-aa88 approved these changes on Oct 03, 2026 03:36 UTC
    Approved Reviewer

    LGTM

    Reviewers
    Assignees
    rupayon123 rupayon123
    Labels
    risk: low confidence: 68.1% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 58.1% (MEDIUM) · Higher = larger blast radius
    58.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 68.1% · Lower = rushed or shallow review
    68.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 18.6% · Safe to merge
    18.6%