diff --git a/src/keyless/http-sig.test.ts b/src/keyless/http-sig.test.ts new file mode 100644 index 00000000..da58f3db --- /dev/null +++ b/src/keyless/http-sig.test.ts @@ -0,0 +1,209 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { generateKeyPairSync, sign as edSign, verify as edVerify } from "node:crypto"; +import { + signatureBase, + signatureParamsValue, + signRequest, + verifyRequest, + componentValue, + DEFAULT_COMPONENTS, + type SignableRequest, + type SignatureParams, +} from "./http-sig.js"; + +// Ephemeral Ed25519 keypair — mirrors how identity.ts signs (crypto.sign(null,…)). +const { publicKey, privateKey } = generateKeyPairSync("ed25519"); +const PUB_PEM = publicKey.export({ type: "spki", format: "pem" }).toString(); +const KID = "kid_test0000"; + +const sign = (data: Buffer): Buffer => edSign(null, data, privateKey); +const verify = (data: Buffer, sig: Buffer, pubPem: string): boolean => { + try { + return edVerify(null, data, pubPem, sig); + } catch { + return false; + } +}; +const resolvePub = (kid: string): string | undefined => (kid === KID ? PUB_PEM : undefined); + +const REQ: SignableRequest = { + method: "post", + url: "https://api.acme.com/v1/charge?amount=100", + headers: { "content-type": "application/json" }, +}; + +const baseParams = (over: Partial = {}): SignatureParams => ({ + keyid: KID, + created: 1_000_000, + ...over, +}); + +describe("keyless RFC 9421 — component derivation", () => { + it("derives @method uppercased, @authority lowercased, @path, @query with leading ?", () => { + assert.equal(componentValue("@method", REQ), "POST"); + assert.equal(componentValue("@authority", REQ), "api.acme.com"); + assert.equal(componentValue("@path", REQ), "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/v1/charge"); + assert.equal(componentValue("@query", REQ), "?amount=100"); + assert.equal(componentValue("@scheme", REQ), "https"); + }); + + it("uses '?' for @query when there is no query string", () => { + assert.equal(componentValue("@query", { method: "GET", url: "https://x.io/a" }), "?"); + }); + + it("resolves a header component case-insensitively and trims OWS", () => { + const r: SignableRequest = { + method: "GET", + url: "https://x.io/", + headers: { "X-Foo": " bar " }, + }; + assert.equal(componentValue("x-foo", r), "bar"); + }); + + it("throws for a covered header that is not present (fail-closed at sign time)", () => { + assert.throws(() => componentValue("x-missing", REQ), /covered header not present/); + }); +}); + +describe("keyless RFC 9421 — signature base", () => { + it("emits one line per component then the @signature-params line last", () => { + const params = baseParams({ + components: ["@method", "@authority", "@path"], + expires: 1_000_060, + }); + const base = signatureBase(REQ, params); + assert.equal( + base, + [ + `"@method": POST`, + `"@authority": api.acme.com`, + `"@path": /v1/charge`, + `"@signature-params": ("@method" "@authority" "@path");created=1000000;keyid="${KID}";alg="ed25519";expires=1000060`, + ].join("\n"), + ); + }); + + it("serializes params in a deterministic order", () => { + const v = signatureParamsValue(baseParams({ expires: 5, nonce: "n1" })); + assert.equal( + v, + `("@method" "@authority" "@path");created=1000000;keyid="${KID}";alg="ed25519";expires=5;nonce="n1"`, + ); + }); + + it("rejects a parameterized or unknown derived component", () => { + assert.throws( + () => signatureParamsValue(baseParams({ components: ["@query-param;name=q"] })), + /not supported/, + ); + assert.throws( + () => signatureParamsValue(baseParams({ components: ["@bogus"] })), + /unsupported covered component/, + ); + }); +}); + +describe("keyless RFC 9421 — sign + verify round-trip", () => { + it("a freshly signed request verifies", () => { + const params = baseParams({ expires: 1_000_060 }); + const headers = signRequest(REQ, params, sign); + const r = verifyRequest( + REQ, + { signatureInput: headers["Signature-Input"], signature: headers.Signature }, + resolvePub, + verify, + { now: 1_000_010 }, + ); + assert.equal(r.valid, true, r.detail); + assert.equal(r.keyid, KID); + }); + + it("emits the expected header shapes", () => { + const headers = signRequest(REQ, baseParams(), sign); + assert.match(headers["Signature-Input"], /^sig1=\("@method" "@authority" "@path"\);created=/); + assert.match(headers.Signature, /^sig1=:[A-Za-z0-9+/=]+:$/); + }); +}); + +describe("keyless RFC 9421 — fail-closed", () => { + const signed = () => signRequest(REQ, baseParams({ expires: 1_000_060 }), sign); + const hdr = (h: ReturnType) => ({ + signatureInput: h["Signature-Input"], + signature: h.Signature, + }); + + it("rejects when the method is tampered", () => { + const r = verifyRequest({ ...REQ, method: "GET" }, hdr(signed()), resolvePub, verify, { + now: 1_000_010, + }); + assert.equal(r.valid, false); + assert.match(r.detail, /does not verify/); + }); + + it("rejects when the path is tampered", () => { + const r = verifyRequest( + { ...REQ, url: "https://api.acme.com/v1/refund?amount=100" }, + hdr(signed()), + resolvePub, + verify, + { now: 1_000_010 }, + ); + assert.equal(r.valid, false); + }); + + it("rejects an expired signature", () => { + const r = verifyRequest(REQ, hdr(signed()), resolvePub, verify, { now: 1_000_061 }); + assert.equal(r.valid, false); + assert.match(r.detail, /expired/); + }); + + it("rejects an unresolvable keyid", () => { + const r = verifyRequest(REQ, hdr(signed()), () => undefined, verify, { now: 1_000_010 }); + assert.equal(r.valid, false); + assert.match(r.detail, /unknown keyid/); + }); + + it("rejects when a required component was not covered", () => { + const r = verifyRequest(REQ, hdr(signed()), resolvePub, verify, { + now: 1_000_010, + required: ["content-type"], + }); + assert.equal(r.valid, false); + assert.match(r.detail, /required component not covered/); + }); + + it("verifies when the required component IS covered", () => { + const headers = signRequest( + REQ, + baseParams({ components: [...DEFAULT_COMPONENTS, "content-type"], expires: 1_000_060 }), + sign, + ); + const r = verifyRequest(REQ, hdr(headers), resolvePub, verify, { + now: 1_000_010, + required: ["content-type"], + }); + assert.equal(r.valid, true, r.detail); + }); + + it("rejects malformed headers", () => { + assert.equal( + verifyRequest(REQ, { signatureInput: "garbage", signature: "sig1=::" }, resolvePub, verify) + .valid, + false, + ); + }); + + it("rejects a Signature/Signature-Input label mismatch", () => { + const h = signed(); + const r = verifyRequest( + REQ, + { signatureInput: h["Signature-Input"], signature: h.Signature.replace("sig1=", "other=") }, + resolvePub, + verify, + { now: 1_000_010 }, + ); + assert.equal(r.valid, false); + assert.match(r.detail, /label mismatch/); + }); +}); diff --git a/src/keyless/http-sig.ts b/src/keyless/http-sig.ts new file mode 100644 index 00000000..22cf74b2 --- /dev/null +++ b/src/keyless/http-sig.ts @@ -0,0 +1,311 @@ +/** + * kit keyless credentials (Pillar 2 tail) — RFC 9421 HTTP Message Signatures. + * + * "Sign, don't store": instead of carrying a long-lived bearer token, an agent + * signs each outbound request with its Ed25519 identity (Pillar 1). The server + * verifies against the agent's PUBLIC key — there is no secret at rest to steal, + * rotate, or redact. This module is the pure, deterministic core that builds the + * RFC 9421 signature base and assembles / checks the `Signature-Input` + + * `Signature` headers. + * + * Deliberately pure: NO filesystem, NO network, NO identity import, NO model + * calls. Signing/verifying take injected callbacks (`sign` / `resolvePub`) so the + * same primitive is used by the broker (with `signWithIdentity`) and by tests + * (with an ephemeral keypair). Byte-for-byte stable across machines so a + * signature produced on one host verifies offline on another. + * + * Fail-CLOSED throughout: a missing covered component, an unresolvable keyid, an + * expired signature, or a base that does not verify all return "not valid" — the + * caller must treat anything but `valid: true` as no proof of identity. + * + * Scope of this v1: the derived components `@method`, `@authority`, `@path`, + * `@query`, `@scheme`, `@target-uri`, plus arbitrary request headers by name. + * Parameterized component identifiers (e.g. `@query-param;name=…`) are out of + * scope and rejected rather than half-supported. + */ + +/** A request in a form we can derive RFC 9421 covered-component values from. */ +export interface SignableRequest { + method: string; + /** Absolute request URL (scheme://authority/path?query). */ + url: string; + /** Request headers, matched case-insensitively for header components. */ + headers?: Record; +} + +/** Parameters of a single signature (the `@signature-params` line). */ +export interface SignatureParams { + /** Key id of the signer — an identity `kid_…`. */ + keyid: string; + /** Unix seconds the signature was created. */ + created: number; + /** Unix seconds after which the signature must be rejected (replay bound). */ + expires?: number; + /** Optional nonce for extra replay resistance. */ + nonce?: string; + /** Signature algorithm; only `ed25519` is supported. Default `ed25519`. */ + alg?: string; + /** Ordered covered component identifiers. Default {@link DEFAULT_COMPONENTS}. */ + components?: string[]; + /** Signature label used in the headers. Default `sig1`. */ + label?: string; +} + +/** The two headers a signed request carries. */ +export interface SignatureHeaders { + "Signature-Input": string; + Signature: string; +} + +/** Minimal covered set: method + authority + path. Enough to bind who/where/what. */ +export const DEFAULT_COMPONENTS = ["@method", "@authority", "@path"]; + +const SUPPORTED_ALG = "ed25519"; + +/** Derived component identifiers we know how to evaluate (no parameters). */ +const DERIVED = new Set(["@method", "@authority", "@path", "@query", "@scheme", "@target-uri"]); + +function parseUrl(url: string): URL { + return new URL(url); +} + +/** + * Derive the RFC 9421 value for one covered component. Throws for a component + * that cannot be evaluated (missing header, unknown/parameterized id) so signing + * never emits a base that silently omits a claimed component. + */ +export function componentValue(id: string, req: SignableRequest): string { + if (id.startsWith("@")) { + const u = parseUrl(req.url); + switch (id) { + case "@method": + return req.method.toUpperCase(); + case "@authority": + return u.host.toLowerCase(); + case "@path": + return u.pathname || "/"; + case "@query": + // Per §2.2.8: the query INCLUDING the leading "?"; "?" when there is none. + return u.search === "" ? "?" : u.search; + case "@scheme": + return u.protocol.replace(/:$/, "").toLowerCase(); + case "@target-uri": + return req.url; + default: + throw new Error(`unsupported derived component: ${id}`); + } + } + // A header component. Match case-insensitively, trim OWS, join dupes with ", ". + const wanted = id.toLowerCase(); + const headers = req.headers ?? {}; + const values: string[] = []; + for (const [k, v] of Object.entries(headers)) { + if (k.toLowerCase() === wanted) values.push(String(v).trim()); + } + if (values.length === 0) throw new Error(`covered header not present: ${id}`); + return values.join(", "); +} + +/** Serialize the `@signature-params` value: the inner list + ordered parameters. */ +export function signatureParamsValue(params: SignatureParams): string { + const components = params.components ?? DEFAULT_COMPONENTS; + for (const c of components) { + if (c.includes(";")) throw new Error(`parameterized component not supported: ${c}`); + if (c.startsWith("@") && !DERIVED.has(c)) { + throw new Error(`unsupported covered component: ${c}`); + } + } + const inner = "(" + components.map((c) => `"${c}"`).join(" ") + ")"; + // Deterministic parameter order: created, keyid, alg, expires, nonce. + let out = inner + `;created=${params.created}`; + out += `;keyid="${params.keyid}"`; + out += `;alg="${params.alg ?? SUPPORTED_ALG}"`; + if (params.expires !== undefined) out += `;expires=${params.expires}`; + if (params.nonce !== undefined) out += `;nonce="${params.nonce}"`; + return out; +} + +/** + * Build the RFC 9421 signature base (§2.5): one line per covered component, then + * the `"@signature-params": …` line last. This exact string is what gets signed. + */ +export function signatureBase(req: SignableRequest, params: SignatureParams): string { + const components = params.components ?? DEFAULT_COMPONENTS; + const lines: string[] = []; + for (const c of components) { + lines.push(`"${c}": ${componentValue(c, req)}`); + } + lines.push(`"@signature-params": ${signatureParamsValue(params)}`); + return lines.join("\n"); +} + +/** + * Sign a request: build the base, sign it with the injected `sign` callback + * (Ed25519 over the base bytes), and return the two headers. `sign` is expected + * to produce a raw Ed25519 signature (e.g. `signWithIdentity`). + */ +export function signRequest( + req: SignableRequest, + params: SignatureParams, + sign: (data: Buffer) => Buffer, +): SignatureHeaders { + if ((params.alg ?? SUPPORTED_ALG) !== SUPPORTED_ALG) { + throw new Error(`unsupported alg: ${params.alg}`); + } + const label = params.label ?? "sig1"; + const base = signatureBase(req, params); + const sig = sign(Buffer.from(base, "utf-8")); + return { + "Signature-Input": `${label}=${signatureParamsValue(params)}`, + Signature: `${label}=:${sig.toString("base64")}:`, + }; +} + +// ─── Verification ────────────────────────────────────────────────────────────── + +/** A parsed `Signature-Input` entry for one label. */ +interface ParsedInput { + label: string; + components: string[]; + params: SignatureParams; +} + +/** Parse a single-signature `Signature-Input` value. Returns null if malformed. */ +function parseSignatureInput(value: string): ParsedInput | null { + //