diff --git a/crates/auth-sdk/src/lib.rs b/crates/auth-sdk/src/lib.rs index e397784d9..b77e59345 100644 --- a/crates/auth-sdk/src/lib.rs +++ b/crates/auth-sdk/src/lib.rs @@ -67,8 +67,9 @@ //! //! [`KeyCache`] caches a JWKS for any issuer. An unknown `kid` triggers one refetch, //! fetches happen at most every 30 seconds, and the last good keys survive an outage. -//! Each [`Issuer`] holds one for its own keys. [`Jws`] parses a token so it can be -//! checked by hand, as for Google ID tokens. +//! Each [`Issuer`] holds one for its own keys, and [`KeyCache::fixed`] holds a +//! [`KeySet`] that is never fetched, for pinned keys. [`Jws`] parses a token so it +//! can be checked by hand, as for Google ID tokens. //! //! # Errors //! diff --git a/docs/architecture/sdk.md b/docs/architecture/sdk.md index 5ffb99ffb..cfae31125 100644 --- a/docs/architecture/sdk.md +++ b/docs/architecture/sdk.md @@ -123,6 +123,11 @@ This handles signing key rotation: auth publishes the new key before it signs wi it, so tokens from both keys verify during the overlap. Both SDKs' key caches work with any JWKS URL, so auth also uses the Rust one for Google. +A key cache can also hold a fixed set, parsed by the rules above, for pinned keys, +offline verification and tests (`KeyCache::fixed(KeySet::parse(..))` in Rust, +`KeyCache.fixed(KeySet.parse(..))` in TypeScript). It is never fetched, so a `kid` +it lacks fails with `unknown_key`. + ## Scopes Scopes are space-separated strings on the wire (RFC 6749 §3.3), and each token is diff --git a/packages/auth/README.md b/packages/auth/README.md index 9c2f987d7..29a5131dd 100644 --- a/packages/auth/README.md +++ b/packages/auth/README.md @@ -228,6 +228,19 @@ await keys.verify(jws, jws.requireAlgorithm(['RS256'])); const claims: unknown = JSON.parse(new TextDecoder().decode(jws.payload)); ``` +To pin keys, or verify with no network, parse a key set and give it to +`KeyCache.fixed`, which never fetches, so a key ID the set lacks fails with +`unknown_key`. `KeySet.parse` takes the JSON text or the parsed document, skips keys +it cannot use (an unknown `kty` or `alg`, a `use` other than `sig`) and throws a +`keys` error on two keys with one `kid`: + +```ts +import { readFile } from 'node:fs/promises'; +import { KeyCache, KeySet } from '@piquel/auth'; + +const keys = KeyCache.fixed(KeySet.parse(await readFile('jwks.json', 'utf8'))); +``` + ## Development `src/protocol.ts` is generated from the Rust wire types by `just sdk-types`; do not diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts index b635a263e..34675f9c3 100644 --- a/packages/auth/src/index.ts +++ b/packages/auth/src/index.ts @@ -11,7 +11,8 @@ * `@piquel/auth/server` builds the routes and sessions of a server-side app on it, * and `@piquel/auth/browser` a public client for apps without a server. * - {@link KeyCache} verifies JWS signatures against any JWKS URL, refetching on key - * rotation without letting unknown key IDs flood the issuer. + * rotation without letting unknown key IDs flood the issuer, or against a pinned + * {@link KeySet} with {@link KeyCache.fixed}. * - Every failure is an {@link AuthError}, whose `toResponse()` answers with the * canonical `WWW-Authenticate` challenge. * @@ -30,7 +31,7 @@ export { export { AuthError, type AuthErrorCode, type AuthErrorDetail, type TokenReason } from './error.ts'; export type { Fetch } from './http.ts'; export { Issuer, type IssuerOptions } from './issuer.ts'; -export { Jws, KeyCache, type JwsHeader, type KeyCacheOptions } from './keys.ts'; +export { Jws, KeyCache, KeySet, type JwsHeader, type KeyCacheOptions } from './keys.ts'; export { Resource, type ResourceConfig } from './resource.ts'; export { Scopes, defineScopes } from './scope.ts'; export type { Clock } from './time.ts'; diff --git a/packages/auth/src/keys.ts b/packages/auth/src/keys.ts index ed6e22699..6a0441939 100644 --- a/packages/auth/src/keys.ts +++ b/packages/auth/src/keys.ts @@ -201,7 +201,16 @@ class SigningKey { } } -/** The usable keys of a JSON Web Key Set. */ +/** + * The usable keys of a JSON Web Key Set. Parse one to pin keys, or to verify offline, + * with {@link KeyCache.fixed}: + * + * ```ts + * const keys = KeySet.parse(await readFile('jwks.json', 'utf8')); + * keys.kids; // ['key-2026']: keys for encryption, or of an unknown type, are skipped + * const cache = KeyCache.fixed(keys); + * ``` + */ export class KeySet { /** Keys in document order. */ readonly #keys: SigningKey[]; @@ -210,20 +219,22 @@ export class KeySet { this.#keys = keys; } - /** The empty set a cache holds before its first fetch. */ + /** The empty set a cache holds before its first fetch, which verifies nothing. */ static readonly empty = new KeySet([]); /** - * Parses a key set. Keys this SDK cannot use are skipped, as RFC 7517 §5 asks: an - * unknown `kty` or `alg`, a `use` other than `sig`, no `kid`, or material that is - * not base64url. Throws `keys` errors when the document is not a key set - * (`invalid_document`), or two usable keys share a `kid` (`duplicate_key_id`). + * Parses a key set, from its JSON text or the parsed document. Keys this SDK cannot + * use are skipped, as RFC 7517 §5 asks: an unknown `kty` or `alg`, a `use` other + * than `sig`, no `kid`, or material that is not base64url. Throws `keys` errors when + * the document is not a key set (`invalid_document`), or two usable keys share a + * `kid` (`duplicate_key_id`). */ static parse(document: unknown): KeySet { - return KeySet.#decode(() => document); + // A JSON string is never a key set, so a string can only be the document's text. + return KeySet.#decode(() => (typeof document === 'string' ? json.parse(document) : document)); } - /** Parses a key set from a response body. */ + /** @internal Parses a key set from a response body. */ static read(reply: Reply): KeySet { return KeySet.#decode(() => reply.json()); } @@ -278,9 +289,18 @@ export type KeyCacheOptions = { clock?: Clock; }; +/** Where a cache's keys come from. */ +type Source = { + /** The JWKS URL. */ + url: string; + /** Client fetching it. */ + http: Http; +}; + /** - * A cache of an issuer's signing keys, usable with any JWKS URL. Share one per - * issuer: every verification shares its keys and fetch spacing. + * A cache of an issuer's signing keys, usable with any JWKS URL, or a fixed set with + * {@link KeyCache.fixed}. Share one per issuer: every verification shares its keys + * and fetch spacing. * * - An unknown `kid` triggers one refetch, then fails with `unknown_key`. * - Keys are fetched at most once every 30 seconds, whatever the reason, so unknown @@ -290,8 +310,8 @@ export type KeyCacheOptions = { * - A failed fetch keeps the last good keys, and still counts as a fetch. */ export class KeyCache { - readonly #url: string; - readonly #http: Http; + /** Where keys are fetched from; `undefined` for a fixed set. */ + readonly #source: Source | undefined; readonly #clock: Clock; /** Keys from the last successful fetch. */ #keys = KeySet.empty; @@ -305,12 +325,32 @@ export class KeyCache { #fetching: Promise | undefined; /** Keys fetched from `jwksUri` on first use. */ - constructor(jwksUri: string, options: KeyCacheOptions = {}) { - this.#url = jwksUri; - this.#http = new Http(options.fetch); + constructor(jwksUri: string, options?: KeyCacheOptions); + /** @internal A fixed set; {@link KeyCache.fixed} is its public name. */ + constructor(keys: KeySet); + constructor(source: string | KeySet, options: KeyCacheOptions = {}) { + if (typeof source === 'string') { + this.#source = { url: source, http: new Http(options.fetch) }; + } else { + this.#source = undefined; + this.#keys = source; + } this.#clock = options.clock ?? Date.now; } + /** + * Keys that never change and are never fetched, for tests, pinned keys and offline + * verification. A `kid` the set lacks fails with `unknown_key`. + * + * ```ts + * const keys = KeyCache.fixed(KeySet.parse(pinnedJwks)); + * await keys.verify(jws, jws.requireAlgorithm(['RS256'])); + * ``` + */ + static fixed(keys: KeySet): KeyCache { + return new KeyCache(keys); + } + /** * Verifies `jws`'s signature under `algorithm`, which the caller checked with * {@link Jws.requireAlgorithm}, with the key its `kid` names. Throws `unknown_key` @@ -346,7 +386,10 @@ export class KeyCache { return fresh ? this.#keys.find(kid) : undefined; } - /** The key named `kid`, fetching keys when they are stale or lack it and the last fetch is old enough. */ + /** + * The key named `kid`, fetching keys when they are stale or lack it and the last + * fetch is old enough. A fixed set is never fresh, so every lookup reads it here. + */ async #key(kid: string): Promise { const fresh = this.#fresh(kid); if (fresh !== undefined) return fresh; @@ -354,12 +397,16 @@ export class KeyCache { while (this.#fetching !== undefined) await this.#fetching; const fetched = this.#fresh(kid); if (fetched !== undefined) return fetched; + const source = this.#source; const now = this.#clock(); - if (this.#fetchedAt === undefined || now - this.#fetchedAt >= MIN_FETCH_INTERVAL) { + if ( + source !== undefined && + (this.#fetchedAt === undefined || now - this.#fetchedAt >= MIN_FETCH_INTERVAL) + ) { // Counted as failed until it succeeds. this.#fetchedAt = now; this.#failed = true; - const fetching = this.#refresh(now, kid); + const fetching = this.#refresh(source, now, kid); this.#fetching = fetching.then( () => undefined, () => undefined @@ -382,9 +429,9 @@ export class KeyCache { } /** Fetches the key set, keeping the old one if the fetch fails. */ - async #refresh(now: number, kid: string): Promise { + async #refresh(source: Source, now: number, kid: string): Promise { try { - const reply = (await this.#http.get(this.#url)).ok(); + const reply = (await source.http.get(source.url)).ok(); const keys = KeySet.read(reply); const lifetime = reply.maxAge === undefined ? DEFAULT_LIFETIME : reply.maxAge * 1000; this.#keys = keys; diff --git a/packages/auth/test/keys.test.ts b/packages/auth/test/keys.test.ts index ac70d40bc..581a1bf9f 100644 --- a/packages/auth/test/keys.test.ts +++ b/packages/auth/test/keys.test.ts @@ -1,7 +1,7 @@ -/** The key cache's fetch rules: one refetch per unknown kid, spacing, freshness and outages. */ +/** The key cache's fetch rules: one refetch per unknown kid, spacing, freshness and outages, and fixed sets. */ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { Jws, KeyCache } from '../src/index.ts'; +import { Jws, KeyCache, KeySet } from '../src/index.ts'; import * as base64 from '../src/base64.ts'; import { FakeFetch, JWKS_URI, ManualClock, outcome, vector } from './vectors.ts'; @@ -125,3 +125,14 @@ test('a weak RSA key verifies nothing, however its modulus is written', async () error: { code: 'invalid_token', reason: 'bad_signature' } }); }); + +test('a fixed set verifies its keys, and a kid it lacks is unknown', async () => { + const keys = KeyCache.fixed(KeySet.parse(jwks('rotation-before'))); + assert.deepEqual(await verify(keys, OLD), { ok: 'verified' }); + // No fetch can add a key, so a missing one is unknown rather than unavailable. + for (const missing of [NEW, UNKNOWN]) { + assert.deepEqual(await verify(keys, missing), { + error: { code: 'invalid_token', reason: 'unknown_key' } + }); + } +}); diff --git a/packages/auth/test/vectors.test.ts b/packages/auth/test/vectors.test.ts index 2d4257b6c..68c691456 100644 --- a/packages/auth/test/vectors.test.ts +++ b/packages/auth/test/vectors.test.ts @@ -1,8 +1,13 @@ /** Every case in tests/sdk-vectors, with the case's clock and a fake fetch. */ import assert from 'node:assert/strict'; import { describe, test } from 'node:test'; -import { Issuer, formatChallenge, parseChallenge, type BearerChallenge } from '../src/index.ts'; -import { KeySet } from '../src/keys.ts'; +import { + Issuer, + KeySet, + formatChallenge, + parseChallenge, + type BearerChallenge +} from '../src/index.ts'; import { DISCOVERY_URL, DOCUMENT, @@ -32,10 +37,11 @@ describe('discovery vectors', () => { describe('jwks vectors', () => { for (const vector of cases('jwks')) { test(vector.name, async () => { - const result = await outcome(() => - Promise.resolve({ kids: KeySet.parse(vector.input.jwks).kids }) - ); - assert.deepEqual(result, vector.expected); + // As the parsed document, and as its JSON text. + for (const document of [vector.input.jwks, JSON.stringify(vector.input.jwks)]) { + const result = await outcome(() => Promise.resolve({ kids: KeySet.parse(document).kids })); + assert.deepEqual(result, vector.expected); + } }); } });