Repository navigation
feat(auth): bearer/API-key authentication - #635
Merged
Merged
Conversation
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
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Implements the #571 triage decision: bearer/API-key authentication as an
optional capability of the existing
authextension (packages/auth), not anew core YAML feature and not a new package.
AuthService.issueApiKey/listApiKeys/revokeApiKey/authenticateApiKey(
packages/auth/src/auth-core.ts), backed by a newauth_api_keystable(
auth-store.ts, newapi-key-store.ts). Issued keys areuak_<id>.<secret>:idis a public lookup identifier,secretis hashed at rest with the samescrypt derivation
auth-core.tsalready uses for passwords(
hashPassword/verifyPassword) rather than a fast digest — lookup isalways by
idfirst, never by hashing an incoming secret against everystored key (which would not scale and would let a flood of bogus bearer
tokens exhaust the shared password-hash concurrency budget).
auth: {bearer: {scopes: [...]}}(packages/core'sRouteAuthConfig+schemas/urlcode.schema.json), exclusive of theexisting session keys (
role/permission/verified/freshWithinSeconds/onDeny). The auth extension'sauthorize()gate checks theAuthorization: Bearerheader with RFC 6750-shaped responses: 401 with noerrorparam for missing/malformed, 401invalid_tokenfor unknown/wrong-secret/expired/revoked, 403
insufficient_scopenaming the missingscopes.
urlcode-authCLI:api-key-issue/api-key-list/api-key-revoke,matching the existing
--operator-file/JSON-stdin pattern.AuthServiceobject that already owns sessions, or the CLI above —matching how auth's other operator-supplied config already works.
corestill never importspackages/auth; core's addition is only thegeneric
bearerfield on the existing routeauth:schema, validatedagain by the extension's own
policySchemaexactly like every otherkey that schema already owns.
Design decisions
said to reuse the "scrypt-based hashing pattern," and this does — the
secret half is hashed exactly the way passwords are (
hashPassword, samebounded 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.secretsplit gets both: O(1) lookup byid, and thepart that actually needs to resist offline brute force (
secret) hashedexactly like a password.
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
FunctionContexta route'sown trusted
function/middlewarereceives is built from the originalrequest headers, not from anything an extension touched, and
Authorizationis already unconditionally stripped from it by an existing,deliberate boundary (
packages/core/src/extensions.ts: "Session andbearer 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 aboundary
SECURITY.mddocuments as deliberate, and it deserves its ownreviewed 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.
beareris exclusive of the session keys, not composable withrole/permission/etc. — a route is protected by a signed-in session orby an API key, never both, matching how the issue's example
(
auth: {bearer: {scopes: [...]}}) reads and keeping the gate simple.it does not interpret, hierarchy, or wildcard-expand them.
Test plan
packages/auth/test/auth-core.test.ts: issuance, verification, wrongsecret, 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 — 401missing header, 401 malformed scheme, 401 unknown/wrong-secret key
(with
WWW-Authenticate: Bearer error="invalid_token"), 403insufficient scope (with the RFC 6750 header and JSON body), allow
with matching scopes, 401 after revocation, 401 after expiry.
npm run typecheck(root andpackages/auth) — clean.npm run build(packages/auth) — clean.npx eslinton every changed file — clean.node scripts/check-core-boundaries.ts— clean (no optionalextension imports from core).
node scripts/check-workspace-links.ts— clean.npm run check:docs— clean (includes the closed-key-set check thatwould catch a stale key list in POLICIES.md/AI-AUTHORING.md).
npm run docs:reference/npm run docs:llms— regenerated,committed.
test/extensions.test.ts,test/schema-errors.test.ts— 33/33 pass.packages/authsuite (221 tests): 218 pass, 3 fail. All 3failures are pre-existing, unrelated tests (
password hashing queues briefly under contention,waitlist registration replies without waiting,recovery drill) that depend on wall-clock timing budgetsor 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_MSexists to accommodate onslow/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