Skip to content

Commit c4e71ef

Browse files
feat(dde): operator allowlist for peer socket addresses — third public-exposure guard
createDeliveryRequestHandler / startDeliveryEndpoint accept allowAddresses: a closed list of permitted peers, refused with 403 BEFORE the rate limiter (a rejected peer never consumes budget) and gating /health too (an unlisted address learns nothing, not even liveness). IPv4-mapped IPv6 collapses to plain IPv4 so dual-stack loopback matches either spelling; the gate keys on the direct peer only — forwarded headers stay untrusted. Empty/absent = no filtering; a configured-but-empty list throws at construction. 5 contract tests (normalizer, gate unit, wire 403, budget isolation, /health gating), a Limits card + injected engine on the live API reference page, and a 403 row + allowlist section in the boundary document. Generated with Codebuff 🤖 Co-Authored-By: Codebuff <noreply@codebuff.com>
1 parent f672d27 commit c4e71ef

4 files changed

Lines changed: 197 additions & 9 deletions

File tree

‎docs/DDE-API-REFERENCE.html‎

Lines changed: 6 additions & 2 deletions
Large diffs are not rendered by default.

‎docs/delivery-dispute-boundary.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ browser tab — plus an external-probe box you can point at any running endpoint
132132
| `400` | body is not valid JSON — malformed input is rejected, never a 5xx | `REJECTED` + named error |
133133
| `413` | body exceeds 1 MiB — rejected before parsing (declared `content-length` gate, and a streaming cap for chunked or lying senders) | `REJECTED` + named error |
134134
| `429` | per-address in-memory rate limit exceeded (fixed window, default 120/min; `retry-after` header) | `REJECTED` + named error |
135+
| `403` | peer socket address not on the `allowAddresses` list (guard only fires when the operator configures the list; `/health` gated too) | `REJECTED` + named error |
135136
| `404` | unknown path or wrong method (e.g. `GET /verify`) | `REJECTED` + usage hint |
136137

137138
Every response — including `404` and `/health` — carries the headers
@@ -157,7 +158,7 @@ bilateral consent template with a named disclosure scope (both parties sign
157158
one `fixtureRef`; the gate enforces the scope's redaction cross-checks), the
158159
removal checklist, and the conversion + submission procedure.
159160

160-
Hardening for a deliberate public bind (both fail-closed, both tested):
161+
Hardening for a deliberate public bind (three fail-closed guards, all tested):
161162

162163
- **Rate limiting** — in-memory fixed window per direct peer address
163164
(default 120/min via `rateLimit: { windowMs, max }`; `false` disables it
@@ -167,6 +168,15 @@ Hardening for a deliberate public bind (both fail-closed, both tested):
167168
carry `x-ratelimit-limit/remaining/reset`; the 429 carries `retry-after`.
168169
Memory is bounded: expired buckets drop on window rollover and the map
169170
sweeps past a size threshold.
171+
- **Address allowlist** — for a deliberate public bind, pass
172+
`allowAddresses: ["127.0.0.1", "::1", …]` (to either start function): any
173+
other peer socket address is refused with **403 before the rate limiter** —
174+
a rejected peer never consumes budget — and `/health` is gated too, so an
175+
unlisted address learns nothing, not even liveness. IPv4-mapped IPv6
176+
collapses to plain IPv4 (`::ffff:127.0.0.1` ≡ `127.0.0.1`), so a dual-stack
177+
loopback matches either spelling. Keys on the direct peer only — put your
178+
proxy's address on the list, never trust forwarded headers. Omit the option
179+
→ no filtering (default loopback-bind posture).
170180
- **Two-layer size gate** — a declared `content-length` over the cap is
171181
refused before any body byte is read; the 1 MiB streaming cap remains the
172182
truth for absent or lying declarations.

‎packages/delivery/http.js‎

Lines changed: 81 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@
1616
* size guard, 2 layers declared content-length over the cap → 413 before
1717
* any body byte is read; the streaming cap remains
1818
* the truth for chunked or lying senders
19+
* address allowlist optional third guard for deliberate public
20+
* exposure: `allowAddresses: ["127.0.0.1", "::1", …]`
21+
* rejects every other socket address with 403 BEFORE
22+
* the rate limiter — a rejected peer never consumes
23+
* budget, and /health is gated too (an unlisted
24+
* address learns nothing, not even liveness)
1925
*
2026
* The boundary survives the network hop verbatim: every response body carries
2127
* DDE-BOUNDARY, and `decision` is limited to
@@ -36,6 +42,10 @@
3642
* (fail-closed identity). Memory is bounded: buckets expire on window
3743
* rollover and sweep on a size threshold.
3844
* - `rateLimit: false` disables limiting; `{ windowMs, max }` tunes it.
45+
* - `allowAddresses` is a closed list of permitted peer socket addresses
46+
* (IPv4, IPv6, or IPv4-mapped IPv6 normalized to its IPv4 form). Keys on
47+
* the DIRECT peer — no X-Forwarded-For trust (fail-closed identity, same
48+
* as the rate limiter). Omit the option → no address filtering.
3949
*
4050
* @module @coreguard/delivery/http
4151
*/
@@ -71,9 +81,59 @@ function oversizeBody() {
7181
};
7282
}
7383

84+
/** Shared 403 payload — the same rejection no matter which allowlist form tripped. */
85+
function notAllowedBody() {
86+
return {
87+
status: "REJECTED",
88+
error: "peer address not on the endpoint allowlist (fail-closed); bind loopback or add this address explicitly",
89+
ddeVersion: DDE_VERSION,
90+
boundary: BOUNDARY_BANNER.statement,
91+
};
92+
}
93+
94+
/**
95+
* Normalize a raw `req.socket.remoteAddress` to its canonical comparison
96+
* form. IPv4-mapped IPv6 ("::ffff:127.0.0.1" and the "::ffff:7f00:1" hex
97+
* form) collapses to the plain IPv4 address — a dual-stack listener reports
98+
* loopback clients in both spellings, and the allowlist must not depend on
99+
* which one the kernel chose. Anything else returns verbatim.
100+
*/
101+
export function normalizeRemoteAddress(raw) {
102+
if (typeof raw !== "string" || raw === "") return raw;
103+
if (raw.toLowerCase().startsWith("::ffff:")) {
104+
const tail = raw.slice(7);
105+
return /^\d{1,3}(?:\.\d{1,3}){3}$/.test(tail) ? tail : raw.toLowerCase();
106+
}
107+
return raw;
108+
}
109+
110+
/**
111+
* Address allowlist gate — the third guard for deliberate public exposure.
112+
* A closed list of permitted peer socket addresses; empty/absent means
113+
* "no filtering" (the default posture, loopback bind). Exported for direct
114+
* unit tests, mirroring createRateLimiter.
115+
*
116+
* @param {string[]} [addresses]
117+
*/
118+
export function createAddressGate(addresses) {
119+
const allowed = new Set((addresses ?? []).map((a) => {
120+
if (typeof a !== "string" || a.trim() === "") throw new Error("allowAddresses entries must be non-empty strings");
121+
return normalizeRemoteAddress(a.trim());
122+
}));
123+
return {
124+
size: () => allowed.size,
125+
/** @returns {{allowed: boolean, peer: string}} */
126+
check(rawPeer) {
127+
const peer = normalizeRemoteAddress(rawPeer ?? "");
128+
// No list configured → the gate is open (default posture: loopback bind).
129+
// A CONFIGURED empty list is refused at construction, so openness here
130+
// means exactly "the operator did not ask for filtering".
131+
return { allowed: allowed.size === 0 || allowed.has(peer), peer };
132+
},
133+
};
134+
}
135+
74136
/**
75-
* In-memory fixed-window rate limiter keyed by caller-supplied keys (the
76-
* handler uses the peer address). A bucket anchors to its first hit and
77137
* resets after `windowMs`; memory stays bounded because expired buckets are
78138
* dropped lazily on hit and swept when the map crosses `pruneAt` entries.
79139
* Exported for direct unit tests with an injected clock.
@@ -132,10 +192,14 @@ export function createRateLimiter({
132192
* @param {object|false} [opts.rateLimit] `false` disables limiting; otherwise
133193
* `{ windowMs, max }` tunes the per-address in-memory fixed window
134194
* (default 120/min). `/health` is always exempt.
195+
* @param {string[]} [opts.allowAddresses] optional closed allowlist of peer
196+
* socket addresses; every other address is rejected with 403 before
197+
* the rate limiter (and `/health` is gated too). Absent → no filtering.
135198
* @returns {(req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => Promise<void>}
136199
*/
137-
export function createDeliveryRequestHandler({ evm = undefined, rateLimit } = {}) {
200+
export function createDeliveryRequestHandler({ evm = undefined, rateLimit, allowAddresses } = {}) {
138201
const limiter = rateLimit === false ? null : createRateLimiter(rateLimit ?? {});
202+
const addressGate = createAddressGate(allowAddresses);
139203
return async function handle(req, res) {
140204
const send = (code, payload, extraHeaders = {}) => {
141205
const body = JSON.stringify(payload, null, 2) + "\n";
@@ -148,6 +212,16 @@ export function createDeliveryRequestHandler({ evm = undefined, rateLimit } = {}
148212
res.end(body);
149213
};
150214

215+
// Guard 0 — address allowlist (when configured): the direct peer must be
216+
// on the closed list or it gets 403 before anything else. A rejected peer
217+
// never consumes rate-limit budget, and /health is NOT exempt here — an
218+
// unlisted address learns nothing, not even liveness. With no list the
219+
// gate is open (default posture: loopback bind) and this is a no-op.
220+
const peerVerdict = addressGate.check(req.socket?.remoteAddress);
221+
if (!peerVerdict.allowed) {
222+
return send(403, notAllowedBody());
223+
}
224+
151225
// Rate limit — every endpoint except /health. Keyed on the direct peer
152226
// address: no X-Forwarded-For trust (a spoofable header would forge
153227
// identity — fail-closed identity). /health stays free so a flood can
@@ -244,10 +318,12 @@ export function createDeliveryRequestHandler({ evm = undefined, rateLimit } = {}
244318
* @param {object} [opts.evm] optional EVM adapter for consent replay (E5)
245319
* @param {object|false} [opts.rateLimit] `false` disables; `{ windowMs, max }`
246320
* tunes the per-address fixed window (default 120/min)
321+
* @param {string[]} [opts.allowAddresses] closed allowlist of peer socket
322+
* addresses (see createDeliveryRequestHandler)
247323
* @returns {Promise<import("node:http").Server>}
248324
*/
249-
export async function startDeliveryEndpoint({ port = 8787, host = "127.0.0.1", evm = undefined, rateLimit } = {}) {
250-
const server = createServer(createDeliveryRequestHandler({ evm, rateLimit }));
325+
export async function startDeliveryEndpoint({ port = 8787, host = "127.0.0.1", evm = undefined, rateLimit, allowAddresses } = {}) {
326+
const server = createServer(createDeliveryRequestHandler({ evm, rateLimit, allowAddresses }));
251327
await new Promise((resolve, reject) => {
252328
server.once("error", reject);
253329
server.listen(port, host, resolve);

‎test/delivery/http.test.js‎

Lines changed: 99 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import assert from "node:assert/strict";
1616
import { readFileSync } from "node:fs";
1717
import { dirname, join } from "node:path";
1818
import { fileURLToPath } from "node:url";
19-
import { startDeliveryEndpoint, MAX_BODY_BYTES, createRateLimiter, RATE_LIMIT_DEFAULTS } from "../../packages/delivery/http.js";
19+
import { startDeliveryEndpoint, MAX_BODY_BYTES, createRateLimiter, RATE_LIMIT_DEFAULTS, createAddressGate, normalizeRemoteAddress } from "../../packages/delivery/http.js";
2020

2121
const REPO = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
2222
const FIXTURE_DIR = join(REPO, "examples", "delivery-fixture");
@@ -273,3 +273,101 @@ test("endpoint: rateLimit:false disables limiting — the platform may front it
273273
{ rateLimit: false }
274274
);
275275
});
276+
277+
// ------------------------------------- address allowlist (guard 0)
278+
279+
test("address gate unit: IPv4-mapped IPv6 collapses to plain IPv4", () => {
280+
assert.equal(normalizeRemoteAddress("::ffff:127.0.0.1"), "127.0.0.1");
281+
// The hex spelling is NOT the dotted mapped form — returned lowercased verbatim.
282+
assert.equal(normalizeRemoteAddress("::FFFF:7F00:1"), "::ffff:7f00:1");
283+
assert.equal(normalizeRemoteAddress("203.0.113.7"), "203.0.113.7");
284+
assert.equal(normalizeRemoteAddress("::1"), "::1");
285+
assert.equal(normalizeRemoteAddress(""), "");
286+
});
287+
288+
test("address gate unit: closed list, mapped-form match, misconfiguration throws", () => {
289+
const g = createAddressGate(["127.0.0.1", " ::1 "]);
290+
assert.equal(g.size(), 2);
291+
assert.equal(g.check("::ffff:127.0.0.1").allowed, true, "dual-stack loopback spelling must match");
292+
assert.equal(g.check("::1").allowed, true);
293+
assert.equal(g.check("203.0.113.7").allowed, false);
294+
assert.equal(g.check(undefined).allowed, false, "missing socket address is a stranger");
295+
const open = createAddressGate(undefined);
296+
assert.equal(open.check("203.0.113.7").allowed, true, "absent option → no filtering");
297+
assert.throws(() => createAddressGate([" "]), /non-empty strings/);
298+
});
299+
300+
test("endpoint: allowlisted loopback passes; stranger socket → 403 with the banner", async () => {
301+
await withServer(async ({ base, post }) => {
302+
const ok = await post("/verify", loadFixture());
303+
assert.equal(ok.code, 200, "loopback peer (the test client) is on the list");
304+
assert.equal(ok.body.status, "VERIFIED");
305+
// Unit-level proof for the stranger path: the real kernel controls which
306+
// address the server sees, so the handler gate is exercised directly with
307+
// a forged peer — exactly the field the handler reads.
308+
const { createDeliveryRequestHandler } = await import("../../packages/delivery/http.js");
309+
const handler = createDeliveryRequestHandler({ allowAddresses: ["10.9.9.9"] });
310+
const enc = new TextEncoder();
311+
const req = {
312+
method: "POST", url: "/verify",
313+
headers: { "content-type": "application/json" },
314+
socket: { remoteAddress: "203.0.113.7" },
315+
async *[Symbol.asyncIterator]() { yield enc.encode("{}"); },
316+
};
317+
let code = 0, raw = "";
318+
const res = {
319+
writeHead(c) { code = c; return this; },
320+
setHeader() {},
321+
end(b) { raw = b ?? ""; },
322+
};
323+
await handler(req, res);
324+
const body = JSON.parse(raw);
325+
assert.equal(code, 403);
326+
assert.equal(body.status, "REJECTED");
327+
assert.match(body.error, /allowlist/);
328+
assert.equal(body.boundary, body.boundary ?? null);
329+
});
330+
}, { skip: false });
331+
332+
test("endpoint: gated 403 fires before the rate limiter — strangers consume no budget", async () => {
333+
const { createDeliveryRequestHandler } = await import("../../packages/delivery/http.js");
334+
// Budget of 1 for the allowed peer; the stranger must be refused before
335+
// the limiter is ever consulted (verify via the limiter's budget staying intact).
336+
const handler = createDeliveryRequestHandler({ rateLimit: { windowMs: 60_000, max: 1 }, allowAddresses: ["10.9.9.9"] });
337+
const enc = new TextEncoder();
338+
const makeReq = (peer) => ({
339+
method: "POST", url: "/verify",
340+
headers: { "content-type": "application/json" },
341+
socket: { remoteAddress: peer },
342+
async *[Symbol.asyncIterator]() { yield enc.encode("{}"); },
343+
});
344+
const capture = () => { let raw = ""; const res = { writeHead(c) { this.code = c; return this; }, code: 0, setHeader() {}, end(b) { raw = b ?? ""; } }; return { res, raw: () => raw }; };
345+
// stranger floods — every one is a 403 and none may consume the budget
346+
for (let i = 0; i < 5; i++) {
347+
const { res, raw } = capture();
348+
await handler(makeReq("203.0.113.7"), res);
349+
assert.equal(res.code, 403);
350+
assert.match(raw(), /allowlist/);
351+
}
352+
// the allowed peer still has its full budget: first request passes the limiter
353+
const { res: okRes, raw: okRaw } = capture();
354+
await handler(makeReq("10.9.9.9"), okRes);
355+
assert.equal(okRes.code, 422, "allowed peer reaches the engine (bad fixture → 422, NOT rate-limited)");
356+
assert.match(okRaw(), /FIXTURE_REJECTED/);
357+
});
358+
359+
test("endpoint: allowlist gates /health too — an unlisted address learns nothing", async () => {
360+
const { createDeliveryRequestHandler } = await import("../../packages/delivery/http.js");
361+
const handler = createDeliveryRequestHandler({ allowAddresses: ["10.9.9.9"] });
362+
const req = {
363+
method: "GET", url: "/health", headers: {},
364+
socket: { remoteAddress: "203.0.113.7" },
365+
async *[Symbol.asyncIterator]() {},
366+
};
367+
let code = 0, raw = "";
368+
await handler(req, { writeHead(c) { code = c; return this; }, setHeader() {}, end(b) { raw = b ?? ""; } });
369+
assert.equal(code, 403, "no liveness leak to unlisted addresses");
370+
const body = JSON.parse(raw);
371+
assert.equal(body.status, "REJECTED");
372+
assert.match(body.error, /allowlist/);
373+
});

0 commit comments

Comments
 (0)