fix(auth): move the BankID flow into a signed, user-gated, single-use cookie (#1625)
* fix(auth): move the BankID flow into a signed, single-use, confirm-on-resume cookie
A user's BankID signup identified successfully four times and created no
account. His screenshots show four tabs, one on the finished "Verifierad med
BankID, ange e-post" step, and the tab he was looking at showing the idle
button. Prod agreed: no bankid_identities row, no auth.users row.
On iOS outside plain Safari the BankID return URL is handed to the OS, which
opens a NEW tab. The session lived in per-tab sessionStorage, so that tab
started empty and rendered the start button while the completed flow sat
stranded. Login hid it (self-finishing, cookie-backed session); signup waits
for a human to type an e-mail into the stranded tab, so it dies there.
The session id is no longer handed to the browser. It lives in a signed
__Host- HttpOnly cookie set at /start; /poll, /complete, /link and /cancel
read it. Cookies are shared by every tab of the origin, which is what the
handoff needed. The id had to leave the client because it is an
unauthenticated bearer credential: /poll was skipAuth and returned
user.personalNumber, and /complete with mode 'login' returns a tokenHash that
verifyOtp turns into a session, MFA skipped for bankid_linked accounts.
A completed identification must never be consumed by whoever merely opens the
page. A shared cookie plus a shared machine means the tab that finds a
completed flow cannot prove the person at it is the one who made it, and no
client-side token can prove otherwise: nothing survives an iOS same-tab reload
yet dies on reopen-closed-tab / session restore / tab duplication. So a resume
is never automatic. The mount probe routes any found live flow to a confirm
card ("Fortsätt bara om det var du") that reveals no name, and only that click
polls and consumes. Auto-consume happens only inside the live component
instance that called startSession (desktop QR; the pre-navigation mobile
launch), which by construction is the originator. Cost: one tap after
returning from the BankID app on iOS, exactly where the reported bug lives;
desktop and Android never hit the resume path.
The rest is defence the four review rounds proved load-bearing:
- __Host- with Path=/ and unconditional Secure, so a script cannot plant the
same name at a longer path; readBankIdFlow fails closed on duplicates and on
a malformed percent-escape.
- Single-use is a unique index (bankid_consumed_sessions), claimed before
generateLink, not a Set-Cookie. Fail-closed on any non-23505 error, so the
migration MUST be applied before the code.
- A link flow requires auth at /start and pins userId; /link rejects a flow
owned by anyone else, before any TIC call. mode is pinned and /poll rejects a
body mode that does not match, so a login session cannot finish through the
signup panel. /poll withholds the holder name from a probe. The 900s
verified-step window is capped by MAX_TOTAL_LIFE from a signed startedAt.
/poll never clears the cookie (an untargeted Set-Cookie would delete a newer
flow); only /cancel and terminal /complete + /link exits clear. Avbryt holds
a 'cancelling' state until /cancel resolves so a new /start cannot race the
clear. Session id is logged only as an 8-char prefix.
The launch is untouched: iOS keeps its return URL, Android keeps redirect=null
(#194 closed that path deliberately).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(auth): bind BankID actions to the resumed flow
* docs: record BankID staging migration drift
* fix(auth): address BankID PR review
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
2deea05d42
commit
edfdbe2d2a
@@ -15,11 +15,52 @@ vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
import { collectBankIdResult, requestEnrichment, fetchEnrichmentData } from '../lib/bankid-client'
|
||||
import {
|
||||
cancelBankIdSession,
|
||||
collectBankIdResult,
|
||||
pollBankIdSession,
|
||||
requestEnrichment,
|
||||
fetchEnrichmentData,
|
||||
startBankIdAuth,
|
||||
} from '../lib/bankid-client'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { ticExtension } from '../index'
|
||||
import {
|
||||
BANKID_FLOW_COOKIE,
|
||||
BANKID_FLOW_ID_HEADER,
|
||||
signBankIdFlow,
|
||||
verifyBankIdFlow,
|
||||
type BankIdFlowMode,
|
||||
} from '../lib/bankid-flow-cookie'
|
||||
|
||||
const TEST_KEY = 'a'.repeat(64)
|
||||
const TEST_FLOW_ID = 'flow-1'
|
||||
|
||||
/**
|
||||
* The session id and the mode now arrive in a signed HttpOnly cookie rather
|
||||
* than the request body, so nothing a caller can name decides which session
|
||||
* gets completed, or as which kind of flow.
|
||||
*/
|
||||
async function flowCookie(
|
||||
mode: BankIdFlowMode,
|
||||
sessionId = 'test-session',
|
||||
userId = 'user-1',
|
||||
): Promise<Record<string, string>> {
|
||||
const value = await signBankIdFlow({
|
||||
version: 1,
|
||||
sessionId,
|
||||
flowId: TEST_FLOW_ID,
|
||||
mode,
|
||||
// A link flow is owned by the user who opened it; login/signup have none.
|
||||
userId: mode === 'link' ? userId : undefined,
|
||||
startedAt: Date.now(),
|
||||
expiresAt: Date.now() + 60_000,
|
||||
})
|
||||
return {
|
||||
cookie: `${BANKID_FLOW_COOKIE}=${encodeURIComponent(value)}`,
|
||||
[BANKID_FLOW_ID_HEADER]: TEST_FLOW_ID,
|
||||
}
|
||||
}
|
||||
|
||||
function findCompleteHandler() {
|
||||
const route = ticExtension.apiRoutes!.find(
|
||||
@@ -45,7 +86,14 @@ function makeSession(overrides: Partial<{ status: string; user: unknown }> = {})
|
||||
|
||||
type QueuedResult = { data?: unknown; error?: unknown }
|
||||
|
||||
function mockServiceClient(fromResults: QueuedResult[]) {
|
||||
function mockServiceClient(
|
||||
fromResults: QueuedResult[],
|
||||
// The single-use claim against bankid_consumed_sessions. Routed by table name
|
||||
// rather than taken from the queue, so each test's queue keeps describing
|
||||
// only the lookups it cares about. `{ error: { code: '23505' } }` is the
|
||||
// other tab having claimed the session first.
|
||||
consumed: QueuedResult = { error: null },
|
||||
) {
|
||||
const queue = [...fromResults]
|
||||
|
||||
const chain = (): unknown => {
|
||||
@@ -82,7 +130,9 @@ function mockServiceClient(fromResults: QueuedResult[]) {
|
||||
}
|
||||
|
||||
const client = {
|
||||
from: vi.fn().mockImplementation(() => chain()),
|
||||
from: vi.fn().mockImplementation((table: string) =>
|
||||
table === 'bankid_consumed_sessions' ? chain2(consumed) : chain()
|
||||
),
|
||||
auth: { admin },
|
||||
}
|
||||
|
||||
@@ -117,7 +167,8 @@ describe('POST /bankid/complete', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session', mode: 'signup', email: 'victim@example.com' },
|
||||
headers: await flowCookie('signup'),
|
||||
body: { email: 'victim@example.com' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string; data?: unknown }>(
|
||||
await findCompleteHandler()(req)
|
||||
@@ -149,7 +200,8 @@ describe('POST /bankid/complete', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session', mode: 'signup', email: 'fresh@example.com' },
|
||||
headers: await flowCookie('signup'),
|
||||
body: { email: 'fresh@example.com' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findCompleteHandler()(req)
|
||||
@@ -171,7 +223,8 @@ describe('POST /bankid/complete', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session', mode: 'signup', email: 'fresh@example.com' },
|
||||
headers: await flowCookie('signup'),
|
||||
body: { email: 'fresh@example.com' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { tokenHash?: string; type?: string; isNewUser?: boolean }
|
||||
@@ -203,7 +256,8 @@ describe('POST /bankid/complete', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session', mode: 'signup', email: 'x@example.com' },
|
||||
headers: await flowCookie('signup'),
|
||||
body: { email: 'x@example.com' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findCompleteHandler()(req)
|
||||
@@ -217,7 +271,7 @@ describe('POST /bankid/complete', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('signup mode — rollback on partial failure', () => {
|
||||
describe('signup mode: rollback on partial failure', () => {
|
||||
// A half-created account strands the user: retrying signup hits
|
||||
// account_exists/already_linked, but the account only has a random
|
||||
// password they never saw. Every failure after createUser must delete
|
||||
@@ -232,7 +286,8 @@ describe('POST /bankid/complete', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session', mode: 'signup', email: 'fresh@example.com' },
|
||||
headers: await flowCookie('signup'),
|
||||
body: { email: 'fresh@example.com' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findCompleteHandler()(req)
|
||||
@@ -258,7 +313,8 @@ describe('POST /bankid/complete', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session', mode: 'signup', email: 'fresh@example.com' },
|
||||
headers: await flowCookie('signup'),
|
||||
body: { email: 'fresh@example.com' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findCompleteHandler()(req)
|
||||
@@ -281,7 +337,8 @@ describe('POST /bankid/complete', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session', mode: 'signup', email: 'fresh@example.com' },
|
||||
headers: await flowCookie('signup'),
|
||||
body: { email: 'fresh@example.com' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findCompleteHandler()(req)
|
||||
@@ -302,7 +359,8 @@ describe('POST /bankid/complete', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session', mode: 'signup', email: 'fresh@example.com' },
|
||||
headers: await flowCookie('signup'),
|
||||
body: { email: 'fresh@example.com' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await findCompleteHandler()(req))
|
||||
|
||||
@@ -320,7 +378,7 @@ describe('POST /bankid/complete', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session', mode: 'login' },
|
||||
headers: await flowCookie('login'),
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findCompleteHandler()(req)
|
||||
@@ -395,7 +453,8 @@ describe('POST /bankid/complete', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session', mode: 'signup', email: 'fresh@example.com' },
|
||||
headers: await flowCookie('signup'),
|
||||
body: { email: 'fresh@example.com' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { tokenHash?: string; isNewUser?: boolean }
|
||||
@@ -434,7 +493,8 @@ describe('POST /bankid/complete', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session', mode: 'signup', email: 'x@example.com' },
|
||||
headers: await flowCookie('signup'),
|
||||
body: { email: 'x@example.com' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findCompleteHandler()(req)
|
||||
@@ -449,7 +509,7 @@ describe('POST /bankid/complete', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session', mode: 'signup' },
|
||||
headers: await flowCookie('signup'),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await findCompleteHandler()(req))
|
||||
|
||||
@@ -458,4 +518,516 @@ describe('POST /bankid/complete', () => {
|
||||
expect(collectBankIdResult).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the flow cookie is the only thing that names a session', () => {
|
||||
/** Did the handler expire the flow cookie on this response? */
|
||||
function clearedFlow(response: Response): boolean {
|
||||
return response.headers
|
||||
.getSetCookie()
|
||||
.some((c) => c.startsWith(`${BANKID_FLOW_COOKIE}=`) && /Max-Age=0/i.test(c))
|
||||
}
|
||||
|
||||
it('refuses completion from a stale tab after the shared cookie was replaced', async () => {
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
mockServiceClient([])
|
||||
const headers = await flowCookie('signup')
|
||||
headers[BANKID_FLOW_ID_HEADER] = 'older-flow'
|
||||
|
||||
const { status } = await parseJsonResponse(
|
||||
await findCompleteHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: { email: 'fresh@example.com' },
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(collectBankIdResult).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ignores a sessionId and mode supplied in the body', async () => {
|
||||
// The old contract took both from the body, which made /complete a
|
||||
// bearer endpoint: anyone who had seen a session id could complete it,
|
||||
// in whatever mode suited them.
|
||||
mockServiceClient([])
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'attacker-session', mode: 'login' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findCompleteHandler()(req)
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('session_invalid')
|
||||
expect(collectBankIdResult).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses to complete a session that was opened as a link flow', async () => {
|
||||
// Linking happens on the authenticated /bankid/link route. Completing a
|
||||
// link session here would create or sign in an account off a session
|
||||
// opened for something else entirely.
|
||||
mockServiceClient([])
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('link'),
|
||||
body: { email: 'attacker@example.com' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findCompleteHandler()(req)
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('session_invalid')
|
||||
expect(collectBankIdResult).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('spends the flow on success, so a second tab cannot mint a rival magic link', async () => {
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
const { admin } = mockServiceClient([
|
||||
{ data: null }, // pnr lookup → not linked
|
||||
{ error: null }, // bankid_identities insert OK
|
||||
])
|
||||
|
||||
const response = await findCompleteHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('signup'),
|
||||
body: { email: 'fresh@example.com' },
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(admin.generateLink).toHaveBeenCalled()
|
||||
// Without this, two tabs that both saw 'complete' would each mint a
|
||||
// magic link and the second would invalidate the first.
|
||||
expect(clearedFlow(response)).toBe(true)
|
||||
})
|
||||
|
||||
it('refuses a login whose session another tab already spent', async () => {
|
||||
// The Set-Cookie clear does NOT make this single-use: two requests that
|
||||
// both already carried the cookie both reach here. The unique index on
|
||||
// bankid_consumed_sessions is what stops the second from minting a rival
|
||||
// magic link that would invalidate the first tab's.
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
const { admin } = mockServiceClient(
|
||||
[{ data: { user_id: 'existing-user' } }], // pnr is linked
|
||||
{ error: { code: '23505', message: 'duplicate key' } },
|
||||
)
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findCompleteHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('login'),
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('session_invalid')
|
||||
expect(admin.generateLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rolls the new account back when a signup loses the same race', async () => {
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
const { admin } = mockServiceClient(
|
||||
[{ data: null }, { error: null }],
|
||||
{ error: { code: '23505', message: 'duplicate key' } },
|
||||
)
|
||||
|
||||
const { status } = await parseJsonResponse(
|
||||
await findCompleteHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('signup'),
|
||||
body: { email: 'fresh@example.com' },
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(admin.generateLink).not.toHaveBeenCalled()
|
||||
// A half-created account would strand the address: the retry would hit
|
||||
// account_exists on an account whose password the user never saw.
|
||||
expect(admin.deleteUser).toHaveBeenCalledWith('new-user-uuid')
|
||||
})
|
||||
|
||||
it('fails closed when the single-use claim errors for any other reason', async () => {
|
||||
// Minting a second magic link is worse than asking the user to
|
||||
// authenticate again, so an unreachable table must not be waved through.
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
const { admin } = mockServiceClient(
|
||||
[{ data: { user_id: 'existing-user' } }],
|
||||
{ error: { code: '42P01', message: 'relation does not exist' } },
|
||||
)
|
||||
|
||||
const { status } = await parseJsonResponse(
|
||||
await findCompleteHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('login'),
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(admin.generateLink).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the flow alive when the e-mail is already taken, so it can be corrected', async () => {
|
||||
// account_exists consumes nothing and is usually a typo: forcing a
|
||||
// second BankID round trip to fix an address would be gratuitous.
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
const { admin } = mockServiceClient([{ data: null }])
|
||||
admin.createUser.mockResolvedValueOnce({
|
||||
data: { user: null },
|
||||
error: { status: 422, code: 'email_exists', message: 'already registered' },
|
||||
} as never)
|
||||
|
||||
const response = await findCompleteHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/complete', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('signup'),
|
||||
body: { email: 'taken@example.com' },
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(409)
|
||||
expect(clearedFlow(response)).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /bankid/start', () => {
|
||||
function findStartHandler() {
|
||||
const route = ticExtension.apiRoutes!.find(
|
||||
(r) => r.method === 'POST' && r.path === '/bankid/start'
|
||||
)
|
||||
if (!route) throw new Error('POST /bankid/start route not found')
|
||||
return route.handler
|
||||
}
|
||||
|
||||
it('rejects a request that does not name a flow', async () => {
|
||||
const { status } = await parseJsonResponse(
|
||||
await findStartHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/start', {
|
||||
method: 'POST',
|
||||
body: { mode: 'admin' },
|
||||
})
|
||||
)
|
||||
)
|
||||
expect(status).toBe(400)
|
||||
expect(startBankIdAuth).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('withholds the session id from the response and puts it in the cookie', async () => {
|
||||
vi.mocked(startBankIdAuth).mockResolvedValue({
|
||||
sessionId: 'secret-session',
|
||||
autoStartToken: 'ast',
|
||||
qrStartToken: 'qrt',
|
||||
qrStartSecret: 'qrs',
|
||||
} as never)
|
||||
|
||||
const response = await findStartHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/start', {
|
||||
method: 'POST',
|
||||
body: { mode: 'signup' },
|
||||
})
|
||||
)
|
||||
const payload = await response.clone().text()
|
||||
const parsed = JSON.parse(payload) as { data: { flowId: string } }
|
||||
|
||||
// The id is a bearer credential for a personnummer and for a session.
|
||||
// The browser gets the autostart/QR tokens, which identify nobody.
|
||||
expect(payload).not.toContain('secret-session')
|
||||
expect(payload).toContain('ast')
|
||||
expect(parsed.data.flowId).toBeTruthy()
|
||||
|
||||
const flowCookieHeader = response.headers
|
||||
.getSetCookie()
|
||||
.find((c) => c.startsWith(`${BANKID_FLOW_COOKIE}=`))
|
||||
expect(flowCookieHeader).toMatch(/HttpOnly/i)
|
||||
|
||||
const [, value] = /^[^=]+=([^;]*)/.exec(flowCookieHeader!)!
|
||||
const flow = await verifyBankIdFlow(decodeURIComponent(value))
|
||||
expect(flow).toMatchObject({
|
||||
sessionId: 'secret-session',
|
||||
mode: 'signup',
|
||||
})
|
||||
expect(flow?.flowId).toBe(parsed.data.flowId)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /bankid/poll', () => {
|
||||
function findPollHandler() {
|
||||
const route = ticExtension.apiRoutes!.find(
|
||||
(r) => r.method === 'POST' && r.path === '/bankid/poll'
|
||||
)
|
||||
if (!route) throw new Error('POST /bankid/poll route not found')
|
||||
return route.handler
|
||||
}
|
||||
|
||||
it('answers 404 when the browser holds no flow, instead of polling a named session', async () => {
|
||||
const { status } = await parseJsonResponse(
|
||||
await findPollHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/poll', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'attacker-session' },
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(pollBankIdSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('never returns the personnummer', async () => {
|
||||
// This route is skipAuth, so whatever it returns is readable by whoever
|
||||
// holds the flow cookie. The UI only ever needed the names.
|
||||
vi.mocked(pollBankIdSession).mockResolvedValue({
|
||||
status: 'complete',
|
||||
user: {
|
||||
personalNumber: '199001011234',
|
||||
givenName: 'Anna',
|
||||
surname: 'Andersson',
|
||||
name: 'Anna Andersson',
|
||||
},
|
||||
} as never)
|
||||
|
||||
const response = await findPollHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/poll', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('signup'),
|
||||
body: { mode: 'signup' },
|
||||
})
|
||||
)
|
||||
const payload = await response.clone().text()
|
||||
const { body } = await parseJsonResponse<{ data: { user?: Record<string, unknown> } }>(response)
|
||||
|
||||
expect(payload).not.toContain('199001011234')
|
||||
expect(body.data.user).toEqual({ givenName: 'Anna', surname: 'Andersson' })
|
||||
})
|
||||
|
||||
it('withholds the holder name from a probe, but gives it to the active poll', async () => {
|
||||
// The mount probe runs before the person here has confirmed the flow is
|
||||
// theirs, so the name must not reach them (it would identify a stranger on
|
||||
// a shared machine). The active poll, reached only after ownership/confirm,
|
||||
// needs the name for the signup e-mail step.
|
||||
vi.mocked(pollBankIdSession).mockResolvedValue({
|
||||
status: 'complete',
|
||||
user: { givenName: 'Anna', surname: 'Andersson', personalNumber: 'x' },
|
||||
} as never)
|
||||
|
||||
const probe = await parseJsonResponse<{ data: { flowId?: string; user?: unknown } }>(
|
||||
await findPollHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/poll', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('signup'),
|
||||
body: { mode: 'signup', probe: true },
|
||||
})
|
||||
)
|
||||
)
|
||||
expect(probe.body.data.flowId).toBe(TEST_FLOW_ID)
|
||||
expect(probe.body.data.user).toBeUndefined()
|
||||
|
||||
const active = await parseJsonResponse<{ data: { user?: unknown } }>(
|
||||
await findPollHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/poll', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('signup'),
|
||||
body: { mode: 'signup' },
|
||||
})
|
||||
)
|
||||
)
|
||||
expect(active.body.data.user).toEqual({ givenName: 'Anna', surname: 'Andersson' })
|
||||
})
|
||||
|
||||
it('refuses to poll a flow whose mode does not match the panel asking', async () => {
|
||||
// A login session started on /login must not be pollable by the signup
|
||||
// panel: the client would render the signup e-mail step and /complete
|
||||
// would then read mode 'login' off the cookie, either signing the user in
|
||||
// from the "Skapa konto" form or burning the identification on no_account.
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findPollHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/poll', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('login'),
|
||||
body: { mode: 'signup' },
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error).toBe('no_session')
|
||||
expect(pollBankIdSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('polls when both the panel mode and tab flow id match', async () => {
|
||||
vi.mocked(pollBankIdSession).mockResolvedValue({ status: 'pending' } as never)
|
||||
|
||||
const { status } = await parseJsonResponse(
|
||||
await findPollHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/poll', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('signup'),
|
||||
body: { mode: 'signup' },
|
||||
})
|
||||
)
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(pollBankIdSession).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('refuses a stale tab after a newer same-mode flow replaced the shared cookie', async () => {
|
||||
vi.mocked(pollBankIdSession).mockResolvedValue({ status: 'complete' } as never)
|
||||
const headers = await flowCookie('signup')
|
||||
headers[BANKID_FLOW_ID_HEADER] = 'older-flow'
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findPollHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/poll', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: { mode: 'signup' },
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error).toBe('no_session')
|
||||
expect(pollBankIdSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does NOT clear the cookie when TIC has forgotten the session', async () => {
|
||||
// A clearing Set-Cookie cannot be aimed at one flow, so a slow response
|
||||
// about a dead session would delete whatever flow is in the jar by the
|
||||
// time it lands, including one the user just started in another tab.
|
||||
const { TICAPIError } = await import('../lib/tic-types')
|
||||
vi.mocked(pollBankIdSession).mockRejectedValueOnce(
|
||||
new TICAPIError('gone', 404)
|
||||
)
|
||||
|
||||
const response = await findPollHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/poll', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('login'),
|
||||
body: { mode: 'login' },
|
||||
})
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error).toBe('no_session')
|
||||
const cleared = response.headers
|
||||
.getSetCookie()
|
||||
.some((c) => c.startsWith(`${BANKID_FLOW_COOKIE}=`) && /Max-Age=0/i.test(c))
|
||||
expect(cleared).toBe(false)
|
||||
})
|
||||
|
||||
it('extends the window to the verified budget once identification completes', async () => {
|
||||
// The signup e-mail step is a person typing; the order window (300s) is
|
||||
// too short for it, so completion re-issues at the longer budget.
|
||||
vi.mocked(pollBankIdSession).mockResolvedValue({
|
||||
status: 'complete',
|
||||
user: { givenName: 'Anna', surname: 'Andersson', personalNumber: 'x' },
|
||||
} as never)
|
||||
|
||||
const response = await findPollHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/poll', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('signup'),
|
||||
body: { mode: 'signup' },
|
||||
})
|
||||
)
|
||||
|
||||
// A fresh signed cookie is issued (Max-Age well past the 300s order window).
|
||||
const reissued = response.headers
|
||||
.getSetCookie()
|
||||
.find((c) => c.startsWith(`${BANKID_FLOW_COOKIE}=`))
|
||||
expect(reissued).toBeDefined()
|
||||
const maxAge = Number(/Max-Age=(\d+)/i.exec(reissued!)?.[1])
|
||||
expect(maxAge).toBeGreaterThan(300)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /bankid/cancel', () => {
|
||||
function findCancelHandler() {
|
||||
const route = ticExtension.apiRoutes!.find(
|
||||
(r) => r.method === 'POST' && r.path === '/bankid/cancel'
|
||||
)
|
||||
if (!route) throw new Error('POST /bankid/cancel route not found')
|
||||
return route.handler
|
||||
}
|
||||
|
||||
function clearsFlow(response: Response): boolean {
|
||||
return response.headers
|
||||
.getSetCookie()
|
||||
.some((c) => c.startsWith(`${BANKID_FLOW_COOKIE}=`) && /Max-Age=0/i.test(c))
|
||||
}
|
||||
|
||||
it('cancels the flow this browser holds, with no id to aim it', async () => {
|
||||
const response = await findCancelHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/cancel', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('signup'),
|
||||
// A named session in the body must be ignored: the old DELETE route
|
||||
// took one, which let a caller cancel a session they merely knew of.
|
||||
body: { sessionId: 'someone-elses-session' },
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(clearsFlow(response)).toBe(true)
|
||||
expect(cancelBankIdSession).toHaveBeenCalledWith('test-session')
|
||||
})
|
||||
|
||||
it('still clears the cookie when TIC cannot be reached', async () => {
|
||||
// Otherwise pressing Avbryt during a TIC outage leaves a flow in the
|
||||
// browser that the next page load resumes.
|
||||
vi.mocked(cancelBankIdSession).mockRejectedValueOnce(new Error('network down'))
|
||||
|
||||
const response = await findCancelHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/cancel', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('signup'),
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(clearsFlow(response)).toBe(true)
|
||||
})
|
||||
|
||||
it('does not cancel or clear a newer flow from a stale tab', async () => {
|
||||
const headers = await flowCookie('signup')
|
||||
headers[BANKID_FLOW_ID_HEADER] = 'older-flow'
|
||||
|
||||
const response = await findCancelHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/cancel', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
})
|
||||
)
|
||||
const { body } = await parseJsonResponse<{
|
||||
data?: { cancelled?: boolean; replaced?: boolean }
|
||||
}>(response.clone())
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.data).toEqual({ cancelled: false, replaced: true })
|
||||
expect(clearsFlow(response)).toBe(false)
|
||||
expect(cancelBankIdSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('is a no-op that still succeeds when there is no flow', async () => {
|
||||
const response = await findCancelHandler()(
|
||||
createMockRequest('/api/extensions/ext/tic/bankid/cancel', { method: 'POST' })
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(cancelBankIdSession).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
BANKID_FLOW_COOKIE,
|
||||
FLOW_VERIFIED_WINDOW_SECONDS,
|
||||
FLOW_WINDOW_SECONDS,
|
||||
clearBankIdFlowCookies,
|
||||
isBankIdFlowMode,
|
||||
readBankIdFlow,
|
||||
setBankIdFlowCookies,
|
||||
signBankIdFlow,
|
||||
verifyBankIdFlow,
|
||||
type BankIdFlowState,
|
||||
} from '../lib/bankid-flow-cookie'
|
||||
|
||||
const TEST_KEY = 'a'.repeat(64)
|
||||
const T0 = 1_700_000_000_000
|
||||
|
||||
const STATE: BankIdFlowState = {
|
||||
version: 1,
|
||||
sessionId: 'sess-1',
|
||||
flowId: 'flow-1',
|
||||
mode: 'signup',
|
||||
startedAt: T0,
|
||||
expiresAt: T0 + FLOW_WINDOW_SECONDS * 1000,
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('BANKID_ENCRYPTION_KEY', TEST_KEY)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
/** Parse the Set-Cookie headers a handler attached to its response. */
|
||||
function setCookies(response: NextResponse): Map<string, { value: string; attrs: string }> {
|
||||
const result = new Map<string, { value: string; attrs: string }>()
|
||||
for (const header of response.headers.getSetCookie()) {
|
||||
const [pair, ...attrs] = header.split(';')
|
||||
const separator = pair.indexOf('=')
|
||||
result.set(pair.slice(0, separator).trim(), {
|
||||
value: decodeURIComponent(pair.slice(separator + 1)),
|
||||
attrs: attrs.join(';'),
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function cookieHeader(value: string, name = BANKID_FLOW_COOKIE): Request {
|
||||
return new Request('http://localhost:3000/x', {
|
||||
headers: { cookie: `${name}=${encodeURIComponent(value)}` },
|
||||
})
|
||||
}
|
||||
|
||||
describe('sign / verify', () => {
|
||||
it('round-trips a flow', async () => {
|
||||
const signed = await signBankIdFlow(STATE)
|
||||
expect(await verifyBankIdFlow(signed, process.env, T0 + 1000)).toEqual(STATE)
|
||||
})
|
||||
|
||||
it('carries the owner of a link flow', async () => {
|
||||
const link: BankIdFlowState = { ...STATE, mode: 'link', userId: 'user-1' }
|
||||
expect(await verifyBankIdFlow(await signBankIdFlow(link), process.env, T0)).toEqual(link)
|
||||
})
|
||||
|
||||
it('rejects a link flow with no owner', async () => {
|
||||
// An unowned link flow is the shape that binds one person's personnummer
|
||||
// to the next person to use a shared browser.
|
||||
const signed = await signBankIdFlow({ ...STATE, mode: 'link' })
|
||||
expect(await verifyBankIdFlow(signed, process.env, T0)).toBeNull()
|
||||
})
|
||||
|
||||
it('does not put the session id in the clear', async () => {
|
||||
const signed = await signBankIdFlow(STATE)
|
||||
expect(signed).not.toContain('sess-1')
|
||||
expect(signed.split('.')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('rejects a tampered payload', async () => {
|
||||
const signed = await signBankIdFlow(STATE)
|
||||
const [, signature] = signed.split('.')
|
||||
const forged = Buffer.from(
|
||||
JSON.stringify({ ...STATE, sessionId: 'attacker-session' }),
|
||||
).toString('base64url')
|
||||
|
||||
expect(await verifyBankIdFlow(`${forged}.${signature}`, process.env, T0)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects an unsigned cookie a script could plant', async () => {
|
||||
const payload = Buffer.from(JSON.stringify(STATE)).toString('base64url')
|
||||
expect(await verifyBankIdFlow(payload, process.env, T0)).toBeNull()
|
||||
expect(await verifyBankIdFlow(`${payload}.`, process.env, T0)).toBeNull()
|
||||
expect(await verifyBankIdFlow(`${payload}.x`, process.env, T0)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a cookie signed with a different secret', async () => {
|
||||
const signed = await signBankIdFlow(STATE, { BANKID_ENCRYPTION_KEY: 'b'.repeat(64) })
|
||||
expect(await verifyBankIdFlow(signed, process.env, T0)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects malformed and empty values', async () => {
|
||||
expect(await verifyBankIdFlow(undefined, process.env, T0)).toBeNull()
|
||||
expect(await verifyBankIdFlow('', process.env, T0)).toBeNull()
|
||||
expect(await verifyBankIdFlow('not.a.cookie', process.env, T0)).toBeNull()
|
||||
expect(await verifyBankIdFlow('....', process.env, T0)).toBeNull()
|
||||
})
|
||||
|
||||
it('expires on the server clock, not the browser Max-Age', async () => {
|
||||
const signed = await signBankIdFlow(STATE)
|
||||
expect(await verifyBankIdFlow(signed, process.env, STATE.expiresAt)).toEqual(STATE)
|
||||
expect(await verifyBankIdFlow(signed, process.env, STATE.expiresAt + 1)).toBeNull()
|
||||
})
|
||||
|
||||
it('refuses an expiry further out than the longest window this server issues', async () => {
|
||||
const signed = await signBankIdFlow({ ...STATE, expiresAt: T0 + 24 * 3600 * 1000 })
|
||||
expect(await verifyBankIdFlow(signed, process.env, T0)).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts the verified window, which the e-mail step needs', async () => {
|
||||
const verified = { ...STATE, expiresAt: T0 + FLOW_VERIFIED_WINDOW_SECONDS * 1000 }
|
||||
expect(await verifyBankIdFlow(await signBankIdFlow(verified), process.env, T0)).toEqual(verified)
|
||||
})
|
||||
|
||||
it('caps the whole flow from startedAt, so re-issuing cannot extend it forever', async () => {
|
||||
// /poll pushes expiresAt out when it sees a completed identification.
|
||||
// Without a cap measured from the original start, polling in a loop would
|
||||
// keep a usable identification alive for as long as TIC retains it.
|
||||
// MAX_TOTAL_LIFE is FLOW_WINDOW + FLOW_VERIFIED_WINDOW from startedAt.
|
||||
const cap = (FLOW_WINDOW_SECONDS + FLOW_VERIFIED_WINDOW_SECONDS) * 1000
|
||||
// A cookie re-issued near the cap is still honoured up to it...
|
||||
const late = { ...STATE, expiresAt: T0 + cap + 60_000 }
|
||||
const signed = await signBankIdFlow(late)
|
||||
expect(await verifyBankIdFlow(signed, process.env, T0 + cap)).toEqual(late)
|
||||
// ...and dies the moment the flow as a whole is older than the cap, no
|
||||
// matter how far out the latest re-issue pushed expiresAt.
|
||||
expect(await verifyBankIdFlow(signed, process.env, T0 + cap + 1)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a startedAt in the future, which would never age out', async () => {
|
||||
const signed = await signBankIdFlow({ ...STATE, startedAt: T0 + 60_000 })
|
||||
expect(await verifyBankIdFlow(signed, process.env, T0)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects an unknown mode', async () => {
|
||||
const signed = await signBankIdFlow({ ...STATE, mode: 'admin' as never })
|
||||
expect(await verifyBankIdFlow(signed, process.env, T0)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a flow with no tab-binding id', async () => {
|
||||
const signed = await signBankIdFlow({ ...STATE, flowId: undefined as never })
|
||||
expect(await verifyBankIdFlow(signed, process.env, T0)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects an unknown version, so a future format cannot be replayed as this one', async () => {
|
||||
const signed = await signBankIdFlow({ ...STATE, version: 2 as never })
|
||||
expect(await verifyBankIdFlow(signed, process.env, T0)).toBeNull()
|
||||
})
|
||||
|
||||
it('refuses to run without a signing secret rather than falling back to unsigned', async () => {
|
||||
const empty = {}
|
||||
await expect(signBankIdFlow(STATE, empty)).rejects.toThrow(/requires BANKID_ENCRYPTION_KEY/)
|
||||
expect(await verifyBankIdFlow(await signBankIdFlow(STATE), empty, T0)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('isBankIdFlowMode', () => {
|
||||
it('accepts exactly the three flows', () => {
|
||||
expect(isBankIdFlowMode('login')).toBe(true)
|
||||
expect(isBankIdFlowMode('signup')).toBe(true)
|
||||
expect(isBankIdFlowMode('link')).toBe(true)
|
||||
expect(isBankIdFlowMode('unlink')).toBe(false)
|
||||
expect(isBankIdFlowMode('')).toBe(false)
|
||||
expect(isBankIdFlowMode(undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('readBankIdFlow', () => {
|
||||
it('reads its own cookie out of a header carrying others', async () => {
|
||||
const signed = await signBankIdFlow({ ...STATE, startedAt: Date.now(), expiresAt: Date.now() + 60_000 })
|
||||
const request = new Request('http://localhost:3000/x', {
|
||||
headers: {
|
||||
cookie: `sb-access-token=abc; ${BANKID_FLOW_COOKIE}=${encodeURIComponent(signed)}; other=1`,
|
||||
},
|
||||
})
|
||||
expect((await readBankIdFlow(request))?.sessionId).toBe('sess-1')
|
||||
})
|
||||
|
||||
it('fails closed when two cookies of this name arrive', async () => {
|
||||
// The shadowing attack: a script plants the same name at a longer path, and
|
||||
// RFC 6265 sends longer paths FIRST. Taking the first match would use the
|
||||
// planted one. The __Host- prefix should make this unreachable; being wrong
|
||||
// about that must not silently hand the flow to the attacker's cookie.
|
||||
const mine = await signBankIdFlow({ ...STATE, startedAt: Date.now(), expiresAt: Date.now() + 60_000 })
|
||||
const planted = await signBankIdFlow({
|
||||
...STATE,
|
||||
sessionId: 'attacker-session',
|
||||
startedAt: Date.now(),
|
||||
expiresAt: Date.now() + 60_000,
|
||||
})
|
||||
const request = new Request('http://localhost:3000/x', {
|
||||
headers: {
|
||||
cookie:
|
||||
`${BANKID_FLOW_COOKIE}=${encodeURIComponent(planted)}; ` +
|
||||
`${BANKID_FLOW_COOKIE}=${encodeURIComponent(mine)}`,
|
||||
},
|
||||
})
|
||||
|
||||
expect(await readBankIdFlow(request)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null with no cookie header and for a foreign cookie name', async () => {
|
||||
expect(await readBankIdFlow(new Request('http://localhost:3000/x'))).toBeNull()
|
||||
const signed = await signBankIdFlow({ ...STATE, startedAt: Date.now(), expiresAt: Date.now() + 60_000 })
|
||||
expect(await readBankIdFlow(cookieHeader(signed, 'accounted-bankid-active'))).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('cookie attributes', () => {
|
||||
it('is a __Host- cookie: HttpOnly, Secure, Lax, Path=/, no Domain', async () => {
|
||||
const response = NextResponse.json({})
|
||||
const expiresAt = Date.now() + FLOW_WINDOW_SECONDS * 1000
|
||||
await setBankIdFlowCookies(response, { ...STATE, startedAt: Date.now(), expiresAt })
|
||||
|
||||
const flow = setCookies(response).get(BANKID_FLOW_COOKIE)!
|
||||
expect(BANKID_FLOW_COOKIE.startsWith('__Host-')).toBe(true)
|
||||
expect(flow.attrs).toMatch(/HttpOnly/i)
|
||||
// Unconditional: __Host- requires it, and BankID is disabled on self-hosted
|
||||
// so there is no plain-http deployment to accommodate.
|
||||
expect(flow.attrs).toMatch(/Secure/i)
|
||||
expect(flow.attrs).toMatch(/Path=\/(;|$)/i)
|
||||
expect(flow.attrs).not.toMatch(/Domain=/i)
|
||||
// Lax, not Strict: the BankID app returns the user by a top-level
|
||||
// navigation from outside the site, and Strict would drop the cookie there.
|
||||
expect(flow.attrs).toMatch(/SameSite=lax/i)
|
||||
expect(flow.attrs).not.toMatch(/SameSite=strict/i)
|
||||
})
|
||||
|
||||
it('mirrors the signed expiry in Max-Age', async () => {
|
||||
const response = NextResponse.json({})
|
||||
const now = Date.now()
|
||||
await setBankIdFlowCookies(response, { ...STATE, startedAt: now, expiresAt: now + 120_000 }, process.env, now)
|
||||
|
||||
expect(setCookies(response).get(BANKID_FLOW_COOKIE)!.attrs).toMatch(/Max-Age=120/i)
|
||||
})
|
||||
|
||||
it('never emits a non-positive Max-Age for an almost-expired flow', async () => {
|
||||
// Max-Age=0 would mean "delete", which would drop a flow that is still
|
||||
// valid for a few hundred milliseconds.
|
||||
const response = NextResponse.json({})
|
||||
const now = Date.now()
|
||||
await setBankIdFlowCookies(response, { ...STATE, startedAt: now, expiresAt: now + 100 }, process.env, now)
|
||||
|
||||
expect(setCookies(response).get(BANKID_FLOW_COOKIE)!.attrs).toMatch(/Max-Age=1(;|$)/i)
|
||||
})
|
||||
|
||||
it('clears with the same name and attributes it set', () => {
|
||||
const response = NextResponse.json({})
|
||||
clearBankIdFlowCookies(response)
|
||||
|
||||
const flow = setCookies(response).get(BANKID_FLOW_COOKIE)!
|
||||
// A deletion that differs on path or attributes leaves the real cookie.
|
||||
expect(flow.attrs).toMatch(/Path=\/(;|$)/i)
|
||||
expect(flow.attrs).toMatch(/HttpOnly/i)
|
||||
expect(flow.attrs).toMatch(/Secure/i)
|
||||
expect(flow.attrs).toMatch(/Max-Age=0/i)
|
||||
})
|
||||
})
|
||||
@@ -24,8 +24,37 @@ import { collectBankIdResult } from '../lib/bankid-client'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { ticExtension } from '../index'
|
||||
import {
|
||||
BANKID_FLOW_COOKIE,
|
||||
BANKID_FLOW_ID_HEADER,
|
||||
signBankIdFlow,
|
||||
type BankIdFlowMode,
|
||||
} from '../lib/bankid-flow-cookie'
|
||||
|
||||
const TEST_KEY = 'a'.repeat(64)
|
||||
const TEST_FLOW_ID = 'flow-1'
|
||||
|
||||
/** Linking reads its session from the signed flow cookie, not the body. */
|
||||
async function flowCookie(
|
||||
mode: BankIdFlowMode,
|
||||
sessionId = 'test-session',
|
||||
userId = 'user-1',
|
||||
): Promise<Record<string, string>> {
|
||||
const value = await signBankIdFlow({
|
||||
version: 1,
|
||||
sessionId,
|
||||
flowId: TEST_FLOW_ID,
|
||||
mode,
|
||||
// A link flow is owned by the user who opened it; login/signup have none.
|
||||
userId: mode === 'link' ? userId : undefined,
|
||||
startedAt: Date.now(),
|
||||
expiresAt: Date.now() + 60_000,
|
||||
})
|
||||
return {
|
||||
cookie: `${BANKID_FLOW_COOKIE}=${encodeURIComponent(value)}`,
|
||||
[BANKID_FLOW_ID_HEADER]: TEST_FLOW_ID,
|
||||
}
|
||||
}
|
||||
|
||||
function findRoute(method: string, path: string) {
|
||||
const route = ticExtension.apiRoutes!.find((r) => r.method === method && r.path === path)
|
||||
@@ -56,7 +85,12 @@ function mockUnauthenticated() {
|
||||
type QueuedResult = { data?: unknown; error?: unknown }
|
||||
|
||||
/** Minimal chainable service-client mock (same pattern as bankid-complete.test.ts). */
|
||||
function mockServiceClient(fromResults: QueuedResult[], appMetadata: Record<string, unknown>) {
|
||||
function mockServiceClient(
|
||||
fromResults: QueuedResult[],
|
||||
appMetadata: Record<string, unknown>,
|
||||
// Single-use claim; `{ error: { code: '23505' } }` means another tab won.
|
||||
consumed: QueuedResult = { error: null },
|
||||
) {
|
||||
const queue = [...fromResults]
|
||||
|
||||
const chain = (): unknown => {
|
||||
@@ -87,7 +121,9 @@ function mockServiceClient(fromResults: QueuedResult[], appMetadata: Record<stri
|
||||
}
|
||||
|
||||
const client = {
|
||||
from: vi.fn().mockImplementation(() => chain()),
|
||||
from: vi.fn().mockImplementation((table: string) =>
|
||||
table === 'bankid_consumed_sessions' ? chain2(consumed) : chain()
|
||||
),
|
||||
auth: { admin },
|
||||
}
|
||||
|
||||
@@ -170,6 +206,32 @@ describe('POST /bankid/unlink', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /bankid/start, link mode', () => {
|
||||
it('requires a signed-in caller, so a link flow always has an owner', async () => {
|
||||
// An anonymous link flow would have no userId to check at /bankid/link,
|
||||
// which is what lets an abandoned flow bind to the next person to sign in.
|
||||
mockUnauthenticated()
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/start', {
|
||||
method: 'POST',
|
||||
body: { mode: 'link' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await findHandler('POST', '/bankid/start')(req))
|
||||
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('does not require auth for login or signup, which have no user yet', async () => {
|
||||
mockUnauthenticated()
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/start', {
|
||||
method: 'POST',
|
||||
body: { mode: 'login' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await findHandler('POST', '/bankid/start')(req))
|
||||
|
||||
expect(status).not.toBe(401)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /bankid/link', () => {
|
||||
function makeSession() {
|
||||
return {
|
||||
@@ -189,13 +251,13 @@ describe('POST /bankid/link', () => {
|
||||
mockServiceClient([], {})
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/link', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session' },
|
||||
headers: await flowCookie('link'),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await findHandler('POST', '/bankid/link')(req))
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 when sessionId is missing', async () => {
|
||||
it('returns 400 when the browser holds no flow', async () => {
|
||||
mockAuthenticated()
|
||||
mockServiceClient([], {})
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/link', {
|
||||
@@ -206,6 +268,107 @@ describe('POST /bankid/link', () => {
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('refuses a session that was not opened as a link flow', async () => {
|
||||
// A session started to sign someone IN must not be redirectable into
|
||||
// binding their personnummer to whoever happens to be logged in here.
|
||||
mockAuthenticated()
|
||||
const { admin, client } = mockServiceClient([], {})
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/link', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('login'),
|
||||
body: {},
|
||||
})
|
||||
const { status } = await parseJsonResponse(await findHandler('POST', '/bankid/link')(req))
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(collectBankIdResult).not.toHaveBeenCalled()
|
||||
expect(client.from).not.toHaveBeenCalled()
|
||||
expect(admin.updateUserById).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses a link flow that another user opened', async () => {
|
||||
// The shared-browser takeover: A starts "Koppla BankID" and authenticates
|
||||
// but never finishes; B signs in on the same machine and clicks the same
|
||||
// button. Without the owner check, A's personnummer is written against B's
|
||||
// user_id, and A can then sign in as B with their own BankID.
|
||||
mockAuthenticated('user-b')
|
||||
const { admin, client } = mockServiceClient([], {})
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/link', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('link', 'test-session', 'user-a'),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await findHandler('POST', '/bankid/link')(req))
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(collectBankIdResult).not.toHaveBeenCalled()
|
||||
expect(client.from).not.toHaveBeenCalled()
|
||||
expect(admin.updateUserById).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses a stale tab after a newer link flow replaced the shared cookie', async () => {
|
||||
mockAuthenticated()
|
||||
const { client } = mockServiceClient([], {})
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
const headers = await flowCookie('link')
|
||||
headers[BANKID_FLOW_ID_HEADER] = 'older-flow'
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/link', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
})
|
||||
const { status } = await parseJsonResponse(await findHandler('POST', '/bankid/link')(req))
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(collectBankIdResult).not.toHaveBeenCalled()
|
||||
expect(client.from).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses to link twice off one identification', async () => {
|
||||
mockAuthenticated()
|
||||
const { admin, client } = mockServiceClient(
|
||||
[{ data: null }], // pnr not linked to anyone yet
|
||||
{},
|
||||
{ error: { code: '23505', message: 'duplicate key' } }, // another tab claimed it first
|
||||
)
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/link', {
|
||||
method: 'POST',
|
||||
headers: await flowCookie('link'),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await findHandler('POST', '/bankid/link')(req))
|
||||
|
||||
expect(status).toBe(400)
|
||||
// The identity insert never ran, so nothing was bound twice.
|
||||
const inserts = vi.mocked(client.from).mock.calls.filter((c) => c[0] === 'bankid_identities')
|
||||
expect(inserts).toHaveLength(1) // the pnr lookup only
|
||||
expect(admin.updateUserById).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses a forged flow cookie', async () => {
|
||||
mockAuthenticated()
|
||||
const { client } = mockServiceClient([], {})
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
|
||||
// Same shape, no valid signature: what a same-origin script could plant.
|
||||
const forged = Buffer.from(
|
||||
JSON.stringify({ version: 1, sessionId: 'attacker-session', mode: 'link', startedAt: Date.now() }),
|
||||
).toString('base64url')
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/link', {
|
||||
method: 'POST',
|
||||
headers: { cookie: `${BANKID_FLOW_COOKIE}=${forged}.not-a-signature` },
|
||||
body: {},
|
||||
})
|
||||
const { status } = await parseJsonResponse(await findHandler('POST', '/bankid/link')(req))
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(client.from).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('merges app_metadata so an existing has_password: true survives linking', async () => {
|
||||
mockAuthenticated()
|
||||
vi.mocked(collectBankIdResult).mockResolvedValue(makeSession())
|
||||
@@ -219,7 +382,7 @@ describe('POST /bankid/link', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/link', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session' },
|
||||
headers: await flowCookie('link'),
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data?: { linked?: boolean } }>(
|
||||
await findHandler('POST', '/bankid/link')(req)
|
||||
@@ -242,7 +405,7 @@ describe('POST /bankid/link', () => {
|
||||
|
||||
const req = createMockRequest('/api/extensions/ext/tic/bankid/link', {
|
||||
method: 'POST',
|
||||
body: { sessionId: 'test-session' },
|
||||
headers: await flowCookie('link'),
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await findHandler('POST', '/bankid/link')(req)
|
||||
|
||||
Reference in New Issue
Block a user