From c5c4f3462eb47260f9e07d1c02e639ec21ff5fd2 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:11:45 +0000 Subject: [PATCH 01/12] test: specify bounded browser redirect diagnostics Signed-off-by: Jeremi Joslin --- .../tests/receipt.test.mjs | 69 +++++++++++++------ 1 file changed, 47 insertions(+), 22 deletions(-) diff --git a/deploy/examples/business-registration/tests/receipt.test.mjs b/deploy/examples/business-registration/tests/receipt.test.mjs index 1cf7815a13..89693706ea 100644 --- a/deploy/examples/business-registration/tests/receipt.test.mjs +++ b/deploy/examples/business-registration/tests/receipt.test.mjs @@ -148,21 +148,33 @@ test('browser authorization records match each observed request across both orig observed.observeResponse(app, 'app-1') await observed.waitForResponses() assert.deepEqual(observed.receipt(recordedRequests), browserAuthorization) + const withUnmatchedRow = [...recordedRequests, { id: 'app-2', headerNames: [] }] + assert.deepEqual(observed.receipt(withUnmatchedRow), { + ...browserAuthorization, recordedRequests: withUnmatchedRow, + }) }) -test('an unresolved browser marker still fails after the bounded wait even with an edge record', { timeout: 1_000 }, async () => { +test('an unresolved issuer logout document reports its redirect parent and unmatched edge totals', { timeout: 1_000 }, async () => { const observed = new BrowserAuthorizationEvidence(10) const app = {} - const issuer = { failure: () => ({ errorText: 'synthetic-request-error-canary' }) } - observed.observe(app, 'app') - observed.observe(issuer, 'issuer', browserStages.returnFromIssuer) + const issuer = { + resourceType: () => 'document', + redirectedFrom: () => app, + failure: () => ({ errorText: 'synthetic-request-error-canary' }), + } + observed.observe(app, 'app', browserStages.signOut, '/session/sign-out') + const logout = new URL('https://issuer.invalid/oauth2/logout?id_token_hint=synthetic-token-canary') + observed.observe(issuer, 'issuer', browserStages.returnFromIssuer, logout.pathname) observed.observeResponse(app, 'app-1') + const rows = [...recordedRequests, { id: 'issuer-2', headerNames: [] }, { id: 'app-2', headerNames: [] }] await observed.waitForResponses(20) observed.observeRequestEnd(issuer, false) - assert.throws(() => observed.receipt(recordedRequests), { + assert.throws(() => observed.receipt(rows), { message: 'request #2: no matching edge response marker before Chromium closed' + ' (scope=issuer, stage="return from the issuer to the signed-out page",' - + ' before close: response=pending request=pending, after close: response=pending request=failed)', + + ' route-class=logout, resource-type=document, redirect-parent-ordinal=1,' + + ' before close: response=pending request=pending, after close: response=pending request=failed)' + + '\nUnmatched recorded edge rows: app=1 issuer=2.', }) }) @@ -187,14 +199,14 @@ test('a valid response marker delivered during Chromium shutdown completes the e test('unresolved markers report only fixed request state', async () => { const observed = new BrowserAuthorizationEvidence(10) - const wrongScope = {} - const malformed = {} - const other = { url: () => 'https://origin-canary.invalid/url-canary?token=token-canary' } - const unmarked = {} - observed.observe(wrongScope, 'app', browserStages.signOut) - observed.observe(malformed, 'issuer', 'synthetic-stage-canary') - observed.observe(other, 'https://origin-canary.invalid') - observed.observe(unmarked, 'issuer') + const wrongScope = { resourceType: () => 'document' } + const malformed = { resourceType: () => 'image' } + const other = { resourceType: () => 'synthetic-resource-type-canary' } + const unmarked = { resourceType: () => 'fetch', redirectedFrom: () => ({}) } + observed.observe(wrongScope, 'app', browserStages.signOut, '/session/sign-out') + observed.observe(malformed, 'issuer', 'synthetic-stage-canary', '/path-canary') + observed.observe(other, 'https://origin-canary.invalid', undefined, '/oauth2/logout') + observed.observe(unmarked, 'issuer', undefined, '/oauth2/authorize') observed.observeResponse(wrongScope, 'issuer-1') observed.observeResponse(malformed, 'synthetic-header-value-canary') observed.observeResponse(other, 'app-1') @@ -206,19 +218,30 @@ test('unresolved markers report only fixed request state', async () => { message: [ 'request #1: no matching edge response marker before Chromium closed' + ' (scope=app, stage="submit the first registrar sign-out form",' + + ' route-class=sign-out, resource-type=document, redirect-parent-ordinal=none,' + ' before close: response=wrong-scope-marker request=finished,' + ' after close: response=wrong-scope-marker request=finished)', 'request #2: no matching edge response marker before Chromium closed' - + ' (scope=issuer, stage="unknown", before close: response=invalid-marker request=pending,' + + ' (scope=issuer, stage="unknown", route-class=other, resource-type=image, redirect-parent-ordinal=none,' + + ' before close: response=invalid-marker request=pending,' + ' after close: response=invalid-marker request=pending)', 'request #3: no matching edge response marker before Chromium closed' - + ' (scope=other, stage="unknown", before close: response=wrong-scope-marker request=pending,' + + ' (scope=other, stage="unknown", route-class=other, resource-type=other, redirect-parent-ordinal=none,' + + ' before close: response=wrong-scope-marker request=pending,' + ' after close: response=wrong-scope-marker request=pending)', 'request #4: no matching edge response marker before Chromium closed' - + ' (scope=issuer, stage="unknown", before close: response=pending request=pending,' + + ' (scope=issuer, stage="unknown", route-class=authorize, resource-type=fetch, redirect-parent-ordinal=unobserved,' + + ' before close: response=pending request=pending,' + ' after close: response=unmarked request=finished)', + 'Unmatched recorded edge rows: app=1 issuer=1.', ].join('\n'), }) + const invalidRows = [...recordedRequests, { id: 'synthetic-row-canary', headerNames: [] }] + assert.throws(() => observed.receipt(invalidRows), error => { + assert.match(error.message, /\nUnmatched recorded edge rows unavailable \(edge records failed validation\)\.$/u) + assert.doesNotMatch(error.message, /canary/u) + return true + }) }) test('unresolved marker diagnostics cap the ordinals and count the remaining requests', async () => { @@ -232,9 +255,10 @@ test('unresolved marker diagnostics cap the ordinals and count the remaining req assert.throws(() => observed.receipt(recordedRequests), { message: [1, 2, 3, 4].map(ordinal => `request #${ordinal}: no matching edge response marker before Chromium closed` - + ' (scope=app, stage="unknown", before close: response=unmarked request=pending,' + + ' (scope=app, stage="unknown", route-class=other, resource-type=other, redirect-parent-ordinal=none,' + + ' before close: response=unmarked request=pending,' + ' after close: response=unmarked request=pending)', - ).concat('2 more unresolved browser requests').join('\n'), + ).concat('2 more unresolved browser requests', 'Unmatched recorded edge rows: app=1 issuer=1.').join('\n'), }) }) @@ -249,11 +273,12 @@ test('the edge proof includes requests observed during the wait and finalization observed.observeResponse(app, 'app-1') setImmediate(() => observed.observeResponse(issuer, 'issuer-1')) await checked - observed.observe(late, 'issuer', browserStages.closeChromium) + observed.observe(late, 'app', browserStages.closeChromium, '/session/signed-out') assert.throws(() => observed.receipt(recordedRequests), { message: 'request #3: no matching edge response marker before Chromium closed' - + ' (scope=issuer, stage="close Chromium", before close: not observed,' - + ' after close: response=pending request=pending)', + + ' (scope=app, stage="close Chromium", route-class=signed-out, resource-type=other, redirect-parent-ordinal=none,' + + ' before close: not observed, after close: response=pending request=pending)' + + '\nUnmatched recorded edge rows: app=0 issuer=0.', }) }) From 358d22e6c389d658f9b53555ef3f6e31b5a491d3 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:12:38 +0000 Subject: [PATCH 02/12] test: report bounded browser redirect and edge evidence Signed-off-by: Jeremi Joslin --- .../tests/browser-authorization.mjs | 62 ++++++++++++++++--- .../business-registration/tests/browser.mjs | 2 +- 2 files changed, 55 insertions(+), 9 deletions(-) diff --git a/deploy/examples/business-registration/tests/browser-authorization.mjs b/deploy/examples/business-registration/tests/browser-authorization.mjs index 78df84d72a..fbd8c9e469 100644 --- a/deploy/examples/business-registration/tests/browser-authorization.mjs +++ b/deploy/examples/business-registration/tests/browser-authorization.mjs @@ -2,6 +2,18 @@ import { readFile } from 'node:fs/promises' const requestId = /^(app|issuer)-[1-9][0-9]{0,7}$/u const maxReportedRequests = 4 +const resourceTypes = new Set([ + 'document', 'stylesheet', 'image', 'media', 'font', 'script', 'texttrack', + 'xhr', 'fetch', 'eventsource', 'websocket', 'manifest', +]) + +function routeClass(scope, pathname) { + if (scope === 'issuer' && pathname === '/oauth2/logout') return 'logout' + if (scope === 'issuer' && pathname === '/oauth2/authorize') return 'authorize' + if (scope === 'app' && pathname === '/session/sign-out') return 'sign-out' + if (scope === 'app' && pathname === '/session/signed-out') return 'signed-out' + return 'other' +} export const browserStages = Object.freeze({ firstSignIn: 'sign in the first registrar', @@ -51,9 +63,8 @@ export async function readBrowserAuthorizationRecords(path, maxRows) { } } -export function assertBrowserAuthorizationEvidence(evidence) { - const { observedRequestIds, recordedRequests } = evidence ?? {} - if (!Array.isArray(observedRequestIds) || !Array.isArray(recordedRequests)) { +function checkedRecordedRequestIds(recordedRequests) { + if (!Array.isArray(recordedRequests)) { throw new BrowserAuthorizationError('Browser authorization receipt is missing edge evidence.') } @@ -76,6 +87,30 @@ 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, observedRequestIds) { + let recorded + try { + recorded = checkedRecordedRequestIds(recordedRequests) + } catch (error) { + if (!(error instanceof BrowserAuthorizationError)) throw error + return 'Unmatched recorded edge rows unavailable (edge records failed validation).' + } + // Only a same-scope response marker can tie a browser observation to a row. + for (const id of observedRequestIds) recorded.delete(id) + const counts = { app: 0, issuer: 0 } + for (const id of recorded) counts[id.slice(0, id.indexOf('-'))] += 1 + return `Unmatched recorded edge rows: app=${counts.app} issuer=${counts.issuer}.` +} + +export function assertBrowserAuthorizationEvidence(evidence) { + const { observedRequestIds, recordedRequests } = evidence ?? {} + if (!Array.isArray(observedRequestIds)) { + throw new BrowserAuthorizationError('Browser authorization receipt is missing edge evidence.') + } + const recorded = checkedRecordedRequestIds(recordedRequests) const observed = new Set() const scopes = new Set() @@ -100,14 +135,16 @@ export class BrowserAuthorizationEvidence { this.#limit = limit } - observe(request, scope, stage) { + observe(request, scope, stage, pathname) { 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', + route: routeClass(scope, pathname), responded: false, outcome: 'pending', receipt: Promise.withResolvers(), }) } @@ -155,7 +192,7 @@ 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) @@ -163,13 +200,22 @@ export class BrowserAuthorizationEvidence { } 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},` + + ` resource-type=${resource}, redirect-parent-ordinal=${parentOrdinal},` + + ` 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')) + if (missing.length) { + missing.push(unmatchedRecordedRows(recordedRequests, observedRequestIds)) + throw new BrowserAuthorizationError(missing.join('\n')) + } const evidence = { observedRequestIds, recordedRequests } assertBrowserAuthorizationEvidence(evidence) return evidence diff --git a/deploy/examples/business-registration/tests/browser.mjs b/deploy/examples/business-registration/tests/browser.mjs index 6d2a17bf76..3f3e9442ba 100644 --- a/deploy/examples/business-registration/tests/browser.mjs +++ b/deploy/examples/business-registration/tests/browser.mjs @@ -31,7 +31,7 @@ async function signIn(person, path = '/apply/', expectedSignIn = 'registrar') { context.on('request', request => { const url = new URL(request.url()) const scope = url.origin === origin ? 'app' : url.origin === issuer ? 'issuer' : undefined - authorizationEvidence.observe(request, scope, stage) + authorizationEvidence.observe(request, scope, stage, url.pathname) if (url.origin === origin && url.pathname === '/session/sign-in') starts.push(request) if (request.method() === 'GET' && url.origin === issuer && url.pathname === '/oauth2/authorize' && url.searchParams.get('redirect_uri') === origin + '/session/callback') { From 01f1b590cfe52b9189dc5f71410c70600b40e555 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:45:54 +0000 Subject: [PATCH 03/12] test: trace reference browser and edge request lifecycles Signed-off-by: Jeremi Joslin --- .../tests/browser-authorization.mjs | 107 +++++++-- .../tests/browser-edge.mjs | 74 ++++-- .../business-registration/tests/browser.mjs | 5 +- .../business-registration/tests/receipt.mjs | 6 +- .../tests/receipt.test.mjs | 215 +++++++++++++++--- 5 files changed, 325 insertions(+), 82 deletions(-) diff --git a/deploy/examples/business-registration/tests/browser-authorization.mjs b/deploy/examples/business-registration/tests/browser-authorization.mjs index fbd8c9e469..ca602555a2 100644 --- a/deploy/examples/business-registration/tests/browser-authorization.mjs +++ b/deploy/examples/business-registration/tests/browser-authorization.mjs @@ -2,17 +2,46 @@ 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', ]) -function routeClass(scope, pathname) { - if (scope === 'issuer' && pathname === '/oauth2/logout') return 'logout' - if (scope === 'issuer' && pathname === '/oauth2/authorize') return 'authorize' - if (scope === 'app' && pathname === '/session/sign-out') return 'sign-out' - if (scope === 'app' && pathname === '/session/signed-out') return 'signed-out' - return 'other' +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']) + +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 const browserStages = Object.freeze({ @@ -54,28 +83,50 @@ export class BrowserAuthorizationError extends Error {} 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() + const row = recorded.get(id) + if (event === undefined) { + if (row || recorded.size >= maxRows || !validRequestFields(request)) throw new Error() + recorded.set(id, { id, ...request, upstreamHeaders: false, downstreamFinished: false, downstreamClosed: false }) + continue + } + if (!row || line.length >= maxEventLine || Object.keys(request).length !== 0 || !isBrowserEdgeEvent(event) + || row[event] || (event === 'downstreamFinished' && !row.upstreamHeaders)) throw new Error() + row[event] = true + } + return [...recorded.values()] } catch { throw new BrowserAuthorizationError('Browser edge records missing, incomplete, or invalid.') } } -function checkedRecordedRequestIds(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') +} + +function checkedRecordedRequests(recordedRequests) { if (!Array.isArray(recordedRequests)) { throw new BrowserAuthorizationError('Browser authorization receipt is missing edge evidence.') } - const recorded = new Set() + const recorded = new Map() const counts = { app: 0, issuer: 0 } const present = [] for (const row of recordedRequests) { - const { id, headerNames } = row ?? {} + const { id, upstreamHeaders, downstreamFinished, downstreamClosed, ...request } = row ?? {} if (typeof id !== 'string' || !requestId.test(id) || recorded.has(id) - || Object.keys(row).length !== 2 || !Array.isArray(headerNames) - || headerNames.length > 1 || (headerNames.length === 1 && headerNames[0] !== 'authorization')) { + || !validRequestFields(request) || typeof upstreamHeaders !== 'boolean' + || typeof downstreamFinished !== 'boolean' || typeof downstreamClosed !== 'boolean' + || (downstreamFinished && !upstreamHeaders)) { throw new BrowserAuthorizationError('Browser edge record is invalid or duplicated.') } const scope = id.slice(0, id.indexOf('-')) @@ -83,8 +134,8 @@ function checkedRecordedRequestIds(recordedRequests) { if (id !== `${scope}-${counts[scope]}`) { throw new BrowserAuthorizationError('Browser edge record sequence is incomplete or out of order.') } - recorded.add(id) - if (headerNames.length === 1) present.push(`${id}: Authorization header present at the browser edge`) + recorded.set(id, row) + if (request.headerNames.length === 1) present.push(`${id}: Authorization header present at the browser edge`) } if (present.length) throw new BrowserAuthorizationError(present.join('\n')) return recorded @@ -93,7 +144,7 @@ function checkedRecordedRequestIds(recordedRequests) { function unmatchedRecordedRows(recordedRequests, observedRequestIds) { let recorded try { - recorded = checkedRecordedRequestIds(recordedRequests) + recorded = checkedRecordedRequests(recordedRequests) } catch (error) { if (!(error instanceof BrowserAuthorizationError)) throw error return 'Unmatched recorded edge rows unavailable (edge records failed validation).' @@ -101,8 +152,18 @@ function unmatchedRecordedRows(recordedRequests, observedRequestIds) { // Only a same-scope response marker can tie a browser observation to a row. for (const id of observedRequestIds) recorded.delete(id) const counts = { app: 0, issuer: 0 } - for (const id of recorded) counts[id.slice(0, id.indexOf('-'))] += 1 - return `Unmatched recorded edge rows: app=${counts.app} issuer=${counts.issuer}.` + for (const id of recorded.keys()) 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 recorded.values()) { + if (lines.length > maxReportedRequests) break + 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)}`) + } + const remaining = recorded.size - (lines.length - 1) + if (remaining > 0) lines.push(`${remaining} more unmatched recorded edge rows.`) + return lines.join('\n') } export function assertBrowserAuthorizationEvidence(evidence) { @@ -110,7 +171,7 @@ export function assertBrowserAuthorizationEvidence(evidence) { if (!Array.isArray(observedRequestIds)) { throw new BrowserAuthorizationError('Browser authorization receipt is missing edge evidence.') } - const recorded = checkedRecordedRequestIds(recordedRequests) + const recorded = checkedRecordedRequests(recordedRequests) const observed = new Set() const scopes = new Set() @@ -135,7 +196,7 @@ export class BrowserAuthorizationEvidence { this.#limit = limit } - observe(request, scope, stage, pathname) { + observe(request, scope, stage, pathname, method) { if (this.#requests.has(request) || this.#requests.size >= this.#limit) { this.#invalid = true return @@ -144,7 +205,7 @@ export class BrowserAuthorizationEvidence { ordinal: this.#requests.size + 1, scope: scope === 'app' || scope === 'issuer' ? scope : 'other', stage: knownStages.has(stage) ? stage : 'unknown', - route: routeClass(scope, pathname), + ...classifyBrowserRequest(scope, pathname, method), responded: false, outcome: 'pending', receipt: Promise.withResolvers(), }) } @@ -205,7 +266,7 @@ export class BrowserAuthorizationEvidence { 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},` + + ` (scope=${entry.scope}, stage="${entry.stage}", route-class=${entry.route}, method=${entry.method},` + ` resource-type=${resource}, redirect-parent-ordinal=${parentOrdinal},` + ` before close: ${entry.beforeClose ?? 'not observed'},` + ` after close: ${formatRequestState(marker, entry.outcome)})`) diff --git a/deploy/examples/business-registration/tests/browser-edge.mjs b/deploy/examples/business-registration/tests/browser-edge.mjs index 7694000963..a926c0aaf9 100644 --- a/deploy/examples/business-registration/tests/browser-edge.mjs +++ b/deploy/examples/business-registration/tests/browser-edge.mjs @@ -4,6 +4,7 @@ import { createServer, request } from 'node:https' import { checkServerIdentity } from 'node:tls' import { join } from 'node:path' import { fileURLToPath } from 'node:url' +import { classifyBrowserRequest, isBrowserEdgeEvent } from './browser-authorization.mjs' export const browserEvidenceHeader = 'x-registry-reference-request-id' export const browserEvidenceFilename = 'browser-authorization.jsonl' @@ -12,10 +13,10 @@ export const maxBrowserEvidenceRows = 2048 export function createBrowserHeaderRecorder(path) { const counts = { app: 0, issuer: 0 } let identity, size = 0, rows = 0, failed = false - return (scope, rawHeaders) => { + function append(record) { let fd try { - if (failed || !Object.hasOwn(counts, scope) || !Array.isArray(rawHeaders) || rawHeaders.length % 2) throw new Error() + if (failed) throw new Error() try { fd = openSync(path, constants.O_WRONLY | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK) } catch (error) { @@ -24,24 +25,13 @@ export function createBrowserHeaderRecorder(path) { } const stat = fstatSync(fd) if (!stat.isFile() || (stat.mode & 0o777) !== 0o600 || stat.uid !== process.getuid() || - stat.size !== size || (identity && identity !== `${stat.dev}:${stat.ino}`) || - rows >= maxBrowserEvidenceRows) throw new Error() + stat.size !== size || (identity && identity !== `${stat.dev}:${stat.ino}`)) throw new Error() identity = `${stat.dev}:${stat.ino}` - // Inspect original names, including an empty field, before any forwarding. - const headerNames = [] - for (let index = 0; index < rawHeaders.length; index += 2) { - if (rawHeaders[index].toLowerCase() === 'authorization') { - headerNames.push('authorization') - break - } - } - const id = `${scope}-${++counts[scope]}` - const row = `${JSON.stringify({ id, headerNames })}\n` + const row = `${JSON.stringify(record)}\n` if (writeSync(fd, row) !== Buffer.byteLength(row)) throw new Error() fsyncSync(fd) size += Buffer.byteLength(row) - rows++ - return id + return true } catch { failed = true throw new Error('Browser edge evidence failed.') @@ -54,6 +44,37 @@ export function createBrowserHeaderRecorder(path) { } } } + return (scope, rawHeaders, target, method) => { + try { + if (failed || !Object.hasOwn(counts, scope) || !Array.isArray(rawHeaders) || rawHeaders.length % 2 + || rows >= maxBrowserEvidenceRows) throw new Error() + // Inspect original names, including an empty field, before any forwarding. + const headerNames = [] + for (let index = 0; index < rawHeaders.length; index += 2) { + if (rawHeaders[index].toLowerCase() === 'authorization') { + headerNames.push('authorization') + break + } + } + const id = `${scope}-${counts[scope] + 1}` + if (!append({ id, headerNames, ...classifyBrowserRequest(scope, target, method) })) return null + counts[scope]++ + rows++ + return { + id, + note(event) { + if (!isBrowserEdgeEvent(event)) { + failed = true + throw new Error('Browser edge evidence failed.') + } + append({ id, event }) + }, + } + } catch { + failed = true + throw new Error('Browser edge evidence failed.') + } + } } function mappedPort(value) { @@ -101,15 +122,29 @@ export async function startBrowserEdge(config, upstreamPorts, listenPorts, onFai minVersion: 'TLSv1.2', maxHeaderSize: 16 * 1024, }, (incoming, outgoing) => { - let id + let evidence try { - id = record(scope, incoming.rawHeaders) + evidence = record(scope, incoming.rawHeaders, incoming.url, incoming.method) } catch { incoming.destroy() outgoing.destroy() fail() return } + const id = evidence?.id + const note = event => { + try { + evidence?.note(event) + return true + } catch { + fail() + return false + } + } + if (id) { + outgoing.once('finish', () => note('downstreamFinished')) + outgoing.once('close', () => note('downstreamClosed')) + } const upstream = request({ hostname: '127.0.0.1', port: upstreamPorts[index], ca, rejectUnauthorized: true, servername: scope === 'issuer' ? 'identity.reference.test' : '', @@ -117,6 +152,8 @@ export async function startBrowserEdge(config, upstreamPorts, listenPorts, onFai method: incoming.method, path: incoming.url, headers: incoming.headers, agent: false, }, response => { + response.on('error', fail) + if (!note('upstreamHeaders')) return const headers = [] for (let n = 0; n < response.rawHeaders.length; n += 2) { const name = response.rawHeaders[n].toLowerCase() @@ -125,7 +162,6 @@ export async function startBrowserEdge(config, upstreamPorts, listenPorts, onFai } if (id) headers.push(browserEvidenceHeader, id, 'cache-control', 'no-store') outgoing.writeHead(response.statusCode, response.statusMessage, headers) - response.on('error', fail) response.pipe(outgoing) }) upstream.on('socket', socket => { diff --git a/deploy/examples/business-registration/tests/browser.mjs b/deploy/examples/business-registration/tests/browser.mjs index 3f3e9442ba..cbd259bbd1 100644 --- a/deploy/examples/business-registration/tests/browser.mjs +++ b/deploy/examples/business-registration/tests/browser.mjs @@ -31,9 +31,10 @@ async function signIn(person, path = '/apply/', expectedSignIn = 'registrar') { context.on('request', request => { const url = new URL(request.url()) const scope = url.origin === origin ? 'app' : url.origin === issuer ? 'issuer' : undefined - authorizationEvidence.observe(request, scope, stage, url.pathname) + const method = request.method() + authorizationEvidence.observe(request, scope, stage, url.pathname, method) if (url.origin === origin && url.pathname === '/session/sign-in') starts.push(request) - if (request.method() === 'GET' && url.origin === issuer && url.pathname === '/oauth2/authorize' + if (method === 'GET' && url.origin === issuer && url.pathname === '/oauth2/authorize' && url.searchParams.get('redirect_uri') === origin + '/session/callback') { // The issuer can revisit the authorize URL within the same OIDC state. const state = url.searchParams.get('state') diff --git a/deploy/examples/business-registration/tests/receipt.mjs b/deploy/examples/business-registration/tests/receipt.mjs index 8a44ed6d30..3cfd0f4543 100644 --- a/deploy/examples/business-registration/tests/receipt.mjs +++ b/deploy/examples/business-registration/tests/receipt.mjs @@ -45,8 +45,12 @@ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.ar const recordedRequests = await readBrowserAuthorizationRecords(edgePath, maxBrowserEvidenceRows) const evidence = receipt.browserAuthorization assertBrowserAuthorizationEvidence({ ...evidence, recordedRequests }) + // Lifecycle events may still arrive between browser finalization and edge shutdown. if (recordedRequests.length !== evidence.recordedRequests.length - || recordedRequests.some((row, index) => row.id !== evidence.recordedRequests[index].id)) { + || recordedRequests.some(({ id, route, method }, index) => { + const prior = evidence.recordedRequests[index] + return id !== prior.id || route !== prior.route || method !== prior.method + })) { throw new BrowserAuthorizationError('Browser edge records changed after browser finalization.') } } diff --git a/deploy/examples/business-registration/tests/receipt.test.mjs b/deploy/examples/business-registration/tests/receipt.test.mjs index 89693706ea..853da33919 100644 --- a/deploy/examples/business-registration/tests/receipt.test.mjs +++ b/deploy/examples/business-registration/tests/receipt.test.mjs @@ -1,7 +1,8 @@ import assert from 'node:assert/strict' import { spawnSync } from 'node:child_process' -import { copyFileSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { createServer } from 'node:http' +import { createServer as createHttpsServer, get as httpsGet } from 'node:https' import { tmpdir } from 'node:os' import { join } from 'node:path' import { test } from 'node:test' @@ -10,10 +11,14 @@ import { BrowserAuthorizationEvidence, browserStages, readBrowserAuthorizationRe import { browserEvidenceHeader, createBrowserHeaderRecorder, startBrowserEdge } from './browser-edge.mjs' import { assertReceipt } from './receipt.mjs' -const recordedRequests = [ - { id: 'app-1', headerNames: [] }, - { id: 'issuer-1', headerNames: [] }, -] +const edgeRow = (id, fields = {}) => ({ + id, headerNames: [], route: 'other', method: 'other', + upstreamHeaders: false, downstreamFinished: false, downstreamClosed: false, ...fields, +}) +const recordedRequests = [edgeRow('app-1'), edgeRow('issuer-1')] +const ledgerLine = (id, fields = {}) => JSON.stringify({ + id, headerNames: [], route: 'other', method: 'other', ...fields, +}) + '\n' const browserAuthorization = { observedRequestIds: ['app-1', 'issuer-1'], recordedRequests } const baseline = { @@ -95,9 +100,9 @@ test('a positive browser receipt requires complete edge evidence without Authori { ...browserAuthorization, observedRequestIds: ['app-1', 'issuer-3'] }, { ...browserAuthorization, observedRequestIds: ['app-1', 'issuer-1', 'app-1'] }, { ...browserAuthorization, recordedRequests: [...recordedRequests, recordedRequests[0]] }, - { ...browserAuthorization, recordedRequests: [{ id: 'app-1', headerNames: ['authorization'] }, recordedRequests[1]] }, - { ...browserAuthorization, recordedRequests: [...recordedRequests, { id: 'app-2', headerNames: ['authorization'] }] }, - { ...browserAuthorization, recordedRequests: [...recordedRequests, { id: 'app-2', headerNames: [], private: 'redaction canary' }] }, + { ...browserAuthorization, recordedRequests: [edgeRow('app-1', { headerNames: ['authorization'] }), recordedRequests[1]] }, + { ...browserAuthorization, recordedRequests: [...recordedRequests, edgeRow('app-2', { headerNames: ['authorization'] })] }, + { ...browserAuthorization, recordedRequests: [...recordedRequests, edgeRow('app-2', { private: 'redaction canary' })] }, ]) assert.throws(() => withEvidence(evidence)) }) @@ -108,7 +113,7 @@ test('each edge ledger scope starts at one and has no sequence gaps', () => { ['app-1', 'issuer-1', 'app-3'], ['app-1', 'issuer-1', 'issuer-3', 'issuer-2'], ]) { - const evidence = { observedRequestIds: ids, recordedRequests: ids.map(id => ({ id, headerNames: [] })) } + const evidence = { observedRequestIds: ids, recordedRequests: ids.map(id => edgeRow(id)) } assert.throws(() => assertReceipt('breg', { ...baseline, browserAuthorization: evidence }), { message: 'Browser edge record sequence is incomplete or out of order.', }) @@ -122,14 +127,18 @@ test('the stopped edge ledger must agree with the browser receipt at final valid const edgeLog = join(scratch, 'edge.jsonl') writeFileSync(report, JSON.stringify(baseline)) const command = [fileURLToPath(new URL('./receipt.mjs', import.meta.url)), 'breg', report, edgeLog] - const save = rows => writeFileSync(edgeLog, rows.map(row => JSON.stringify(row) + '\n').join('')) + const save = rows => writeFileSync(edgeLog, rows.map(({ id, headerNames }) => ledgerLine(id, { headerNames })).join('')) save(recordedRequests) assert.equal(spawnSync(process.execPath, command).status, 0) - save([...recordedRequests, { id: 'app-2', headerNames: ['authorization'] }]) + writeFileSync(edgeLog, ledgerLine('app-1', { route: 'sign-out', method: 'POST' }) + ledgerLine('issuer-1')) + const changed = spawnSync(process.execPath, command, { encoding: 'utf8' }) + assert.equal(changed.status, 1) + assert.match(changed.stderr, /Browser edge records changed after browser finalization/) + save([...recordedRequests, edgeRow('app-2', { headerNames: ['authorization'] })]) const forbidden = spawnSync(process.execPath, command, { encoding: 'utf8' }) assert.equal(forbidden.status, 1) assert.match(forbidden.stderr, /Authorization header present at the browser edge/) - save([...recordedRequests, { id: 'app-2', headerNames: [] }]) + save([...recordedRequests, edgeRow('app-2')]) const late = spawnSync(process.execPath, command, { encoding: 'utf8' }) assert.equal(late.status, 1) assert.match(late.stderr, /Browser edge records changed after browser finalization/) @@ -148,7 +157,7 @@ test('browser authorization records match each observed request across both orig observed.observeResponse(app, 'app-1') await observed.waitForResponses() assert.deepEqual(observed.receipt(recordedRequests), browserAuthorization) - const withUnmatchedRow = [...recordedRequests, { id: 'app-2', headerNames: [] }] + const withUnmatchedRow = [...recordedRequests, edgeRow('app-2')] assert.deepEqual(observed.receipt(withUnmatchedRow), { ...browserAuthorization, recordedRequests: withUnmatchedRow, }) @@ -162,19 +171,24 @@ test('an unresolved issuer logout document reports its redirect parent and unmat redirectedFrom: () => app, failure: () => ({ errorText: 'synthetic-request-error-canary' }), } - observed.observe(app, 'app', browserStages.signOut, '/session/sign-out') + observed.observe(app, 'app', browserStages.signOut, '/session/sign-out', 'POST') const logout = new URL('https://issuer.invalid/oauth2/logout?id_token_hint=synthetic-token-canary') - observed.observe(issuer, 'issuer', browserStages.returnFromIssuer, logout.pathname) + observed.observe(issuer, 'issuer', browserStages.returnFromIssuer, logout.pathname, 'GET') observed.observeResponse(app, 'app-1') - const rows = [...recordedRequests, { id: 'issuer-2', headerNames: [] }, { id: 'app-2', headerNames: [] }] + const rows = [...recordedRequests, edgeRow('issuer-2', { + route: 'logout', method: 'GET', downstreamClosed: true, + }), edgeRow('app-2')] await observed.waitForResponses(20) observed.observeRequestEnd(issuer, false) assert.throws(() => observed.receipt(rows), { message: 'request #2: no matching edge response marker before Chromium closed' + ' (scope=issuer, stage="return from the issuer to the signed-out page",' - + ' route-class=logout, resource-type=document, redirect-parent-ordinal=1,' + + ' route-class=logout, method=GET, resource-type=document, redirect-parent-ordinal=1,' + ' before close: response=pending request=pending, after close: response=pending request=failed)' - + '\nUnmatched recorded edge rows: app=1 issuer=2.', + + '\nUnmatched recorded edge rows: app=1 issuer=2.' + + '\nedge issuer-1: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no' + + '\nedge issuer-2: route-class=logout method=GET upstream-headers=no downstream-finished=no downstream-closed=yes' + + '\nedge app-2: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no', }) }) @@ -191,7 +205,7 @@ test('a valid response marker delivered during Chromium shutdown completes the e observed.observeResponse(issuer, 'issuer-1') observed.observeRequestEnd(issuer, true) assert.deepEqual(observed.receipt(recordedRequests), browserAuthorization) - const forbidden = [...recordedRequests, { id: 'issuer-2', headerNames: ['authorization'] }] + const forbidden = [...recordedRequests, edgeRow('issuer-2', { headerNames: ['authorization'] })] assert.throws(() => observed.receipt(forbidden), { message: 'issuer-2: Authorization header present at the browser edge', }) @@ -203,10 +217,10 @@ test('unresolved markers report only fixed request state', async () => { const malformed = { resourceType: () => 'image' } const other = { resourceType: () => 'synthetic-resource-type-canary' } const unmarked = { resourceType: () => 'fetch', redirectedFrom: () => ({}) } - observed.observe(wrongScope, 'app', browserStages.signOut, '/session/sign-out') - observed.observe(malformed, 'issuer', 'synthetic-stage-canary', '/path-canary') + observed.observe(wrongScope, 'app', browserStages.signOut, '/session/sign-out', 'POST') + observed.observe(malformed, 'issuer', 'synthetic-stage-canary', '/path-canary', 'synthetic-method-canary') observed.observe(other, 'https://origin-canary.invalid', undefined, '/oauth2/logout') - observed.observe(unmarked, 'issuer', undefined, '/oauth2/authorize') + observed.observe(unmarked, 'issuer', undefined, '/oauth2/authorize', 'GET') observed.observeResponse(wrongScope, 'issuer-1') observed.observeResponse(malformed, 'synthetic-header-value-canary') observed.observeResponse(other, 'app-1') @@ -218,22 +232,24 @@ test('unresolved markers report only fixed request state', async () => { message: [ 'request #1: no matching edge response marker before Chromium closed' + ' (scope=app, stage="submit the first registrar sign-out form",' - + ' route-class=sign-out, resource-type=document, redirect-parent-ordinal=none,' + + ' route-class=sign-out, method=POST, resource-type=document, redirect-parent-ordinal=none,' + ' before close: response=wrong-scope-marker request=finished,' + ' after close: response=wrong-scope-marker request=finished)', 'request #2: no matching edge response marker before Chromium closed' - + ' (scope=issuer, stage="unknown", route-class=other, resource-type=image, redirect-parent-ordinal=none,' + + ' (scope=issuer, stage="unknown", route-class=other, method=other, resource-type=image, redirect-parent-ordinal=none,' + ' before close: response=invalid-marker request=pending,' + ' after close: response=invalid-marker request=pending)', 'request #3: no matching edge response marker before Chromium closed' - + ' (scope=other, stage="unknown", route-class=other, resource-type=other, redirect-parent-ordinal=none,' + + ' (scope=other, stage="unknown", route-class=other, method=other, resource-type=other, redirect-parent-ordinal=none,' + ' before close: response=wrong-scope-marker request=pending,' + ' after close: response=wrong-scope-marker request=pending)', 'request #4: no matching edge response marker before Chromium closed' - + ' (scope=issuer, stage="unknown", route-class=authorize, resource-type=fetch, redirect-parent-ordinal=unobserved,' + + ' (scope=issuer, stage="unknown", route-class=authorize, method=GET, resource-type=fetch, redirect-parent-ordinal=unobserved,' + ' before close: response=pending request=pending,' + ' after close: response=unmarked request=finished)', 'Unmatched recorded edge rows: app=1 issuer=1.', + 'edge app-1: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no', + 'edge issuer-1: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no', ].join('\n'), }) const invalidRows = [...recordedRequests, { id: 'synthetic-row-canary', headerNames: [] }] @@ -244,6 +260,44 @@ test('unresolved markers report only fixed request state', async () => { }) }) +test('browser and edge diagnostics share the supported route and method classes', async () => { + const scratch = mkdtempSync(join(tmpdir(), 'reference-edge-classes-')) + try { + const path = join(scratch, 'record.jsonl') + writeFileSync(path, '', { flag: 'wx', mode: 0o600 }) + const record = createBrowserHeaderRecorder(path) + const cases = [ + ['issuer', '/flow/meta', 'GET', 'flow-meta', 'GET'], + ['issuer', '/.well-known/openid-configuration', 'GET', 'discovery', 'GET'], + ['issuer', '/oauth2/jwks', 'GET', 'jwks', 'GET'], + ['issuer', '/flow/execute', 'POST', 'flow-execute', 'POST'], + ['issuer', '/oauth2/auth/callback', 'POST', 'issuer-callback', 'POST'], + ['issuer', '/i18n/languages/en-US/translations/resolve', 'GET', 'issuer-text', 'GET'], + ['app', '/session/callback', 'GET', 'session-callback', 'GET'], + ['app', '/flow/meta', 'HEAD', 'other', 'HEAD'], + ['issuer', '/i18n/synthetic-path-canary', 'synthetic-method-canary', 'other', 'other'], + ] + for (const [scope, pathname, method, routeClass, methodBucket] of cases) { + const observed = new BrowserAuthorizationEvidence(1) + const request = { resourceType: () => 'fetch' } + observed.observe(request, scope, browserStages.returnFromIssuer, pathname, method) + observed.observeResponse(request, undefined) + await observed.waitForResponses() + record(scope, [], pathname + '?key=synthetic-query-canary', method) + const rows = await readBrowserAuthorizationRecords(path, 10) + assert.deepEqual(rows.at(-1), edgeRow(rows.at(-1).id, { route: routeClass, method: methodBucket })) + assert.throws(() => observed.receipt(rows), error => { + assert.ok(error.message.includes(`route-class=${routeClass}, method=${methodBucket}, resource-type=fetch`)) + assert.doesNotMatch(error.message, /canary/u) + return true + }) + } + assert.doesNotMatch(readFileSync(path, 'utf8'), /canary/u) + } finally { + rmSync(scratch, { recursive: true }) + } +}) + test('unresolved marker diagnostics cap the ordinals and count the remaining requests', async () => { const observed = new BrowserAuthorizationEvidence(10) for (let index = 0; index < 6; index++) { @@ -252,13 +306,19 @@ test('unresolved marker diagnostics cap the ordinals and count the remaining req observed.observeResponse(request, undefined) } await observed.waitForResponses() - assert.throws(() => observed.receipt(recordedRequests), { + const rows = [...recordedRequests, ...[2, 3, 4, 5].map(id => edgeRow(`issuer-${id}`))] + assert.throws(() => observed.receipt(rows), { message: [1, 2, 3, 4].map(ordinal => `request #${ordinal}: no matching edge response marker before Chromium closed` - + ' (scope=app, stage="unknown", route-class=other, resource-type=other, redirect-parent-ordinal=none,' + + ' (scope=app, stage="unknown", route-class=other, method=other, resource-type=other, redirect-parent-ordinal=none,' + ' before close: response=unmarked request=pending,' + ' after close: response=unmarked request=pending)', - ).concat('2 more unresolved browser requests', 'Unmatched recorded edge rows: app=1 issuer=1.').join('\n'), + ).concat( + '2 more unresolved browser requests', 'Unmatched recorded edge rows: app=1 issuer=5.', + ...rows.slice(0, 4).map(({ id }) => + `edge ${id}: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no`), + '2 more unmatched recorded edge rows.', + ).join('\n'), }) }) @@ -273,10 +333,10 @@ test('the edge proof includes requests observed during the wait and finalization observed.observeResponse(app, 'app-1') setImmediate(() => observed.observeResponse(issuer, 'issuer-1')) await checked - observed.observe(late, 'app', browserStages.closeChromium, '/session/signed-out') + observed.observe(late, 'app', browserStages.closeChromium, '/session/signed-out', 'GET') assert.throws(() => observed.receipt(recordedRequests), { message: 'request #3: no matching edge response marker before Chromium closed' - + ' (scope=app, stage="close Chromium", route-class=signed-out, resource-type=other, redirect-parent-ordinal=none,' + + ' (scope=app, stage="close Chromium", route-class=signed-out, method=GET, resource-type=other, redirect-parent-ordinal=none,' + ' before close: not observed, after close: response=pending request=pending)' + '\nUnmatched recorded edge rows: app=0 issuer=0.', }) @@ -292,7 +352,7 @@ test('absent or malformed private edge records cannot establish browser authoriz message: 'Browser edge records missing, incomplete, or invalid.', }) } - writeFileSync(path, recordedRequests.map(row => JSON.stringify(row) + '\n').join('')) + writeFileSync(path, recordedRequests.map(({ id }) => ledgerLine(id)).join('')) assert.deepEqual(await readBrowserAuthorizationRecords(path, 10), recordedRequests) await assert.rejects(readBrowserAuthorizationRecords(path, 1)) } finally { @@ -300,13 +360,51 @@ test('absent or malformed private edge records cannot establish browser authoriz } }) +test('the edge ledger retains interleaved request lifecycle events and refuses invalid updates', async () => { + const scratch = mkdtempSync(join(tmpdir(), 'reference-edge-lifecycle-')) + try { + const path = join(scratch, 'record.jsonl') + writeFileSync(path, '', { flag: 'wx', mode: 0o600 }) + const record = createBrowserHeaderRecorder(path) + const app = record('app', [], '/session/signed-out', 'GET') + const issuer = record('issuer', [], '/flow/meta', 'GET') + app.note('upstreamHeaders') + issuer.note('downstreamClosed') + app.note('downstreamFinished') + app.note('downstreamClosed') + issuer.note('upstreamHeaders') + assert.deepEqual(await readBrowserAuthorizationRecords(path, 2), [ + edgeRow('app-1', { route: 'signed-out', method: 'GET', upstreamHeaders: true, + downstreamFinished: true, downstreamClosed: true }), + edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', upstreamHeaders: true, downstreamClosed: true }), + ]) + const event = (id, name, extra = {}) => JSON.stringify({ id, event: name, ...extra }) + '\n' + for (const data of [ + event('app-1', 'downstreamClosed') + ledgerLine('app-1'), + ledgerLine('app-1') + event('app-2', 'downstreamClosed'), + ledgerLine('app-1') + event('app-1', 'downstreamFinished'), + ledgerLine('app-1') + event('app-1', 'downstreamClosed') + event('app-1', 'downstreamClosed'), + ledgerLine('app-1') + event('app-1', 'downstreamClosed', { private: 'synthetic-row-canary' }), + ledgerLine('app-1', { route: 'synthetic-route-canary' }), + ]) { + writeFileSync(path, data) + await assert.rejects(readBrowserAuthorizationRecords(path, 2), { + message: 'Browser edge records missing, incomplete, or invalid.', + }) + } + } finally { + rmSync(scratch, { recursive: true }) + } +}) + test('a live ingress request carrying Authorization prevents a checked receipt', async () => { const scratch = mkdtempSync(join(tmpdir(), 'reference-edge-header-')) const path = join(scratch, 'record.jsonl') writeFileSync(path, '', { flag: 'wx', mode: 0o600 }) const record = createBrowserHeaderRecorder(path) const server = createServer((request, response) => { - response.setHeader(browserEvidenceHeader, record(request.url === '/issuer' ? 'issuer' : 'app', request.rawHeaders)) + const { id } = record(request.url === '/issuer' ? 'issuer' : 'app', request.rawHeaders, request.url, request.method) + response.setHeader(browserEvidenceHeader, id) response.end('Synthetic test response') }) try { @@ -325,7 +423,7 @@ test('a live ingress request carrying Authorization prevents a checked receipt', const forbiddenId = forbidden.headers.get(browserEvidenceHeader) await forbidden.text() const evidence = await readEvidence() - assert.deepEqual(evidence.recordedRequests.at(-1), { id: forbiddenId, headerNames: ['authorization'] }) + assert.deepEqual(evidence.recordedRequests.at(-1), edgeRow(forbiddenId, { headerNames: ['authorization'], method: 'GET' })) assert.throws(() => assertReceipt('breg', { ...baseline, browserAuthorization: evidence }), { message: `${forbiddenId}: Authorization header present at the browser edge`, }) @@ -346,9 +444,9 @@ test('the edge recorder inspects raw field names without interpreting values', a record('app', ['x-fixture', 'synthetic-only', 'aUtHoRiZaTiOn', '']) record('issuer', ['AUTHORIZATION', 'synthetic-only', 'Authorization', '']) assert.deepEqual(await readBrowserAuthorizationRecords(path, 10), [ - { id: 'app-1', headerNames: [] }, - { id: 'app-2', headerNames: ['authorization'] }, - { id: 'issuer-1', headerNames: ['authorization'] }, + edgeRow('app-1'), + edgeRow('app-2', { headerNames: ['authorization'] }), + edgeRow('issuer-1', { headerNames: ['authorization'] }), ]) } finally { rmSync(scratch, { recursive: true }) @@ -380,6 +478,49 @@ function prepareEdgeTls(directory) { return local.cert } +test('HTTPS ingress records upstream headers and downstream finish and close for the same marker', { timeout: 5_000 }, async () => { + const scratch = mkdtempSync(join(tmpdir(), 'reference-ingress-lifecycle-')) + try { + const trusted = prepareEdgeTls(scratch) + const upstream = createHttpsServer({ + key: readFileSync(join(scratch, 'local.key')), cert: readFileSync(trusted), + }, (_, response) => { + response.end('Synthetic fixture response') + }) + await new Promise(resolve => upstream.listen(0, '127.0.0.1', resolve)) + try { + const path = join(scratch, 'browser-authorization.jsonl') + writeFileSync(path, '', { flag: 'wx', mode: 0o600 }) + const port = upstream.address().port + const edge = await startBrowserEdge(scratch, [port, port], [0, 0], assert.fail) + let id + try { + id = await new Promise((resolve, reject) => { + const fail = () => reject(new Error('Synthetic ingress request failed.')) + httpsGet({ hostname: '127.0.0.1', port: edge.servers[1].address().port, + ca: readFileSync(trusted), path: '/flow/meta?key=synthetic-query-canary' }, response => { + response.resume() + response.on('end', () => resolve(response.headers[browserEvidenceHeader])) + response.on('error', fail) + }).on('error', fail) + }) + } finally { + await edge.close() + } + assert.equal(id, 'issuer-1') + assert.deepEqual(await readBrowserAuthorizationRecords(path, 1), [ + edgeRow(id, { route: 'flow-meta', method: 'GET', upstreamHeaders: true, + downstreamFinished: true, downstreamClosed: true }), + ]) + } finally { + upstream.closeAllConnections() + await new Promise(resolve => upstream.close(resolve)) + } + } finally { + rmSync(scratch, { recursive: true }) + } +}) + test('each HTTPS ingress uses a byte bound without truncating the header list', async () => { const scratch = mkdtempSync(join(tmpdir(), 'reference-ingress-limits-')) try { From 08470e68d16cb9f09c0d355bd8b19253f7684766 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 09:51:32 +0000 Subject: [PATCH 04/12] fix: preserve reference browser evidence through final validation Signed-off-by: Jeremi Joslin --- .../tests/browser-authorization.mjs | 17 +++-- .../business-registration/tests/receipt.mjs | 7 +- .../tests/receipt.test.mjs | 64 +++++++++++++++++++ 3 files changed, 82 insertions(+), 6 deletions(-) diff --git a/deploy/examples/business-registration/tests/browser-authorization.mjs b/deploy/examples/business-registration/tests/browser-authorization.mjs index ca602555a2..3a7141aa21 100644 --- a/deploy/examples/business-registration/tests/browser-authorization.mjs +++ b/deploy/examples/business-registration/tests/browser-authorization.mjs @@ -141,7 +141,7 @@ function checkedRecordedRequests(recordedRequests) { return recorded } -function unmatchedRecordedRows(recordedRequests, observedRequestIds) { +function unmatchedRecordedRows(recordedRequests, observations) { let recorded try { recorded = checkedRecordedRequests(recordedRequests) @@ -149,8 +149,17 @@ function unmatchedRecordedRows(recordedRequests, observedRequestIds) { if (!(error instanceof BrowserAuthorizationError)) throw error return 'Unmatched recorded edge rows unavailable (edge records failed validation).' } - // Only a same-scope response marker can tie a browser observation to a row. - for (const id of observedRequestIds) recorded.delete(id) + // 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)) + } + } + for (const [id, matches] of uniqueMatches) { + if (matches) recorded.delete(id) + } const counts = { app: 0, issuer: 0 } for (const id of recorded.keys()) counts[id.slice(0, id.indexOf('-'))] += 1 const lines = [`Unmatched recorded edge rows: app=${counts.app} issuer=${counts.issuer}.`] @@ -274,7 +283,7 @@ export class BrowserAuthorizationEvidence { } if (missingCount > missing.length) missing.push(`${missingCount - missing.length} more unresolved browser requests`) if (missing.length) { - missing.push(unmatchedRecordedRows(recordedRequests, observedRequestIds)) + missing.push(unmatchedRecordedRows(recordedRequests, this.#requests.values())) throw new BrowserAuthorizationError(missing.join('\n')) } const evidence = { observedRequestIds, recordedRequests } diff --git a/deploy/examples/business-registration/tests/receipt.mjs b/deploy/examples/business-registration/tests/receipt.mjs index 3cfd0f4543..8a35d3c2b9 100644 --- a/deploy/examples/business-registration/tests/receipt.mjs +++ b/deploy/examples/business-registration/tests/receipt.mjs @@ -47,9 +47,12 @@ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.ar assertBrowserAuthorizationEvidence({ ...evidence, recordedRequests }) // Lifecycle events may still arrive between browser finalization and edge shutdown. if (recordedRequests.length !== evidence.recordedRequests.length - || recordedRequests.some(({ id, route, method }, index) => { + || recordedRequests.some((row, index) => { const prior = evidence.recordedRequests[index] - return id !== prior.id || route !== prior.route || method !== prior.method + return row.id !== prior.id || row.route !== prior.route || row.method !== prior.method + || (prior.upstreamHeaders && !row.upstreamHeaders) + || (prior.downstreamFinished && !row.downstreamFinished) + || (prior.downstreamClosed && !row.downstreamClosed) })) { throw new BrowserAuthorizationError('Browser edge records changed after browser finalization.') } diff --git a/deploy/examples/business-registration/tests/receipt.test.mjs b/deploy/examples/business-registration/tests/receipt.test.mjs index 853da33919..b2ca4895eb 100644 --- a/deploy/examples/business-registration/tests/receipt.test.mjs +++ b/deploy/examples/business-registration/tests/receipt.test.mjs @@ -147,6 +147,52 @@ test('the stopped edge ledger must agree with the browser receipt at final valid } }) +test('the stopped edge ledger preserves observed lifecycle events and accepts later events', () => { + const scratch = mkdtempSync(join(tmpdir(), 'reference-final-edge-lifecycle-')) + try { + const report = join(scratch, 'report.json') + const edgeLog = join(scratch, 'edge.jsonl') + const requestRows = ledgerLine('app-1') + ledgerLine('issuer-1') + const eventLine = (id, event) => JSON.stringify({ id, event }) + '\n' + const appHeaders = eventLine('app-1', 'upstreamHeaders') + const appFinished = eventLine('app-1', 'downstreamFinished') + const appClosed = eventLine('app-1', 'downstreamClosed') + const issuerHeaders = eventLine('issuer-1', 'upstreamHeaders') + const observed = requestRows + appHeaders + appFinished + appClosed + issuerHeaders + const later = observed + eventLine('issuer-1', 'downstreamFinished') + eventLine('issuer-1', 'downstreamClosed') + const evidence = { + ...browserAuthorization, + recordedRequests: [ + edgeRow('app-1', { upstreamHeaders: true, downstreamFinished: true, downstreamClosed: true }), + edgeRow('issuer-1', { upstreamHeaders: true }), + ], + } + + for (const [profile, receipt] of [['breg', baseline], ['casework', casework]]) { + writeFileSync(report, JSON.stringify({ ...receipt, browserAuthorization: evidence })) + const command = [fileURLToPath(new URL('./receipt.mjs', import.meta.url)), profile, report, edgeLog] + for (const ledger of [observed, later]) { + writeFileSync(edgeLog, ledger) + const result = spawnSync(process.execPath, command, { encoding: 'utf8' }) + assert.equal(result.status, 0, result.stderr) + } + for (const [missing, ledger] of [ + ['all events', requestRows], + ['issuer headers', requestRows + appHeaders + appFinished + appClosed], + ['app finish', requestRows + appHeaders + appClosed + issuerHeaders], + ['app close', requestRows + appHeaders + appFinished + issuerHeaders], + ]) { + writeFileSync(edgeLog, ledger) + const result = spawnSync(process.execPath, command, { encoding: 'utf8' }) + assert.equal(result.status, 1, `${profile} ledger missing ${missing}`) + assert.match(result.stderr, /Browser edge records changed after browser finalization/u) + } + } + } finally { + rmSync(scratch, { recursive: true }) + } +}) + test('browser authorization records match each observed request across both origins', async () => { const observed = new BrowserAuthorizationEvidence(10) const app = {} @@ -192,6 +238,24 @@ test('an unresolved issuer logout document reports its redirect parent and unmat }) }) +test('an unresolved request leaves a row with duplicated markers unmatched', async () => { + for (const duplicateScope of ['app', 'issuer']) { + const observed = new BrowserAuthorizationEvidence(4) + for (const [scope, id] of [ + [duplicateScope, 'app-1'], ['app', 'app-1'], ['issuer', 'issuer-1'], ['issuer', undefined], + ]) { + const request = {} + observed.observe(request, scope) + observed.observeResponse(request, id) + } + await observed.waitForResponses() + assert.throws(() => observed.receipt(recordedRequests), error => { + assert.match(error.message, /\nUnmatched recorded edge rows: app=1 issuer=0\.\nedge app-1:/u) + return true + }) + } +}) + test('a valid response marker delivered during Chromium shutdown completes the evidence', { timeout: 1_000 }, async () => { const observed = new BrowserAuthorizationEvidence(10) const app = {} From 0d83dff8ec7657b34f847cd7c7406bf7186f7ac8 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 10:20:07 +0000 Subject: [PATCH 05/12] test: keep the generated ingress certificate in memory for the request Signed-off-by: Jeremi Joslin --- .../tests/receipt.test.mjs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/deploy/examples/business-registration/tests/receipt.test.mjs b/deploy/examples/business-registration/tests/receipt.test.mjs index b2ca4895eb..e1fc645025 100644 --- a/deploy/examples/business-registration/tests/receipt.test.mjs +++ b/deploy/examples/business-registration/tests/receipt.test.mjs @@ -523,10 +523,12 @@ function makeCertificate(directory, name) { const openssl = spawnSync('openssl', [ 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-noenc', '-days', '1', '-subj', '/CN=reference-fixture', '-addext', 'subjectAltName=IP:127.0.0.1,DNS:identity.reference.test', - '-keyout', key, '-out', cert, - ], { stdio: 'ignore' }) + '-keyout', key, + ], { stdio: ['ignore', 'pipe', 'ignore'] }) assert.equal(openssl.status, 0, 'Generate a disposable test certificate') - return { key, cert } + const certificate = openssl.stdout + writeFileSync(cert, certificate, { flag: 'wx' }) + return { key, cert, certificate } } function prepareEdgeTls(directory) { @@ -539,15 +541,15 @@ function prepareEdgeTls(directory) { } mkdirSync(join(directory, 'trust')) copyFileSync(local.cert, join(directory, 'trust', 'https-ca.pem')) - return local.cert + return local } test('HTTPS ingress records upstream headers and downstream finish and close for the same marker', { timeout: 5_000 }, async () => { const scratch = mkdtempSync(join(tmpdir(), 'reference-ingress-lifecycle-')) try { - const trusted = prepareEdgeTls(scratch) + const { key, certificate } = prepareEdgeTls(scratch) const upstream = createHttpsServer({ - key: readFileSync(join(scratch, 'local.key')), cert: readFileSync(trusted), + key: readFileSync(key), cert: certificate, }, (_, response) => { response.end('Synthetic fixture response') }) @@ -562,7 +564,7 @@ test('HTTPS ingress records upstream headers and downstream finish and close for id = await new Promise((resolve, reject) => { const fail = () => reject(new Error('Synthetic ingress request failed.')) httpsGet({ hostname: '127.0.0.1', port: edge.servers[1].address().port, - ca: readFileSync(trusted), path: '/flow/meta?key=synthetic-query-canary' }, response => { + ca: certificate, path: '/flow/meta?key=synthetic-query-canary' }, response => { response.resume() response.on('end', () => resolve(response.headers[browserEvidenceHeader])) response.on('error', fail) @@ -658,7 +660,7 @@ test('upstream TLS refuses an untrusted fixture certificate under an inherited o await new Promise(resolve => upstream.close(resolve)) } ` - const result = spawnSync(process.execPath, ['--input-type=module', '-', scratch, trusted, untrusted.key, untrusted.cert], { + const result = spawnSync(process.execPath, ['--input-type=module', '-', scratch, trusted.cert, untrusted.key, untrusted.cert], { input: script, env: { ...process.env, NODE_TLS_REJECT_UNAUTHORIZED: '0' }, encoding: 'utf8', From 1b4abd3f8f37b1d4837204250ca3922a890a0d01 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 10:41:36 +0000 Subject: [PATCH 06/12] test: expose delayed issuer metadata response markers Signed-off-by: Jeremi Joslin --- .../tests/receipt.test.mjs | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/deploy/examples/business-registration/tests/receipt.test.mjs b/deploy/examples/business-registration/tests/receipt.test.mjs index e1fc645025..566fed8373 100644 --- a/deploy/examples/business-registration/tests/receipt.test.mjs +++ b/deploy/examples/business-registration/tests/receipt.test.mjs @@ -587,6 +587,59 @@ test('HTTPS ingress records upstream headers and downstream finish and close for } }) +test('issuer flow metadata exposes its edge marker while the upstream body is pending', { timeout: 5_000 }, async () => { + const scratch = mkdtempSync(join(tmpdir(), 'reference-ingress-metadata-')) + try { + const { key, certificate } = prepareEdgeTls(scratch) + const releaseBody = Promise.withResolvers() + const upstream = createHttpsServer({ key: readFileSync(key), cert: certificate }, (_, response) => { + response.writeHead(200, { 'Content-Type': 'application/json' }) + response.flushHeaders() + void releaseBody.promise.then(() => response.end('{}')) + }) + await new Promise(resolve => upstream.listen(0, '127.0.0.1', resolve)) + try { + const path = join(scratch, 'browser-authorization.jsonl') + writeFileSync(path, '', { flag: 'wx', mode: 0o600 }) + const port = upstream.address().port + const edge = await startBrowserEdge(scratch, [port, port], [0, 0], assert.fail) + let beforeBody + try { + const headers = new Promise((resolve, reject) => { + httpsGet({ hostname: '127.0.0.1', port: edge.servers[1].address().port, ca: certificate, + path: '/flow/meta?type=synthetic' }, resolve).on('error', reject) + }) + let timer + const deadline = new Promise(resolve => { timer = setTimeout(resolve, 1_000) }) + beforeBody = await Promise.race([headers, deadline]).finally(() => clearTimeout(timer)) + assert.deepEqual(await readBrowserAuthorizationRecords(path, 1), [ + edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', upstreamHeaders: true }), + ]) + releaseBody.resolve() + const response = await headers + assert.equal(response.statusCode, 200) + assert.equal(response.headers[browserEvidenceHeader], 'issuer-1') + let body = '' + for await (const chunk of response) body += chunk + assert.equal(body, '{}') + } finally { + releaseBody.resolve() + await edge.close() + } + assert.deepEqual(await readBrowserAuthorizationRecords(path, 1), [ + edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', upstreamHeaders: true, + downstreamFinished: true, downstreamClosed: true }), + ]) + assert.ok(beforeBody, 'Issuer marker did not arrive before the body was released.') + } finally { + upstream.closeAllConnections() + await new Promise(resolve => upstream.close(resolve)) + } + } finally { + rmSync(scratch, { recursive: true }) + } +}) + test('each HTTPS ingress uses a byte bound without truncating the header list', async () => { const scratch = mkdtempSync(join(tmpdir(), 'reference-ingress-limits-')) try { From 3a8f3a7e368523137d7e6aeb9182ca9c6c9bc841 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 10:43:18 +0000 Subject: [PATCH 07/12] fix: send issuer metadata markers before streaming the body Signed-off-by: Jeremi Joslin --- .../examples/business-registration/tests/browser-edge.mjs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/deploy/examples/business-registration/tests/browser-edge.mjs b/deploy/examples/business-registration/tests/browser-edge.mjs index a926c0aaf9..4a0715ed43 100644 --- a/deploy/examples/business-registration/tests/browser-edge.mjs +++ b/deploy/examples/business-registration/tests/browser-edge.mjs @@ -57,11 +57,13 @@ export function createBrowserHeaderRecorder(path) { } } const id = `${scope}-${counts[scope] + 1}` - if (!append({ id, headerNames, ...classifyBrowserRequest(scope, target, method) })) return null + const request = classifyBrowserRequest(scope, target, method) + if (!append({ id, headerNames, ...request })) return null counts[scope]++ rows++ return { id, + ...request, note(event) { if (!isBrowserEdgeEvent(event)) { failed = true @@ -162,6 +164,9 @@ export async function startBrowserEdge(config, upstreamPorts, listenPorts, onFai } if (id) headers.push(browserEvidenceHeader, id, 'cache-control', 'no-store') outgoing.writeHead(response.statusCode, response.statusMessage, headers) + // The issuer can navigate away while its metadata body is still in flight. + // Send the recorded response ID as soon as the upstream headers arrive. + if (evidence?.route === 'flow-meta' && evidence.method === 'GET') outgoing.flushHeaders() response.pipe(outgoing) }) upstream.on('socket', socket => { From b230e48c0e7e70dcc23163c81bcab51787798733 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 10:59:59 +0000 Subject: [PATCH 08/12] test: trace issuer metadata through browser sign-out Signed-off-by: Jeremi Joslin --- .../tests/browser-authorization.mjs | 66 ++++++++++--- .../business-registration/tests/browser.mjs | 35 ++++++- .../business-registration/tests/receipt.mjs | 6 +- .../tests/receipt.test.mjs | 99 +++++++++++++++---- 4 files changed, 167 insertions(+), 39 deletions(-) diff --git a/deploy/examples/business-registration/tests/browser-authorization.mjs b/deploy/examples/business-registration/tests/browser-authorization.mjs index 3a7141aa21..b53bed4113 100644 --- a/deploy/examples/business-registration/tests/browser-authorization.mjs +++ b/deploy/examples/business-registration/tests/browser-authorization.mjs @@ -30,6 +30,12 @@ const issuerTextPath = /^\/i18n\/languages(?:\/[^/]+\/translations(?:\/ns\/[^/]+ 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']) +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] @@ -44,6 +50,17 @@ export function isBrowserEdgeEvent(event) { return edgeEvents.has(event) } +function validEdgeEvents(events) { + if (!Array.isArray(events) || events.length > edgeEvents.size) return false + const seen = new Set() + for (const event of events) { + if (!isBrowserEdgeEvent(event) || seen.has(event) + || (event === 'downstreamFinished' && !seen.has('upstreamHeaders'))) return false + seen.add(event) + } + return true +} + export const browserStages = Object.freeze({ firstSignIn: 'sign in the first registrar', secondSignIn: 'sign in the second registrar', @@ -78,6 +95,12 @@ 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 readBrowserAuthorizationRecords(path, maxRows) { @@ -94,12 +117,12 @@ export async function readBrowserAuthorizationRecords(path, maxRows) { const row = recorded.get(id) if (event === undefined) { if (row || recorded.size >= maxRows || !validRequestFields(request)) throw new Error() - recorded.set(id, { id, ...request, upstreamHeaders: false, downstreamFinished: false, downstreamClosed: false }) + recorded.set(id, { id, ...request, events: [] }) continue } - if (!row || line.length >= maxEventLine || Object.keys(request).length !== 0 || !isBrowserEdgeEvent(event) - || row[event] || (event === 'downstreamFinished' && !row.upstreamHeaders)) throw new Error() - row[event] = true + if (!row || line.length >= maxEventLine || Object.keys(request).length !== 0) throw new Error() + row.events.push(event) + if (!validEdgeEvents(row.events)) throw new Error() } return [...recorded.values()] } catch { @@ -122,11 +145,9 @@ function checkedRecordedRequests(recordedRequests) { const counts = { app: 0, issuer: 0 } const present = [] for (const row of recordedRequests) { - const { id, upstreamHeaders, downstreamFinished, downstreamClosed, ...request } = row ?? {} + const { id, events, ...request } = row ?? {} if (typeof id !== 'string' || !requestId.test(id) || recorded.has(id) - || !validRequestFields(request) || typeof upstreamHeaders !== 'boolean' - || typeof downstreamFinished !== 'boolean' || typeof downstreamClosed !== 'boolean' - || (downstreamFinished && !upstreamHeaders)) { + || !validRequestFields(request) || !validEdgeEvents(events)) { throw new BrowserAuthorizationError('Browser edge record is invalid or duplicated.') } const scope = id.slice(0, id.indexOf('-')) @@ -163,12 +184,10 @@ function unmatchedRecordedRows(recordedRequests, observations) { const counts = { app: 0, issuer: 0 } for (const id of recorded.keys()) 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 recorded.values()) { if (lines.length > maxReportedRequests) break 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)}`) + + ` event-order=${row.events.join(',') || 'none'}`) } const remaining = recorded.size - (lines.length - 1) if (remaining > 0) lines.push(`${remaining} more unmatched recorded edge rows.`) @@ -198,6 +217,7 @@ export function assertBrowserAuthorizationEvidence(evidence) { export class BrowserAuthorizationEvidence { #requests = new Map() + #logoutCheckpoints = new Map() #limit #invalid = false @@ -235,6 +255,29 @@ export class BrowserAuthorizationEvidence { if (entry) entry.outcome = finished ? 'finished' : 'failed' } + observeLogoutCheckpoint(frame, checkpoint) { + if (!knownLogoutCheckpoints.includes(checkpoint)) { + throw new BrowserAuthorizationError('Browser logout checkpoint is invalid.') + } + if (this.#logoutCheckpoints.has(checkpoint)) return + const observed = new Map() + for (const [request, entry] of this.#requests) { + if (isLogoutMetadata(request, entry) && request.frame() === 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 details = [] + for (const [name, { frame, observed }] of this.#logoutCheckpoints) { + if (request.frame() === frame) details.push(` at ${name}: ${observed.get(request) ?? 'not yet observed'},`) + } + return details.join('') + } + async waitForResponses(timeoutMs = 10_000) { let timer const deadline = new Promise(resolve => { @@ -277,6 +320,7 @@ export class BrowserAuthorizationEvidence { 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)})`) } diff --git a/deploy/examples/business-registration/tests/browser.mjs b/deploy/examples/business-registration/tests/browser.mjs index cbd259bbd1..dd59c4112d 100644 --- a/deploy/examples/business-registration/tests/browser.mjs +++ b/deploy/examples/business-registration/tests/browser.mjs @@ -5,7 +5,7 @@ import { createHash, randomUUID, X509Certificate } from 'node:crypto' import { readFile } from 'node:fs/promises' import { isAbsolute, join } from 'node:path' import { pathToFileURL } from 'node:url' -import { BrowserAuthorizationError, BrowserAuthorizationEvidence, browserStages, readBrowserAuthorizationRecords } from './browser-authorization.mjs' +import { BrowserAuthorizationError, BrowserAuthorizationEvidence, browserStages, logoutCheckpoints, readBrowserAuthorizationRecords } from './browser-authorization.mjs' import { browserEvidenceFilename, browserEvidenceHeader, maxBrowserEvidenceRows } from './browser-edge.mjs' import { assertReceipt } from './receipt.mjs' @@ -154,10 +154,35 @@ async function signOut(page) { form.append(button) document.body.append(form) }) - await page.getByRole('button', { name: 'Sign out for acceptance test' }).click() - assert.equal((await response).status(), 303) - startStage(browserStages.returnFromIssuer) - await page.waitForURL(origin + '/session/signed-out') + const signedOutUrl = origin + '/session/signed-out' + const mainFrame = page.mainFrame() + // Capture what the Playwright observer had seen when the real logout progressed. + const onRequest = request => { + if (request.method() === 'POST' && request.url() === issuer + '/oauth2/logout/callback' + && request.frame() === mainFrame) { + authorizationEvidence.observeLogoutCheckpoint(mainFrame, logoutCheckpoints.callbackRequest) + } + if (request.method() === 'GET' && request.url() === signedOutUrl + && request.isNavigationRequest() && request.frame() === mainFrame) { + authorizationEvidence.observeLogoutCheckpoint(mainFrame, logoutCheckpoints.signedOutRequest) + } + } + const onFrameNavigated = frame => { + if (frame === mainFrame && frame.url() === signedOutUrl) { + authorizationEvidence.observeLogoutCheckpoint(mainFrame, logoutCheckpoints.signedOutCommit) + } + } + page.on('request', onRequest) + page.on('framenavigated', onFrameNavigated) + try { + await page.getByRole('button', { name: 'Sign out for acceptance test' }).click() + assert.equal((await response).status(), 303) + startStage(browserStages.returnFromIssuer) + await page.waitForURL(signedOutUrl) + } finally { + page.off('request', onRequest) + page.off('framenavigated', onFrameNavigated) + } } let stage diff --git a/deploy/examples/business-registration/tests/receipt.mjs b/deploy/examples/business-registration/tests/receipt.mjs index 8a35d3c2b9..193095d94f 100644 --- a/deploy/examples/business-registration/tests/receipt.mjs +++ b/deploy/examples/business-registration/tests/receipt.mjs @@ -45,14 +45,12 @@ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.ar const recordedRequests = await readBrowserAuthorizationRecords(edgePath, maxBrowserEvidenceRows) const evidence = receipt.browserAuthorization assertBrowserAuthorizationEvidence({ ...evidence, recordedRequests }) - // Lifecycle events may still arrive between browser finalization and edge shutdown. + // Lifecycle events may still be appended between browser finalization and edge shutdown. if (recordedRequests.length !== evidence.recordedRequests.length || recordedRequests.some((row, index) => { const prior = evidence.recordedRequests[index] return row.id !== prior.id || row.route !== prior.route || row.method !== prior.method - || (prior.upstreamHeaders && !row.upstreamHeaders) - || (prior.downstreamFinished && !row.downstreamFinished) - || (prior.downstreamClosed && !row.downstreamClosed) + || prior.events.some((event, position) => event !== row.events[position]) })) { throw new BrowserAuthorizationError('Browser edge records changed after browser finalization.') } diff --git a/deploy/examples/business-registration/tests/receipt.test.mjs b/deploy/examples/business-registration/tests/receipt.test.mjs index 566fed8373..0660106b67 100644 --- a/deploy/examples/business-registration/tests/receipt.test.mjs +++ b/deploy/examples/business-registration/tests/receipt.test.mjs @@ -12,8 +12,7 @@ import { browserEvidenceHeader, createBrowserHeaderRecorder, startBrowserEdge } import { assertReceipt } from './receipt.mjs' const edgeRow = (id, fields = {}) => ({ - id, headerNames: [], route: 'other', method: 'other', - upstreamHeaders: false, downstreamFinished: false, downstreamClosed: false, ...fields, + id, headerNames: [], route: 'other', method: 'other', events: [], ...fields, }) const recordedRequests = [edgeRow('app-1'), edgeRow('issuer-1')] const ledgerLine = (id, fields = {}) => JSON.stringify({ @@ -103,6 +102,11 @@ test('a positive browser receipt requires complete edge evidence without Authori { ...browserAuthorization, recordedRequests: [edgeRow('app-1', { headerNames: ['authorization'] }), recordedRequests[1]] }, { ...browserAuthorization, recordedRequests: [...recordedRequests, edgeRow('app-2', { headerNames: ['authorization'] })] }, { ...browserAuthorization, recordedRequests: [...recordedRequests, edgeRow('app-2', { private: 'redaction canary' })] }, + ...[ + ['upstreamHeaders', 'upstreamHeaders'], + ['downstreamFinished', 'upstreamHeaders'], + ['synthetic-event-canary'], + ].map(events => ({ ...browserAuthorization, recordedRequests: [edgeRow('app-1', { events }), recordedRequests[1]] })), ]) assert.throws(() => withEvidence(evidence)) }) @@ -163,8 +167,8 @@ test('the stopped edge ledger preserves observed lifecycle events and accepts la const evidence = { ...browserAuthorization, recordedRequests: [ - edgeRow('app-1', { upstreamHeaders: true, downstreamFinished: true, downstreamClosed: true }), - edgeRow('issuer-1', { upstreamHeaders: true }), + edgeRow('app-1', { events: ['upstreamHeaders', 'downstreamFinished', 'downstreamClosed'] }), + edgeRow('issuer-1', { events: ['upstreamHeaders'] }), ], } @@ -181,6 +185,8 @@ test('the stopped edge ledger preserves observed lifecycle events and accepts la ['issuer headers', requestRows + appHeaders + appFinished + appClosed], ['app finish', requestRows + appHeaders + appClosed + issuerHeaders], ['app close', requestRows + appHeaders + appFinished + issuerHeaders], + ['issuer close inserted before previously observed headers', + observed.slice(0, -issuerHeaders.length) + eventLine('issuer-1', 'downstreamClosed') + issuerHeaders], ]) { writeFileSync(edgeLog, ledger) const result = spawnSync(process.execPath, command, { encoding: 'utf8' }) @@ -222,7 +228,7 @@ test('an unresolved issuer logout document reports its redirect parent and unmat observed.observe(issuer, 'issuer', browserStages.returnFromIssuer, logout.pathname, 'GET') observed.observeResponse(app, 'app-1') const rows = [...recordedRequests, edgeRow('issuer-2', { - route: 'logout', method: 'GET', downstreamClosed: true, + route: 'logout', method: 'GET', events: ['downstreamClosed'], }), edgeRow('app-2')] await observed.waitForResponses(20) observed.observeRequestEnd(issuer, false) @@ -232,9 +238,9 @@ test('an unresolved issuer logout document reports its redirect parent and unmat + ' route-class=logout, method=GET, resource-type=document, redirect-parent-ordinal=1,' + ' before close: response=pending request=pending, after close: response=pending request=failed)' + '\nUnmatched recorded edge rows: app=1 issuer=2.' - + '\nedge issuer-1: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no' - + '\nedge issuer-2: route-class=logout method=GET upstream-headers=no downstream-finished=no downstream-closed=yes' - + '\nedge app-2: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no', + + '\nedge issuer-1: route-class=other method=other event-order=none' + + '\nedge issuer-2: route-class=logout method=GET event-order=downstreamClosed' + + '\nedge app-2: route-class=other method=other event-order=none', }) }) @@ -256,6 +262,61 @@ test('an unresolved request leaves a row with duplicated markers unmatched', asy } }) +test('unmatched issuer metadata diagnostics distinguish close before and after upstream headers', async () => { + const scratch = mkdtempSync(join(tmpdir(), 'reference-unmatched-order-')) + try { + const path = join(scratch, 'record.jsonl') + const observed = new BrowserAuthorizationEvidence(2) + observed.observe({}, 'issuer', browserStages.returnFromIssuer, '/flow/meta', 'GET') + for (const events of [ + ['downstreamClosed', 'upstreamHeaders'], + ['upstreamHeaders', 'downstreamClosed'], + ]) { + writeFileSync(path, ledgerLine('issuer-1', { route: 'flow-meta', method: 'GET' }) + + events.map(event => JSON.stringify({ id: 'issuer-1', event }) + '\n').join('')) + const rows = await readBrowserAuthorizationRecords(path, 2) + assert.throws(() => observed.receipt(rows), error => { + assert.ok(error.message.includes('event-order=' + events.join(','))) + return true + }) + } + } finally { + rmSync(scratch, { recursive: true }) + } +}) + +test('issuer metadata diagnostics snapshot only the signing-out frame at each checkpoint', () => { + const observed = new BrowserAuthorizationEvidence(4) + const frame = {} + const secondFrame = {} + const request = { frame: () => frame, resourceType: () => 'fetch' } + const otherFrame = { frame: () => secondFrame, resourceType: () => 'fetch' } + const earlierRequest = { frame: () => frame, resourceType: () => 'fetch' } + const lateRequest = { frame: () => frame, resourceType: () => 'fetch' } + observed.observe(earlierRequest, 'issuer', browserStages.firstSignIn, '/flow/meta', 'GET') + observed.observe(request, 'issuer', browserStages.returnFromIssuer, '/flow/meta', 'GET') + observed.observe(otherFrame, 'issuer', browserStages.returnFromIssuer, '/flow/meta', 'GET') + observed.observeLogoutCheckpoint(frame, 'issuer logout callback request') + observed.observeLogoutCheckpoint(frame, 'signed-out document request') + observed.observe(lateRequest, 'issuer', browserStages.returnFromIssuer, '/flow/meta', 'GET') + observed.observeRequestEnd(request, false) + observed.observeLogoutCheckpoint(frame, 'signed-out document commit') + + assert.throws(() => observed.receipt(recordedRequests), error => { + const lines = error.message.split('\n') + assert.match(lines[1], /^request #2:/u) + assert.ok(lines[1].includes('at issuer logout callback request: response=pending request=pending,' + + ' at signed-out document request: response=pending request=pending,' + + ' at signed-out document commit: response=pending request=failed')) + assert.doesNotMatch(lines[0], /at .* request:|at .* commit:/u) + assert.doesNotMatch(lines[2], /at .* request:|at .* commit:/u) + assert.ok(lines[3].includes('at issuer logout callback request: not yet observed,' + + ' at signed-out document request: not yet observed,' + + ' at signed-out document commit: response=pending request=pending')) + return true + }) +}) + test('a valid response marker delivered during Chromium shutdown completes the evidence', { timeout: 1_000 }, async () => { const observed = new BrowserAuthorizationEvidence(10) const app = {} @@ -312,8 +373,8 @@ test('unresolved markers report only fixed request state', async () => { + ' before close: response=pending request=pending,' + ' after close: response=unmarked request=finished)', 'Unmatched recorded edge rows: app=1 issuer=1.', - 'edge app-1: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no', - 'edge issuer-1: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no', + 'edge app-1: route-class=other method=other event-order=none', + 'edge issuer-1: route-class=other method=other event-order=none', ].join('\n'), }) const invalidRows = [...recordedRequests, { id: 'synthetic-row-canary', headerNames: [] }] @@ -380,7 +441,7 @@ test('unresolved marker diagnostics cap the ordinals and count the remaining req ).concat( '2 more unresolved browser requests', 'Unmatched recorded edge rows: app=1 issuer=5.', ...rows.slice(0, 4).map(({ id }) => - `edge ${id}: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no`), + `edge ${id}: route-class=other method=other event-order=none`), '2 more unmatched recorded edge rows.', ).join('\n'), }) @@ -438,9 +499,9 @@ test('the edge ledger retains interleaved request lifecycle events and refuses i app.note('downstreamClosed') issuer.note('upstreamHeaders') assert.deepEqual(await readBrowserAuthorizationRecords(path, 2), [ - edgeRow('app-1', { route: 'signed-out', method: 'GET', upstreamHeaders: true, - downstreamFinished: true, downstreamClosed: true }), - edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', upstreamHeaders: true, downstreamClosed: true }), + edgeRow('app-1', { route: 'signed-out', method: 'GET', + events: ['upstreamHeaders', 'downstreamFinished', 'downstreamClosed'] }), + edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', events: ['downstreamClosed', 'upstreamHeaders'] }), ]) const event = (id, name, extra = {}) => JSON.stringify({ id, event: name, ...extra }) + '\n' for (const data of [ @@ -575,8 +636,8 @@ test('HTTPS ingress records upstream headers and downstream finish and close for } assert.equal(id, 'issuer-1') assert.deepEqual(await readBrowserAuthorizationRecords(path, 1), [ - edgeRow(id, { route: 'flow-meta', method: 'GET', upstreamHeaders: true, - downstreamFinished: true, downstreamClosed: true }), + edgeRow(id, { route: 'flow-meta', method: 'GET', + events: ['upstreamHeaders', 'downstreamFinished', 'downstreamClosed'] }), ]) } finally { upstream.closeAllConnections() @@ -613,7 +674,7 @@ test('issuer flow metadata exposes its edge marker while the upstream body is pe const deadline = new Promise(resolve => { timer = setTimeout(resolve, 1_000) }) beforeBody = await Promise.race([headers, deadline]).finally(() => clearTimeout(timer)) assert.deepEqual(await readBrowserAuthorizationRecords(path, 1), [ - edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', upstreamHeaders: true }), + edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', events: ['upstreamHeaders'] }), ]) releaseBody.resolve() const response = await headers @@ -627,8 +688,8 @@ test('issuer flow metadata exposes its edge marker while the upstream body is pe await edge.close() } assert.deepEqual(await readBrowserAuthorizationRecords(path, 1), [ - edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', upstreamHeaders: true, - downstreamFinished: true, downstreamClosed: true }), + edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', + events: ['upstreamHeaders', 'downstreamFinished', 'downstreamClosed'] }), ]) assert.ok(beforeBody, 'Issuer marker did not arrive before the body was released.') } finally { From 3e7f82cbd64e00665e89630cf1ac5911077fefbf Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 11:04:25 +0000 Subject: [PATCH 09/12] fix: keep browser edge event order in failure diagnostics Signed-off-by: Jeremi Joslin --- .../tests/browser-authorization.mjs | 51 ++++--- .../business-registration/tests/browser.mjs | 6 +- .../business-registration/tests/receipt.mjs | 6 +- .../tests/receipt.test.mjs | 141 +++++++++++++----- 4 files changed, 138 insertions(+), 66 deletions(-) diff --git a/deploy/examples/business-registration/tests/browser-authorization.mjs b/deploy/examples/business-registration/tests/browser-authorization.mjs index b53bed4113..2fc268a4d4 100644 --- a/deploy/examples/business-registration/tests/browser-authorization.mjs +++ b/deploy/examples/business-registration/tests/browser-authorization.mjs @@ -30,6 +30,8 @@ const issuerTextPath = /^\/i18n\/languages(?:\/[^/]+\/translations(?:\/ns\/[^/]+ 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', @@ -50,15 +52,13 @@ export function isBrowserEdgeEvent(event) { return edgeEvents.has(event) } -function validEdgeEvents(events) { - if (!Array.isArray(events) || events.length > edgeEvents.size) return false - const seen = new Set() - for (const event of events) { - if (!isBrowserEdgeEvent(event) || seen.has(event) - || (event === 'downstreamFinished' && !seen.has('upstreamHeaders'))) return false - seen.add(event) +export function requestFrameForDiagnostics(request) { + try { + return request.frame?.() + } catch { + // Playwright may report a request before its frame is available. + return undefined } - return true } export const browserStages = Object.freeze({ @@ -114,15 +114,18 @@ export async function readBrowserAuthorizationRecords(path, maxRows) { if (line.length >= maxRequestLine) throw new Error() const { id, event, ...request } = JSON.parse(line) if (typeof id !== 'string' || !requestId.test(id)) throw new Error() - const row = recorded.get(id) if (event === undefined) { - if (row || recorded.size >= maxRows || !validRequestFields(request)) throw new Error() - recorded.set(id, { id, ...request, events: [] }) + 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 } - if (!row || line.length >= maxEventLine || Object.keys(request).length !== 0) throw new Error() - row.events.push(event) - if (!validEdgeEvents(row.events)) throw new Error() + 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 { @@ -145,9 +148,11 @@ function checkedRecordedRequests(recordedRequests) { const counts = { app: 0, issuer: 0 } const present = [] for (const row of recordedRequests) { - const { id, events, ...request } = row ?? {} + const { id, upstreamHeaders, downstreamFinished, downstreamClosed, ...request } = row ?? {} if (typeof id !== 'string' || !requestId.test(id) || recorded.has(id) - || !validRequestFields(request) || !validEdgeEvents(events)) { + || !validRequestFields(request) || typeof upstreamHeaders !== 'boolean' + || typeof downstreamFinished !== 'boolean' || typeof downstreamClosed !== 'boolean' + || (downstreamFinished && !upstreamHeaders)) { throw new BrowserAuthorizationError('Browser edge record is invalid or duplicated.') } const scope = id.slice(0, id.indexOf('-')) @@ -184,10 +189,14 @@ function unmatchedRecordedRows(recordedRequests, observations) { const counts = { app: 0, issuer: 0 } for (const id of recorded.keys()) 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 recorded.values()) { if (lines.length > maxReportedRequests) break + const events = edgeEventOrder.get(row) lines.push(`edge ${row.id}: route-class=${row.route} method=${row.method}` - + ` event-order=${row.events.join(',') || 'none'}`) + + ` upstream-headers=${yesNo(row.upstreamHeaders)} downstream-finished=${yesNo(row.downstreamFinished)}` + + ` downstream-closed=${yesNo(row.downstreamClosed)}` + + (events?.length ? ` event-order=${events.join(',')}` : '')) } const remaining = recorded.size - (lines.length - 1) if (remaining > 0) lines.push(`${remaining} more unmatched recorded edge rows.`) @@ -259,10 +268,10 @@ export class BrowserAuthorizationEvidence { if (!knownLogoutCheckpoints.includes(checkpoint)) { throw new BrowserAuthorizationError('Browser logout checkpoint is invalid.') } - if (this.#logoutCheckpoints.has(checkpoint)) return + if (!frame || this.#logoutCheckpoints.has(checkpoint)) return const observed = new Map() for (const [request, entry] of this.#requests) { - if (isLogoutMetadata(request, entry) && request.frame() === frame) { + if (isLogoutMetadata(request, entry) && requestFrameForDiagnostics(request) === frame) { observed.set(request, formatRequestState(responseMarkerState(entry), entry.outcome)) } } @@ -271,9 +280,11 @@ export class BrowserAuthorizationEvidence { #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 (request.frame() === frame) details.push(` at ${name}: ${observed.get(request) ?? 'not yet observed'},`) + if (requestFrame === frame) details.push(` at ${name}: ${observed.get(request) ?? 'not yet observed'},`) } return details.join('') } diff --git a/deploy/examples/business-registration/tests/browser.mjs b/deploy/examples/business-registration/tests/browser.mjs index dd59c4112d..c861bae749 100644 --- a/deploy/examples/business-registration/tests/browser.mjs +++ b/deploy/examples/business-registration/tests/browser.mjs @@ -5,7 +5,7 @@ import { createHash, randomUUID, X509Certificate } from 'node:crypto' import { readFile } from 'node:fs/promises' import { isAbsolute, join } from 'node:path' import { pathToFileURL } from 'node:url' -import { BrowserAuthorizationError, BrowserAuthorizationEvidence, browserStages, logoutCheckpoints, readBrowserAuthorizationRecords } from './browser-authorization.mjs' +import { BrowserAuthorizationError, BrowserAuthorizationEvidence, browserStages, logoutCheckpoints, readBrowserAuthorizationRecords, requestFrameForDiagnostics } from './browser-authorization.mjs' import { browserEvidenceFilename, browserEvidenceHeader, maxBrowserEvidenceRows } from './browser-edge.mjs' import { assertReceipt } from './receipt.mjs' @@ -159,11 +159,11 @@ async function signOut(page) { // Capture what the Playwright observer had seen when the real logout progressed. const onRequest = request => { if (request.method() === 'POST' && request.url() === issuer + '/oauth2/logout/callback' - && request.frame() === mainFrame) { + && requestFrameForDiagnostics(request) === mainFrame) { authorizationEvidence.observeLogoutCheckpoint(mainFrame, logoutCheckpoints.callbackRequest) } if (request.method() === 'GET' && request.url() === signedOutUrl - && request.isNavigationRequest() && request.frame() === mainFrame) { + && request.isNavigationRequest() && requestFrameForDiagnostics(request) === mainFrame) { authorizationEvidence.observeLogoutCheckpoint(mainFrame, logoutCheckpoints.signedOutRequest) } } diff --git a/deploy/examples/business-registration/tests/receipt.mjs b/deploy/examples/business-registration/tests/receipt.mjs index 193095d94f..8a35d3c2b9 100644 --- a/deploy/examples/business-registration/tests/receipt.mjs +++ b/deploy/examples/business-registration/tests/receipt.mjs @@ -45,12 +45,14 @@ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.ar const recordedRequests = await readBrowserAuthorizationRecords(edgePath, maxBrowserEvidenceRows) const evidence = receipt.browserAuthorization assertBrowserAuthorizationEvidence({ ...evidence, recordedRequests }) - // Lifecycle events may still be appended between browser finalization and edge shutdown. + // Lifecycle events may still arrive between browser finalization and edge shutdown. if (recordedRequests.length !== evidence.recordedRequests.length || recordedRequests.some((row, index) => { const prior = evidence.recordedRequests[index] return row.id !== prior.id || row.route !== prior.route || row.method !== prior.method - || prior.events.some((event, position) => event !== row.events[position]) + || (prior.upstreamHeaders && !row.upstreamHeaders) + || (prior.downstreamFinished && !row.downstreamFinished) + || (prior.downstreamClosed && !row.downstreamClosed) })) { throw new BrowserAuthorizationError('Browser edge records changed after browser finalization.') } diff --git a/deploy/examples/business-registration/tests/receipt.test.mjs b/deploy/examples/business-registration/tests/receipt.test.mjs index 0660106b67..df9e99289b 100644 --- a/deploy/examples/business-registration/tests/receipt.test.mjs +++ b/deploy/examples/business-registration/tests/receipt.test.mjs @@ -7,17 +7,19 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { test } from 'node:test' import { fileURLToPath } from 'node:url' -import { BrowserAuthorizationEvidence, browserStages, readBrowserAuthorizationRecords } from './browser-authorization.mjs' +import { BrowserAuthorizationError, BrowserAuthorizationEvidence, browserStages, logoutCheckpoints, readBrowserAuthorizationRecords } from './browser-authorization.mjs' import { browserEvidenceHeader, createBrowserHeaderRecorder, startBrowserEdge } from './browser-edge.mjs' import { assertReceipt } from './receipt.mjs' const edgeRow = (id, fields = {}) => ({ - id, headerNames: [], route: 'other', method: 'other', events: [], ...fields, + id, headerNames: [], route: 'other', method: 'other', + upstreamHeaders: false, downstreamFinished: false, downstreamClosed: false, ...fields, }) const recordedRequests = [edgeRow('app-1'), edgeRow('issuer-1')] const ledgerLine = (id, fields = {}) => JSON.stringify({ id, headerNames: [], route: 'other', method: 'other', ...fields, }) + '\n' +const eventLine = (id, event, extra = {}) => JSON.stringify({ id, event, ...extra }) + '\n' const browserAuthorization = { observedRequestIds: ['app-1', 'issuer-1'], recordedRequests } const baseline = { @@ -102,11 +104,9 @@ test('a positive browser receipt requires complete edge evidence without Authori { ...browserAuthorization, recordedRequests: [edgeRow('app-1', { headerNames: ['authorization'] }), recordedRequests[1]] }, { ...browserAuthorization, recordedRequests: [...recordedRequests, edgeRow('app-2', { headerNames: ['authorization'] })] }, { ...browserAuthorization, recordedRequests: [...recordedRequests, edgeRow('app-2', { private: 'redaction canary' })] }, - ...[ - ['upstreamHeaders', 'upstreamHeaders'], - ['downstreamFinished', 'upstreamHeaders'], - ['synthetic-event-canary'], - ].map(events => ({ ...browserAuthorization, recordedRequests: [edgeRow('app-1', { events }), recordedRequests[1]] })), + ...[{ events: [] }, { upstreamHeaders: 1 }, { downstreamFinished: true }].map(fields => ({ + ...browserAuthorization, recordedRequests: [edgeRow('app-1', fields), recordedRequests[1]], + })), ]) assert.throws(() => withEvidence(evidence)) }) @@ -157,25 +157,26 @@ test('the stopped edge ledger preserves observed lifecycle events and accepts la const report = join(scratch, 'report.json') const edgeLog = join(scratch, 'edge.jsonl') const requestRows = ledgerLine('app-1') + ledgerLine('issuer-1') - const eventLine = (id, event) => JSON.stringify({ id, event }) + '\n' const appHeaders = eventLine('app-1', 'upstreamHeaders') const appFinished = eventLine('app-1', 'downstreamFinished') const appClosed = eventLine('app-1', 'downstreamClosed') const issuerHeaders = eventLine('issuer-1', 'upstreamHeaders') const observed = requestRows + appHeaders + appFinished + appClosed + issuerHeaders const later = observed + eventLine('issuer-1', 'downstreamFinished') + eventLine('issuer-1', 'downstreamClosed') + const closedBeforeHeaders = requestRows + appHeaders + appFinished + appClosed + + eventLine('issuer-1', 'downstreamClosed') + issuerHeaders const evidence = { ...browserAuthorization, recordedRequests: [ - edgeRow('app-1', { events: ['upstreamHeaders', 'downstreamFinished', 'downstreamClosed'] }), - edgeRow('issuer-1', { events: ['upstreamHeaders'] }), + edgeRow('app-1', { upstreamHeaders: true, downstreamFinished: true, downstreamClosed: true }), + edgeRow('issuer-1', { upstreamHeaders: true }), ], } for (const [profile, receipt] of [['breg', baseline], ['casework', casework]]) { writeFileSync(report, JSON.stringify({ ...receipt, browserAuthorization: evidence })) const command = [fileURLToPath(new URL('./receipt.mjs', import.meta.url)), profile, report, edgeLog] - for (const ledger of [observed, later]) { + for (const ledger of [observed, later, closedBeforeHeaders]) { writeFileSync(edgeLog, ledger) const result = spawnSync(process.execPath, command, { encoding: 'utf8' }) assert.equal(result.status, 0, result.stderr) @@ -185,8 +186,6 @@ test('the stopped edge ledger preserves observed lifecycle events and accepts la ['issuer headers', requestRows + appHeaders + appFinished + appClosed], ['app finish', requestRows + appHeaders + appClosed + issuerHeaders], ['app close', requestRows + appHeaders + appFinished + issuerHeaders], - ['issuer close inserted before previously observed headers', - observed.slice(0, -issuerHeaders.length) + eventLine('issuer-1', 'downstreamClosed') + issuerHeaders], ]) { writeFileSync(edgeLog, ledger) const result = spawnSync(process.execPath, command, { encoding: 'utf8' }) @@ -215,6 +214,36 @@ test('browser authorization records match each observed request across both orig }) }) +test('a successful browser receipt serializes exactly the existing authorization evidence', async () => { + const scratch = mkdtempSync(join(tmpdir(), 'reference-receipt-serialization-')) + try { + const path = join(scratch, 'record.jsonl') + writeFileSync(path, ledgerLine('app-1', { route: 'signed-out', method: 'GET' }) + + ledgerLine('issuer-1', { route: 'flow-meta', method: 'GET' }) + + eventLine('app-1', 'upstreamHeaders') + eventLine('issuer-1', 'downstreamClosed') + + eventLine('app-1', 'downstreamFinished') + eventLine('issuer-1', 'upstreamHeaders')) + const observed = new BrowserAuthorizationEvidence(2) + const frame = {} + const app = {} + const issuer = { frame: () => frame, resourceType: () => 'fetch' } + observed.observe(app, 'app', browserStages.returnFromIssuer, '/session/signed-out', 'GET') + observed.observe(issuer, 'issuer', browserStages.returnFromIssuer, '/flow/meta', 'GET') + observed.observeLogoutCheckpoint(frame, logoutCheckpoints.signedOutRequest) + observed.observeResponse(app, 'app-1') + observed.observeResponse(issuer, 'issuer-1') + + const rows = await readBrowserAuthorizationRecords(path, 2) + assert.equal(JSON.stringify(observed.receipt(rows)), + '{"observedRequestIds":["app-1","issuer-1"],"recordedRequests":[' + + '{"id":"app-1","headerNames":[],"route":"signed-out","method":"GET",' + + '"upstreamHeaders":true,"downstreamFinished":true,"downstreamClosed":false},' + + '{"id":"issuer-1","headerNames":[],"route":"flow-meta","method":"GET",' + + '"upstreamHeaders":true,"downstreamFinished":false,"downstreamClosed":true}]}') + } finally { + rmSync(scratch, { recursive: true }) + } +}) + test('an unresolved issuer logout document reports its redirect parent and unmatched edge totals', { timeout: 1_000 }, async () => { const observed = new BrowserAuthorizationEvidence(10) const app = {} @@ -228,7 +257,7 @@ test('an unresolved issuer logout document reports its redirect parent and unmat observed.observe(issuer, 'issuer', browserStages.returnFromIssuer, logout.pathname, 'GET') observed.observeResponse(app, 'app-1') const rows = [...recordedRequests, edgeRow('issuer-2', { - route: 'logout', method: 'GET', events: ['downstreamClosed'], + route: 'logout', method: 'GET', downstreamClosed: true, }), edgeRow('app-2')] await observed.waitForResponses(20) observed.observeRequestEnd(issuer, false) @@ -238,9 +267,9 @@ test('an unresolved issuer logout document reports its redirect parent and unmat + ' route-class=logout, method=GET, resource-type=document, redirect-parent-ordinal=1,' + ' before close: response=pending request=pending, after close: response=pending request=failed)' + '\nUnmatched recorded edge rows: app=1 issuer=2.' - + '\nedge issuer-1: route-class=other method=other event-order=none' - + '\nedge issuer-2: route-class=logout method=GET event-order=downstreamClosed' - + '\nedge app-2: route-class=other method=other event-order=none', + + '\nedge issuer-1: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no' + + '\nedge issuer-2: route-class=logout method=GET upstream-headers=no downstream-finished=no downstream-closed=yes' + + '\nedge app-2: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no', }) }) @@ -273,11 +302,16 @@ test('unmatched issuer metadata diagnostics distinguish close before and after u ['upstreamHeaders', 'downstreamClosed'], ]) { writeFileSync(path, ledgerLine('issuer-1', { route: 'flow-meta', method: 'GET' }) - + events.map(event => JSON.stringify({ id: 'issuer-1', event }) + '\n').join('')) + + events.map(event => eventLine('issuer-1', event)).join('')) const rows = await readBrowserAuthorizationRecords(path, 2) - assert.throws(() => observed.receipt(rows), error => { - assert.ok(error.message.includes('event-order=' + events.join(','))) - return true + assert.throws(() => observed.receipt(rows), { + message: 'request #1: no matching edge response marker before Chromium closed' + + ' (scope=issuer, stage="return from the issuer to the signed-out page",' + + ' route-class=flow-meta, method=GET, resource-type=other, redirect-parent-ordinal=none,' + + ' before close: not observed, after close: response=pending request=pending)' + + '\nUnmatched recorded edge rows: app=0 issuer=1.' + + '\nedge issuer-1: route-class=flow-meta method=GET upstream-headers=yes downstream-finished=no downstream-closed=yes' + + ` event-order=${events.join(',')}`, }) } } finally { @@ -296,11 +330,11 @@ test('issuer metadata diagnostics snapshot only the signing-out frame at each ch observed.observe(earlierRequest, 'issuer', browserStages.firstSignIn, '/flow/meta', 'GET') observed.observe(request, 'issuer', browserStages.returnFromIssuer, '/flow/meta', 'GET') observed.observe(otherFrame, 'issuer', browserStages.returnFromIssuer, '/flow/meta', 'GET') - observed.observeLogoutCheckpoint(frame, 'issuer logout callback request') - observed.observeLogoutCheckpoint(frame, 'signed-out document request') + observed.observeLogoutCheckpoint(frame, logoutCheckpoints.callbackRequest) + observed.observeLogoutCheckpoint(frame, logoutCheckpoints.signedOutRequest) observed.observe(lateRequest, 'issuer', browserStages.returnFromIssuer, '/flow/meta', 'GET') observed.observeRequestEnd(request, false) - observed.observeLogoutCheckpoint(frame, 'signed-out document commit') + observed.observeLogoutCheckpoint(frame, logoutCheckpoints.signedOutCommit) assert.throws(() => observed.receipt(recordedRequests), error => { const lines = error.message.split('\n') @@ -317,6 +351,29 @@ test('issuer metadata diagnostics snapshot only the signing-out frame at each ch }) }) +test('an unavailable request frame leaves the missing-marker refusal and successful receipt intact', () => { + const observed = new BrowserAuthorizationEvidence(2) + const frame = {} + const app = {} + const issuer = { + resourceType: () => 'fetch', + frame: () => { throw new Error('synthetic unavailable frame') }, + } + observed.observe(app, 'app') + observed.observeResponse(app, 'app-1') + observed.observe(issuer, 'issuer', browserStages.returnFromIssuer, '/flow/meta', 'GET') + observed.observeLogoutCheckpoint(frame, logoutCheckpoints.signedOutCommit) + + assert.throws(() => observed.receipt(recordedRequests), error => { + assert.ok(error instanceof BrowserAuthorizationError) + assert.match(error.message, /^request #2: no matching edge response marker before Chromium closed/u) + assert.doesNotMatch(error.message, /at signed-out document commit|synthetic unavailable frame/u) + return true + }) + observed.observeResponse(issuer, 'issuer-1') + assert.deepEqual(observed.receipt(recordedRequests), browserAuthorization) +}) + test('a valid response marker delivered during Chromium shutdown completes the evidence', { timeout: 1_000 }, async () => { const observed = new BrowserAuthorizationEvidence(10) const app = {} @@ -373,8 +430,8 @@ test('unresolved markers report only fixed request state', async () => { + ' before close: response=pending request=pending,' + ' after close: response=unmarked request=finished)', 'Unmatched recorded edge rows: app=1 issuer=1.', - 'edge app-1: route-class=other method=other event-order=none', - 'edge issuer-1: route-class=other method=other event-order=none', + 'edge app-1: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no', + 'edge issuer-1: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no', ].join('\n'), }) const invalidRows = [...recordedRequests, { id: 'synthetic-row-canary', headerNames: [] }] @@ -441,7 +498,7 @@ test('unresolved marker diagnostics cap the ordinals and count the remaining req ).concat( '2 more unresolved browser requests', 'Unmatched recorded edge rows: app=1 issuer=5.', ...rows.slice(0, 4).map(({ id }) => - `edge ${id}: route-class=other method=other event-order=none`), + `edge ${id}: route-class=other method=other upstream-headers=no downstream-finished=no downstream-closed=no`), '2 more unmatched recorded edge rows.', ).join('\n'), }) @@ -499,17 +556,19 @@ test('the edge ledger retains interleaved request lifecycle events and refuses i app.note('downstreamClosed') issuer.note('upstreamHeaders') assert.deepEqual(await readBrowserAuthorizationRecords(path, 2), [ - edgeRow('app-1', { route: 'signed-out', method: 'GET', - events: ['upstreamHeaders', 'downstreamFinished', 'downstreamClosed'] }), - edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', events: ['downstreamClosed', 'upstreamHeaders'] }), + edgeRow('app-1', { route: 'signed-out', method: 'GET', upstreamHeaders: true, + downstreamFinished: true, downstreamClosed: true }), + edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', upstreamHeaders: true, downstreamClosed: true }), ]) - const event = (id, name, extra = {}) => JSON.stringify({ id, event: name, ...extra }) + '\n' + const closed = eventLine('app-1', 'downstreamClosed') for (const data of [ - event('app-1', 'downstreamClosed') + ledgerLine('app-1'), - ledgerLine('app-1') + event('app-2', 'downstreamClosed'), - ledgerLine('app-1') + event('app-1', 'downstreamFinished'), - ledgerLine('app-1') + event('app-1', 'downstreamClosed') + event('app-1', 'downstreamClosed'), - ledgerLine('app-1') + event('app-1', 'downstreamClosed', { private: 'synthetic-row-canary' }), + closed + ledgerLine('app-1'), + ledgerLine('app-1') + ledgerLine('app-1'), + ledgerLine('app-1') + eventLine('app-2', 'downstreamClosed'), + ledgerLine('app-1') + eventLine('app-1', 'downstreamFinished'), + ledgerLine('app-1') + closed + closed, + ledgerLine('app-1') + eventLine('app-1', 'synthetic-event-canary'), + ledgerLine('app-1') + eventLine('app-1', 'downstreamClosed', { private: 'synthetic-row-canary' }), ledgerLine('app-1', { route: 'synthetic-route-canary' }), ]) { writeFileSync(path, data) @@ -636,8 +695,8 @@ test('HTTPS ingress records upstream headers and downstream finish and close for } assert.equal(id, 'issuer-1') assert.deepEqual(await readBrowserAuthorizationRecords(path, 1), [ - edgeRow(id, { route: 'flow-meta', method: 'GET', - events: ['upstreamHeaders', 'downstreamFinished', 'downstreamClosed'] }), + edgeRow(id, { route: 'flow-meta', method: 'GET', upstreamHeaders: true, + downstreamFinished: true, downstreamClosed: true }), ]) } finally { upstream.closeAllConnections() @@ -674,7 +733,7 @@ test('issuer flow metadata exposes its edge marker while the upstream body is pe const deadline = new Promise(resolve => { timer = setTimeout(resolve, 1_000) }) beforeBody = await Promise.race([headers, deadline]).finally(() => clearTimeout(timer)) assert.deepEqual(await readBrowserAuthorizationRecords(path, 1), [ - edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', events: ['upstreamHeaders'] }), + edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', upstreamHeaders: true }), ]) releaseBody.resolve() const response = await headers @@ -688,8 +747,8 @@ test('issuer flow metadata exposes its edge marker while the upstream body is pe await edge.close() } assert.deepEqual(await readBrowserAuthorizationRecords(path, 1), [ - edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', - events: ['upstreamHeaders', 'downstreamFinished', 'downstreamClosed'] }), + edgeRow('issuer-1', { route: 'flow-meta', method: 'GET', upstreamHeaders: true, + downstreamFinished: true, downstreamClosed: true }), ]) assert.ok(beforeBody, 'Issuer marker did not arrive before the body was released.') } finally { From 2d86d2d5c76ed6f9a40e55a0a5a24a1511b7d585 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 11:25:06 +0000 Subject: [PATCH 10/12] test: drain issuer metadata before continuing logout Signed-off-by: Jeremi Joslin --- .../tests/browser-authorization.mjs | 83 ++++++- .../business-registration/tests/browser.mjs | 21 +- .../tests/receipt.test.mjs | 228 +++++++++++++++++- 3 files changed, 317 insertions(+), 15 deletions(-) diff --git a/deploy/examples/business-registration/tests/browser-authorization.mjs b/deploy/examples/business-registration/tests/browser-authorization.mjs index 2fc268a4d4..59ae1210be 100644 --- a/deploy/examples/business-registration/tests/browser-authorization.mjs +++ b/deploy/examples/business-registration/tests/browser-authorization.mjs @@ -103,6 +103,39 @@ function isLogoutMetadata(request, entry) { 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') @@ -227,6 +260,7 @@ export function assertBrowserAuthorizationEvidence(evidence) { export class BrowserAuthorizationEvidence { #requests = new Map() #logoutCheckpoints = new Map() + #logoutMetadataChanged #limit #invalid = false @@ -257,11 +291,52 @@ 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) { @@ -270,10 +345,8 @@ export class BrowserAuthorizationEvidence { } if (!frame || this.#logoutCheckpoints.has(checkpoint)) return const observed = new Map() - for (const [request, entry] of this.#requests) { - if (isLogoutMetadata(request, entry) && requestFrameForDiagnostics(request) === frame) { - observed.set(request, formatRequestState(responseMarkerState(entry), entry.outcome)) - } + for (const [request, entry] of this.#logoutMetadata(frame)) { + observed.set(request, formatRequestState(responseMarkerState(entry), entry.outcome)) } this.#logoutCheckpoints.set(checkpoint, { frame, observed }) } diff --git a/deploy/examples/business-registration/tests/browser.mjs b/deploy/examples/business-registration/tests/browser.mjs index c861bae749..7ef89f28c2 100644 --- a/deploy/examples/business-registration/tests/browser.mjs +++ b/deploy/examples/business-registration/tests/browser.mjs @@ -5,7 +5,7 @@ import { createHash, randomUUID, X509Certificate } from 'node:crypto' import { readFile } from 'node:fs/promises' import { isAbsolute, join } from 'node:path' import { pathToFileURL } from 'node:url' -import { BrowserAuthorizationError, BrowserAuthorizationEvidence, browserStages, logoutCheckpoints, readBrowserAuthorizationRecords, requestFrameForDiagnostics } from './browser-authorization.mjs' +import { BrowserAuthorizationError, BrowserAuthorizationEvidence, browserStages, logoutCheckpoints, readBrowserAuthorizationRecords, requestFrameForDiagnostics, withIssuerLogoutCallback } from './browser-authorization.mjs' import { browserEvidenceFilename, browserEvidenceHeader, maxBrowserEvidenceRows } from './browser-edge.mjs' import { assertReceipt } from './receipt.mjs' @@ -142,8 +142,6 @@ async function assertOwnRecord(page, expected) { async function signOut(page) { startStage(browserStages.signOut) - const response = page.waitForResponse(item => - item.url() === origin + '/session/sign-out' && item.request().method() === 'POST') // The frozen page is unchanged. Submit a top-level form as a service's own page would. await page.evaluate(() => { const form = document.createElement('form') @@ -154,11 +152,12 @@ async function signOut(page) { form.append(button) document.body.append(form) }) + const callbackUrl = issuer + '/oauth2/logout/callback' const signedOutUrl = origin + '/session/signed-out' const mainFrame = page.mainFrame() // Capture what the Playwright observer had seen when the real logout progressed. const onRequest = request => { - if (request.method() === 'POST' && request.url() === issuer + '/oauth2/logout/callback' + if (request.method() === 'POST' && request.url() === callbackUrl && requestFrameForDiagnostics(request) === mainFrame) { authorizationEvidence.observeLogoutCheckpoint(mainFrame, logoutCheckpoints.callbackRequest) } @@ -175,10 +174,16 @@ async function signOut(page) { page.on('request', onRequest) page.on('framenavigated', onFrameNavigated) try { - await page.getByRole('button', { name: 'Sign out for acceptance test' }).click() - assert.equal((await response).status(), 303) - startStage(browserStages.returnFromIssuer) - await page.waitForURL(signedOutUrl) + await withIssuerLogoutCallback(page, callbackUrl, authorizationEvidence, async () => { + const [response] = await Promise.all([ + page.waitForResponse(item => + item.url() === origin + '/session/sign-out' && item.request().method() === 'POST'), + page.getByRole('button', { name: 'Sign out for acceptance test' }).click(), + ]) + assert.equal(response.status(), 303) + startStage(browserStages.returnFromIssuer) + await page.waitForURL(signedOutUrl) + }) } finally { page.off('request', onRequest) page.off('framenavigated', onFrameNavigated) diff --git a/deploy/examples/business-registration/tests/receipt.test.mjs b/deploy/examples/business-registration/tests/receipt.test.mjs index df9e99289b..8ba43060b1 100644 --- a/deploy/examples/business-registration/tests/receipt.test.mjs +++ b/deploy/examples/business-registration/tests/receipt.test.mjs @@ -1,13 +1,14 @@ import assert from 'node:assert/strict' import { spawnSync } from 'node:child_process' +import { createHash, X509Certificate } from 'node:crypto' import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { createServer } from 'node:http' import { createServer as createHttpsServer, get as httpsGet } from 'node:https' import { tmpdir } from 'node:os' import { join } from 'node:path' import { test } from 'node:test' -import { fileURLToPath } from 'node:url' -import { BrowserAuthorizationError, BrowserAuthorizationEvidence, browserStages, logoutCheckpoints, readBrowserAuthorizationRecords } from './browser-authorization.mjs' +import { fileURLToPath, pathToFileURL } from 'node:url' +import { BrowserAuthorizationError, BrowserAuthorizationEvidence, browserStages, logoutCheckpoints, readBrowserAuthorizationRecords, withIssuerLogoutCallback } from './browser-authorization.mjs' import { browserEvidenceHeader, createBrowserHeaderRecorder, startBrowserEdge } from './browser-edge.mjs' import { assertReceipt } from './receipt.mjs' @@ -351,6 +352,98 @@ test('issuer metadata diagnostics snapshot only the signing-out frame at each ch }) }) +test('the logout gate waits only for already observed metadata from the signing-out frame', { timeout: 1_000 }, async () => { + const observed = new BrowserAuthorizationEvidence(10) + const frame = {} + const metadata = (requestFrame, stage = browserStages.returnFromIssuer) => { + const request = { frame: () => requestFrame, resourceType: () => 'fetch' } + observed.observe(request, 'issuer', stage, '/flow/meta', 'GET') + return request + } + metadata({}, browserStages.signOut) + metadata(frame, browserStages.firstSignIn) + await observed.waitForLogoutMetadata(frame, 0) + + const first = metadata(frame) + const second = metadata(frame, browserStages.signOut) + const waiting = observed.waitForLogoutMetadata(frame, 500) + metadata(frame) + observed.observeResponse(first, 'issuer-1') + const stillWaiting = Symbol('still waiting') + assert.equal(await Promise.race([waiting, new Promise(resolve => setImmediate(resolve, stillWaiting))]), stillWaiting) + observed.observeResponse(second, 'issuer-2') + await waiting +}) + +test('the logout gate refuses missing and invalid markers with a fixed diagnostic', { timeout: 1_000 }, async () => { + const frame = {} + const invalid = 'Browser issuer logout metadata has no valid edge response marker.' + for (const marker of [undefined, 'synthetic-private-marker', 'app-1']) { + const observed = new BrowserAuthorizationEvidence(2) + const request = { frame: () => frame, resourceType: () => 'xhr' } + observed.observe(request, 'issuer', browserStages.signOut, '/flow/meta', 'GET') + const waiting = observed.waitForLogoutMetadata(frame, 500) + observed.observeResponse(request, marker) + await assert.rejects(waiting, { message: invalid }) + await assert.rejects(observed.waitForLogoutMetadata(frame, 0), { message: invalid }) + } + + const observed = new BrowserAuthorizationEvidence(2) + const failed = { frame: () => frame, resourceType: () => 'fetch' } + observed.observe(failed, 'issuer', browserStages.signOut, '/flow/meta', 'GET') + const waiting = observed.waitForLogoutMetadata(frame, 500) + observed.observeRequestEnd(failed, false) + await assert.rejects(waiting, { message: invalid }) +}) + +test('the logout marker observer detaches when its deadline expires', { timeout: 1_000 }, async () => { + const frame = {} + const observed = new BrowserAuthorizationEvidence(1) + const request = { frame: () => frame, resourceType: () => 'fetch' } + observed.observe(request, 'issuer', browserStages.signOut, '/flow/meta', 'GET') + await assert.rejects(observed.waitForLogoutMetadata(frame, 0), { + message: 'Browser issuer logout metadata edge response marker timed out.', + }) + observed.observeResponse(request, 'issuer-1') + await observed.waitForLogoutMetadata(frame, 0) +}) + +test('the one-use logout route continues unchanged and is removed even when the proof fails', async () => { + const observed = new BrowserAuthorizationEvidence(1) + const frame = {} + const metadata = { frame: () => frame, resourceType: () => 'fetch' } + observed.observe(metadata, 'issuer', browserStages.signOut, '/flow/meta', 'GET') + observed.observeResponse(metadata, undefined) + + const callbackUrl = 'https://issuer.invalid/oauth2/logout/callback' + let handler + const calls = [] + const page = { + mainFrame: () => frame, + route: async (url, routeHandler) => { + assert.equal(url, callbackUrl) + handler = routeHandler + }, + unroute: async (url, routeHandler) => { + assert.equal(url, callbackUrl) + assert.equal(routeHandler, handler) + calls.push(['unroute']) + }, + } + const route = (method, requestFrame) => ({ + request: () => ({ method: () => method, frame: () => requestFrame }), + fallback: async (...args) => { calls.push(['fallback', ...args]) }, + continue: async (...args) => { calls.push(['continue', ...args]) }, + }) + await assert.rejects(withIssuerLogoutCallback(page, callbackUrl, observed, async () => { + await handler(route('GET', frame)) + await handler(route('POST', {})) + await handler(route('POST', frame)) + await handler(route('POST', frame)) + }), { message: 'Browser issuer logout metadata has no valid edge response marker.' }) + assert.deepEqual(calls, [['fallback'], ['fallback'], ['continue'], ['fallback'], ['unroute']]) +}) + test('an unavailable request frame leaves the missing-marker refusal and successful receipt intact', () => { const observed = new BrowserAuthorizationEvidence(2) const frame = {} @@ -760,6 +853,137 @@ test('issuer flow metadata exposes its edge marker while the upstream body is pe } }) +const playwrightModule = process.env.REFERENCE_PLAYWRIGHT_MODULE +test('Chromium continues the issuer logout callback after delayed metadata headers', { + skip: playwrightModule ? false : 'Set REFERENCE_PLAYWRIGHT_MODULE to run the Chromium ordering check.', + timeout: 30_000, +}, async () => { + const { chromium } = await import(pathToFileURL(playwrightModule)) + const scratch = mkdtempSync(join(tmpdir(), 'reference-logout-order-')) + try { + const { key, certificate } = prepareEdgeTls(scratch) + const path = join(scratch, 'browser-authorization.jsonl') + writeFileSync(path, '', { flag: 'wx', mode: 0o600 }) + const pending = new Map(['first', 'other'].map(name => [name, Promise.withResolvers()])) + const callbacks = [] + let signedOutUrl + let firstMarkerSeen = false + const upstream = createHttpsServer({ key: readFileSync(key), cert: certificate }, (request, response) => { + const { pathname, searchParams } = new URL(request.url, 'https://fixture.invalid') + if (pathname === '/flow/meta') { + const headers = pending.get(searchParams.get('page')) + if (headers) { + headers.resolve(response) + return + } + } + if (pathname === '/oauth2/logout/callback' && request.method === 'POST') { + let body = '' + request.setEncoding('utf8') + request.on('data', chunk => { body += chunk }) + request.on('end', () => { + callbacks.push({ body, firstMarkerSeen }) + response.end(signedOutUrl) + }) + return + } + response.setHeader('content-type', 'text/html') + response.end(`Logout fixture + + `) + }) + await new Promise(resolve => upstream.listen(0, '127.0.0.1', resolve)) + try { + const port = upstream.address().port + const edge = await startBrowserEdge(scratch, [port, port], [0, 0], assert.fail) + const observed = new BrowserAuthorizationEvidence(24) + try { + const [app, issuer] = edge.servers.map(server => `https://127.0.0.1:${server.address().port}`) + signedOutUrl = app + '/session/signed-out' + const callback = issuer + '/oauth2/logout/callback' + const firstMetadataUrl = issuer + '/flow/meta?page=first' + const pin = createHash('sha256').update(new X509Certificate(certificate).publicKey + .export({ type: 'spki', format: 'der' })).digest('base64') + const browser = await chromium.launch({ + executablePath: process.env.REFERENCE_TEST_CHROMIUM, + args: ['--no-proxy-server', '--ignore-certificate-errors-spki-list=' + pin], + }) + try { + const first = await browser.newPage() + const other = await browser.newPage() + for (const [page, name] of [[first, 'first'], [other, 'other']]) { + page.setDefaultTimeout(8_000) + const context = page.context() + context.on('request', request => { + const { origin, pathname } = new URL(request.url()) + observed.observe(request, origin === issuer ? 'issuer' : origin === app ? 'app' : undefined, + browserStages.returnFromIssuer, pathname, request.method()) + }) + context.on('response', response => { + const id = response.fromServiceWorker() ? undefined : response.headers()[browserEvidenceHeader] + observed.observeResponse(response.request(), id) + if (response.url() === firstMetadataUrl) firstMarkerSeen = /^issuer-[1-9][0-9]*$/u.test(id) + }) + context.on('requestfinished', request => observed.observeRequestEnd(request, true)) + context.on('requestfailed', request => observed.observeRequestEnd(request, false)) + await page.goto(issuer + '/logout-fixture') + const metadataPath = '/flow/meta?page=' + name + await Promise.all([ + page.waitForRequest(issuer + metadataPath), + page.evaluate(path => { window.metadata = fetch(path) }, metadataPath), + ]) + } + let timer + const deadline = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('Fixture metadata did not reach the upstream.')), 8_000) + }) + const [firstHeaders, otherHeaders] = await Promise.race([ + Promise.all([...pending.values()].map(item => item.promise)), deadline, + ]).finally(() => clearTimeout(timer)) + const callbackRequested = first.waitForRequest(request => request.url() === callback && request.method() === 'POST') + await Promise.all([ + withIssuerLogoutCallback(first, callback, observed, async () => { + await Promise.all([first.waitForURL(signedOutUrl), first.getByRole('button', { name: 'Sign out' }).click()]) + }), + (async () => { + await callbackRequested + const target = await other.evaluate(async () => { + const response = await fetch('/oauth2/logout/callback', { method: 'POST', body: 'other' }) + if (!response.ok) throw new Error('Fixture callback did not succeed.') + return response.text() + }) + assert.equal(target, signedOutUrl) + assert.deepEqual(callbacks, [{ body: 'other', firstMarkerSeen: false }]) + firstHeaders.end('{}') + })(), + ]) + assert.deepEqual(callbacks, [ + { body: 'other', firstMarkerSeen: false }, { body: 'first', firstMarkerSeen: true }, + ]) + otherHeaders.end('{}') + assert.equal(await other.evaluate(async () => (await window.metadata).text()), '{}') + } finally { + await browser.close() + } + } finally { + await edge.close() + } + observed.receipt(await readBrowserAuthorizationRecords(path, 24)) + } finally { + upstream.closeAllConnections() + await new Promise(resolve => upstream.close(resolve)) + } + } finally { + rmSync(scratch, { recursive: true }) + } +}) + test('each HTTPS ingress uses a byte bound without truncating the header list', async () => { const scratch = mkdtempSync(join(tmpdir(), 'reference-ingress-limits-')) try { From 2637adc2f6ffffdceae441c6e59e68929fcbc60d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 11:26:45 +0000 Subject: [PATCH 11/12] test: settle the logout fixture before checking order Signed-off-by: Jeremi Joslin --- .../business-registration/tests/receipt.test.mjs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/deploy/examples/business-registration/tests/receipt.test.mjs b/deploy/examples/business-registration/tests/receipt.test.mjs index 8ba43060b1..91da9c90bb 100644 --- a/deploy/examples/business-registration/tests/receipt.test.mjs +++ b/deploy/examples/business-registration/tests/receipt.test.mjs @@ -901,7 +901,8 @@ test('Chromium continues the issuer logout callback after delayed metadata heade await new Promise(resolve => upstream.listen(0, '127.0.0.1', resolve)) try { const port = upstream.address().port - const edge = await startBrowserEdge(scratch, [port, port], [0, 0], assert.fail) + let edgeFailed = false + const edge = await startBrowserEdge(scratch, [port, port], [0, 0], () => { edgeFailed = true }) const observed = new BrowserAuthorizationEvidence(24) try { const [app, issuer] = edge.servers.map(server => `https://127.0.0.1:${server.address().port}`) @@ -935,7 +936,7 @@ test('Chromium continues the issuer logout callback after delayed metadata heade await page.goto(issuer + '/logout-fixture') const metadataPath = '/flow/meta?page=' + name await Promise.all([ - page.waitForRequest(issuer + metadataPath), + page.waitForRequest(request => request.url() === issuer + metadataPath), page.evaluate(path => { window.metadata = fetch(path) }, metadataPath), ]) } @@ -947,6 +948,7 @@ test('Chromium continues the issuer logout callback after delayed metadata heade Promise.all([...pending.values()].map(item => item.promise)), deadline, ]).finally(() => clearTimeout(timer)) const callbackRequested = first.waitForRequest(request => request.url() === callback && request.method() === 'POST') + let callbacksBeforeHeaders await Promise.all([ withIssuerLogoutCallback(first, callback, observed, async () => { await Promise.all([first.waitForURL(signedOutUrl), first.getByRole('button', { name: 'Sign out' }).click()]) @@ -959,21 +961,23 @@ test('Chromium continues the issuer logout callback after delayed metadata heade return response.text() }) assert.equal(target, signedOutUrl) - assert.deepEqual(callbacks, [{ body: 'other', firstMarkerSeen: false }]) + callbacksBeforeHeaders = [...callbacks] firstHeaders.end('{}') })(), ]) + otherHeaders.end('{}') + assert.equal(await other.evaluate(async () => (await window.metadata).text()), '{}') + assert.deepEqual(callbacksBeforeHeaders, [{ body: 'other', firstMarkerSeen: false }]) assert.deepEqual(callbacks, [ { body: 'other', firstMarkerSeen: false }, { body: 'first', firstMarkerSeen: true }, ]) - otherHeaders.end('{}') - assert.equal(await other.evaluate(async () => (await window.metadata).text()), '{}') } finally { await browser.close() } } finally { await edge.close() } + assert.equal(edgeFailed || edge.failed, false, 'Fixture browser edge failed.') observed.receipt(await readBrowserAuthorizationRecords(path, 24)) } finally { upstream.closeAllConnections() From 6f4f6b48acbac9337994b74d43a08f4358be2799 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 4 Dec 2026 11:39:13 +0000 Subject: [PATCH 12/12] test: pin browser logout continuation and receipt shape Signed-off-by: Jeremi Joslin --- .../tests/browser-authorization.mjs | 44 ++++--- .../business-registration/tests/receipt.mjs | 13 +- .../tests/receipt.test.mjs | 120 +++++++++++------- 3 files changed, 102 insertions(+), 75 deletions(-) diff --git a/deploy/examples/business-registration/tests/browser-authorization.mjs b/deploy/examples/business-registration/tests/browser-authorization.mjs index 59ae1210be..8540728915 100644 --- a/deploy/examples/business-registration/tests/browser-authorization.mjs +++ b/deploy/examples/business-registration/tests/browser-authorization.mjs @@ -172,20 +172,33 @@ function validRequestFields({ headerNames, route, method, ...extra }) { && (headerNames.length === 0 || headerNames[0] === 'authorization') } -function checkedRecordedRequests(recordedRequests) { +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 } + }) +} - const recorded = new Map() +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 = [] for (const row of recordedRequests) { - const { id, upstreamHeaders, downstreamFinished, downstreamClosed, ...request } = row ?? {} + const { id, headerNames } = row ?? {} if (typeof id !== 'string' || !requestId.test(id) || recorded.has(id) - || !validRequestFields(request) || typeof upstreamHeaders !== 'boolean' - || typeof downstreamFinished !== 'boolean' || typeof downstreamClosed !== 'boolean' - || (downstreamFinished && !upstreamHeaders)) { + || Object.keys(row).length !== 2 || !Array.isArray(headerNames) + || headerNames.length > 1 || (headerNames.length === 1 && headerNames[0] !== 'authorization')) { throw new BrowserAuthorizationError('Browser edge record is invalid or duplicated.') } const scope = id.slice(0, id.indexOf('-')) @@ -193,17 +206,16 @@ function checkedRecordedRequests(recordedRequests) { if (id !== `${scope}-${counts[scope]}`) { throw new BrowserAuthorizationError('Browser edge record sequence is incomplete or out of order.') } - recorded.set(id, row) - if (request.headerNames.length === 1) present.push(`${id}: Authorization header present at the browser edge`) + recorded.add(id) + 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) { - let recorded try { - recorded = checkedRecordedRequests(recordedRequests) + checkedRecordedRequests(browserAuthorizationReceiptRows(recordedRequests)) } catch (error) { if (!(error instanceof BrowserAuthorizationError)) throw error return 'Unmatched recorded edge rows unavailable (edge records failed validation).' @@ -216,14 +228,12 @@ function unmatchedRecordedRows(recordedRequests, observations) { uniqueMatches.set(entry.id, marker === 'same-scope-marker' && !uniqueMatches.has(entry.id)) } } - for (const [id, matches] of uniqueMatches) { - if (matches) recorded.delete(id) - } + const unmatched = recordedRequests.filter(({ id }) => !uniqueMatches.get(id)) const counts = { app: 0, issuer: 0 } - for (const id of recorded.keys()) counts[id.slice(0, id.indexOf('-'))] += 1 + 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 recorded.values()) { + 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}` @@ -231,7 +241,7 @@ function unmatchedRecordedRows(recordedRequests, observations) { + ` downstream-closed=${yesNo(row.downstreamClosed)}` + (events?.length ? ` event-order=${events.join(',')}` : '')) } - const remaining = recorded.size - (lines.length - 1) + const remaining = unmatched.length - (lines.length - 1) if (remaining > 0) lines.push(`${remaining} more unmatched recorded edge rows.`) return lines.join('\n') } @@ -414,7 +424,7 @@ export class BrowserAuthorizationEvidence { missing.push(unmatchedRecordedRows(recordedRequests, this.#requests.values())) throw new BrowserAuthorizationError(missing.join('\n')) } - const evidence = { observedRequestIds, recordedRequests } + const evidence = { observedRequestIds, recordedRequests: browserAuthorizationReceiptRows(recordedRequests) } assertBrowserAuthorizationEvidence(evidence) return evidence } diff --git a/deploy/examples/business-registration/tests/receipt.mjs b/deploy/examples/business-registration/tests/receipt.mjs index 8a35d3c2b9..ef020deff4 100644 --- a/deploy/examples/business-registration/tests/receipt.mjs +++ b/deploy/examples/business-registration/tests/receipt.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict' import { realpathSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { pathToFileURL } from 'node:url' -import { assertBrowserAuthorizationEvidence, BrowserAuthorizationError, readBrowserAuthorizationRecords } from './browser-authorization.mjs' +import { assertBrowserAuthorizationEvidence, BrowserAuthorizationError, browserAuthorizationReceiptRows, readBrowserAuthorizationRecords } from './browser-authorization.mjs' import { maxBrowserEvidenceRows } from './browser-edge.mjs' const refusal = { status: 403, code: 'profile.not-authorized' } @@ -42,18 +42,11 @@ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.ar const receipt = JSON.parse(await readFile(path, 'utf8')) assertReceipt(profile, receipt) if (edgePath) { - const recordedRequests = await readBrowserAuthorizationRecords(edgePath, maxBrowserEvidenceRows) + const recordedRequests = browserAuthorizationReceiptRows(await readBrowserAuthorizationRecords(edgePath, maxBrowserEvidenceRows)) const evidence = receipt.browserAuthorization assertBrowserAuthorizationEvidence({ ...evidence, recordedRequests }) - // Lifecycle events may still arrive between browser finalization and edge shutdown. if (recordedRequests.length !== evidence.recordedRequests.length - || recordedRequests.some((row, index) => { - const prior = evidence.recordedRequests[index] - return row.id !== prior.id || row.route !== prior.route || row.method !== prior.method - || (prior.upstreamHeaders && !row.upstreamHeaders) - || (prior.downstreamFinished && !row.downstreamFinished) - || (prior.downstreamClosed && !row.downstreamClosed) - })) { + || recordedRequests.some((row, index) => row.id !== evidence.recordedRequests[index].id)) { throw new BrowserAuthorizationError('Browser edge records changed after browser finalization.') } } diff --git a/deploy/examples/business-registration/tests/receipt.test.mjs b/deploy/examples/business-registration/tests/receipt.test.mjs index 91da9c90bb..0d0edafd54 100644 --- a/deploy/examples/business-registration/tests/receipt.test.mjs +++ b/deploy/examples/business-registration/tests/receipt.test.mjs @@ -8,7 +8,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { test } from 'node:test' import { fileURLToPath, pathToFileURL } from 'node:url' -import { BrowserAuthorizationError, BrowserAuthorizationEvidence, browserStages, logoutCheckpoints, readBrowserAuthorizationRecords, withIssuerLogoutCallback } from './browser-authorization.mjs' +import { BrowserAuthorizationError, BrowserAuthorizationEvidence, browserAuthorizationReceiptRows, browserStages, logoutCheckpoints, readBrowserAuthorizationRecords, withIssuerLogoutCallback } from './browser-authorization.mjs' import { browserEvidenceHeader, createBrowserHeaderRecorder, startBrowserEdge } from './browser-edge.mjs' import { assertReceipt } from './receipt.mjs' @@ -16,12 +16,15 @@ const edgeRow = (id, fields = {}) => ({ id, headerNames: [], route: 'other', method: 'other', upstreamHeaders: false, downstreamFinished: false, downstreamClosed: false, ...fields, }) +const receiptRow = (id, fields = {}) => ({ id, headerNames: [], ...fields }) const recordedRequests = [edgeRow('app-1'), edgeRow('issuer-1')] const ledgerLine = (id, fields = {}) => JSON.stringify({ id, headerNames: [], route: 'other', method: 'other', ...fields, }) + '\n' const eventLine = (id, event, extra = {}) => JSON.stringify({ id, event, ...extra }) + '\n' -const browserAuthorization = { observedRequestIds: ['app-1', 'issuer-1'], recordedRequests } +const browserAuthorization = { + observedRequestIds: ['app-1', 'issuer-1'], recordedRequests: [receiptRow('app-1'), receiptRow('issuer-1')], +} const baseline = { distinctSubjects: true, @@ -101,12 +104,12 @@ test('a positive browser receipt requires complete edge evidence without Authori undefined, { ...browserAuthorization, observedRequestIds: ['app-1', 'issuer-3'] }, { ...browserAuthorization, observedRequestIds: ['app-1', 'issuer-1', 'app-1'] }, - { ...browserAuthorization, recordedRequests: [...recordedRequests, recordedRequests[0]] }, - { ...browserAuthorization, recordedRequests: [edgeRow('app-1', { headerNames: ['authorization'] }), recordedRequests[1]] }, - { ...browserAuthorization, recordedRequests: [...recordedRequests, edgeRow('app-2', { headerNames: ['authorization'] })] }, - { ...browserAuthorization, recordedRequests: [...recordedRequests, edgeRow('app-2', { private: 'redaction canary' })] }, - ...[{ events: [] }, { upstreamHeaders: 1 }, { downstreamFinished: true }].map(fields => ({ - ...browserAuthorization, recordedRequests: [edgeRow('app-1', fields), recordedRequests[1]], + { ...browserAuthorization, recordedRequests: [...browserAuthorization.recordedRequests, receiptRow('app-1')] }, + { ...browserAuthorization, recordedRequests: [receiptRow('app-1', { headerNames: ['authorization'] }), receiptRow('issuer-1')] }, + { ...browserAuthorization, recordedRequests: [...browserAuthorization.recordedRequests, receiptRow('app-2', { headerNames: ['authorization'] })] }, + ...[{ private: 'redaction canary' }, { route: 'sign-out' }, { method: 'POST' }, + { events: [] }, { upstreamHeaders: true }, { downstreamFinished: true }, { downstreamClosed: true }].map(fields => ({ + ...browserAuthorization, recordedRequests: [receiptRow('app-1', fields), receiptRow('issuer-1')], })), ]) assert.throws(() => withEvidence(evidence)) }) @@ -118,7 +121,7 @@ test('each edge ledger scope starts at one and has no sequence gaps', () => { ['app-1', 'issuer-1', 'app-3'], ['app-1', 'issuer-1', 'issuer-3', 'issuer-2'], ]) { - const evidence = { observedRequestIds: ids, recordedRequests: ids.map(id => edgeRow(id)) } + const evidence = { observedRequestIds: ids, recordedRequests: ids.map(id => receiptRow(id)) } assert.throws(() => assertReceipt('breg', { ...baseline, browserAuthorization: evidence }), { message: 'Browser edge record sequence is incomplete or out of order.', }) @@ -135,10 +138,14 @@ test('the stopped edge ledger must agree with the browser receipt at final valid const save = rows => writeFileSync(edgeLog, rows.map(({ id, headerNames }) => ledgerLine(id, { headerNames })).join('')) save(recordedRequests) assert.equal(spawnSync(process.execPath, command).status, 0) - writeFileSync(edgeLog, ledgerLine('app-1', { route: 'sign-out', method: 'POST' }) + ledgerLine('issuer-1')) - const changed = spawnSync(process.execPath, command, { encoding: 'utf8' }) - assert.equal(changed.status, 1) - assert.match(changed.stderr, /Browser edge records changed after browser finalization/) + save([receiptRow('issuer-1'), receiptRow('app-1')]) + const reordered = spawnSync(process.execPath, command, { encoding: 'utf8' }) + assert.equal(reordered.status, 1) + assert.match(reordered.stderr, /Browser edge records changed after browser finalization/) + save([receiptRow('app-1')]) + const missing = spawnSync(process.execPath, command, { encoding: 'utf8' }) + assert.equal(missing.status, 1) + assert.match(missing.stderr, /Browser request has a missing or duplicated edge record/) save([...recordedRequests, edgeRow('app-2', { headerNames: ['authorization'] })]) const forbidden = spawnSync(process.execPath, command, { encoding: 'utf8' }) assert.equal(forbidden.status, 1) @@ -152,7 +159,7 @@ test('the stopped edge ledger must agree with the browser receipt at final valid } }) -test('the stopped edge ledger preserves observed lifecycle events and accepts later events', () => { +test('the stopped edge ledger validates private lifecycle events for both receipt profiles', () => { const scratch = mkdtempSync(join(tmpdir(), 'reference-final-edge-lifecycle-')) try { const report = join(scratch, 'report.json') @@ -166,32 +173,26 @@ test('the stopped edge ledger preserves observed lifecycle events and accepts la const later = observed + eventLine('issuer-1', 'downstreamFinished') + eventLine('issuer-1', 'downstreamClosed') const closedBeforeHeaders = requestRows + appHeaders + appFinished + appClosed + eventLine('issuer-1', 'downstreamClosed') + issuerHeaders - const evidence = { - ...browserAuthorization, - recordedRequests: [ - edgeRow('app-1', { upstreamHeaders: true, downstreamFinished: true, downstreamClosed: true }), - edgeRow('issuer-1', { upstreamHeaders: true }), - ], - } - for (const [profile, receipt] of [['breg', baseline], ['casework', casework]]) { - writeFileSync(report, JSON.stringify({ ...receipt, browserAuthorization: evidence })) + writeFileSync(report, JSON.stringify(receipt)) const command = [fileURLToPath(new URL('./receipt.mjs', import.meta.url)), profile, report, edgeLog] for (const ledger of [observed, later, closedBeforeHeaders]) { writeFileSync(edgeLog, ledger) const result = spawnSync(process.execPath, command, { encoding: 'utf8' }) assert.equal(result.status, 0, result.stderr) } - for (const [missing, ledger] of [ - ['all events', requestRows], - ['issuer headers', requestRows + appHeaders + appFinished + appClosed], - ['app finish', requestRows + appHeaders + appClosed + issuerHeaders], - ['app close', requestRows + appHeaders + appFinished + issuerHeaders], + for (const [invalid, ledger] of [ + ['missing prerequisite headers', requestRows + appFinished], + ['duplicate close', observed + appClosed], + ['event for an omitted row', observed + eventLine('issuer-2', 'downstreamClosed')], + ['invalid route', ledgerLine('app-1', { route: 'synthetic-route-canary' }) + ledgerLine('issuer-1')], + ['invalid method', ledgerLine('app-1', { method: 'synthetic-method-canary' }) + ledgerLine('issuer-1')], ]) { writeFileSync(edgeLog, ledger) const result = spawnSync(process.execPath, command, { encoding: 'utf8' }) - assert.equal(result.status, 1, `${profile} ledger missing ${missing}`) - assert.match(result.stderr, /Browser edge records changed after browser finalization/u) + assert.equal(result.status, 1, `${profile} ledger with ${invalid}`) + assert.match(result.stderr, /Browser edge records missing, incomplete, or invalid/u) + assert.doesNotMatch(result.stderr, /canary/u) } } } finally { @@ -211,7 +212,7 @@ test('browser authorization records match each observed request across both orig assert.deepEqual(observed.receipt(recordedRequests), browserAuthorization) const withUnmatchedRow = [...recordedRequests, edgeRow('app-2')] assert.deepEqual(observed.receipt(withUnmatchedRow), { - ...browserAuthorization, recordedRequests: withUnmatchedRow, + ...browserAuthorization, recordedRequests: [...browserAuthorization.recordedRequests, receiptRow('app-2')], }) }) @@ -236,10 +237,7 @@ test('a successful browser receipt serializes exactly the existing authorization const rows = await readBrowserAuthorizationRecords(path, 2) assert.equal(JSON.stringify(observed.receipt(rows)), '{"observedRequestIds":["app-1","issuer-1"],"recordedRequests":[' - + '{"id":"app-1","headerNames":[],"route":"signed-out","method":"GET",' - + '"upstreamHeaders":true,"downstreamFinished":true,"downstreamClosed":false},' - + '{"id":"issuer-1","headerNames":[],"route":"flow-meta","method":"GET",' - + '"upstreamHeaders":true,"downstreamFinished":false,"downstreamClosed":true}]}') + + '{"id":"app-1","headerNames":[]},{"id":"issuer-1","headerNames":[]}]}') } finally { rmSync(scratch, { recursive: true }) } @@ -693,14 +691,16 @@ test('a live ingress request carrying Authorization prevents a checked receipt', observedRequestIds.push(response.headers.get(browserEvidenceHeader)) await response.text() } - const readEvidence = async () => ({ observedRequestIds, recordedRequests: await readBrowserAuthorizationRecords(path, 10) }) + const readEvidence = async () => ({ + observedRequestIds, recordedRequests: browserAuthorizationReceiptRows(await readBrowserAuthorizationRecords(path, 10)), + }) assertReceipt('breg', { ...baseline, browserAuthorization: await readEvidence() }) const forbidden = await fetch(origin + '/app', { headers: { Authorization: '' } }) const forbiddenId = forbidden.headers.get(browserEvidenceHeader) await forbidden.text() const evidence = await readEvidence() - assert.deepEqual(evidence.recordedRequests.at(-1), edgeRow(forbiddenId, { headerNames: ['authorization'], method: 'GET' })) + assert.deepEqual(evidence.recordedRequests.at(-1), receiptRow(forbiddenId, { headerNames: ['authorization'] })) assert.throws(() => assertReceipt('breg', { ...baseline, browserAuthorization: evidence }), { message: `${forbiddenId}: Authorization header present at the browser edge`, }) @@ -867,7 +867,6 @@ test('Chromium continues the issuer logout callback after delayed metadata heade const pending = new Map(['first', 'other'].map(name => [name, Promise.withResolvers()])) const callbacks = [] let signedOutUrl - let firstMarkerSeen = false const upstream = createHttpsServer({ key: readFileSync(key), cert: certificate }, (request, response) => { const { pathname, searchParams } = new URL(request.url, 'https://fixture.invalid') if (pathname === '/flow/meta') { @@ -882,7 +881,7 @@ test('Chromium continues the issuer logout callback after delayed metadata heade request.setEncoding('utf8') request.on('data', chunk => { body += chunk }) request.on('end', () => { - callbacks.push({ body, firstMarkerSeen }) + callbacks.push(body) response.end(signedOutUrl) }) return @@ -909,6 +908,7 @@ test('Chromium continues the issuer logout callback after delayed metadata heade signedOutUrl = app + '/session/signed-out' const callback = issuer + '/oauth2/logout/callback' const firstMetadataUrl = issuer + '/flow/meta?page=first' + const otherMetadataUrl = issuer + '/flow/meta?page=other' const pin = createHash('sha256').update(new X509Certificate(certificate).publicKey .export({ type: 'spki', format: 'der' })).digest('base64') const browser = await chromium.launch({ @@ -918,6 +918,8 @@ test('Chromium continues the issuer logout callback after delayed metadata heade try { const first = await browser.newPage() const other = await browser.newPage() + let firstMarkerSeen = false + let otherMarkerSeen = false for (const [page, name] of [[first, 'first'], [other, 'other']]) { page.setDefaultTimeout(8_000) const context = page.context() @@ -930,6 +932,7 @@ test('Chromium continues the issuer logout callback after delayed metadata heade const id = response.fromServiceWorker() ? undefined : response.headers()[browserEvidenceHeader] observed.observeResponse(response.request(), id) if (response.url() === firstMetadataUrl) firstMarkerSeen = /^issuer-[1-9][0-9]*$/u.test(id) + if (response.url() === otherMetadataUrl) otherMarkerSeen = /^issuer-[1-9][0-9]*$/u.test(id) }) context.on('requestfinished', request => observed.observeRequestEnd(request, true)) context.on('requestfailed', request => observed.observeRequestEnd(request, false)) @@ -947,30 +950,51 @@ test('Chromium continues the issuer logout callback after delayed metadata heade const [firstHeaders, otherHeaders] = await Promise.race([ Promise.all([...pending.values()].map(item => item.promise)), deadline, ]).finally(() => clearTimeout(timer)) - const callbackRequested = first.waitForRequest(request => request.url() === callback && request.method() === 'POST') - let callbacksBeforeHeaders + const intercepted = Promise.withResolvers() + const continuations = [] + let wrappedHandler + const firstPage = { + mainFrame: () => first.mainFrame(), + route(url, handler) { + wrappedHandler = route => { + intercepted.resolve({ firstMarkerSeen, otherMarkerSeen }) + return handler({ + request: () => route.request(), + fallback: (...args) => route.fallback(...args), + continue: (...args) => { + // Measure forwarding here, before the upstream can report its arrival. + continuations.push({ firstMarkerSeen, otherMarkerSeen, args }) + return route.continue(...args) + }, + }) + } + return first.route(url, wrappedHandler) + }, + unroute: url => first.unroute(url, wrappedHandler), + } await Promise.all([ - withIssuerLogoutCallback(first, callback, observed, async () => { + withIssuerLogoutCallback(firstPage, callback, observed, async () => { await Promise.all([first.waitForURL(signedOutUrl), first.getByRole('button', { name: 'Sign out' }).click()]) }), (async () => { - await callbackRequested + assert.deepEqual(await intercepted.promise, { firstMarkerSeen: false, otherMarkerSeen: false }) const target = await other.evaluate(async () => { const response = await fetch('/oauth2/logout/callback', { method: 'POST', body: 'other' }) if (!response.ok) throw new Error('Fixture callback did not succeed.') return response.text() }) assert.equal(target, signedOutUrl) - callbacksBeforeHeaders = [...callbacks] firstHeaders.end('{}') })(), ]) + // Keep the other context's metadata pending until the first has completed logout. + assert.equal(otherHeaders.headersSent, false) otherHeaders.end('{}') assert.equal(await other.evaluate(async () => (await window.metadata).text()), '{}') - assert.deepEqual(callbacksBeforeHeaders, [{ body: 'other', firstMarkerSeen: false }]) - assert.deepEqual(callbacks, [ - { body: 'other', firstMarkerSeen: false }, { body: 'first', firstMarkerSeen: true }, - ]) + assert.equal(otherMarkerSeen, true) + assert.deepEqual(continuations, [{ firstMarkerSeen: true, otherMarkerSeen: false, args: [] }], + 'First-frame callback must continue unchanged after its own metadata marker while the other context is pending.') + assert.deepEqual(callbacks.sort(), ['first', 'other']) } finally { await browser.close() }