Skip to content

feat(auth): bearer/API-key authentication - #635

Merged
jimhoyd merged 2 commits into
mainfrom
claude/bearer-api-key-auth-v2
Sep 24, 2026
Merged

jimhoyd merged 2 commits into
mainfrom
claude/bearer-api-key-auth-v2

Conversation

@jimhoyd

@jimhoyd jimhoyd commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator

Summary

Implements the #571 triage decision: bearer/API-key authentication as an
optional capability of the existing auth extension (packages/auth), not a
new core YAML feature and not a new package.

  • AuthService.issueApiKey/listApiKeys/revokeApiKey/authenticateApiKey
    (packages/auth/src/auth-core.ts), backed by a new auth_api_keys table
    (auth-store.ts, new api-key-store.ts). Issued keys are uak_<id>.<secret>:
    id is a public lookup identifier, secret is hashed at rest with the same
    scrypt derivation auth-core.ts already uses for passwords
    (hashPassword/verifyPassword) rather than a fast digest — lookup is
    always by id first, never by hashing an incoming secret against every
    stored key (which would not scale and would let a flood of bogus bearer
    tokens exhaust the shared password-hash concurrency budget).
  • Route short form auth: {bearer: {scopes: [...]}} (packages/core's
    RouteAuthConfig + schemas/urlcode.schema.json), exclusive of the
    existing session keys (role/permission/verified/freshWithinSeconds/
    onDeny). The auth extension's authorize() gate checks the
    Authorization: Bearer header with RFC 6750-shaped responses: 401 with no
    error param for missing/malformed, 401 invalid_token for unknown/
    wrong-secret/expired/revoked, 403 insufficient_scope naming the missing
    scopes.
  • urlcode-auth CLI: api-key-issue/api-key-list/api-key-revoke,
    matching the existing --operator-file/JSON-stdin pattern.
  • Operators issue/revoke keys outside route YAML, through the same
    AuthService object that already owns sessions, or the CLI above —
    matching how auth's other operator-supplied config already works.
  • core still never imports packages/auth; core's addition is only the
    generic bearer field on the existing route auth: schema, validated
    again by the extension's own policySchema exactly like every other
    key that schema already owns.

Design decisions

  • Lookup by public id, not a hash of the secret. The task description
    said to reuse the "scrypt-based hashing pattern," and this does — the
    secret half is hashed exactly the way passwords are (hashPassword, same
    bounded hash-slot budget). But a scrypt hash cannot be looked up by
    re-deriving it from an incoming key (scrypt is deliberately slow and only
    usable once you already know which stored row to compare against); doing
    that per-request against every stored key would not scale past a handful
    of keys and would let a flood of bogus bearer tokens exhaust the same
    bounded hash-slot budget passwords use. Sessions in this codebase already
    solve the "opaque, high-entropy token" case with a fast keyed digest
    looked up by that digest directly — but "peppered, at rest" (this task's
    wording) reads as intentionally not that fast-digest pattern for a
    credential meant to be issued to less-trusted machine callers. The
    Stripe-style id.secret split gets both: O(1) lookup by id, and the
    part that actually needs to resist offline brute force (secret) hashed
    exactly like a password.
  • Gate-only in this PR — no principal exposed to the handler. The
    triage decision says the extension should expose "the principal/scopes to
    the handler context." Implementing this found that no extension has any
    way to do that today
    : ExtensionInstance.authorize()/middleware()
    only ever gate a request (deny or allow); the FunctionContext a route's
    own trusted function/middleware receives is built from the original
    request headers, not from anything an extension touched, and
    Authorization is already unconditionally stripped from it by an existing,
    deliberate boundary (packages/core/src/extensions.ts: "Session and
    bearer credentials never cross into application guests"). Closing this
    cleanly needs a new, generic, core-owned mechanism — I traced one
    (a reserved header namespace, always stripped from inbound requests,
    that an extension can write into and the runtime then carries through to
    guestHeaders/context) but it's a new core semantic seam touching a
    boundary SECURITY.md documents as deliberate, and it deserves its own
    reviewed design rather than landing inside this PR. Filed as
    #618 with that traced
    design as a starting point. This PR's gate still fully enforces
    authentication and scopes (401 vs 403 exactly as specified) — only "the
    handler can read who authenticated" is deferred.
  • bearer is exclusive of the session keys, not composable with
    role/permission/etc. — a route is protected by a signed-in session or
    by an API key, never both, matching how the issue's example
    (auth: {bearer: {scopes: [...]}}) reads and keeping the gate simple.
  • Scopes are opaque, route-declared strings the gate checks for membership;
    it does not interpret, hierarchy, or wildcard-expand them.

Test plan

  • packages/auth/test/auth-core.test.ts: issuance, verification, wrong
    secret, malformed/unknown key, expiry, revocation, scope
    deduplication, last-used tracking, validation errors, raw secret never
    persisted to disk.
  • packages/auth/test/auth-handler.test.ts: authorize() gate — 401
    missing header, 401 malformed scheme, 401 unknown/wrong-secret key
    (with WWW-Authenticate: Bearer error="invalid_token"), 403
    insufficient scope (with the RFC 6750 header and JSON body), allow
    with matching scopes, 401 after revocation, 401 after expiry.
  • npm run typecheck (root and packages/auth) — clean.
  • npm run build (packages/auth) — clean.
  • npx eslint on every changed file — clean.
  • node scripts/check-core-boundaries.ts — clean (no optional
    extension imports from core).
  • node scripts/check-workspace-links.ts — clean.
  • npm run check:docs — clean (includes the closed-key-set check that
    would catch a stale key list in POLICIES.md/AI-AUTHORING.md).
  • npm run docs:reference / npm run docs:llms — regenerated,
    committed.
  • Targeted core regression: test/extensions.test.ts,
    test/schema-errors.test.ts — 33/33 pass.
  • Full packages/auth suite (221 tests): 218 pass, 3 fail. All 3
    failures are pre-existing, unrelated tests (password hashing queues briefly under contention, waitlist registration replies without waiting, recovery drill) that depend on wall-clock timing budgets
    or subprocess timeouts; this machine had a load average of ~200 from
    many other concurrent agent sessions while the suite ran. Re-running
    the waitlist test in isolation passed; the contention test's failure
    mode (2 of 6 concurrent scrypt derivations missing a 2s budget) is
    exactly what URLCODE_AUTH_HASH_WAIT_MS exists to accommodate on
    slow/shared runners, per its own doc comment. None of the three touch
    any file this PR changes. Relying on CI's isolated runners to confirm.

Closes / Refs

Refs #571 — scoped down as described above (principal exposure to the
handler context deferred to #618). Commented on #571 with what's left.

🤖 Generated with Claude Code

Add bearer/API-key authentication as an optional capability of the
existing auth extension, per the #571 triage decision: not a core YAML
feature, not a new package. The extension owns credential hashing,
expiry/revocation, scope enforcement and 401/403 shaping.

- AuthService.issueApiKey/listApiKeys/revokeApiKey/authenticateApiKey
  (auth-core.ts), backed by a new auth_api_keys table (auth-store.ts,
  api-key-store.ts). Keys are `uak_<id>.<secret>`: `id` is a public
  lookup identifier, `secret` is hashed at rest with the same scrypt
  derivation auth-core.ts already uses for passwords (hashPassword/
  verifyPassword) rather than a fast digest, so verification is always
  by looking up `id` first, never by hashing an incoming secret against
  every stored key.
- Route short form `auth: {bearer: {scopes: [...]}}` (packages/core
  RouteAuthConfig + schemas/urlcode.schema.json), exclusive of the
  existing session keys (role/permission/verified/freshWithinSeconds/
  onDeny). The auth extension's authorize() gate checks the
  Authorization: Bearer header with RFC 6750-shaped responses: 401 with
  no error param for missing/malformed, 401 invalid_token for unknown/
  wrong-secret/expired/revoked, 403 insufficient_scope naming the
  missing scopes.
- urlcode-auth CLI: api-key-issue/api-key-list/api-key-revoke, matching
  the existing operator-file/JSON-stdin pattern.
- Operators issue/revoke keys outside route YAML, via the same
  AuthService object that owns sessions or the CLI above.

Known gap, filed as #618 and documented in
packages/auth/README.md, SECURITY.md and docs/EXTENSIONS.md: no
extension today has a way to hand data forward into a route's own
function/middleware context, so the gate enforces auth/scopes
correctly but a protected route cannot yet read which key
authenticated it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-auth-v2

# Conflicts:
#	docs/YAML-REFERENCE.md
#	llms-full.txt
@jimhoyd
jimhoyd merged commit 6fc71f9 into main Sep 24, 2026
21 checks passed
@jimhoyd
jimhoyd deleted the claude/bearer-api-key-auth-v2 branch September 24, 2026 03:44
jimhoyd added a commit that referenced this pull request Sep 25, 2026
Add `auth: {bearer: {scopes, quota: {requests, window}}}`. Each API key
gets `requests` per `window` seconds, in the units core throttle uses.
The auth extension's authorize() gate counts a request only after the
key authenticates and covers the route's scopes. The request over budget
gets a 429 before the handler runs, with Retry-After and the IETF
RateLimit-Policy/RateLimit fields under the policy name "credential".

- AuthService.consumeApiKeyQuota counts by a SHA-256 of the key id and
  the budget, never the secret. It uses the sign-in attempt counter's
  auth_attempts table and fixed window: refusals are not counted,
  expired rows are swept, and the 100,000-row ceiling applies. The count
  survives a restart and is shared by processes on one host, which
  serialize on the SQLite file. It is not shared across hosts. A store
  failure is a 503; the request is never let through uncounted.
- Core is unchanged apart from the route short-form mirror
  (RouteAuthConfig and schemas/urlcode.schema.json), as with #635.
  Core throttle still counts per client before auth and remains the
  guard against unauthenticated floods.
- Tests cover: under and over quota, Retry-After and RateLimit fields,
  separate credentials and budgets, 403 not counted, window reset,
  restart on the same file, a second OS process sharing the count, and
  load-time refusal of bad values.

Follow-ups filed: #701 (throttle replaces RateLimit fields on an
extension 429), #702 (auth short-form errors report "must be true"),
#703 (per-key budget override, RateLimit fields on allowed responses).

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

1 participant