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) <[email protected]>

* 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) <[email protected]>
This commit is contained in:
Mattsson
2026-08-15 23:07:29 +02:00
committed by GitHub
co-authored by Claude Opus 5
parent 2deea05d42
commit edfdbe2d2a
13 changed files with 2294 additions and 227 deletions
+6
View File
File diff suppressed because one or more lines are too long
+51 -14
View File
@@ -62,11 +62,12 @@ function RegisterPageContent() {
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [isLoading, setIsLoading] = useState(false)
const [isCancelling, setIsCancelling] = useState(false)
const [isRegistered, setIsRegistered] = useState(false)
const [duplicateEmail, setDuplicateEmail] = useState<string | null>(null)
const [inviteEmail, setInviteEmail] = useState<string | null>(null)
const [bankIdUser, setBankIdUser] = useState<{ givenName?: string; surname?: string } | null>(null)
const [bankIdSessionId, setBankIdSessionId] = useState<string | null>(null)
const [bankIdFlowId, setBankIdFlowId] = useState<string | null>(null)
const [bankIdEmail, setBankIdEmail] = useState('')
// Signup failures render inline next to the form (see AuthFormError), never
// as a toast. Field-level problems attach to their field; everything else
@@ -166,29 +167,37 @@ function RegisterPageContent() {
setFormError({ kind: 'bankid', message: t('bankid_failed_description') })
return
}
// BankID verified: store sessionId and show email form
// BankID verified: show the email form. The session itself stays in the
// server's HttpOnly flow cookie, so there is nothing to hold on to here.
setFormError(null)
setBankIdUser({ givenName: result.givenName, surname: result.surname })
if (result.sessionId) setBankIdSessionId(result.sessionId)
setBankIdFlowId(result.flowId ?? null)
}
const handleBankIdSignup = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
setFormError(null)
setIsLoading(true)
const formData = new FormData(e.currentTarget)
const emailValue = (formData.get('bankid_email') as string) || bankIdEmail
if (!bankIdFlowId) {
setFormError({ kind: 'bankid', message: t('bankid_failed_description') })
return
}
setIsLoading(true)
try {
// Only the e-mail travels: the session and the fact that this is a
// signup are both pinned in the server's flow cookie.
const res = await fetch('/api/extensions/ext/tic/bankid/complete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
sessionId: bankIdSessionId,
mode: 'signup',
email: emailValue,
}),
headers: {
'Content-Type': 'application/json',
'x-bankid-flow-id': bankIdFlowId,
},
body: JSON.stringify({ email: emailValue }),
})
const json = await res.json()
@@ -546,7 +555,9 @@ function RegisterPageContent() {
{inviteEmail ? t('invite_email_hint') : t('bankid_email_hint')}
</p>
</div>
<Button type="submit" className="w-full h-11" disabled={isLoading}>
{/* Also disabled while Back's /cancel is in flight: submitting
then would race the cookie clear (recoverable, but pointless). */}
<Button type="submit" className="w-full h-11" disabled={isLoading || isCancelling}>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
@@ -560,9 +571,35 @@ function RegisterPageContent() {
type="button"
variant="ghost"
className="w-full text-muted-foreground"
onClick={() => {
setBankIdUser(null)
setBankIdSessionId(null)
disabled={isLoading || isCancelling}
onClick={async () => {
// AWAIT the cancel before remounting BankIdAuth. The flow
// cookie outlives this component and BankIdAuth probes for a
// live flow on mount, so clearing the form first would let it
// find the still-completed session. Its own isCancelling
// state, not isLoading: isLoading drives the submit button's
// "Skapar konto...", and pressing Back should not claim an
// account is being created.
setIsCancelling(true)
try {
const res = await fetch('/api/extensions/ext/tic/bankid/cancel', {
method: 'POST',
headers: bankIdFlowId
? { 'x-bankid-flow-id': bankIdFlowId }
: undefined,
})
if (!res.ok) throw new Error(`cancel failed: ${res.status}`)
// Flow cleared server-side; the remounted BankIdAuth will
// probe, find nothing, and show the start button.
setBankIdUser(null)
setBankIdFlowId(null)
} catch {
// The flow is still live, so resetting the form would just
// bounce the user back here. Say so instead of looping.
setFormError({ kind: 'bankid', message: t('bankid_cancel_failed') })
} finally {
setIsCancelling(false)
}
}}
>
<ArrowLeft className="mr-2 h-4 w-4" />
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -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)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,364 @@
/**
* Server-held state for an in-flight BankID flow.
*
* Why the session id is not allowed near the browser's JavaScript
* -------------------------------------------------------------
* A TIC `sessionId` is an unauthenticated bearer credential. Anyone holding
* one can POST it to /bankid/poll (skipAuth) and read the holder's
* personnummer, or POST it to /bankid/complete with mode 'login' and receive a
* `tokenHash` that `verifyOtp` turns into a full Supabase session, with MFA
* skipped because BankID accounts carry `bankid_linked`. It used to be handed
* to the client and kept in `sessionStorage`, which made every one of those a
* single XSS away, and made the obvious fix for the cross-tab bug (move it to
* `localStorage` so the tab BankID returns to can resume) a straight upgrade
* of any same-origin XSS into a login-fixation primitive.
*
* So the id never leaves the server. It lives in an HttpOnly cookie that the
* browser attaches to the BankID endpoints and nothing else:
*
* • HttpOnly script cannot read it, so XSS cannot steal a session.
* • signed script cannot FORGE one. It does not stop a script from
* planting a cookie the server genuinely minted (an attacker
* can fetch one with curl), and it does not bind the flow to
* a browser or a person. Planting a completed identification
* is what login fixation is, so the protection against that
* is not here: it is the client refusing to consume a flow
* this browsing context did not start without an explicit
* confirmation. See BankIdAuth's resume handling.
* • __Host- forbids Domain and forces Path=/, which leaves exactly one
* possible (name, domain, path) for this cookie. Without it a
* script can plant the same name at a LONGER path, which the
* browser sends first and the server's deletion cannot reach.
* • SameSite=Lax the BankID app returns the user by top-level navigation
* from outside the site; Strict would drop the cookie there
* and strand exactly the flow this exists to serve.
* • short Max-Age a BankID order is good for ~3 minutes. An abandoned flow
* should not outlive it by much.
*
* Being a cookie rather than client storage is also what fixes the original
* bug: cookies are shared by every tab of the origin, so whichever tab BankID
* returns the user to, new or reloaded, simply polls and continues. No
* client-side handoff, no cross-tab lock, no heartbeat.
*
* `mode` is pinned here at /start and read back at /complete, so the flow a
* session was opened for is the only flow that can finish it. The client
* cannot ask to complete a 'link' session as a 'login'.
*/
import { NextResponse } from 'next/server'
export type BankIdFlowMode = 'login' | 'signup' | 'link'
/**
* HttpOnly, signed. Holds the session id, and is never readable by scripts.
*
* The `__Host-` prefix is load-bearing, not decoration. Browsers only refuse a
* `document.cookie` write when it collides with an existing HttpOnly cookie on
* the exact (name, domain, path) triple, so without the prefix a script could
* set the SAME NAME at a longer path; RFC 6265 §5.4 serialises longer paths
* first, so the planted one would win, and a Max-Age=0 written to the shorter
* path could never delete it. `__Host-` forbids `Domain` and forces `Path=/`,
* which leaves exactly one possible (name, domain, path) for this cookie: the
* one the server owns. That also blocks cookie-tossing from a sibling
* white-label subdomain.
*
* Losing the narrow Path is the price. It is worth it: the narrow Path only
* ever bought log hygiene, whereas the shadowing it permitted was a way to
* plant a completed session in someone else's browser.
*/
export const BANKID_FLOW_COOKIE = '__Host-accounted-bankid-flow'
/**
* Non-secret identifier that binds one browser tab to the flow it started or
* explicitly resumed. The signed cookie remains the credential; this header
* only prevents a stale tab from silently acting on a newer flow that replaced
* the shared cookie.
*/
export const BANKID_FLOW_ID_HEADER = 'x-bankid-flow-id'
/**
* How long a fresh order may be resumed. A BankID order is good for ~3 minutes;
* the rest covers the app switch and a slow return.
*/
export const FLOW_WINDOW_SECONDS = 300
/**
* Replaces the window above once the identification has actually happened. The
* signup flow then asks for an e-mail, and a user hunting for the right address
* (or switching to a password manager and back) must not have the session
* expire under them: on `main` this step was bounded only by TIC's own
* retention, so a short shared budget would have been a real regression.
*/
export const FLOW_VERIFIED_WINDOW_SECONDS = 900
/** Sanity bound on a decoded expiry, so no cookie can claim an unbounded life. */
const MAX_WINDOW_MS = FLOW_VERIFIED_WINDOW_SECONDS * 1000
/**
* Ceiling on a whole flow, measured from /start. Bounds the re-issue chain:
* an identification cannot be kept resumable indefinitely by polling.
*/
export const MAX_TOTAL_LIFE_SECONDS = FLOW_WINDOW_SECONDS + FLOW_VERIFIED_WINDOW_SECONDS
const MAX_TOTAL_LIFE_MS = MAX_TOTAL_LIFE_SECONDS * 1000
const SIGNING_CONTEXT = 'accounted-bankid-flow-v1:'
export interface BankIdFlowState {
version: 1
sessionId: string
/** Random, non-secret tab binding. The BankID session id remains HttpOnly. */
flowId: string
mode: BankIdFlowMode
/**
* Who opened a `link` flow. Linking binds a personnummer to whoever is
* authenticated when /bankid/link runs, so without this a flow started by one
* person and left unfinished could be picked up by the next person to use the
* browser and bind the FIRST person's identity to the SECOND person's
* account. Absent for login and signup, which have no user yet.
*/
userId?: string
/**
* When /start opened this flow. Carried so the total life can be capped:
* /poll extends `expiresAt` when it observes completion, and without a fixed
* origin a caller could keep polling to push the window forward forever,
* leaving a usable identification in the jar for as long as TIC retains it.
*/
startedAt: number
/** Absolute expiry, enforced server-side; the browser's Max-Age only mirrors it. */
expiresAt: number
}
type Environment = Record<string, string | undefined>
export function isBankIdFlowMode(value: unknown): value is BankIdFlowMode {
return value === 'login' || value === 'signup' || value === 'link'
}
/**
* Unlike the session-timeout cookie, which degrades to unsigned-and-ignored
* when misconfigured, this one throws: a BankID flow that cannot be bound to
* the browser that started it must not run at all.
*/
function getSigningSecret(env: Environment): string {
const dedicated = env.BANKID_ENCRYPTION_KEY?.trim()
if (dedicated) return dedicated
const sessionSecret = env.SESSION_TIMEOUT_SECRET?.trim()
if (sessionSecret) return sessionSecret
const serviceRole = env.SUPABASE_SERVICE_ROLE_KEY?.trim()
if (serviceRole) return serviceRole
throw new Error(
'BankID flow cookie requires BANKID_ENCRYPTION_KEY, SESSION_TIMEOUT_SECRET or SUPABASE_SERVICE_ROLE_KEY',
)
}
function bytesToBase64Url(bytes: Uint8Array): string {
let binary = ''
for (const byte of bytes) binary += String.fromCharCode(byte)
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '')
}
// The explicit ArrayBuffer parameter matters: a bare Uint8Array is
// Uint8Array<ArrayBufferLike>, which crypto.subtle rejects as a BufferSource
// because it could be backed by a SharedArrayBuffer. Same annotation as
// lib/auth/session-timeout.ts, for the same reason.
function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer> | null {
try {
const base64 = value.replaceAll('-', '+').replaceAll('_', '/')
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, '=')
const binary = atob(padded)
const bytes = new Uint8Array(binary.length)
for (let index = 0; index < binary.length; index += 1) {
bytes[index] = binary.charCodeAt(index)
}
return bytes
} catch {
return null
}
}
async function importSigningKey(secret: string): Promise<CryptoKey> {
// HKDF-derived with a purpose-bound info string, never the raw secret: the
// same key material also encrypts personnummer at rest (lib/auth/bankid.ts)
// and the SUPABASE_SERVICE_ROLE_KEY fallback is a privileged credential.
// Neither may double as an HMAC key directly.
const baseKey = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secret),
'HKDF',
false,
['deriveKey'],
)
return crypto.subtle.deriveKey(
{
name: 'HKDF',
hash: 'SHA-256',
salt: new Uint8Array(32),
info: new TextEncoder().encode(SIGNING_CONTEXT),
},
baseKey,
{ name: 'HMAC', hash: 'SHA-256', length: 256 },
false,
['sign', 'verify'],
)
}
export async function signBankIdFlow(
state: BankIdFlowState,
env: Environment = process.env,
): Promise<string> {
const payload = bytesToBase64Url(new TextEncoder().encode(JSON.stringify(state)))
const key = await importSigningKey(getSigningSecret(env))
const signature = await crypto.subtle.sign(
'HMAC',
key,
new TextEncoder().encode(`${SIGNING_CONTEXT}${payload}`),
)
return `${payload}.${bytesToBase64Url(new Uint8Array(signature))}`
}
/**
* Verify and decode a flow cookie. Returns null for anything that is not a
* cookie this server minted and still considers live: bad signature, wrong
* shape, unknown mode, an unowned `link` flow, a `startedAt` in the future,
* one whose `expiresAt` is past or claims more than MAX_WINDOW, or a whole
* flow older than MAX_TOTAL_LIFE. Expiry is re-checked here rather than
* trusted to the browser's Max-Age, which a client controls.
*/
export async function verifyBankIdFlow(
value: string | undefined,
env: Environment = process.env,
now: number = Date.now(),
): Promise<BankIdFlowState | null> {
if (!value) return null
const [payload, signature, extra] = value.split('.')
if (!payload || !signature || extra !== undefined) return null
const signatureBytes = base64UrlToBytes(signature)
if (!signatureBytes) return null
try {
const key = await importSigningKey(getSigningSecret(env))
const valid = await crypto.subtle.verify(
'HMAC',
key,
signatureBytes,
new TextEncoder().encode(`${SIGNING_CONTEXT}${payload}`),
)
if (!valid) return null
} catch {
return null
}
const decoded = base64UrlToBytes(payload)
if (!decoded) return null
let parsed: unknown
try {
parsed = JSON.parse(new TextDecoder().decode(decoded))
} catch {
return null
}
if (!parsed || typeof parsed !== 'object') return null
const state = parsed as Partial<BankIdFlowState>
if (state.version !== 1) return null
if (typeof state.sessionId !== 'string' || !state.sessionId) return null
if (typeof state.flowId !== 'string' || !state.flowId) return null
if (!isBankIdFlowMode(state.mode)) return null
if (state.userId !== undefined && (typeof state.userId !== 'string' || !state.userId)) return null
// A `link` flow with no owner cannot be validated against the caller, and an
// unowned link is exactly the shape that binds the wrong identity.
if (state.mode === 'link' && !state.userId) return null
if (typeof state.startedAt !== 'number' || !Number.isFinite(state.startedAt)) return null
if (state.startedAt > now) return null
if (typeof state.expiresAt !== 'number' || !Number.isFinite(state.expiresAt)) return null
if (now > state.expiresAt) return null
// Expiry is enforced here rather than trusted to the browser's Max-Age, which
// a client controls. The upper bound stops any cookie claiming a longer life
// than the longest window this server ever issues.
if (state.expiresAt - now > MAX_WINDOW_MS) return null
// Hard cap on the whole flow, not just this cookie. /poll re-issues with a
// longer window 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 the session.
if (now - state.startedAt > MAX_TOTAL_LIFE_MS) return null
return state as BankIdFlowState
}
/**
* `__Host-` requires Secure, Path=/ and no Domain; a cookie missing any of them
* is rejected outright by the browser. Secure is therefore unconditional here,
* and that costs nothing: isBankIdEnabled() (lib/auth/bankid.ts) returns false
* whenever NEXT_PUBLIC_SELF_HOSTED is set, so there is no plain-http BankID
* deployment to accommodate. An earlier version made Secure conditional on
* x-forwarded-proto for that imagined case, which only meant a proxy that omits
* the header would silently ship this cookie unprotected on a real HTTPS site.
*/
const FLOW_COOKIE_OPTIONS = {
httpOnly: true,
secure: true,
sameSite: 'lax',
path: '/',
} as const
/** Attach a flow to the response, replacing any flow already there. */
export async function setBankIdFlowCookies(
response: NextResponse,
state: BankIdFlowState,
env: Environment = process.env,
now: number = Date.now(),
): Promise<void> {
response.cookies.set(BANKID_FLOW_COOKIE, await signBankIdFlow(state, env), {
...FLOW_COOKIE_OPTIONS,
// Mirrors the signed expiry so an abandoned flow also disappears from the
// jar; the server-side check in verifyBankIdFlow is the real bound.
maxAge: Math.max(1, Math.ceil((state.expiresAt - now) / 1000)),
})
}
/** End the flow. Called on every terminal outcome. */
export function clearBankIdFlowCookies(response: NextResponse): void {
// Same name, same path, same attributes: a deletion written to a different
// path would leave the real cookie in place.
response.cookies.set(BANKID_FLOW_COOKIE, '', { ...FLOW_COOKIE_OPTIONS, maxAge: 0 })
}
/**
* Read and verify the flow attached to an incoming request.
*
* Fails closed when the header carries more than one cookie of this name.
* `__Host-` should make that impossible, but the cost of being wrong about a
* browser's prefix handling is that a planted duplicate gets used instead of
* the real one, so ambiguity is treated as no flow rather than resolved by
* picking a winner.
*/
export async function readBankIdFlow(
request: Request,
env: Environment = process.env,
): Promise<BankIdFlowState | null> {
const header = request.headers.get('cookie')
if (!header) return null
const values: string[] = []
for (const part of header.split(';')) {
const separator = part.indexOf('=')
if (separator === -1) continue
if (part.slice(0, separator).trim() !== BANKID_FLOW_COOKIE) continue
const raw = part.slice(separator + 1).trim()
// A malformed percent-escape throws URIError. Treat it as an unusable
// cookie rather than letting it become a 500 in every handler that reads
// the flow.
try {
values.push(decodeURIComponent(raw))
} catch {
return null
}
}
if (values.length !== 1) return null
return verifyBankIdFlow(values[0], env)
}
+9
View File
@@ -314,6 +314,14 @@
"bankid_no_account_create": "Or create a new account",
"bankid_unavailable_title": "No password?",
"bankid_unavailable_body": "If you created your account with BankID you can use \"Forgot password?\" to get a sign-in link by email.",
"bankid_cancelling": "Cancelling...",
"bankid_completing": "Completing the BankID identification...",
"bankid_finish_in_app": "Complete the identification in the BankID app",
"bankid_resume_title": "BankID identification in progress",
"bankid_resume_description": "This browser has an ongoing BankID identification. Continue only if you started it.",
"bankid_resume_continue": "Continue",
"bankid_resume_hint": "Complete the BankID identification...",
"bankid_resume_restart": "Start over",
"terms_prefix": "By signing in you agree to our",
"terms_link": "terms",
"terms_and": "and",
@@ -1162,6 +1170,7 @@
"terms_and": "and",
"privacy_link": "privacy policy",
"bankid_failed_title": "BankID failed",
"bankid_cancel_failed": "Could not cancel the BankID identification. Please try again.",
"bankid_failed_description": "Could not verify your identity.",
"bankid_already_linked_title": "BankID already linked",
"bankid_already_linked_description": "This BankID is already linked to an account. Try signing in instead.",
+9
View File
@@ -314,6 +314,14 @@
"bankid_no_account_create": "Eller skapa ett nytt konto",
"bankid_unavailable_title": "Har du inget lösenord?",
"bankid_unavailable_body": "Om du skapade ditt konto med BankID kan du använda \"Glömt lösenord?\" för att få en inloggningslänk via e-post.",
"bankid_cancelling": "Avbryter...",
"bankid_completing": "Slutför BankID-identifieringen...",
"bankid_finish_in_app": "Slutför identifieringen i BankID-appen",
"bankid_resume_title": "BankID-identifiering pågår",
"bankid_resume_description": "Den här webbläsaren har en påbörjad BankID-identifiering. Fortsätt bara om det är du som startade den.",
"bankid_resume_continue": "Fortsätt",
"bankid_resume_hint": "Slutför BankID-identifieringen...",
"bankid_resume_restart": "Starta om",
"terms_prefix": "Genom att logga in godkänner du våra",
"terms_link": "villkor",
"terms_and": "och",
@@ -1162,6 +1170,7 @@
"terms_and": "och",
"privacy_link": "integritetspolicy",
"bankid_failed_title": "BankID misslyckades",
"bankid_cancel_failed": "Kunde inte avbryta BankID-identifieringen. Försök igen.",
"bankid_failed_description": "Kunde inte verifiera din identitet.",
"bankid_already_linked_title": "BankID redan kopplat",
"bankid_already_linked_description": "Detta BankID är redan kopplat till ett konto. Försök logga in istället.",
@@ -0,0 +1,53 @@
-- Makes a BankID session usable exactly once, atomically.
--
-- The BankID flow now lives in a cookie rather than per-tab client storage, so
-- every tab of the browser shares one session. That is what lets the tab the
-- BankID app returns the user to finish a flow another tab started, and it is
-- also why two tabs can observe `status: complete` inside the same poll tick
-- and both try to finish it.
--
-- Both would call supabase.auth.admin.generateLink(), and the second magic link
-- invalidates the first, so whichever tab the user is actually looking at may
-- be the one that fails with "Inloggningen med BankID misslyckades".
--
-- Clearing the flow cookie on the way out does NOT prevent this: a Set-Cookie
-- only takes effect once a response reaches the browser, so two requests that
-- both already carried the cookie both pass the check. There is no shared
-- process memory to coordinate in on serverless either. A unique index is the
-- only thing here that is genuinely atomic: the second INSERT raises 23505 and
-- that request stops before minting anything.
--
-- Rows are bookkeeping, not business data: a BankID session id is meaningless
-- to TIC within the hour, and nothing reads a row back. They are nonetheless
-- retained rather than deleted, so a replayed id is still recognised as spent
-- instead of silently becoming reusable.
--
-- There is deliberately NO cleanup job in this migration. At current volume
-- (single-digit BankID authentications per day) the table takes decades to
-- reach a megabyte, and a pruning cron is a moving part that can fail open.
-- consumed_at is indexed so an age-based prune can be added later without a
-- second migration. What the retention does mean, and is worth being explicit
-- about: this is a permanent record of when each BankID identification
-- happened, which is why the table is service-role only.
CREATE TABLE public.bankid_consumed_sessions (
session_id TEXT PRIMARY KEY,
consumed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- For a future age-based prune; nothing queries it today.
CREATE INDEX idx_bankid_consumed_sessions_consumed_at
ON public.bankid_consumed_sessions (consumed_at);
ALTER TABLE public.bankid_consumed_sessions ENABLE ROW LEVEL SECURITY;
-- No policies at all, deliberately. The table is written and read only by the
-- TIC extension's BankID handlers through createServiceClient(), which bypasses
-- RLS. Nothing user-facing may see which sessions exist: the ids are bearer
-- credentials for a personnummer and for a Supabase session, and the row set is
-- a record of who authenticated and when.
COMMENT ON TABLE public.bankid_consumed_sessions IS
'Spent BankID session ids. The PK is the single-use guard for /bankid/complete and /bankid/link; see migration header.';
NOTIFY pgrst, 'reload schema';
+3 -1
View File
@@ -683,6 +683,8 @@ export function createMockRequest(
method?: string
body?: unknown
searchParams?: Record<string, string>
/** Extra request headers, e.g. `cookie` for routes that read one. */
headers?: Record<string, string>
}
): Request {
const fullUrl = new URL(url, 'http://localhost:3000')
@@ -693,7 +695,7 @@ export function createMockRequest(
}
return new Request(fullUrl.toString(), {
method: options?.method || 'GET',
headers: { 'Content-Type': 'application/json' },
headers: { 'Content-Type': 'application/json', ...options?.headers },
...(options?.body ? { body: JSON.stringify(options.body) } : {}),
})
}
@@ -0,0 +1,99 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool, withUserContext } from './setup'
import { insertAuthUser } from './fixtures'
/**
* bankid_consumed_sessions (migration 20260815120000) is the single-use guard
* for a BankID identification.
*
* The flow now lives in a cookie, so every tab of a browser shares one session
* and two of them can observe `status: complete` in the same poll tick. Both
* would call generateLink(), and the second magic link invalidates the first,
* so the tab the user is looking at may be the one that fails. Expiring the
* cookie on the way out does not prevent that: a Set-Cookie only applies once a
* response reaches the browser, and both requests already carried it.
*
* These pin the two properties the application actually relies on: the claim is
* atomic, and the table is invisible to end users. A session id is a bearer
* credential for a personnummer and for a Supabase session, and the row set is
* a record of who authenticated and when.
*/
describe('bankid_consumed_sessions (pg)', () => {
it('lets exactly one claim win for a given session id', async () => {
const sessionId = `sess-${randomUUID()}`
await getPool().query(
'INSERT INTO public.bankid_consumed_sessions (session_id) VALUES ($1)',
[sessionId],
)
await expect(
getPool().query(
'INSERT INTO public.bankid_consumed_sessions (session_id) VALUES ($1)',
[sessionId],
),
).rejects.toMatchObject({ code: '23505' })
})
it('does not collide across different sessions', async () => {
const a = `sess-${randomUUID()}`
const b = `sess-${randomUUID()}`
await getPool().query(
'INSERT INTO public.bankid_consumed_sessions (session_id) VALUES ($1), ($2)',
[a, b],
)
const { rows } = await getPool().query<{ n: number }>(
'SELECT count(*)::int AS n FROM public.bankid_consumed_sessions WHERE session_id IN ($1, $2)',
[a, b],
)
expect(rows[0]!.n).toBe(2)
})
it('stamps consumed_at so spent sessions can be aged out', async () => {
const sessionId = `sess-${randomUUID()}`
await getPool().query(
'INSERT INTO public.bankid_consumed_sessions (session_id) VALUES ($1)',
[sessionId],
)
const { rows } = await getPool().query<{ consumed_at: Date }>(
'SELECT consumed_at FROM public.bankid_consumed_sessions WHERE session_id = $1',
[sessionId],
)
expect(rows[0]!.consumed_at).toBeInstanceOf(Date)
})
it('has RLS on with no policies, so authenticated users see nothing', async () => {
const { rows: flags } = await getPool().query<{ relrowsecurity: boolean }>(
`SELECT c.relrowsecurity
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public' AND c.relname = 'bankid_consumed_sessions'`,
)
expect(flags[0]!.relrowsecurity).toBe(true)
const { rows: policies } = await getPool().query<{ n: number }>(
`SELECT count(*)::int AS n FROM pg_policies
WHERE schemaname = 'public' AND tablename = 'bankid_consumed_sessions'`,
)
expect(policies[0]!.n).toBe(0)
// And the guard actually bites for a real user, not just on paper: the
// handlers write through the service role, which bypasses RLS.
const sessionId = `sess-${randomUUID()}`
await getPool().query(
'INSERT INTO public.bankid_consumed_sessions (session_id) VALUES ($1)',
[sessionId],
)
const userId = await insertAuthUser()
await withUserContext(userId, async (client) => {
const { rows } = await client.query<{ n: number }>(
'SELECT count(*)::int AS n FROM public.bankid_consumed_sessions WHERE session_id = $1',
[sessionId],
)
expect(rows[0]!.n).toBe(0)
})
})
})