Files
TREK/server/tests/integration/oidc.test.ts
T
Maurice 2d0414b4a3 security: internal audit — batch 1
Fixes the critical + high + medium findings from our internal security
review. Bundled into one PR because the changes overlap heavily (JWT
verification unifies across three call sites; backup-code hashing and
demo-email handling cross-cut several services); splitting them out
would mean redundant reviews of the same files.

Critical
- CI-C1 — .github/workflows/test.yml: restore actions/{checkout,setup-
  node,upload-artifact} to @v4. The @v6 refs don't exist, so the test
  workflow was errorring before a single test ran.
- SEC-C1 — mfaPolicy now extracts the token via extractToken() (cookie-
  first, Bearer fallback). Previously it only read Authorization, so
  every cookie-authenticated SPA session bypassed require_mfa entirely.
- SEC-C2/C4/C6 — all JWT verification paths (MCP bearer, file download,
  photo route) now go through the shared verifyJwtAndLoadUser that
  checks password_version. resetPassword additionally deletes every
  mcp_tokens row and marks outstanding oauth_tokens revoked, so a
  password reset invalidates ALL credential classes — not just the
  cookie JWT.

High
- SEC-H2 — reset email URL is built from server-side APP_URL /
  ALLOWED_ORIGINS (via existing getAppUrl()), not request headers.
  Closes the host-header-injection vector into reset links.
- SEC-H3 — OIDC findOrCreateUser wraps the invite-redemption UPDATE +
  user INSERT in a transaction. The UPDATE is the capacity check; if
  a concurrent callback takes the last slot, the whole transaction
  aborts with registration_disabled instead of double-creating users.
- SEC-H4 — new verifyIdToken() performs full JWT signature
  verification via the provider's JWKS (Node's crypto.createPublicKey
  accepts JWK directly — no extra dependency), plus iss/aud/exp
  checks. The callback also rejects the login when userinfo.sub does
  not match id_token.sub.
- SEC-H5 — OAuth DCR now validates redirect_uris against an allowlist
  of schemes: https, http-loopback, or a private custom scheme. Plain
  http://non-loopback is rejected.
- SEC-H6 — oauthService audience defaults to mcpResource when the
  `resource` parameter is missing, so tokens are always audience-bound
  to /mcp instead of being issued with audience=null.
- SEC-H7 — HSTS is enabled any time NODE_ENV=production (previously
  required FORCE_HTTPS=true), includeSubDomains defaults on and can
  be disabled with HSTS_INCLUDE_SUBDOMAINS=false.
- SEC-H8 — trek_session cookie Secure flag is also driven by
  req.secure (which Express resolves from X-Forwarded-Proto once
  trust proxy is set), so instances behind a TLS-terminating proxy
  get Secure cookies without needing FORCE_HTTPS.

Medium
- SEC-M1 — permanentDeleteFile / emptyTrash / avatar unlink now use
  fs.promises.rm with { force: true } (one async op vs the previous
  existsSync + unlinkSync pair per file).
- SEC-M2 — invalidatePermissionsCache() is called inside restoreFromZip
  so a restored DB with different permission rows is honoured
  immediately.
- SEC-M3 + C1 — idempotency store bounds the key at 128 chars, caches
  only responses ≤ 256 KiB, and scopes the lookup by (key, user_id,
  method, path) rather than (key, user_id). Same key replayed against
  a different endpoint no longer returns a stale unrelated body.
- SEC-M4 — share_tokens gets an expires_at column; new tokens default
  to 90-day TTL, expired tokens are denied at lookup. Existing tokens
  stay NULL = no expiry so already-published links don't break.
- SEC-M5 — /uploads/photos/:filename now resolves the photo to its
  trip_id and requires the share token to cover THAT trip. Previously
  any share token for any trip would unlock any photo filename.
- SEC-M6 — BLOCKED_EXTENSIONS is the single source of truth shared
  between fileService and collab uploads. The '*' allowed_file_types
  wildcard now still rejects executables/scripts.
- SEC-M7 — single DEMO_EMAILS constant (services/demo.ts) used by
  demoUploadBlock, mfaPolicy, and every demo-mode guard in
  authService. The old demoUploadBlock only matched 'demo@nomad.app'
  so the seed 'demo@trek.app' could in fact upload in demo mode.
- SEC-M8 — MFA backup codes are now bcrypt-hashed at rest
  (hashBackupCodeBcrypt). matchBackupCode accepts both bcrypt and
  legacy SHA-256 hex hashes, so existing installs keep working until
  the user regenerates codes via enableMfa.
- SEC-M9 — document the "security via UUID v4 filename" model for
  /uploads/avatars|covers|journey. Requires no code change but
  captures the decision so future reviewers don't re-flag it.
- SEC-M10 — already covered by the resetPassword revocation logic
  above: mcp_tokens DELETE + oauth_tokens UPDATE … SET revoked_at.

Performance
- PERF-H1 — new migration adds the indexes flagged in the audit:
  trips(user_id), trips(created_at DESC), photos(day_id),
  photos(place_id), reservations(day_id), share_tokens(token), plus
  conditional day_accommodations and notifications indexes depending
  on which columns are present.

Tests
- tests/integration/oidc.test.ts now mocks verifyIdToken and passes
  an id_token in the exchangeCodeForToken stub for the three flows
  that exercise a successful callback. The three remaining failures
  tests pointed out were all pre-existing (file-upload flakes +
  notificationPreferences event_types count drift), none introduced
  by this PR.
2026-04-20 20:36:52 +02:00

293 lines
12 KiB
TypeScript

/**
* OIDC integration tests — OIDC-001 through OIDC-010.
* Covers /api/auth/oidc/login, /callback, /exchange.
* HTTP calls (discover, exchangeCodeForToken, getUserInfo) are mocked.
* State management, auth codes, and findOrCreateUser run against the real test DB.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
import request from 'supertest';
import type { Application } from 'express';
// ── DB mock (inline vi.hoisted pattern) ──────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: any, userId: number) =>
db.prepare(`SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`).get(userId, tripId, userId),
isOwner: (tripId: any, userId: number) =>
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../src/db/database', () => dbMock);
vi.mock('../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
// ── Mock only the HTTP-calling functions from oidcService ────────────────────
vi.mock('../../src/services/oidcService', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/services/oidcService')>();
return {
...actual,
discover: vi.fn(),
exchangeCodeForToken: vi.fn(),
getUserInfo: vi.fn(),
// Bypass real JWKS fetch + signature verification in tests. Callers
// that exercise the security of verifyIdToken should unit-test the
// function directly instead; integration tests here focus on the
// callback flow, not the crypto.
verifyIdToken: vi.fn(),
};
});
import { createApp } from '../../src/app';
import { createTables } from '../../src/db/schema';
import { runMigrations } from '../../src/db/migrations';
import { resetTestDb } from '../helpers/test-db';
import { createUser } from '../helpers/factories';
import { loginAttempts, mfaAttempts } from '../../src/routes/auth';
import * as oidcService from '../../src/services/oidcService';
const mockDiscover = vi.mocked(oidcService.discover);
const mockExchangeCode = vi.mocked(oidcService.exchangeCodeForToken);
const mockGetUserInfo = vi.mocked(oidcService.getUserInfo);
const mockVerifyIdToken = vi.mocked(oidcService.verifyIdToken);
const MOCK_DISCOVERY_DOC = {
authorization_endpoint: 'https://oidc.example.com/auth',
token_endpoint: 'https://oidc.example.com/token',
userinfo_endpoint: 'https://oidc.example.com/userinfo',
};
const app: Application = createApp();
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
loginAttempts.clear();
mfaAttempts.clear();
vi.clearAllMocks();
// Set OIDC environment variables for each test
process.env.OIDC_ISSUER = 'https://oidc.example.com';
process.env.OIDC_CLIENT_ID = 'test-client-id';
process.env.OIDC_CLIENT_SECRET = 'test-client-secret';
process.env.APP_URL = 'http://localhost:3001';
});
afterEach(() => {
delete process.env.OIDC_ISSUER;
delete process.env.OIDC_CLIENT_ID;
delete process.env.OIDC_CLIENT_SECRET;
delete process.env.APP_URL;
});
afterAll(() => {
testDb.close();
});
// ── /login ───────────────────────────────────────────────────────────────────
describe('GET /api/auth/oidc/login', () => {
it('OIDC-001: redirects to OIDC authorization endpoint (302)', async () => {
mockDiscover.mockResolvedValueOnce(MOCK_DISCOVERY_DOC);
const res = await request(app).get('/api/auth/oidc/login');
expect(res.status).toBe(302);
expect(res.headers.location).toContain('https://oidc.example.com/auth');
expect(res.headers.location).toContain('client_id=test-client-id');
expect(res.headers.location).toContain('response_type=code');
expect(res.headers.location).toContain('redirect_uri=');
expect(res.headers.location).toContain('state=');
});
it('OIDC-002: returns 400 when OIDC is not configured', async () => {
delete process.env.OIDC_ISSUER;
delete process.env.OIDC_CLIENT_ID;
delete process.env.OIDC_CLIENT_SECRET;
const res = await request(app).get('/api/auth/oidc/login');
expect(res.status).toBe(400);
expect(res.body.error).toBeDefined();
});
it('OIDC-003: includes invite token in state when provided', async () => {
mockDiscover.mockResolvedValueOnce(MOCK_DISCOVERY_DOC);
const res = await request(app).get('/api/auth/oidc/login?invite=abc123');
expect(res.status).toBe(302);
// State is a hex token; the invite is embedded in pendingStates (internal)
// We just verify the redirect happened successfully
expect(res.headers.location).toContain('state=');
});
});
// ── /callback ────────────────────────────────────────────────────────────────
describe('GET /api/auth/oidc/callback', () => {
it('OIDC-004: valid code for existing user → redirects to frontend with oidc_code', async () => {
const { user } = createUser(testDb, { email: 'alice@example.com' });
mockDiscover.mockResolvedValueOnce(MOCK_DISCOVERY_DOC);
mockExchangeCode.mockResolvedValueOnce({
access_token: 'test-access-token',
id_token: 'fake.id.token',
_ok: true,
_status: 200,
});
mockVerifyIdToken.mockResolvedValueOnce({ ok: true, claims: { sub: 'sub-alice-123' } });
mockGetUserInfo.mockResolvedValueOnce({
sub: 'sub-alice-123',
email: 'alice@example.com',
name: 'Alice',
});
// Create a valid state token
const state = oidcService.createState('http://localhost:3001/api/auth/oidc/callback');
const res = await request(app).get(`/api/auth/oidc/callback?code=authcode123&state=${state}`);
expect(res.status).toBe(302);
expect(res.headers.location).toContain('/login?oidc_code=');
});
it('OIDC-005: new user gets created when registration is open', async () => {
mockDiscover.mockResolvedValueOnce(MOCK_DISCOVERY_DOC);
mockExchangeCode.mockResolvedValueOnce({ access_token: 'new-token', id_token: 'fake.id.token', _ok: true, _status: 200 });
mockVerifyIdToken.mockResolvedValueOnce({ ok: true, claims: { sub: 'sub-newuser-999' } });
mockGetUserInfo.mockResolvedValueOnce({
sub: 'sub-newuser-999',
email: 'newuser@example.com',
name: 'New User',
});
const state = oidcService.createState('http://localhost:3001/api/auth/oidc/callback');
const res = await request(app).get(`/api/auth/oidc/callback?code=code999&state=${state}`);
expect(res.status).toBe(302);
expect(res.headers.location).toContain('/login?oidc_code=');
// Verify user was created in DB
const newUser = testDb.prepare("SELECT * FROM users WHERE email = 'newuser@example.com'").get();
expect(newUser).toBeDefined();
});
it('OIDC-006: invalid state → redirects with invalid_state error', async () => {
const res = await request(app).get('/api/auth/oidc/callback?code=abc&state=invalid-state-xyz');
expect(res.status).toBe(302);
expect(res.headers.location).toContain('oidc_error=invalid_state');
});
it('OIDC-007: provider error param → redirects with error', async () => {
const res = await request(app).get('/api/auth/oidc/callback?error=access_denied');
expect(res.status).toBe(302);
expect(res.headers.location).toContain('oidc_error=access_denied');
});
it('OIDC-008: missing code or state → redirects with missing_params error', async () => {
const res = await request(app).get('/api/auth/oidc/callback');
expect(res.status).toBe(302);
expect(res.headers.location).toContain('oidc_error=missing_params');
});
it('OIDC-009: token exchange failure → redirects with token_failed error', async () => {
mockDiscover.mockResolvedValueOnce(MOCK_DISCOVERY_DOC);
mockExchangeCode.mockResolvedValueOnce({ _ok: false, _status: 400 });
const state = oidcService.createState('http://localhost:3001/api/auth/oidc/callback');
const res = await request(app).get(`/api/auth/oidc/callback?code=badcode&state=${state}`);
expect(res.status).toBe(302);
expect(res.headers.location).toContain('oidc_error=token_failed');
});
it('OIDC-010: registration disabled for new user → redirects with registration_disabled error', async () => {
// Need at least one existing user so isFirstUser=false
createUser(testDb, { email: 'existing@example.com' });
// Disable registration
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('allow_registration', 'false')").run();
mockDiscover.mockResolvedValueOnce(MOCK_DISCOVERY_DOC);
mockExchangeCode.mockResolvedValueOnce({ access_token: 'tok', id_token: 'fake.id.token', _ok: true, _status: 200 });
mockVerifyIdToken.mockResolvedValueOnce({ ok: true, claims: { sub: 'sub-blocked-user' } });
mockGetUserInfo.mockResolvedValueOnce({
sub: 'sub-blocked-user',
email: 'blocked@example.com',
name: 'Blocked',
});
const state = oidcService.createState('http://localhost:3001/api/auth/oidc/callback');
const res = await request(app).get(`/api/auth/oidc/callback?code=anycode&state=${state}`);
expect(res.status).toBe(302);
expect(res.headers.location).toContain('oidc_error=registration_disabled');
});
});
// ── /exchange ─────────────────────────────────────────────────────────────────
describe('GET /api/auth/oidc/exchange', () => {
it('OIDC-011: valid auth code returns JWT and sets cookie', async () => {
const fakeToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.test.sig';
const code = oidcService.createAuthCode(fakeToken);
const res = await request(app).get(`/api/auth/oidc/exchange?code=${code}`);
expect(res.status).toBe(200);
expect(res.body.token).toBe(fakeToken);
expect(res.headers['set-cookie']).toBeDefined();
const cookieHeader = Array.isArray(res.headers['set-cookie'])
? res.headers['set-cookie'].join(';')
: res.headers['set-cookie'];
expect(cookieHeader).toContain('trek_session');
});
it('OIDC-012: missing code returns 400', async () => {
const res = await request(app).get('/api/auth/oidc/exchange');
expect(res.status).toBe(400);
expect(res.body.error).toBeDefined();
});
it('OIDC-013: invalid/expired code returns 400', async () => {
const res = await request(app).get('/api/auth/oidc/exchange?code=not-a-real-code');
expect(res.status).toBe(400);
expect(res.body.error).toBeDefined();
});
it('OIDC-014: auth code is single-use (second use returns 400)', async () => {
const fakeToken = 'test.token.here';
const code = oidcService.createAuthCode(fakeToken);
// First use: success
const res1 = await request(app).get(`/api/auth/oidc/exchange?code=${code}`);
expect(res1.status).toBe(200);
// Second use: rejected
const res2 = await request(app).get(`/api/auth/oidc/exchange?code=${code}`);
expect(res2.status).toBe(400);
});
});