mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 09:22:15 +00:00
fix(server): tighten the guard, audit and token paths
Permissions cached an empty map before it had loaded, so a DB error during the load cached permissive defaults and every later check answered from that cache - fail-open, and it never expired. The rate limiter grew its per-IP map forever; the GC the legacy version had was dropped in the fold. Idempotency did a check-then-insert, so two concurrent duplicates both ran the handler. Audit rows recorded whatever X-Forwarded-For said, which the client writes, and the request-body debug logger redacted by exact key match - it missed refresh tokens, api keys and PKCE verifiers. FORCE_HTTPS built its redirect from the client's Host header. CSP asked for unsafe-eval on top of the wasm-unsafe-eval it actually needs. The OAuth deny path redirected to an unvalidated URI, ws-token minting had no rate limit at all, and PKCE was skipped when code_verifier was absent rather than refused. An MCP session resumed with a token whose scopes had since been reduced kept the capability set it was created with, and the session cap was checked before the async registration that increments it. Plugin frame containment was lexical, so a symlink out of the directory was never noticed, and instance config accepted keys the manifest never declared.
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import express from 'express';
|
||||
import request from 'supertest';
|
||||
import { applyGlobalMiddleware } from '../../../src/middleware/globalMiddleware';
|
||||
|
||||
async function connectSrcSources(): Promise<string[]> {
|
||||
async function directiveSources(name: string): Promise<string[]> {
|
||||
const app = express();
|
||||
applyGlobalMiddleware(app);
|
||||
app.get('/probe', (_req, res) => res.json({ ok: true }));
|
||||
@@ -13,11 +13,13 @@ async function connectSrcSources(): Promise<string[]> {
|
||||
const directive = csp
|
||||
.split(';')
|
||||
.map(d => d.trim())
|
||||
.find(d => d.startsWith('connect-src'));
|
||||
.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`
|
||||
@@ -30,3 +32,44 @@ describe('global CSP: OpenStreetMap tile hosts (#1733)', () => {
|
||||
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("does not allow 'unsafe-eval' — the policy the wiki documents, and nothing first-party evals", async () => {
|
||||
expect(await directiveSources('script-src')).not.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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -45,6 +45,25 @@ describe('globalMiddleware request-log redaction', () => {
|
||||
});
|
||||
});
|
||||
|
||||
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('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);
|
||||
|
||||
@@ -61,10 +61,12 @@ afterAll(() => {
|
||||
});
|
||||
|
||||
function makeReq(options: {
|
||||
ip?: string;
|
||||
xff?: string | string[];
|
||||
remoteAddress?: string;
|
||||
} = {}): Request {
|
||||
return {
|
||||
ip: options.ip,
|
||||
headers: {
|
||||
...(options.xff !== undefined ? { 'x-forwarded-for': options.xff } : {}),
|
||||
},
|
||||
@@ -75,33 +77,34 @@ function makeReq(options: {
|
||||
// ── getClientIp (pure, moved 1:1) ─────────────────────────────────────────────
|
||||
|
||||
describe('getClientIp', () => {
|
||||
it('AUDIT-SVC-001: returns first IP from comma-separated X-Forwarded-For string', () => {
|
||||
expect(getClientIp(makeReq({ xff: '1.2.3.4, 5.6.7.8, 9.10.11.12' }))).toBe('1.2.3.4');
|
||||
it('AUDIT-SVC-001: returns req.ip, which Express resolved through the trust-proxy hop count', () => {
|
||||
expect(getClientIp(makeReq({ ip: '1.2.3.4', xff: '9.9.9.9, 1.2.3.4' }))).toBe('1.2.3.4');
|
||||
});
|
||||
|
||||
it('AUDIT-SVC-002: returns single IP when X-Forwarded-For has no comma', () => {
|
||||
expect(getClientIp(makeReq({ xff: '10.0.0.1' }))).toBe('10.0.0.1');
|
||||
it('AUDIT-SVC-002: ignores a hand-written X-Forwarded-For — the leftmost entry is whatever the caller typed', () => {
|
||||
expect(getClientIp(makeReq({ ip: '203.0.113.7', xff: '10.0.0.1' }))).toBe('203.0.113.7');
|
||||
});
|
||||
|
||||
it('AUDIT-SVC-003: returns first element when X-Forwarded-For is an array', () => {
|
||||
expect(getClientIp(makeReq({ xff: ['203.0.113.1', '10.0.0.1'] }))).toBe('203.0.113.1');
|
||||
it('AUDIT-SVC-003: ignores an array-valued X-Forwarded-For too', () => {
|
||||
expect(getClientIp(makeReq({ ip: '203.0.113.7', xff: ['203.0.113.1', '10.0.0.1'] }))).toBe('203.0.113.7');
|
||||
});
|
||||
|
||||
it('AUDIT-SVC-004: trims whitespace from extracted IP', () => {
|
||||
expect(getClientIp(makeReq({ xff: ' 192.168.1.1 , 10.0.0.1' }))).toBe('192.168.1.1');
|
||||
it('AUDIT-SVC-004: trims whitespace from the resolved IP', () => {
|
||||
expect(getClientIp(makeReq({ ip: ' 192.168.1.1 ' }))).toBe('192.168.1.1');
|
||||
});
|
||||
|
||||
it('AUDIT-SVC-005: falls back to req.socket.remoteAddress when no X-Forwarded-For', () => {
|
||||
it('AUDIT-SVC-005: falls back to req.socket.remoteAddress when req.ip is unset', () => {
|
||||
expect(getClientIp(makeReq({ remoteAddress: '172.16.0.1' }))).toBe('172.16.0.1');
|
||||
});
|
||||
|
||||
it('AUDIT-SVC-006: returns null when no forwarded header and no socket address', () => {
|
||||
it('AUDIT-SVC-006: returns null when there is neither a resolved IP nor a socket address', () => {
|
||||
expect(getClientIp(makeReq({}))).toBeNull();
|
||||
});
|
||||
|
||||
it('AUDIT-SVC-007: returns null for empty string X-Forwarded-For', () => {
|
||||
it('AUDIT-SVC-007: returns null for an empty req.ip with no socket address', () => {
|
||||
const req = {
|
||||
headers: { 'x-forwarded-for': '' },
|
||||
ip: '',
|
||||
headers: { 'x-forwarded-for': '203.0.113.9' },
|
||||
socket: { remoteAddress: undefined },
|
||||
} as unknown as Request;
|
||||
expect(getClientIp(req)).toBeNull();
|
||||
@@ -147,6 +150,19 @@ describe('writeAudit', () => {
|
||||
expect(logInfo).toHaveBeenLastCalledWith('anonymous logged in ip=9.9.9.9');
|
||||
});
|
||||
|
||||
it('AUDIT-SVC-019: a trip title with a line break cannot forge a second log line', () => {
|
||||
seedUser(1, 'a@b.c');
|
||||
svc.writeAudit({
|
||||
userId: 1,
|
||||
action: 'trip.create',
|
||||
details: { title: 'Rome\nadmin@b.c changed user role' },
|
||||
ip: '1.2.3.4',
|
||||
});
|
||||
const logged = String((logInfo as unknown as { mock: { calls: string[][] } }).mock.calls.at(-1)?.[0]);
|
||||
expect(logged).not.toContain('\n');
|
||||
expect(logged).toBe('a@b.c created trip "Rome admin@b.c changed user role" ip=1.2.3.4');
|
||||
});
|
||||
|
||||
it('AUDIT-SVC-011: omitted resource/ip store NULL and the log line ends ip=-', () => {
|
||||
seedUser(1, 'a@b.c');
|
||||
svc.writeAudit({ userId: 1, action: 'user.login' });
|
||||
|
||||
@@ -249,8 +249,23 @@ describe('AuthController (authenticated)', () => {
|
||||
});
|
||||
|
||||
it('resource-token 503 when unavailable, else returns the token payload', () => {
|
||||
expect(thrown(() => ac(asvc({}), rl(), { createResourceToken: vi.fn().mockReturnValue(null) }).resourceToken(user, {}))).toEqual({ status: 503, body: { error: 'Service unavailable' } });
|
||||
expect(ac(asvc({}), rl(), { createResourceToken: vi.fn().mockReturnValue({ token: 'rt' }) }).resourceToken(user, { purpose: 'download' })).toEqual({ token: 'rt' });
|
||||
expect(thrown(() => ac(asvc({}), rl(), { createResourceToken: vi.fn().mockReturnValue(null) }).resourceToken(user, {}, req))).toEqual({ status: 503, body: { error: 'Service unavailable' } });
|
||||
expect(ac(asvc({}), rl(), { createResourceToken: vi.fn().mockReturnValue({ token: 'rt' }) }).resourceToken(user, { purpose: 'download' }, req)).toEqual({ token: 'rt' });
|
||||
});
|
||||
|
||||
it('ws/resource tokens throttle on their own buckets, so a mint loop cannot drain the store or block login', () => {
|
||||
const s = rl();
|
||||
const now = Date.now();
|
||||
for (let i = 0; i < 120; i++) s.check('ws_token', '9.9.9.9', 120, 15 * 60 * 1000, now);
|
||||
expect(thrown(() => ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user, req)))
|
||||
.toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
|
||||
// The login bucket is untouched: an exhausted socket loop must not lock the account out.
|
||||
expect(s.check('login', '9.9.9.9', 5, 15 * 60 * 1000, now)).toBe(true);
|
||||
|
||||
const s2 = rl();
|
||||
for (let i = 0; i < 120; i++) s2.check('resource_token', '9.9.9.9', 120, 15 * 60 * 1000, now);
|
||||
expect(thrown(() => ac(asvc({}), s2, { createResourceToken: vi.fn().mockReturnValue({ token: 'rt' }) }).resourceToken(user, {}, req)))
|
||||
.toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
|
||||
});
|
||||
|
||||
it('rate-limited account ops throw 429 once the bucket is exhausted', () => {
|
||||
@@ -385,8 +400,8 @@ describe('AuthController (authenticated)', () => {
|
||||
});
|
||||
|
||||
it('ws-token maps error, else returns the token', () => {
|
||||
expect(thrown(() => ac(asvc({}), rl(), { createWsToken: vi.fn().mockReturnValue({ error: 'down', status: 503 }) }).wsToken(user))).toEqual({ status: 503, body: { error: 'down' } });
|
||||
expect(ac(asvc({}), rl(), { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user)).toEqual({ token: 'ws' });
|
||||
expect(thrown(() => ac(asvc({}), rl(), { createWsToken: vi.fn().mockReturnValue({ error: 'down', status: 503 }) }).wsToken(user, req))).toEqual({ status: 503, body: { error: 'down' } });
|
||||
expect(ac(asvc({}), rl(), { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user, req)).toEqual({ token: 'ws' });
|
||||
});
|
||||
|
||||
it('avatar saves when not in demo mode (env present but email is not a demo email)', async () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { HttpException } from '@nestjs/common';
|
||||
import type { CallHandler, ExecutionContext } from '@nestjs/common';
|
||||
import { of, lastValueFrom } from 'rxjs';
|
||||
import { from, of, lastValueFrom } from 'rxjs';
|
||||
import { IdempotencyInterceptor } from '../../../src/nest/common/idempotency.interceptor';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
|
||||
@@ -181,6 +181,62 @@ describe('IdempotencyInterceptor (parity with the legacy applyIdempotency middle
|
||||
expect(returned).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it('makes an overlapping replay of the same key wait, then answers it from the first response', async () => {
|
||||
// The row only appears once the first request answers, so without the
|
||||
// in-flight map both of these would miss the SELECT and both would run.
|
||||
const rows = new Map<string, { status_code: number; response_body: string }>();
|
||||
const db = makeDb({
|
||||
get: vi.fn((_sql: string, ...params: unknown[]) => rows.get(String(params[0]))) as unknown as DatabaseService['get'],
|
||||
run: vi.fn((_sql: string, ...params: unknown[]) => {
|
||||
rows.set(String(params[0]), { status_code: Number(params[4]), response_body: String(params[5]) });
|
||||
return {} as never;
|
||||
}) as unknown as DatabaseService['run'],
|
||||
});
|
||||
const interceptor = new IdempotencyInterceptor(db);
|
||||
|
||||
// The first handler is still running when the second request arrives.
|
||||
let finish!: (value: unknown) => void;
|
||||
const slow = { handle: vi.fn(() => from(new Promise((resolve) => { finish = resolve; }))) };
|
||||
const firstRes = makeRes();
|
||||
const first = lastValueFrom(interceptor.intercept(ctx({ method: 'POST', headers: { 'x-idempotency-key': 'k' }, path: '/api/places', user: { id: 1 } }, firstRes), slow));
|
||||
|
||||
const secondHandler = handler({ id: 'second' });
|
||||
const secondRes = makeRes();
|
||||
const second = lastValueFrom(interceptor.intercept(ctx({ method: 'POST', headers: { 'x-idempotency-key': 'k' }, path: '/api/places', user: { id: 1 } }, secondRes), secondHandler));
|
||||
|
||||
firstRes.statusCode = 201;
|
||||
firstRes.json({ id: 'first' });
|
||||
finish({ id: 'first' });
|
||||
|
||||
expect(await first).toEqual({ id: 'first' });
|
||||
expect(await second).toEqual({ id: 'first' });
|
||||
expect(secondHandler.handle).not.toHaveBeenCalled();
|
||||
expect(secondRes.status).toHaveBeenCalledWith(201);
|
||||
});
|
||||
|
||||
it('runs the waiting request itself when the first one cached nothing', async () => {
|
||||
const db = makeDb({ get: vi.fn().mockReturnValue(undefined), run: vi.fn() });
|
||||
const interceptor = new IdempotencyInterceptor(db);
|
||||
|
||||
let finish!: (value: unknown) => void;
|
||||
const slow = { handle: vi.fn(() => from(new Promise((resolve) => { finish = resolve; }))) };
|
||||
const first = lastValueFrom(interceptor.intercept(
|
||||
ctx({ method: 'POST', headers: { 'x-idempotency-key': 'k' }, path: '/api/places', user: { id: 1 } }, makeRes()),
|
||||
slow,
|
||||
));
|
||||
|
||||
const secondHandler = handler({ id: 'second' });
|
||||
const second = lastValueFrom(interceptor.intercept(
|
||||
ctx({ method: 'POST', headers: { 'x-idempotency-key': 'k' }, path: '/api/places', user: { id: 1 } }, makeRes()),
|
||||
secondHandler,
|
||||
));
|
||||
|
||||
finish({ id: 'first' });
|
||||
await first;
|
||||
expect(await second).toEqual({ id: 'second' });
|
||||
expect(secondHandler.handle).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('treats a PATCH as a mutating method', async () => {
|
||||
const db = makeDb({ get: vi.fn().mockReturnValue(undefined), run: vi.fn() });
|
||||
const res = makeRes();
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
armSseKeepalive,
|
||||
countSessionsForUser,
|
||||
jsonRpcError,
|
||||
sameScopes,
|
||||
setAuthChallenge,
|
||||
} from '../../../src/nest/mcp-transport/mcp-transport.service';
|
||||
import { McpTransportController } from '../../../src/nest/mcp-transport/mcp-transport.controller';
|
||||
@@ -70,6 +71,21 @@ describe('setAuthChallenge', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('sameScopes', () => {
|
||||
it('MCPT-008: full access only matches full access', () => {
|
||||
expect(sameScopes(null, null)).toBe(true);
|
||||
expect(sameScopes(null, ['trips:read'])).toBe(false);
|
||||
expect(sameScopes(['trips:read'], null)).toBe(false);
|
||||
});
|
||||
|
||||
it('MCPT-009: order does not matter, membership does', () => {
|
||||
expect(sameScopes(['a', 'b'], ['b', 'a'])).toBe(true);
|
||||
expect(sameScopes(['a', 'b'], ['a'])).toBe(false);
|
||||
expect(sameScopes(['a'], ['b'])).toBe(false);
|
||||
expect(sameScopes([], [])).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('countSessionsForUser', () => {
|
||||
afterEach(() => sessions.clear());
|
||||
|
||||
|
||||
@@ -374,10 +374,15 @@ describe('TrekOAuthProvider.exchangeAuthorizationCode', () => {
|
||||
it('SDKP-046: a pending code without a resource issues a null-audience token', async () => {
|
||||
const oauth = makeOauth({ consumeAuthCode: vi.fn(() => pending({ resource: null })) });
|
||||
const { provider } = makeProvider(oauth);
|
||||
await provider.exchangeAuthorizationCode(clientInfo(), 'code');
|
||||
await provider.exchangeAuthorizationCode(clientInfo(), 'code', 'verifier');
|
||||
expect(oauth.issueTokens).toHaveBeenCalledWith('cid-1', 7, ['trips:read'], null, null);
|
||||
// No codeVerifier was supplied, so PKCE verification is skipped entirely.
|
||||
expect(oauth.verifyPKCE).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('SDKP-047: a missing codeVerifier is refused, not waved through', async () => {
|
||||
const oauth = makeOauth({ consumeAuthCode: vi.fn(() => pending()) });
|
||||
const { provider } = makeProvider(oauth);
|
||||
await expect(provider.exchangeAuthorizationCode(clientInfo(), 'code')).rejects.toThrow(invalid);
|
||||
expect(oauth.issueTokens).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -339,7 +339,8 @@ describe('OauthApiController', () => {
|
||||
});
|
||||
|
||||
it('authorize: denied returns a redirect with access_denied, approved issues a code', () => {
|
||||
const denied = new OauthApiController(osvc(), rl()).authorize(user, { client_id: 'c', redirect_uri: 'https://cb', scope: 's', code_challenge: 'cc', code_challenge_method: 'S256', approved: false }, req);
|
||||
const deniedSvc = osvc({ validateAuthorizeRequest: vi.fn().mockReturnValue({ valid: true, scopes: ['s'] }) });
|
||||
const denied = new OauthApiController(deniedSvc, rl()).authorize(user, { client_id: 'c', redirect_uri: 'https://cb', scope: 's', code_challenge: 'cc', code_challenge_method: 'S256', approved: false }, req);
|
||||
expect((denied as { redirect: string }).redirect).toContain('error=access_denied');
|
||||
const svc = osvc({ validateAuthorizeRequest: vi.fn().mockReturnValue({ valid: true, scopes: ['s'], resource: null }), saveConsent: vi.fn(), createAuthCode: vi.fn().mockReturnValue('the_code') });
|
||||
const ok = new OauthApiController(svc, rl()).authorize(user, { client_id: 'c', redirect_uri: 'https://cb', scope: 's', code_challenge: 'cc', code_challenge_method: 'S256', approved: true }, req);
|
||||
@@ -405,7 +406,8 @@ describe('OauthApiController', () => {
|
||||
});
|
||||
|
||||
it('authorize: carries the state through both the denied and approved redirects', () => {
|
||||
const denied = new OauthApiController(osvc(), rl()).authorize(user, { client_id: 'c', redirect_uri: 'https://cb', scope: 's', state: 'xyz', code_challenge: 'cc', code_challenge_method: 'S256', approved: false }, req);
|
||||
const deniedSvc = osvc({ validateAuthorizeRequest: vi.fn().mockReturnValue({ valid: true, scopes: ['s'] }) });
|
||||
const denied = new OauthApiController(deniedSvc, rl()).authorize(user, { client_id: 'c', redirect_uri: 'https://cb', scope: 's', state: 'xyz', code_challenge: 'cc', code_challenge_method: 'S256', approved: false }, req);
|
||||
expect((denied as { redirect: string }).redirect).toContain('state=xyz');
|
||||
|
||||
const svc = osvc({ validateAuthorizeRequest: vi.fn().mockReturnValue({ valid: true, scopes: ['s'], resource: 'https://aud' }), saveConsent: vi.fn(), createAuthCode: vi.fn().mockReturnValue('the_code') });
|
||||
@@ -414,6 +416,15 @@ describe('OauthApiController', () => {
|
||||
expect((ok as { redirect: string }).redirect).toContain('state=xyz');
|
||||
});
|
||||
|
||||
it('authorize: a denial is validated too, so the redirect can only be a registered URI', () => {
|
||||
const validateAuthorizeRequest = vi.fn().mockReturnValue({ valid: false, error: 'invalid_redirect_uri', error_description: 'Invalid redirect URI' });
|
||||
const svc = osvc({ validateAuthorizeRequest, saveConsent: vi.fn(), createAuthCode: vi.fn() });
|
||||
expect(thrown(() => new OauthApiController(svc, rl())
|
||||
.authorize(user, { client_id: 'c', redirect_uri: 'not a url', scope: 's', code_challenge: 'cc', code_challenge_method: 'S256', approved: false }, req)))
|
||||
.toEqual({ status: 400, body: { error: 'invalid_redirect_uri', error_description: 'Invalid redirect URI' } });
|
||||
expect(validateAuthorizeRequest).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('client/session errors default the status to 400 when the service omits it', () => {
|
||||
expect(thrown(() => new OauthApiController(osvc({ createOAuthClient: vi.fn().mockReturnValue({ error: 'bad' }) }), rl()).createClient(user, { name: 'X', allowed_scopes: ['a'] }, req)))
|
||||
.toEqual({ status: 400, body: { error: 'bad' } });
|
||||
|
||||
@@ -43,7 +43,10 @@ import { runMigrations } from '../../../src/db/migrations';
|
||||
import { logError } from '../../../src/nest/audit/audit-log.logger';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { PermissionsService, PERMISSION_ACTIONS } from '../../../src/nest/permissions/permissions.service';
|
||||
import { invalidatePermissionsCache as invalidateSharedCache } from '../../../src/nest/permissions/permissions-cache';
|
||||
import {
|
||||
getPermissionsCache,
|
||||
invalidatePermissionsCache as invalidateSharedCache,
|
||||
} from '../../../src/nest/permissions/permissions-cache';
|
||||
|
||||
const svc = new PermissionsService(new DatabaseService(testDb));
|
||||
|
||||
@@ -192,6 +195,22 @@ describe('load failures', () => {
|
||||
svc.invalidatePermissionsCache(); // don't leak the bare-DB cache to later tests
|
||||
});
|
||||
|
||||
it('PERM-SVC-024: a failed read serves defaults without installing them, and a later read populates the cache', () => {
|
||||
const failing = { all: vi.fn((): { key: string; value: string }[] => { throw new Error('database connection is closed'); }) };
|
||||
const flakySvc = new PermissionsService(failing as unknown as DatabaseService);
|
||||
flakySvc.invalidatePermissionsCache();
|
||||
|
||||
expect(flakySvc.getPermissionLevel('trip_edit')).toBe('trip_owner');
|
||||
// Nothing installed: an admin's stricter stored level would otherwise stay
|
||||
// invisible until somebody invalidated by hand.
|
||||
expect(getPermissionsCache()).toBe(null);
|
||||
|
||||
failing.all.mockReturnValue([{ key: 'perm_trip_edit', value: 'trip_member' }]);
|
||||
expect(flakySvc.getPermissionLevel('trip_edit')).toBe('trip_member');
|
||||
expect(getPermissionsCache()).not.toBe(null);
|
||||
svc.invalidatePermissionsCache(); // don't leak the stub cache to later tests
|
||||
});
|
||||
|
||||
it('PERM-SVC-023: an all-skipped save writes nothing and leaves the cache untouched', () => {
|
||||
expect(svc.getPermissionLevel('trip_edit')).toBe('trip_owner'); // prime the cache
|
||||
testDb.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run('perm_trip_edit', 'trip_member');
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* RateLimitService — the per-IP buckets every auth-adjacent route throttles on.
|
||||
* The limit behaviour is the legacy one line for line; what is worth pinning
|
||||
* here is that the maps do not grow forever, because the keys come from
|
||||
* proxy headers and are therefore attacker-influenced.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { RateLimitService } from '../../../src/nest/common/rate-limit.service';
|
||||
|
||||
const WINDOW = 15 * 60 * 1000;
|
||||
|
||||
/** The private bucket map, which is the only place the housekeeping is visible. */
|
||||
function bucketSize(service: RateLimitService, bucket: string): number {
|
||||
const buckets = (service as unknown as { buckets: Map<string, Map<string, unknown>> }).buckets;
|
||||
return buckets.get(bucket)?.size ?? 0;
|
||||
}
|
||||
|
||||
describe('RateLimitService', () => {
|
||||
it('allows up to max attempts in a window, then refuses', () => {
|
||||
const s = new RateLimitService();
|
||||
const now = Date.now();
|
||||
for (let i = 0; i < 5; i++) expect(s.check('login', '1.2.3.4', 5, WINDOW, now)).toBe(true);
|
||||
expect(s.check('login', '1.2.3.4', 5, WINDOW, now)).toBe(false);
|
||||
});
|
||||
|
||||
it('starts a fresh window once the old one elapsed', () => {
|
||||
const s = new RateLimitService();
|
||||
const now = Date.now();
|
||||
for (let i = 0; i < 5; i++) s.check('login', '1.2.3.4', 5, WINDOW, now);
|
||||
expect(s.check('login', '1.2.3.4', 5, WINDOW, now + WINDOW)).toBe(true);
|
||||
});
|
||||
|
||||
it('drops expired records instead of keeping one per address that ever knocked', () => {
|
||||
const s = new RateLimitService();
|
||||
const now = Date.now();
|
||||
for (let i = 0; i < 100; i++) s.check('login', `10.0.0.${i}`, 5, WINDOW, now);
|
||||
expect(bucketSize(s, 'login')).toBe(100);
|
||||
|
||||
// One request a window later sweeps the hundred stale keys and leaves its own.
|
||||
s.check('login', '10.0.0.0', 5, WINDOW, now + WINDOW);
|
||||
expect(bucketSize(s, 'login')).toBe(1);
|
||||
});
|
||||
|
||||
it('sweeps each bucket on its own clock, so a busy bucket cannot starve a quiet one', () => {
|
||||
const s = new RateLimitService();
|
||||
const now = Date.now();
|
||||
s.check('login', '1.2.3.4', 5, WINDOW, now);
|
||||
for (let i = 0; i < 3; i++) s.check('mfa', `10.0.0.${i}`, 5, WINDOW, now + WINDOW * (i + 1));
|
||||
expect(bucketSize(s, 'login')).toBe(1);
|
||||
|
||||
s.check('login', '5.6.7.8', 5, WINDOW, now + WINDOW);
|
||||
expect(bucketSize(s, 'login')).toBe(1);
|
||||
});
|
||||
|
||||
it('keeps a record that is still inside its window when the sweep runs', () => {
|
||||
const s = new RateLimitService();
|
||||
const now = Date.now();
|
||||
s.check('login', '1.2.3.4', 5, WINDOW, now);
|
||||
s.check('login', '5.6.7.8', 5, WINDOW, now + WINDOW);
|
||||
// The second key was written after the sweep, the first one was expired.
|
||||
expect(bucketSize(s, 'login')).toBe(1);
|
||||
expect(s.check('login', '1.2.3.4', 5, WINDOW, now + WINDOW)).toBe(true);
|
||||
});
|
||||
|
||||
it('reset clears a single bucket, or all of them', () => {
|
||||
const s = new RateLimitService();
|
||||
const now = Date.now();
|
||||
s.check('login', '1.2.3.4', 5, WINDOW, now);
|
||||
s.check('mfa', '1.2.3.4', 5, WINDOW, now);
|
||||
s.reset('login');
|
||||
expect(bucketSize(s, 'login')).toBe(0);
|
||||
expect(bucketSize(s, 'mfa')).toBe(1);
|
||||
s.reset();
|
||||
expect(bucketSize(s, 'mfa')).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -15,16 +15,36 @@ import { PluginFrameController } from '../../../src/nest/plugins/plugin-frame.co
|
||||
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
|
||||
let codeRoot: string;
|
||||
let outsideRoot: string;
|
||||
// Windows only lets an unprivileged process create a directory junction.
|
||||
const dirLink = process.platform === 'win32' ? 'junction' : 'dir';
|
||||
let symlinksAvailable = true;
|
||||
|
||||
beforeAll(() => {
|
||||
codeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'trekplug-frame-'));
|
||||
outsideRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'trekplug-outside-'));
|
||||
process.env.TREK_PLUGINS_DIR = codeRoot;
|
||||
const dir = path.join(codeRoot, 'widget', 'client');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'index.html'), '<!doctype html><body>hi</body>');
|
||||
|
||||
// Something worth stealing, plus a link out of client/ that points at it.
|
||||
fs.mkdirSync(path.join(outsideRoot, 'secrets'), { recursive: true });
|
||||
fs.writeFileSync(path.join(outsideRoot, 'secrets', 'leak.js'), 'TOP SECRET');
|
||||
// A dev-linked plugin: the whole tree is a link, which must still be served.
|
||||
fs.mkdirSync(path.join(outsideRoot, 'linked', 'client'), { recursive: true });
|
||||
fs.writeFileSync(path.join(outsideRoot, 'linked', 'client', 'index.html'), '<!doctype html><body>dev</body>');
|
||||
try {
|
||||
fs.symlinkSync(path.join(outsideRoot, 'secrets'), path.join(dir, 'esc'), dirLink);
|
||||
fs.symlinkSync(path.join(outsideRoot, 'linked'), path.join(codeRoot, 'linked'), dirLink);
|
||||
} catch {
|
||||
symlinksAvailable = false;
|
||||
}
|
||||
});
|
||||
afterAll(() => {
|
||||
delete process.env.TREK_PLUGINS_DIR;
|
||||
fs.rmSync(codeRoot, { recursive: true, force: true });
|
||||
fs.rmSync(outsideRoot, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function fakeRes() {
|
||||
@@ -157,4 +177,23 @@ describe('PluginFrameController', () => {
|
||||
new PluginFrameController(runtime(true)).serve('widget', req('missing.js'), res as never);
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
// The lexical guard above cannot see through a link, and statSync follows one.
|
||||
it('403 on a symlink inside client/ that points out of the plugin', () => {
|
||||
if (!symlinksAvailable) return;
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true)).serve('widget', req('esc/leak.js'), res as never);
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.filePath).toBeUndefined();
|
||||
});
|
||||
|
||||
// Dev-link mode: the plugin directory itself is a link, so the containment
|
||||
// check has to resolve BOTH sides or local development stops working.
|
||||
it('still serves a dev-linked plugin whose whole tree is a symlink', () => {
|
||||
if (!symlinksAvailable) return;
|
||||
const res = fakeRes();
|
||||
new PluginFrameController(runtime(true)).serve('linked', req(''), res as never);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.filePath).toContain('index.html');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -246,6 +246,7 @@ describe('PluginsService instance config', () => {
|
||||
it('encrypts secret fields on write and masks them on read; keeps plaintext for non-secrets', () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, name, status, config) VALUES ('x','X','inactive','{}')").run();
|
||||
testDb.prepare("INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES ('x','api_key','instance',1)").run();
|
||||
testDb.prepare("INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES ('x','server','instance',0)").run();
|
||||
|
||||
const svc = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn)));
|
||||
const masked = svc.updateInstanceConfig('x', { api_key: 'super-secret', server: 'https://h' });
|
||||
@@ -267,6 +268,19 @@ describe('PluginsService instance config', () => {
|
||||
expect(svc.getInstanceConfig('x').api_key).toBe('••••••••');
|
||||
});
|
||||
|
||||
it('drops a key the plugin never declared, like the user-scope sibling does', () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, name, status, config) VALUES ('y','Y','inactive','{}')").run();
|
||||
testDb.prepare("INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES ('y','server','instance',0)").run();
|
||||
|
||||
const svc = new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn)));
|
||||
const masked = svc.updateInstanceConfig('y', { server: 'https://h', smuggled: 'nope' });
|
||||
|
||||
expect(masked.server).toBe('https://h');
|
||||
expect(masked.smuggled).toBeUndefined();
|
||||
const stored = JSON.parse((testDb.prepare("SELECT config FROM plugins WHERE id='y'").get() as { config: string }).config);
|
||||
expect(stored).toEqual({ server: 'https://h' });
|
||||
});
|
||||
|
||||
it('throws for an unknown plugin', () => {
|
||||
expect(() => new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).updateInstanceConfig('nope', {})).toThrow(/not found/);
|
||||
expect(() => new PluginsService(new DatabaseService(dbConn), new AddonsService(new DatabaseService(dbConn))).getInstanceConfig('nope')).toThrow(/not found/);
|
||||
|
||||
Reference in New Issue
Block a user