diff --git a/server/tests/e2e/session-revocation.e2e.test.ts b/server/tests/e2e/session-revocation.e2e.test.ts new file mode 100644 index 000000000..fb4a0be48 --- /dev/null +++ b/server/tests/e2e/session-revocation.e2e.test.ts @@ -0,0 +1,130 @@ +/** + * Session revocation e2e: the admin actions that sign another account out. + * + * sessions.e2e.test.ts covers what a user does to their own sessions on the + * auth routes alone. An admin setting a password, clearing two-factor or + * deleting an account goes through AdminModule, which pulls in most of the + * app, so this suite boots the whole thing with `buildApp()` against the + * migrated snapshot, every global guard included. The member signs in twice + * for real (two tracked sessions), the admin acts, and both of the member's + * cookies must stop working while the admin's own session carries on. + */ +import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest'; +import request from 'supertest'; +import type { Application } from 'express'; +import type { INestApplication } from '@nestjs/common'; +import jwt from 'jsonwebtoken'; + +vi.mock('../../src/db/database', async () => { + const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock'); + return buildDbMock(createSnapshotTestDb()); +}); +vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() })); + +import { db as testDb } from '../../src/db/database'; +import { buildApp } from '../../src/bootstrap'; +import { resetRateLimits } from '../helpers/test-db'; +import { createAdmin, createUser } from '../helpers/factories'; +import { sessionRows } from '../helpers/sessions'; + +let nestApp: INestApplication; +let app: Application; + +beforeAll(async () => { + nestApp = await buildApp(); + app = nestApp.getHttpAdapter().getInstance(); +}); + +beforeEach(() => { + resetRateLimits(nestApp); +}); + +afterAll(async () => { + await nestApp.close(); +}); + +/** Sign in from a device; returns the `trek_session=…` cookie pair. */ +async function signIn(email: string, password: string, device: string): Promise { + const res = await request(app).post('/api/auth/login').set('User-Agent', device).send({ email, password }); + expect(res.status).toBe(200); + const cookie = (res.headers['set-cookie'] as unknown as string[]).find((c) => c.startsWith('trek_session='))!; + return /^(trek_session=[^;]+)/.exec(cookie)![1]; +} + +const sessionIdOf = (cookie: string) => (jwt.decode(cookie.slice('trek_session='.length)) as { jti: string }).jti; +const me = (cookie: string) => request(app).get('/api/auth/me').set('Cookie', cookie); +const liveRows = (userId: number) => sessionRows(testDb as never, userId).filter((row) => row.revoked_at === null); + +/** An admin and a member, each signed in; the member on two devices. */ +async function signedInPair(name: string) { + const admin = createAdmin(testDb as never, { username: `${name}-admin`, email: `${name}-admin@example.test` }); + const member = createUser(testDb as never, { username: `${name}-member`, email: `${name}-member@example.test` }); + return { + adminCookie: await signIn(admin.user.email, admin.password, 'Admin browser'), + member: member.user, + laptop: await signIn(member.user.email, member.password, 'Laptop'), + phone: await signIn(member.user.email, member.password, 'Phone'), + }; +} + +describe('Admin actions that end another account\'s sessions', () => { + it('SESS-E2E-ADMIN-001: setting a new password for a member ends every session of that member', async () => { + const { adminCookie, member, laptop, phone } = await signedInPair('sess-admin-pw'); + expect((await me(laptop)).status).toBe(200); + + const res = await request(app) + .put(`/api/admin/users/${member.id}`) + .set('Cookie', adminCookie) + .send({ password: 'Admin1234!x' }); + expect(res.status).toBe(200); + + expect((await me(laptop)).status).toBe(401); + expect((await me(phone)).status).toBe(401); + expect(sessionRows(testDb as never, member.id).map((row) => row.id).sort()).toEqual([sessionIdOf(laptop), sessionIdOf(phone)].sort()); + expect(liveRows(member.id)).toEqual([]); + expect((await me(adminCookie)).status).toBe(200); + }, 30000); + + it('SESS-E2E-ADMIN-002: clearing a member\'s two-factor ends every session of that member', async () => { + const { adminCookie, member, laptop, phone } = await signedInPair('sess-admin-mfa'); + testDb.prepare("UPDATE users SET mfa_enabled = 1, mfa_secret = 'x' WHERE id = ?").run(member.id); + + const res = await request(app).delete(`/api/admin/users/${member.id}/mfa`).set('Cookie', adminCookie); + expect(res.status).toBe(200); + expect(res.body).toEqual({ success: true }); + + expect((await me(laptop)).status).toBe(401); + expect((await me(phone)).status).toBe(401); + expect(liveRows(member.id)).toEqual([]); + expect(testDb.prepare('SELECT mfa_enabled FROM users WHERE id = ?').get(member.id)).toEqual({ mfa_enabled: 0 }); + expect((await me(adminCookie)).status).toBe(200); + }, 30000); + + it('SESS-E2E-ADMIN-003: deleting a member takes the member\'s session rows with the account', async () => { + const { adminCookie, member, laptop, phone } = await signedInPair('sess-admin-delete'); + expect(sessionRows(testDb as never, member.id)).toHaveLength(2); + + const res = await request(app).delete(`/api/admin/users/${member.id}`).set('Cookie', adminCookie); + expect(res.status).toBe(200); + expect(res.body).toEqual({ success: true }); + + expect(sessionRows(testDb as never, member.id)).toEqual([]); + expect((await me(laptop)).status).toBe(401); + expect((await me(phone)).status).toBe(401); + expect((await me(adminCookie)).status).toBe(200); + }, 30000); + + it('SESS-E2E-ADMIN-004: an admin edit that leaves the password alone signs nobody out', async () => { + const { adminCookie, member, laptop, phone } = await signedInPair('sess-admin-rename'); + + const res = await request(app) + .put(`/api/admin/users/${member.id}`) + .set('Cookie', adminCookie) + .send({ username: 'sess-admin-renamed' }); + expect(res.status).toBe(200); + + expect((await me(laptop)).status).toBe(200); + expect((await me(phone)).status).toBe(200); + expect(liveRows(member.id)).toHaveLength(2); + }, 30000); +}); diff --git a/server/tests/e2e/sessions.e2e.test.ts b/server/tests/e2e/sessions.e2e.test.ts index 7c2ff902c..20cdcd56e 100644 --- a/server/tests/e2e/sessions.e2e.test.ts +++ b/server/tests/e2e/sessions.e2e.test.ts @@ -5,8 +5,11 @@ * with the real JwtAuthGuard, the real cookie service and the real * renewal interceptor, then drives the flows a browser would: sign in on two * devices, list the sessions, end one, end the others, log out, change the - * password. A token from before sessions were tracked (the harness's - * `sessionCookie`, which carries no `jti`) must keep working throughout. + * password, reset it by email, turn two-factor off, delete the account, and + * run the nightly purge against the real table. A token from before sessions + * were tracked (the harness's `sessionCookie`, which carries no `jti`) must + * keep working throughout. The admin paths that end sessions boot the whole + * app and live in session-revocation.e2e.test.ts. */ import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest'; import request from 'supertest'; @@ -14,6 +17,8 @@ import cookieParser from 'cookie-parser'; import type { Server } from 'http'; import { Test } from '@nestjs/testing'; import jwt from 'jsonwebtoken'; +import { authenticator } from 'otplib'; +import { MikroORM } from '@mikro-orm/core'; import { sessionCookie } from './harness'; vi.mock('../../src/db/database', async () => { @@ -38,22 +43,30 @@ import { createUser } from '../helpers/factories'; import { resetRateLimits } from '../helpers/test-db'; import { AuthModule } from '../../src/nest/auth/auth.module'; import { SessionsService } from '../../src/nest/sessions/sessions.service'; +import { SessionPurgeJob } from '../../src/nest/sessions/session-purge.job'; +import { withRequestContext } from '../../src/nest/database/request-context'; +import { encryptMfaSecret } from '../../src/nest/common/crypto/mfaCrypto'; +import { sessionRows } from '../helpers/sessions'; import { SessionRenewalInterceptor } from '../../src/nest/auth/session-renewal.interceptor'; import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe'; import { TestUnitOfWorkModule } from '../helpers/test-uow'; import { createTestMikroOrmModule } from '../helpers/test-orm'; +/** The reset mail the forgot-password route sends; the link in it carries the token. */ +const sendPasswordResetEmail = vi.fn().mockResolvedValue({ delivered: 'email' }); + describe('Sessions e2e (sign-in sessions that can be ended)', () => { let server: Server; let app: Awaited>; + let moduleRef: Awaited['compile']>>; async function build() { - const moduleRef = await Test.createTestingModule({ + moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), AuthModule], }) .overrideProvider(MailerService) - .useValue({ sendPasswordResetEmail: vi.fn().mockResolvedValue({ delivered: 'email' }) }) + .useValue({ sendPasswordResetEmail }) .compile(); const nest = moduleRef.createNestApplication(); nest.use(cookieParser()); @@ -260,4 +273,84 @@ describe('Sessions e2e (sign-in sessions that can be ended)', () => { vi.unstubAllEnvs(); } }, 15000); + + /** The rows of the user's sessions that still let a token in. */ + const liveRows = (userId: number) => sessionRows(db as never, userId).filter((row) => row.revoked_at === null); + + it('a password reset by email ends every session of the account', async () => { + const { user, password } = freshUser('sess-reset'); + const laptop = await signIn(user.email, password, 'Laptop'); + const phone = await signIn(user.email, password, 'Phone'); + sendPasswordResetEmail.mockClear(); + + const forgot = await request(server).post('/api/auth/forgot-password').send({ email: user.email }); + expect(forgot.status).toBe(200); + expect(sendPasswordResetEmail).toHaveBeenCalledTimes(1); + const link = sendPasswordResetEmail.mock.calls[0][1] as string; + const resetToken = decodeURIComponent(/[?&]token=([^&]+)/.exec(link)![1]); + + const reset = await request(server).post('/api/auth/reset-password').send({ token: resetToken, new_password: 'Reset1234!x' }); + expect(reset.status).toBe(200); + expect(reset.body).toEqual({ success: true }); + + expect((await me(laptop)).status).toBe(401); + expect((await me(phone)).status).toBe(401); + expect(sessionRows(db as never, user.id).map((row) => row.id).sort()).toEqual([sessionIdOf(laptop), sessionIdOf(phone)].sort()); + expect(liveRows(user.id)).toEqual([]); + // The new password signs in again, as a new session. + const after = await signIn(user.email, 'Reset1234!x', 'Laptop'); + expect((await me(after)).status).toBe(200); + }, 20000); + + it('turning two-factor off ends every other session and keeps this one', async () => { + const { user, password } = freshUser('sess-mfa-off'); + const here = await signIn(user.email, password, 'Here'); + const there = await signIn(user.email, password, 'There'); + // Two-factor turned on after both sign-ins, as the factory does it. + const secret = 'JBSWY3DPEHPK3PXP'; + db.prepare('UPDATE users SET mfa_enabled = 1, mfa_secret = ? WHERE id = ?').run(encryptMfaSecret(secret), user.id); + + const off = await request(server) + .post('/api/auth/mfa/disable') + .set('Cookie', here) + .send({ password, code: authenticator.generate(secret) }); + expect(off.status).toBe(200); + expect(off.body).toEqual({ success: true, mfa_enabled: false }); + + expect((await me(there)).status).toBe(401); + expect((await me(here)).status).toBe(200); + expect(liveRows(user.id).map((row) => row.id)).toEqual([sessionIdOf(here)]); + }, 15000); + + it('deleting the account takes its sessions with it', async () => { + const { user, password } = freshUser('sess-delete'); + const here = await signIn(user.email, password, 'Here'); + const there = await signIn(user.email, password, 'There'); + expect(sessionRows(db as never, user.id)).toHaveLength(2); + + const res = await request(server).delete('/api/auth/me').set('Cookie', here); + expect(res.status).toBe(200); + + expect(sessionRows(db as never, user.id)).toEqual([]); + expect((await me(here)).status).toBe(401); + expect((await me(there)).status).toBe(401); + }, 15000); + + it('the nightly purge removes the ended and expired rows and leaves the live session working', async () => { + const { user, password } = freshUser('sess-purge'); + const live = await signIn(user.email, password, 'Live'); + const ended = await signIn(user.email, password, 'Ended'); + expect((await request(server).delete(`/api/auth/sessions/${sessionIdOf(ended)}`).set('Cookie', live)).status).toBe(200); + db.prepare( + "INSERT INTO user_sessions (id, user_id, created_at, last_seen_at, expires_at) VALUES ('0b7c6f3e-2a51-4c8e-9d43-5f1e2b7a9c10', ?, '2020-01-01 00:00:00', '2020-01-01 00:00:00', '2020-01-02 00:00:00')", + ).run(user.id); + expect(sessionRows(db as never, user.id)).toHaveLength(3); + + const job = moduleRef.get(SessionPurgeJob); + await withRequestContext(moduleRef.get(MikroORM), () => job.tick()); + + expect(sessionRows(db as never, user.id).map((row) => row.id)).toEqual([sessionIdOf(live)]); + expect((await me(live)).status).toBe(200); + expect((await me(ended)).status).toBe(401); + }, 15000); }); diff --git a/server/tests/unit/db/reset-admin-sessions.test.ts b/server/tests/unit/db/reset-admin-sessions.test.ts new file mode 100644 index 000000000..068a40dd8 --- /dev/null +++ b/server/tests/unit/db/reset-admin-sessions.test.ts @@ -0,0 +1,128 @@ +/** + * reset-admin.js and the session rows. + * + * The recovery script resets an account an operator is locked out of. Its + * password_version bump already refuses every token of that account; it also + * ends the account's rows in `user_sessions`, so the session list shows none + * of them as live. A database no server tracking sessions has booted yet has + * no such table, and the script must not trip over that. + * + * The script is plain JS run with `node`, so it is run here the way an + * operator runs it, against a throwaway file holding only the columns it + * touches. + */ +import { execFileSync } from 'child_process'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import Database from 'better-sqlite3'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +const SERVER_ROOT = path.resolve(__dirname, '../../..'); + +let tmpDir: string; +let dbPath: string; + +beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-reset-admin-')); + dbPath = path.join(tmpDir, 'travel.db'); +}); + +afterEach(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); +}); + +function seed(withSessions: boolean): void { + const db = new Database(dbPath); + db.exec(` + CREATE TABLE users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT UNIQUE, + email TEXT UNIQUE, + password_hash TEXT, + role TEXT, + must_change_password INTEGER DEFAULT 0, + password_version INTEGER NOT NULL DEFAULT 0 + ); + INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES + (1, 'boss', 'boss@example.com', 'x', 'admin', 2), + (2, 'member', 'member@example.com', 'x', 'user', 0); + `); + if (withSessions) { + db.exec(` + CREATE TABLE user_sessions ( + id TEXT PRIMARY KEY NOT NULL, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + last_seen_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + expires_at DATETIME NOT NULL, + revoked_at DATETIME, + user_agent TEXT + ); + INSERT INTO user_sessions (id, user_id, expires_at, revoked_at) VALUES + ('boss-laptop', 1, '2099-01-01 00:00:00', NULL), + ('boss-phone', 1, '2099-01-01 00:00:00', NULL), + ('boss-old', 1, '2099-01-01 00:00:00', '2020-01-01 00:00:00'), + ('member-laptop', 2, '2099-01-01 00:00:00', NULL); + `); + } + db.close(); +} + +function resetAdmin(email: string): void { + execFileSync(process.execPath, ['reset-admin.js'], { + cwd: SERVER_ROOT, + env: { ...process.env, TREK_DB_FILE: dbPath, RESET_ADMIN_EMAIL: email, RESET_ADMIN_PASSWORD: 'Recovery12345!' }, + stdio: 'pipe', + }); +} + +function read(sql: string): T[] { + const db = new Database(dbPath); + try { + return db.prepare(sql).all() as T[]; + } finally { + db.close(); + } +} + +describe('reset-admin.js and user_sessions', () => { + it('RESETADMIN-SESS-001: ends every live session of the account it resets, and nobody else\'s', () => { + seed(true); + + resetAdmin('Boss@Example.com'); + + const sessions = read<{ id: string; revoked_at: string | null }>('SELECT id, revoked_at FROM user_sessions ORDER BY id'); + const byId = Object.fromEntries(sessions.map((s) => [s.id, s.revoked_at])); + expect(byId['boss-laptop']).not.toBeNull(); + expect(byId['boss-phone']).not.toBeNull(); + // An already ended session keeps the time it ended. + expect(byId['boss-old']).toBe('2020-01-01 00:00:00'); + expect(byId['member-laptop']).toBeNull(); + expect(read('SELECT password_version, must_change_password FROM users WHERE id = 1')).toEqual([ + { password_version: 3, must_change_password: 1 }, + ]); + }, 60000); + + it('RESETADMIN-SESS-002: a database without the sessions table is reset all the same', () => { + seed(false); + + resetAdmin('boss@example.com'); + + expect(read("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'user_sessions'")).toEqual([]); + expect(read('SELECT role, password_version, must_change_password FROM users WHERE id = 1')).toEqual([ + { role: 'admin', password_version: 3, must_change_password: 1 }, + ]); + }, 60000); + + it('RESETADMIN-SESS-003: creating a new admin ends no existing session', () => { + seed(true); + + resetAdmin('new-admin@example.com'); + + expect(read('SELECT COUNT(*) AS n FROM user_sessions WHERE revoked_at IS NULL')).toEqual([{ n: 3 }]); + expect(read("SELECT role, must_change_password FROM users WHERE email = 'new-admin@example.com'")).toEqual([ + { role: 'admin', must_change_password: 1 }, + ]); + }, 60000); +});