From 2293c6a3ea8f3095103d80e5d30f4ac403480d97 Mon Sep 17 00:00:00 2001 From: Dmitry Sergeev Date: Thu, 5 Nov 2026 20:31:30 +0100 Subject: [PATCH 1/4] fix(rest/python): verify dual-audience (WBA-shape) request signatures signatures.md recommends one dual-audience signature for Web Bot Auth interop and says a UCP verifier accepts it. That signature covers "signature-agent";key="sig1" and carries tag="web-bot-auth" with the key's RFC 7638 thumbprint as keyid. parse_signature_input returned None for any component with a parameter, so such a request was answered signature_missing. Select the Dictionary member a key parameter names (RFC 9421 Section 2.1.2), require signature-agent coverage when the header is present, and under tag="web-bot-auth" require keyid to be the key's thumbprint, as the verification routine in signatures.md does. A component parameter other than key now skips only that signature, not the whole header. --- rest/python/server/ucp_signing.py | 164 ++++++++++++++++++++++--- rest/python/server/ucp_signing_test.py | 145 ++++++++++++++++++++-- 2 files changed, 280 insertions(+), 29 deletions(-) diff --git a/rest/python/server/ucp_signing.py b/rest/python/server/ucp_signing.py index 68740fb3..b3646e24 100644 --- a/rest/python/server/ucp_signing.py +++ b/rest/python/server/ucp_signing.py @@ -22,6 +22,8 @@ * ECDSA P-256 (`ES256`) verification with fixed-width raw `r||s` signatures (RFC 9421 Section 3.3.4) -- never ASN.1/DER -- and Ed25519 (RFC 8032). * Signer public-key discovery from the `UCP-Agent` profile's `signing_keys[]`. +* WBA-shape (dual-audience) signatures: the `key` component parameter (RFC 9421 + Section 2.1.2) for `signature-agent`, and the RFC 7638 `keyid` binding. Only the encoding and canonicalization are implemented here; every cryptographic primitive comes from the `cryptography` package. The module is @@ -32,7 +34,9 @@ import base64 import hashlib import ipaddress +import json import logging +import re import socket import time from urllib.parse import urlsplit @@ -56,6 +60,17 @@ "P-256": ("ES256", 32), } +# RFC 7638 Section 3.2: the required members of each key type, in the +# lexicographic order the thumbprint input uses. +_THUMBPRINT_MEMBERS = { + "EC": ("crv", "kty", "x", "y"), + "OKP": ("crv", "kty", "x"), + "RSA": ("e", "kty", "n"), +} + +# An RFC 8941 Dictionary member key, at the start of a member. +_SF_KEY = re.compile(r"[a-z*][a-z0-9_\-.*]*") + class SignatureError(Exception): """A signature or profile-resolution failure with UCP wire semantics. @@ -185,10 +200,13 @@ def parse_signature_input(value: str) -> dict | None: value: The ``Signature-Input`` header value. Returns: - A mapping ``{label: {"raw", "components", "params"}}`` where ``raw`` is the - member value verbatim (what ``@signature-params`` must echo), ``components`` - are the unquoted component identifiers, and ``params`` maps parameter names - to their unquoted values. None on malformed input. + A mapping ``{label: {"raw", "components", "component_keys", "unsupported", + "params"}}`` where ``raw`` is the member value verbatim (what + ``@signature-params`` must echo), ``components`` are the unquoted component + names, ``component_keys`` holds each component's ``key`` parameter (RFC + 9421 Section 2.1.2) or None, ``unsupported`` is True when a component + carries any other parameter, and ``params`` maps parameter names to their + unquoted values. None on malformed input. """ if not isinstance(value, str) or not value.strip(): @@ -213,10 +231,23 @@ def parse_signature_input(value: str) -> dict | None: inner = val[1:end] rest = val[end + 1 :] components: list[str] = [] + component_keys: list[str | None] = [] + unsupported = False for tok in _sf_split(inner, " "): - if not (tok.startswith('"') and tok.endswith('"')) or ";" in tok: + name, *component_params = _sf_split(tok, ";") + if len(name) < 2 or not (name.startswith('"') and name.endswith('"')): return None - components.append(tok[1:-1]) + key = None + for param in component_params: + k, _, v = param.partition("=") + if k.strip() == "key" and v.startswith('"') and v.endswith('"'): + key = v[1:-1] + else: + # A parameter this verifier does not implement makes only this + # signature unverifiable, not the whole header (RFC 9421 4.3). + unsupported = True + components.append(name[1:-1]) + component_keys.append(key) params: dict[str, str] = {} for part in _sf_split(rest, ";"): if not part: @@ -225,7 +256,13 @@ def parse_signature_input(value: str) -> dict | None: if v.startswith('"') and v.endswith('"'): v = v[1:-1] params[k.strip()] = v - out[label] = {"raw": val, "components": components, "params": params} + out[label] = { + "raw": val, + "components": components, + "component_keys": component_keys, + "unsupported": unsupported, + "params": params, + } return out or None @@ -256,14 +293,16 @@ def parse_signature(value: str) -> dict | None: def build_signature_base( - components: list[str], + components: list, raw_params: str, resolve: "callable", ) -> bytes | None: """Construct the RFC 9421 signature base. Args: - components: The ordered component identifiers to cover. + components: The ordered component identifiers to cover: a name, or a + ``(name, key)`` pair for a Dictionary member selected with the ``key`` + parameter (RFC 9421 Section 2.1.2). raw_params: The ``Signature-Input`` member value verbatim, echoed on the ``@signature-params`` line. resolve: A callable mapping a component identifier to its string value, or @@ -274,15 +313,73 @@ def build_signature_base( """ lines: list[str] = [] - for name in components: - value = resolve(name) + for component in components: + value = resolve(component) if value is None: return None - lines.append(f'"{name}": {value}') + if isinstance(component, tuple): + name, key = component + identifier = f'"{name}";key="{key}"' + else: + identifier = f'"{component}"' + lines.append(f"{identifier}: {value}") lines.append(f'"@signature-params": {raw_params}') return "\n".join(lines).encode("utf-8") +def dictionary_member(value: str, key: str) -> str | None: + """Return one Dictionary member's value as RFC 9421 Section 2.1.2 signs it. + + Args: + value: A field value holding an RFC 8941 Dictionary. + key: The member key the component's ``key`` parameter names. + + Returns: + The member value with its parameters, serialized without optional + whitespace, or None when the Dictionary has no such member. As in RFC 8941, + the last of duplicate members wins. + + """ + found = None + for member in _sf_split(value, ","): + match = _SF_KEY.match(member) + if not match or match.group(0) != key: + continue + rest = member[match.end() :] + if rest.startswith("="): + found = rest[1:] + elif not rest or rest.startswith(";"): + found = "?1" + rest # A member without a value is boolean true. + parts = _sf_split(found, ";") if found is not None else [] + if not parts: + return None + item, *params = parts + serialized = item + for param in params: + k, eq, v = param.partition("=") + k, v = k.strip(), v.strip() + serialized += f";{k}" if not eq or v == "?1" else f";{k}={v}" + return serialized + + +def jwk_thumbprint(jwk: dict) -> str | None: + """Return the RFC 7638 SHA-256 thumbprint of a JWK, base64url-encoded. + + Args: + jwk: A JWK of type EC, OKP or RSA. + + Returns: + The thumbprint, or None for another key type or a JWK missing a member the + thumbprint needs. + + """ + members = _THUMBPRINT_MEMBERS.get(jwk.get("kty")) + if members is None or not all(isinstance(jwk.get(m), str) for m in members): + return None + canonical = json.dumps({m: jwk[m] for m in members}, separators=(",", ":")) + return _b64u_encode(hashlib.sha256(canonical.encode("utf-8")).digest()) + + def required_components( method: str, has_query: bool, @@ -316,12 +413,10 @@ def required_components( required.append("idempotency-key") if "ucp-agent" in headers: required.append("ucp-agent") - # signature-agent is a WBA-shape component (carried with RFC 8941 component - # parameters, e.g. "signature-agent";key="sig1", under tag=web-bot-auth). This - # verifier covers the default-UCP regime only and does not parse WBA-shape - # component parameters, so it does not gate on signature-agent — the coverage - # promise matches what the module can actually verify. WBA-shape support - # (member selection, keyid thumbprint binding) is a documented follow-up. + # A WBA-shape (dual-audience) signature covers signature-agent with a key + # parameter, e.g. "signature-agent";key="sig1"; the gate keys on the name. + if "signature-agent" in headers: + required.append("signature-agent") return required @@ -531,7 +626,12 @@ def verify_request( # use:"enc" and any key_ops that omits "verify" before matching on kid. keys_by_kid = {k.get("kid"): k for k in keys if _sig_capable(k)} - def resolve(name: str) -> str | None: + def resolve(name) -> str | None: + if isinstance(name, tuple): + # RFC 9421 Section 2.1.2: the key parameter selects a Dictionary member. + field, key = name + value = headers.get(field) + return dictionary_member(value, key) if isinstance(value, str) else None if name == "@method": return method.upper() if name == "@authority": @@ -558,6 +658,13 @@ def resolve(name: str) -> str | None: "Signature-Input MUST NOT carry an 'alg' parameter", ) continue + if desc["unsupported"]: + last_error = SignatureError( + "signature_invalid", + 401, + "Signature covers a component parameter other than key", + ) + continue if not set(required).issubset(desc["components"]): missing = sorted(set(required) - set(desc["components"])) last_error = SignatureError( @@ -573,7 +680,24 @@ def resolve(name: str) -> str | None: "key_not_found", 401, f"No published key with kid={keyid!r}" ) continue - base = build_signature_base(desc["components"], desc["raw"], resolve) + # signatures.md, step pre-2a: a WBA-shape signature's keyid MUST be the + # RFC 7638 thumbprint of the key it resolved to. + if desc["params"].get("tag") == "web-bot-auth" and keyid != jwk_thumbprint( + jwk + ): + last_error = SignatureError( + "signature_invalid", + 401, + "tag=web-bot-auth requires keyid to be the key's RFC 7638 thumbprint", + ) + continue + components = [ + name if key is None else (name, key) + for name, key in zip( + desc["components"], desc["component_keys"], strict=True + ) + ] + base = build_signature_base(components, desc["raw"], resolve) if base is None: last_error = SignatureError( "signature_invalid", 401, "Unresolvable signed component" diff --git a/rest/python/server/ucp_signing_test.py b/rest/python/server/ucp_signing_test.py index 2452e8ad..2b578188 100644 --- a/rest/python/server/ucp_signing_test.py +++ b/rest/python/server/ucp_signing_test.py @@ -240,6 +240,19 @@ def test_malformed_returns_none(self) -> None: self.assertIsNone(signing.parse_signature_input("not a signature input")) self.assertIsNone(signing.parse_signature("")) + def test_component_key_parameter(self) -> None: + """A key parameter is kept per component; other parameters are flagged.""" + parsed = signing.parse_signature_input( + 'sig1=("@method" "signature-agent";key="sig1");keyid="k", ' + 'sig2=("content-type";sf);keyid="k"' + ) + self.assertEqual( + parsed["sig1"]["components"], ["@method", "signature-agent"] + ) + self.assertEqual(parsed["sig1"]["component_keys"], [None, "sig1"]) + self.assertFalse(parsed["sig1"]["unsupported"]) + self.assertTrue(parsed["sig2"]["unsupported"]) + class CoverageGateTest(absltest.TestCase): """The UCP required-component coverage table.""" @@ -268,19 +281,13 @@ def test_idempotency_key_header_on_get(self) -> None: ) self.assertIn("idempotency-key", required) - def test_ucp_agent_covered_signature_agent_out_of_scope(self) -> None: - """A present ucp-agent header must be covered; signature-agent is not. - - signature-agent is a WBA-shape component (component parameters / - tag=web-bot-auth) that this default-UCP verifier does not parse, so it is - deliberately outside the coverage gate: the module's promise matches what - it can actually verify. - """ + def test_present_ucp_agent_and_signature_agent_must_be_covered(self) -> None: + """Present ucp-agent and signature-agent headers must both be covered.""" required = signing.required_components( "GET", False, {"ucp-agent": "a", "signature-agent": "b"}, False ) self.assertIn("ucp-agent", required) - self.assertNotIn("signature-agent", required) + self.assertIn("signature-agent", required) def test_alg_param_rejected_by_verify_request(self) -> None: """A signature carrying an alg parameter is rejected (spec MUST NOT).""" @@ -307,6 +314,126 @@ def test_alg_param_rejected_by_verify_request(self) -> None: self.assertEqual(ctx.exception.code, "signature_invalid") +# RFC 7638 thumbprint of RFC_ED25519_JWK; the keyid of the signatures.md +# dual-audience example. +WBA_KEYID = "poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U" + + +class WbaShapeTest(absltest.TestCase): + """Dual-audience signatures from the signatures.md WBA Interop section.""" + + PROFILE = "https://platform.example/.well-known/ucp" + BODY = b'{"line_items":[]}' + COMPONENTS = ( + '"@method"', + '"@authority"', + '"@path"', + '"signature-agent";key="sig1"', + '"ucp-agent"', + '"idempotency-key"', + '"content-digest"', + '"content-type"', + ) + + def _signed(self, keyid: str = WBA_KEYID, components: tuple = COMPONENTS): + """Sign the example request over a hand-built RFC 9421 base.""" + headers = { + "ucp-agent": f'profile="{self.PROFILE}"', + "signature-agent": f'sig1="{self.PROFILE}";type=jwks_uri', + "idempotency-key": "550e8400-e29b-41d4-a716-446655440000", + "content-type": "application/json", + "content-digest": signing.content_digest(self.BODY), + } + raw = ( + f'({" ".join(components)});keyid="{keyid}";created=1738617600;' + 'expires=1738621200;tag="web-bot-auth"' + ) + values = { + '"@method"': "POST", + '"@authority"': "merchant.example.com", + '"@path"': "/checkout-sessions", + # RFC 9421 Section 2.1.2: the value of the sig1 member, not the field. + '"signature-agent";key="sig1"': f'"{self.PROFILE}";type=jwks_uri', + '"ucp-agent"': headers["ucp-agent"], + '"idempotency-key"': headers["idempotency-key"], + '"content-digest"': headers["content-digest"], + '"content-type"': headers["content-type"], + } + lines = [f"{c}: {values[c]}" for c in components] + base = "\n".join([*lines, f'"@signature-params": {raw}']).encode() + key = ed25519.Ed25519PrivateKey.from_private_bytes(_b64u(RFC_ED25519_D)) + sig = base64.b64encode(key.sign(base)).decode("ascii") + headers["signature-input"] = f"sig1={raw}" + headers["signature"] = f"sig1=:{sig}:" + return headers + + def _verify(self, headers: dict, kid: str = WBA_KEYID) -> str: + jwk = dict(RFC_ED25519_JWK, kid=kid) + return signing.verify_request( + "POST", + "merchant.example.com", + "/checkout-sessions", + "", + headers, + self.BODY, + [jwk], + ) + + def test_thumbprint_vectors(self) -> None: + """RFC 7638 thumbprints match RFC 8037 A.3 and the signatures.md keyid.""" + self.assertEqual(signing.jwk_thumbprint(RFC_ED25519_JWK), WBA_KEYID) + self.assertEqual( + signing.jwk_thumbprint( + { + "kty": "OKP", + "crv": "Ed25519", + "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", + } + ), + "kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k", + ) + + def test_dictionary_member_is_reserialized(self) -> None: + """The selected member is serialized without optional whitespace.""" + value = 'sig2="https://b.example", sig1="https://a.example"; type=jwks_uri' + self.assertEqual( + signing.dictionary_member(value, "sig1"), + '"https://a.example";type=jwks_uri', + ) + self.assertEqual(signing.dictionary_member("sig1;a, sig2", "sig1"), "?1;a") + self.assertIsNone(signing.dictionary_member(value, "sig3")) + + def test_dual_audience_signature_verifies(self) -> None: + """The recommended WBA-shape signature verifies via UCP-Agent keys.""" + self.assertEqual(self._verify(self._signed()), WBA_KEYID) + + def test_web_bot_auth_keyid_must_be_the_thumbprint(self) -> None: + """Under tag=web-bot-auth a keyid other than the thumbprint is rejected.""" + headers = self._signed(keyid="test-key-ed25519") + with self.assertRaises(signing.SignatureError) as ctx: + self._verify(headers, kid="test-key-ed25519") + self.assertEqual(ctx.exception.code, "signature_invalid") + self.assertIn("thumbprint", ctx.exception.message) + + def test_present_signature_agent_must_be_covered(self) -> None: + """A signature that leaves out the present Signature-Agent is rejected.""" + headers = self._signed( + components=tuple(c for c in self.COMPONENTS if "signature-agent" not in c) + ) + with self.assertRaises(signing.SignatureError) as ctx: + self._verify(headers) + self.assertIn("signature-agent", ctx.exception.message) + + def test_unsupported_parameter_skips_only_that_signature(self) -> None: + """Another label's unsupported parameter does not hide a valid signature.""" + headers = self._signed() + headers["signature-input"] = ( + 'sig0=("@method";sf);keyid="x", ' + headers["signature-input"] + ) + headers["signature"] = "sig0=:AAAA:, " + headers["signature"] + self.assertEqual(self._verify(headers), WBA_KEYID) + + class SsrfGuardTest(absltest.TestCase): """Profile-URL transport and SSRF guards.""" From f9eee78fa608cf1c80ea5a6906d3a540d5cbb99f Mon Sep 17 00:00:00 2001 From: Dmitry Sergeev Date: Thu, 5 Nov 2026 20:31:31 +0100 Subject: [PATCH 2/4] fix(rest/nodejs): verify dual-audience (WBA-shape) request signatures The Node verifier had the same gap as the Python one: a component with a parameter made parseSignatureInput return null, so the dual-audience signature signatures.md recommends was answered signature_missing. Mirror the Python change: Dictionary member selection for the key parameter (RFC 9421 Section 2.1.2), signature-agent coverage when the header is present, the RFC 7638 keyid check under tag="web-bot-auth", and skipping only the signature that uses another component parameter. buildSignatureBase takes a name or a [name, key] pair. --- rest/nodejs/src/utils/signature.ts | 150 +++++++++++++++++++++++++---- rest/nodejs/test/signing.test.ts | 141 ++++++++++++++++++++++++++- 2 files changed, 272 insertions(+), 19 deletions(-) diff --git a/rest/nodejs/src/utils/signature.ts b/rest/nodejs/src/utils/signature.ts index 0bc806d2..acff4157 100644 --- a/rest/nodejs/src/utils/signature.ts +++ b/rest/nodejs/src/utils/signature.ts @@ -25,8 +25,10 @@ import { UcpError, ucpErrorResponse } from "./ucp_error"; // This is the Node twin of the Python server's ucp_signing.py: RFC 9421 // signature-base construction with the UCP covered-component set, RFC 9530 // Content-Digest over the raw body bytes (sha-256), ES256 (ECDSA P-256 with -// fixed-width raw r||s signatures, never ASN.1/DER) plus Ed25519, and signer -// key discovery from the UCP-Agent profile's keys[]. Only node:crypto is used; +// fixed-width raw r||s signatures, never ASN.1/DER) plus Ed25519, signer key +// discovery from the UCP-Agent profile's keys[], and WBA-shape (dual-audience) +// signatures: the key component parameter (RFC 9421 Section 2.1.2) for +// signature-agent and the RFC 7638 keyid binding. Only node:crypto is used; // the RFC 8941 structured-field subset is hand-rolled, no new dependencies. // Public keys resolved from a signer profile are cached for this long. @@ -37,6 +39,17 @@ const keyCache = new Map(); // OPTIONAL and the baseline every verifier MUST support is ES256. const ES256_COORD_BYTES = 32; +// RFC 7638 Section 3.2: the required members of each key type, in the +// lexicographic order the thumbprint input uses. +const THUMBPRINT_MEMBERS: Record = { + EC: ["crv", "kty", "x", "y"], + OKP: ["crv", "kty", "x"], + RSA: ["e", "kty", "n"], +}; + +// An RFC 8941 Dictionary member key, at the start of a member. +const SF_KEY = /^[a-z*][a-z0-9_\-.*]*/; + // A signature or profile-resolution failure with UCP wire semantics: the UCP // error code and the HTTP status the spec maps it to. export class SignatureError extends Error { @@ -64,9 +77,17 @@ export type Jwk = { export type SignatureInputMember = { raw: string; components: string[]; + // Each component's key parameter (RFC 9421 Section 2.1.2), or null. + componentKeys: (string | null)[]; + // True when a component carries any parameter other than key. + unsupported: boolean; params: Record; }; +// A covered component: a name, or [name, key] for a Dictionary member selected +// with the key parameter (RFC 9421 Section 2.1.2). +export type ComponentId = string | [string, string]; + // Returns the RFC 9530 Content-Digest value (sha-256 over the raw body bytes). export function contentDigest(body: Uint8Array): string { const digest = crypto.createHash("sha256").update(body).digest("base64"); @@ -137,8 +158,9 @@ export function sfSplit(value: string, seps: string): string[] { } // Parses a Signature-Input header into per-label descriptors: the member value -// verbatim (what @signature-params must echo), the unquoted component -// identifiers, and the parameters. Null on malformed input. +// verbatim (what @signature-params must echo), the unquoted component names +// with each one's key parameter, whether any component carries another +// parameter, and the signature parameters. Null on malformed input. export function parseSignatureInput( value: string ): Record | null { @@ -166,11 +188,28 @@ export function parseSignatureInput( const inner = val.slice(1, end); const rest = val.slice(end + 1); const components: string[] = []; + const componentKeys: (string | null)[] = []; + let unsupported = false; for (const tok of sfSplit(inner, " ")) { - if (!tok.startsWith('"') || !tok.endsWith('"') || tok.includes(";")) { + const [name = "", ...componentParams] = sfSplit(tok, ";"); + if (name.length < 2 || !name.startsWith('"') || !name.endsWith('"')) { return null; } - components.push(tok.slice(1, -1)); + let key: string | null = null; + for (const param of componentParams) { + const pEq = param.indexOf("="); + const k = (pEq === -1 ? param : param.slice(0, pEq)).trim(); + const v = pEq === -1 ? "" : param.slice(pEq + 1); + if (k === "key" && v.startsWith('"') && v.endsWith('"')) { + key = v.slice(1, -1); + } else { + // A parameter this verifier does not implement makes only this + // signature unverifiable, not the whole header (RFC 9421 4.3). + unsupported = true; + } + } + components.push(name.slice(1, -1)); + componentKeys.push(key); } const params: Record = {}; for (const part of sfSplit(rest, ";")) { @@ -181,7 +220,7 @@ export function parseSignatureInput( if (v.startsWith('"') && v.endsWith('"')) v = v.slice(1, -1); params[k] = v; } - out[label] = { raw: val, components, params }; + out[label] = { raw: val, components, componentKeys, unsupported, params }; } return Object.keys(out).length ? out : null; } @@ -211,25 +250,72 @@ export function parseSignature(value: string): Record | null { // Constructs the RFC 9421 signature base. The raw Signature-Input member value // is echoed verbatim on the @signature-params line. Null if any covered // component cannot be resolved for this message. -export function buildSignatureBase( - components: string[], +export function buildSignatureBase( + components: C[], rawParams: string, - resolve: (name: string) => string | undefined | null + resolve: (component: C) => string | undefined | null ): Buffer | null { const lines: string[] = []; - for (const name of components) { - const value = resolve(name); + for (const component of components) { + const value = resolve(component); if (value === undefined || value === null) return null; - lines.push(`"${name}": ${value}`); + const identifier = + typeof component === "string" + ? `"${component}"` + : `"${component[0]}";key="${component[1]}"`; + lines.push(`${identifier}: ${value}`); } lines.push(`"@signature-params": ${rawParams}`); return Buffer.from(lines.join("\n"), "utf-8"); } +// Returns one Dictionary member's value as RFC 9421 Section 2.1.2 signs it: +// the member value with its parameters, serialized without optional +// whitespace, or null when the Dictionary has no such member. As in RFC 8941, +// the last of duplicate members wins. +export function dictionaryMember(value: string, key: string): string | null { + let found: string | null = null; + for (const member of sfSplit(value, ",")) { + const match = SF_KEY.exec(member); + if (!match || match[0] !== key) continue; + const rest = member.slice(match[0].length); + if (rest.startsWith("=")) { + found = rest.slice(1); + } else if (!rest || rest.startsWith(";")) { + found = "?1" + rest; // A member without a value is boolean true. + } + } + const parts = found === null ? [] : sfSplit(found, ";"); + if (!parts.length) return null; + const [item, ...params] = parts; + let serialized = item!; + for (const param of params) { + const pEq = param.indexOf("="); + const k = (pEq === -1 ? param : param.slice(0, pEq)).trim(); + const v = pEq === -1 ? "" : param.slice(pEq + 1).trim(); + serialized += pEq === -1 || v === "?1" ? `;${k}` : `;${k}=${v}`; + } + return serialized; +} + +// Returns the RFC 7638 SHA-256 thumbprint of a JWK, base64url-encoded, or null +// for another key type or a JWK missing a member the thumbprint needs. +export function jwkThumbprint(jwk: Jwk): string | null { + const members = THUMBPRINT_MEMBERS[jwk.kty ?? ""]; + if (!members || !members.every((m) => typeof jwk[m] === "string")) { + return null; + } + const canonical = JSON.stringify( + Object.fromEntries(members.map((m) => [m, jwk[m]])) + ); + return crypto.createHash("sha256").update(canonical).digest("base64url"); +} + // The components a UCP request signature MUST cover (the verification-side // coverage gate from signatures.md). Coverage keys on header presence, not on -// the method. signature-agent is a WBA-shape component this default-UCP -// verifier does not parse, so it is deliberately outside the gate. +// the method. A WBA-shape (dual-audience) signature covers signature-agent +// with a key parameter, e.g. "signature-agent";key="sig1"; the gate keys on +// the name. export function requiredComponents( _method: string, hasQuery: boolean, @@ -241,6 +327,7 @@ export function requiredComponents( if (hasBody) required.push("content-digest", "content-type"); if ("idempotency-key" in headers) required.push("idempotency-key"); if ("ucp-agent" in headers) required.push("ucp-agent"); + if ("signature-agent" in headers) required.push("signature-agent"); return required; } @@ -387,7 +474,14 @@ export function verifyRequest( if (sigCapable(key)) keysByKid.set(key.kid, key); } - const resolve = (name: string): string | undefined => { + const resolve = (name: ComponentId): string | undefined | null => { + if (typeof name !== "string") { + // RFC 9421 Section 2.1.2: the key parameter selects a Dictionary member. + const value = headers[name[0]]; + return typeof value === "string" + ? dictionaryMember(value, name[1]) + : null; + } if (name === "@method") return method.toUpperCase(); if (name === "@authority") return normalizeAuthority(authority); if (name === "@path") return path || "/"; // RFC 9421 2.2.6: empty is "/" @@ -413,6 +507,14 @@ export function verifyRequest( ); continue; } + if (desc.unsupported) { + lastError = new SignatureError( + "signature_invalid", + 401, + "Signature covers a component parameter other than key" + ); + continue; + } const missing = required.filter((c) => !desc.components.includes(c)); if (missing.length) { lastError = new SignatureError( @@ -432,7 +534,21 @@ export function verifyRequest( ); continue; } - const base = buildSignatureBase(desc.components, desc.raw, resolve); + // signatures.md, step pre-2a: a WBA-shape signature's keyid MUST be the + // RFC 7638 thumbprint of the key it resolved to. + if (desc.params["tag"] === "web-bot-auth" && keyid !== jwkThumbprint(jwk)) { + lastError = new SignatureError( + "signature_invalid", + 401, + "tag=web-bot-auth requires keyid to be the key's RFC 7638 thumbprint" + ); + continue; + } + const components: ComponentId[] = desc.components.map((name, i) => { + const key = desc.componentKeys[i]; + return key === null || key === undefined ? name : [name, key]; + }); + const base = buildSignatureBase(components, desc.raw, resolve); if (base === null) { lastError = new SignatureError( "signature_invalid", diff --git a/rest/nodejs/test/signing.test.ts b/rest/nodejs/test/signing.test.ts index dd102c7a..bb3dcaa3 100644 --- a/rest/nodejs/test/signing.test.ts +++ b/rest/nodejs/test/signing.test.ts @@ -24,9 +24,11 @@ import { clearKeyCache, contentDigest, contentDigestMatches, + dictionaryMember, extractKeys, fetchSigningKeys, jwkFromPublicKey, + jwkThumbprint, normalizeAuthority, parseSignature, parseSignatureInput, @@ -403,7 +405,7 @@ test("coverage keys on header presence, not on the method", () => { assert.ok(required.includes("idempotency-key")); }); -test("ucp-agent must be covered; signature-agent is out of scope", () => { +test("present ucp-agent and signature-agent headers must both be covered", () => { const required = requiredComponents( "GET", false, @@ -411,7 +413,7 @@ test("ucp-agent must be covered; signature-agent is out of scope", () => { false ); assert.ok(required.includes("ucp-agent")); - assert.ok(!required.includes("signature-agent")); + assert.ok(required.includes("signature-agent")); }); test("a signature carrying an alg parameter is rejected (spec MUST NOT)", () => { @@ -439,6 +441,141 @@ test("a signature carrying an alg parameter is rejected (spec MUST NOT)", () => ); }); +/* Dual-audience signatures from the signatures.md WBA Interop section. */ + +// RFC 7638 thumbprint of RFC_ED25519_JWK; the keyid of the signatures.md +// dual-audience example. +const WBA_KEYID = "poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U"; +const WBA_PROFILE = "https://platform.example/.well-known/ucp"; +const WBA_BODY = Buffer.from('{"line_items":[]}'); +const WBA_COMPONENTS = [ + '"@method"', + '"@authority"', + '"@path"', + '"signature-agent";key="sig1"', + '"ucp-agent"', + '"idempotency-key"', + '"content-digest"', + '"content-type"', +]; + +// Signs the example request over a hand-built RFC 9421 base. +function wbaSigned(keyid = WBA_KEYID, components = WBA_COMPONENTS) { + const headers: Record = { + "ucp-agent": `profile="${WBA_PROFILE}"`, + "signature-agent": `sig1="${WBA_PROFILE}";type=jwks_uri`, + "idempotency-key": "550e8400-e29b-41d4-a716-446655440000", + "content-type": "application/json", + "content-digest": contentDigest(WBA_BODY), + }; + const raw = + `(${components.join(" ")});keyid="${keyid}";created=1738617600;` + + 'expires=1738621200;tag="web-bot-auth"'; + const values: Record = { + '"@method"': "POST", + '"@authority"': "merchant.example.com", + '"@path"': "/checkout-sessions", + // RFC 9421 Section 2.1.2: the value of the sig1 member, not the field. + '"signature-agent";key="sig1"': `"${WBA_PROFILE}";type=jwks_uri`, + '"ucp-agent"': headers["ucp-agent"]!, + '"idempotency-key"': headers["idempotency-key"]!, + '"content-digest"': headers["content-digest"]!, + '"content-type"': headers["content-type"]!, + }; + const base = Buffer.from( + [ + ...components.map((c) => `${c}: ${values[c]}`), + `"@signature-params": ${raw}`, + ].join("\n") + ); + const key = crypto.createPrivateKey({ + key: { ...RFC_ED25519_JWK, d: RFC_ED25519_D }, + format: "jwk", + }); + const sig = crypto.sign(null, base, key).toString("base64"); + headers["signature-input"] = `sig1=${raw}`; + headers["signature"] = `sig1=:${sig}:`; + return headers; +} + +function wbaVerify(headers: Record, kid = WBA_KEYID) { + return verifyRequest( + "POST", + "merchant.example.com", + "/checkout-sessions", + "", + headers, + WBA_BODY, + [{ ...RFC_ED25519_JWK, kid }] + ); +} + +test("RFC 7638 thumbprints match RFC 8037 A.3 and the signatures.md keyid", () => { + assert.equal(jwkThumbprint(RFC_ED25519_JWK), WBA_KEYID); + assert.equal( + jwkThumbprint({ + kty: "OKP", + crv: "Ed25519", + x: "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", + }), + "kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k" + ); +}); + +test("the selected Dictionary member is serialized without optional whitespace", () => { + const value = + 'sig2="https://b.example", sig1="https://a.example"; type=jwks_uri'; + assert.equal( + dictionaryMember(value, "sig1"), + '"https://a.example";type=jwks_uri' + ); + assert.equal(dictionaryMember("sig1;a, sig2", "sig1"), "?1;a"); + assert.equal(dictionaryMember(value, "sig3"), null); +}); + +test("a key parameter is kept per component; other parameters are flagged", () => { + const parsed = parseSignatureInput( + 'sig1=("@method" "signature-agent";key="sig1");keyid="k", ' + + 'sig2=("content-type";sf);keyid="k"' + ); + assert.ok(parsed); + assert.deepEqual(parsed["sig1"]?.components, ["@method", "signature-agent"]); + assert.deepEqual(parsed["sig1"]?.componentKeys, [null, "sig1"]); + assert.equal(parsed["sig1"]?.unsupported, false); + assert.equal(parsed["sig2"]?.unsupported, true); +}); + +test("the recommended WBA-shape signature verifies via UCP-Agent keys", () => { + assert.equal(wbaVerify(wbaSigned()), WBA_KEYID); +}); + +test("under tag=web-bot-auth a keyid other than the thumbprint is rejected", () => { + const err = assertSignatureError( + () => wbaVerify(wbaSigned("test-key-ed25519"), "test-key-ed25519"), + "signature_invalid" + ); + assert.match(err.message, /thumbprint/); +}); + +test("a signature that leaves out the present Signature-Agent is rejected", () => { + const components = WBA_COMPONENTS.filter( + (c) => !c.includes("signature-agent") + ); + const err = assertSignatureError( + () => wbaVerify(wbaSigned(WBA_KEYID, components)), + "signature_invalid" + ); + assert.match(err.message, /signature-agent/); +}); + +test("another label's unsupported parameter does not hide a valid signature", () => { + const headers = wbaSigned(); + headers["signature-input"] = + 'sig0=("@method";sf);keyid="x", ' + headers["signature-input"]; + headers["signature"] = "sig0=:AAAA:, " + headers["signature"]; + assert.equal(wbaVerify(headers), WBA_KEYID); +}); + /* Caller-requested extra covered components beyond the UCP minimum. * * RFC 9421 lets a signer cover any component; the UCP table is the required From ca1c17371086bf31819154223e4a8f777c967484 Mon Sep 17 00:00:00 2001 From: Dmitry Sergeev Date: Wed, 11 Nov 2026 11:10:55 +0100 Subject: [PATCH 3/4] fix(rest/python): cover required components only when signed whole A required component signed with a key parameter selected one Dictionary member and left the rest of the field unbound, so "content-digest";key="a" passed coverage while the body digest sat in an unsigned member. Coverage now checks (name, key) pairs: a required component counts only without a key, and signature-agent also as ;key="