diff --git a/.env.example b/.env.example index 00c4b05f9..f9adcf8d6 100644 --- a/.env.example +++ b/.env.example @@ -275,9 +275,10 @@ TWIGPINE_MAX_CONCURRENT_PIN_TASKS=8 # Max concurrent read ops (upload-pack + the upload-pack info/refs advertisement) # a single caller may hold, so one caller cannot monopolize the read pool. Keyed # on the resolved SOURCE IP, never the DID: a signature does not move a caller off -# this cap. The source-IP key is only as granular as TWIGPINE_TRUSTED_PROXY below: -# left unset, a node behind an edge/NAT keys all callers on the edge IP and this -# collapses to one global cap. Set TWIGPINE_TRUSTED_PROXY for per-client keying; a +# this cap. The source-IP key is only as granular as the verified +# TWIGPINE_TRUSTED_PROXY and TWIGPINE_TRUSTED_PROXY_CIDRS pair below: without a +# verified proxy peer, a node behind an edge/NAT keys all callers on the edge IP +# and this collapses to one global cap. Configure both for per-client keying; a # high-fanout caller (CI behind one NAT) then needs the operator to raise this. # Default 16. TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER=16 @@ -298,7 +299,8 @@ TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER=16 # rate, not in-flight concurrency, and owner enforcement can be turned off for # a rolling upgrade). # Keyed on the resolved source IP, never the DID, so a DID farm does not defeat -# them; keying granularity follows TWIGPINE_TRUSTED_PROXY like the read cap above. +# them; keying granularity follows the same verified trusted-proxy pair as the +# read cap above. # ── Push rate limiting (git-receive-pack flood brake) ───────────────────── # Max receive-pack requests (info/refs advertisement + push POST) per client @@ -314,7 +316,8 @@ TWIGPINE_PUSH_RATE_LIMIT=600 # the served-git pools). Over-cap sheds a 503. Default 32. TWIGPINE_MAX_CONCURRENT_IPFS_WALKS=32 # Max concurrent /ipfs walks a single SOURCE IP may hold (keyed like the git -# per-caller caps via TWIGPINE_TRUSTED_PROXY; reject-before-insert bounded map). +# per-caller caps through the verified trusted-proxy pair; reject-before-insert +# bounded map). # Default 4. TWIGPINE_IPFS_WALK_PER_SOURCE=4 # Max legacy (NULL-provenance) repos probed per single /ipfs request, bounding the @@ -377,8 +380,8 @@ TWIGPINE_IPFS_RATE_LIMIT=600 # GET /api/v1/tasks/{id} runs get_visible_task and returns an opaque 404 when # the task is hidden or missing. These reads can require task, repository, # and visibility-rule queries even when no task is returned, so the brake -# bounds the cost of anonymous probes. Keyed on the resolved client IP via -# TWIGPINE_TRUSTED_PROXY. 0 disables. Default: 1200 (a list page +# bounds the cost of anonymous probes. Keyed on the client IP resolved through +# the verified trusted-proxy configuration. 0 disables. Default: 1200 (a list page # followed by per-task reads is a normal client pattern, so this sits above # the /ipfs budget). The GraphQL/WS task-read brake shares this budget. TWIGPINE_TASK_READ_RATE_LIMIT=1200 @@ -388,8 +391,8 @@ TWIGPINE_TASK_READ_RATE_LIMIT=1200 # pulls) per client IP per hour, in addition to the per-DID limit. The per-DID # limit alone is bypassed by a did:key farm (one throwaway identity per repo), # which is how spam-repo floods slip past it and the iCaptcha gate; the per-IP -# brake caps a single-source flood. Uses TWIGPINE_TRUSTED_PROXY below to resolve -# the client IP. 0 disables. Default 120. +# brake caps a single-source flood. Uses the verified trusted-proxy configuration +# below to resolve the client IP. 0 disables. Default 120. TWIGPINE_CREATE_RATE_LIMIT=120 # Per-DID creation requests allowed inside the window below (repo create, # issue create, PR create, register, fork). 0 is rejected at startup: it would @@ -411,14 +414,14 @@ TWIGPINE_RATE_LIMIT_WINDOW_SECS=3600 # after the read gate, rather than in router middleware. Issue close also draws # on its own TWIGPINE_CLOSE_ISSUE_RATE_LIMIT bucket, and a close refused by # either cap spends nothing from the other. Separate from the creation and push -# brakes. Uses TWIGPINE_TRUSTED_PROXY to resolve the client IP. +# brakes. Uses the verified trusted-proxy configuration to resolve the client IP. # NOTE: this is a per-IP aggregate across ALL those write actions, so behind a -# shared NAT/egress IP (or with TWIGPINE_TRUSTED_PROXY unset) many users collapse -# onto one bucket — raise this for automation-heavy or multi-user single-IP +# shared NAT/egress IP (or without a verified proxy peer) many users collapse +# onto one bucket. Raise this for automation-heavy or multi-user single-IP # deployments. 0 disables. Default 600. TWIGPINE_WRITE_RATE_LIMIT=600 -# ── Peer-sync rate limiting (per client IP, uses TWIGPINE_TRUSTED_PROXY below) ─ +# ── Peer-sync rate limiting (per client IP, uses the verified proxy pair) ────── # /api/v1/peers/announce and /api/v1/sync/notify accept unsigned requests from # known peers and run at higher frequency, so a generous bucket. Separate from # the trigger bucket so an unsigned notify flood can't drain trigger's quota. @@ -429,15 +432,27 @@ TWIGPINE_PEER_WRITE_RATE_LIMIT=600 TWIGPINE_SYNC_TRIGGER_RATE_LIMIT=60 # Which forwarded header the edge is trusted to set, used to resolve the real -# client IP for the push limiter. One of: +# client IP for every source-IP brake. One of: # (unset) — no trusted proxy: key on the socket peer address, ignore headers. # fly — behind Fly's edge (trust Fly-Client-IP). # x-forwarded-for — behind a single reverse proxy like Caddy/NGINX (trust the # rightmost X-Forwarded-For hop). -# Only set this when a proxy you control actually fronts the node; trusting a -# forwarded header on a directly-exposed node lets clients spoof the key. +# The header mode is not sufficient by itself. The node uses the forwarded value +# only when the socket peer matches TWIGPINE_TRUSTED_PROXY_CIDRS below. TWIGPINE_TRUSTED_PROXY= +# Comma-separated exact IPv4/IPv6 addresses or CIDR ranges for the proxy peers +# allowed to assert the forwarded header selected above. Exact addresses are +# host prefixes. Blank trusts no proxy peer. Any malformed entry invalidates the +# whole list and fails closed: the node still starts, logs an error, and ignores +# forwarded headers. With a header mode set and this list +# empty, forwarded headers are ignored; behind a proxy all clients then collapse +# onto the proxy socket-peer bucket, and the node logs a warning. Example: +# TWIGPINE_TRUSTED_PROXY_CIDRS=10.0.0.8/32,2001:db8::10/128 +# Full client-IP keys are still cheaply rotatable for a caller that controls a +# routed IPv6 /64; this boundary stops header spoofing, not address-space rotation. +TWIGPINE_TRUSTED_PROXY_CIDRS= + # ── Sync ───────────────────────────────────────────────────────────────── # Enable automatic background sync from known peers TWIGPINE_AUTO_SYNC=false diff --git a/Cargo.lock b/Cargo.lock index 0aa99f10f..5416182d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7508,6 +7508,7 @@ dependencies = [ "hex", "hmac 0.12.1", "http-body-util", + "ipnet", "libc", "libp2p-core", "libp2p-dns", diff --git a/README.md b/README.md index a6f124f9a..5e4190359 100644 --- a/README.md +++ b/README.md @@ -437,7 +437,9 @@ Important node settings: | `TWIGPINE_WRITE_LOCK_HOLD_TIMEOUT_SECS` | Max seconds a repo write guard may hold its advisory-lock pool connection, measured from lock-take. One deadline covers every phase under the lock: the under-lock refresh, the caller's under-lock work (for a push, the whole `receive-pack` subprocess, clamped to the lesser of `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` and the remaining budget), and the release-side upload/unlock. It bounds the lock-pool slot's hold, so a slow push cannot starve other writers for the sum of every per-phase bound. It does not bound the acquire-side lock wait (`TWIGPINE_GIT_ACQUIRE_TIMEOUT_SECS`), post-git outcome bookkeeping, the few seconds the detached reaper holds the session while the git process group dies, or merge writes, which take their guards without this deadline: their git runs unbounded under the lock, and their refresh, publish and unlock keep their own bounds, so a slow merge is never rolled back for overrunning it. Issue writes keep the deadline: an expired one refuses the write before the ref is touched, and the create's ref write and every git child of the close are clamped to it. Create's rollback after a refused publish keeps its own git-timeout budget. Unset, the effective bound is `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` itself (600 by default), tracking the git budget. The `gitlawb_push_duration_seconds` histogram is the evidence for tightening it below that: set the hold near the tail latency your pushes actually need, not lower. Merge is intentionally not bounded by it: it is owner-only, and a stamped deadline mid-merge would rewind a completed merge, so merge keeps its own per-phase bounds instead. An explicit value above `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` is rejected at boot. | | `TWIGPINE_MAX_CONCURRENT_GIT_OPS` | Max concurrent served git READ ops (upload-pack and its `info/refs` advertisement) across all callers; over-cap sheds a 503 + Retry-After. Anonymous reads draw from this pool, so pair it with `TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER`. Pushes and the receive-pack advertisement have their own pools, so a read flood cannot shed an authenticated push. Default 128. | | `TWIGPINE_MAX_CONCURRENT_GIT_PUSHES` | Max concurrent `git-receive-pack` POST operations, in a pool separate from the read pool. The anon receive-pack `info/refs` advertisement runs in a third pool of the same size, disjoint from both, so an advertisement flood cannot shed a push either. Two per-source push caps are derived from this value (`/8`, floor 1) and have no env var of their own. Over-cap sheds a 503 + Retry-After. Default 32. | -| `TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER` | Max concurrent read ops a single caller may hold, so one caller cannot monopolize the read pool. Keyed on the resolved source IP, never the DID, and only as granular as `TWIGPINE_TRUSTED_PROXY`: left unset, a node behind an edge or NAT keys every caller on the edge IP and this collapses to one global cap. Default 16. | +| `TWIGPINE_TRUSTED_PROXY` | Selects which forwarded header a verified edge proxy may assert: `fly` for `Fly-Client-IP`, or `x-forwarded-for` for the rightmost `X-Forwarded-For` hop. Unset ignores forwarded headers. The header is honored only when the socket peer matches `TWIGPINE_TRUSTED_PROXY_CIDRS`. | +| `TWIGPINE_TRUSTED_PROXY_CIDRS` | Comma-separated exact IPv4/IPv6 addresses or CIDR ranges for trusted proxy socket peers. Exact addresses are host prefixes. Blank trusts no proxy; any malformed entry invalidates the whole list and fails closed: the node starts, logs an error, and ignores forwarded headers. With a header mode set and no matching proxy peer, clients are keyed on the socket peer instead of the attacker-controlled header. Behind a proxy with no verified peer range they collapse onto the proxy's address. Even correct full-IP keys remain cheaply rotatable for a caller controlling a routed IPv6 `/64`; this setting stops header spoofing, not address-space rotation. | +| `TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER` | Max concurrent read ops a single caller may hold, so one caller cannot monopolize the read pool. Keyed on the resolved source IP, never the DID, and only as granular as the verified `TWIGPINE_TRUSTED_PROXY` and `TWIGPINE_TRUSTED_PROXY_CIDRS` pair: without a verified proxy peer, a node behind an edge or NAT keys every caller on the edge IP and this collapses to one global cap. Default 16. | | `TWIGPINE_MAX_CONCURRENT_PIN_TASKS` | Max post-push pin loops (IPFS + Pinata) running concurrently across all repos. This caps how many loops RUN at once, not how much object-id list memory the node retains: on the local IPFS path a loop parked waiting for a permit still holds its full list. Do not size memory from this knob alone. A loop over cap waits, never drops a pin. Up to two loops run per push that starts its own encrypt/pin task when both IPFS and Pinata are configured; a push coalesced onto an in-flight task adds at most one warm loop. See [docs/STORAGE-AND-PINNING.md](docs/STORAGE-AND-PINNING.md) for the two-tier model, dedup, and parked-list memory. Default 8. | | `TWIGPINE_REPO_LEASE_MAX_WAITERS` | Max pushes parked at once waiting for the same repo's write lease. Each waiter pins its buffered pack body, so this bounds that memory for a hot repo; past the cap the newest push sheds a 503 + Retry-After instead of queueing. Pushes to other repos are unaffected, and the lease holder is not counted. Default 8. | | `TWIGPINE_MAX_CONCURRENT_IPFS_WALKS` | Max concurrent `GET /ipfs/{cid}` visibility walks across all callers (own pool, disjoint from the served-git pools); over-cap sheds 503. Default 32. | @@ -449,7 +451,7 @@ Important node settings: | `TWIGPINE_IPFS_REQUEST_BUDGET_SECS` | Absolute wall-clock budget for one admitted `/ipfs/{cid}` request's acquire+walk lifetime. Per-stage clamps bound the acquire and walk stages to the remaining budget, and no stage starts once it is exhausted; the scan then stops with a retryable 503. The object-type probe and content-read `cat-file` subprocesses are budget-checked before starting and each also run under their own deadline (the lesser of `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` and the remaining budget), reaped via process-group teardown, so a hung `cat-file` cannot hold the request's walk slot past it. One hang path is still unbounded: the probe's object-store readability check is a plain filesystem sweep with nothing to reap, so a wedged filesystem can hold the slot past the deadline. Default 600. Accepted range is 1 to 3153600000 (100 years), since the node derives a deadline from this value and a larger one cannot be represented. | | `TWIGPINE_IPFS_RESOLVE_BUDGET_SECS` | Shorter budget for the pre-walk CID resolve inside an admitted `/ipfs/{cid}` request: the lookup that maps the requested CID to its git oid(s), which runs while the scarce walk admission is already held. A well-formed CID with no pin row does no probe and no walk work, so without this it could hold a walk slot for the whole request budget while nothing walked, and enough such requests shed every real retrieval at admission. The effective deadline is the lesser of this and the remaining request budget, so a value above `TWIGPINE_IPFS_REQUEST_BUDGET_SECS` degrades to the request budget. Only the resolve is on this clock; walk and probe work stay on the request budget, so a slow but progressing scan is never shed by it. Default 10. Accepted range is 1 to 3153600000 (100 years). | | `TWIGPINE_IPFS_RATE_LIMIT` | Max `/ipfs/{cid}` requests per client IP per hour (route flood brake). 0 disables. Default 600. | -| `TWIGPINE_TASK_READ_RATE_LIMIT` | Max anonymous task-read requests (`GET /api/v1/tasks`, `GET /api/v1/tasks/{id}`) per client IP per hour, sharing the budget with the GraphQL/WS task-read brake. Uses `TWIGPINE_TRUSTED_PROXY` to resolve the client IP. 0 disables. Default 1200 (above the `/ipfs` budget to allow list pages followed by per-task reads). | +| `TWIGPINE_TASK_READ_RATE_LIMIT` | Max anonymous task-read requests (`GET /api/v1/tasks`, `GET /api/v1/tasks/{id}`) per client IP per hour, sharing the budget with the GraphQL/WS task-read brake. Uses the verified trusted-proxy configuration to resolve the client IP. 0 disables. Default 1200 (above the `/ipfs` budget to allow list pages followed by per-task reads). | | `TWIGPINE_TIGRIS_BUCKET` | Optional S3/Tigris shared repo storage bucket. | | `TWIGPINE_PINATA_JWT` | Optional Pinata/IPFS warm-storage pinning. | | `TWIGPINE_IRYS_URL` | Optional Irys/Arweave permanent anchoring. | diff --git a/crates/twigpine-node/Cargo.toml b/crates/twigpine-node/Cargo.toml index d592802a9..b79cfb142 100644 --- a/crates/twigpine-node/Cargo.toml +++ b/crates/twigpine-node/Cargo.toml @@ -115,6 +115,7 @@ libp2p-dns = { version = "0.45.0", features = ["tokio"] } # Optional: only needed by the test-harness feature's lib modules # (test_git_shim, test_harness); dev-deps are invisible to lib code. tempfile = { version = "3", optional = true } +ipnet = "2.12.0" [dev-dependencies] multibase = { workspace = true } diff --git a/crates/twigpine-node/src/api/ipfs.rs b/crates/twigpine-node/src/api/ipfs.rs index 07b7d433e..f1e35ffbe 100644 --- a/crates/twigpine-node/src/api/ipfs.rs +++ b/crates/twigpine-node/src/api/ipfs.rs @@ -459,7 +459,7 @@ const SCAN_TOKEN_TTL_SECS: i64 = 3600; /// lifetime of the future that requested it. struct WalkAdmission { _global: tokio::sync::OwnedSemaphorePermit, - _per_source: Option, + _per_source: crate::rate_limit::PerCallerPermit, } pub async fn get_by_cid( @@ -518,9 +518,8 @@ pub async fn get_by_cid( // (`*_bounded` + `run_bounded_git` teardown), so a hung git cannot pin the slot // past `git_service_timeout_secs`. On unavailability shed a clean 503. The // per-source key is the resolved source IP (`client_key`), never the DID (`/ipfs` - // admits any `did:key` unthrottled, so a DID key would be free to mint around); a - // `None` key (no trusted header, no peer) is bounded by the global pool only, - // never the per-source sub-cap. + // admits any `did:key` unthrottled, so a DID key would be free to mint around). A + // missing socket peer shares the reserved unknown-peer bucket under the same cap. let global_permit = state .git_ipfs_walk_semaphore .clone() @@ -529,14 +528,11 @@ pub async fn get_by_cid( tracing::warn!("/ipfs walk concurrency cap reached; shedding request with 503"); AppError::Overloaded("ipfs service at capacity, retry shortly".into()) })?; - let source_key = crate::rate_limit::client_key(&headers, peer, state.push_limiter_trust); - let caller_permit = match &source_key { - Some(ip) => Some(state.git_ipfs_walk_per_caller.try_acquire(ip).ok_or_else(|| { - tracing::warn!(key = %ip, "/ipfs per-source walk cap reached; shedding request with 503"); - AppError::Overloaded("ipfs service at capacity for this source, retry shortly".into()) - })?), - None => None, - }; + let source_key = state.client_key(&headers, peer); + let caller_permit = state.git_ipfs_walk_per_caller.try_acquire(&source_key).ok_or_else(|| { + tracing::warn!(key = %source_key, "/ipfs per-source walk cap reached; shedding request with 503"); + AppError::Overloaded("ipfs service at capacity for this source, retry shortly".into()) + })?; // Share the admission rather than holding it as a handler local (#174 U1). A // clone goes into every `spawn_blocking` closure below, so the permits release // only when the LAST holder drops. That makes the two failure directions one @@ -939,18 +935,15 @@ pub async fn get_by_cid( // the 404 tail. That is the honest answer (its search never ran), and it drops // an oracle, since the old order let a throttled caller tell a complete source // set from an incomplete one by 404 vs 429. - if let Some(key) = - crate::rate_limit::client_key(rctx.headers, rctx.peer, state.push_limiter_trust) - { - if state.ipfs_work_rate_limiter.is_throttled(&key).await { - throttled = true; - // Skipped for a spent bucket is NOT finished: no scan ran, so nothing was - // covered. Leaving it unfinished keeps the proposer role here, so the - // caller's existing token resumes this candidate once the bucket refills - // instead of the ladder advancing past work that never happened. - earlier_all_finished = false; - continue; - } + let key = state.client_key(rctx.headers, rctx.peer); + if state.ipfs_work_rate_limiter.is_throttled(&key).await { + throttled = true; + // Skipped for a spent bucket is NOT finished: no scan ran, so nothing was + // covered. Leaving it unfinished keeps the proposer role here, so the + // caller's existing token resumes this candidate once the bucket refills + // instead of the ladder advancing past work that never happened. + earlier_all_finished = false; + continue; } // Earlier candidates were finished by earlier rungs, so their scans are owed // nothing. The skip sits HERE on purpose: above it the provenance phase can still @@ -1106,19 +1099,16 @@ pub async fn get_by_cid( // for. Without it a denial-only inventory could be re-paged for free // by re-requesting, which is the across-request half of the same // amplification. Reuses the `source_key` already resolved at - // admission; no resolvable key (a test oneshot with no peer or - // trusted header) skips the charge, exactly as the walk and probe - // brakes do. + // admission; a missing peer charges the reserved unknown-peer bucket, + // exactly as the walk and probe brakes do. // // A spent bucket sets `throttled` and breaks WITHOUT tainting and // WITHOUT a token: the caller's own bucket stopped them, their // previous token still resumes them after it refills, and the tail // renders the 429 when nothing else tainted. - if let Some(key) = &source_key { - if !state.ipfs_work_rate_limiter.check(key).await { - throttled = true; - break; - } + if !state.ipfs_work_rate_limiter.check(&source_key).await { + throttled = true; + break; } pager .fetch_next_page(&state, request_deadline, &cid_str) @@ -1657,7 +1647,7 @@ async fn gate_and_serve( // as the second bound (a single request's ceiling). A spent quota is the same non-fatal Throttled as the // walk brake: keep scanning for a walk-free copy, and only a wholly-unservable // request becomes the 429. No resolvable key (a test oneshot with no peer/header) - // skips the brake, as the walk brake does. The provenance path targets one repo + // shares the unknown-peer bucket. The provenance path targets one repo // (no fan-out) and is exempt (`legacy_scan == false`). if legacy_scan { if walk.probes >= state.ipfs_max_legacy_probes { @@ -1667,12 +1657,9 @@ async fn gate_and_serve( // refused and only the caller knows it. return GateOutcome::CeilingStop("probe-ceiling"); } - if let Some(key) = - crate::rate_limit::client_key(ctx.headers, ctx.peer, state.push_limiter_trust) - { - if !state.ipfs_work_rate_limiter.check(&key).await { - return GateOutcome::Throttled; - } + let key = state.client_key(ctx.headers, ctx.peer); + if !state.ipfs_work_rate_limiter.check(&key).await { + return GateOutcome::Throttled; } walk.probes += 1; } @@ -1886,18 +1873,15 @@ async fn gate_and_serve( // Brake each spawned walk on the source IP (#173, F3, INV-15), BEFORE // spending walk budget: a throttled candidate neither walks nor consumes // budget and must not end the request — skip it and keep scanning - // (#173 review, F-C). No key (a test oneshot with no peer/header) skips the - // brake, as the other IP brakes do. On the LEGACY path the probe brake + // (#173 review, F-C). A missing peer uses the unknown-peer bucket, as the + // other IP brakes do. On the LEGACY path the probe brake // above already charged THIS candidate to the source (#173, F3, jatmn), so // the walk brake must not double-charge it: only the provenance path // (`legacy_scan == false`, no probe toll) charges here. if !legacy_scan { - if let Some(key) = - crate::rate_limit::client_key(ctx.headers, ctx.peer, state.push_limiter_trust) - { - if !state.ipfs_work_rate_limiter.check(&key).await { - return GateOutcome::Throttled; - } + let key = state.client_key(ctx.headers, ctx.peer); + if !state.ipfs_work_rate_limiter.check(&key).await { + return GateOutcome::Throttled; } } if legacy_scan { @@ -2924,10 +2908,11 @@ mod tests { //! admission (a global pool + per-source sub-cap) held through the `spawn_blocking` //! walk, plus a per-IP route rate limit. These are handler-layer proofs: mount the //! real handler/router, drive one request, assert the exact 503 shed, then name the - //! mutation that turns each RED. The per-source key resolves an IP only (`Some(ip)` - //! vs `None`), never a DID — both arms are driven so neither is vacuous. The + //! mutation that turns each RED. The per-source key is the resolved client IP or the + //! reserved unknown-peer bucket, never a DID. The //! CID-resolution / visibility-gate behavior of the handler itself is covered by the - //! `#[sqlx::test]` suite in `test_support.rs`. + //! `#[sqlx::test]` suite in `test_support.rs`. A request without a verifiable socket + //! peer shares the reserved unknown-peer bucket rather than bypassing the sub-cap. use super::{arm_marker_query_stall, disarm_marker_query_stall, MarkerQuery}; use axum::body::Body; @@ -8832,19 +8817,18 @@ mod tests { ); } - /// The `None`-key arm: a request with no resolvable source key (no trusted-proxy - /// header, no `ConnectInfo`) is bounded by the GLOBAL pool only, never the per-source - /// sub-cap. With the global pool exhausted it still sheds 503 (the counterpart to the - /// `Some(ip)` arm above, so neither arm is vacuous). + /// With the global pool exhausted, a request whose peer cannot be verified still + /// sheds 503 even though the per-source cap is permissive. The reserved unknown-peer + /// bucket is bounded by both caps; this test isolates the global one. #[tokio::test] - async fn get_by_cid_none_key_arm_sheds_on_global_pool() { + async fn get_by_cid_unknown_peer_sheds_on_global_pool() { let mut state = crate::test_support::test_state_lazy(); state.git_ipfs_walk_semaphore = Arc::new(Semaphore::new(0)); // Per-source cap permissive so only the global pool can shed. state.git_ipfs_walk_per_caller = crate::rate_limit::PerCallerConcurrency::new(1000, 1000); state.push_limiter_trust = crate::rate_limit::TrustedProxy::None; - // No ConnectInfo + no trusted header -> client_key resolves None. + // No ConnectInfo means the reserved unknown-peer key. let resp = ipfs_router(state) .oneshot(get_cid(&valid_cid(), None)) .await @@ -8852,7 +8836,7 @@ mod tests { assert_eq!( resp.status(), StatusCode::SERVICE_UNAVAILABLE, - "a None-key request must still shed 503 on the exhausted GLOBAL /ipfs walk pool" + "an unknown-peer request must still shed 503 on the exhausted GLOBAL /ipfs walk pool" ); } @@ -9509,6 +9493,83 @@ mod tests { ); } + /// #207 server wiring: the production router must pass the state's trusted proxy + /// peer policy into the mounted IP limiter. A verified proxy gets distinct + /// forwarded-client buckets; a direct peer rotating the same header stays on its + /// socket-peer bucket and is throttled. + #[sqlx::test] + async fn server_ip_rate_limiter_uses_verified_proxy_peer_policy(pool: sqlx::PgPool) { + let mut state = crate::test_support::test_state(pool).await; + state.ipfs_rate_limiter = + crate::rate_limit::RateLimiter::new(1, std::time::Duration::from_secs(3600)); + state.push_limiter_trust = crate::rate_limit::TrustedProxy::XForwardedFor; + state.push_limiter_trusted_peers = + crate::rate_limit::TrustedProxyPeers::from_env_value("10.0.0.1").unwrap(); + + let router = crate::server::build_router(state); + let cid = valid_cid(); + let make = |peer: SocketAddr, xff: &str| { + let mut req = Request::builder() + .method(Method::GET) + .uri(format!("/ipfs/{cid}")) + .header("x-forwarded-for", xff) + .body(Body::empty()) + .unwrap(); + req.extensions_mut().insert(ConnectInfo(peer)); + req + }; + let proxy: SocketAddr = "10.0.0.1:5000".parse().unwrap(); + + let resp = router + .clone() + .oneshot(make(proxy, "198.51.100.1")) + .await + .unwrap(); + assert_ne!( + resp.status(), + StatusCode::TOO_MANY_REQUESTS, + "the first request for one forwarded client must pass the brake" + ); + let resp = router + .clone() + .oneshot(make(proxy, "198.51.100.1")) + .await + .unwrap(); + assert_eq!( + resp.status(), + StatusCode::TOO_MANY_REQUESTS, + "the same forwarded client must exhaust its own bucket" + ); + let resp = router + .clone() + .oneshot(make(proxy, "198.51.100.2")) + .await + .unwrap(); + assert_ne!( + resp.status(), + StatusCode::TOO_MANY_REQUESTS, + "a verified proxy peer must receive distinct forwarded-client buckets" + ); + + let direct: SocketAddr = "203.0.113.99:5000".parse().unwrap(); + let resp = router + .clone() + .oneshot(make(direct, "198.51.100.3")) + .await + .unwrap(); + assert_ne!( + resp.status(), + StatusCode::TOO_MANY_REQUESTS, + "the first direct-client request must pass the brake" + ); + let resp = router.oneshot(make(direct, "198.51.100.4")).await.unwrap(); + assert_eq!( + resp.status(), + StatusCode::TOO_MANY_REQUESTS, + "an unverified direct client must not rotate its bucket through XFF" + ); + } + /// F6/KTD-5: the legacy scan's page queries (`list_repos_page_for_scan`, /// `list_visibility_rules_for_repos`) run AFTER the scarce walk permits are /// acquired (held RAII for the whole request) but BEFORE the per-repo loop's diff --git a/crates/twigpine-node/src/api/issues.rs b/crates/twigpine-node/src/api/issues.rs index 2245b7eaa..cd3652f07 100644 --- a/crates/twigpine-node/src/api/issues.rs +++ b/crates/twigpine-node/src/api/issues.rs @@ -224,11 +224,10 @@ pub async fn create_issue_comment( // distinguish a hidden repo from a missing one (INV-12 — the same // placement close_issue uses for its brake). The route group carries no // outer brake for exactly this reason. - if let Some(key) = crate::rate_limit::client_key(&headers, peer, state.push_limiter_trust) { - if let Some(retry_after) = state.write_rate_limiter.check_retry(&key).await { - tracing::warn!(repo = %repo, key = %key, "create_issue_comment rate limited"); - return Err(AppError::RateLimited(retry_after)); - } + let key = state.client_key(&headers, peer); + if let Some(retry_after) = state.write_rate_limiter.check_retry(&key).await { + tracing::warn!(repo = %repo, key = %key, "create_issue_comment rate limited"); + return Err(AppError::RateLimited(retry_after)); } // Spend the signature only now. The route group has no outer brake, so a row @@ -333,28 +332,27 @@ pub async fn close_issue( // let disposable identities drive unbounded transfer/CPU/disk with parallel // close requests for arbitrary issue ids. Applied after the read gate so a // denied reader still sees 404, not 429. - if let Some(key) = crate::rate_limit::client_key(&headers, peer, state.push_limiter_trust) { - // Both buckets debit here, after the read gate (INV-12): the shared - // per-IP write brake — the route group deliberately carries no outer - // brake — and this route's own close budget. - // - // A close refused by either cap spends nothing from the other bucket. - // The write bucket is debited first, and refunded when the close cap - // then refuses, so the guarantee holds even when a concurrent close - // takes the last close slot between the two checks. A write-bucket - // refusal advertises its window's Retry-After; the close-cap refusal - // keeps the plain 429 it has always returned. - if let Some(retry_after) = state.write_rate_limiter.check_retry(&key).await { - tracing::warn!(repo = %repo, key = %key, "close_issue rate limited"); - return Err(AppError::RateLimited(retry_after)); - } - if !state.close_issue_rate_limiter.check(&key).await { - state.write_rate_limiter.refund(&key).await; - tracing::warn!(repo = %repo, key = %key, "close_issue rate limited"); - return Err(AppError::TooManyRequests( - "rate limit exceeded — try again later".into(), - )); - } + let key = state.client_key(&headers, peer); + // Both buckets debit here, after the read gate (INV-12): the shared + // per-IP write brake (the route group deliberately carries no outer + // brake) and this route's own close budget. + // + // A close refused by either cap spends nothing from the other bucket. + // The write bucket is debited first, and refunded when the close cap + // then refuses, so the guarantee holds even when a concurrent close + // takes the last close slot between the two checks. A write-bucket + // refusal advertises its window's Retry-After; the close-cap refusal + // keeps the plain 429 it has always returned. + if let Some(retry_after) = state.write_rate_limiter.check_retry(&key).await { + tracing::warn!(repo = %repo, key = %key, "close_issue rate limited"); + return Err(AppError::RateLimited(retry_after)); + } + if !state.close_issue_rate_limiter.check(&key).await { + state.write_rate_limiter.refund(&key).await; + tracing::warn!(repo = %repo, key = %key, "close_issue rate limited"); + return Err(AppError::TooManyRequests( + crate::rate_limit::RATE_LIMIT_MESSAGE.into(), + )); } // Spend the signature only now, after the read gate and both debits, for the @@ -1461,8 +1459,11 @@ mod lock_pool_shed_tests { ) .await; assert!( - matches!(res, Err(AppError::TooManyRequests(_))), - "close cap exhausted must 429: {:?}", + matches!( + &res, + Err(AppError::TooManyRequests(msg)) if msg == crate::rate_limit::RATE_LIMIT_MESSAGE + ), + "close cap exhausted must 429 with the shared rate-limit message: {:?}", res ); assert!( @@ -2476,8 +2477,7 @@ exec git "$@" let headers = axum::http::HeaderMap::new(); let peer = || crate::rate_limit::PeerAddr(Some("203.0.113.77:5000".parse().unwrap())); - let key = crate::rate_limit::client_key(&headers, peer().0, state.push_limiter_trust) - .expect("a peer addr yields a brake key"); + let key = state.client_key(&headers, peer().0); assert!(state.write_rate_limiter.check(&key).await); assert!( !state.write_rate_limiter.check(&key).await, diff --git a/crates/twigpine-node/src/api/peers.rs b/crates/twigpine-node/src/api/peers.rs index 7eb123646..0e0497118 100644 --- a/crates/twigpine-node/src/api/peers.rs +++ b/crates/twigpine-node/src/api/peers.rs @@ -899,6 +899,7 @@ mod tests { .layer(Extension(IpRateLimiter { limiter: RateLimiter::new(60, Duration::from_secs(3600)), trust: TrustedProxy::None, + trusted_peers: crate::rate_limit::TrustedProxyPeers::default(), })) .with_state(state); let mut req = @@ -947,6 +948,7 @@ mod tests { .layer(Extension(IpRateLimiter { limiter: RateLimiter::new(1, Duration::from_secs(3600)), trust: TrustedProxy::None, + trusted_peers: crate::rate_limit::TrustedProxyPeers::default(), })) .with_state(state); let peer = "203.0.113.5:5000".parse::().unwrap(); diff --git a/crates/twigpine-node/src/api/repos.rs b/crates/twigpine-node/src/api/repos.rs index 9516e0089..3741c4b07 100644 --- a/crates/twigpine-node/src/api/repos.rs +++ b/crates/twigpine-node/src/api/repos.rs @@ -764,15 +764,12 @@ pub async fn git_info_refs( // fresh-acquire reachable unauthenticated and unlimited. Applied before the // acquire so a rejected request does no Tigris work. Same per-IP limiter and // trusted-proxy policy as the POST middleware (shared buckets). - if service == "git-receive-pack" { - if let Some(key) = crate::rate_limit::client_key(&headers, peer, state.push_limiter_trust) { - if !state.push_rate_limiter.check(&key).await { - tracing::warn!(repo = %name, key = %key, "receive-pack advertisement rate limited"); - return Err(AppError::TooManyRequests( - "push rate limit exceeded — try again later".into(), - )); - } - } + let caller_key = state.client_key(&headers, peer); + if service == "git-receive-pack" && !state.push_rate_limiter.check(&caller_key).await { + tracing::warn!(repo = %name, key = %caller_key, "receive-pack advertisement rate limited"); + return Err(AppError::TooManyRequests( + "push rate limit exceeded — try again later".into(), + )); } // Per-source concurrency sub-cap (#174), keyed on the resolved source IP and @@ -785,21 +782,15 @@ pub async fn git_info_refs( // multi-source flood of push-handshake advertisements could hold every advert-pool // slot across acquire_fresh and shed other sources' advertisements, since the // per-IP push rate limiter caps rate, not concurrency (#174 review fix). - let caller_key = read_caller_key(&headers, peer, state.push_limiter_trust); let _caller_permit = if service == "git-receive-pack" { acquire_read_caller_permit( &state.git_push_advert_per_caller, - caller_key.as_deref(), + &caller_key, name, "receive-pack advert", )? } else { - acquire_read_caller_permit( - &state.git_read_per_caller, - caller_key.as_deref(), - name, - "info/refs", - )? + acquire_read_caller_permit(&state.git_read_per_caller, &caller_key, name, "info/refs")? }; // Shed with a 503 before spawning git when the concurrency cap is saturated; @@ -926,44 +917,23 @@ fn git_permit( }) } -/// Resolve the per-caller key for the read sub-cap (#174): always the resolved -/// source IP (`client_key`), never the signed DID. Public read routes accept any -/// valid `did:key` via `optional_signature` with no admission step, so keying on -/// the DID would let one host mint disposable DIDs to multiply its per-source -/// budget; the push path already throttles on the resolved source IP for exactly -/// this DID-farm reason (`rate_limit.rs`, `IpRateLimiter`). `None` when no key -/// resolves (no trusted header and no peer): such a request is bounded by the -/// global read pool only, never a 500. The per-source-IP key is only as granular -/// as `trust`; see the `max_concurrent_reads_per_caller` config doc. -fn read_caller_key( - headers: &axum::http::HeaderMap, - peer: Option, - trust: crate::rate_limit::TrustedProxy, -) -> Option { - crate::rate_limit::client_key(headers, peer, trust) -} - -/// Acquire the per-caller read sub-cap permit (#174), or shed with a 503. `key` is -/// `None` when no caller key resolves — that request is bounded by the global read -/// pool only and is never shed here (returns `Ok(None)`). `handler` labels the shed -/// log line. Shared by both read handlers so the two acquire sites cannot drift. +/// Acquire the per-caller read sub-cap permit (#174), or shed with a 503. +/// `handler` labels the shed log line. Shared by both read handlers so the two +/// acquire sites cannot drift. fn acquire_read_caller_permit( limiter: &crate::rate_limit::PerCallerConcurrency, - key: Option<&str>, + key: &str, repo: &str, handler: &str, -) -> Result> { - match key { - Some(k) => match limiter.try_acquire(k) { - Some(p) => Ok(Some(p)), - None => { - tracing::warn!(repo = %repo, caller = %k, handler, "per-caller cap reached; shedding with 503"); - Err(AppError::Overloaded( - "git service at capacity for this caller, retry shortly".into(), - )) - } - }, - None => Ok(None), +) -> Result { + match limiter.try_acquire(key) { + Some(p) => Ok(p), + None => { + tracing::warn!(repo = %repo, caller = %key, handler, "per-caller cap reached; shedding with 503"); + Err(AppError::Overloaded( + "git service at capacity for this caller, retry shortly".into(), + )) + } } } @@ -1888,15 +1858,11 @@ pub async fn git_upload_pack( // Per-caller read sub-cap (#174): after the visibility gate (KTD7) so a // visibility-denied caller never consumes a scarce read slot. Keyed on the - // resolved source IP (never the signed DID, #174 U1); no resolvable key -> - // global read pool only. - let caller_key = read_caller_key(&headers, peer, state.push_limiter_trust); - let _caller_permit = acquire_read_caller_permit( - &state.git_read_per_caller, - caller_key.as_deref(), - name, - "upload-pack", - )?; + // resolved source IP (never the signed DID, #174 U1); no verifiable peer uses + // the reserved unknown-peer bucket. + let caller_key = state.client_key(&headers, peer); + let _caller_permit = + acquire_read_caller_permit(&state.git_read_per_caller, &caller_key, name, "upload-pack")?; // Shed with a 503 before spawning git when the concurrency cap is saturated; // held for the whole op (incl. the smart_http call), released on return. Taken @@ -2931,13 +2897,13 @@ pub async fn git_receive_pack( // off for a rolling upgrade, and even with it on a single owner can open many // concurrent slow pushes to their own repo. // Keyed on the resolved source IP, NEVER the signed DID (a DID farm defeats - // a DID key); no resolvable key -> global write pool only. Then the global write permit: + // a DID key); no verifiable peer uses the reserved unknown-peer bucket. Then the global write permit: // pushes draw from the dedicated WRITE pool, separate from reads, and it is held for the // whole op (moved into the AdmissionGuard below). - let caller_key = read_caller_key(&headers, peer, state.push_limiter_trust); + let caller_key = state.client_key(&headers, peer); let _caller_permit = match acquire_read_caller_permit( &state.git_write_per_caller, - caller_key.as_deref(), + &caller_key, name, "receive-pack", ) { @@ -11586,14 +11552,11 @@ mod tests { ); } - /// #174 U1 (P1-a): the `None`-key arm — a request with no resolvable source key - /// (no trusted-proxy header, no peer) is bounded by the GLOBAL read pool only, never - /// a per-source cap. With the global read pool exhausted such a request still sheds - /// 503, proving the plain path admits/sheds on the global pool for the `None` arm - /// (the counterpart to the `Some(ip)` arm above). Complements the resolver-arm rule: - /// neither arm is vacuous. + /// #174 U1 (P1-a): with the global read pool exhausted, a request whose peer + /// cannot be verified still sheds 503 even though the per-source cap is permissive. + /// The unknown-peer bucket is bounded by both caps; this test isolates the global one. #[tokio::test] - async fn upload_pack_plain_none_key_arm_sheds_on_global_pool() { + async fn upload_pack_plain_unknown_peer_sheds_on_global_pool() { use axum::body::Body; use axum::http::{Method, Request, StatusCode}; use axum::Router; @@ -11603,7 +11566,7 @@ mod tests { let mut state = crate::test_support::test_state_lazy(); // Global read pool exhausted; per-source cap permissive so only the global pool - // can shed. No ConnectInfo + no trusted header -> read_caller_key resolves None. + // can shed. No ConnectInfo means the reserved unknown-peer key. state.git_read_semaphore = Arc::new(Semaphore::new(0)); state.git_read_per_caller = crate::rate_limit::PerCallerConcurrency::new(1000, 1000); state.push_limiter_trust = crate::rate_limit::TrustedProxy::None; @@ -11614,7 +11577,7 @@ mod tests { axum::routing::post(crate::api::repos::git_upload_pack), ) .with_state(state); - // No ConnectInfo extension and no XFF header: the caller key is None. + // No ConnectInfo extension: the caller key is the reserved unknown-peer bucket. let req = Request::builder() .method(Method::POST) .uri("/alice/repo.git/git-upload-pack") @@ -11624,7 +11587,7 @@ mod tests { assert_eq!( resp.status(), StatusCode::SERVICE_UNAVAILABLE, - "a None-key request must still shed 503 on the exhausted GLOBAL read pool" + "an unknown-peer request must still shed 503 on the exhausted GLOBAL read pool" ); } @@ -14888,7 +14851,7 @@ mod tests { /// multiply its budget. Fill the source IP's single read slot, then drive two /// requests signed under DIFFERENT DIDs from that SAME IP: both must shed 503 /// (keyed by the saturated IP, not their own free DID slots). A signed request - /// from a DIFFERENT source IP keeps its own budget. Revert `read_caller_key` to + /// from a DIFFERENT source IP keeps its own budget. Revert the caller key to /// prefer the DID and the same-IP assertions go green-not-503 (each fresh DID /// gets a free slot) -- the farm-defeat mutation probe. #[sqlx::test] @@ -14969,12 +14932,11 @@ mod tests { ); } - /// #174 SC2 (None-key): a request with no resolvable caller key (no ConnectInfo, - /// no trusted header) must NOT be shed by the per-caller cap even when another - /// caller's budget is full — it is bounded by the global read pool only. A None - /// key never keys into the map, so it never 503s from the per-caller sub-cap. + /// #174 SC2 (unknown peer): a request with no `ConnectInfo` cannot prove a + /// socket peer, so it shares the reserved unknown-peer concurrency bucket + /// rather than bypassing the per-caller cap. #[sqlx::test] - async fn info_refs_none_key_bypasses_per_caller_cap(pool: sqlx::PgPool) { + async fn info_refs_unknown_peer_shares_per_caller_cap(pool: sqlx::PgPool) { use axum::body::Body; use axum::http::{Method, Request, StatusCode}; use tower::ServiceExt; @@ -14987,24 +14949,21 @@ mod tests { .upsert_mirror_repo("z6pcnone", "pc", "/tmp/pc-nonexistent", None, false) .await .unwrap(); - // Saturate an unrelated caller's budget; the None-key request must be - // unaffected because it never keys into the per-caller map. let _slot = state .git_read_per_caller - .try_acquire("203.0.113.99") - .expect("hold an unrelated caller's slot"); + .try_acquire(crate::rate_limit::UNKNOWN_PEER_KEY) + .expect("hold the unknown-peer slot"); - // No ConnectInfo inserted -> PeerAddr is None -> no per-caller key. let router = crate::server::build_router(state.clone()); let req = Request::builder() .method(Method::GET) .uri("/z6pcnone/pc/info/refs?service=git-upload-pack") .body(Body::empty()) .unwrap(); - assert_ne!( + assert_eq!( router.oneshot(req).await.unwrap().status(), StatusCode::SERVICE_UNAVAILABLE, - "a request with no resolvable caller key must not be shed by the per-caller cap" + "a request without a verifiable peer must share the capped unknown-peer bucket" ); } @@ -15999,8 +15958,7 @@ mod tests { ); } let r = push(other, "k2").await; - // Positive, for the same reason as `f1_write_cap_is_inert_without_a_resolvable - // _source_key`: `!matches!(.., Overloaded)` is satisfied by a Forbidden, so a + // Positive: `!matches!(.., Overloaded)` is satisfied by a Forbidden, so a // gate that started rejecting this pusher would leave the test green and inert. assert!( matches!(r, Err(AppError::Git(_))), @@ -16009,12 +15967,11 @@ mod tests { ); } - /// #174 F1 (U1) fallback: a caller with no resolvable source key (no trusted - /// header, no peer address) takes no per-caller permit and is bounded by the global - /// write pool only, exactly as before the move. `acquire_read_caller_permit` - /// returns `Ok(None)` for a `None` key, so it must never 503 here. + /// #174 F1 (U1) unknown-peer fallback: a caller with no socket peer cannot + /// prove a source, so it shares the reserved unknown-peer write-cap bucket + /// instead of bypassing the per-caller cap. #[sqlx::test] - async fn f1_write_cap_is_inert_without_a_resolvable_source_key(pool: sqlx::PgPool) { + async fn f1_write_cap_bounds_unknown_peer_bucket(pool: sqlx::PgPool) { use axum::extract::{Path, State}; use axum::Extension; use std::sync::Arc; @@ -16022,19 +15979,17 @@ mod tests { let mut state = crate::test_support::test_state(pool).await; state.git_write_semaphore = Arc::new(Semaphore::new(4)); - state.git_write_per_caller = crate::rate_limit::PerCallerConcurrency::new(1, 1); + state.git_write_per_caller = crate::rate_limit::PerCallerConcurrency::new(1, 100); state.push_limiter_trust = crate::rate_limit::TrustedProxy::None; state .db .upsert_mirror_repo("z6f1none", "n1", "/tmp/f1-none-nonexistent", None, false) .await .unwrap(); - // Saturate the limiter's only key slot as well, so a request that DID resolve a - // key would be shed. The keyless request must still pass. let _slot = state .git_write_per_caller - .try_acquire("203.0.113.67") - .expect("occupy the limiter's single key slot"); + .try_acquire(crate::rate_limit::UNKNOWN_PEER_KEY) + .expect("hold the unknown-peer write slot"); let r = git_receive_pack( State(state.clone()), @@ -16048,15 +16003,9 @@ mod tests { axum::body::Bytes::from_static(b"0000"), ) .await; - // Assert the POSITIVE outcome, not the absence of one error. Reaching git on - // the missing on-disk repo is proof the request cleared BOTH the owner gate - // and the per-caller cap. The previous shape — `!matches!(r, Overloaded)` — - // was satisfied by any other error, so when owner-only push began rejecting - // this pusher the test kept reporting ok while measuring nothing. assert!( - matches!(r, Err(AppError::Git(_))), - "a caller with no resolvable source key must fall back to the global write \ - pool only, never shed on the per-caller cap, and must reach git; got {r:?}" + matches!(r, Err(AppError::Overloaded(_))), + "a caller with no verifiable peer must share the capped unknown-peer write bucket; got {r:?}" ); } diff --git a/crates/twigpine-node/src/auth/mod.rs b/crates/twigpine-node/src/auth/mod.rs index b02efbd0d..79fbe0b5f 100644 --- a/crates/twigpine-node/src/auth/mod.rs +++ b/crates/twigpine-node/src/auth/mod.rs @@ -1283,6 +1283,7 @@ mod tests { webhook_secret_key: Arc::new(webhook_secret_key), ipfs_max_served_object_bytes: crate::api::ipfs::MAX_SERVED_OBJECT_BYTES, push_limiter_trust: crate::rate_limit::TrustedProxy::None, + push_limiter_trusted_peers: crate::rate_limit::TrustedProxyPeers::default(), sync_trigger_rate_limiter: RateLimiter::new(60, Duration::from_secs(3600)), peer_write_rate_limiter: RateLimiter::new(600, Duration::from_secs(3600)), federated_rate_limiter: RateLimiter::new_bounded(12, Duration::from_secs(60), 10_000), diff --git a/crates/twigpine-node/src/config.rs b/crates/twigpine-node/src/config.rs index 777c90b74..a339b49f0 100644 --- a/crates/twigpine-node/src/config.rs +++ b/crates/twigpine-node/src/config.rs @@ -724,10 +724,11 @@ pub struct Config { /// cannot monopolize the `max_concurrent_git_ops` read pool (#174). Callers are /// keyed on the RESOLVED SOURCE IP, never the DID — a signature does not move a /// caller off this cap, so an authenticated client cannot mint DIDs to escape it. - /// IMPORTANT: the source-IP key is only as granular as `TWIGPINE_TRUSTED_PROXY`. - /// Left unset (the default), a node behind an edge/NAT keys all callers on the + /// IMPORTANT: the source-IP key is only as granular as the verified + /// `TWIGPINE_TRUSTED_PROXY` plus `TWIGPINE_TRUSTED_PROXY_CIDRS` pair. + /// Without a verified proxy peer, a node behind an edge/NAT keys all callers on the /// edge IP, so this cap collapses to a single global cap rather than per-client. - /// Set `TWIGPINE_TRUSTED_PROXY` to key on the real client; a high-fanout caller (a + /// Configure both settings to key on the real client; a high-fanout caller (a /// CI fleet behind one NAT) then needs the operator to raise this. Over-cap for a /// caller sheds a clean 503 + Retry-After. /// @@ -762,11 +763,11 @@ pub struct Config { /// Maximum concurrent `/ipfs/{cid}` walk requests a single source may hold at /// once, so one source cannot monopolize `max_concurrent_ipfs_walks` (#174). - /// Callers are keyed on the RESOLVED SOURCE IP (`client_key`/`TWIGPINE_TRUSTED_PROXY`), - /// never the DID — `/ipfs` accepts any `did:key` via `optional_signature` with no - /// admission step, so keying on the DID would let one host mint disposable DIDs to - /// multiply its budget. A request with no resolvable key (no trusted header, no - /// peer) is bounded by the global pool only, never this sub-cap. Over-cap sheds a + /// Callers are keyed on the RESOLVED SOURCE IP (`client_key` and the verified + /// trusted-proxy configuration), never the DID: `/ipfs` accepts any `did:key` via + /// `optional_signature` with no admission step, so keying on the DID would let one + /// host mint disposable DIDs to multiply its budget. A request with no verifiable + /// socket peer shares the reserved unknown-peer bucket under this sub-cap. Over-cap sheds a /// clean 503 + Retry-After. Must be between 1 and 1_048_576. Default: 4. #[arg( long, @@ -957,8 +958,8 @@ pub struct Config { /// route is publicly reachable (`optional_signature`) and each request can drive /// a full-history git walk, so it carries a per-IP flood brake in addition to the /// concurrency cap above (a rate limit bounds request *rate*, the semaphore - /// bounds concurrent slow holds — different axes). Keyed on the resolved client - /// IP via `TWIGPINE_TRUSTED_PROXY`. `0` disables. Default: 600. + /// bounds concurrent slow holds, different axes). Keyed on the client IP resolved + /// through the verified trusted-proxy configuration. `0` disables. Default: 600. /// /// This is the pure once-per-request ROUTE brake. The resolver's internal /// per-probe/per-walk WORK budget is a SEPARATE bucket whose capacity is DERIVED @@ -1046,8 +1047,8 @@ pub struct Config { /// `GET /api/v1/tasks/{id}` runs `get_visible_task` and returns an opaque 404 /// when the task is hidden or missing. These reads can require task, /// repository, and visibility-rule queries even when no task is returned, - /// so the brake bounds the cost of anonymous probes. Keyed on the resolved - /// client IP via `TWIGPINE_TRUSTED_PROXY`. `0` disables. Default: 1200 (a list page + /// so the brake bounds the cost of anonymous probes. Keyed on the client IP resolved + /// through the verified trusted-proxy configuration. `0` disables. Default: 1200 (a list page /// followed by per-task reads is a normal client pattern, so this sits above /// the `/ipfs` budget). GraphQL `tasks` / `task` queries, including WebSocket /// operations, share this per-IP budget with REST task reads. @@ -1058,7 +1059,7 @@ pub struct Config { /// (`/hf/api/models/...` and `/hf/.../resolve/...`), in requests per hour. /// These reads run the publicity gate plus release and manifest lookups /// before any answer, so the brake bounds the cost of anonymous probes. - /// Keyed on the resolved client IP via `TWIGPINE_TRUSTED_PROXY`. + /// Keyed on the client IP resolved through the verified trusted-proxy configuration. /// `0` disables. Default: 600. #[arg(long, env = "TWIGPINE_HF_READ_RATE_LIMIT", default_value_t = 600)] pub hf_read_rate_limit: usize, diff --git a/crates/twigpine-node/src/git/smart_http.rs b/crates/twigpine-node/src/git/smart_http.rs index 13a99eeeb..c798e4efd 100644 --- a/crates/twigpine-node/src/git/smart_http.rs +++ b/crates/twigpine-node/src/git/smart_http.rs @@ -32,7 +32,7 @@ pub struct AdmissionGuard { // guard only needs to hold them and drop them, never inspect them. `Send + // 'static` so the guard can move into the detached reaper task. _global: Option>, - _caller: Option>, + _caller: Box, // Any further work-scoped hold that must outlive the process group; see `with_hold`. _hold: Option>, // Per-repo write lease (#174 U2/F3), `Some` ONLY on the receive-pack write path @@ -48,14 +48,14 @@ pub struct AdmissionGuard { } impl AdmissionGuard { - /// Take ownership of the global permit and an optional per-caller permit. Both are - /// erased to `Box` — the guard's only job is to hold them until it drops. + /// Take ownership of the global and per-caller permits. Both are erased to + /// `Box`; the guard's only job is to hold them until it drops. /// No lease is attached here; the receive-pack write path adds one via /// [`with_lease`](Self::with_lease), so every other call site is lease-free. - pub fn new(global: impl Send + 'static, caller: Option) -> Self { + pub fn new(global: impl Send + 'static, caller: impl Send + 'static) -> Self { Self { _global: Some(Box::new(global)), - _caller: caller.map(|c| Box::new(c) as Box), + _caller: Box::new(caller), _hold: None, _lease: None, } @@ -2414,7 +2414,7 @@ mod tests { let sem = Arc::new(Semaphore::new(4)); let g = sem.clone().try_acquire_owned().unwrap(); let c = sem.clone().try_acquire_owned().unwrap(); - let admission = AdmissionGuard::new(g, Some(c)); + let admission = AdmissionGuard::new(g, c); let mut fut = Box::pin(build_filtered_pack( git_bin.to_str().unwrap(), tmp.path(), @@ -2538,7 +2538,7 @@ mod tests { ); let git_bin = write_fake_git(tmp.path(), &body); let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(1)); - let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), None::<()>); + let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), ()); let withheld = HashSet::new(); let mut fut = Box::pin(build_filtered_pack( @@ -2611,7 +2611,7 @@ mod tests { let td = TempDir::new().unwrap(); let (_work, bare, secret_oid, _public_oid) = fixture_with_secret(&td); let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(1)); - let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), None::<()>); + let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), ()); let withheld = HashSet::from([secret_oid]); let (resp, _served_pack) = upload_pack_excluding( "git", @@ -2645,7 +2645,7 @@ mod tests { let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(1)); for i in 0..FAKE_GIT_RETRY_ATTEMPTS { - let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), None::<()>); + let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), ()); let result = build_filtered_pack( git_bin.to_str().unwrap(), tmp.path(), @@ -2695,7 +2695,7 @@ mod tests { let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(1)); for i in 0..FAKE_GIT_RETRY_ATTEMPTS { - let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), None::<()>); + let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), ()); let result = tokio::time::timeout( Duration::from_secs(10), build_filtered_pack( @@ -2750,7 +2750,7 @@ mod tests { let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(1)); for i in 0..FAKE_GIT_RETRY_ATTEMPTS { - let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), None::<()>); + let guard = AdmissionGuard::new(sem.clone().try_acquire_owned().unwrap(), ()); let mut command = tokio::process::Command::new(git_bin.to_str().unwrap()); command .args(["pack-objects", "--stdout"]) diff --git a/crates/twigpine-node/src/lib.rs b/crates/twigpine-node/src/lib.rs index 4b1a05ea4..a445ebc03 100644 --- a/crates/twigpine-node/src/lib.rs +++ b/crates/twigpine-node/src/lib.rs @@ -490,13 +490,29 @@ pub async fn run() -> Result<()> { ); } - // Which forwarded header the edge is trusted to set. Default None (trust - // nothing, key on the socket peer). Fly nodes set TWIGPINE_TRUSTED_PROXY=fly; - // a node behind Caddy/NGINX sets it to x-forwarded-for. + // Which forwarded header a verified edge peer may assert. Default None + // (trust nothing, key on the socket peer). The peer allowlist is separate: + // the header mode alone never proves the connection came from that edge. let push_limiter_trust = rate_limit::TrustedProxy::from_env_value( &std::env::var("TWIGPINE_TRUSTED_PROXY").unwrap_or_default(), ); - tracing::info!(trust = ?push_limiter_trust, "push rate limiter trust configured"); + let push_limiter_trusted_peers = match rate_limit::TrustedProxyPeers::from_env_value( + &std::env::var("TWIGPINE_TRUSTED_PROXY_CIDRS").unwrap_or_default(), + ) { + Ok(peers) => peers, + Err(err) => { + tracing::error!(error = %err, "trusted proxy peer configuration invalid; trusting no proxy peers"); + rate_limit::TrustedProxyPeers::default() + } + }; + if push_limiter_trust != rate_limit::TrustedProxy::None && push_limiter_trusted_peers.is_empty() + { + tracing::warn!( + trust = ?push_limiter_trust, + "TWIGPINE_TRUSTED_PROXY is set but TWIGPINE_TRUSTED_PROXY_CIDRS is empty; forwarded headers are ignored and clients share the proxy peer bucket" + ); + } + tracing::info!(trust = ?push_limiter_trust, trusted_proxy_peers_empty = push_limiter_trusted_peers.is_empty(), "push rate limiter trust configured"); // Peer-sync flood brakes, keyed on the resolved client IP (per-DID is useless // here — a did:key farm self-registers). Two buckets so an unsigned notify @@ -554,6 +570,7 @@ pub async fn run() -> Result<()> { webhook_secret_key: Arc::new(webhook_secret_key), ipfs_max_served_object_bytes: crate::api::ipfs::MAX_SERVED_OBJECT_BYTES, push_limiter_trust, + push_limiter_trusted_peers, sync_trigger_rate_limiter, peer_write_rate_limiter, federated_rate_limiter, diff --git a/crates/twigpine-node/src/rate_limit.rs b/crates/twigpine-node/src/rate_limit.rs index c38247f42..0b7837484 100644 --- a/crates/twigpine-node/src/rate_limit.rs +++ b/crates/twigpine-node/src/rate_limit.rs @@ -1,5 +1,5 @@ use std::collections::HashMap; -use std::net::SocketAddr; +use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -408,38 +408,141 @@ impl TrustedProxy { } } +/// Key used when no socket peer is available to verify. The angle brackets cannot +/// collide with the string form of a socket IP, so one reserved bucket covers +/// synthetic or misintegrated transports instead of letting them bypass the limiter. +pub const UNKNOWN_PEER_KEY: &str = ""; + +/// Error for one malformed entry in `TWIGPINE_TRUSTED_PROXY_CIDRS`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TrustedProxyPeersError { + entry: String, +} + +impl std::fmt::Display for TrustedProxyPeersError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "invalid trusted proxy peer entry {:?}; expected an IP address or CIDR", + self.entry + ) + } +} + +impl std::error::Error for TrustedProxyPeersError {} + +/// Operator-configured socket peers allowed to assert forwarded client identity. +/// Empty trusts no proxy. Parsing is all-or-nothing so one typo cannot silently +/// leave a partial trust boundary in force. +#[derive(Clone, Debug, Default)] +pub struct TrustedProxyPeers { + networks: Arc>, +} + +impl TrustedProxyPeers { + /// Parse `TWIGPINE_TRUSTED_PROXY_CIDRS`: comma-separated exact IPs or CIDRs. + pub fn from_env_value(s: &str) -> Result { + let mut networks = Vec::new(); + for entry in s.split(',').map(str::trim).filter(|e| !e.is_empty()) { + let network = entry.parse::().or_else(|_| { + entry.parse::().map(|ip| { + let prefix = match ip { + IpAddr::V4(_) => 32, + IpAddr::V6(_) => 128, + }; + ipnet::IpNet::new(ip, prefix).expect("host prefix is valid") + }) + }); + match network { + Ok(network) => networks.push(canonical_net(network)), + Err(_) => { + return Err(TrustedProxyPeersError { + entry: entry.to_string(), + }) + } + } + } + Ok(Self { + networks: Arc::new(networks), + }) + } + + pub fn contains(&self, ip: IpAddr) -> bool { + self.networks.iter().any(|network| network.contains(&ip)) + } + + pub fn is_empty(&self) -> bool { + self.networks.is_empty() + } +} + +/// IPv4-mapped IPv6 peers are the IPv4 host for trust matching and keying. +fn canonical_ip(ip: IpAddr) -> IpAddr { + match ip { + IpAddr::V6(v6) => v6 + .to_ipv4_mapped() + .map(IpAddr::V4) + .unwrap_or(IpAddr::V6(v6)), + v4 => v4, + } +} + +/// An allowlist entry inside the IPv4-mapped subspace (`::ffff:0:0/96`) is the +/// matching IPv4 network, because `client_key` matches peers after +/// `canonical_ip`. Native IPv6 entries are kept as written. +fn canonical_net(net: ipnet::IpNet) -> ipnet::IpNet { + match net { + ipnet::IpNet::V6(v6) if v6.prefix_len() >= 96 => match v6.network().to_ipv4_mapped() { + Some(v4) => ipnet::Ipv4Net::new(v4, v6.prefix_len() - 96) + .expect("a prefix of 96..=128 maps to 0..=32") + .into(), + None => net, + }, + other => other, + } +} + fn trimmed_nonempty(v: &str) -> Option { let t = v.trim(); (!t.is_empty()).then(|| t.to_string()) } /// Resolve the rate-limit key for a request. In a trusted-proxy mode the -/// operator's edge header is preferred; when that header is missing or empty we -/// fall back to the socket peer address rather than skipping the limiter (a -/// malformed header must never disable the brake). With no trusted proxy the -/// socket peer is always used and forwarded headers are ignored entirely. -/// Returns `None` only when neither a trusted header nor a peer address is -/// available (e.g. a synthetic test request with no `ConnectInfo`). +/// operator's edge header is used only when the socket peer is in the configured +/// trusted-proxy allowlist. When that proof is absent, or the header is missing +/// or empty, the key falls back to the socket peer address rather than skipping +/// the limiter (a malformed header must never disable the brake). With no trusted +/// proxy the socket peer is always used and forwarded headers are ignored entirely. +/// With no socket peer, the request shares the reserved unknown-peer bucket. pub fn client_key( headers: &HeaderMap, peer: Option, trust: TrustedProxy, -) -> Option { - let from_header = match trust { - TrustedProxy::None => None, - TrustedProxy::Fly => headers - .get("fly-client-ip") - .and_then(|v| v.to_str().ok()) - .and_then(trimmed_nonempty), - // Rightmost hop = the value appended by the immediately-upstream trusted - // proxy. The leftmost hop is client-controlled and must not be trusted. - TrustedProxy::XForwardedFor => headers - .get("x-forwarded-for") - .and_then(|v| v.to_str().ok()) - .and_then(|v| v.rsplit(',').next()) - .and_then(trimmed_nonempty), + trusted_peers: &TrustedProxyPeers, +) -> String { + let peer_ip = peer.map(|p| canonical_ip(p.ip())); + let peer_is_trusted_proxy = peer_ip.is_some_and(|ip| trusted_peers.contains(ip)); + let from_header = if peer_is_trusted_proxy { + match trust { + TrustedProxy::None => None, + TrustedProxy::Fly => headers + .get("fly-client-ip") + .and_then(|v| v.to_str().ok()) + .and_then(trimmed_nonempty), + // Rightmost hop = the value appended by the immediately-upstream trusted + // proxy. The leftmost hop is client-controlled and must not be trusted. + TrustedProxy::XForwardedFor => headers + .get("x-forwarded-for") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.rsplit(',').next()) + .and_then(trimmed_nonempty), + } + } else { + None }; - from_header.or_else(|| peer.map(|p| p.ip().to_string())) + from_header + .or_else(|| peer_ip.map(|ip| ip.to_string())) + .unwrap_or_else(|| UNKNOWN_PEER_KEY.to_string()) } /// Per-client-IP limiter for the git push path, carrying the trusted-proxy @@ -451,6 +554,7 @@ pub fn client_key( pub struct IpRateLimiter { pub limiter: RateLimiter, pub trust: TrustedProxy, + pub trusted_peers: TrustedProxyPeers, } /// Infallible extractor for the socket peer address from `ConnectInfo`. Yields @@ -523,19 +627,17 @@ pub const MAX_GRAPHQL_TASK_READS_PER_REQUEST: usize = 5; #[derive(Clone)] pub struct TaskReadBrake { pub limiter: RateLimiter, - /// `None` when no key could be resolved at all (no trusted header and no - /// `ConnectInfo`, e.g. a synthetic test request). Never braked, matching - /// [`rate_limit_by_ip`]. - pub key: Option, + /// Resolved once at the connection or request boundary. A missing socket peer + /// is the reserved unknown-peer bucket, so unattributable requests are braked + /// together rather than skipped. + pub key: String, pub request_count: Arc, } impl TaskReadBrake { /// Debit one slot for one task-read field. `true` = proceed. pub async fn check(&self, field: &str) -> bool { - let Some(key) = self.key.as_deref() else { - return true; - }; + let key = self.key.as_str(); let count = self .request_count .fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -558,7 +660,7 @@ impl TaskReadBrake { /// Throttle the git push path by resolved client IP. The socket peer address is /// read from `ConnectInfo` (see `into_make_service_with_connect_info` in -/// `main`). Only skips the limiter when no key can be resolved at all. +/// `main`). A missing peer resolves to the reserved unknown-peer bucket. pub async fn rate_limit_by_ip(request: Request, next: Next) -> Response { let limiter = request.extensions().get::().cloned(); let peer = request @@ -567,11 +669,15 @@ pub async fn rate_limit_by_ip(request: Request, next: Next) -> Response { .map(|c| c.0); if let Some(limiter) = limiter { - if let Some(key) = client_key(request.headers(), peer, limiter.trust) { - if let Some(retry_after) = limiter.limiter.check_retry(&key).await { - tracing::warn!(key = %key, path = %request.uri().path(), "per-IP rate limit exceeded"); - return too_many_requests(retry_after); - } + let key = client_key( + request.headers(), + peer, + limiter.trust, + &limiter.trusted_peers, + ); + if let Some(retry_after) = limiter.limiter.check_retry(&key).await { + tracing::warn!(key = %key, path = %request.uri().path(), "per-IP rate limit exceeded"); + return too_many_requests(retry_after); } } @@ -798,36 +904,174 @@ mod tests { Some(s.parse().unwrap()) } + fn peers(s: &str) -> TrustedProxyPeers { + TrustedProxyPeers::from_env_value(s).unwrap() + } + #[test] fn none_mode_ignores_headers_and_uses_peer() { // Even a well-formed Fly header is ignored without a trusted proxy. let h = headers(&[("fly-client-ip", "203.0.113.7")]); assert_eq!( - client_key(&h, peer("198.51.100.9:4000"), TrustedProxy::None).as_deref(), - Some("198.51.100.9") + client_key( + &h, + peer("198.51.100.9:4000"), + TrustedProxy::None, + &peers("198.51.100.9"), + ), + "198.51.100.9" ); } #[test] - fn fly_mode_trusts_fly_header() { + fn fly_mode_ignores_header_from_untrusted_peer() { + // The issue-207 exploit: direct reachability must not let a client choose + // a fresh bucket by rotating Fly-Client-IP. let h = headers(&[ ("fly-client-ip", "203.0.113.7"), ("x-forwarded-for", "1.2.3.4"), ]); assert_eq!( - client_key(&h, peer("10.0.0.1:1"), TrustedProxy::Fly).as_deref(), - Some("203.0.113.7") + client_key( + &h, + peer("198.51.100.9:4000"), + TrustedProxy::Fly, + &peers("10.0.0.1") + ), + "198.51.100.9" + ); + } + + #[test] + fn fly_mode_trusts_header_from_configured_proxy_peer() { + let h = headers(&[ + ("fly-client-ip", "203.0.113.7"), + ("x-forwarded-for", "1.2.3.4"), + ]); + assert_eq!( + client_key( + &h, + peer("10.0.0.1:1"), + TrustedProxy::Fly, + &peers("10.0.0.0/24") + ), + "203.0.113.7" + ); + } + + #[test] + fn mapped_allowlist_entries_match_the_ipv4_peer() { + // client_key canonicalizes an IPv4-mapped socket peer to IPv4, so a + // mapped host or mapped-subspace CIDR in the allowlist must match too. + let h = headers(&[("fly-client-ip", "203.0.113.7")]); + for entry in ["::ffff:10.0.0.1", "::ffff:10.0.0.0/120"] { + for p in ["[::ffff:10.0.0.1]:4000", "10.0.0.1:4000"] { + assert_eq!( + client_key(&h, peer(p), TrustedProxy::Fly, &peers(entry)), + "203.0.113.7", + "entry {entry} must trust peer {p}" + ); + } + } + // The mapped /120 covers 10.0.0.0/24 and nothing outside it. + assert_eq!( + client_key( + &h, + peer("[::ffff:10.0.1.1]:4000"), + TrustedProxy::Fly, + &peers("::ffff:10.0.0.0/120"), + ), + "10.0.1.1" + ); + // A mapped host entry trusts only that host. + assert_eq!( + client_key( + &h, + peer("10.0.0.2:4000"), + TrustedProxy::Fly, + &peers("::ffff:10.0.0.1"), + ), + "10.0.0.2" + ); + } + + #[test] + fn native_ipv6_allowlist_entries_still_match() { + let h = headers(&[("fly-client-ip", "203.0.113.7")]); + for entry in ["2001:db8::1", "2001:db8::/64"] { + assert_eq!( + client_key( + &h, + peer("[2001:db8::1]:4000"), + TrustedProxy::Fly, + &peers(entry) + ), + "203.0.113.7", + "native entry {entry}" + ); + } + assert_eq!( + client_key( + &h, + peer("[2001:db9::1]:4000"), + TrustedProxy::Fly, + &peers("2001:db8::/64"), + ), + "2001:db9::1" + ); + } + + #[test] + fn empty_allowlist_never_trusts_forwarded_header() { + let h = headers(&[("fly-client-ip", "203.0.113.7")]); + assert_eq!( + client_key( + &h, + peer("10.0.0.1:1"), + TrustedProxy::Fly, + &TrustedProxyPeers::default(), + ), + "10.0.0.1", + "an empty trusted proxy peer list must ignore forwarded headers" + ); + } + + #[test] + fn missing_peer_uses_reserved_unknown_bucket() { + let h = headers(&[("fly-client-ip", "203.0.113.7")]); + assert_eq!( + client_key(&h, None, TrustedProxy::Fly, &peers("10.0.0.1")), + UNKNOWN_PEER_KEY + ); + } + + #[test] + fn ipv4_mapped_ipv6_proxy_matches_ipv4_allowlist() { + let h = headers(&[("x-forwarded-for", "203.0.113.7")]); + assert_eq!( + client_key( + &h, + peer("[::ffff:10.0.0.1]:1"), + TrustedProxy::XForwardedFor, + &peers("10.0.0.0/24"), + ), + "203.0.113.7" ); } #[test] fn fly_mode_empty_header_falls_back_to_peer_not_skip() { - // Empty Fly-Client-IP must NOT collapse traffic onto Some("") nor skip - // the limiter — it falls back to the real peer. + // Empty Fly-Client-IP must not collapse traffic onto Some("") nor skip + // the limiter; it falls back to the real peer. let h = headers(&[("fly-client-ip", "")]); assert_eq!( - client_key(&h, peer("198.51.100.9:4000"), TrustedProxy::Fly).as_deref(), - Some("198.51.100.9") + client_key( + &h, + peer("10.0.0.1:4000"), + TrustedProxy::Fly, + &peers("10.0.0.1") + ), + "10.0.0.1" ); } @@ -836,18 +1080,28 @@ mod tests { // Client prepends spoofed hops; only the rightmost (proxy-appended) is trusted. let h = headers(&[("x-forwarded-for", "9.9.9.9, 8.8.8.8, 198.51.100.9")]); assert_eq!( - client_key(&h, peer("10.0.0.1:1"), TrustedProxy::XForwardedFor).as_deref(), - Some("198.51.100.9") + client_key( + &h, + peer("10.0.0.1:1"), + TrustedProxy::XForwardedFor, + &peers("10.0.0.1"), + ), + "198.51.100.9" ); } #[test] fn xff_mode_empty_leading_hop_does_not_disable_brake() { - // "X-Forwarded-For: ,1.2.3.4" — rightmost hop is used; never None-skips. + // "X-Forwarded-For: ,1.2.3.4": rightmost hop is used; never None-skips. let h = headers(&[("x-forwarded-for", ",1.2.3.4")]); assert_eq!( - client_key(&h, peer("10.0.0.1:1"), TrustedProxy::XForwardedFor).as_deref(), - Some("1.2.3.4") + client_key( + &h, + peer("10.0.0.1:1"), + TrustedProxy::XForwardedFor, + &peers("10.0.0.1"), + ), + "1.2.3.4" ); } @@ -855,11 +1109,63 @@ mod tests { fn malformed_xff_falls_back_to_peer() { let h = headers(&[("x-forwarded-for", " , ")]); assert_eq!( - client_key(&h, peer("198.51.100.9:4000"), TrustedProxy::XForwardedFor).as_deref(), - Some("198.51.100.9") + client_key( + &h, + peer("10.0.0.1:4000"), + TrustedProxy::XForwardedFor, + &peers("10.0.0.1"), + ), + "10.0.0.1" ); } + #[test] + fn trusted_exact_ipv6_peer_can_assert_fly_header() { + let h = headers(&[("fly-client-ip", "203.0.113.7")]); + assert_eq!( + client_key( + &h, + peer("[2001:db8::10]:443"), + TrustedProxy::Fly, + &peers("2001:db8::10"), + ), + "203.0.113.7" + ); + } + + #[test] + fn ipv4_mapped_ipv6_fallback_key_is_canonical_ipv4() { + assert_eq!( + client_key( + &HeaderMap::new(), + peer("[::ffff:10.0.0.1]:1"), + TrustedProxy::None, + &TrustedProxyPeers::default(), + ), + "10.0.0.1" + ); + } + + #[test] + fn trusted_proxy_peer_parsing_accepts_ips_and_cidrs() { + assert!(TrustedProxyPeers::from_env_value(" , ") + .unwrap() + .is_empty()); + let parsed = peers(" 10.0.0.1, 192.168.0.0/16,2001:db8::1, 2001:db8::/32 "); + assert!(parsed.contains("10.0.0.1".parse().unwrap())); + assert!(!parsed.contains("10.0.0.2".parse().unwrap())); + assert!(parsed.contains("192.168.4.5".parse().unwrap())); + assert!(parsed.contains("2001:db8::1".parse().unwrap())); + assert!(parsed.contains("2001:db8::ffff".parse().unwrap())); + assert!(!parsed.contains("2001:db9::1".parse().unwrap())); + } + + #[test] + fn trusted_proxy_peer_parsing_rejects_whole_list_on_one_bad_entry() { + let err = TrustedProxyPeers::from_env_value("10.0.0.1, not-an-ip").unwrap_err(); + assert!(err.to_string().contains("not-an-ip")); + } + #[test] fn trusted_proxy_parsing() { assert_eq!(TrustedProxy::from_env_value("fly"), TrustedProxy::Fly); @@ -901,11 +1207,22 @@ mod tests { router.clone().oneshot(req).await.unwrap().status() } + async fn post_without_peer(router: &axum::Router) -> StatusCode { + use tower::ServiceExt; + let req = axum::http::Request::builder() + .method(axum::http::Method::POST) + .uri("/o/r/git-receive-pack") + .body(axum::body::Body::empty()) + .unwrap(); + router.clone().oneshot(req).await.unwrap().status() + } + #[tokio::test] async fn middleware_returns_429_over_limit() { let router = ip_limited_router(IpRateLimiter { limiter: RateLimiter::new(2, Duration::from_secs(60)), trust: TrustedProxy::None, + trusted_peers: crate::rate_limit::TrustedProxyPeers::default(), }); let peer: SocketAddr = "203.0.113.7:5000".parse().unwrap(); // Two requests inside the budget, the third over it (shared Arc state). @@ -922,6 +1239,7 @@ mod tests { let router = ip_limited_router(IpRateLimiter { limiter: RateLimiter::new(1, Duration::from_secs(60)), trust: TrustedProxy::None, + trusted_peers: crate::rate_limit::TrustedProxyPeers::default(), }); let a: SocketAddr = "203.0.113.1:1".parse().unwrap(); let b: SocketAddr = "203.0.113.2:1".parse().unwrap(); @@ -975,6 +1293,7 @@ mod tests { let router = ip_limited_over_auth_router(IpRateLimiter { limiter: RateLimiter::new(1, Duration::from_secs(60)), trust: TrustedProxy::None, + trusted_peers: crate::rate_limit::TrustedProxyPeers::default(), }); let peer: SocketAddr = "203.0.113.42:7000".parse().unwrap(); @@ -1023,6 +1342,7 @@ mod tests { let router = ip_limited_over_auth_router(IpRateLimiter { limiter: RateLimiter::new(1, Duration::from_secs(60)), trust: TrustedProxy::XForwardedFor, + trusted_peers: peers("10.0.0.0/24,172.16.0.1"), }); let p1: SocketAddr = "10.0.0.1:1".parse().unwrap(); let p2: SocketAddr = "10.0.0.2:1".parse().unwrap(); @@ -1047,6 +1367,7 @@ mod tests { let router = ip_limited_over_auth_router(IpRateLimiter { limiter: RateLimiter::new(1, Duration::from_secs(60)), trust: TrustedProxy::XForwardedFor, + trusted_peers: peers("10.0.0.0/24,172.16.0.1"), }); let peer: SocketAddr = "10.0.0.9:1".parse().unwrap(); assert_eq!( @@ -1070,6 +1391,62 @@ mod tests { ); } + #[tokio::test] + async fn direct_client_cannot_rotate_xff_bucket() { + // A direct client is not in the trusted proxy range. Rotating the + // forwarded value must leave the key on the real socket peer, so the + // second request hits the same exhausted bucket. + let router = ip_limited_over_auth_router(IpRateLimiter { + limiter: RateLimiter::new(1, Duration::from_secs(60)), + trust: TrustedProxy::XForwardedFor, + trusted_peers: peers("10.0.0.0/24"), + }); + let direct: SocketAddr = "203.0.113.99:1".parse().unwrap(); + assert_eq!( + post_with(&router, direct, &[("x-forwarded-for", "198.51.100.1")]).await, + StatusCode::UNAUTHORIZED + ); + assert_eq!( + post_with(&router, direct, &[("x-forwarded-for", "198.51.100.2")]).await, + StatusCode::TOO_MANY_REQUESTS, + "an untrusted peer must not rotate its bucket through X-Forwarded-For" + ); + } + + #[tokio::test] + async fn direct_client_cannot_rotate_fly_bucket() { + let router = ip_limited_over_auth_router(IpRateLimiter { + limiter: RateLimiter::new(1, Duration::from_secs(60)), + trust: TrustedProxy::Fly, + trusted_peers: peers("10.0.0.0/24"), + }); + let direct: SocketAddr = "203.0.113.99:1".parse().unwrap(); + assert_eq!( + post_with(&router, direct, &[("fly-client-ip", "198.51.100.1")]).await, + StatusCode::UNAUTHORIZED + ); + assert_eq!( + post_with(&router, direct, &[("fly-client-ip", "198.51.100.2")]).await, + StatusCode::TOO_MANY_REQUESTS, + "an untrusted peer must not rotate its bucket through Fly-Client-IP" + ); + } + + #[tokio::test] + async fn missing_connect_info_shares_unknown_peer_bucket() { + let router = ip_limited_router(IpRateLimiter { + limiter: RateLimiter::new(1, Duration::from_secs(60)), + trust: TrustedProxy::XForwardedFor, + trusted_peers: peers("10.0.0.0/24"), + }); + assert_eq!(post_without_peer(&router).await, StatusCode::OK); + assert_eq!( + post_without_peer(&router).await, + StatusCode::TOO_MANY_REQUESTS, + "requests without a verifiable socket peer share one braked bucket" + ); + } + #[tokio::test] async fn absent_trusted_header_collapses_to_socket_peer() { // The documented fallback: in a trusted-proxy mode, a request with no @@ -1079,6 +1456,7 @@ mod tests { let router = ip_limited_over_auth_router(IpRateLimiter { limiter: RateLimiter::new(1, Duration::from_secs(60)), trust: TrustedProxy::XForwardedFor, + trusted_peers: peers("10.0.0.0/24,172.16.0.1"), }); let proxy: SocketAddr = "172.16.0.1:1".parse().unwrap(); assert_eq!( @@ -1125,6 +1503,7 @@ mod tests { let router = ip_limited_router(IpRateLimiter { limiter: RateLimiter::new(1, Duration::from_secs(100)), trust: TrustedProxy::None, + trusted_peers: crate::rate_limit::TrustedProxyPeers::default(), }); let peer: SocketAddr = "203.0.113.50:6000".parse().unwrap(); assert_eq!(resp_from(&router, peer).await.status(), StatusCode::OK); @@ -1150,6 +1529,7 @@ mod tests { let router = ip_limited_router(IpRateLimiter { limiter, trust: TrustedProxy::None, + trusted_peers: crate::rate_limit::TrustedProxyPeers::default(), }); let resp = resp_from(&router, peer).await; assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS); @@ -1173,6 +1553,7 @@ mod tests { let router = ip_limited_router(IpRateLimiter { limiter, trust: TrustedProxy::None, + trusted_peers: crate::rate_limit::TrustedProxyPeers::default(), }); let resp = resp_from(&router, peer).await; assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS); diff --git a/crates/twigpine-node/src/server.rs b/crates/twigpine-node/src/server.rs index 01318b6e9..f0f1e2dea 100644 --- a/crates/twigpine-node/src/server.rs +++ b/crates/twigpine-node/src/server.rs @@ -45,7 +45,7 @@ async fn graphql_handler( // and not signature verification. inner = inner.data(rate_limit::TaskReadBrake { limiter: state.task_read_rate_limiter.clone(), - key: rate_limit::client_key(&headers, peer, state.push_limiter_trust), + key: state.client_key(&headers, peer), request_count: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)), }); state.graphql_schema.execute(inner).await.into() @@ -65,7 +65,7 @@ async fn graphql_ws_handler( } data.insert(rate_limit::TaskReadBrake { limiter: state.task_read_rate_limiter.clone(), - key: rate_limit::client_key(&headers, peer, state.push_limiter_trust), + key: state.client_key(&headers, peer), request_count: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)), }); let schema = state.graphql_ws_schema.as_ref().clone(); @@ -167,6 +167,7 @@ pub fn build_router(state: AppState) -> Router { let write_ip_limiter = rate_limit::IpRateLimiter { limiter: state.write_rate_limiter.clone(), trust: state.push_limiter_trust, + trusted_peers: state.push_limiter_trusted_peers.clone(), }; let graphql_http = Router::new() @@ -217,6 +218,7 @@ pub fn build_router(state: AppState) -> Router { let task_read_limiter = rate_limit::IpRateLimiter { limiter: state.task_read_rate_limiter.clone(), trust: state.push_limiter_trust, + trusted_peers: state.push_limiter_trusted_peers.clone(), // Braking reads is this limiter's job; no write-only exemption. }; let task_read_routes = Router::new() @@ -241,6 +243,7 @@ pub fn build_router(state: AppState) -> Router { let create_ip_limiter = rate_limit::IpRateLimiter { limiter: state.create_ip_rate_limiter.clone(), trust: state.push_limiter_trust, + trusted_peers: state.push_limiter_trusted_peers.clone(), }; let creation_routes = add_auth_layers( Router::new() @@ -385,6 +388,7 @@ pub fn build_router(state: AppState) -> Router { .layer(axum::Extension(rate_limit::IpRateLimiter { limiter: state.create_ip_rate_limiter.clone(), trust: state.push_limiter_trust, + trusted_peers: state.push_limiter_trusted_peers.clone(), })); // ── Status claim reads — open, behind `optional_signature` so the handler @@ -418,6 +422,7 @@ pub fn build_router(state: AppState) -> Router { let push_limiter = rate_limit::IpRateLimiter { limiter: state.push_rate_limiter.clone(), trust: state.push_limiter_trust, + trusted_peers: state.push_limiter_trusted_peers.clone(), }; let git_write_routes = add_auth_layers( Router::new() @@ -460,6 +465,7 @@ pub fn build_router(state: AppState) -> Router { let ipfs_limiter = rate_limit::IpRateLimiter { limiter: state.ipfs_rate_limiter.clone(), trust: state.push_limiter_trust, + trusted_peers: state.push_limiter_trusted_peers.clone(), }; let ipfs_cid_routes = Router::new() .route("/ipfs/{cid}", get(ipfs::get_by_cid)) @@ -592,6 +598,7 @@ pub fn build_router(state: AppState) -> Router { .layer(axum::Extension(rate_limit::IpRateLimiter { limiter: state.sync_trigger_rate_limiter.clone(), trust: state.push_limiter_trust, + trusted_peers: state.push_limiter_trusted_peers.clone(), })); // announce + notify keep their rolling-upgrade signature behavior (unsigned @@ -615,6 +622,7 @@ pub fn build_router(state: AppState) -> Router { .layer(axum::Extension(rate_limit::IpRateLimiter { limiter: state.peer_write_rate_limiter.clone(), trust: state.push_limiter_trust, + trusted_peers: state.push_limiter_trusted_peers.clone(), })) // Announce and notify payloads are both small even at every field cap. // Keep unknown-member padding from turning the pre-validation parse @@ -634,6 +642,7 @@ pub fn build_router(state: AppState) -> Router { .route_layer(axum::Extension(rate_limit::IpRateLimiter { limiter: state.federated_rate_limiter.clone(), trust: state.push_limiter_trust, + trusted_peers: state.push_limiter_trusted_peers.clone(), // Braking reads is this limiter's job; no write-only exemption. })), ) @@ -839,6 +848,7 @@ pub fn build_router(state: AppState) -> Router { let hf_limiter = rate_limit::IpRateLimiter { limiter: state.hf_read_rate_limiter.clone(), trust: state.push_limiter_trust, + trusted_peers: state.push_limiter_trusted_peers.clone(), }; let hf = Router::new() .route("/hf/api/models/{owner}/{repo}", get(hf::hf_model_info)) diff --git a/crates/twigpine-node/src/state.rs b/crates/twigpine-node/src/state.rs index d8c777ca1..6717fb9e9 100644 --- a/crates/twigpine-node/src/state.rs +++ b/crates/twigpine-node/src/state.rs @@ -218,9 +218,12 @@ pub struct AppState { /// A field for the same test-seam reason as the sibling caps. pub ipfs_max_served_object_bytes: u64, /// Which forwarded header (if any) the edge is trusted to set, for - /// resolving the push limiter's client-IP key. See `TWIGPINE_TRUSTED_PROXY`. + /// resolving client-IP keys. Honored only for peers in `push_limiter_trusted_peers`. /// Node-wide; also keys the two peer-sync limiters below. pub push_limiter_trust: crate::rate_limit::TrustedProxy, + /// Socket peers allowed to assert the forwarded header selected by + /// `push_limiter_trust`. Empty trusts no proxy and therefore keys on peers. + pub push_limiter_trusted_peers: crate::rate_limit::TrustedProxyPeers, /// Per-client-IP limiter for `POST /api/v1/sync/trigger` (tight). The route /// requires a signature, but a signature does not cap cost (a did:key farm /// self-registers), and its per-call cost is an O(peers) fan-out, so the IP @@ -363,8 +366,10 @@ pub struct AppState { /// (keyed on the resolved source IP, never the DID — `/ipfs` admits any `did:key` /// unthrottled, so a DID key would be free to mint around) may hold at most /// `ipfs_walk_per_source` in-flight walk slots, so one source cannot monopolize - /// `git_ipfs_walk_semaphore` (#174 P1-3). A request with no resolvable key is - /// bounded by the global pool only, never this sub-cap. The key map is bounded + /// `git_ipfs_walk_semaphore` (#174 P1-3). The key comes from `client_key`, which + /// trusts forwarded headers only from a verified proxy peer; a request with no + /// verifiable socket peer shares the reserved `UNKNOWN_PEER_KEY` bucket under this + /// sub-cap. The key map is bounded /// (`with_default_max_keys`, reject-before-insert) so a source-key farm cannot grow /// it (INV-15). pub git_ipfs_walk_per_caller: crate::rate_limit::PerCallerConcurrency, @@ -405,6 +410,24 @@ pub struct AppState { } impl AppState { + /// Resolve the rate-limit key for a request under this node's verified + /// trusted-proxy policy: the configured forwarded header only when the socket + /// peer is a configured proxy, else the socket peer, else the reserved + /// unknown-peer bucket. Single entry point so no call site can pass a trust + /// mode without its peer allowlist. + pub fn client_key( + &self, + headers: &axum::http::HeaderMap, + peer: Option, + ) -> String { + crate::rate_limit::client_key( + headers, + peer, + self.push_limiter_trust, + &self.push_limiter_trusted_peers, + ) + } + /// Subscribe to the shutdown signal. Returns a fresh receiver whose /// initial value matches the current state. pub fn subscribe_shutdown(&self) -> tokio::sync::watch::Receiver { diff --git a/crates/twigpine-node/src/test_harness.rs b/crates/twigpine-node/src/test_harness.rs index e90695afe..f61be2dc7 100644 --- a/crates/twigpine-node/src/test_harness.rs +++ b/crates/twigpine-node/src/test_harness.rs @@ -227,6 +227,7 @@ fn build_state( webhook_secret_key: Arc::new(webhook_secret_key), ipfs_max_served_object_bytes: crate::api::ipfs::MAX_SERVED_OBJECT_BYTES, push_limiter_trust: TrustedProxy::None, + push_limiter_trusted_peers: crate::rate_limit::TrustedProxyPeers::default(), sync_trigger_rate_limiter: RateLimiter::new(60, Duration::from_secs(3600)), peer_write_rate_limiter: RateLimiter::new(600, Duration::from_secs(3600)), shutdown_tx: watch::channel(false).0, diff --git a/crates/twigpine-node/src/test_support.rs b/crates/twigpine-node/src/test_support.rs index 20bd68494..378f6bb22 100644 --- a/crates/twigpine-node/src/test_support.rs +++ b/crates/twigpine-node/src/test_support.rs @@ -132,6 +132,7 @@ fn build_state(db: Arc, pool: PgPool) -> AppState { webhook_secret_key: Arc::new(webhook_secret_key), ipfs_max_served_object_bytes: crate::api::ipfs::MAX_SERVED_OBJECT_BYTES, push_limiter_trust: crate::rate_limit::TrustedProxy::None, + push_limiter_trusted_peers: crate::rate_limit::TrustedProxyPeers::default(), sync_trigger_rate_limiter: RateLimiter::new(60, Duration::from_secs(3600)), peer_write_rate_limiter: RateLimiter::new(600, Duration::from_secs(3600)), federated_rate_limiter: RateLimiter::new_bounded(12, Duration::from_secs(60), 10_000), @@ -8827,7 +8828,7 @@ mod tests { let mut state = test_state(pool).await; state.ipfs_work_rate_limiter = crate::rate_limit::RateLimiter::new(1, Duration::from_secs(3600)); - state.push_limiter_trust = crate::rate_limit::TrustedProxy::XForwardedFor; + enable_xff_test_proxy(&mut state); // One PRIVATE source, recorded cleanly: the set is non-empty, below cap and // unmarked, so nothing but the peek can keep the request off the queries. @@ -15731,7 +15732,7 @@ mod tests { let mut state = test_state(pool).await; state.ipfs_work_rate_limiter = crate::rate_limit::RateLimiter::new(1, Duration::from_secs(3600)); - state.push_limiter_trust = crate::rate_limit::TrustedProxy::XForwardedFor; + enable_xff_test_proxy(&mut state); let fx = seed_cid_repos(&slug, &short, &["provthrottle"]); let bare = std::path::PathBuf::from("/tmp") @@ -15958,7 +15959,7 @@ mod tests { // that sets the limiter by hand has to do the arithmetic itself. state.ipfs_work_rate_limiter = crate::rate_limit::RateLimiter::new(2, Duration::from_secs(3600)); - state.push_limiter_trust = crate::rate_limit::TrustedProxy::XForwardedFor; + enable_xff_test_proxy(&mut state); let fx = seed_cid_repos(&slug, &short, &["fanout"]); let bare = std::path::PathBuf::from("/tmp") @@ -16024,7 +16025,7 @@ mod tests { // `AppState::ipfs_work_budget`; only a hand-set limiter does this arithmetic. state.ipfs_work_rate_limiter = crate::rate_limit::RateLimiter::new(5, Duration::from_secs(3600)); - state.push_limiter_trust = crate::rate_limit::TrustedProxy::XForwardedFor; + enable_xff_test_proxy(&mut state); let names = ["a0", "a1", "a2", "a3"]; let _fx = seed_cid_repos(&slug, &short, &names); @@ -16088,7 +16089,7 @@ mod tests { // Budget 1, keyed on XFF so `oneshot` can choose the source IP. state.ipfs_work_rate_limiter = crate::rate_limit::RateLimiter::new(1, Duration::from_secs(3600)); - state.push_limiter_trust = crate::rate_limit::TrustedProxy::XForwardedFor; + enable_xff_test_proxy(&mut state); let _fx = seed_cid_repos(&slug, &short, &["r0"]); state @@ -16344,6 +16345,21 @@ mod tests { ); } + /// The fixed socket peer used by forwarded-header test requests. Tests opt it + /// into the trusted boundary explicitly; production behavior never trusts a + /// forwarded header merely because the header mode is configured. + fn enable_xff_test_proxy(state: &mut AppState) { + state.push_limiter_trust = crate::rate_limit::TrustedProxy::XForwardedFor; + state.push_limiter_trusted_peers = + crate::rate_limit::TrustedProxyPeers::from_env_value("10.0.0.1").unwrap(); + } + + fn insert_test_proxy_peer(req: &mut Request) { + req.extensions_mut().insert(axum::extract::ConnectInfo( + "10.0.0.1:1".parse::().unwrap(), + )); + } + fn cid_router(state: &AppState) -> Router { Router::new() .route( @@ -16385,16 +16401,18 @@ mod tests { .body(Body::empty()) .unwrap() } - /// Anonymous CID request carrying `x-forwarded-for: ` — an anon caller with a - /// resolvable source IP, so the per-IP walk brake keys on it (the walk still - /// denies anon at a path rule). + /// Anonymous CID request carrying `x-forwarded-for: ` through the fixed + /// trusted test proxy peer. The state must opt that peer in with + /// `enable_xff_test_proxy` before the forwarded value resolves as the source. fn cid_anon_xff(cid: &str, xff_ip: &str) -> Request { - Request::builder() + let mut req = Request::builder() .method(Method::GET) .uri(format!("/ipfs/{cid}")) .header("x-forwarded-for", xff_ip) .body(Body::empty()) - .unwrap() + .unwrap(); + insert_test_proxy_peer(&mut req); + req } fn cid_signed(kp: &twigpine_core::identity::Keypair, cid: &str) -> Request { let path = format!("/ipfs/{cid}"); @@ -16408,10 +16426,9 @@ mod tests { .body(Body::empty()) .unwrap() } - /// Signed CID request carrying `x-forwarded-for: `. Used by the walk - /// rate-limit test to key the per-IP limiter off a chosen source under - /// `TrustedProxy::XForwardedFor` (the request goes through `oneshot`, which - /// leaves no socket peer, so the header is the only key source). + /// Signed CID request carrying `x-forwarded-for: ` through the fixed + /// trusted test proxy peer. Used by the walk rate-limit tests to key the + /// per-IP limiter off a chosen client source under `TrustedProxy::XForwardedFor`. fn cid_signed_xff( kp: &twigpine_core::identity::Keypair, cid: &str, @@ -16419,7 +16436,7 @@ mod tests { ) -> Request { let path = format!("/ipfs/{cid}"); let s = twigpine_core::http_sig::sign_request(kp, "GET", &path, b""); - Request::builder() + let mut req = Request::builder() .method(Method::GET) .uri(&path) .header("content-digest", s.content_digest) @@ -16427,7 +16444,9 @@ mod tests { .header("signature", s.signature) .header("x-forwarded-for", xff_ip) .body(Body::empty()) - .unwrap() + .unwrap(); + insert_test_proxy_peer(&mut req); + req } /// #110: `GET /ipfs/{cid}` must gate a withheld blob by per-caller visibility. @@ -17776,7 +17795,7 @@ mod tests { // probes + pages by `AppState::ipfs_work_budget`; a hand-set limiter is not. state.ipfs_work_rate_limiter = crate::rate_limit::RateLimiter::new(3, Duration::from_secs(3600)); - state.push_limiter_trust = crate::rate_limit::TrustedProxy::XForwardedFor; + enable_xff_test_proxy(&mut state); let fx = seed_cid_repos(&slug, &short, &["walklimit"]); let bare = std::path::PathBuf::from("/tmp") @@ -17986,7 +18005,7 @@ mod tests { // `AppState::ipfs_work_budget`, so only a hand-set limiter counts this out. state.ipfs_work_rate_limiter = crate::rate_limit::RateLimiter::new(3, Duration::from_secs(3600)); - state.push_limiter_trust = crate::rate_limit::TrustedProxy::XForwardedFor; + enable_xff_test_proxy(&mut state); // Identical secret-blob content in both bare clones → one CID resolves to // `secret_oid` in each. A NEWER path-scoped denier (walk-and-deny anon) and an @@ -18270,7 +18289,7 @@ mod tests { let mut state = test_state(pool).await; state.ipfs_work_rate_limiter = crate::rate_limit::RateLimiter::new(1, Duration::from_secs(3600)); - state.push_limiter_trust = crate::rate_limit::TrustedProxy::XForwardedFor; + enable_xff_test_proxy(&mut state); let fx = seed_cid_repos(&slug, &short, &["w0", "w1"]); let bare = std::path::PathBuf::from("/tmp").join(&slug).join("w0.git"); @@ -18408,7 +18427,7 @@ mod tests { state.ipfs_rate_limiter = crate::rate_limit::RateLimiter::new(2, Duration::from_secs(3600)); state.ipfs_work_rate_limiter = crate::rate_limit::RateLimiter::new(600, Duration::from_secs(3600)); - state.push_limiter_trust = crate::rate_limit::TrustedProxy::XForwardedFor; + enable_xff_test_proxy(&mut state); // Seed a public, walk-free CID so /ipfs/{cid} serves cheaply. This // matters because the proof half of the test fires a real CID request @@ -18429,7 +18448,7 @@ mod tests { let pins_path = "/api/v1/ipfs/pins"; let pins_signed = sign_request(&kp, "GET", pins_path, b""); for i in 0..5 { - let req = Request::builder() + let mut req = Request::builder() .method(Method::GET) .uri(pins_path) .header("content-digest", &pins_signed.content_digest) @@ -18438,6 +18457,7 @@ mod tests { .header("x-forwarded-for", peer_ip) .body(Body::empty()) .unwrap(); + insert_test_proxy_peer(&mut req); let resp = router.clone().oneshot(req).await.unwrap(); assert_eq!( resp.status(), @@ -18451,7 +18471,7 @@ mod tests { // debited it, the bucket would be empty and the CID request would 429.) let cid_path = format!("/ipfs/{cid}"); let cid_signed = sign_request(&kp, "GET", &cid_path, b""); - let req = Request::builder() + let mut req = Request::builder() .method(Method::GET) .uri(&cid_path) .header("content-digest", cid_signed.content_digest) @@ -18460,6 +18480,7 @@ mod tests { .header("x-forwarded-for", peer_ip) .body(Body::empty()) .unwrap(); + insert_test_proxy_peer(&mut req); let resp = router.oneshot(req).await.unwrap(); assert_eq!( resp.status(), @@ -18489,7 +18510,7 @@ mod tests { state.ipfs_rate_limiter = crate::rate_limit::RateLimiter::new(1, Duration::from_secs(3600)); state.ipfs_work_rate_limiter = crate::rate_limit::RateLimiter::new(600, Duration::from_secs(3600)); - state.push_limiter_trust = crate::rate_limit::TrustedProxy::XForwardedFor; + enable_xff_test_proxy(&mut state); let fx = seed_cid_repos(&slug, &short, &["pinsexh"]); let bare = std::path::PathBuf::from("/tmp") @@ -18505,7 +18526,7 @@ mod tests { // First /ipfs/{cid} request — debits the single CID token, serves 200. let cid_path = format!("/ipfs/{cid}"); let cid_signed = sign_request(&kp, "GET", &cid_path, b""); - let req = Request::builder() + let mut req = Request::builder() .method(Method::GET) .uri(&cid_path) .header("content-digest", cid_signed.content_digest) @@ -18514,6 +18535,7 @@ mod tests { .header("x-forwarded-for", peer_ip) .body(Body::empty()) .unwrap(); + insert_test_proxy_peer(&mut req); let resp = router.clone().oneshot(req).await.unwrap(); assert_eq!( resp.status(), @@ -18525,7 +18547,7 @@ mod tests { // exhaustion is real and observable on this router). Re-sign because // `SignedHeaders` holds owned `String`s. let cid_signed_2 = sign_request(&kp, "GET", &cid_path, b""); - let req = Request::builder() + let mut req = Request::builder() .method(Method::GET) .uri(&cid_path) .header("content-digest", cid_signed_2.content_digest) @@ -18534,6 +18556,7 @@ mod tests { .header("x-forwarded-for", peer_ip) .body(Body::empty()) .unwrap(); + insert_test_proxy_peer(&mut req); let resp = router.clone().oneshot(req).await.unwrap(); assert_eq!( resp.status(), @@ -18545,7 +18568,7 @@ mod tests { // serve 200 — pins are auth-only and never see this bucket. let pins_path = "/api/v1/ipfs/pins"; let pins_signed = sign_request(&kp, "GET", pins_path, b""); - let req = Request::builder() + let mut req = Request::builder() .method(Method::GET) .uri(pins_path) .header("content-digest", pins_signed.content_digest) @@ -18554,6 +18577,7 @@ mod tests { .header("x-forwarded-for", peer_ip) .body(Body::empty()) .unwrap(); + insert_test_proxy_peer(&mut req); let resp = router.oneshot(req).await.unwrap(); assert_eq!( resp.status(), diff --git a/docs/RUN-A-NODE.md b/docs/RUN-A-NODE.md index 2bd6f5a87..b6acd8d91 100644 --- a/docs/RUN-A-NODE.md +++ b/docs/RUN-A-NODE.md @@ -93,6 +93,19 @@ Optional: - `TWIGPINE_HEARTBEAT_INTERVAL_HOURS=20` — how often to post heartbeats (must be < 24) - `TWIGPINE_RECONCILIATION_SWEEP=true` — enable the hourly durability sweep that re-pins/backstops missing objects (default `true`; disabled when no IPFS/Pinata backend is configured). Public pin repair runs against any configured backend. Encrypted recovery repair requires local IPFS (`TWIGPINE_IPFS_API`); Pinata-only nodes reconcile public pins only. Set `=false` to disable. +### Reverse proxy client-IP keying + +Per-IP brakes key on the socket peer unless you configure both halves of a verified proxy boundary: + +```bash +TWIGPINE_TRUSTED_PROXY=x-forwarded-for +TWIGPINE_TRUSTED_PROXY_CIDRS=10.0.0.8/32 +``` + +`TWIGPINE_TRUSTED_PROXY` selects the header (`fly` for `Fly-Client-IP`, `x-forwarded-for` for the rightmost `X-Forwarded-For` hop). `TWIGPINE_TRUSTED_PROXY_CIDRS` is a comma-separated list of exact IPv4/IPv6 addresses or CIDR ranges whose socket peers may assert that header. Exact addresses are host prefixes. Blank trusts no proxy peer, and one malformed entry invalidates the whole list, so both cases fail closed: forwarded headers are ignored. Behind a proxy without a verified peer range, clients collapse onto the proxy socket-peer bucket and the node logs a startup warning. + +Use the narrowest range you control, preferably the proxy's exact address. Do not guess broad platform ranges. Fly sets `Fly-Client-IP`, but Fly does not publish stable proxy source ranges, so a stock Fly deployment cannot provide verified per-client keying unless the operator can measure and accept a trustworthy range. Full client-IP keys also remain cheaply rotatable for a caller controlling a routed IPv6 `/64`; this boundary stops forwarded-header spoofing, not address-space rotation. + Outbound requests to URLs other people choose (peer announce and ping, bootstrap, webhook delivery, and the sync worker's git fetch of a peer) resolve each hostname and connect only when every resolved address passes the node's outbound address policy. The policy refuses loopback, private and unique-local, link-local (which covers the `169.254.169.254` cloud metadata address), carrier-grade NAT, multicast, and the documentation, benchmarking and other non-global special-purpose ranges the node lists. It is narrower than every IANA special-purpose range: an address in the well-known NAT64 prefix `64:ff9b::/96` is allowed when the IPv4 address it embeds is public. Every refused lookup is logged at `warn`. An IP-literal URL never reaches a resolver. The URL check at registration and at webhook delivery refuses loopback, private, link-local and carrier-grade NAT literals, and the sync worker and the periodic gossip ping also apply the full policy to a literal before sending anything. The manual `GET /api/v1/peers/{did}/ping` diagnostic does not apply that literal check. The node ignores `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY` for that traffic. Endpoints you configure yourself (`TWIGPINE_IPFS_API`, Pinata and Irys) are unaffected and keep working on a private or loopback hostname, on the push path and in the reconciliation sweep alike. The sync worker writes the same hardening into each peer mirror's own git config, so a later lazy fetch of a promisor mirror (for example a read of an object the peer withheld) stays pinned to the last checked addresses with proxy, redirect, credential and bundle channels off. If the peer legitimately moves to new addresses, that lazy fetch fails until the next sync refresh writes a fresh pin. diff --git a/infra/aws/compose.yaml.tftpl b/infra/aws/compose.yaml.tftpl index 0d1974cc1..26ceda4dd 100644 --- a/infra/aws/compose.yaml.tftpl +++ b/infra/aws/compose.yaml.tftpl @@ -3,6 +3,18 @@ # image instead of building, and binds data dirs to the dedicated EBS volume. # `$${VAR}` entries are resolved by docker compose from /opt/gitlawb/.env at runtime. +# A tiny benchmarking-range subnet gives Caddy a deterministic source address. +# The node trusts that exact address, and only that address, to assert XFF. +# ip_range keeps dynamic allocation (node, postgres) off Caddy's .2, which they +# would otherwise take first because Caddy starts after node is healthy. +networks: + gitlawb_internal: + driver: bridge + ipam: + config: + - subnet: 198.18.0.0/29 + ip_range: 198.18.0.4/30 + services: %{ if domain_name != "" ~} caddy: @@ -16,6 +28,9 @@ services: command: caddy reverse-proxy --from ${domain_name} --to node:${gitlawb_port} volumes: - /mnt/data/caddy:/data + networks: + gitlawb_internal: + ipv4_address: 198.18.0.2 restart: unless-stopped %{ endif ~} @@ -33,6 +48,8 @@ services: interval: 10s timeout: 5s retries: 5 + networks: + - gitlawb_internal restart: unless-stopped %{ endif ~} @@ -51,6 +68,8 @@ services: %{ endif ~} volumes: - /mnt/data/node:/data + networks: + - gitlawb_internal environment: DATABASE_URL: postgresql://${pg_user}:$${POSTGRES_PASSWORD}@${db_host != "" ? db_host : "postgres"}:5432/${pg_db} GITLAWB_HOST: 0.0.0.0 @@ -59,11 +78,12 @@ services: GITLAWB_REPOS_DIR: /data/repos GITLAWB_KEY: /data/keys/identity.pem # Only trust X-Forwarded-For when the Caddy sidecar above is actually - # deployed (domain_name != ""). Caddy appends the real client as the - # rightmost hop, letting the push rate limiter key on the true client IP - # rather than Caddy's container address. Without Caddy, this header is - # fully client-controlled and must not be trusted. + # deployed (domain_name != ""). Caddy has the fixed service-network + # address below, and the node honors the forwarded client only when the + # socket peer is that exact address. Without Caddy both settings are + # empty, so the header is fully client-controlled and ignored. GITLAWB_TRUSTED_PROXY: "${domain_name != "" ? "x-forwarded-for" : ""}" + GITLAWB_TRUSTED_PROXY_CIDRS: "${domain_name != "" ? "198.18.0.2/32" : ""}" # iCaptcha proof-of-intelligence gate (spam protection on create/fork/register) ICAPTCHA_MODE: ${icaptcha_mode} ICAPTCHA_PUBKEY: ${icaptcha_pubkey} diff --git a/infra/fly/fly.toml b/infra/fly/fly.toml index ffda6e95b..176b18e96 100644 --- a/infra/fly/fly.toml +++ b/infra/fly/fly.toml @@ -17,10 +17,14 @@ primary_region = "iad" GITLAWB_BOOTSTRAP_PEERS = "https://node.gitlawb.com,https://node2.gitlawb.com,https://node3.gitlawb.com" GITLAWB_AUTO_SYNC = "true" GITLAWB_MAX_PACK_BYTES = "524288000" - # On Fly: the edge sets Fly-Client-IP (overwriting any client-supplied value), - # so the push rate limiter keys on the real client. Without this the limiter - # would fall back to the socket peer (Fly's proxy) and over-throttle. + # Fly's edge sets Fly-Client-IP (overwriting any client-supplied value), but + # Fly does not publish stable proxy source ranges. The node verifies the socket + # peer before trusting that header, so this mode alone does not provide + # per-client keying. With the peer list empty, clients share Fly's edge socket + # bucket. Operators who can measure and accept a trustworthy range may set it + # in GITLAWB_TRUSTED_PROXY_CIDRS; do not guess a broad range. GITLAWB_TRUSTED_PROXY = "fly" + GITLAWB_TRUSTED_PROXY_CIDRS = "" [http_service] internal_port = 7545