Skip to content

Commit 787cfb2

Browse files
bokelleyclaude
andauthored
feat(signing): accept any well-formed adcp_use purpose in keygen (#1710)
generate_signing_keypair, pem_to_adcp_jwk and adcp-keygen --purpose took a closed Literal["request-signing", "webhook-signing"] and refused every other value, so the SDK could not mint or publish a key for response-signing (the designated-task response JWS profile, core/response-payload-jws-envelope.json), governance-signing (which governance.py already verifies), or a surface the vocabulary does not name yet. The helpers they delegate to already took a str. purpose is now validated by syntax instead of membership: a lowercase hyphenated token of at most 64 characters. Malformed values (empty, upper case, underscores, whitespace, leading/trailing/double hyphens, non-str) still raise ValueError, and the CLI exits 2 before writing a file. An open vocabulary is safe because purpose matching is fail-closed: a verifier accepts a key only when adcp_use equals the purpose of the surface it verifies, so a key under any other purpose verifies nothing there. A test pins that against the request and webhook verifiers. adcp.signing exports ADCP_USE_REQUEST, ADCP_USE_WEBHOOK (marked deprecated upstream), and the new ADCP_USE_RESPONSE and ADCP_USE_GOVERNANCE, so callers need not retype literals. The docstrings no longer say request- and webhook-signing keys must be distinct for every verifier: 3.3 webhook verifiers accept request-signing keys, and new webhook signers publish request-signing. Backport of #1708 to 9.x. Closes #1677 on main. Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent aac52ca commit 787cfb2

5 files changed

Lines changed: 188 additions & 44 deletions

File tree

‎src/adcp/signing/__init__.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,10 @@
170170
signing_operation,
171171
)
172172
from adcp.signing.constants import (
173+
ADCP_USE_GOVERNANCE,
174+
ADCP_USE_REQUEST,
175+
ADCP_USE_RESPONSE,
176+
ADCP_USE_WEBHOOK,
173177
DEFAULT_EXPIRES_IN_SECONDS,
174178
DEFAULT_SKEW_SECONDS,
175179
DEFAULT_TAG,
@@ -368,6 +372,10 @@ def __init__(self, *args: object, **kwargs: object) -> None:
368372
"ResolvedSignerKey",
369373
"SignerKeyResolver",
370374
"StaticSignerKeys",
375+
"ADCP_USE_GOVERNANCE",
376+
"ADCP_USE_REQUEST",
377+
"ADCP_USE_RESPONSE",
378+
"ADCP_USE_WEBHOOK",
371379
"ALG_ED25519",
372380
"ALG_ES256",
373381
"ALLOWED_ALGS",

‎src/adcp/signing/constants.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,12 @@
55
DEFAULT_TAG = "adcp/request-signing/v1"
66
WEBHOOK_TAG = "adcp/webhook-signing/v1"
77
ADCP_USE_REQUEST = "request-signing"
8+
#: Deprecated upstream (adcp#5555): new webhook signers publish ``request-signing``.
89
ADCP_USE_WEBHOOK = "webhook-signing"
10+
#: Designated-task response JWS (``core/response-payload-jws-envelope.json``).
11+
ADCP_USE_RESPONSE = "response-signing"
12+
#: Governance attestation JWS (``check_governance`` ``governance_context``).
13+
ADCP_USE_GOVERNANCE = "governance-signing"
914
#: Current request keys and deprecated webhook keys are both valid for webhooks.
1015
WEBHOOK_ACCEPTED_ADCP_USES: frozenset[str] = frozenset({ADCP_USE_REQUEST, ADCP_USE_WEBHOOK})
1116
MAX_WINDOW_SECONDS = 300
@@ -15,7 +20,9 @@
1520
SIG_LABEL_DEFAULT = "sig1"
1621

1722
__all__ = [
23+
"ADCP_USE_GOVERNANCE",
1824
"ADCP_USE_REQUEST",
25+
"ADCP_USE_RESPONSE",
1926
"ADCP_USE_WEBHOOK",
2027
"DEFAULT_EXPIRES_IN_SECONDS",
2128
"DEFAULT_SKEW_SECONDS",

‎src/adcp/signing/keygen.py‎

Lines changed: 81 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@
1010
ergonomic.
1111
1212
Both paths produce the same PEM and JWK. Publish the JWK (public half)
13-
at your agent's ``jwks_uri`` — the ``adcp_use`` claim (``request-signing``
14-
or ``webhook-signing``) pins the key to one signing profile; verifiers
15-
reject keys used in the wrong surface.
13+
at your agent's ``jwks_uri`` — the ``adcp_use`` claim pins the key to one
14+
signing purpose (``request-signing``, ``response-signing``,
15+
``governance-signing``, the deprecated ``webhook-signing``, or any other
16+
lowercase hyphenated token); verifiers reject keys used in the wrong surface.
1617
1718
Usage (CLI):
1819
adcp-keygen --alg ed25519 --out private-key.pem
@@ -43,6 +44,7 @@
4344
import getpass
4445
import json
4546
import os
47+
import re
4648
import secrets
4749
import sys
4850
import unicodedata
@@ -53,6 +55,12 @@
5355
from cryptography.hazmat.primitives import serialization
5456
from cryptography.hazmat.primitives.asymmetric import ec, ed25519
5557

58+
from adcp.signing.constants import (
59+
ADCP_USE_GOVERNANCE,
60+
ADCP_USE_REQUEST,
61+
ADCP_USE_RESPONSE,
62+
ADCP_USE_WEBHOOK,
63+
)
5664
from adcp.signing.crypto import ALG_ED25519, ALG_ES256, b64url_encode, load_private_key_pem
5765

5866

@@ -64,7 +72,11 @@ def _encryption_algorithm(
6472
return serialization.BestAvailableEncryption(passphrase)
6573

6674

67-
_ADCP_USE_VALUES = ("request-signing", "webhook-signing")
75+
#: Purposes the spec names today, for help text. The accepted vocabulary is
76+
#: open: any token matching ``_ADCP_USE_PATTERN`` is a valid ``adcp_use``.
77+
_KNOWN_ADCP_USES = (ADCP_USE_REQUEST, ADCP_USE_RESPONSE, ADCP_USE_GOVERNANCE, ADCP_USE_WEBHOOK)
78+
_ADCP_USE_PATTERN = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
79+
_ADCP_USE_MAX_LENGTH = 64
6880

6981

7082
def _public_jwk_ed25519(
@@ -103,6 +115,25 @@ def _public_jwk_es256(
103115
}
104116

105117

118+
def _check_purpose(purpose: object) -> str:
119+
"""``purpose`` if it is a lowercase hyphenated token, else ``ValueError``.
120+
121+
Validation is syntactic, not by membership: an AdCP verifier accepts a
122+
key only when ``adcp_use`` equals the purpose of the surface it verifies
123+
(fail-closed), so a purpose no verifier implements authorizes nothing.
124+
"""
125+
if (
126+
not isinstance(purpose, str)
127+
or len(purpose) > _ADCP_USE_MAX_LENGTH
128+
or _ADCP_USE_PATTERN.fullmatch(purpose) is None
129+
):
130+
raise ValueError(
131+
"purpose must be a lowercase hyphenated token of at most "
132+
f"{_ADCP_USE_MAX_LENGTH} characters (e.g. {ADCP_USE_REQUEST!r}), got {purpose!r}"
133+
)
134+
return purpose
135+
136+
106137
def generate_ed25519(
107138
kid: str, passphrase: bytes | None = None, adcp_use: str = "request-signing"
108139
) -> tuple[bytes, dict[str, Any]]:
@@ -133,7 +164,7 @@ def pem_to_adcp_jwk(
133164
pem: bytes,
134165
*,
135166
kid: str,
136-
purpose: Literal["request-signing", "webhook-signing"],
167+
purpose: str,
137168
password: bytes | None = None,
138169
) -> dict[str, Any]:
139170
"""Derive the public JWK for an existing AdCP signing PEM.
@@ -153,8 +184,8 @@ def pem_to_adcp_jwk(
153184
* ``alg`` — MUST be ``"EdDSA"`` for Ed25519, ``"ES256"`` for P-256
154185
(NOT the RFC 9421 ``alg`` casing used in ``Signature-Input``).
155186
* ``adcp_use`` — required by AdCP #2423; verifiers reject keys
156-
lacking it. MUST match the signing surface (``"request-signing"``
157-
vs. ``"webhook-signing"``).
187+
lacking it. MUST match the signing surface (``"request-signing"``,
188+
``"response-signing"``, ``"governance-signing"``, ...).
158189
* ``key_ops`` — MUST be ``["verify"]`` (the public half cannot
159190
sign).
160191
@@ -165,22 +196,20 @@ def pem_to_adcp_jwk(
165196
the loader handles both forms.
166197
:param kid: JWK ``kid`` to embed. MUST match the value the signer
167198
will advertise via :meth:`SigningProvider.key_id`.
168-
:param purpose: Which AdCP signing profile this key is for. Sets
169-
``adcp_use``. Generate distinct keys per purpose — sharing
170-
material across request-signing and webhook-signing is a spec
171-
violation, not just a convention.
199+
:param purpose: Which AdCP signing purpose this key is for. Sets
200+
``adcp_use``. Any lowercase hyphenated token is accepted; see
201+
:func:`generate_signing_keypair` for the vocabulary and why an
202+
open one is safe. Generate distinct keys per purpose.
172203
:param password: Passphrase if ``pem`` is an encrypted private
173204
key.
174205
175206
:returns: Public JWK ready to publish in the agent's ``jwks_uri``.
176207
The private scalar (``d``) is NEVER included in the output.
177208
178-
:raises ValueError: ``purpose`` is not in
179-
``("request-signing", "webhook-signing")``; the PEM is not
180-
Ed25519 or ECDSA-P-256; the EC curve is not P-256.
209+
:raises ValueError: ``purpose`` is not a lowercase hyphenated token;
210+
the PEM is not Ed25519 or ECDSA-P-256; the EC curve is not P-256.
181211
"""
182-
if purpose not in _ADCP_USE_VALUES:
183-
raise ValueError(f"purpose must be one of {_ADCP_USE_VALUES}, got {purpose!r}")
212+
purpose = _check_purpose(purpose)
184213
if not kid:
185214
raise ValueError("kid must be a non-empty string")
186215

@@ -234,7 +263,7 @@ def generate_signing_keypair(
234263
*,
235264
alg: Literal["ed25519", "es256"] = "ed25519",
236265
kid: str | None = None,
237-
purpose: Literal["request-signing", "webhook-signing"] = "request-signing",
266+
purpose: str = ADCP_USE_REQUEST,
238267
passphrase: bytes | None = None,
239268
) -> tuple[bytes, dict[str, Any]]:
240269
"""Generate an AdCP signing keypair.
@@ -253,11 +282,20 @@ def generate_signing_keypair(
253282
collision-resistant within a single process but does not
254283
guarantee uniqueness across processes; rotation tooling needs
255284
its own identifier scheme to track retirement / revocation.
256-
:param purpose: Which AdCP signing profile this key is for. Sets the
257-
JWK ``adcp_use`` claim. **Request-signing and webhook-signing
258-
keys MUST be distinct** — a signature from one surface cannot
259-
replay as the other, and every conformant verifier enforces the
260-
claim. Generate separate keys per purpose.
285+
:param purpose: Which AdCP signing purpose this key is for. Sets the
286+
JWK ``adcp_use`` claim. The spec names ``"request-signing"`` (RFC
287+
9421 requests, and webhooks from new signers),
288+
``"response-signing"`` (designated-task response JWS),
289+
``"governance-signing"`` and the deprecated ``"webhook-signing"``;
290+
the constants are in :mod:`adcp.signing.constants`
291+
(``ADCP_USE_REQUEST``, ...). Any other lowercase hyphenated token
292+
is accepted for a surface the vocabulary does not name yet.
293+
An open vocabulary is safe because purpose matching is
294+
fail-closed: a verifier accepts a key only when ``adcp_use``
295+
equals the purpose of the surface it verifies (webhook verifiers
296+
accept ``request-signing`` or ``webhook-signing``), so a key
297+
published under any other purpose verifies nothing there.
298+
Generate separate keys per purpose.
261299
:param passphrase: When provided, the PEM is encrypted with
262300
``BestAvailableEncryption``. Typical only for dev-laptop keys;
263301
automated deployments usually leave the PEM unencrypted and
@@ -275,7 +313,8 @@ def generate_signing_keypair(
275313
publish at your ``jwks_uri``. The private scalar is NOT in the
276314
JWK — only in the PEM.
277315
278-
:raises ValueError: ``alg`` or ``purpose`` is unsupported.
316+
:raises ValueError: ``alg`` is unsupported, or ``purpose`` is not a
317+
lowercase hyphenated token.
279318
280319
Example:
281320
>>> pem, jwk = generate_signing_keypair(
@@ -286,8 +325,7 @@ def generate_signing_keypair(
286325
"""
287326
if alg not in ("ed25519", "es256"):
288327
raise ValueError(f"alg must be 'ed25519' or 'es256', got {alg!r}")
289-
if purpose not in _ADCP_USE_VALUES:
290-
raise ValueError(f"purpose must be one of {_ADCP_USE_VALUES}, got {purpose!r}")
328+
purpose = _check_purpose(purpose)
291329
resolved_kid = kid or _default_kid(alg)
292330
if alg == "ed25519":
293331
return generate_ed25519(resolved_kid, passphrase=passphrase, adcp_use=purpose)
@@ -310,10 +348,17 @@ def _prompt_passphrase_bytes() -> bytes:
310348
return unicodedata.normalize("NFC", first).encode("utf-8")
311349

312350

351+
def _purpose_arg(value: str) -> str:
352+
try:
353+
return _check_purpose(value)
354+
except ValueError as exc:
355+
raise argparse.ArgumentTypeError(str(exc)) from None
356+
357+
313358
def main(argv: list[str] | None = None) -> int:
314359
parser = argparse.ArgumentParser(
315360
prog="adcp-keygen",
316-
description="Generate a signing keypair for the AdCP request-signing profile.",
361+
description="Generate an AdCP signing keypair (PEM private key + public JWK).",
317362
)
318363
parser.add_argument(
319364
"--alg",
@@ -347,13 +392,17 @@ def main(argv: list[str] | None = None) -> int:
347392
)
348393
parser.add_argument(
349394
"--purpose",
350-
choices=list(_ADCP_USE_VALUES),
351-
default="request-signing",
395+
type=_purpose_arg,
396+
default=ADCP_USE_REQUEST,
397+
metavar="PURPOSE",
352398
help=(
353-
"Which AdCP signing profile this key is for (sets the JWK `adcp_use` "
354-
"claim). `request-signing` for outbound tool calls; `webhook-signing` "
355-
"for keys a sender uses to sign outbound webhooks to buyers. Verifiers "
356-
"enforce the claim, so mixing the two silently fails at first delivery."
399+
"Which AdCP signing purpose this key is for (sets the JWK `adcp_use` "
400+
f"claim): {', '.join(_KNOWN_ADCP_USES)}, or another lowercase "
401+
"hyphenated token. `request-signing` (default) signs outbound tool "
402+
"calls and, for new signers, webhooks; `response-signing` signs "
403+
"designated-task response envelopes; `webhook-signing` is deprecated. "
404+
"Verifiers enforce the claim, so a key under the wrong purpose fails "
405+
"at first use."
357406
),
358407
)
359408
args = parser.parse_args(argv)

‎tests/conformance/signing/test_keygen_programmatic.py‎

Lines changed: 84 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,15 @@
1818
from cryptography.hazmat.primitives import serialization
1919
from cryptography.hazmat.primitives.asymmetric import ec, ed25519
2020

21-
from adcp.signing import generate_signing_keypair, public_key_from_jwk
21+
from adcp.signing import (
22+
ADCP_USE_GOVERNANCE,
23+
ADCP_USE_REQUEST,
24+
ADCP_USE_RESPONSE,
25+
ADCP_USE_WEBHOOK,
26+
generate_signing_keypair,
27+
public_key_from_jwk,
28+
)
29+
from adcp.signing.constants import WEBHOOK_ACCEPTED_ADCP_USES
2230

2331
# ---------------------------------------------------------------------------
2432
# Core contract — returns (pem_bytes, public_jwk)
@@ -88,15 +96,81 @@ def test_webhook_signing_purpose_sets_adcp_use() -> None:
8896
assert jwk["adcp_use"] == "webhook-signing"
8997

9098

91-
def test_invalid_purpose_raises_value_error() -> None:
92-
"""Typos in ``purpose`` should fail loud — a silent fallback would
93-
silently mint a key with an unexpected ``adcp_use``."""
94-
with pytest.raises(ValueError, match="purpose must be one of"):
95-
generate_signing_keypair(
96-
alg="ed25519",
97-
kid="test-kid",
98-
purpose="requets-signing", # type: ignore[arg-type] # typo
99-
)
99+
@pytest.mark.parametrize(
100+
"purpose",
101+
[ADCP_USE_RESPONSE, ADCP_USE_GOVERNANCE, "oauth-access-token-signing", "x1"],
102+
)
103+
def test_purpose_vocabulary_is_open(purpose: str) -> None:
104+
"""``response-signing`` and purposes the spec does not name yet are
105+
expressible (#1677); only the token's syntax is checked."""
106+
_, jwk = generate_signing_keypair(alg="es256", kid="test-kid", purpose=purpose)
107+
assert jwk["adcp_use"] == purpose
108+
109+
110+
@pytest.mark.parametrize(
111+
"purpose",
112+
[
113+
"",
114+
"Request-Signing",
115+
"request_signing",
116+
"request signing",
117+
"-request",
118+
"request-",
119+
"request--signing",
120+
"request-signing\n",
121+
"a" * 65,
122+
None,
123+
b"request-signing",
124+
],
125+
)
126+
def test_malformed_purpose_raises_value_error(purpose: object) -> None:
127+
"""The vocabulary is open but the input is still validated: a value
128+
that is not a lowercase hyphenated token fails loud rather than mint
129+
a key with an unexpected ``adcp_use``."""
130+
with pytest.raises(ValueError, match="purpose must be a lowercase hyphenated token"):
131+
generate_signing_keypair(alg="ed25519", kid="test-kid", purpose=purpose) # type: ignore[arg-type]
132+
133+
134+
def test_unregistered_purpose_fails_closed_at_the_request_verifier() -> None:
135+
"""An open vocabulary is safe because purpose matching is fail-closed:
136+
a key minted under any purpose other than the verified surface's is
137+
refused with ``request_signature_key_purpose_invalid``."""
138+
from adcp.signing.errors import (
139+
REQUEST_SIGNATURE_KEY_PURPOSE_INVALID,
140+
SignatureVerificationError,
141+
)
142+
from adcp.signing.verifier import _check_key_purpose
143+
144+
for purpose in (ADCP_USE_RESPONSE, ADCP_USE_GOVERNANCE, "oauth-access-token-signing"):
145+
_, jwk = generate_signing_keypair(alg="ed25519", kid="k", purpose=purpose)
146+
with pytest.raises(SignatureVerificationError) as excinfo:
147+
_check_key_purpose(jwk, "ed25519", expected_adcp_use=ADCP_USE_REQUEST)
148+
assert excinfo.value.code == REQUEST_SIGNATURE_KEY_PURPOSE_INVALID
149+
with pytest.raises(SignatureVerificationError):
150+
_check_key_purpose(
151+
jwk,
152+
"ed25519",
153+
expected_adcp_use=ADCP_USE_WEBHOOK,
154+
accepted_adcp_uses=WEBHOOK_ACCEPTED_ADCP_USES,
155+
)
156+
157+
158+
def test_cli_accepts_open_purpose_and_rejects_malformed(tmp_path, capsys) -> None:
159+
import json
160+
161+
from adcp.signing import keygen
162+
163+
out = tmp_path / "response.pem"
164+
rc = keygen.main(["--out", str(out), "--kid", "resp", "--purpose", "response-signing"])
165+
assert rc == 0
166+
printed = json.loads(capsys.readouterr().out)
167+
assert printed["keys"][0]["adcp_use"] == "response-signing"
168+
169+
with pytest.raises(SystemExit) as excinfo:
170+
keygen.main(["--out", str(tmp_path / "bad.pem"), "--purpose", "Response_Signing"])
171+
assert excinfo.value.code == 2
172+
assert "lowercase hyphenated token" in capsys.readouterr().err
173+
assert not (tmp_path / "bad.pem").exists()
100174

101175

102176
def test_invalid_alg_raises_value_error() -> None:

‎tests/conformance/signing/test_signing_provider.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -303,8 +303,14 @@ def test_pem_to_adcp_jwk_accepts_spki_public_pem() -> None:
303303

304304
def test_pem_to_adcp_jwk_rejects_invalid_purpose() -> None:
305305
pem, _ = generate_signing_keypair(alg="ed25519", kid="x", purpose="request-signing")
306-
with pytest.raises(ValueError, match="purpose must be one of"):
307-
pem_to_adcp_jwk(pem, kid="x", purpose="some-other-purpose") # type: ignore[arg-type]
306+
with pytest.raises(ValueError, match="purpose must be a lowercase hyphenated token"):
307+
pem_to_adcp_jwk(pem, kid="x", purpose="Request Signing")
308+
309+
310+
def test_pem_to_adcp_jwk_accepts_response_signing() -> None:
311+
pem, minted = generate_signing_keypair(alg="es256", kid="x", purpose="response-signing")
312+
derived = pem_to_adcp_jwk(pem, kid="x", purpose="response-signing")
313+
assert derived == minted
308314

309315

310316
def test_pem_to_adcp_jwk_rejects_empty_kid() -> None:

0 commit comments

Comments
 (0)