Skip to content

Commit b95e406

Browse files
feat(delivery): optional trustedForwarders — proxy-pinned XFF classification (Class A/B labels), zero-trust default untouched, signed by contract
trustedForwarders: [addresses] arms a client-class gate that LABELS forwarded-client claims on every response via x-dde-client-class: forwarder-claimed (a listed proxy vouches for the XFF claim; every guard still keys on the proxy's socket), forwarder-no-xff, self-claimed (an unlisted peer's header — an unverified client claim), or direct. The default posture is unchanged and contract-proven to stay unchanged: with no list configured the XFF header is never read, never parsed, and no class header is emitted; a 403'd stranger is refused before classification; allowlist, rate buckets, and the boundary read the direct peer alone in EVERY configuration. createClientClassGate normalizes peers exactly like the allowlist (mapped-v6 collapse), is exported for unit tests, and the doc gains the option, the classification arm of the proxy posture, and a wire-proven start line (doc-curl pin 7->8). 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
1 parent 7b89eb2 commit b95e406

5 files changed

Lines changed: 246 additions & 14 deletions

File tree

‎docs/DDE-API-REFERENCE.html‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎docs/delivery-dispute-boundary.md‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,24 @@ Hardening for a deliberate public bind (three fail-closed guards, all tested):
194194
- **Two-layer size gate** — a declared `content-length` over the cap is
195195
refused before any body byte is read; the 1 MiB streaming cap remains the
196196
truth for absent or lying declarations.
197+
- **Trusted-forwarder classification (OPTIONAL, off by default)** —
198+
`trustedForwarders: ["127.0.0.1", …]` names the proxies whose
199+
`X-Forwarded-For` claims may be CLASSIFIED. With a list configured, every
200+
response carries `x-dde-client-class`: `forwarder-claimed` (the peer IS a
201+
listed forwarder and it supplied an XFF claim — the proxy vouches; the wire
202+
identity every guard keys on is still the proxy), `forwarder-no-xff`
203+
(listed forwarder, no claim), `self-claimed` (an unlisted peer sent an XFF
204+
header — an unverified client-supplied claim, exactly the forged-header
205+
posture the default rejects trusting), or `direct` (no forwarder
206+
infrastructure; the peer address is the client identity). The classes are
207+
an observability and policy-adjacent surface: allowlist and rate-limit
208+
decisions still key on the direct peer alone in every configuration.
209+
Absent or empty → the header is never read at all: the zero-trust default
210+
is the default, not a mode you fall out of by omission.
211+
- **Forwarded-header rule (unchanged)** — forwarded headers are LOGGING data
212+
and, with `trustedForwarders` configured, CLASSIFICATION input — never
213+
identity. No configuration makes a header open the allowlist, alter the
214+
rate bucket, or replace the socket peer in any decision.
197215

198216
### Wire-level integration — a copy-ready payout gate
199217

@@ -329,6 +347,22 @@ default of 1m); adapt names to your proxy if it is not nginx.
329347
private network, list the proxy hosts' addresses. (They all share one
330348
verdict: the proxy is the front door by design.)
331349
350+
3b. **OPTIONAL: classify forwarded-client claims with `trustedForwarders`.**
351+
Passing the same proxy addresses to `trustedForwarders` arms the
352+
client-class gate WITHOUT moving any decision off the socket: responses
353+
then carry `x-dde-client-class` — `forwarder-claimed` when the proxy (a
354+
listed forwarder) supplied an `X-Forwarded-For` claim (the proxy vouches;
355+
every guard still keys on the proxy's socket), `forwarder-no-xff`,
356+
`self-claimed` when an UNLISTED peer sends the header (an unverified
357+
client-supplied claim — exactly what the zero-trust default refuses to
358+
trust), or `direct`. The classes feed YOUR logging, metrics, or
359+
downstream policy — the allowlist, the rate buckets, and the boundary
360+
never read the header. Leave the option off and nothing changes at all:
361+
the header is not even parsed. (A listed forwarder on a private network
362+
is the only posture where this mode says anything; on loopback with a
363+
same-host proxy it distinguishes proxied traffic from direct
364+
probes — useful, still zero-decision.)
365+
332366
4. **The in-process rate limiter becomes a backstop, not the primary limiter.**
333367
Size it above the proxy's per-client ceiling (e.g. `rateLimit: {
334368
windowMs: 60_000, max: 600 }` for a 10 r/s edge limit) so it only fires on
@@ -347,6 +381,7 @@ default of 1m); adapt names to your proxy if it is not nginx.
347381
| `host` | `127.0.0.1` | `127.0.0.1` (proxy on same host) or a private interface — never `0.0.0.0` |
348382
| `rateLimit` | `120/min` per real client | backstop per proxy, sized **above** the proxy's per-client ceiling (e.g. 600/min); primary limiting at the edge |
349383
| `allowAddresses` | omit — the loopback bind *is* the guard | pin the proxy's source address(es) — containment for a misexposed port |
384+
| `trustedForwarders` | omit — XFF is never read (zero-trust default) | optionally the proxy's address(es) — adds `x-dde-client-class` labels (`forwarder-claimed` / `self-claimed` / `direct`); no decision ever reads the header |
350385
| body cap | 1 MiB (two layers) | 1 MiB, with the edge cap ≤ 1 MiB so oversize dies at the proxy |
351386
| TLS | out of scope (loopback) | terminated at the proxy; the app speaks plain HTTP over loopback/private net |
352387
@@ -362,7 +397,16 @@ The limiter keys on the proxy (the direct peer), so its `x-ratelimit-*`
362397
headers read as the backstop budget — `x-ratelimit-limit: 600` on every
363398
response is the proof the posture took. Per-client limiting lives at the
364399
edge (`limit_req`), the app ignores forwarded headers by contract, and the
365-
allowlist is the containment layer for a misexposed port.
400+
allowlist is the containment layer for a misexposed port. Add the same
401+
address to `trustedForwarders` to additionally label every response with
402+
`x-dde-client-class` (`forwarder-claimed` / `forwarder-no-xff` /
403+
`self-claimed` / `direct`) — classification for your ops, never identity
404+
for the guards.
405+
406+
```bash
407+
# the optional classification arm of the same posture (adds the header only):
408+
node --input-type=module -e "import { startDeliveryEndpoint } from './packages/delivery/http.js'; const server = await startDeliveryEndpoint({ port: 8787, allowAddresses: ['127.0.0.1'], trustedForwarders: ['127.0.0.1'], rateLimit: { windowMs: 60000, max: 600 } }); console.log('DDE endpoint (proxy posture, client-class labels on) on :8787 —', server.address());"
409+
```
366410
367411
**Backups and recovery.** The endpoint is stateless by design: no database, no
368412
persisted fixtures, rate-limit state is per-process memory. There is nothing

‎packages/delivery/http.js‎

Lines changed: 66 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,48 @@ export function createAddressGate(addresses) {
139139
};
140140
}
141141

142+
/**
143+
* Client-class gate for the OPTIONAL trusted-forwarder mode (proxy-pinned
144+
* X-Forwarded-For classification). Only meaningful when the operator hands
145+
* the endpoint a list of trusted forwarder addresses; it labels every
146+
* request with a CLASS, never decides by itself:
147+
* A — the direct peer IS a trusted forwarder: the client-ish XFF claim is
148+
* labeled ("forwarder-claimed"), i.e. the proxy VOUCHES, but the wire
149+
* identity that every guard keys on remains the proxy.
150+
* B — direct peer is NOT a forwarder: any XFF header is an unverified
151+
* CLIENT-supplied claim, labeled "self-claimed".
152+
* direct — no forwarder infrastructure: no XFF header may be present
153+
* (present+direct = a forged-header attempt), and the peer address is
154+
* the client identity itself.
155+
* The DEFAULT posture is and stays zero-trust: with no list configured the
156+
* gate is inert, no header is ever read for any decision, and nothing is
157+
* labeled. Exported for direct unit tests with injectable headers.
158+
*/
159+
export function createClientClassGate(trustedForwarders) {
160+
const trusted = new Set((trustedForwarders ?? []).map((a) => {
161+
if (typeof a !== "string" || a.trim() === "") throw new Error("trustedForwarders entries must be non-empty strings");
162+
return normalizeRemoteAddress(a.trim());
163+
}));
164+
if (trusted.size === 0) return { enabled: false, classify: () => null };
165+
return {
166+
enabled: true,
167+
/** @returns {{clientClass: string, clientClaim: string|null}} */
168+
classify(headers, rawPeer) {
169+
// Same normalization the allowlist gate applies — a dual-stack listener
170+
// reporting "::ffff:10.9.9.9" must classify as the listed IPv4 form.
171+
const peer = normalizeRemoteAddress(rawPeer ?? "");
172+
const xff = headers?.["x-forwarded-for"];
173+
const claim = typeof xff === "string" && xff.trim() !== "" ? xff.trim() : null;
174+
if (trusted.has(peer)) {
175+
if (claim === null) return { clientClass: "forwarder-no-xff", clientClaim: null };
176+
return { clientClass: "forwarder-claimed", clientClaim: claim };
177+
}
178+
if (claim !== null) return { clientClass: "self-claimed", clientClaim: claim };
179+
return { clientClass: "direct", clientClaim: null };
180+
},
181+
};
182+
}
183+
142184
/**
143185
* resets after `windowMs`; memory stays bounded because expired buckets are
144186
* dropped lazily on hit and swept when the map crosses `pruneAt` entries.
@@ -201,11 +243,16 @@ export function createRateLimiter({
201243
* @param {string[]} [opts.allowAddresses] optional closed allowlist of peer
202244
* socket addresses; every other address is rejected with 403 before
203245
* the rate limiter (and `/health` is gated too). Absent → no filtering.
246+
* @param {string[]} [opts.trustedForwarders] OPTIONAL list of proxy/forwarder
247+
* socket addresses whose X-Forwarded-For claims may be classified
248+
* (never silently trusted). Absent/empty → the header is never read:
249+
* the zero-trust default is untouched. See createClientClassGate.
204250
* @returns {(req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => Promise<void>}
205251
*/
206-
export function createDeliveryRequestHandler({ evm = undefined, rateLimit, allowAddresses } = {}) {
252+
export function createDeliveryRequestHandler({ evm = undefined, rateLimit, allowAddresses, trustedForwarders } = {}) {
207253
const limiter = rateLimit === false ? null : createRateLimiter(rateLimit ?? {});
208254
const addressGate = createAddressGate(allowAddresses);
255+
const clientClassGate = createClientClassGate(trustedForwarders);
209256
return async function handle(req, res) {
210257
const send = (code, payload, extraHeaders = {}) => {
211258
const body = JSON.stringify(payload, null, 2) + "\n";
@@ -228,6 +275,19 @@ export function createDeliveryRequestHandler({ evm = undefined, rateLimit, allow
228275
return send(403, notAllowedBody());
229276
}
230277

278+
// OPTIONAL trusted-forwarder classification (proxy-pinned XFF). Only when
279+
// the operator passed `trustedForwarders` does the XFF header get READ at
280+
// all — and even then it is labeled, never trusted: Class A means the
281+
// proxy (a pinned forwarder) vouches for the client-ish claim, and the
282+
// wire identity every guard keys on remains the proxy; Class B marks a
283+
// client-supplied XFF as an unverified self-claim. The default posture
284+
// never reads the header (zero-trust, unchanged). The classification is
285+
// surfaced for ops via `x-dde-client-class` on responses.
286+
const ccGate = clientClassGate.classify(req.headers, peerVerdict.peer);
287+
if (ccGate !== null) {
288+
res.setHeader("x-dde-client-class", ccGate.clientClass);
289+
}
290+
231291
// Rate limit — every endpoint except /health. Keyed on the direct peer
232292
// address: no X-Forwarded-For trust (a spoofable header would forge
233293
// identity — fail-closed identity). /health stays free so a flood can
@@ -329,10 +389,13 @@ export function createDeliveryRequestHandler({ evm = undefined, rateLimit, allow
329389
* tunes the per-address fixed window (default 120/min)
330390
* @param {string[]} [opts.allowAddresses] closed allowlist of peer socket
331391
* addresses (see createDeliveryRequestHandler)
392+
* @param {string[]} [opts.trustedForwarders] OPTIONAL proxy-pinned forwarder
393+
* addresses (see createDeliveryRequestHandler / createClientClassGate).
394+
* Absent → zero-trust default: XFF is never read for anything.
332395
* @returns {Promise<import("node:http").Server>}
333396
*/
334-
export async function startDeliveryEndpoint({ port = 8787, host = "127.0.0.1", evm = undefined, rateLimit, allowAddresses } = {}) {
335-
const server = createServer(createDeliveryRequestHandler({ evm, rateLimit, allowAddresses }));
397+
export async function startDeliveryEndpoint({ port = 8787, host = "127.0.0.1", evm = undefined, rateLimit, allowAddresses, trustedForwarders } = {}) {
398+
const server = createServer(createDeliveryRequestHandler({ evm, rateLimit, allowAddresses, trustedForwarders }));
336399
await new Promise((resolve, reject) => {
337400
server.once("error", reject);
338401
server.listen(port, host, resolve);

‎test/delivery/doc-curl-contract.test.js‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -467,16 +467,16 @@ test("doc curl examples execute against a live documented endpoint and match the
467467
(n, f) => n + logicalCommands(f).filter((c) => c.includes("startDeliveryEndpoint") && !c.trimStart().startsWith("#")).length,
468468
0,
469469
);
470-
// [C25]+[C32] exactness: the pin is the MEASURED set (7 start lines:
471-
// delivery-dispute-boundary ×3, examples README, README, INTEGRATION,
472-
// agent-incident-evidence — the hardening line joined the count only after
473-
// the comment-inert tokenizer fix made it visible). A line LOST fails here
474-
// by name; a line ADDED must update this pin in the same commit AND
475-
// inherit the per-line proof above — which is the point: a start line
476-
// never ships unproven again, in either direction.
470+
// [C25]+[C32] exactness: the pin is the MEASURED set (8 start lines:
471+
// delivery-dispute-boundary ×4 — base, hardening, production, and the
472+
// optional trustedForwarders classification arm — examples README, README,
473+
// INTEGRATION, agent-incident-evidence). A line LOST fails here by name;
474+
// a line ADDED must update this pin in the same commit AND inherit the
475+
// per-line proof above — which is the point: a start line never ships
476+
// unproven again, in either direction.
477477
assert.equal(
478-
totalStartCmds, 7,
479-
`documented start-line set moved: found ${totalStartCmds}, pin is 7 — a line was lost (restore/prove it) or added (update the pin in the same commit and confirm the per-line proof above ran for it)`,
478+
totalStartCmds, 8,
479+
`documented start-line set moved: found ${totalStartCmds}, pin is 8 — a line was lost (restore/prove it) or added (update the pin in the same commit and confirm the per-line proof above ran for it)`,
480480
);
481481
assert.equal(
482482
provenStarts.length, totalStartCmds,

0 commit comments

Comments
 (0)