fix(relay-auth): close 5 pre-production security findings (F1–F5)

F1 (HIGH): bind step-up freshness to the required method (stepUpMethod) so a
  login-time or weaker (TOTP) factor can no longer satisfy a passkey requirement.
F2 (HIGH): make the step-up gate host-driven and fail-closed on connect+reattach
  (deny when policy.required and the principal is missing/stale/wrong-method).
F3 (MED): bind the WebAuthn assertion to the stored credential (credentialId
  cross-check + forward publicKey/credentialId to the verifier).
F4 (LOW): make verifyDpopProof totally fail-safe (no unhandled throw), wrap the
  authz boundary into a clean audited 401, and validate cnfJkt format at issue.
F5 (LOW): return newSignCount from finishAuthentication so the caller can persist
  the advanced counter (WebAuthn clone detection).

All fixes ship regression tests. relay-auth: 122 tests green, tsc clean.
This commit is contained in:
Yaojia Wang
2026-07-02 16:41:18 +02:00
parent 1529d2c94c
commit a09c131539
15 changed files with 248 additions and 60 deletions

View File

@@ -54,9 +54,15 @@ async function coreAuthorize(
} catch { } catch {
return { outcome: deny(401, 'invalid_capability_token') } return { outcome: deny(401, 'invalid_capability_token') }
} }
// verifyDpopProof is fail-safe, but guard defensively so an unexpected throw becomes a single
// audited deny (emitted once by onUpgrade) rather than an unhandled exception (Finding-4).
try {
if (!(await verifyDpopProof(token, dpop, now))) { if (!(await verifyDpopProof(token, dpop, now))) {
return { outcome: deny(401, 'dpop_proof_failed') } return { outcome: deny(401, 'dpop_proof_failed') }
} }
} catch {
return { outcome: deny(401, 'dpop_proof_failed') }
}
if (await revocation.isRevoked(token.jti)) return { outcome: deny(403, 'token_revoked') } if (await revocation.isRevoked(token.jti)) return { outcome: deny(403, 'token_revoked') }
if (!token.rights.includes(req.requiredRight)) return { outcome: deny(403, 'insufficient_rights') } if (!token.rights.includes(req.requiredRight)) return { outcome: deny(403, 'insufficient_rights') }
if (token.host !== req.requestedHostId) return { outcome: deny(403, 'host_scope_mismatch') } if (token.host !== req.requestedHostId) return { outcome: deny(403, 'host_scope_mismatch') }

View File

@@ -11,6 +11,7 @@ export type CapabilityErrorReason =
| 'bad_signature' | 'bad_signature'
| 'replayed' | 'replayed'
| 'no_cnf' | 'no_cnf'
| 'bad_cnf'
export class CapabilityError extends Error { export class CapabilityError extends Error {
readonly reason: CapabilityErrorReason readonly reason: CapabilityErrorReason

View File

@@ -49,6 +49,8 @@ export async function issueCapabilityToken(
for (const r of a.rights) CapabilityRightSchema.parse(r) for (const r of a.rights) CapabilityRightSchema.parse(r)
if (a.rights.length === 0) throw new CapabilityError('malformed', 'rights must be non-empty') if (a.rights.length === 0) throw new CapabilityError('malformed', 'rights must be non-empty')
if (a.cnfJkt.length === 0) throw new CapabilityError('no_cnf') if (a.cnfJkt.length === 0) throw new CapabilityError('no_cnf')
// A base64url SHA-256 JWK thumbprint is exactly 43 chars of [A-Za-z0-9_-] (hardening, Finding-4).
if (!/^[A-Za-z0-9_-]{43}$/.test(a.cnfJkt)) throw new CapabilityError('bad_cnf')
const ttl = Math.max(a.ttlSeconds, CONNECT_TOKEN_MIN_TTL_SEC) const ttl = Math.max(a.ttlSeconds, CONNECT_TOKEN_MIN_TTL_SEC)
const body: TokenBody = { const body: TokenBody = {

View File

@@ -116,6 +116,10 @@ export async function verifyDpopProof(
dpop: DpopContext, dpop: DpopContext,
now: number, now: number,
): Promise<boolean> { ): Promise<boolean> {
// TOTALLY fail-safe (Finding-4): any thrown error — from readCnfJkt, jwkThumbprint,
// importEd25519PublicRaw, or any decode — becomes `false`, never a rejected promise, so the
// INV15 gate always denies through an audited path instead of an unhandled exception.
try {
const expectedJkt = readCnfJkt(token) const expectedJkt = readCnfJkt(token)
const parts = dpop.proofJws.split('.') const parts = dpop.proofJws.split('.')
if (parts.length !== 3) return false if (parts.length !== 3) return false
@@ -148,6 +152,9 @@ export async function verifyDpopProof(
} }
if (!(await verifyEd25519(pubKey, sig, signed))) return false if (!(await verifyEd25519(pubKey, sig, signed))) return false
return rememberDpop(payload.jti, payload.iat + DPOP_MAX_AGE_SEC, now) return rememberDpop(payload.jti, payload.iat + DPOP_MAX_AGE_SEC, now)
} catch {
return false
}
} }
/** Build a DPoP proof (client-side helper; also used by tests). Signs with the ephemeral key. */ /** Build a DPoP proof (client-side helper; also used by tests). Signs with the ephemeral key. */

View File

@@ -124,10 +124,14 @@ export async function runEnforcement(
await emitDeny(deps, ctx, base, 'too_many_sessions', now) await emitDeny(deps, ctx, base, 'too_many_sessions', now)
return deny(403, 'too_many_sessions') return deny(403, 'too_many_sessions')
} }
// 5. Step-up gate (Finding-3, v0.10) — only when a session principal is present. // 5. Step-up gate (Finding-3/F1/F2) — HOST-DRIVEN and FAIL-CLOSED on connect AND reattach.
if (ctx.principal !== null) { // When a host REQUIRES step-up, DENY unless an authenticated principal proves a FRESH step-up
// of the required method. A missing host, a null principal, or a stale/wrong-method step-up all
// fail closed. When the policy does not require step-up, this gate is a no-op.
const host = await deps.hosts.getById(outcome.hostId) const host = await deps.hosts.getById(outcome.hostId)
if (host !== null && needsStepUp(ctx.principal, deps.stepUpPolicyFor(host), now)) { const policy = deps.stepUpPolicyFor(host as HostRecord)
if (policy.required) {
if (host === null || ctx.principal === null || needsStepUp(ctx.principal, policy, now)) {
await emitDeny(deps, ctx, 'stepup', 'step_up_required', now) await emitDeny(deps, ctx, 'stepup', 'step_up_required', now)
return deny(403, 'step_up_required') return deny(403, 'step_up_required')
} }

View File

@@ -14,14 +14,22 @@ import type { AuthMethod, AuthenticatedPrincipal, StepUpPolicy } from '../../typ
export const DEFAULT_STEPUP_MAX_AGE_SECONDS = 300 as const export const DEFAULT_STEPUP_MAX_AGE_SECONDS = 300 as const
/** Per-host step-up freshness requirement (default: recent passkey step-up). */ /** Per-host step-up freshness requirement (default: recent passkey step-up REQUIRED). */
export function policyForHost(_host: HostRecord): StepUpPolicy { export function policyForHost(_host: HostRecord): StepUpPolicy {
return { maxAgeSeconds: DEFAULT_STEPUP_MAX_AGE_SECONDS, requiredMethod: 'passkey' } return { required: true, maxAgeSeconds: DEFAULT_STEPUP_MAX_AGE_SECONDS, requiredMethod: 'passkey' }
}
/** v0.9 "never required" default: step-up gate is off (used until per-host tiers exist). */
export const NO_STEPUP_POLICY: StepUpPolicy = {
required: false,
maxAgeSeconds: DEFAULT_STEPUP_MAX_AGE_SECONDS,
requiredMethod: 'passkey',
} }
/** /**
* true when step-up is required: never stepped up, OR the last step-up is stale, OR the required * true when step-up is required: never stepped up, OR the last step-up is stale, OR the LAST step-up
* method is not present in `amr` — i.e. a fresh login alone does NOT satisfy it. * was not performed with the required method (method-binding, F1) — i.e. neither a fresh login nor a
* weaker (e.g. TOTP) step-up satisfies a passkey requirement.
*/ */
export function needsStepUp( export function needsStepUp(
principal: AuthenticatedPrincipal, principal: AuthenticatedPrincipal,
@@ -30,16 +38,19 @@ export function needsStepUp(
): boolean { ): boolean {
if (principal.stepUpAt === null) return true if (principal.stepUpAt === null) return true
if (now - principal.stepUpAt > policy.maxAgeSeconds) return true if (now - principal.stepUpAt > policy.maxAgeSeconds) return true
if (!principal.amr.includes(policy.requiredMethod)) return true if ((principal.stepUpMethod ?? null) !== policy.requiredMethod) return true
return false return false
} }
/** Returns a NEW principal with `stepUpAt = now` and `method` added to `amr` (immutable). */ /**
* Returns a NEW principal recording a fresh step-up: `stepUpAt = now`, `stepUpMethod = method`, and
* `method` appended to `amr` (audit trail). Immutable — the original is untouched.
*/
export function recordStepUp( export function recordStepUp(
principal: AuthenticatedPrincipal, principal: AuthenticatedPrincipal,
method: AuthMethod, method: AuthMethod,
now: number, now: number,
): AuthenticatedPrincipal { ): AuthenticatedPrincipal {
const amr = principal.amr.includes(method) ? principal.amr : [...principal.amr, method] const amr = principal.amr.includes(method) ? principal.amr : [...principal.amr, method]
return { ...principal, amr, stepUpAt: now } return { ...principal, amr, stepUpAt: now, stepUpMethod: method }
} }

View File

@@ -32,16 +32,19 @@ export async function finishAuthentication(
origin: string, origin: string,
verifier: WebAuthnVerifier, verifier: WebAuthnVerifier,
now: number, now: number,
): Promise<AuthenticatedPrincipal> { ): Promise<{ principal: AuthenticatedPrincipal; newSignCount: number }> {
if (resp.clientChallenge !== expectedChallenge) throw new WebAuthnError('challenge mismatch') if (resp.clientChallenge !== expectedChallenge) throw new WebAuthnError('challenge mismatch')
if (resp.origin !== origin) throw new WebAuthnError('origin mismatch') if (resp.origin !== origin) throw new WebAuthnError('origin mismatch')
if (resp.rpId !== rpId) throw new WebAuthnError('rpId mismatch') if (resp.rpId !== rpId) throw new WebAuthnError('rpId mismatch')
if (resp.credentialId !== cred.credentialId) throw new WebAuthnError('credential id mismatch')
const result = await verifier.verifyAuthentication( const result = await verifier.verifyAuthentication(
resp, resp,
expectedChallenge, expectedChallenge,
rpId, rpId,
origin, origin,
cred.publicKey,
cred.credentialId,
cred.signCount, cred.signCount,
) )
if (!result.verified) throw new WebAuthnError('assertion not verified') if (!result.verified) throw new WebAuthnError('assertion not verified')
@@ -49,7 +52,7 @@ export async function finishAuthentication(
throw new WebAuthnError('signCount regression (cloned authenticator)') throw new WebAuthnError('signCount regression (cloned authenticator)')
} }
return { const principal: AuthenticatedPrincipal = {
kind: 'human', kind: 'human',
accountId: cred.accountId, accountId: cred.accountId,
principalId: cred.credentialId, principalId: cred.credentialId,
@@ -57,4 +60,5 @@ export async function finishAuthentication(
authAt: now, authAt: now,
stepUpAt: null, stepUpAt: null,
} }
return { principal, newSignCount: result.newSignCount }
} }

View File

@@ -28,6 +28,7 @@ export interface AuthenticationResponse {
readonly clientChallenge: string readonly clientChallenge: string
readonly origin: string readonly origin: string
readonly rpId: string readonly rpId: string
readonly credentialId: string
} }
export interface RegistrationVerification { export interface RegistrationVerification {
@@ -54,6 +55,8 @@ export interface WebAuthnVerifier {
expectedChallenge: string, expectedChallenge: string,
rpId: string, rpId: string,
origin: string, origin: string,
credentialPublicKey: Uint8Array,
expectedCredentialId: string,
storedSignCount: number, storedSignCount: number,
): Promise<AuthenticationVerification> ): Promise<AuthenticationVerification>
} }

View File

@@ -34,6 +34,7 @@ export interface AuthenticatedPrincipal {
readonly amr: readonly AuthMethod[] // methods satisfied this session (for step-up, T8) readonly amr: readonly AuthMethod[] // methods satisfied this session (for step-up, T8)
readonly authAt: number // epoch seconds of last successful auth (login freshness) readonly authAt: number // epoch seconds of last successful auth (login freshness)
readonly stepUpAt: number | null // epoch seconds of last step-up (T8 freshness); null = never readonly stepUpAt: number | null // epoch seconds of last step-up (T8 freshness); null = never
readonly stepUpMethod?: AuthMethod | null // method used for the LAST step-up (F1 method-binding); absent/null ⇒ none
} }
/** /**
@@ -44,6 +45,7 @@ export interface AuthenticatedPrincipal {
export const CAP_TOKEN_SUB_IS_ACCOUNT_ID = true as const export const CAP_TOKEN_SUB_IS_ACCOUNT_ID = true as const
export interface StepUpPolicy { export interface StepUpPolicy {
readonly required: boolean
readonly maxAgeSeconds: number readonly maxAgeSeconds: number
readonly requiredMethod: AuthMethod readonly requiredMethod: AuthMethod
} }
@@ -141,11 +143,13 @@ export const AuthenticatedPrincipalSchema = z
amr: z.array(AuthMethodSchema).readonly(), amr: z.array(AuthMethodSchema).readonly(),
authAt: z.number().int().nonnegative(), authAt: z.number().int().nonnegative(),
stepUpAt: z.number().int().nonnegative().nullable(), stepUpAt: z.number().int().nonnegative().nullable(),
stepUpMethod: AuthMethodSchema.nullable().optional(),
}) })
.strict() .strict()
export const StepUpPolicySchema = z export const StepUpPolicySchema = z
.object({ .object({
required: z.boolean(),
maxAgeSeconds: z.number().int().nonnegative(), maxAgeSeconds: z.number().int().nonnegative(),
requiredMethod: AuthMethodSchema, requiredMethod: AuthMethodSchema,
}) })

View File

@@ -11,6 +11,7 @@ import {
} from '../src/capability/verify.js' } from '../src/capability/verify.js'
import { jwkThumbprint } from '../src/crypto/thumbprint.js' import { jwkThumbprint } from '../src/crypto/thumbprint.js'
import { CapabilityError } from '../src/capability/errors.js' import { CapabilityError } from '../src/capability/errors.js'
import { encodeBase64UrlBytes } from 'relay-contracts'
import { setupP5SigningKey, makeEphemeral, principal, uuid } from './_helpers.js' import { setupP5SigningKey, makeEphemeral, principal, uuid } from './_helpers.js'
const NOW = 1_700_000_000 const NOW = 1_700_000_000
@@ -150,5 +151,31 @@ describe('capability token (§4.3)', () => {
expect(await verifyDpopProof(tok, { proofJws: proof, htu, htm: 'GET' }, NOW)).toBe(true) expect(await verifyDpopProof(tok, { proofJws: proof, htu, htm: 'GET' }, NOW)).toBe(true)
expect(await verifyDpopProof(tok, { proofJws: proof, htu, htm: 'GET' }, NOW)).toBe(false) expect(await verifyDpopProof(tok, { proofJws: proof, htu, htm: 'GET' }, NOW)).toBe(false)
}) })
// F4: a proof whose jwk.x decodes to a NON-32-byte blob makes importEd25519PublicRaw throw.
// verifyDpopProof must be TOTALLY fail-safe and RESOLVE to false, never reject.
it('resolves false (never throws) when the proof key is not a valid 32-byte Ed25519 key', async () => {
// A 16-byte "key" — importEd25519PublicRaw will reject this raw length.
const shortBlob = new Uint8Array(16).fill(7)
// cnf.jkt is computed over the SAME 16-byte blob so the thumbprint check passes and
// execution reaches the risky importEd25519PublicRaw call.
const cnfJkt = await jwkThumbprint(shortBlob)
const raw = await issueFor(signingKey, { cnfJkt })
const tok = await verifyCapabilityToken(raw, AUD, NOW)
const htu = 'https://alice.term.example.com/ws'
const enc = (o: unknown) => encodeBase64UrlBytes(new TextEncoder().encode(JSON.stringify(o)))
const h = enc({ typ: 'dpop+ed25519', jwk: { crv: 'Ed25519', kty: 'OKP', x: encodeBase64UrlBytes(shortBlob) } })
const p = enc({ htu, htm: 'GET', jti: uuid(), iat: NOW })
const s = encodeBase64UrlBytes(new Uint8Array(64)) // any signature bytes
const proofJws = `${h}.${p}.${s}`
const verify = verifyDpopProof(tok, { proofJws, htu, htm: 'GET' }, NOW)
await expect(verify).resolves.toBe(false)
})
})
it('rejects a malformed cnf.jkt at issue (not a 43-char base64url thumbprint)', async () => {
await expect(issueFor(signingKey, { cnfJkt: 'short' })).rejects.toMatchObject({ reason: 'bad_cnf' })
}) })
}) })

View File

@@ -20,7 +20,7 @@ const NOW = 1_700_000_000
const AUD_A = 'alice.term.example.com' const AUD_A = 'alice.term.example.com'
const ORIGIN_A = `https://${AUD_A}` const ORIGIN_A = `https://${AUD_A}`
const ALLOWED = [ORIGIN_A] const ALLOWED = [ORIGIN_A]
const NEVER_REQUIRED: StepUpPolicy = { maxAgeSeconds: Number.MAX_SAFE_INTEGER, requiredMethod: 'passkey' } const NEVER_REQUIRED: StepUpPolicy = { required: false, maxAgeSeconds: Number.MAX_SAFE_INTEGER, requiredMethod: 'passkey' }
describe('enforcement onUpgrade/onReattach (T12)', () => { describe('enforcement onUpgrade/onReattach (T12)', () => {
let signingKey: CryptoKey let signingKey: CryptoKey
@@ -126,8 +126,8 @@ describe('enforcement onUpgrade/onReattach (T12)', () => {
expect(out).toMatchObject({ ok: false, status: 403, reason: 'cross_tenant_session' }) expect(out).toMatchObject({ ok: false, status: 403, reason: 'cross_tenant_session' })
}) })
describe('v0.10 step-up augmentation (Finding-3)', () => { describe('v0.10 step-up augmentation (Finding-3, F1/F2)', () => {
const STRICT: StepUpPolicy = { maxAgeSeconds: 300, requiredMethod: 'passkey' } const STRICT: StepUpPolicy = { required: true, maxAgeSeconds: 300, requiredMethod: 'passkey' }
it('fresh login but stale step-up → 403 step_up_required at onUpgrade', async () => { it('fresh login but stale step-up → 403 step_up_required at onUpgrade', async () => {
deps = { ...deps, stepUpPolicyFor: () => STRICT } deps = { ...deps, stepUpPolicyFor: () => STRICT }
@@ -141,10 +141,26 @@ describe('enforcement onUpgrade/onReattach (T12)', () => {
it('after a fresh step-up the same request → ok:true', async () => { it('after a fresh step-up the same request → ok:true', async () => {
deps = { ...deps, stepUpPolicyFor: () => STRICT } deps = { ...deps, stepUpPolicyFor: () => STRICT }
const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW }) const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
const steppedUp = principal('acct-A', { authAt: NOW, stepUpAt: NOW, amr: ['passkey', 'stepup'] }) const steppedUp = principal('acct-A', { authAt: NOW, stepUpAt: NOW, amr: ['passkey', 'stepup'], stepUpMethod: 'passkey' })
expect(needsStepUp(steppedUp, STRICT, NOW)).toBe(false) expect(needsStepUp(steppedUp, STRICT, NOW)).toBe(false)
const out = await onUpgrade(ctxFor(b, { principal: steppedUp }), deps, ALLOWED, NOW) const out = await onUpgrade(ctxFor(b, { principal: steppedUp }), deps, ALLOWED, NOW)
expect(out.ok).toBe(true) expect(out.ok).toBe(true)
}) })
it('STRICT (required) policy + principal:null → 403 step_up_required (F2 fail-closed)', async () => {
deps = { ...deps, stepUpPolicyFor: () => STRICT }
const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
const out = await onUpgrade(ctxFor(b, { principal: null }), deps, ALLOWED, NOW)
expect(out).toMatchObject({ ok: false, status: 403, reason: 'step_up_required' })
expect(audit.events.some((e) => e.action === 'stepup' && e.outcome === 'deny')).toBe(true)
})
it('required:false policy + principal:null → allow (non-step-up host preserved)', async () => {
deps = { ...deps, stepUpPolicyFor: () => NEVER_REQUIRED }
const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
const out = await onUpgrade(ctxFor(b, { principal: null }), deps, ALLOWED, NOW)
expect(out.ok).toBe(true)
expect(audit.events.some((e) => e.outcome === 'allow')).toBe(true)
})
}) })
}) })

View File

@@ -1,10 +1,10 @@
import { describe, it, expect } from 'vitest' import { describe, it, expect } from 'vitest'
import { needsStepUp, recordStepUp, policyForHost } from '../src/human/stepup/stepup.js' import { needsStepUp, recordStepUp, policyForHost, NO_STEPUP_POLICY } from '../src/human/stepup/stepup.js'
import type { StepUpPolicy } from '../src/types.js' import type { StepUpPolicy } from '../src/types.js'
import { principal, makeHost, uuid } from './_helpers.js' import { principal, makeHost, uuid } from './_helpers.js'
const NOW = 1_700_000_000 const NOW = 1_700_000_000
const POLICY: StepUpPolicy = { maxAgeSeconds: 300, requiredMethod: 'passkey' } const POLICY: StepUpPolicy = { required: true, maxAgeSeconds: 300, requiredMethod: 'passkey' }
describe('step-up before session open (T8, Finding-3)', () => { describe('step-up before session open (T8, Finding-3)', () => {
it('fresh login but stepUpAt=null → needsStepUp true (login ≠ step-up)', () => { it('fresh login but stepUpAt=null → needsStepUp true (login ≠ step-up)', () => {
@@ -13,34 +13,61 @@ describe('step-up before session open (T8, Finding-3)', () => {
}) })
it('stale step-up (older than maxAgeSeconds) → true', () => { it('stale step-up (older than maxAgeSeconds) → true', () => {
const p = principal('acct-A', { stepUpAt: NOW - 301, amr: ['passkey', 'stepup'] }) const p = principal('acct-A', { stepUpAt: NOW - 301, amr: ['passkey', 'stepup'], stepUpMethod: 'passkey' })
expect(needsStepUp(p, POLICY, NOW)).toBe(true) expect(needsStepUp(p, POLICY, NOW)).toBe(true)
}) })
it('required method absent from amr → true', () => { it('required method not the LAST step-up method → true', () => {
const p = principal('acct-A', { stepUpAt: NOW, amr: ['totp'] }) const p = principal('acct-A', { stepUpAt: NOW, amr: ['totp'], stepUpMethod: 'totp' })
expect(needsStepUp(p, POLICY, NOW)).toBe(true) expect(needsStepUp(p, POLICY, NOW)).toBe(true)
}) })
it('fresh passkey step-up → false', () => { it('fresh passkey step-up satisfies passkey policy → false (F1)', () => {
const p = principal('acct-A', { stepUpAt: NOW, amr: ['passkey'] }) const p = principal('acct-A', { stepUpAt: NOW, amr: ['passkey'], stepUpMethod: 'passkey' })
expect(needsStepUp(p, POLICY, NOW)).toBe(false) expect(needsStepUp(p, POLICY, NOW)).toBe(false)
}) })
it('fresh TOTP step-up does NOT satisfy passkey policy → true (F1 factor-downgrade regression)', () => {
// A weaker (TOTP) step-up performed just now must not satisfy a passkey requirement, even though
// it is fresh — the required method itself must be the LAST step-up.
const p = principal('acct-A', { stepUpAt: NOW, amr: ['passkey', 'totp'], stepUpMethod: 'totp' })
expect(needsStepUp(p, POLICY, NOW)).toBe(true)
})
it('login-time passkey in amr but no step-up (stepUpMethod null) → true (login ≠ step-up)', () => {
const p = principal('acct-A', { stepUpAt: NOW, amr: ['passkey'], stepUpMethod: null })
expect(needsStepUp(p, POLICY, NOW)).toBe(true)
})
it('recordStepUp returns a NEW principal (immutable), original untouched', () => { it('recordStepUp returns a NEW principal (immutable), original untouched', () => {
const p = principal('acct-A', { stepUpAt: null, amr: ['totp'] }) const p = principal('acct-A', { stepUpAt: null, amr: ['totp'], stepUpMethod: 'totp' })
const stepped = recordStepUp(p, 'passkey', NOW) const stepped = recordStepUp(p, 'passkey', NOW)
expect(stepped).not.toBe(p) expect(stepped).not.toBe(p)
expect(p.stepUpAt).toBeNull() expect(p.stepUpAt).toBeNull()
expect(p.amr).toEqual(['totp']) expect(p.amr).toEqual(['totp'])
expect(p.stepUpMethod).toBe('totp')
expect(stepped.stepUpAt).toBe(NOW) expect(stepped.stepUpAt).toBe(NOW)
expect(stepped.amr).toContain('passkey') expect(stepped.amr).toContain('passkey')
expect(needsStepUp(stepped, POLICY, NOW)).toBe(false) expect(needsStepUp(stepped, POLICY, NOW)).toBe(false)
}) })
it('policyForHost yields a passkey freshness requirement', () => { it('recordStepUp stamps stepUpMethod with the method used (F1)', () => {
const p = principal('acct-A', { stepUpAt: null, amr: ['passkey'], stepUpMethod: null })
const stepped = recordStepUp(p, 'passkey', NOW)
expect(stepped.stepUpMethod).toBe('passkey')
expect(stepped.stepUpAt).toBe(NOW)
})
it('policyForHost yields a REQUIRED passkey freshness requirement', () => {
const policy = policyForHost(makeHost('acct-A', uuid())) const policy = policyForHost(makeHost('acct-A', uuid()))
expect(policy.required).toBe(true)
expect(policy.requiredMethod).toBe('passkey') expect(policy.requiredMethod).toBe('passkey')
expect(policy.maxAgeSeconds).toBeGreaterThan(0) expect(policy.maxAgeSeconds).toBeGreaterThan(0)
}) })
it('NO_STEPUP_POLICY is the v0.9 never-required default', () => {
expect(NO_STEPUP_POLICY.required).toBe(false)
expect(NO_STEPUP_POLICY.requiredMethod).toBe('passkey')
expect(NO_STEPUP_POLICY.maxAgeSeconds).toBeGreaterThan(0)
})
}) })

View File

@@ -29,7 +29,7 @@ const NOW = 1_700_000_000
const AUD_A = 'alice.term.example.com' const AUD_A = 'alice.term.example.com'
const AUD_B = 'bob.term.example.com' const AUD_B = 'bob.term.example.com'
const ORIGIN_A = `https://${AUD_A}` const ORIGIN_A = `https://${AUD_A}`
const NEVER: StepUpPolicy = { maxAgeSeconds: Number.MAX_SAFE_INTEGER, requiredMethod: 'passkey' } const NEVER: StepUpPolicy = { required: false, maxAgeSeconds: Number.MAX_SAFE_INTEGER, requiredMethod: 'passkey' }
describe('PERMANENT TRIPWIRE — device A can never reach host B (INV1)', () => { describe('PERMANENT TRIPWIRE — device A can never reach host B (INV1)', () => {
let signingKey: CryptoKey let signingKey: CryptoKey

View File

@@ -0,0 +1,60 @@
import { describe, it, expect } from 'vitest'
import {
AuthenticatedPrincipalSchema,
StepUpPolicySchema,
type AuthenticatedPrincipal,
type StepUpPolicy,
} from '../src/types.js'
const basePrincipal = {
kind: 'human' as const,
accountId: 'acct-A',
principalId: 'cred-1',
amr: ['passkey' as const],
authAt: 1_700_000_000,
stepUpAt: null,
}
describe('StepUpPolicy.required (host-driven, fail-closed)', () => {
it('parses a policy with required=true', () => {
const policy: StepUpPolicy = { required: true, maxAgeSeconds: 300, requiredMethod: 'passkey' }
expect(StepUpPolicySchema.parse(policy)).toEqual(policy)
})
it('parses a policy with required=false', () => {
const policy: StepUpPolicy = { required: false, maxAgeSeconds: 300, requiredMethod: 'passkey' }
expect(StepUpPolicySchema.parse(policy)).toEqual(policy)
})
it('rejects a policy missing required', () => {
const bad = { maxAgeSeconds: 300, requiredMethod: 'passkey' }
expect(StepUpPolicySchema.safeParse(bad).success).toBe(false)
})
it('rejects a non-boolean required', () => {
const bad = { required: 'yes', maxAgeSeconds: 300, requiredMethod: 'passkey' }
expect(StepUpPolicySchema.safeParse(bad).success).toBe(false)
})
})
describe('AuthenticatedPrincipal.stepUpMethod (F1 method-binding, optional)', () => {
it('parses a principal that omits stepUpMethod (backward compatible)', () => {
const parsed = AuthenticatedPrincipalSchema.parse(basePrincipal)
expect(parsed.stepUpMethod).toBeUndefined()
})
it('parses a principal with an explicit stepUpMethod', () => {
const p: AuthenticatedPrincipal = { ...basePrincipal, stepUpAt: 1_700_000_100, stepUpMethod: 'passkey' }
expect(AuthenticatedPrincipalSchema.parse(p).stepUpMethod).toBe('passkey')
})
it('parses a principal with stepUpMethod=null (no step-up)', () => {
const parsed = AuthenticatedPrincipalSchema.parse({ ...basePrincipal, stepUpMethod: null })
expect(parsed.stepUpMethod).toBeNull()
})
it('rejects an invalid stepUpMethod value', () => {
const bad = { ...basePrincipal, stepUpMethod: 'sms' }
expect(AuthenticatedPrincipalSchema.safeParse(bad).success).toBe(false)
})
})

View File

@@ -21,14 +21,14 @@ const verifier: WebAuthnVerifier = {
signCount: 0, signCount: 0,
transports: ['internal'], transports: ['internal'],
}), }),
verifyAuthentication: async (_r, _c, _rp, _o, stored) => ({ verified: true, newSignCount: stored + 1 }), verifyAuthentication: async (_r, _c, _rp, _o, _pk, _cid, stored) => ({ verified: true, newSignCount: stored + 1 }),
} }
function regResp(over: Partial<RegistrationResponse> = {}): RegistrationResponse { function regResp(over: Partial<RegistrationResponse> = {}): RegistrationResponse {
return { clientChallenge: 'chal', origin: ORIGIN, rpId: RP_ID, ...over } return { clientChallenge: 'chal', origin: ORIGIN, rpId: RP_ID, ...over }
} }
function authResp(over: Partial<AuthenticationResponse> = {}): AuthenticationResponse { function authResp(over: Partial<AuthenticationResponse> = {}): AuthenticationResponse {
return { clientChallenge: 'chal', origin: ORIGIN, rpId: RP_ID, ...over } return { clientChallenge: 'chal', origin: ORIGIN, rpId: RP_ID, credentialId: 'cred-1', ...over }
} }
const cred: WebAuthnCredential = { const cred: WebAuthnCredential = {
credentialId: 'cred-1', credentialId: 'cred-1',
@@ -68,16 +68,32 @@ describe('WebAuthn / Passkey (T5, primary)', () => {
it('happy path auth yields a principal with amr:[passkey]', async () => { it('happy path auth yields a principal with amr:[passkey]', async () => {
const startOpts = await startAuthentication('acct-A', RP_ID) const startOpts = await startAuthentication('acct-A', RP_ID)
expect(startOpts.rpId).toBe(RP_ID) expect(startOpts.rpId).toBe(RP_ID)
const p = await finishAuthentication(cred, authResp(), 'chal', RP_ID, ORIGIN, verifier, NOW) const { principal: p } = await finishAuthentication(cred, authResp(), 'chal', RP_ID, ORIGIN, verifier, NOW)
expect(p.accountId).toBe('acct-A') expect(p.accountId).toBe('acct-A')
expect(p.amr).toEqual(['passkey']) expect(p.amr).toEqual(['passkey'])
expect(p.authAt).toBe(NOW) expect(p.authAt).toBe(NOW)
}) })
it('F3: rejects an assertion whose credentialId does not match the stored credential', async () => {
const forgiving: WebAuthnVerifier = {
...verifier,
verifyAuthentication: async (_r, _c, _rp, _o, _pk, _cid, stored) => ({ verified: true, newSignCount: stored + 1 }),
}
await expect(
finishAuthentication(cred, authResp({ credentialId: 'other-cred' }), 'chal', RP_ID, ORIGIN, forgiving, NOW),
).rejects.toThrow('credential id mismatch')
})
it('F5: returns the verifier-advanced newSignCount so the caller can persist it', async () => {
const { principal: p, newSignCount } = await finishAuthentication(cred, authResp(), 'chal', RP_ID, ORIGIN, verifier, NOW)
expect(p.accountId).toBe('acct-A')
expect(newSignCount).toBe(cred.signCount + 1)
})
it('rejects a signCount regression (cloned authenticator signal)', async () => { it('rejects a signCount regression (cloned authenticator signal)', async () => {
const regressing: WebAuthnVerifier = { const regressing: WebAuthnVerifier = {
...verifier, ...verifier,
verifyAuthentication: async () => ({ verified: true, newSignCount: 3 }), // < stored 5 verifyAuthentication: async () => ({ verified: true, newSignCount: 3 }), // < stored 5 (adapts to {principal,newSignCount} return)
} }
await expect( await expect(
finishAuthentication(cred, authResp(), 'chal', RP_ID, ORIGIN, regressing, NOW), finishAuthentication(cred, authResp(), 'chal', RP_ID, ORIGIN, regressing, NOW),