Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
280 changes: 267 additions & 13 deletions deploy/examples/business-registration/tests/browser-authorization.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,64 @@ import { readFile } from 'node:fs/promises'

const requestId = /^(app|issuer)-[1-9][0-9]{0,7}$/u
const maxReportedRequests = 4
const maxRequestLine = 128
const maxEventLine = 64
const resourceTypes = new Set([
'document', 'stylesheet', 'image', 'media', 'font', 'script', 'texttrack',
'xhr', 'fetch', 'eventsource', 'websocket', 'manifest',
])

const appRoutes = new Map([
['/session/sign-in', 'sign-in'],
['/session/callback', 'session-callback'],
['/session/sign-out', 'sign-out'],
['/session/signed-out', 'signed-out'],
])
const issuerRoutes = new Map([
['/oauth2/logout', 'logout'],
['/oauth2/authorize', 'authorize'],
['/oauth2/auth/callback', 'issuer-callback'],
['/.well-known/openid-configuration', 'discovery'],
['/oauth2/jwks', 'jwks'],
['/flow/meta', 'flow-meta'],
['/flow/execute', 'flow-execute'],
['/gate/signin', 'issuer-sign-in'],
['/design/resolve', 'issuer-design'],
])
const issuerTextPath = /^\/i18n\/languages(?:\/[^/]+\/translations(?:\/ns\/[^/]+\/keys\/[^/]+)?\/resolve)?$/u
const methods = new Set(['GET', 'POST', 'HEAD', 'OPTIONS', 'other'])
const routes = new Set(['other', 'issuer-text', ...appRoutes.values(), ...issuerRoutes.values()])
const edgeEvents = new Set(['upstreamHeaders', 'downstreamFinished', 'downstreamClosed'])
// Retain the ledger's order for failure diagnostics without serializing it in the receipt.
const edgeEventOrder = new WeakMap()
export const logoutCheckpoints = Object.freeze({
callbackRequest: 'issuer logout callback request',
signedOutRequest: 'signed-out document request',
signedOutCommit: 'signed-out document commit',
})
const knownLogoutCheckpoints = Object.values(logoutCheckpoints)

export function classifyBrowserRequest(scope, target, method) {
const pathname = target?.split('?', 1)[0]
const scopeRoutes = scope === 'app' ? appRoutes : scope === 'issuer' ? issuerRoutes : undefined
return {
route: scopeRoutes?.get(pathname) ?? (scope === 'issuer' && issuerTextPath.test(pathname) ? 'issuer-text' : 'other'),
method: methods.has(method) ? method : 'other',
}
}

export function isBrowserEdgeEvent(event) {
return edgeEvents.has(event)
}

export function requestFrameForDiagnostics(request) {
try {
return request.frame?.()
} catch {
// Playwright may report a request before its frame is available.
return undefined
}
}

export const browserStages = Object.freeze({
firstSignIn: 'sign in the first registrar',
Expand Down Expand Up @@ -37,26 +95,102 @@ function formatRequestState(marker, outcome) {
return `response=${marker} request=${outcome}`
}

function isLogoutMetadata(request, entry) {
return entry.scope === 'issuer' && entry.route === 'flow-meta' && entry.method === 'GET'
&& (entry.stage === browserStages.signOut || entry.stage === browserStages.returnFromIssuer)
&& ['fetch', 'xhr'].includes(request.resourceType?.()) && !request.serviceWorker?.()
}

export class BrowserAuthorizationError extends Error {}

export async function withIssuerLogoutCallback(page, callbackUrl, evidence, signOut) {
const frame = page.mainFrame()
let continuation
let failure
const recordRoutingFailure = () => {
failure ??= new BrowserAuthorizationError('Browser issuer logout callback routing failed.')
}
const onRoute = async route => {
const request = route.request()
if (continuation || request.method() !== 'POST' || requestFrameForDiagnostics(request) !== frame) {
await route.fallback().catch(recordRoutingFailure)
return
}
// Let the real issuer finish the logout even when marker collection fails the test.
continuation = evidence.waitForLogoutMetadata(frame).catch(error => { failure ??= error })
.then(() => route.continue()).catch(recordRoutingFailure)
await continuation
}

await page.route(callbackUrl, onRoute)
try {
await signOut()
} finally {
try {
await page.unroute(callbackUrl, onRoute)
} finally {
await continuation
if (failure) throw failure
}
}
if (!continuation) throw new BrowserAuthorizationError('Browser issuer logout callback was not observed.')
}

export async function readBrowserAuthorizationRecords(path, maxRows) {
try {
const data = await readFile(path, 'utf8')
if (!data.endsWith('\n') || data.length > maxRows * 80) throw new Error()
if (!data.endsWith('\n') || data.length > maxRows * (maxRequestLine + edgeEvents.size * maxEventLine)) throw new Error()
const lines = data.slice(0, -1).split('\n')
if (lines.length > maxRows) throw new Error()
return lines.map(line => JSON.parse(line))
if (lines.length > maxRows * (1 + edgeEvents.size)) throw new Error()
const recorded = new Map()
for (const line of lines) {
if (line.length >= maxRequestLine) throw new Error()
const { id, event, ...request } = JSON.parse(line)
if (typeof id !== 'string' || !requestId.test(id)) throw new Error()
if (event === undefined) {
if (recorded.has(id) || recorded.size >= maxRows || !validRequestFields(request)) throw new Error()
const row = { id, ...request, upstreamHeaders: false, downstreamFinished: false, downstreamClosed: false }
recorded.set(id, row)
edgeEventOrder.set(row, [])
continue
}
const row = recorded.get(id)
if (!row || line.length >= maxEventLine || Object.keys(request).length !== 0 || !isBrowserEdgeEvent(event)
|| row[event] || (event === 'downstreamFinished' && !row.upstreamHeaders)) throw new Error()
row[event] = true
edgeEventOrder.get(row).push(event)
}
return [...recorded.values()]
} catch {
throw new BrowserAuthorizationError('Browser edge records missing, incomplete, or invalid.')
}
}

export function assertBrowserAuthorizationEvidence(evidence) {
const { observedRequestIds, recordedRequests } = evidence ?? {}
if (!Array.isArray(observedRequestIds) || !Array.isArray(recordedRequests)) {
function validRequestFields({ headerNames, route, method, ...extra }) {
return Object.keys(extra).length === 0 && routes.has(route) && methods.has(method)
&& Array.isArray(headerNames) && headerNames.length <= 1
&& (headerNames.length === 0 || headerNames[0] === 'authorization')
}

export function browserAuthorizationReceiptRows(recordedRequests) {
if (!Array.isArray(recordedRequests)) {
throw new BrowserAuthorizationError('Browser authorization receipt is missing edge evidence.')
}
return recordedRequests.map(row => {
const { id, upstreamHeaders, downstreamFinished, downstreamClosed, ...request } = row ?? {}
if (!validRequestFields(request) || typeof upstreamHeaders !== 'boolean'
|| typeof downstreamFinished !== 'boolean' || typeof downstreamClosed !== 'boolean'
|| (downstreamFinished && !upstreamHeaders)) {
throw new BrowserAuthorizationError('Browser edge record is invalid or duplicated.')
}
return { id, headerNames: request.headerNames }
})
}

function checkedRecordedRequests(recordedRequests) {
if (!Array.isArray(recordedRequests)) {
throw new BrowserAuthorizationError('Browser authorization receipt is missing edge evidence.')
}
const recorded = new Set()
const counts = { app: 0, issuer: 0 }
const present = []
Expand All @@ -76,6 +210,48 @@ export function assertBrowserAuthorizationEvidence(evidence) {
if (headerNames.length === 1) present.push(`${id}: Authorization header present at the browser edge`)
}
if (present.length) throw new BrowserAuthorizationError(present.join('\n'))
return recorded
}

function unmatchedRecordedRows(recordedRequests, observations) {
try {
checkedRecordedRequests(browserAuthorizationReceiptRows(recordedRequests))
} catch (error) {
if (!(error instanceof BrowserAuthorizationError)) throw error
return 'Unmatched recorded edge rows unavailable (edge records failed validation).'
}
// A marker can tie an observation to a row only if it appears once and matches the scope.
const uniqueMatches = new Map()
for (const entry of observations) {
const marker = responseMarkerState(entry)
if (marker === 'same-scope-marker' || marker === 'wrong-scope-marker') {
uniqueMatches.set(entry.id, marker === 'same-scope-marker' && !uniqueMatches.has(entry.id))
}
}
const unmatched = recordedRequests.filter(({ id }) => !uniqueMatches.get(id))
const counts = { app: 0, issuer: 0 }
for (const { id } of unmatched) counts[id.slice(0, id.indexOf('-'))] += 1
const lines = [`Unmatched recorded edge rows: app=${counts.app} issuer=${counts.issuer}.`]
const yesNo = value => value ? 'yes' : 'no'
for (const row of unmatched) {
if (lines.length > maxReportedRequests) break
const events = edgeEventOrder.get(row)
lines.push(`edge ${row.id}: route-class=${row.route} method=${row.method}`
+ ` upstream-headers=${yesNo(row.upstreamHeaders)} downstream-finished=${yesNo(row.downstreamFinished)}`
+ ` downstream-closed=${yesNo(row.downstreamClosed)}`
+ (events?.length ? ` event-order=${events.join(',')}` : ''))
}
const remaining = unmatched.length - (lines.length - 1)
if (remaining > 0) lines.push(`${remaining} more unmatched recorded edge rows.`)
return lines.join('\n')
}

export function assertBrowserAuthorizationEvidence(evidence) {
const { observedRequestIds, recordedRequests } = evidence ?? {}
if (!Array.isArray(observedRequestIds)) {
throw new BrowserAuthorizationError('Browser authorization receipt is missing edge evidence.')
}
const recorded = checkedRecordedRequests(recordedRequests)

const observed = new Set()
const scopes = new Set()
Expand All @@ -93,21 +269,25 @@ export function assertBrowserAuthorizationEvidence(evidence) {

export class BrowserAuthorizationEvidence {
#requests = new Map()
#logoutCheckpoints = new Map()
#logoutMetadataChanged
#limit
#invalid = false

constructor(limit) {
this.#limit = limit
}

observe(request, scope, stage) {
observe(request, scope, stage, pathname, method) {
if (this.#requests.has(request) || this.#requests.size >= this.#limit) {
this.#invalid = true
return
}
this.#requests.set(request, {
ordinal: this.#requests.size + 1,
scope: scope === 'app' || scope === 'issuer' ? scope : 'other',
stage: knownStages.has(stage) ? stage : 'unknown',
...classifyBrowserRequest(scope, pathname, method),
responded: false, outcome: 'pending', receipt: Promise.withResolvers(),
})
}
Expand All @@ -121,11 +301,75 @@ export class BrowserAuthorizationEvidence {
entry.id = id
entry.responded = true
entry.receipt.resolve()
this.#logoutMetadataChanged?.(entry)
}

observeRequestEnd(request, finished) {
const entry = this.#requests.get(request)
if (entry) entry.outcome = finished ? 'finished' : 'failed'
if (!entry) return
entry.outcome = finished ? 'finished' : 'failed'
if (!entry.responded) this.#logoutMetadataChanged?.(entry)
}

*#logoutMetadata(frame) {
for (const [request, entry] of this.#requests) {
if (isLogoutMetadata(request, entry) && requestFrameForDiagnostics(request) === frame) yield [request, entry]
}
}

async waitForLogoutMetadata(frame, timeoutMs = 5_000) {
if (this.#logoutMetadataChanged) {
throw new BrowserAuthorizationError('Browser issuer logout metadata observer is already active.')
}
const noMarker = () => new BrowserAuthorizationError('Browser issuer logout metadata has no valid edge response marker.')
const pending = new Set()
// Only the requests already observed at this callback can delay it.
for (const [, entry] of this.#logoutMetadata(frame)) {
const marker = responseMarkerState(entry)
if (marker === 'same-scope-marker') continue
if (marker !== 'pending' || entry.outcome !== 'pending') throw noMarker()
pending.add(entry)
}
if (!pending.size) return

const { promise, resolve, reject } = Promise.withResolvers()
const timer = setTimeout(() => {
reject(new BrowserAuthorizationError('Browser issuer logout metadata edge response marker timed out.'))
}, timeoutMs)
this.#logoutMetadataChanged = entry => {
if (!pending.delete(entry)) return
if (responseMarkerState(entry) !== 'same-scope-marker') reject(noMarker())
else if (!pending.size) resolve()
}
try {
await promise
} finally {
clearTimeout(timer)
this.#logoutMetadataChanged = undefined
}
}

observeLogoutCheckpoint(frame, checkpoint) {
if (!knownLogoutCheckpoints.includes(checkpoint)) {
throw new BrowserAuthorizationError('Browser logout checkpoint is invalid.')
}
if (!frame || this.#logoutCheckpoints.has(checkpoint)) return
const observed = new Map()
for (const [request, entry] of this.#logoutMetadata(frame)) {
observed.set(request, formatRequestState(responseMarkerState(entry), entry.outcome))
}
this.#logoutCheckpoints.set(checkpoint, { frame, observed })
}

#describeLogoutCheckpoints(request, entry) {
if (!this.#logoutCheckpoints.size || !isLogoutMetadata(request, entry)) return ''
const requestFrame = requestFrameForDiagnostics(request)
if (!requestFrame) return ''
const details = []
for (const [name, { frame, observed }] of this.#logoutCheckpoints) {
if (requestFrame === frame) details.push(` at ${name}: ${observed.get(request) ?? 'not yet observed'},`)
}
return details.join('')
}

async waitForResponses(timeoutMs = 10_000) {
Expand Down Expand Up @@ -155,22 +399,32 @@ export class BrowserAuthorizationEvidence {
const missing = []
let missingCount = 0
const observedRequestIds = []
for (const [index, entry] of [...this.#requests.values()].entries()) {
for (const [request, entry] of this.#requests) {
const marker = responseMarkerState(entry)
if (marker === 'same-scope-marker') {
observedRequestIds.push(entry.id)
continue
}
missingCount += 1
if (missing.length < maxReportedRequests) {
missing.push(`request #${index + 1}: no matching edge response marker before Chromium closed`
+ ` (scope=${entry.scope}, stage="${entry.stage}", before close: ${entry.beforeClose ?? 'not observed'},`
const type = request.resourceType?.()
const resource = resourceTypes.has(type) ? type : 'other'
const parent = request.redirectedFrom?.()
const parentOrdinal = this.#requests.get(parent)?.ordinal ?? (parent ? 'unobserved' : 'none')
missing.push(`request #${entry.ordinal}: no matching edge response marker before Chromium closed`
+ ` (scope=${entry.scope}, stage="${entry.stage}", route-class=${entry.route}, method=${entry.method},`
+ ` resource-type=${resource}, redirect-parent-ordinal=${parentOrdinal},`
+ this.#describeLogoutCheckpoints(request, entry)
+ ` before close: ${entry.beforeClose ?? 'not observed'},`
+ ` after close: ${formatRequestState(marker, entry.outcome)})`)
}
}
if (missingCount > missing.length) missing.push(`${missingCount - missing.length} more unresolved browser requests`)
if (missing.length) throw new BrowserAuthorizationError(missing.join('\n'))
const evidence = { observedRequestIds, recordedRequests }
if (missing.length) {
missing.push(unmatchedRecordedRows(recordedRequests, this.#requests.values()))
throw new BrowserAuthorizationError(missing.join('\n'))
}
const evidence = { observedRequestIds, recordedRequests: browserAuthorizationReceiptRows(recordedRequests) }
assertBrowserAuthorizationEvidence(evidence)
return evidence
}
Expand Down
Loading