mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 08:30:05 +00:00
@@ -1,184 +0,0 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
vi.mock('../../../src/db/database', () => ({
|
||||
db: { prepare: vi.fn(() => ({ get: vi.fn(), all: vi.fn() })) },
|
||||
}));
|
||||
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret' }));
|
||||
|
||||
import { extractToken, authenticate, adminOnly } from '../../../src/middleware/auth';
|
||||
import { db } from '../../../src/db/database';
|
||||
import type { Request, Response, NextFunction } from 'express';
|
||||
|
||||
function makeReq(overrides: {
|
||||
cookies?: Record<string, string>;
|
||||
headers?: Record<string, string>;
|
||||
} = {}): Request {
|
||||
return {
|
||||
cookies: overrides.cookies || {},
|
||||
headers: overrides.headers || {},
|
||||
} as unknown as Request;
|
||||
}
|
||||
|
||||
function makeRes(): { res: Response; status: ReturnType<typeof vi.fn>; json: ReturnType<typeof vi.fn> } {
|
||||
const json = vi.fn();
|
||||
const status = vi.fn(() => ({ json }));
|
||||
const res = { status } as unknown as Response;
|
||||
return { res, status, json };
|
||||
}
|
||||
|
||||
// ── extractToken ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe('extractToken', () => {
|
||||
it('returns cookie value when trek_session cookie is set', () => {
|
||||
const req = makeReq({ cookies: { trek_session: 'cookie-token' } });
|
||||
expect(extractToken(req)).toBe('cookie-token');
|
||||
});
|
||||
|
||||
it('returns Bearer token from Authorization header when no cookie', () => {
|
||||
const req = makeReq({ headers: { authorization: 'Bearer header-token' } });
|
||||
expect(extractToken(req)).toBe('header-token');
|
||||
});
|
||||
|
||||
it('prefers cookie over Authorization header when both are present', () => {
|
||||
const req = makeReq({
|
||||
cookies: { trek_session: 'cookie-token' },
|
||||
headers: { authorization: 'Bearer header-token' },
|
||||
});
|
||||
expect(extractToken(req)).toBe('cookie-token');
|
||||
});
|
||||
|
||||
it('returns null when neither cookie nor header are present', () => {
|
||||
expect(extractToken(makeReq())).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for Authorization header without a token (empty Bearer)', () => {
|
||||
const req = makeReq({ headers: { authorization: 'Bearer ' } });
|
||||
expect(extractToken(req)).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for Authorization header without Bearer prefix', () => {
|
||||
const req = makeReq({ headers: { authorization: 'Basic sometoken' } });
|
||||
// split(' ')[1] returns 'sometoken' — this IS returned (not a null case)
|
||||
// The function simply splits on space and takes index 1
|
||||
expect(extractToken(req)).toBe('sometoken');
|
||||
});
|
||||
});
|
||||
|
||||
// ── authenticate ─────────────────────────────────────────────────────────────
|
||||
|
||||
describe('authenticate', () => {
|
||||
it('returns 401 when no token is present', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status, json } = makeRes();
|
||||
authenticate(makeReq(), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(401);
|
||||
expect(json).toHaveBeenCalledWith(expect.objectContaining({ code: 'AUTH_REQUIRED' }));
|
||||
});
|
||||
|
||||
it('returns 401 when JWT is invalid', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status } = makeRes();
|
||||
authenticate(makeReq({ cookies: { trek_session: 'invalid.jwt.token' } }), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(401);
|
||||
});
|
||||
|
||||
it('AUTH-MW-003: calls next() and sets req.user for a valid JWT', () => {
|
||||
const mockUser = { id: 1, username: 'alice', email: 'alice@example.com', role: 'user' };
|
||||
vi.mocked(db.prepare).mockReturnValue({ get: vi.fn(() => mockUser), all: vi.fn() } as any);
|
||||
|
||||
const token = jwt.sign({ id: 1 }, 'test-secret', { algorithm: 'HS256' });
|
||||
const req = makeReq({ cookies: { trek_session: token } });
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
|
||||
authenticate(req, res, next);
|
||||
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
expect((req as any).user).toEqual(mockUser);
|
||||
});
|
||||
|
||||
it('AUTH-MW-004: returns 401 for a valid JWT when user does not exist in DB', () => {
|
||||
vi.mocked(db.prepare).mockReturnValue({ get: vi.fn(() => undefined), all: vi.fn() } as any);
|
||||
|
||||
const token = jwt.sign({ id: 99999 }, 'test-secret', { algorithm: 'HS256' });
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status } = makeRes();
|
||||
|
||||
authenticate(makeReq({ cookies: { trek_session: token } }), res, next);
|
||||
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(401);
|
||||
});
|
||||
|
||||
it('AUTH-MW-005: returns 401 for an expired JWT', () => {
|
||||
const expiredToken = jwt.sign(
|
||||
{ id: 1, exp: Math.floor(Date.now() / 1000) - 3600 },
|
||||
'test-secret',
|
||||
{ algorithm: 'HS256' }
|
||||
);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status } = makeRes();
|
||||
authenticate(makeReq({ cookies: { trek_session: expiredToken } }), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(401);
|
||||
});
|
||||
|
||||
it('AUTH-MW-006: returns 401 for a JWT signed with the wrong secret', () => {
|
||||
const tamperedToken = jwt.sign({ id: 1 }, 'wrong-secret', { algorithm: 'HS256' });
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status } = makeRes();
|
||||
authenticate(makeReq({ cookies: { trek_session: tamperedToken } }), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(401);
|
||||
});
|
||||
|
||||
it('AUTH-MW-007: rejects a purpose-scoped mfa_login token even when the user is valid', () => {
|
||||
// The token issued after the password check but before TOTP is signed with
|
||||
// the same secret. It must never authenticate a normal request, otherwise
|
||||
// password alone grants full access and MFA is bypassed.
|
||||
const mockUser = { id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 0 };
|
||||
vi.mocked(db.prepare).mockReturnValue({ get: vi.fn(() => mockUser), all: vi.fn() } as any);
|
||||
|
||||
const mfaToken = jwt.sign({ id: 1, purpose: 'mfa_login', pv: 0 }, 'test-secret', { algorithm: 'HS256' });
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status } = makeRes();
|
||||
|
||||
authenticate(makeReq({ headers: { authorization: `Bearer ${mfaToken}` } }), res, next);
|
||||
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ── adminOnly ─────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('adminOnly', () => {
|
||||
it('returns 403 when user role is not admin', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status, json } = makeRes();
|
||||
const req = { ...makeReq(), user: { id: 1, role: 'user' } } as unknown as Request;
|
||||
adminOnly(req, res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(403);
|
||||
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringContaining('Admin') }));
|
||||
});
|
||||
|
||||
it('calls next() when user role is admin', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
const req = { ...makeReq(), user: { id: 1, role: 'admin' } } as unknown as Request;
|
||||
adminOnly(req, res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 403 when req.user is undefined', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status } = makeRes();
|
||||
adminOnly(makeReq() as unknown as Request, res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(403);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import express from 'express';
|
||||
import request from 'supertest';
|
||||
import { applyGlobalMiddleware } from '../../../src/middleware/globalMiddleware';
|
||||
|
||||
async function directiveSources(name: string): Promise<string[]> {
|
||||
const app = express();
|
||||
applyGlobalMiddleware(app);
|
||||
app.get('/probe', (_req, res) => res.json({ ok: true }));
|
||||
|
||||
const res = await request(app).get('/probe');
|
||||
const csp = String(res.headers['content-security-policy'] || '');
|
||||
const directive = csp
|
||||
.split(';')
|
||||
.map(d => d.trim())
|
||||
.find(d => d.startsWith(name));
|
||||
|
||||
return directive ? directive.split(/\s+/).slice(1) : [];
|
||||
}
|
||||
|
||||
const connectSrcSources = () => directiveSources('connect-src');
|
||||
|
||||
describe('global CSP: OpenStreetMap tile hosts (#1733)', () => {
|
||||
it('allows the bare tile.openstreetmap.org host', async () => {
|
||||
// A CSP wildcard host never matches the apex, so `*.tile.openstreetmap.org`
|
||||
// alone would block the tile prefetcher's fetch() against the single host
|
||||
// OSM has served from since it retired a/b/c/d sharding.
|
||||
expect(await connectSrcSources()).toContain('https://tile.openstreetmap.org');
|
||||
});
|
||||
|
||||
it('still allows the sharded hosts for templates saved earlier', async () => {
|
||||
expect(await connectSrcSources()).toContain('https://*.tile.openstreetmap.org');
|
||||
});
|
||||
});
|
||||
|
||||
describe('global CSP: script-src', () => {
|
||||
it("allows 'wasm-unsafe-eval' so the WASM decoders keep running", async () => {
|
||||
expect(await directiveSources('script-src')).toContain("'wasm-unsafe-eval'");
|
||||
});
|
||||
|
||||
it("still allows 'unsafe-eval', which heic-to needs to decode an iPhone photo", async () => {
|
||||
// Pinned so the next tidy-up of this list finds the reason before the
|
||||
// consequence: libheif initialises embind with new Function(), and without
|
||||
// this every .heic upload fails in the browser. See the comment on the
|
||||
// directive for how to actually get rid of it.
|
||||
expect(await directiveSources('script-src')).toContain("'unsafe-eval'");
|
||||
});
|
||||
});
|
||||
|
||||
describe('forced-HTTPS redirect', () => {
|
||||
const saved = { FORCE_HTTPS: process.env.FORCE_HTTPS, APP_URL: process.env.APP_URL };
|
||||
|
||||
afterEach(() => {
|
||||
process.env.FORCE_HTTPS = saved.FORCE_HTTPS;
|
||||
process.env.APP_URL = saved.APP_URL;
|
||||
if (saved.FORCE_HTTPS === undefined) delete process.env.FORCE_HTTPS;
|
||||
if (saved.APP_URL === undefined) delete process.env.APP_URL;
|
||||
});
|
||||
|
||||
async function redirectLocation(): Promise<string> {
|
||||
const app = express();
|
||||
applyGlobalMiddleware(app);
|
||||
app.get('/trips', (_req, res) => res.json({ ok: true }));
|
||||
const res = await request(app).get('/trips').set('Host', 'evil.example.com');
|
||||
return String(res.headers.location || '');
|
||||
}
|
||||
|
||||
it('redirects to the configured APP_URL host, not the Host header the caller sent', async () => {
|
||||
process.env.FORCE_HTTPS = 'true';
|
||||
process.env.APP_URL = 'https://trip.pakulat.org';
|
||||
expect(await redirectLocation()).toBe('https://trip.pakulat.org/trips');
|
||||
});
|
||||
|
||||
it('falls back to the request host when APP_URL is unset', async () => {
|
||||
process.env.FORCE_HTTPS = 'true';
|
||||
delete process.env.APP_URL;
|
||||
expect(await redirectLocation()).toBe('https://evil.example.com/trips');
|
||||
});
|
||||
|
||||
it('falls back to the request host when APP_URL is not a URL', async () => {
|
||||
// A typo in the env should not take the instance down, and it should not
|
||||
// produce a redirect to a host built from a half-parsed string either.
|
||||
process.env.FORCE_HTTPS = 'true';
|
||||
process.env.APP_URL = 'not a url';
|
||||
expect(await redirectLocation()).toBe('https://evil.example.com/trips');
|
||||
});
|
||||
|
||||
it('leaves an already-secure request alone, and never redirects the health probe', async () => {
|
||||
process.env.FORCE_HTTPS = 'true';
|
||||
process.env.APP_URL = 'https://trip.pakulat.org';
|
||||
const app = express();
|
||||
applyGlobalMiddleware(app);
|
||||
app.get('/trips', (_req, res) => res.json({ ok: true }));
|
||||
app.get('/api/health', (_req, res) => res.json({ ok: true }));
|
||||
|
||||
// The proxy already terminated TLS, so there is nothing to upgrade.
|
||||
const forwarded = await request(app).get('/trips').set('X-Forwarded-Proto', 'https');
|
||||
expect(forwarded.status).toBe(200);
|
||||
|
||||
// The container probe talks plain HTTP on the loopback and must not be
|
||||
// bounced to a hostname it cannot resolve.
|
||||
const probe = await request(app).get('/api/health');
|
||||
expect(probe.status).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { redact, SENSITIVE_KEYS } from '../../../src/middleware/globalMiddleware';
|
||||
|
||||
describe('globalMiddleware request-log redaction', () => {
|
||||
it('redacts secretAccessKey (any casing) — storage admin PUT bodies land in the same debug log line', () => {
|
||||
expect(redact({ secretAccessKey: 'sk-super-secret' })).toEqual({ secretAccessKey: '[REDACTED]' });
|
||||
expect(redact({ SecretAccessKey: 'sk-super-secret' })).toEqual({ SecretAccessKey: '[REDACTED]' });
|
||||
expect(redact({ secretaccesskey: 'sk-super-secret' })).toEqual({ secretaccesskey: '[REDACTED]' });
|
||||
});
|
||||
|
||||
it('lists secretaccesskey in the lowercase lookup set (lookup lowercases the key first)', () => {
|
||||
expect(SENSITIVE_KEYS.has('secretaccesskey')).toBe(true);
|
||||
});
|
||||
|
||||
it('still redacts every pre-existing sensitive key (no regression)', () => {
|
||||
const input = {
|
||||
password: 'p',
|
||||
new_password: 'p',
|
||||
current_password: 'p',
|
||||
token: 't',
|
||||
jwt: 'j',
|
||||
authorization: 'a',
|
||||
cookie: 'c',
|
||||
client_secret: 's',
|
||||
mfa_token: 'm',
|
||||
code: '123456',
|
||||
smtp_pass: 's',
|
||||
};
|
||||
const out = redact(input) as Record<string, unknown>;
|
||||
for (const key of Object.keys(input)) {
|
||||
expect(out[key]).toBe('[REDACTED]');
|
||||
}
|
||||
});
|
||||
|
||||
it('redacts nested objects and arrays, leaving non-sensitive fields untouched', () => {
|
||||
const out = redact({
|
||||
name: 'off-box',
|
||||
options: { secretAccessKey: 'sk-1', accessKeyId: 'ak-1' },
|
||||
backends: [{ secretAccessKey: 'sk-2' }, { accessKeyId: 'ak-2' }],
|
||||
});
|
||||
expect(out).toEqual({
|
||||
name: 'off-box',
|
||||
options: { secretAccessKey: '[REDACTED]', accessKeyId: 'ak-1' },
|
||||
backends: [{ secretAccessKey: '[REDACTED]' }, { accessKeyId: 'ak-2' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('redacts secret-shaped keys by suffix — the OAuth token body and the settings API keys', () => {
|
||||
const out = redact({
|
||||
refresh_token: 'rt-1',
|
||||
code_verifier: 'cv-1',
|
||||
llm_api_key: 'sk-1',
|
||||
mapbox_access_token: 'pk-1',
|
||||
grant_type: 'refresh_token',
|
||||
}) as Record<string, unknown>;
|
||||
expect(out.refresh_token).toBe('[REDACTED]');
|
||||
expect(out.code_verifier).toBe('[REDACTED]');
|
||||
expect(out.llm_api_key).toBe('[REDACTED]');
|
||||
expect(out.mapbox_access_token).toBe('[REDACTED]');
|
||||
expect(out.grant_type).toBe('refresh_token');
|
||||
});
|
||||
|
||||
it('redacts the value of a {key, value} settings body when the key names a secret', () => {
|
||||
expect(redact({ key: 'carto_api_key', value: 'carto-secret' })).toEqual({
|
||||
key: 'carto_api_key',
|
||||
value: '[REDACTED]',
|
||||
});
|
||||
expect(redact({ key: 'mapbox_access_token', value: 'pk-1' })).toEqual({
|
||||
key: 'mapbox_access_token',
|
||||
value: '[REDACTED]',
|
||||
});
|
||||
// A harmless setting keeps its value: the name is what decides.
|
||||
expect(redact({ key: 'map_tile_url', value: 'https://tiles.example/{z}/{x}/{y}.png' })).toEqual({
|
||||
key: 'map_tile_url',
|
||||
value: 'https://tiles.example/{z}/{x}/{y}.png',
|
||||
});
|
||||
});
|
||||
|
||||
it('matches the suffix on the end of the key only, so identifiers stay readable', () => {
|
||||
expect(redact({ accessKeyId: 'ak-1', tokenCount: 5 })).toEqual({ accessKeyId: 'ak-1', tokenCount: 5 });
|
||||
});
|
||||
|
||||
it('passes non-object values through untouched', () => {
|
||||
expect(redact('plain string')).toBe('plain string');
|
||||
expect(redact(42)).toBe(42);
|
||||
expect(redact(null)).toBe(null);
|
||||
expect(redact(undefined)).toBe(undefined);
|
||||
});
|
||||
});
|
||||
@@ -1,176 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// ── In-memory store + DB mock using vi.hoisted ────────────────────────────────
|
||||
const { rows, dbMock } = vi.hoisted(() => {
|
||||
const rows: Record<string, { status_code: number; response_body: string }> = {};
|
||||
|
||||
const dbMock = {
|
||||
db: {
|
||||
prepare: vi.fn((sql: string) => ({
|
||||
get: vi.fn((...args: unknown[]) => {
|
||||
const [key, userId, method, path] = args;
|
||||
return rows[`${key}:${userId}:${method}:${path}`] ?? undefined;
|
||||
}),
|
||||
run: vi.fn((...args: unknown[]) => {
|
||||
const [key, userId, method, path, status_code, response_body] = args as [string, number, string, string, number, string];
|
||||
const k = `${key}:${userId}:${method}:${path}`;
|
||||
if (!rows[k]) rows[k] = { status_code, response_body };
|
||||
}),
|
||||
})),
|
||||
},
|
||||
};
|
||||
|
||||
return { rows, dbMock };
|
||||
});
|
||||
|
||||
vi.mock('../../../src/db/database', () => dbMock);
|
||||
|
||||
import { applyIdempotency } from '../../../src/middleware/idempotency';
|
||||
import type { Request, Response, NextFunction } from 'express';
|
||||
|
||||
function makeReq(method = 'POST', headers: Record<string, string> = {}, path = '/api/test'): Request {
|
||||
return { method, path, headers } as unknown as Request;
|
||||
}
|
||||
|
||||
function makeRes(statusCode = 200): Response {
|
||||
const ctx = { status: statusCode };
|
||||
const res = {
|
||||
get statusCode() { return ctx.status; },
|
||||
status(code: number) { ctx.status = code; return res; },
|
||||
json: vi.fn((_body: unknown) => res),
|
||||
} as unknown as Response;
|
||||
return res;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
Object.keys(rows).forEach(k => delete rows[k]);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('applyIdempotency', () => {
|
||||
it('calls next() for GET requests', () => {
|
||||
const req = makeReq('GET', { 'x-idempotency-key': 'key1' });
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
applyIdempotency(req, res, next, 1);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('calls next() when header is absent for POST', () => {
|
||||
const req = makeReq('POST', {});
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
applyIdempotency(req, res, next, 1);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('replays cached response when key+user+method+path already stored', () => {
|
||||
rows['cached-key:42:POST:/api/test'] = { status_code: 201, response_body: JSON.stringify({ id: 99 }) };
|
||||
const req = makeReq('POST', { 'x-idempotency-key': 'cached-key' });
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
applyIdempotency(req, res, next, 42);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res.json as ReturnType<typeof vi.fn>).toHaveBeenCalledWith({ id: 99 });
|
||||
});
|
||||
|
||||
it('different user same key does NOT replay', () => {
|
||||
rows['cached-key:1:POST:/api/test'] = { status_code: 200, response_body: JSON.stringify({ ok: true }) };
|
||||
const req = makeReq('POST', { 'x-idempotency-key': 'cached-key' });
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
applyIdempotency(req, res, next, 99); // different user
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('same key+user on different path does NOT replay (scoped cache)', () => {
|
||||
// Key 'dual-key' is cached under /api/a but reused against /api/b.
|
||||
// Without the (key, user_id, method, path) scoping, /api/b would
|
||||
// have replayed /api/a's body — a silent cross-endpoint leak.
|
||||
rows['dual-key:7:POST:/api/a'] = { status_code: 200, response_body: JSON.stringify({ from: 'a' }) };
|
||||
const req = makeReq('POST', { 'x-idempotency-key': 'dual-key' }, '/api/b');
|
||||
const res = makeRes();
|
||||
const next = vi.fn(() => {
|
||||
(res.json as ReturnType<typeof vi.fn>)({ from: 'b' });
|
||||
});
|
||||
applyIdempotency(req, res, next, 7);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
expect(rows['dual-key:7:POST:/api/b']).toBeDefined();
|
||||
expect(JSON.parse(rows['dual-key:7:POST:/api/b'].response_body)).toEqual({ from: 'b' });
|
||||
// /api/a's row is untouched.
|
||||
expect(JSON.parse(rows['dual-key:7:POST:/api/a'].response_body)).toEqual({ from: 'a' });
|
||||
});
|
||||
|
||||
it('same key+user+path but different method does NOT replay', () => {
|
||||
rows['m-key:3:POST:/api/x'] = { status_code: 201, response_body: JSON.stringify({ m: 'post' }) };
|
||||
const req = makeReq('PATCH', { 'x-idempotency-key': 'm-key' }, '/api/x');
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
applyIdempotency(req, res, next, 3);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('stores 2xx response on first execution via wrapped res.json', () => {
|
||||
const req = makeReq('POST', { 'x-idempotency-key': 'new-key' });
|
||||
const res = makeRes(201);
|
||||
const next = vi.fn(() => {
|
||||
// Simulate handler calling res.json
|
||||
(res.json as ReturnType<typeof vi.fn>)({ id: 5 });
|
||||
});
|
||||
applyIdempotency(req, res, next, 7);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
expect(rows['new-key:7:POST:/api/test']).toBeDefined();
|
||||
expect(rows['new-key:7:POST:/api/test'].status_code).toBe(201);
|
||||
expect(JSON.parse(rows['new-key:7:POST:/api/test'].response_body)).toEqual({ id: 5 });
|
||||
});
|
||||
|
||||
it('does NOT store 4xx responses', () => {
|
||||
const req = makeReq('POST', { 'x-idempotency-key': 'fail-key' });
|
||||
const res = makeRes(422);
|
||||
const next = vi.fn(() => {
|
||||
(res.json as ReturnType<typeof vi.fn>)({ error: 'Invalid' });
|
||||
});
|
||||
applyIdempotency(req, res, next, 3);
|
||||
expect(rows['fail-key:3:POST:/api/test']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns 400 when X-Idempotency-Key exceeds 128 characters', () => {
|
||||
const longKey = 'a'.repeat(129);
|
||||
const req = makeReq('POST', { 'x-idempotency-key': longKey });
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
applyIdempotency(req, res, next, 1);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(res.json as ReturnType<typeof vi.fn>).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ error: expect.stringContaining('128') }),
|
||||
);
|
||||
});
|
||||
|
||||
it('does NOT cache response body exceeding 256 KiB', () => {
|
||||
const req = makeReq('POST', { 'x-idempotency-key': 'big-key' });
|
||||
const res = makeRes(200);
|
||||
const originalJsonSpy = res.json as ReturnType<typeof vi.fn>;
|
||||
const largePayload = { data: 'x'.repeat(256 * 1024 + 1) };
|
||||
const next = vi.fn(() => {
|
||||
// res.json is now the wrapper; calling it exercises the size-cap branch
|
||||
res.json(largePayload);
|
||||
});
|
||||
applyIdempotency(req, res, next, 5);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
// Underlying spy was called (response reached the client)
|
||||
expect(originalJsonSpy).toHaveBeenCalledWith(largePayload);
|
||||
// But NOT stored in the idempotency store
|
||||
expect(rows['big-key:5:POST:/api/test']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('handles PUT, PATCH, and DELETE the same as POST', () => {
|
||||
for (const method of ['PUT', 'PATCH', 'DELETE'] as const) {
|
||||
const req = makeReq(method, { 'x-idempotency-key': `key-${method}` });
|
||||
const res = makeRes(200);
|
||||
const next = vi.fn();
|
||||
applyIdempotency(req, res, next, 1);
|
||||
expect(next).toHaveBeenCalled();
|
||||
vi.clearAllMocks();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,100 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../../src/db/database', () => ({
|
||||
db: { prepare: () => ({ get: vi.fn(), all: vi.fn() }) },
|
||||
}));
|
||||
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret' }));
|
||||
|
||||
import { isPublicApiPath, isMfaSetupExemptPath } from '../../../src/middleware/mfaPolicy';
|
||||
|
||||
// ── isPublicApiPath ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('isPublicApiPath', () => {
|
||||
// AUTH-001 — Public paths must bypass MFA
|
||||
it('AUTH-001: GET /api/health is public', () => {
|
||||
expect(isPublicApiPath('GET', '/api/health')).toBe(true);
|
||||
});
|
||||
|
||||
it('GET /api/auth/app-config is public', () => {
|
||||
expect(isPublicApiPath('GET', '/api/auth/app-config')).toBe(true);
|
||||
});
|
||||
|
||||
it('POST /api/auth/login is public', () => {
|
||||
expect(isPublicApiPath('POST', '/api/auth/login')).toBe(true);
|
||||
});
|
||||
|
||||
it('POST /api/auth/register is public', () => {
|
||||
expect(isPublicApiPath('POST', '/api/auth/register')).toBe(true);
|
||||
});
|
||||
|
||||
it('POST /api/auth/demo-login is public', () => {
|
||||
expect(isPublicApiPath('POST', '/api/auth/demo-login')).toBe(true);
|
||||
});
|
||||
|
||||
it('GET /api/auth/invite/<token> is public', () => {
|
||||
expect(isPublicApiPath('GET', '/api/auth/invite/abc123')).toBe(true);
|
||||
expect(isPublicApiPath('GET', '/api/auth/invite/xyz-789')).toBe(true);
|
||||
});
|
||||
|
||||
it('POST /api/auth/mfa/verify-login is public', () => {
|
||||
expect(isPublicApiPath('POST', '/api/auth/mfa/verify-login')).toBe(true);
|
||||
});
|
||||
|
||||
it('OIDC paths are public (any method)', () => {
|
||||
expect(isPublicApiPath('GET', '/api/auth/oidc/callback')).toBe(true);
|
||||
expect(isPublicApiPath('POST', '/api/auth/oidc/login')).toBe(true);
|
||||
expect(isPublicApiPath('GET', '/api/auth/oidc/discovery')).toBe(true);
|
||||
});
|
||||
|
||||
it('GET /api/trips is not public', () => {
|
||||
expect(isPublicApiPath('GET', '/api/trips')).toBe(false);
|
||||
});
|
||||
|
||||
it('POST /api/auth/login with wrong method (GET) is not public', () => {
|
||||
expect(isPublicApiPath('GET', '/api/auth/login')).toBe(false);
|
||||
});
|
||||
|
||||
it('GET /api/auth/me is not public', () => {
|
||||
expect(isPublicApiPath('GET', '/api/auth/me')).toBe(false);
|
||||
});
|
||||
|
||||
it('DELETE /api/auth/logout is not public', () => {
|
||||
expect(isPublicApiPath('DELETE', '/api/auth/logout')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ── isMfaSetupExemptPath ─────────────────────────────────────────────────────
|
||||
|
||||
describe('isMfaSetupExemptPath', () => {
|
||||
it('GET /api/auth/me is MFA-setup exempt', () => {
|
||||
expect(isMfaSetupExemptPath('GET', '/api/auth/me')).toBe(true);
|
||||
});
|
||||
|
||||
it('POST /api/auth/mfa/setup is MFA-setup exempt', () => {
|
||||
expect(isMfaSetupExemptPath('POST', '/api/auth/mfa/setup')).toBe(true);
|
||||
});
|
||||
|
||||
it('POST /api/auth/mfa/enable is MFA-setup exempt', () => {
|
||||
expect(isMfaSetupExemptPath('POST', '/api/auth/mfa/enable')).toBe(true);
|
||||
});
|
||||
|
||||
it('GET /api/auth/app-settings is MFA-setup exempt', () => {
|
||||
expect(isMfaSetupExemptPath('GET', '/api/auth/app-settings')).toBe(true);
|
||||
});
|
||||
|
||||
it('PUT /api/auth/app-settings is MFA-setup exempt', () => {
|
||||
expect(isMfaSetupExemptPath('PUT', '/api/auth/app-settings')).toBe(true);
|
||||
});
|
||||
|
||||
it('POST /api/auth/app-settings is NOT exempt (wrong method)', () => {
|
||||
expect(isMfaSetupExemptPath('POST', '/api/auth/app-settings')).toBe(false);
|
||||
});
|
||||
|
||||
it('GET /api/trips is NOT exempt', () => {
|
||||
expect(isMfaSetupExemptPath('GET', '/api/trips')).toBe(false);
|
||||
});
|
||||
|
||||
it('GET /api/auth/logout is NOT exempt', () => {
|
||||
expect(isMfaSetupExemptPath('GET', '/api/auth/logout')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,137 +0,0 @@
|
||||
/**
|
||||
* Unit tests for requireTripAccess and requireTripOwner middleware.
|
||||
* TRIP-ACCESS-001 through TRIP-ACCESS-010.
|
||||
* canAccessTrip and isOwner are mocked; no DB required.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import type { Request, Response, NextFunction } from 'express';
|
||||
|
||||
const mockCanAccessTrip = vi.fn();
|
||||
const mockIsOwner = vi.fn();
|
||||
|
||||
vi.mock('../../../src/db/database', () => ({
|
||||
canAccessTrip: (...args: any[]) => mockCanAccessTrip(...args),
|
||||
isOwner: (...args: any[]) => mockIsOwner(...args),
|
||||
}));
|
||||
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret' }));
|
||||
|
||||
import { requireTripAccess, requireTripOwner } from '../../../src/middleware/tripAccess';
|
||||
|
||||
function makeRes(): { res: Response; status: ReturnType<typeof vi.fn>; json: ReturnType<typeof vi.fn> } {
|
||||
const json = vi.fn();
|
||||
const status = vi.fn(() => ({ json }));
|
||||
const res = { status } as unknown as Response;
|
||||
return { res, status, json };
|
||||
}
|
||||
|
||||
function makeReq(params: Record<string, string> = {}, userId = 1): Request {
|
||||
return {
|
||||
params,
|
||||
user: { id: userId },
|
||||
} as unknown as Request;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockCanAccessTrip.mockReset();
|
||||
mockIsOwner.mockReset();
|
||||
});
|
||||
|
||||
// ── requireTripAccess ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('requireTripAccess', () => {
|
||||
it('TRIP-ACCESS-001: returns 400 when no tripId param', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status, json } = makeRes();
|
||||
requireTripAccess(makeReq({}), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(400);
|
||||
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-002: returns 404 when canAccessTrip returns null (not a member)', () => {
|
||||
mockCanAccessTrip.mockReturnValue(null);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status, json } = makeRes();
|
||||
requireTripAccess(makeReq({ tripId: '42' }), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(404);
|
||||
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-003: calls next and attaches trip when user has access', () => {
|
||||
const fakeTrip = { id: 42, user_id: 1 };
|
||||
mockCanAccessTrip.mockReturnValue(fakeTrip);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
const req = makeReq({ tripId: '42' }, 1);
|
||||
requireTripAccess(req, res, next);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
expect((req as any).trip).toEqual(fakeTrip);
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-004: accepts req.params.id as fallback when tripId is absent', () => {
|
||||
const fakeTrip = { id: 7, user_id: 2 };
|
||||
mockCanAccessTrip.mockReturnValue(fakeTrip);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
requireTripAccess(makeReq({ id: '7' }), res, next);
|
||||
expect(mockCanAccessTrip).toHaveBeenCalledWith(7, expect.any(Number));
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-005: passes numeric tripId to canAccessTrip', () => {
|
||||
mockCanAccessTrip.mockReturnValue({ id: 99, user_id: 3 });
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
requireTripAccess(makeReq({ tripId: '99' }, 3), res, next);
|
||||
expect(mockCanAccessTrip).toHaveBeenCalledWith(99, 3);
|
||||
});
|
||||
});
|
||||
|
||||
// ── requireTripOwner ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('requireTripOwner', () => {
|
||||
it('TRIP-ACCESS-006: returns 400 when no tripId param', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status, json } = makeRes();
|
||||
requireTripOwner(makeReq({}), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(400);
|
||||
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-007: returns 403 when user is not the owner', () => {
|
||||
mockIsOwner.mockReturnValue(false);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status, json } = makeRes();
|
||||
requireTripOwner(makeReq({ tripId: '10' }, 2), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(403);
|
||||
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.any(String) }));
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-008: calls next when user is the owner', () => {
|
||||
mockIsOwner.mockReturnValue(true);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
requireTripOwner(makeReq({ tripId: '10' }, 1), res, next);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-009: accepts req.params.id as fallback when tripId is absent', () => {
|
||||
mockIsOwner.mockReturnValue(true);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
requireTripOwner(makeReq({ id: '5' }, 1), res, next);
|
||||
expect(mockIsOwner).toHaveBeenCalledWith(5, 1);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('TRIP-ACCESS-010: passes numeric tripId to isOwner', () => {
|
||||
mockIsOwner.mockReturnValue(true);
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
requireTripOwner(makeReq({ tripId: '77' }, 4), res, next);
|
||||
expect(mockIsOwner).toHaveBeenCalledWith(77, 4);
|
||||
});
|
||||
});
|
||||
@@ -1,109 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { maxLength, validateStringLengths } from '../../../src/middleware/validate';
|
||||
import type { Request, Response, NextFunction } from 'express';
|
||||
|
||||
function makeReq(body: Record<string, unknown> = {}): Request {
|
||||
return { body } as Request;
|
||||
}
|
||||
|
||||
function makeRes(): { res: Response; status: ReturnType<typeof vi.fn>; json: ReturnType<typeof vi.fn> } {
|
||||
const json = vi.fn();
|
||||
const status = vi.fn(() => ({ json }));
|
||||
const res = { status } as unknown as Response;
|
||||
return { res, status, json };
|
||||
}
|
||||
|
||||
// ── maxLength ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('maxLength', () => {
|
||||
it('calls next() when field is absent from body', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
maxLength('name', 10)(makeReq({}), res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls next() when field is not a string (number)', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
maxLength('count', 5)(makeReq({ count: 999 }), res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls next() when string length is within limit', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
maxLength('name', 10)(makeReq({ name: 'hello' }), res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls next() when string length equals max exactly', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
maxLength('name', 5)(makeReq({ name: 'hello' }), res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 400 when field exceeds max', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status, json } = makeRes();
|
||||
maxLength('name', 4)(makeReq({ name: 'hello' }), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(400);
|
||||
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringContaining('name') }));
|
||||
});
|
||||
|
||||
it('error message includes field name and max length', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, json } = makeRes();
|
||||
maxLength('title', 3)(makeReq({ title: 'toolong' }), res, next);
|
||||
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringMatching(/title.*3|3.*title/i) }));
|
||||
});
|
||||
});
|
||||
|
||||
// ── validateStringLengths ────────────────────────────────────────────────────
|
||||
|
||||
describe('validateStringLengths', () => {
|
||||
it('calls next() when all fields are within limits', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
validateStringLengths({ name: 10, bio: 100 })(makeReq({ name: 'Alice', bio: 'A short bio' }), res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 400 on first field that exceeds its limit', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res, status } = makeRes();
|
||||
validateStringLengths({ name: 3 })(makeReq({ name: 'toolong' }), res, next);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(status).toHaveBeenCalledWith(400);
|
||||
});
|
||||
|
||||
it('skips fields not present in body', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
validateStringLengths({ name: 10, missing: 5 })(makeReq({ name: 'Alice' }), res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips non-string fields', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
validateStringLengths({ count: 5 })(makeReq({ count: 999999 }), res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('handles empty maxLengths object — calls next()', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
validateStringLengths({})(makeReq({ anything: 'value' }), res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls next() only once even if multiple fields are valid', () => {
|
||||
const next = vi.fn() as unknown as NextFunction;
|
||||
const { res } = makeRes();
|
||||
validateStringLengths({ a: 10, b: 10 })(makeReq({ a: 'ok', b: 'ok' }), res, next);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user