Skip to content

fix(security): explicit trusted-client-IP contract for rate limiting (CD-05) - #4070

Merged
ety001 merged 2 commits into
nextfrom
fix/cd-05-trusted-client-ip-contract
Nov 3, 2026
Merged

ety001 merged 2 commits into
nextfrom
fix/cd-05-trusted-client-ip-contract

Conversation

@ety001

@ety001 ety001 commented Nov 3, 2026

Copy link
Copy Markdown
Member

The spoof chain (audit CD-05, confirmed by packet capture on 2026-10-24)

getClientIp in lib/cache/rate-limit.ts took the first X-Forwarded-For segment as the rate-limit identity. All four proxy layers (Cloudflare → ALB → openresty → app) merely append to XFF without sanitizing, so a client-supplied X-Forwarded-For: 203.0.113.77 arrives at the app as the first segment and fully controls every per-IP bucket key (authChallenge 30/min, authLoginIp 10/min, steemBroadcast 30/min). Captured at the container:

X-Forwarded-For: 203.0.113.77, <real-client>, <cf-edge>, <real-client>

Normal requests only worked by accident: Cloudflare writes the real client IP first when the client sends no XFF. After the CD-04 fix (#4066) the per-IP bucket is the only remaining gate for unauthenticated login floods, which made the spoof critical.

The contract

New env var TRUSTED_CLIENT_IP_HEADER declares which header the deployment trusts:

Mode Reads Use when
x-real-ip X-Real-IP only Recommended for Steemit: openresty sets proxy_set_header X-Real-IP $remote_addr, unconditionally overwriting any client value
cf-connecting-ip CF-Connecting-IP only App directly behind Cloudflare, no stripping layer in between
xff-tail Last XFF entry Append-only chains; the tail was appended by the closest proxy — as trustworthy as that proxy (documented caveat)
unset / none Nothing Direct exposure (community self-host with no proxy)

Rules:

  • Only the declared header is read; all other candidate headers are ignored entirely. A forged XFF has zero effect under x-real-ip (there is also no fallback to undeclared headers — see missing-header design below).
  • Values must be strict IP literals (IPv4 dotted-quad without leading zeros, IPv6 via the existing parser); garbage (ports, lists, junk) counts as unattributed. IPv6 /64 aggregation (aggregateIpIdentity) is preserved for every trusted source.
  • Startup validation: an unknown env value throws at module load with the valid modes listed — misconfiguration never silently degrades to no-trust.
  • RATE_LIMITS unchanged; aggregateIpIdentity unchanged; getClientIp(request) signature unchanged.

Missing-header design (the deliberate asymmetry)

  • Configured mode + missing/invalid header: the trusted proxy always sets the header, so such a request never went through it — anomalous direct-to-app access (or proxy misconfiguration). It is never exempt (exemption would make "drop the header" the rate-limit bypass); it shares one dedicated unattributed bucket at the rule's normal per-IP limit. Legitimate users never land there, so the shared bucket cannot cause cross-user lockout — only the anomalous traffic is collectively capped. A throttled (1/min) warning names the mode and the anomaly.
  • Unset mode: no header is trusted and route handlers expose no socket peer address, so no sound IP identity exists at all. Bucketing everyone together would recreate the pre-fix hazard (all visitors collapsed into one shared 30/min site-wide bucket, 429-ing each other). IP-dimension buckets are therefore exempt, with a throttled warning explaining the fix. Identifier-dimension buckets (the per-account login limit from CD-04) do not depend on the IP and remain enforced even in this mode.

Test evidence

__tests__/lib/cache/rate-limit.test.ts reworked around a loadRateLimit(mode) loader (the mode is captured at module load, so mode tests re-import the module):

  • each mode resolves identity from its declared header only;
  • forged XFF ignored under x-real-ip (the exact captured spoof shape) and under xff-tail (spoofed first segment ignored);
  • strict-IP validation (ports/lists/leading-zero junk → unattributed);
  • missing trusted header → shared unattributed bucket at the normal limit + throttled warn (never exempt, never mixed into per-user buckets);
  • unset mode → IP-dimension exempt (no Redis call) + warn; identifier-dimension still enforced;
  • invalid env value → module-load throw listing valid modes; case/whitespace normalized;
  • IPv6 /64 aggregation applied to trusted values in every mode;
  • the pre-existing Lua/atomicity/fail-open/log-discipline suite kept green.

Fail-on-pre-fix proof: reverting only lib/cache/rate-limit.ts to next (keeping the new tests) fails 19 of the behavioral tests, including the spot-checked x-real-ip spoof test, xff-tail last-entry test, the unset-mode exemption test, and the startup-validation throw.

__tests__/api/auth/login.test.ts: one vi.hoisted block sets TRUSTED_CLIENT_IP_HEADER=xff-tail so the CD-04 counting limiter's per-IP simulation (single-segment XFF values) keeps resolving distinct buckets; all 27 login tests green.

Gates

  • pnpm lint:ci — 0 errors
  • npx tsc --noEmit — clean
  • pnpm test — 87 files / 1134 tests passed

Deployment action item (out of scope for this PR)

Set TRUSTED_CLIENT_IP_HEADER=x-real-ip as an Elastic Beanstalk environment property when this ships (runtime read at module load — restart, no rebuild needed). Until it is set, the per-IP limiter runs in the exempt (unset) mode and logs the warning documenting that state.

…(CD-05)

getClientIp took the FIRST X-Forwarded-For segment as the rate-limit
identity. Every proxy layer in the production chain (Cloudflare -> ALB ->
openresty -> app) merely APPENDS to XFF without sanitizing, so a client
sending "X-Forwarded-For: 203.0.113.77" arrived at the app as the first
segment (captured at the container: "203.0.113.77, <real-client>,
<cf-edge>, <real-client>") and fully controlled every per-IP bucket key
(authChallenge 30/min, authLoginIp 10/min, steemBroadcast 30/min). After
CD-04 the per-IP bucket is the only gate for unauthenticated login
floods, which made the spoof critical.

Replace the implicit header priority with an explicit trust contract:

- New env var TRUSTED_CLIENT_IP_HEADER declaring WHICH header the
  deployment trusts: x-real-ip (recommended for our openresty chain,
  which sets it unconditionally from the rewritten $remote_addr),
  cf-connecting-ip (directly behind Cloudflare), xff-tail (last XFF
  entry, appended by the closest proxy; as trustworthy as that proxy),
  or unset/none (direct exposure). Only the declared header is read;
  every other candidate header is ignored entirely (a forged XFF has
  zero effect under x-real-ip). Values must be strict IP literals
  (v4/v6, no ports/lists/leading zeros); IPv6 keeps /64 aggregation.
- Unknown env values fail at module load (startup validation listing
  the valid modes) instead of silently degrading to no-trust.
- Missing/invalid trusted header in a CONFIGURED deployment: the proxy
  always sets it, so such a request bypassed the proxy (direct-to-app)
  or the proxy is misconfigured. It is never exempt (dropping the
  header must not become a rate-limit escape); it shares one dedicated
  'unattributed' bucket at the rule's normal per-IP limit, with a
  throttled warning. Legitimate users never land there.
- UNSET mode (direct exposure): no header is trusted and no sound IP
  identity exists (route handlers have no socket peer address), so
  IP-dimension buckets are exempt with a throttled warning instead of
  collapsing all visitors into one shared quota where they 429 each
  other at site-wide ceilings. Identifier-dimension buckets (per-
  account login limit, CD-04) remain enforced.

RATE_LIMITS and aggregateIpIdentity are unchanged; getClientIp's
exported signature is unchanged. Deployment action item: set
TRUSTED_CLIENT_IP_HEADER=x-real-ip as an EB environment property.
…t contract

Review follow-up on #4070 (PR review round 1):

- Document in the module comment, CONFIGURATION.md and .env.example that
  the trusted-header contract only holds for traffic that actually
  traverses the trusted proxy: a direct-to-app client can forge the
  declared header itself with arbitrary valid IP literals (for xff-tail,
  a single-entry X-Forwarded-For is entirely the client's own value), so
  the app port must be reachable only from the trusted proxy. Header
  validation cannot substitute for that segmentation.
- login.test.ts: delete TRUSTED_CLIENT_IP_HEADER in afterAll so the
  trust mode never leaks into other test files sharing the worker (same
  cleanup discipline as the rate-limit tests).
@ety001
ety001 merged commit fb7ccff into next Nov 3, 2026
1 of 2 checks passed
@ety001
ety001 deleted the fix/cd-05-trusted-client-ip-contract branch November 3, 2026 22:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant