Repository navigation
feat(server): credentialPolicy args-bag scan (#1529 L1) - #1535
Conversation
`sync-version` regenerates these from package.json on every build; the release commit (#1507) bumped package.json to 6.9.0 but the generated files weren't checked in. Catching them up so subsequent diffs stay focused on real changes. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Closes the buyer-args credential-smuggling vector class observed across three rounds of review on PR scope3data/agentic-adapters#248: top-level `<platform>_access_token`, nested `context.<platform>_access_token`, nested `ext.<platform>_access_token`. Default `'lax'` preserves existing behavior; opt into `'authInfo-only'` to scan args at any depth and reject with INVALID_REQUEST listing the offending paths. Patterns extensible via `credentialPolicy.patterns.extend` or fully replaceable via `credentialPolicy.patterns.matcher`. Per-tool overrides via `credentialPolicy.tools` for the rare legitimate buyer-creds tool. Rejection envelope reports paths only and bypasses `params.context` echo so the offending value does not round-trip through the response. This is L1 of the design at #1529. L2 (typed wire-spec args, brand at the operational boundary) ships separately after #1530 lands the OperationalPlatform interface. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…olicy # Conflicts: # src/lib/version.ts
|
Author here, but reviewing this with fresh eyes — feedback from the consumer side now that I've read the diff cold. What I really like
Concerns worth addressing in this PR1. Default patterns leave easy escapesThe defaults catch
Suggested defaults extension: /_token$/i, // catches bearer_token, id_token, session_token
/api[_-]?key/i, // catches api_key, apiKey, api-key
/^bearer$/i,…and make the camelCase patterns case-insensitive ( 2. The
|
Six concerns from the cold-eyes review:
1. **Default patterns broadened.** Previous set missed `bearer_token`,
`id_token`, `session_token`, `api_key`, bare `bearer`, and PascalCase
`AccessToken`. New defaults: `_token$/i`, `_secret$/i`, `_password$/i`,
`api[_-]?key/i`, `^bearer$/i`, `^accessToken$/i`, `^refreshToken$/i`.
Removed `_access_token$` (subsumed by `_token$`). camelCase patterns
are now case-insensitive.
2. **Identity-pivot vector documented as out-of-scope.** New section in
CTX-METADATA-SAFETY.md clarifies `credentialPolicy` does NOT cover
`request.account: { brand: 'attacker.com' }` — that's `AccountStore`
org-gating territory. Adopters who don't gate their resolver are not
protected by this scan.
3. **Typo'd `tools[]` keys throw at construction.** New
`validateCredentialPolicy(policy, knownToolNames)` runs after the
tool-registration loop and throws when `tools` references an
unregistered name. Catches `tools: { activte_signal: 'lax' }` before
first traffic so the silent-no-op-then-fail-closed footgun is gone.
4. **`field` dropped from rejection envelope.** Previous `field: hits[0]`
under-disclosed when several vectors were present together. Full
list lives in `details.credential_paths` only.
5. **`extend` + `matcher` both set throws.** Previous behavior silently
chose `matcher`. Now throws with a specific message at the helper
AND at construction time via `validateCredentialPolicy`.
6. **Doc round-N example payloads.** Concrete top-level / nested-context
/ nested-ext payloads in the safety guide so adopters reading cold
know what they're opting into.
Nit: `getCredentialPatterns` was a one-liner used once; inlined it.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Addressed in In this PR1. Default patterns broadened ✅ Punted on broader 2. Identity-pivot disclaimer ✅ 3. Typo'd 4. 5. 6. Round-N example payloads in docs ✅ Nit: Deferred (with reasons)v7 default flip to Lint rule for v5 Test results
Ready for re-review. |
|
Thanks for the thorough walkthrough — the six addressed items look well-scoped and the deferred items (v7 default flip, lint rule) are sensible punts with clear rationale. 36/36 + 1199/1199 with no regressions is a clean baseline for re-review. Generated by Claude Code |
|
Reviewed commit
Also caught that the upstream commit had a 5th fix (concurrent One note for reviewers: the dist in this repo isn't committed, so the test failures visible in the pre-push validation were a stale-dist artifact — source is correct and all 36 tests pass against a fresh build. Triaged by Claude Code. Session: https://claude.ai/code/session_01MmepaE5djoQso4ordzDyfP Generated by Claude Code |
|
Glad the walkthrough landed cleanly. Marking ready for re-review — let me know if anything surfaces on your pass. Generated by Claude Code |
|
Acknowledged — nothing to flag from my side on this pass. The design looks clean and the test coverage is solid. Ready for CODEOWNERS review. Generated by Claude Code |
|
Thanks — noted. No further action from this side; standing by for CODEOWNERS review. Triaged by Claude Code. Session: https://claude.ai/code/session_016EyH4GRNRLKRnMttiVYYaH Generated by Claude Code |
Three independent expert reviews surfaced eight items; addressing all.
**Protocol-correctness (ad-tech-protocol-expert)**
- Error code `INVALID_REQUEST` → `PERMISSION_DENIED`. AdCP request
schemas set `additionalProperties: true`, so a credential-bearing
payload is structurally well-formed. The rejection is a SELLER POLICY
violation, not schema drift. Spec text on `PERMISSION_DENIED`
("authenticated caller is not authorized for the requested action
under the seller's own policies") matches exactly. Mirrors the
existing buyer-agent-status rejection (`details.scope: 'agent'`,
`recovery: 'correctable'`).
**Security (security-reviewer)**
- `validateCredentialPolicy` now runs AFTER `get_adcp_capabilities`
registration so `tools: { get_adcp_capabilities: 'lax' }` doesn't
spuriously throw. The typo-check claim "the registered tool set is
authoritative" is now true for every tool.
- Walker hardened against accessor-property getters via
`Object.getOwnPropertyDescriptors` — credential-named getters are
flagged by name fail-closed, but the getter itself is never invoked.
Defends hand-built / proxy-trapped inputs against
throw-and-log-`params` DoS.
- Default patterns broadened to cover `^authorization$/i`, `^cookie$/i`,
`private[_-]?key/i` (HTTPSig / JWT signing-key flows; HTTP-header
smuggling). Documented exclusions: bare `key`/`principal`/`kid`/`pat`
(too short to risk false positives).
**Code quality (code-reviewer)**
- `/g` and `/y` flags stripped from adopter-supplied `extend` regexes.
`/credentials/gi` is a natural footgun — without stripping,
`RegExp.prototype.test` advances `lastIndex` and skips alternating
inputs across calls. `/i` and other intent-bearing flags preserved.
- `validateCredentialPolicy` and `resolveCredentialPolicyForTool`
marked `@internal` and dropped from the public `index.ts` exports.
Adopters can't construct `knownToolNames` outside the framework
anyway; cleaner public surface.
- New tests: getter defense, `/g`/`/y` stripping, `/i` preservation,
`matcher.path` parameter, idempotency-ordering pin (rejected
credential-bearing payload doesn't poison the replay cache —
retry with same idempotency_key + clean payload succeeds).
- Inlined single-method `ResolvedMatcher` interface as a function type.
43/43 credential-policy tests, 1238/1238 server suite, format /
typecheck / lint clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Ran the PR by three experts (security-reviewer, code-reviewer, ad-tech-protocol-expert) in parallel. Eight findings, all addressed in Protocol-correctness — error code change
The reviewer's spec citation was decisive: AdCP request schemas set New envelope shape: {
"code": "PERMISSION_DENIED",
"message": "Request args carry credential-shaped keys. Credentials must arrive on authInfo, not in the request body.",
"recovery": "correctable",
"details": {
"scope": "credentials",
"credential_paths": ["snap_access_token", "context.linkedin_access_token"]
}
}Mirrors the existing buyer-agent-status rejection ( Security findings
Code quality findings
New test coverage
DeferredThree items kept out of L1 scope, will file as follow-ups:
Test results post-fix
Ready for admin merge once CI greens. |
|
Acknowledged. The Triaged by Claude Code. Session: https://claude.ai/code/session_012Rg1koR28wmheYGdw8kbNT Generated by Claude Code |
* feat(server): WireSafe<T> brand + pickWireSpecFields (#1529 L2) Closes #1529. Ships the L2 half of the credential-discipline plan designed in `.context/operational-fanout-design.md`. L1 (#1535 credentialPolicy) catches credential-shaped keys at the buyer-facing dispatch boundary. L2 catches STRUCTURAL leakage at the operational fan-out boundary — storefront fan-out code that picks per-target args from a buyer request and forwards them upstream, where the buyer-facing scan has already passed. Three pieces: 1. **`WireSafe<T>` brand** via `unique symbol`. `{...buyerReq}` is `T`, not `WireSafe<T>` — so passing it where `WireSafe<T>` is required is a compile error. The brand is the load-bearing element: code that spreads a buyer request directly cannot satisfy it. 2. **`pickWireSpecFields(req, schemaName)`** — the canonical constructor of `WireSafe<T>`. Strips a buyer request to the AdCP wire-spec field allowlist for `schemaName`, returns a branded value. Drops top-level credential-shaped keys, unknown attacker payload, and anything not in the schema's `properties` list. 3. **`scrubExtensions(safe, options)`** — per-target ext/context scrub. Filters `ext` and `context` (which `pickWireSpecFields` keeps whole because they're wire-spec fields) to a caller- specified key allowlist, and merges in caller-injected values (storefront-resolved credentials/IDs). Returns `WireSafe<T>` so the brand survives the chain. **Codegen.** `scripts/generate-wire-spec-fields.ts` walks `schemas/cache/{version}/**/*-request.json` and emits `src/lib/server/wire-spec-fields.generated.ts` with field arrays per request type. Drift between the helper and the schema is structurally impossible — both are emitted from the same codegen pass. Restricted to fan-out-relevant request types (every mutating tool in `MUTATING_TASKS` + `get_media_buy_delivery`); 29 types total. **Source-compatible with #1530.** `OperationalPlatform` method signatures keep their existing plain-typed parameters (`request: UpdateMediaBuyRequest`). The brand is opt-in at the type level — adopters who use `pickWireSpecFields` get the safety benefit at the picking site (compile error if they accidentally spread buyer args into the variable typed `WireSafe<T>`). Adopters not using the helper see no behavior change. If we want to make the brand mandatory at the operational boundary in a future major bump, that's a v7 change. 17/17 wire-safe tests, 1291/1291 server suite, format / typecheck clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(wire-safe): expert review (#1544) Two reviewers flagged convergent and independent findings; addressing all in this commit. **Recursive credential scan** (security M1, the load-bearing fix). `pickWireSpecFields` keeps `ext` and `context` whole because they're wire-spec fields — but a buyer hiding credentials at depth (e.g. `ext.partner.partner_access_token`) survives both `pickWireSpecFields` and a top-level-only `scrubExtensions` filter. Round-4 vector waiting to happen. `scrubExtensions` now recursively scans `ext` and `context` values using the L1 credential-policy default pattern set, dropping credential-shaped keys at any depth. New `recursiveCredentialScan` option (default `true`) lets adopters opt out only when they've validated surviving shapes themselves. Two tests pin the behavior: nested credentials inside allowlisted top-level keys are dropped; top-level credentials are dropped when no allowlist is set. **Scan starts from depth 1 when an allowlist is set, depth 0 when not.** When the adopter explicitly allowlists `scope3_api_key` at the top level, the scan respects that affirmation — wouldn't second- guess by name. When no allowlist runs, the scan walks every depth including top-level. **`__type` phantom in codegen** (code-reviewer #1). Codegen now emits `{ fields: [...], __type: null as unknown as RequestType }` per entry, imported from `../types` (the index that aggregates core.generated + tools.generated). `pickWireSpecFields<K>` return type widened from `WireSafe<Record<string, unknown>>` to `WireSafe<(typeof WIRE_SPEC_FIELDS)[K]['__type']>` — adopters now get strong per-schema narrowing instead of generic Record. **Runtime-frozen arrays** (security L1). Codegen wraps each `fields` array in `Object.freeze` and the outer object too. Test asserts behavioral effect (length unchanged after push attempt) rather than mode-dependent throw. **`inject` JSDoc warning** (security L2). Explicit "values here MUST be storefront-derived, never read from the incoming buyer request." **Migration footgun warning** (security #8). CTX-METADATA-SAFETY.md now spells out: `pickWireSpecFields` ALONE doesn't close round-2/3 vectors. Adopters MUST chain with `scrubExtensions`. Diff-atomic migration recipe included. **`scrubExtensions` constraint widened** to `T extends object`. Was `T extends Record<string, unknown>` which fights `WireSafe<T>` brand. **SI naming fix in codegen.** `si-*` filenames now correctly emit `SI*` PascalCase (uppercase SI prefix matches `json-schema-to- typescript`'s acronym handling). 20/20 wire-safe tests pass (was 17, +3 new), 1287/1287 server suite, format / typecheck clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Closes #1529 L1. Opt-in
credentialPolicy: 'authInfo-only'scans every incoming request's args bag for credential-shaped keys at any depth and rejects withINVALID_REQUEST. Closes the buyer-args credential-smuggling vector class observed across three rounds of review on PR scope3data/agentic-adapters#248 — top-level<platform>_access_token, nestedcontext.<platform>_access_token, nestedext.<platform>_access_token— at the framework boundary, regardless of how each adapter'sextractContextreads from args.Default mode is
'lax'(back-compat). Opt in to enforce.Design
credentialPolicyaccepts a string shorthand or a config object:Default patterns:
_access_token$,_secret$,_password$,accessToken,refreshToken. Per the follow-up comment on #1529, the SDK ships configurable matchers from day one — adopters know their platform vocabulary best, and round-4 vectors land in adopter config rather than SDK releases.The rejection envelope reports paths only (no values) and bypasses
finalizesoinjectContextIntoResponsecan't echo the offendingparams.contextvalue back through the response. Tested explicitly.Hook point: in
toolHandler, before request schema validation. Uniform behavior acrossvalidation: 'off' | 'warn' | 'strict'.Files
src/lib/server/credential-policy.ts(new) —scanArgsForCredentials,resolveCredentialPolicyForTool,getCredentialPatterns,DEFAULT_CREDENTIAL_PATTERNS, typessrc/lib/server/create-adcp-server.ts—credentialPolicy?field onAdcpServerConfig, scan wired intotoolHandlersrc/lib/server/index.ts— re-exportstest/server-credential-policy.test.js(new) — 25 tests covering scanner, policy resolution, all three round-N vectors, no-echo invariant, per-tool override, extensible patternsdocs/guides/CTX-METADATA-SAFETY.md— defense-in-depth section.changeset/credential-policy-l1.md— minor bumpTest plan
npm run buildcleannpm run typecheckcleannpm run format:checkcleannpm run lintbaseline (no new errors)test/server-*.test.js) — no regressionWhat this is NOT
WireSafe<T>brand at the operational boundary) ships separately after First-class OperationalPlatform contract for in-process consumers (poller / fan-out / scheduled jobs) #1530'sOperationalPlatforminterface lands.'lax'is the default;'authInfo-only'is opt-in.🤖 Generated with Claude Code