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,7 +54,13 @@ async function coreAuthorize(
} catch {
return { outcome: deny(401, 'invalid_capability_token') }
}
if (!(await verifyDpopProof(token, dpop, now))) {
// 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))) {
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') }

View File

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

View File

@@ -49,6 +49,8 @@ export async function issueCapabilityToken(
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.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 body: TokenBody = {

View File

@@ -116,38 +116,45 @@ export async function verifyDpopProof(
dpop: DpopContext,
now: number,
): Promise<boolean> {
const expectedJkt = readCnfJkt(token)
const parts = dpop.proofJws.split('.')
if (parts.length !== 3) return false
const [h, p, s] = parts as [string, string, string]
let header: DpopHeader
let payload: DpopPayload
// 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 {
header = JSON.parse(new TextDecoder().decode(decodeBase64UrlBytes(h))) as DpopHeader
payload = JSON.parse(new TextDecoder().decode(decodeBase64UrlBytes(p))) as DpopPayload
const expectedJkt = readCnfJkt(token)
const parts = dpop.proofJws.split('.')
if (parts.length !== 3) return false
const [h, p, s] = parts as [string, string, string]
let header: DpopHeader
let payload: DpopPayload
try {
header = JSON.parse(new TextDecoder().decode(decodeBase64UrlBytes(h))) as DpopHeader
payload = JSON.parse(new TextDecoder().decode(decodeBase64UrlBytes(p))) as DpopPayload
} catch {
return false
}
if (header.jwk?.kty !== 'OKP' || header.jwk?.crv !== 'Ed25519') return false
let rawPub: Uint8Array
try {
rawPub = decodeBase64UrlBytes(header.jwk.x)
} catch {
return false
}
if ((await jwkThumbprint(rawPub)) !== expectedJkt) return false
if (payload.htu !== dpop.htu || payload.htm !== dpop.htm) return false
if (typeof payload.iat !== 'number' || Math.abs(now - payload.iat) > DPOP_MAX_AGE_SEC) return false
const signed = new TextEncoder().encode(`${h}.${p}`)
const pubKey = await importEd25519PublicRaw(rawPub)
let sig: Uint8Array
try {
sig = decodeBase64UrlBytes(s)
} catch {
return false
}
if (!(await verifyEd25519(pubKey, sig, signed))) return false
return rememberDpop(payload.jti, payload.iat + DPOP_MAX_AGE_SEC, now)
} catch {
return false
}
if (header.jwk?.kty !== 'OKP' || header.jwk?.crv !== 'Ed25519') return false
let rawPub: Uint8Array
try {
rawPub = decodeBase64UrlBytes(header.jwk.x)
} catch {
return false
}
if ((await jwkThumbprint(rawPub)) !== expectedJkt) return false
if (payload.htu !== dpop.htu || payload.htm !== dpop.htm) return false
if (typeof payload.iat !== 'number' || Math.abs(now - payload.iat) > DPOP_MAX_AGE_SEC) return false
const signed = new TextEncoder().encode(`${h}.${p}`)
const pubKey = await importEd25519PublicRaw(rawPub)
let sig: Uint8Array
try {
sig = decodeBase64UrlBytes(s)
} catch {
return false
}
if (!(await verifyEd25519(pubKey, sig, signed))) return false
return rememberDpop(payload.jti, payload.iat + DPOP_MAX_AGE_SEC, now)
}
/** 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)
return deny(403, 'too_many_sessions')
}
// 5. Step-up gate (Finding-3, v0.10) — only when a session principal is present.
if (ctx.principal !== null) {
const host = await deps.hosts.getById(outcome.hostId)
if (host !== null && needsStepUp(ctx.principal, deps.stepUpPolicyFor(host), now)) {
// 5. Step-up gate (Finding-3/F1/F2) — HOST-DRIVEN and FAIL-CLOSED on connect AND reattach.
// 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 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)
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
/** 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 {
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
* method is not present in `amr` — i.e. a fresh login alone does NOT satisfy it.
* true when step-up is required: never stepped up, OR the last step-up is stale, OR the LAST step-up
* 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(
principal: AuthenticatedPrincipal,
@@ -30,16 +38,19 @@ export function needsStepUp(
): boolean {
if (principal.stepUpAt === null) 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
}
/** 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(
principal: AuthenticatedPrincipal,
method: AuthMethod,
now: number,
): AuthenticatedPrincipal {
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,
verifier: WebAuthnVerifier,
now: number,
): Promise<AuthenticatedPrincipal> {
): Promise<{ principal: AuthenticatedPrincipal; newSignCount: number }> {
if (resp.clientChallenge !== expectedChallenge) throw new WebAuthnError('challenge mismatch')
if (resp.origin !== origin) throw new WebAuthnError('origin 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(
resp,
expectedChallenge,
rpId,
origin,
cred.publicKey,
cred.credentialId,
cred.signCount,
)
if (!result.verified) throw new WebAuthnError('assertion not verified')
@@ -49,7 +52,7 @@ export async function finishAuthentication(
throw new WebAuthnError('signCount regression (cloned authenticator)')
}
return {
const principal: AuthenticatedPrincipal = {
kind: 'human',
accountId: cred.accountId,
principalId: cred.credentialId,
@@ -57,4 +60,5 @@ export async function finishAuthentication(
authAt: now,
stepUpAt: null,
}
return { principal, newSignCount: result.newSignCount }
}

View File

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

View File

@@ -34,6 +34,7 @@ export interface AuthenticatedPrincipal {
readonly amr: readonly AuthMethod[] // methods satisfied this session (for step-up, T8)
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 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 interface StepUpPolicy {
readonly required: boolean
readonly maxAgeSeconds: number
readonly requiredMethod: AuthMethod
}
@@ -141,11 +143,13 @@ export const AuthenticatedPrincipalSchema = z
amr: z.array(AuthMethodSchema).readonly(),
authAt: z.number().int().nonnegative(),
stepUpAt: z.number().int().nonnegative().nullable(),
stepUpMethod: AuthMethodSchema.nullable().optional(),
})
.strict()
export const StepUpPolicySchema = z
.object({
required: z.boolean(),
maxAgeSeconds: z.number().int().nonnegative(),
requiredMethod: AuthMethodSchema,
})