Skip to content

feat(identity): harden TAP verification and add a JWKS key resolver - #1364

Open
brendanjryan wants to merge 13 commits into
mainfrom
feat/tap-hardening
Open

brendanjryan wants to merge 13 commits into
mainfrom
feat/tap-hardening

Conversation

@brendanjryan

Copy link
Copy Markdown
Collaborator

Builds on #1362 and #1363, which this branch merges. Review those first; this diff shrinks to its own three commits once they land.

Makes TAP verification more robust without changing what the TAP spec requires by default.

Verifier (Tap.Server.verifier)

  • clockSkew (seconds, 0–60, default 0) allows for an agent whose clock differs from the server's, as RFC 9421 §3.2.1 permits. The default stays 0, as TAP specifies. Nonces stay claimed for the skewed lifetime, so a signature can't be accepted again after its claim expires.
  • requiredComponents: { browse, payment } requires components beyond TAP's @authority and @path, per intent. For example, payment: ['@method', 'content-digest'] binds a payment request to its method and body. TAP's minimum doesn't bind the body, so it can be swapped within the 8-minute lifetime.
  • A request carrying more than one TAP-tagged signature is rejected, since it's ambiguous which one identifies the agent. Signatures with other tags are still ignored.

Content-Digest (all HTTP message signatures)

  • A signature that covers content-digest now has its RFC 9530 digest checked against the request body (sha-256 and sha-512). Before, only the header text was signed, so a matching header with a different body verified.
  • The header needs at least one supported digest, and every supported digest present must match. A body that was already read or is locked can't be checked, so the request is rejected.

Prover (Tap.Client.prover)

  • components covers more than the TAP minimum. With content-digest, the prover adds a sha-256 Content-Digest header when the request has none.

Tap.Jwks.resolver({ url })

  • A KeyResolver over an agent provider's JSON Web Key Set, following attestation/Jwks.ts: ttl, refreshInterval, maxStale, timeout, a shared in-flight fetch, no redirects and no MPP payment.
  • A key is returned only when its kid equals the signature's keyid, its kty/crv fit the signature's alg, and any alg (EdDSA, ES256, ES384, PS512), use or key_ops it declares allows that algorithm and verification.
  • A repeated kid is trusted for neither key. Only public members are imported. HTTPS only.

Tests

  • Tap.hardening.test.ts and Jwks.test.ts cover the options above.
  • HttpMessageSignature.fuzz.test.ts (fast-check) checks three properties. Arbitrary and structured-field-shaped headers never throw and always get a rejection status. Signed requests with arbitrary methods, paths, queries, bodies and covered components verify. Changing any covered component invalidates them.
  • HttpMessageSignature.errors.test.ts covers the parser and signer error paths.
  • A local Stryker run on HttpMessageSignature.ts and Jwks.ts scored 93.6% (625 of 668 mutants killed, up from 79.3%). The 43 survivors are unreachable branches, guards backed by a second check, or checks WebCrypto's key import also enforces. Stryker isn't added to the repository.
  • One existing test changed: HttpMessageSignature.components.test.ts covered content-digest but sent its last request without the body. It now sends the body, since the digest is checked.

Checks: pnpm check:types, pnpm check:ci, identity tests (532 passed).

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T03:03:39.697732Z 9873245 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@tempoxyz-bot

tempoxyz-bot commented Nov 25, 2026 •

Copy link
Copy Markdown

👁️ Cyclops Security Review

✅ Reviewed cf5aa09 (latest) · Coverage: partial · ⚠️ 20 open, 1 not rechecked findings · report
⚠️ Not checked: Same-label duplicate Signature-Input handling was not established: TAP counts matching entries after dictionary parsing, but the pinned structured-header dependency's behavior on raw duplicate dictionary keys was not available from the chec
⚠️ Not checked: Web Bot Auth algorithm isolation from TAP ECDSA support: ruled out without reading the cited code at this commit
ℹ️ Not verifiable from the source alone (needs running code or deployed state): No deployed route configuration, proof exposure, ingress override, request deadline, process memory budget, or nonce-store concurrency data was staged. The digest timings are isolated measurements, no
⏸️ The review of cf5aa09 did not recheck 1 earlier finding, so whether it still applies is unknown

# Severity Finding Introduced Status
1 🟡 Medium Concurrent copies can spend a TAP nonce without either request verifying cf5aa09 🟠 Open
2 🟡 Medium Spent digest-bound signatures can still trigger full request-body buffering and hashing cf5aa09 🟠 Open
3 🟢 Low A namespace nonce can overwrite the meaning of another agent's legacy replay key cf5aa09 🟠 Open
4 🟢 Low Mixed-case Content-Digest component skips TAP body digest verification 9873245 🟠 Open
5 🟢 Low TAP verifier accepts signatures whose expires precedes created under clock skew 9873245 🟠 Open
6 🟡 Medium Express adapter reserializes bodies, so Content-Digest check rejects validly signed requests 9873245 🟠 Open
7 🟢 Low TAP verifier skips payment requiredComponents for browse-tagged signatures on the same route 9873245 🟠 Open
8 🟢 Low TAP nonce claim lapses before a higher-clockSkew verifier stops accepting 9873245 🟠 Open
9 🟢 Low TAP verifier accepts two TAP signatures sharing one wire label 9873245 ⏸️ Not rechecked since 9873245
10 🟡 Medium TAP @​query verification rejects signatures over the wire query on Express 9873245 🟠 Open
11 ⚪ Needs review TAP JWKS resolver trusts cached keys past maxStale when ttl is larger 9873245 🟠 Open
12 🟢 Low Web Bot Auth keyResolver type widens to ECDSA algorithms it never receives 9873245 🟠 Open
13 🟡 Medium Covered Content-Digest check rejects parsed-body requests behind the Elysia adapter 9873245 🟠 Open
14 🟡 Medium Mppx.toNodeListener rejects valid signed requests that cover Content-Digest 9873245 🟠 Open
15 🟡 Medium HTTP message signature verifier serializes component parameters before cheap rejections 9873245 🟠 Open
16 🟢 Low TAP JWKS resolver accepts RSA keys below the 2,048-bit PS512 minimum 9873245 🟠 Open
17 🟢 Low TAP JWKS resolver treats aged cached responses as fresh, bypassing maxStale 9873245 🟠 Open
18 🟢 Low TAP JWKS resolver serves expired key set until refreshInterval, ignoring shorter ttl 9873245 🟠 Open
19 🟢 Low TAP prover silently emits unverifiable signatures when covering whole Signature headers 9873245 🟠 Open
20 🟢 Low TAP JWKS resolver accepts RSA-PSS keys with public exponent 1 9873245 🟠 Open
21 🟡 Medium TAP JWKS resolver buffers and retains unbounded provider responses 9873245 🟠 Open

@pkg-pr-new

pkg-pr-new Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/mppx@1364

commit: cf5aa09

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 987324529e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +262 to +264
if (hasComponent(input.components, Constants.components.contentDigest)) {
const reason = await checkContentDigest(request)
if (reason) return { status: 'invalid', reason }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require a supported digest to be covered by the signature

When a signature covers only a dictionary member such as "content-digest";key="md5", the ID-only component check treats the digest as covered, but checkContentDigest validates any supported member in the header, including unsigned ones. An intermediary can retain the signed MD5 member, replace the body, and add an unsigned sha-256 member matching the replacement; both signature verification and the new body check then pass, including with TAP's requiredComponents: { payment: ['content-digest'] }. Require coverage of the entire header or explicitly verify that a supported digest member being checked is itself signed.

Useful? React with 👍 / 👎.

if (!expected.length) return 'The Content-Digest header has no supported digest.'
if (request.bodyUsed || request.body?.locked)
return 'The request body is unavailable to check its Content-Digest.'
const body = await request.clone().arrayBuffer()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Convert body-read failures into verification failures

For a signed request whose upload stream errors or is aborted, bodyUsed and body.locked can both be false while request.clone().arrayBuffer() rejects. This read is outside a catch, so the new digest check makes Tap.Server.verifier().verify() reject instead of returning an invalid verification result. Identity.Server.evaluate and Identity.Server.verify propagate that rejection, so it also interrupts an Identity.anyOf evaluation rather than allowing another valid identity proof to succeed. Catch body-read failures and return an appropriate verification failure.

Useful? React with 👍 / 👎.

Comment thread src/extensions/identity/tap/Jwks.ts Outdated
} catch (error) {
// A failed refetch for an unknown key ID cannot say it is unknown: it may be newly rotated
// in. Only a set that already went stale is served through an outage.
if (!fresh && good && now - good.fetchedAt <= maxStale) return good.keys

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recheck the stale-key deadline after awaiting a failed fetch

When a refresh starts just before maxStale expires and fails after that deadline, the fallback still uses now captured before the fetch, returning a key that should no longer be trusted. For example, with maxStale: 60, a lookup starting at age 59 seconds whose fetch fails 10 seconds later returns the old key at age 69 seconds. This extends acceptance of potentially rotated-out keys by the fetch duration and violates the resolver's fail-closed deadline. Compare Date.now() against good.fetchedAt in the catch block rather than using the pre-fetch timestamp.

Useful? React with 👍 / 👎.

maxAge: Constants.maximumSignatureLifetime,
nonceNamespace: Constants.protocol,
// TAP blocks any nonce seen within the signature lifetime, whichever key signed it.
nonceScope: 'namespace',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve existing replay claims when changing nonce scope

When an existing deployment upgrades while TAP signatures remain live, this changes replay-store keys from tap:<keyId>:<nonce> to tap:<nonce> without consulting the previous claims. A request already accepted by the previous version can therefore be replayed successfully against the upgraded verifier until its signature expires; during a rolling deployment, the same request can likewise succeed once on each version despite their shared store. Preserve compatibility with the previous claims during the transition, or provide an explicit migration that drains outstanding signature lifetimes before switching formats.

Useful? React with 👍 / 👎.

Comment on lines +305 to +308
const perKey = await Store.tryClaim(store, `${namespace}:${input.keyId}:${input.nonce}`, expires)
if (scope !== 'namespace') return perKey
const shared = await Store.tryClaim(store, `${namespace}:${input.nonce}`, expires)
return perKey && shared

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium (trigger unconfirmed) · unverified: Concurrent copies can spend a TAP nonce without either request verifying

The new helper attempts the namespace claim even after losing the per-key claim, then requires both claims to have succeeded. If attempt A successfully inserts the per-key marker but its result is delayed, attempt B can lose that claim, insert the namespace marker, and return false. A then loses the namespace claim and also returns false.

Full finding

The new helper attempts the namespace claim even after losing the per-key claim, then requires both claims to have succeeded. If attempt A successfully inserts the per-key marker but its result is delayed, attempt B can lose that claim, insert the namespace marker, and return false. A then loses the namespace claim and also returns false. Both markers remain held even though neither request verified; subsequent retries with the same proof fail. An in-memory check of the pinned helper with a delayed adapter reproduced two rejections and two retained markers. This can arise from concurrent retries without an attacker; deliberately triggering it requires obtaining a copy of an otherwise valid proof and racing the legitimate request against a shared asynchronous store. One competing request can deny one attempt, without a payment charge at this stage; sustained impact requires a fresh racing copy for each fresh proof. The old single claim would have admitted one contender. The effect is limited to the proof's lifetime and a fresh nonce restores service; no deployed race rate was measured. At minimum, stop immediately after a failed per-key claim. Prefer an atomic multi-key migration operation or one authoritative marker after retiring legacy verifiers.

Valid? React with 👍 / 👎.

Comment on lines +262 to +281
if (hasComponent(input.components, Constants.components.contentDigest)) {
// A digest is checked only when the whole field is signed: covering one member (`;key=`)
// would let an unsigned member stand in for it.
if (!coversWholeField(input.components, Constants.components.contentDigest))
return {
status: 'invalid',
reason: 'The signature must cover the whole Content-Digest field.',
}
const reason = await checkContentDigest(request)
if (reason) return { status: 'invalid', reason }
}
try {
if (
!(await Store.tryClaim(
!(await claimNonce(
options.nonceStore,
`${options.nonceNamespace}:${input.keyId}:${input.nonce}`,
input.expires * 1000,
options.nonceNamespace,
options.nonceScope,
input,
// Held for as long as the skewed lifetime check could still accept the signature.
(input.expires + skew) * 1000,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium (exposure and trigger unconfirmed) · unverified: Spent digest-bound signatures can still trigger full request-body buffering and hashing

Before looking up replay state, the verifier clones, fully buffers, and hashes the body for any cryptographically valid proof covering Content-Digest. A holder of one such proof can reuse it, including after legitimate use, with an arbitrarily different body up to ingress limits.

Full finding

Before looking up replay state, the verifier clones, fully buffers, and hashes the body for any cryptographically valid proof covering Content-Digest. A holder of one such proof can reuse it, including after legitimate use, with an arbitrarily different body up to ingress limits. It passes header signature verification, makes the server read and hash the replacement body, and then fails on the digest without reaching the replay claim. The same proof can drive the work again while its signature is live. The base path rejected spent proofs without reading the body. Setup requires a trusted signing capability or access to a still-live digest-bound proof; no payment Credential or settlement is needed at the request identity stage. Sustain requires sending the entire body per attempt and obtaining fresh proof material when it expires; at one 10 MiB attempt per second this is about 35 GiB/hour of upload, before transport overhead. The same traffic already consumes that ingress bandwidth by honest means; the added cost is server-side buffering and hashing on requests that cannot pass replay protection. On a 32-logical-core host, an isolated Node v24.22.3 release-runtime microbenchmark (node --expose-gc --input-type=module - <mode> <sizeMiB>, 40 sequential attempts per process, Ed25519 verification in both paths, streamed 64 KiB chunks and one SHA-256 in the head path) measured base→head wall time, CPU time, and peak RSS of 4.02→52.27 ms, 5.77→82.04 ms, and 62,640→106,248 KiB at 1 MiB; and 5.36→431.60 ms, 7.28→562.83 ms, and 62,136→221,764 KiB at 10 MiB. CPU amplification in this isolated path was 14.2× and 77.3×; the head path grew about 6.9× in CPU at 10× the body size. The 10 MiB measurement uses the Node adapter's default ingress budget; this was not a full SDK, network, or store benchmark, and deployed timeouts, memory headroom, concurrency, and effective ingress limits are unknown. Reject known-spent proofs before reading the body, retain an atomic final claim, and bound digest validation by bytes and time. Bound concurrent checks for the same proof without letting an invalid body permanently consume its nonce.

Valid? React with 👍 / 👎.

Comment on lines +305 to +308
const perKey = await Store.tryClaim(store, `${namespace}:${input.keyId}:${input.nonce}`, expires)
if (scope !== 'namespace') return perKey
const shared = await Store.tryClaim(store, `${namespace}:${input.nonce}`, expires)
return perKey && shared

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low (exposure and trigger unconfirmed) · unverified: A namespace nonce can overwrite the meaning of another agent's legacy replay…

Namespace-wide markers use tap:<nonce> while legacy markers use tap:<keyId>:<nonce>, and the parser permits colons in either string. An accepted proof from key other with nonce agent:fresh creates the exact marker tap:agent:fresh needed by a different proof from key agent with nonce fresh. The second proof is falsely rejected even though its nonce was never used.

Full finding

A namespace nonce can overwrite the meaning of another agent's legacy replay key

Namespace-wide markers use tap:<nonce> while legacy markers use tap:<keyId>:<nonce>, and the parser permits colons in either string. An accepted proof from key other with nonce agent:fresh creates the exact marker tap:agent:fresh needed by a different proof from key agent with nonce fresh. The second proof is falsely rejected even though its nonce was never used. The isolated helper check reproduced first-proof acceptance and second-proof rejection, while both claims succeeded in legacy-only mode. Targeting a specific attempt requires a trusted signer with control over its nonce, knowledge of the other attempt's key ID and nonce, and arriving first; a fresh unpredictable nonce makes guessing impractical. There is no payment charge in the request gate. One accepted request can deny the targeted proof until the conflicting marker expires; sustaining this against fresh attempts requires learning and winning a new collision for each attempt. One unrelated honest request does not normally deny a different nonce. No broader outage or deployed rate was established. Use a new replay-key prefix disjoint from the legacy prefix, with unambiguous component encoding, and retain legacy compatibility checks only during the migration.

Valid? React with 👍 / 👎.

Comment on lines +262 to +272
if (hasComponent(input.components, Constants.components.contentDigest)) {
// A digest is checked only when the whole field is signed: covering one member (`;key=`)
// would let an unsigned member stand in for it.
if (!coversWholeField(input.components, Constants.components.contentDigest))
return {
status: 'invalid',
reason: 'The signature must cover the whole Content-Digest field.',
}
const reason = await checkContentDigest(request)
if (reason) return { status: 'invalid', reason }
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low (exposure and trigger unconfirmed): Mixed-case Content-Digest component skips TAP body digest verification

HttpMessageSignature.verify runs the body digest check only when a covered component id is exactly content-digest, yet it builds the signature base with a case-insensitive header lookup. A signature covering "Content-Digest" therefore verifies with a body that does not match the signed digest. Verifiers requiring lowercase content-digest still refuse it.

Full finding

HttpMessageSignature.verify runs the body digest check only when a covered component id is exactly content-digest, yet it builds the signature base with a case-insensitive header lookup. A signature covering "Content-Digest" therefore verifies with a body that does not match the signed digest. Verifiers requiring lowercase content-digest still refuse it.

First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Comment on lines +214 to 221
const skew = options.clockSkew ?? 0
const now = Math.floor(Date.now() / 1000)
if (input.created > now || input.expires <= now || input.expires - input.created > options.maxAge)
if (
input.created > now + skew ||
input.expires <= now - skew ||
input.expires - input.created > options.maxAge
)
return { status: 'invalid', reason: 'The signature is expired or has an invalid lifetime.' }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low: TAP verifier accepts signatures whose expires precedes created under clock skew

With a nonzero clockSkew, HttpMessageSignature.verify widens the created and expires checks independently, so they no longer imply expires > created. A signature from a trusted key with created = now + 30 and expires = now - 30 verifies under clockSkew 60. The base check rejected it, and the default zero skew still does.

Full finding

With a nonzero clockSkew, HttpMessageSignature.verify widens the created and expires checks independently, so they no longer imply expires > created. A signature from a trusted key with created = now + 30 and expires = now - 30 verifies under clockSkew 60. The base check rejected it, and the default zero skew still does.

First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Comment on lines +555 to +585
async function checkContentDigest(request: Request): Promise<string | undefined> {
let digests: Dictionary
try {
digests = parseDictionary(request.headers.get('content-digest') ?? '')
} catch {
return 'The Content-Digest header is malformed.'
}
const expected: { algorithm: string; value: Uint8Array }[] = []
for (const [key, algorithm] of Object.entries(digestAlgorithms)) {
const member = digests.get(key)
if (!member) continue
if (isInnerList(member) || !(member[0] instanceof ArrayBuffer))
return 'The Content-Digest header is malformed.'
expected.push({ algorithm, value: new Uint8Array(member[0]) })
}
if (!expected.length) return 'The Content-Digest header has no supported digest.'
if (request.bodyUsed || request.body?.locked)
return 'The request body is unavailable to check its Content-Digest.'
let body: ArrayBuffer
try {
body = await request.clone().arrayBuffer()
} catch {
return 'The request body could not be read to check its Content-Digest.'
}
for (const { algorithm, value } of expected) {
const actual = new Uint8Array(await crypto.subtle.digest(algorithm, body))
if (!constantTimeEqual(Base64.fromBytes(actual), Base64.fromBytes(value)))
return 'The Content-Digest does not match the request body.'
}
return undefined
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium (exposure unconfirmed): Express adapter reserializes bodies, so Content-Digest check rejects validly signed requests

The new checkContentDigest hashes the Fetch Request body it is handed. On Express that body is JSON.stringify(req.body), or absent when no parser ran, while the original Content-Digest and signature headers are kept. A correctly signed body such as {"quantity": 1} is rejected with 401, and different wire bytes that parse to the same object pass.

Full finding

The new checkContentDigest hashes the Fetch Request body it is handed. On Express that body is JSON.stringify(req.body), or absent when no parser ran, while the original Content-Digest and signature headers are kept. A correctly signed body such as {"quantity": 1} is rejected with 401, and different wire bytes that parse to the same object pass.

First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Comment on lines +36 to +39
const extra = {
[Constants.tags.browse]: config.requiredComponents?.browse ?? [],
[Constants.tags.payment]: config.requiredComponents?.payment ?? [],
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low: TAP verifier skips payment requiredComponents for browse-tagged signatures on the same route

Tap.Server.verifier picks the extra required components from the signature's own tag and accepts both TAP tags on every route. With the documented requiredComponents payment list, a signature tagged agent-browser-auth that covers only @​authority and @​path passes on the payment route with any method and body. First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Comment on lines +214 to 221
const skew = options.clockSkew ?? 0
const now = Math.floor(Date.now() / 1000)
if (input.created > now || input.expires <= now || input.expires - input.created > options.maxAge)
if (
input.created > now + skew ||
input.expires <= now - skew ||
input.expires - input.created > options.maxAge
)
return { status: 'invalid', reason: 'The signature is expired or has an invalid lifetime.' }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low: TAP nonce claim lapses before a higher-clockSkew verifier stops accepting

HttpMessageSignature.verify holds a nonce claim until signed expiry plus the accepting verifier's own clockSkew. A verifier with a larger clockSkew on the same nonce store still accepts the signature after that claim lapses, so one TAP signature passes identity verification twice. First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

@tempoxyz-bot

Copy link
Copy Markdown

Low (exposure unconfirmed): TAP verifier accepts two TAP signatures sharing one wire label

Tap.Server.verifier documents that a request carrying more than one TAP signature is rejected. The check counts entries after structured-field parsing has collapsed repeated labels, so two TAP-tagged members under one label in Signature-Input and Signature pass, and the last one is verified. First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Comment on lines +61 to +63
const ttl = (options.ttl ?? 300) * 1_000
const refreshInterval = (options.refreshInterval ?? 30) * 1_000
const maxStale = (options.maxStale ?? 3_600) * 1_000

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs review: TAP JWKS resolver trusts cached keys past maxStale when ttl is larger

Tap.Jwks.resolver accepts a ttl larger than maxStale and then serves a cached key for the whole ttl, even after a refetch has failed. Its documented promise that verification fails closed maxStale seconds after the fetch while the URL is unreachable holds only when ttl is at most maxStale. First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

@@ -346,6 +430,10 @@ function signatureBase(request: Request, input: SignatureInput): string {

function componentValue(request: Request, component: Component): string {
const url = new URL(request.url)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium: TAP @​query verification rejects signatures over the wire query on Express

The new @​query component value is new URL(request.url).search, and the Express adapter builds that URL by re-parsing req.originalUrl, so WHATWG encoding rewrites the query (' becomes %27). A signature over the query actually sent is rejected, while one over the re-encoded spelling verifies for the same request. First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Comment on lines +5 to +8
/** ECDSA using the P-256 curve and SHA-256. */
ecdsaP256Sha256: 'ecdsa-p256-sha256',
/** ECDSA using the P-384 curve and SHA-384. */
ecdsaP384Sha384: 'ecdsa-p384-sha384',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low: Web Bot Auth keyResolver type widens to ECDSA algorithms it never receives

The change adds two ECDSA values to the shared Algorithms constant, which widens the algorithm parameter of the public WebBotAuth.Server.verifier keyResolver callback. The same change keeps that verifier restricted to Ed25519 and RSA-PSS at runtime, so resolvers typed for those two algorithms, or switching exhaustively over them, stop type-checking for values they never receive.

Full finding

The change adds two ECDSA values to the shared Algorithms constant, which widens the algorithm parameter of the public WebBotAuth.Server.verifier keyResolver callback. The same change keeps that verifier restricted to Ed25519 and RSA-PSS at runtime, so resolvers typed for those two algorithms, or switching exhaustively over them, stop type-checking for values they never receive.

First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Comment on lines +571 to +578
if (request.bodyUsed || request.body?.locked)
return 'The request body is unavailable to check its Content-Digest.'
let body: ArrayBuffer
try {
body = await request.clone().arrayBuffer()
} catch {
return 'The request body could not be read to check its Content-Digest.'
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium: Covered Content-Digest check rejects parsed-body requests behind the Elysia adapter

The PR makes the shared HTTP message signature verifier check a covered content-digest against the Fetch Request body and reject a consumed body. Behind the in-repo Elysia adapter, Elysia has already parsed JSON, text, form and octet-stream bodies before the verifier runs, so validly signed requests get 401. First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Comment on lines +571 to +572
if (request.bodyUsed || request.body?.locked)
return 'The request body is unavailable to check its Content-Digest.'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium (exposure unconfirmed): Mppx.toNodeListener rejects valid signed requests that cover Content-Digest

The new Content-Digest check refuses any request whose body was already read. Mppx.toNodeListener drains the body before calling the payment handler, so every body-bearing request whose verified signature covers content-digest is answered 401 instead of reaching payment, even though the signature and digest are correct. First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

id: id as string,
parameters,
}))
if (!hasValidComponents(components)) return undefined

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium (exposure unconfirmed): HTTP message signature verifier serializes component parameters before cheap rejections

The new duplicate-component check in toSignatureInput serializes every covered component's parameters during parsing, before the lifetime check. A rejected request carrying a large byte-sequence component parameter costs 2.1x to 4.4x the CPU it cost at the PR base, with no valid key or signature needed. First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Comment on lines +129 to +155
return async ({ algorithm, keyId }) => {
const jwk = (await keysFor(keyId)).get(keyId)
if (!jwk) return undefined
const { alg, crv, key_ops, kty, use } = jwk
const type = keyTypes[algorithm]
if (kty !== type.kty || (type.crv && crv !== type.crv)) return undefined
if (alg !== undefined && !(joseAlgorithms[algorithm] as readonly unknown[]).includes(alg))
return undefined
if (use !== undefined && use !== 'sig') return undefined
if (key_ops !== undefined && !(Array.isArray(key_ops) && key_ops.includes('verify')))
return undefined
// Only the public members are imported, so a published private key is never used.
const members =
kty === 'RSA'
? ['kty', 'n', 'e']
: kty === 'EC'
? ['kty', 'crv', 'x', 'y']
: ['kty', 'crv', 'x']
const publicJwk = Object.fromEntries(
members.map((member) => [member, jwk[member]]),
) as JsonWebKey
try {
return await crypto.subtle.importKey('jwk', publicJwk, type.importAs, true, ['verify'])
} catch {
return undefined
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low (trigger unconfirmed): TAP JWKS resolver accepts RSA keys below the 2,048-bit PS512 minimum

Tap.Jwks.resolver returns any RSA JWK that WebCrypto imports, without checking its modulus length, and the shared HTTP message signature verifier does not check it either. PS512 keys of 1,034 to 2,047 bits published by the configured provider therefore verify TAP signatures. First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Comment on lines +82 to +92
async function fetchKeys(startedAt: number) {
const response = await fetch(
url,
withoutPayment({
headers: { accept: 'application/jwk-set+json, application/json' },
signal: AbortSignal.timeout(timeout),
// Workers reject 'error'; a redirect is not ok, so it fails below.
redirect: 'manual',
}),
)
if (!response.ok) throw new Error(`JWKS request failed with ${response.status}.`)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low (trigger unconfirmed): TAP JWKS resolver treats aged cached responses as fresh, bypassing maxStale

Tap.Jwks.resolver stamps every successful JWKS response with the lookup's start time and never reads its Age. When an HTTP cache in the Fetch path answers a refetch with an old key set, the ttl and maxStale clocks restart, so a rotated-out key keeps verifying instead of failing closed. First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Comment on lines +61 to +62
const ttl = (options.ttl ?? 300) * 1_000
const refreshInterval = (options.refreshInterval ?? 30) * 1_000

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low (exposure unconfirmed): TAP JWKS resolver serves expired key set until refreshInterval, ignoring shorter ttl

keysFor refetches a key set older than ttl only when refreshInterval has elapsed since the last fetch started, and otherwise returns the cached set under the maxStale allowance. When ttl is below refreshInterval, a successfully fetched set is reused past ttl with no refetch attempted, so the effective cache lifetime becomes refreshInterval.

Full finding

keysFor refetches a key set older than ttl only when refreshInterval has elapsed since the last fetch started, and otherwise returns the cached set under the maxStale allowance. When ttl is below refreshInterval, a successfully fetched set is reused past ttl with no refetch attempted, so the effective cache lifetime becomes refreshInterval.

First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

config.intent === Constants.intents.payment ? Constants.tags.payment : Constants.tags.browse
const expiresIn = config.expiresIn ?? Constants.defaultSignatureLifetime
Signer.resolve(config.key)
const components = [...Constants.requiredComponents, ...(config.components ?? [])]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low: TAP prover silently emits unverifiable signatures when covering whole Signature headers

The new TAP prover components option accepts bare signature and signature-input. When an earlier prover or the caller already set those headers, sign builds the base from the old field value and then appends TAP's own member, so the returned request never verifies. First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Comment on lines +129 to +155
return async ({ algorithm, keyId }) => {
const jwk = (await keysFor(keyId)).get(keyId)
if (!jwk) return undefined
const { alg, crv, key_ops, kty, use } = jwk
const type = keyTypes[algorithm]
if (kty !== type.kty || (type.crv && crv !== type.crv)) return undefined
if (alg !== undefined && !(joseAlgorithms[algorithm] as readonly unknown[]).includes(alg))
return undefined
if (use !== undefined && use !== 'sig') return undefined
if (key_ops !== undefined && !(Array.isArray(key_ops) && key_ops.includes('verify')))
return undefined
// Only the public members are imported, so a published private key is never used.
const members =
kty === 'RSA'
? ['kty', 'n', 'e']
: kty === 'EC'
? ['kty', 'crv', 'x', 'y']
: ['kty', 'crv', 'x']
const publicJwk = Object.fromEntries(
members.map((member) => [member, jwk[member]]),
) as JsonWebKey
try {
return await crypto.subtle.importKey('jwk', publicJwk, type.importAs, true, ['verify'])
} catch {
return undefined
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low (trigger unconfirmed): TAP JWKS resolver accepts RSA-PSS keys with public exponent 1

Tap.Jwks.resolver imports a provider RSA JWK and returns it without checking the public exponent. On Node's OpenSSL-backed WebCrypto an e of 1 imports, so the unsigned PSS encoding of a signature base verifies as a signature. Anyone can then pass TAP verification for that key ID without a private key.

Full finding

Tap.Jwks.resolver imports a provider RSA JWK and returns it without checking the public exponent. On Node's OpenSSL-backed WebCrypto an e of 1 imports, so the unsigned PSS encoding of a signature base verifies as a signature. Anyone can then pass TAP verification for that key ID without a private key.

First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Comment on lines +82 to +107
async function fetchKeys(startedAt: number) {
const response = await fetch(
url,
withoutPayment({
headers: { accept: 'application/jwk-set+json, application/json' },
signal: AbortSignal.timeout(timeout),
// Workers reject 'error'; a redirect is not ok, so it fails below.
redirect: 'manual',
}),
)
if (!response.ok) throw new Error(`JWKS request failed with ${response.status}.`)
const body = (await response.json()) as { keys?: unknown } | null
// A body without a key list is a failed fetch, so it never replaces the last good set.
if (!body || !Array.isArray(body.keys)) throw new Error('JWKS response has no keys list.')
const keys = new Map<string, Record<string, unknown>>()
for (const jwk of body.keys) {
if (!jwk || typeof jwk !== 'object') continue
const { kid } = jwk as { kid?: unknown }
// A repeated kid is ambiguous, so neither key is trusted.
if (typeof kid !== 'string') continue
if (keys.has(kid)) keys.set(kid, {})
else keys.set(kid, jwk as Record<string, unknown>)
}
good = { fetchedAt: startedAt, keys }
return keys
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium (trigger unconfirmed) · unverified: TAP JWKS resolver buffers and retains unbounded provider responses

The new resolver limits refresh frequency and fetch time, but not decoded response bytes, key count, or retained metadata. It fully parses an HTTP success before validating keys and caches each raw JWK, even though the import uses only selected public fields.

Full finding

The new resolver limits refresh frequency and fetch time, but not decoded response bytes, key count, or retained metadata. It fully parses an HTTP success before validating keys and caches each raw JWK, even though the import uses only selected public fields. A configured provider that controls the response can make a syntactically valid key set expand in Fetch and retain its unused fields after successful verification. In a read-only Node 24.22.3 loopback benchmark (TSX_DISABLE_CACHE=1 node --expose-gc --import tsx --input-type=module, 96 visible cores), the pinned resolver used native Fetch through a test URL adapter. Against an uncompressed valid set with the same wire length, 1,199 gzip bytes expanded to 1,048,741 bytes: wall time was 4.9 to 9.2 ms, CPU 8.1 to 14.7 ms, peak RSS 136,524 to 140,044 KiB, and retained heap after GC 161,424 to 1,382,088 bytes. At 16,479 wire bytes expanding to 16,777,381 bytes, wall time was 4.3 to 45.6 ms, CPU 7.9 to 91.6 ms (11.6x), peak RSS 138,300 to 218,564 KiB, and retained heap 177,560 to 17,252,696 bytes (97x). Both sets resolved the public key, and both finishes were well within the shipped 5-second timeout. One cold or eligible refresh suffices to retain the snapshot, with no further provider traffic needed until it is replaced; stale expiry stops use, not retention. At the default 30-second cooldown, continuously triggered refreshes of the larger sample need about 1.98 MB/hour of provider body traffic, excluding headers and TLS. A sufficiently large response can pressure the process serving other requests. The proven actor is the configured publisher; ordinary TAP key holders can trigger eligible lookups but are not shown to control the response. The production memory budget and upstream decoded-body limits are unknown. Bound decoded bytes before JSON parsing, cap key count and field lengths, and cache only normalized public members.

First reported at 9873245; recheck at this head: still present.

Valid? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants