From a888260f01a27b59faa14ad9bdfa8d135af37dc4 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Wed, 18 Nov 2026 13:36:18 +0200 Subject: [PATCH] Accounts: product tests (sign out everywhere, back-channel calls, deletion, export, Connect, admin), lib tests Co-Authored-By: Claude Opus 5.5 --- apps/accounts/backend/src/oidc/provider.ts | 5 + apps/accounts/backend/src/oidc/sessions.ts | 2 +- apps/accounts/backend/tests/lib.test.ts | 95 +++++++++ apps/accounts/backend/tests/products.test.ts | 210 +++++++++++++++++++ apps/accounts/backend/tests/signin.test.ts | 2 +- 5 files changed, 312 insertions(+), 2 deletions(-) create mode 100644 apps/accounts/backend/tests/lib.test.ts create mode 100644 apps/accounts/backend/tests/products.test.ts diff --git a/apps/accounts/backend/src/oidc/provider.ts b/apps/accounts/backend/src/oidc/provider.ts index 963a193..d167353 100644 --- a/apps/accounts/backend/src/oidc/provider.ts +++ b/apps/accounts/backend/src/oidc/provider.ts @@ -124,6 +124,11 @@ export async function createProvider(ctx: Ctx): Promise { Session: (_k, session) => (session.transient ? DAY : sessionDays * DAY), }, renderError: renderError(ctx), + // oidc-provider refuses private addresses for back-channel logout (its SSRF protection). Local + // testing only (LINKS_ALLOW_PRIVATE): send without that check, as for the other link calls. + ...(ctx.config.allowPrivateLinks && !ctx.config.production + ? { fetch: (input: string | URL | Request, init?: RequestInit) => { const { dispatcher: _d, ...rest } = (init ?? {}) as RequestInit & { dispatcher?: unknown }; return fetch(input, rest); } } + : {}), rotateRefreshToken: false, issueRefreshToken: () => false, }; diff --git a/apps/accounts/backend/src/oidc/sessions.ts b/apps/accounts/backend/src/oidc/sessions.ts index 96cdb81..5ff85cb 100644 --- a/apps/accounts/backend/src/oidc/sessions.ts +++ b/apps/accounts/backend/src/oidc/sessions.ts @@ -36,7 +36,7 @@ export async function signOutEverywhere(ctx: Ctx, provider: Provider, accountId: told++; } } catch (e) { - console.warn(`[sessions] back-channel logout to ${clientId} failed:`, (e as Error).message); + console.warn(`[sessions] back-channel logout to ${clientId} failed:`, (e as Error).message, (e as { cause?: Error }).cause?.message ?? ''); } } await ctx.db.oidcPayload.deleteMany({ where: { id: row.id } }); diff --git a/apps/accounts/backend/tests/lib.test.ts b/apps/accounts/backend/tests/lib.test.ts new file mode 100644 index 0000000..ffae7e2 --- /dev/null +++ b/apps/accounts/backend/tests/lib.test.ts @@ -0,0 +1,95 @@ +// The small pieces: passwords (including bcrypt hashes Cross Events 3.0 will bring across), codes, +// recovery codes, secrets at rest, licence states, the church profile rules. +import assert from 'node:assert/strict'; +import { describe, test } from 'node:test'; +import bcrypt from 'bcryptjs'; +import { hashPassword, needsRehash, passwordProblem, verifyPassword } from '../src/lib/passwords.js'; +import { codeAt, generateSecret, matchStep, otpauthUrl } from '../src/lib/totp.js'; +import { hashRecoveryCode, newRecoveryCodes, normaliseRecoveryCode } from '../src/lib/recoveryCodes.js'; +import { Secrets } from '../src/lib/crypto.js'; +import { stateFor, type LicenceClaims } from '../src/hub/licence.js'; +import { normalisePhone } from '../src/accounts/service.js'; +import { waNumber } from '../src/lib/messages.js'; + +describe('passwords', () => { + test('Argon2id hashes verify, wrong passwords don\'t', async () => { + const h = await hashPassword('Correct-horse-1'); + assert.match(h, /^\$argon2id\$/); + assert.equal(await verifyPassword('Correct-horse-1', h), true); + assert.equal(await verifyPassword('wrong-password', h), false); + assert.equal(needsRehash(h), false); + }); + + test('bcrypt hashes from Cross Events verify and are marked for re-hashing', async () => { + const h = await bcrypt.hash('Old-events-password', 4); + assert.equal(await verifyPassword('Old-events-password', h), true); + assert.equal(needsRehash(h), true); + assert.equal(await verifyPassword('anything', null), false); + assert.equal(await verifyPassword('anything', 'not-a-hash'), false); + }); + + test('at least 8 characters', () => { + assert.ok(passwordProblem('short')); + assert.equal(passwordProblem('long-enough'), null); + }); +}); + +describe('authenticator codes', () => { + test('a code works once, with a step either side for clock drift', () => { + const secret = generateSecret(); + const now = Date.now(); + const step = Math.floor(now / 30000); + assert.equal(matchStep(secret, codeAt(secret, step), { now }), step); + assert.equal(matchStep(secret, codeAt(secret, step - 1), { now }), step - 1); + assert.equal(matchStep(secret, codeAt(secret, step - 3), { now }), null); + assert.equal(matchStep(secret, codeAt(secret, step), { now, afterStep: step }), null); + assert.match(otpauthUrl(secret, 'a@b.co', 'Hope Family'), /^otpauth:\/\/totp\/Hope%20Family%3Aa%40b\.co\?secret=/); + }); + + test('the same codes as Cross Events 2.3 for the same secret (RFC 6238 test vector)', () => { + // RFC 6238 SHA-1 secret "12345678901234567890" in base32, T = 59 s → 94287082 (last 6 digits). + assert.equal(codeAt('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', 1), '287082'); + }); +}); + +describe('recovery codes', () => { + test('ten, readable, matched whatever the case and dashes', () => { + const { codes, hashes } = newRecoveryCodes(); + assert.equal(codes.length, 10); + assert.match(codes[0]!, /^[a-z2-9]{4}-[a-z2-9]{4}-[a-z2-9]{4}$/); + assert.equal(hashRecoveryCode(codes[0]!.toUpperCase().replace(/-/g, ' ')), hashes[0]); + assert.equal(normaliseRecoveryCode('ABCD EFGH JKMN'), 'abcd-efgh-jkmn'); + }); +}); + +describe('secrets at rest', () => { + test('round trip; another key can\'t read it; changed data fails', () => { + const a = new Secrets('one-secret-that-is-long-enough-for-tests'); + const enc = a.encrypt('totp-secret'); + assert.match(enc, /^enc:/); + assert.equal(a.decrypt(enc), 'totp-secret'); + assert.throws(() => new Secrets('another-secret-that-is-long-enough').decrypt(enc)); + assert.throws(() => a.decrypt(`${enc.slice(0, -2)}00`)); + }); +}); + +describe('licence states (Accounts never goes read-only)', () => { + const base: LicenceClaims = { v: 1, installId: 'i', customer: 'Hope', status: 'active', licenceExpiresAt: null, validUntil: '2026-12-01T00:00:00Z', graceDays: 14 }; + test('active, grace, lapsed, revoked, unlicensed', () => { + assert.equal(stateFor(base, 'i', new Date('2026-11-20')).state, 'active'); + assert.equal(stateFor(base, 'i', new Date('2026-12-05')).state, 'grace'); + assert.equal(stateFor(base, 'i', new Date('2027-01-01')).state, 'lapsed'); + assert.equal(stateFor({ ...base, status: 'revoked' }, 'i').state, 'revoked'); + assert.equal(stateFor(null, null).state, 'unlicensed'); + assert.equal(stateFor(base, 'other').state, 'unlicensed'); + }); +}); + +describe('phone numbers', () => { + test('South African numbers in every common format', () => { + assert.equal(normalisePhone('082 123 4567'), '+27821234567'); + assert.equal(normalisePhone('+27 82 123 4567'), '+27821234567'); + assert.equal(normalisePhone('hello'), null); + assert.equal(waNumber('+27821234567'), '27821234567'); + }); +}); diff --git a/apps/accounts/backend/tests/products.test.ts b/apps/accounts/backend/tests/products.test.ts new file mode 100644 index 0000000..16c1aa5 --- /dev/null +++ b/apps/accounts/backend/tests/products.test.ts @@ -0,0 +1,210 @@ +// Accounts and the church's products (docs/ACCOUNTS-1.0-PLAN.md §3–§7): signing out everywhere, +// signed back-channel calls, deletion with a product that says "not yet", "download my data", the +// church profile, Connect, and admin and setup rules. +import assert from 'node:assert/strict'; +import { after, before, beforeEach, describe, test } from 'node:test'; +import { churchSchema, IDENTITY_SCHEMA, LINK_SCHEMA, OIDC_CLIENT_PATHS } from '@crosscode/contracts'; +import { generateEd25519, ed25519PublicToPem, newLinkNonce, newLinkSecret, signLink } from '@crosscode/contracts/signing'; +import { Browser, PRODUCT_ID, ACCOUNTS_ID, startHarness, type Harness } from './support/harness.js'; +import { runDue } from '../src/links/deliveries.js'; +import { approveDeletion, runDeletionJob } from '../src/privacy/deletion.js'; +import { finishIfComplete } from '../src/privacy/export.js'; +import { codeAt } from '../src/lib/totp.js'; + +let h: Harness; +before(async () => { h = await startHarness(); }); +after(async () => { await h.close(); }); +beforeEach(() => { h.received.length = 0; for (const k of Object.keys(h.productReplies)) delete h.productReplies[k]; }); + +const isCallback = (u: URL) => u.pathname === OIDC_CLIENT_PATHS.callback; + +/** Signs into Accounts' own pages (the account page). */ +async function accountPage(email: string, password: string) { + const browser = new Browser(); + const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/account`, (u) => u.pathname === '/signin'); + const uid = url.searchParams.get('uid')!; + const step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password }); + return { browser, uid, step }; +} + +describe('signing out everywhere', () => { + test('ends the session and tells each product it signed in to (back-channel logout)', async () => { + const a = await h.makeAccount({ email: 'out@hope.test', password: 'Correct-horse-1' }); + const browser = new Browser(); + await h.signIn(browser, 'out@hope.test', 'Correct-horse-1'); + const res = await h.api(browser, 'POST', '/api/v2/me/sign-out-everywhere'); + assert.equal(res.status, 200, JSON.stringify(res.body)); + const logout = h.received.find((r) => r.path === OIDC_CLIENT_PATHS.backchannelLogout); + assert.ok(logout, 'the product was told'); + const token = new URLSearchParams(logout.body).get('logout_token')!; + const payload = JSON.parse(Buffer.from(token.split('.')[1]!, 'base64url').toString()); + assert.equal(payload.sub, a.id); + assert.ok(payload.events['http://schemas.openid.net/event/backchannel-logout']); + // Signed out: the account page asks to sign in again. + assert.equal((await h.api(browser, 'GET', '/api/v2/me')).status, 401); + }); +}); + +describe('back-channel calls', () => { + test('a profile change reaches the product as user.updated, signed with the link\'s secret', async () => { + await h.makeAccount({ email: 'thandi2@hope.test', password: 'Correct-horse-2' }); + const page = await accountPage('thandi2@hope.test', 'Correct-horse-2'); + assert.equal(page.step.body.stage, 'done', JSON.stringify(page.step.body)); + await page.browser.follow(page.step.body.redirectTo as string, (u) => u.pathname === '/account'); + const put = await h.api(page.browser, 'PUT', '/api/v2/me', { name: 'Thandi Mokoena', phone: '082 123 4567' }); + assert.equal(put.status, 200, JSON.stringify(put.body)); + assert.equal(put.body.phone, '+27821234567'); + await runDue(h.ctx); + const call = h.received.find((r) => r.path === '/api/accounts/v1/events'); + assert.ok(call); + assert.ok(h.signedByLink(call), 'signed with the link secret'); + const body = JSON.parse(call.body); + assert.equal(body.type, 'user.updated'); + assert.equal(body.profile.name, 'Thandi Mokoena'); + }); + + test('a product that can\'t be reached is tried again later, not lost', async () => { + const { queueCall } = await import('../src/links/deliveries.js'); + const link = (await h.db.productLink.findUnique({ where: { installId: PRODUCT_ID } }))!; + await h.db.productLink.update({ where: { installId: PRODUCT_ID }, data: { url: 'http://127.0.0.1:9' } }); + const [d] = await queueCall(h.ctx, 'church.changed', () => ({ schema: 'crosscode.church/1', type: 'church.changed' })); + await runDue(h.ctx); + const after1 = (await h.db.delivery.findUnique({ where: { id: d!.id } }))!; + assert.equal(after1.status, 'pending'); + assert.equal(after1.attempts, 1); + assert.ok((after1.nextAttemptAt as Date) > new Date()); + await h.db.productLink.update({ where: { installId: PRODUCT_ID }, data: { url: link.url } }); + }); +}); + +describe('deleting an account', () => { + test('deactivated at once; after approval each product is asked, "not yet" is asked again, then anonymised', async () => { + const a = await h.makeAccount({ email: 'leaving@hope.test', password: 'Correct-horse-3' }); + const page = await accountPage('leaving@hope.test', 'Correct-horse-3'); + await page.browser.follow(page.step.body.redirectTo as string, (u) => u.pathname === '/account'); + const del = await h.api(page.browser, 'POST', '/api/v2/me/delete', { password: 'Correct-horse-3' }); + assert.equal(del.status, 200, JSON.stringify(del.body)); + assert.equal((await h.db.account.findUnique({ where: { id: a.id } }))!.status, 'deactivated'); + + const req = (await h.db.deletionRequest.findFirst({ where: { accountId: a.id } }))!; + let answer: unknown = { schema: IDENTITY_SCHEMA, status: 'deferred', reason: 'Has a registration for Youth Camp (14 March)', retryAfter: new Date(Date.now() - 1000).toISOString() }; + h.productReplies['user.deleted'] = () => answer; + await approveDeletion(h.ctx, req.id as string, { id: 'admin', role: 'admin' }); + await runDue(h.ctx); + let state = (await h.db.deletionRequest.findUnique({ where: { id: req.id } }))!; + assert.equal(state.status, 'approved'); + assert.equal((state.products as Record)[PRODUCT_ID]!.status, 'deferred'); + + answer = { schema: IDENTITY_SCHEMA, status: 'deleted' }; + await runDeletionJob(h.ctx); + await runDue(h.ctx); + state = (await h.db.deletionRequest.findUnique({ where: { id: req.id } }))!; + assert.equal(state.status, 'done'); + const gone = (await h.db.account.findUnique({ where: { id: a.id } }))!; + assert.equal(gone.status, 'deleted'); + assert.equal(gone.email, `deleted-${a.id}@deleted.invalid`); + assert.equal(gone.passwordHash, null); + }); +}); + +describe('download my data', () => { + test('bundles Accounts\' part and the product\'s', async () => { + const a = await h.makeAccount({ email: 'mydata@hope.test', password: 'Correct-horse-4' }); + h.productReplies['user.export'] = (body) => ({ + schema: IDENTITY_SCHEMA, exportId: body.exportId, sub: a.id, product: 'website', generatedAt: new Date().toISOString(), + sections: [{ key: 'pages', title: 'Pages you edited', records: [{ title: 'Home' }] }], + }); + const page = await accountPage('mydata@hope.test', 'Correct-horse-4'); + await page.browser.follow(page.step.body.redirectTo as string, (u) => u.pathname === '/account'); + const made = await h.api(page.browser, 'POST', '/api/v2/me/exports'); + assert.equal(made.status, 200); + await runDue(h.ctx); + await finishIfComplete(h.ctx, made.body.id as string); + const list = await h.api(page.browser, 'GET', '/api/v2/me/exports'); + assert.equal((list.body.items as { status: string }[])[0]!.status, 'ready'); + const dl = await page.browser.request(`${h.publicUrl}/api/v2/me/exports/${made.body.id}/download`); + const file = await dl.json() as { parts: { product: string }[] }; + assert.deepEqual(file.parts.map((p) => p.product).sort(), ['accounts', 'website']); + assert.ok(h.messenger.emails.some((e) => e.to === 'mydata@hope.test' && /ready/.test(e.subject))); + // Someone else can't download it. + assert.equal((await new Browser().request(`${h.publicUrl}/api/v2/me/exports/${made.body.id}/download`)).status, 401); + }); +}); + +describe('the church profile', () => { + test('is served as crosscode.church/1 with the product links', async () => { + const res = await fetch(`${h.publicUrl}/api/church/v1`); + const body = (await res.json()) as { name: string; links: Record }; + assert.equal(churchSchema.safeParse(body).success, true, JSON.stringify(body)); + assert.equal(body.name, 'Hope Family Church'); + assert.equal(body.links.website, h.productUrl); + assert.equal(body.links.accounts, h.publicUrl); + }); +}); + +describe('Connect from a product', () => { + test('a product the Hub listed connects and becomes a client; an unlisted one can\'t', async () => { + const appKey = generateEd25519(); + const APP_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e04'; + await h.ctx.settings.set('hub_linked_products', JSON.stringify([{ product: 'app', installId: APP_ID, url: 'http://127.0.0.1:7', publicKey: ed25519PublicToPem(appKey.publicKey) }])); + const msg = (key = appKey) => signLink({ schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'app', installId: APP_ID, url: 'http://127.0.0.1:7' }, to: { installId: ACCOUNTS_ID }, secret: newLinkSecret(), issuedAt: new Date().toISOString(), nonce: newLinkNonce() }, key.privateKeyPem); + const bad = await fetch(`${h.publicUrl}/api/links/v1/connect`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(msg(generateEd25519())) }); + assert.equal(bad.status, 401); + const ok = await fetch(`${h.publicUrl}/api/links/v1/connect`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(msg()) }); + assert.equal(ok.status, 200); + assert.equal(((await ok.json()) as { type: string }).type, 'link.connected'); + const client = await h.provider.Client.find(APP_ID); + assert.deepEqual(client?.redirectUris, ['http://127.0.0.1:7/api/auth/callback']); + }); +}); + +describe('admin and setup', () => { + test('admin needs the admin role and a 2FA sign-in', async () => { + await h.makeAccount({ email: 'member@hope.test', password: 'Correct-horse-5' }); + const member = await accountPage('member@hope.test', 'Correct-horse-5'); + await member.browser.follow(member.step.body.redirectTo as string, (u) => u.pathname === '/account'); + assert.equal((await h.api(member.browser, 'GET', '/api/v2/admin/people')).status, 403); + + await h.makeAccount({ email: 'admin@hope.test', password: 'Correct-horse-6', role: 'admin' }); + const admin = await accountPage('admin@hope.test', 'Correct-horse-6'); + assert.equal(admin.step.body.stage, 'setup_two_factor', 'admins must have 2FA'); + const setup = await h.api(admin.browser, 'POST', `/api/v2/interaction/${admin.uid}/two-factor/setup`, { method: 'totp' }); + const done = await h.api(admin.browser, 'POST', `/api/v2/interaction/${admin.uid}/two-factor/setup/confirm`, { method: 'totp', code: codeAt(String(setup.body.secret), Math.floor(Date.now() / 30000)) }); + await admin.browser.follow(done.body.redirectTo as string, (u) => u.pathname === '/admin' || u.pathname === '/account'); + const people = await h.api(admin.browser, 'GET', '/api/v2/admin/people?q=member'); + assert.equal(people.status, 200, JSON.stringify(people.body)); + assert.deepEqual((people.body.items as { email: string }[]).map((p) => p.email), ['member@hope.test']); + // Viewing a person is access-logged. + const id = (people.body.items as { id: string }[])[0]!.id; + await h.api(admin.browser, 'GET', `/api/v2/admin/people/${id}`); + assert.equal(await h.db.accessLog.count({ where: { targetId: id } }), 1); + }); + + test('changes only from the site itself', async () => { + const res = await new Browser().request(`${h.publicUrl}/api/v2/password/forgot`, { body: { email: 'x@hope.test' }, origin: 'https://evil.example' }); + assert.equal(res.status, 403); + }); + + test('setup only while there\'s no admin', async () => { + const res = await h.api(new Browser(), 'POST', '/api/v2/setup', { churchName: 'Other', name: 'Someone', email: 'someone@hope.test', password: 'Correct-horse-7' }); + assert.equal(res.status, 409); + }); +}); + +describe('the sign-out page', () => { + test('signing out from a product ends at that product\'s address', async () => { + const browser = new Browser(); + const r = await h.signIn(browser, 'member@hope.test', 'Correct-horse-5'); + assert.ok('tokens' in r); + const end = new URL(`${h.publicUrl}/api/oidc/session/end`); + end.search = new URLSearchParams({ id_token_hint: r.tokens.id_token!, post_logout_redirect_uri: `${h.productUrl}/` }).toString(); + const page = await browser.request(end.toString()); + const html = await page.text(); + assert.match(html, /logout\.js/); + const xsrf = /name="xsrf" value="([^"]+)"/.exec(html)![1]!; + const confirm = await browser.request(`${h.publicUrl}/api/oidc/session/end/confirm`, { form: { xsrf, logout: 'yes' } }); + const loc = confirm.headers.get('location') ?? ''; + assert.equal(loc, `${h.productUrl}/`); + void isCallback; + }); +}); diff --git a/apps/accounts/backend/tests/signin.test.ts b/apps/accounts/backend/tests/signin.test.ts index 997429d..cc335b5 100644 --- a/apps/accounts/backend/tests/signin.test.ts +++ b/apps/accounts/backend/tests/signin.test.ts @@ -97,7 +97,7 @@ describe('two-factor', () => { test('someone with 2FA by email enters the emailed code; a recovery code works instead', async () => { const a = await h.makeAccount({ email: 'lerato@hope.test', password: 'Correct-horse-3', twoFactorMethod: 'email' }); const { replaceRecoveryCodes } = await import('../src/accounts/twoFactor.js'); - const codes = await replaceRecoveryCodes(h.ctx, a.id); + const codes = await replaceRecoveryCodes(h.ctx, a.id as string); const browser = new Browser(); const r = await h.signIn(browser, 'lerato@hope.test', 'Correct-horse-3');