diff --git a/src/config/trusted-proxy.ts b/src/config/trusted-proxy.ts index 8307bd1a..07651352 100644 --- a/src/config/trusted-proxy.ts +++ b/src/config/trusted-proxy.ts @@ -26,7 +26,8 @@ * is read ONCE and both `CODEMAN_TRUSTED_PROXY_SECRET` and * `CODEMAN_TRUSTED_PROXY_SECRET_FILE` are then deleted from `process.env`, because every * session Codeman spawns inherits that environment. The file's resolved path stays in - * this module (`trustedProxySecretFilePath`) for the sensitive-path blocklist. + * this module (`trustedProxySecretFilePath`, `trustedProxySecretFileRealPath`) for the + * sensitive-path blocklist. * * A configured setup that can't be used stops the server from starting * (`trustedProxyConfigError`, thrown from `WebServer.start()`), so a typo never falls @@ -37,7 +38,7 @@ * e.g. the web-tab relay, can forward or log them. */ -import { readFileSync, statSync } from 'node:fs'; +import { readFileSync, realpathSync, statSync } from 'node:fs'; import type { IncomingHttpHeaders } from 'node:http'; import { resolve } from 'node:path'; @@ -85,6 +86,8 @@ interface LoadedSecret { problem?: string; /** Absolute path of `CODEMAN_TRUSTED_PROXY_SECRET_FILE`, when it was set. */ filePath?: string; + /** That path with symlinks resolved, when it could be resolved. */ + fileRealPath?: string; } let loaded: LoadedSecret | null = null; @@ -101,6 +104,7 @@ function loadSecret(): LoadedSecret { delete process.env.CODEMAN_TRUSTED_PROXY_SECRET; delete process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE; const filePath = file ? resolve(file) : undefined; + const fileRealPath = filePath ? realPathOrUndefined(filePath) : undefined; let secret: string | undefined; let problem: string | undefined; @@ -130,10 +134,18 @@ function loadSecret(): LoadedSecret { 'the trusted-proxy secret must be printable ASCII without spaces (generate one with: openssl rand -hex 32)'; } } - loaded = { secret, problem, filePath }; + loaded = { secret, problem, filePath, fileRealPath }; return loaded; } +function realPathOrUndefined(path: string): string | undefined { + try { + return realpathSync(path); + } catch { + return undefined; + } +} + /** * Read the secret now and remove both variables from `process.env`. Called first in * `WebServer.start()` and again (a no-op then) at auth setup, before any session is @@ -154,6 +166,16 @@ export function trustedProxySecretFilePath(): string | null { return file ? resolve(file) : null; } +/** + * The secret file's path with symlinks resolved, or null (not configured, or it can't be + * resolved). Resolved once when the secret is read; before that, from the environment. + */ +export function trustedProxySecretFileRealPath(): string | null { + if (loaded) return loaded.fileRealPath ?? null; + const file = trustedProxySecretFilePath(); + return (file && realPathOrUndefined(file)) ?? null; +} + /** Test-only: forget the cached secret so the next call re-reads the environment. */ export function resetTrustedProxySecretForTests(): void { loaded = null; diff --git a/src/web/middleware/auth.ts b/src/web/middleware/auth.ts index b5b7be06..f0459e52 100644 --- a/src/web/middleware/auth.ts +++ b/src/web/middleware/auth.ts @@ -398,8 +398,13 @@ export function isLostWebviewRootFrame(req: FastifyRequest): boolean { * sign-in, so the refusal below must recognise every such spelling, not only the literal * one Codeman's own routes use. Any token shape counts: a malformed token is still a * request the proxy let through. + * + * `rawUrl` has been through `stripBasePath()`, which removes the mount prefix only in its + * literal spelling, so under `basePath` a re-spelled prefix (`/CODEMAN/webview/x`, + * `/%63odeman/...`, `//codeman/...`, `/x/../codeman/...`) is still in front. After the + * normalisation, the lower-cased base path is removed once when the path starts with it. */ -export function capabilityPrefixOf(rawUrl: string): 'webview' | 'html-view' | null { +export function capabilityPrefixOf(rawUrl: string, basePath = ''): 'webview' | 'html-view' | null { let path = rawUrl.split('?')[0]; try { path = decodeURIComponent(path); @@ -413,6 +418,8 @@ export function capabilityPrefixOf(rawUrl: string): 'webview' | 'html-view' | nu .normalize(path) .replace(/\u0130/g, 'i') .toLowerCase(); + const base = basePath.toLowerCase(); + if (base && path.startsWith(`${base}/`)) path = path.slice(base.length); if (path.startsWith(`${WEBVIEW_PROXY_PREFIX}/`)) return 'webview'; if (path.startsWith(`${HTML_VIEW_PREFIX}/`)) return 'html-view'; return null; @@ -436,8 +443,8 @@ export function capabilityPrefixOf(rawUrl: string): 'webview' | 'html-view' | nu * * @returns true when the reply was sent. */ -function serveRefusedCapabilityPath(req: FastifyRequest, reply: FastifyReply): boolean { - const kind = capabilityPrefixOf(req.url ?? ''); +function serveRefusedCapabilityPath(req: FastifyRequest, reply: FastifyReply, basePath = ''): boolean { + const kind = capabilityPrefixOf(req.url ?? '', basePath); if (kind === 'webview') { reply.code(403).type('text/plain').send('Forbidden: unknown or expired webview capability'); return true; @@ -847,7 +854,7 @@ function registerMultiUserAuthHook( if (serveLostWebviewFrame(req, reply)) return; // Behind an authenticating proxy, capability paths reach Codeman without the proxy's // sign-in: refuse a non-exempt one with the route's own answer, no challenge, no count. - if (trustedProxy && serveRefusedCapabilityPath(req, reply)) return; + if (trustedProxy && serveRefusedCapabilityPath(req, reply, basePath)) return; // 0. Trusted reverse-proxy identity, checked BEFORE the cookie: when the proxy // vouches for a person on this request, that is authoritative, and a stale cookie diff --git a/src/web/sensitive-path.ts b/src/web/sensitive-path.ts index ebc9d486..5700b5de 100644 --- a/src/web/sensitive-path.ts +++ b/src/web/sensitive-path.ts @@ -33,9 +33,8 @@ */ import { homedir } from 'node:os'; -import { realpathSync } from 'node:fs'; import { join } from 'node:path'; -import { trustedProxySecretFilePath } from '../config/trusted-proxy.js'; +import { trustedProxySecretFilePath, trustedProxySecretFileRealPath } from '../config/trusted-proxy.js'; const SENSITIVE_PATTERNS: RegExp[] = [ // System account databases. @@ -162,17 +161,12 @@ const HOME_SENSITIVE_MEMBERS = ['.claude.json', '.claude/settings.json', '.claud * Whether `absPath` is the configured trusted-proxy secret file * (`CODEMAN_TRUSTED_PROXY_SECRET_FILE`, any name and location). The variable is removed * from `process.env` once the secret is read, so the path comes from the trusted-proxy - * module, which keeps it. + * module, which keeps it, as configured and with symlinks resolved (resolved once). */ function isTrustedProxySecretFile(absPath: string): boolean { const file = trustedProxySecretFilePath(); if (!file) return false; - if (absPath === file) return true; - try { - return absPath === realpathSync(file); - } catch { - return false; - } + return absPath === file || absPath === trustedProxySecretFileRealPath(); } /** diff --git a/test/sensitive-path.test.ts b/test/sensitive-path.test.ts index f215b6ff..9af3b81a 100644 --- a/test/sensitive-path.test.ts +++ b/test/sensitive-path.test.ts @@ -16,7 +16,9 @@ * feature), so the "stays attachable" cases matter just as much: over-blocking * breaks the publish skill and the review-card loop. */ -import { homedir } from 'node:os'; +import { mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { homedir, tmpdir } from 'node:os'; +import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; import { isSensitivePath } from '../src/web/sensitive-path.js'; import { initTrustedProxySecret, resetTrustedProxySecretForTests } from '../src/config/trusted-proxy.js'; @@ -262,5 +264,36 @@ describe('isSensitivePath', () => { else process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = prev; } }); + + it.skipIf(process.platform === 'win32')( + 'blocks the file under its real path when the setting names a symlink, and the other way round', + () => { + const prev = process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE; + const dir = realpathSync(mkdtempSync(join(tmpdir(), 'tp-secret-link-'))); + const real = join(dir, 'real.key'); + const link = join(dir, 'link.key'); + writeFileSync(real, 'x', { mode: 0o600 }); + symlinkSync(real, link); + try { + // The setting names the symlink; a caller resolves the served path to the target. + process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = link; + resetTrustedProxySecretForTests(); + expect(isSensitivePath(real)).toBe(true); + initTrustedProxySecret(); // resolved once here, then answered from the cache + expect(isSensitivePath(real)).toBe(true); + expect(isSensitivePath(join(dir, 'other.key'))).toBe(false); + // The setting names the target; the symlink resolves to it. + process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = real; + resetTrustedProxySecretForTests(); + initTrustedProxySecret(); + expect(isSensitivePath(realpathSync(link))).toBe(true); + } finally { + resetTrustedProxySecretForTests(); + if (prev === undefined) delete process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE; + else process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = prev; + rmSync(dir, { recursive: true, force: true }); + } + } + ); }); }); diff --git a/test/trusted-proxy-auth.test.ts b/test/trusted-proxy-auth.test.ts index 654d8b07..0b3cc0ee 100644 --- a/test/trusted-proxy-auth.test.ts +++ b/test/trusted-proxy-auth.test.ts @@ -20,7 +20,7 @@ import fastifyWebsocket from '@fastify/websocket'; import WebSocket from 'ws'; import { WebServer } from '../src/web/server.js'; import { TmuxManager } from '../src/tmux-manager.js'; -import { createUser, invalidateUsersCache, updateUser } from '../src/user-store.js'; +import { createUser, invalidateUsersCache, touchLastLogin, updateUser } from '../src/user-store.js'; import { AUTH_FAILURE_MAX } from '../src/config/auth-config.js'; import { getTrustedProxyConfig, @@ -38,6 +38,17 @@ import { getLifecycleLog } from '../src/session-lifecycle-log.js'; vi.spyOn(TmuxManager, 'isTmuxAvailable').mockReturnValue(true); +// touchLastLogin is fire-and-forget in the auth hook; wrapped so its calls can be counted. +vi.mock('../src/user-store.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, touchLastLogin: vi.fn(actual.touchLastLogin) }; +}); + +/** Wait for every last-login write started so far, so none races a test that edits users.json. */ +async function settleLastLoginWrites(): Promise { + await Promise.all(vi.mocked(touchLastLogin).mock.results.map((r) => r.value)); +} + const SECRET = 'a'.repeat(24) + 'b'.repeat(24); // 48 chars function basic(user: string, pass: string): string { @@ -253,6 +264,10 @@ describe('trusted-proxy config', () => { 'Sec-WebSocket-Key', 'X-Forwarded-For', 'X-Real-IP', + 'X-Requested-With', + 'X-HTTP-Method-Override', + 'X-CSRF-Token', + 'X-XSRF-Token', 'x-codeman-proxy-secret', 'X-Codeman-Hook-Secret', 'not a header', @@ -299,33 +314,46 @@ describe('takeTrustedProxyHeaders', () => { describe('capabilityPrefixOf judges a path the way a proxy matcher does', () => { it.each([ - ['/webview/x', 'webview'], - ['/webview/', 'webview'], - ['/webview/x?q=1', 'webview'], - [`/webview/${'a'.repeat(200)}/y`, 'webview'], - ['/webview/bad*token!/z', 'webview'], - ['/WEBVIEW/x', 'webview'], - ['/%77ebview/x', 'webview'], - ['//webview/x', 'webview'], - ['/a/../webview/x', 'webview'], - ['/html-view/x', 'html-view'], - ['/HTML-View/a/b', 'html-view'], - ['/html-view%2Fx', 'html-view'], - ['/WEBV%C4%B0EW/x', 'webview'], // U+0130 İ: Caddy's matcher folds it to "i" - ['/HTML-V%C4%B0EW/a', 'html-view'], - ['/webv%C4%B1ew/x', null], // U+0131 dotless ı: folded to "i" by neither side - ['/webview', null], - ['/webviewfoo', null], - ['/webviewfoo/x', null], - ['/html-view', null], - ['/html-viewer/x', null], - ['/', null], - ['/api/me', null], - ['/api/webviews', null], - ['/x/webview/y', null], - ['/webview/../api/me', null], - ] as const)('%s -> %s', (url, expected) => { - expect(capabilityPrefixOf(url)).toBe(expected); + ['/webview/x', '', 'webview'], + ['/webview/', '', 'webview'], + ['/webview/x?q=1', '', 'webview'], + [`/webview/${'a'.repeat(200)}/y`, '', 'webview'], + ['/webview/bad*token!/z', '', 'webview'], + ['/WEBVIEW/x', '', 'webview'], + ['/%77ebview/x', '', 'webview'], + ['//webview/x', '', 'webview'], + ['/a/../webview/x', '', 'webview'], + ['/html-view/x', '', 'html-view'], + ['/HTML-View/a/b', '', 'html-view'], + ['/html-view%2Fx', '', 'html-view'], + ['/WEBV%C4%B0EW/x', '', 'webview'], // U+0130 İ: Caddy's matcher folds it to "i" + ['/HTML-V%C4%B0EW/a', '', 'html-view'], + ['/webv%C4%B1ew/x', '', null], // U+0131 dotless ı: folded to "i" by neither side + ['/webview', '', null], + ['/webviewfoo', '', null], + ['/webviewfoo/x', '', null], + ['/html-view', '', null], + ['/html-viewer/x', '', null], + ['/', '', null], + ['/api/me', '', null], + ['/api/webviews', '', null], + ['/x/webview/y', '', null], + ['/webview/../api/me', '', null], + // Under a base path: the server strips only the literal prefix, so every other + // spelling of it still reaches the hook in front of the capability prefix. + ['/webview/x', '/codeman', 'webview'], // literal prefix, already stripped + ['/CODEMAN/webview/x', '/codeman', 'webview'], + ['/%63odeman/webview/x', '/codeman', 'webview'], + ['//codeman/webview/x', '/codeman', 'webview'], + ['/x/../codeman/webview/x', '/codeman', 'webview'], + ['/CODEMAN/html-view/x', '/codeman', 'html-view'], + ['/codeman/webview/x', '/CodeMan', 'webview'], + ['/codemanx/webview/x', '/codeman', null], + ['/other/webview/x', '/codeman', null], + ['/codeman', '/codeman', null], + ['/CODEMAN/webview/x', '', null], // root mount: no prefix to remove + ] as const)('%s under "%s" -> %s', (url, basePath, expected) => { + expect(capabilityPrefixOf(url, basePath)).toBe(expected); }); }); @@ -413,11 +441,13 @@ describe('the auth middleware strips the headers before any route sees them', () method: 'GET', url: '/echo', remoteAddress: '127.0.0.1', - headers: { 'x-codeman-proxy-secret': SECRET, 'x-forwarded-user': 'bob' }, + headers: { 'x-codeman-proxy-secret': SECRET, 'x-forwarded-user': 'bob', 'x-codeman-user': 'alice' }, }); expect(res.statusCode).toBe(200); expect(res.json().user).toBe('bob'); expect(res.json().headers['x-forwarded-user']).toBeUndefined(); + // The default header is removed too, though it is no longer read. + expect(res.json().headers['x-codeman-user']).toBeUndefined(); } finally { delete process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER; await app.close(); @@ -596,6 +626,52 @@ describe('trusted-proxy sign-in', () => { expect((await me(proxied('frank'))).status).toBe(403); }); + it('records the last login on a proxy sign-in at most every 15 minutes per user', async () => { + const app = appOf(await freshServer()); + const calls = () => vi.mocked(touchLastLogin).mock.calls.filter(([u]) => u === 'erin').length; + const before = calls(); + const realNow = Date.now(); + const nowSpy = vi.spyOn(Date, 'now'); + try { + for (const [minutes, expected] of [ + [0, 1], + [14, 1], + [15, 2], + ] as const) { + nowSpy.mockReturnValue(realNow + minutes * 60_000); + expect((await injectMe(app, '127.0.0.1', proxied('erin'))).statusCode).toBe(200); + expect(calls(), `after ${minutes} min`).toBe(before + expected); + } + } finally { + nowSpy.mockRestore(); + } + }); + + it('answers 503 when the user store is unreadable, without falling back to a cookie or Basic', async () => { + const app = appOf(await freshServer()); + const login = await injectMe(app, '127.0.0.1', { authorization: basic('bob', 'bobpass123') }); + const token = /codeman_session=([^;]+)/.exec(String(login.headers['set-cookie']))![1]; + await settleLastLoginWrites(); + const usersFile = path.join(dataDir, 'users.json'); + const original = await fs.readFile(usersFile, 'utf-8'); + try { + await fs.writeFile(usersFile, '{ not json'); + invalidateUsersCache(); + const withCredentials: Record[] = [ + { cookie: `codeman_session=${token}` }, + { authorization: basic('bob', 'bobpass123') }, + ]; + for (const extra of withCredentials) { + const res = await injectMe(app, '127.0.0.1', proxied('alice', SECRET, extra)); + expect(res.statusCode, Object.keys(extra)[0]).toBe(503); + expect(res.body).toMatch(/user store unreadable/); + } + } finally { + await fs.writeFile(usersFile, original); + invalidateUsersCache(); + } + }); + it('does not apply the mustChangePassword lockbox to a proxy sign-in', async () => { const res = await fetch(url('/api/sessions'), { headers: proxied('dave') }); expect(res.status).toBe(200); @@ -839,7 +915,68 @@ describe('terminal WebSocket through a proxy sign-in is owner-scoped', () => { }); }); +describe('under a base path, every spelling of the mount prefix is refused like the literal one', () => { + /** GET with the path sent exactly as written (fetch would normalise it). */ + function rawGet(port: number, rawPath: string, headers: Record = {}) { + return new Promise<{ status: number; challenge: string | undefined }>((resolve, reject) => { + const req = http.request( + { host: '127.0.0.1', port, path: rawPath, headers: { host: `localhost:${port}`, ...headers } }, + (res) => { + res.resume(); + res.on('end', () => + resolve({ status: res.statusCode ?? 0, challenge: res.headers['www-authenticate'] as string | undefined }) + ); + } + ); + req.on('error', reject); + req.end(); + }); + } + + it('answers each with the route refusal, no challenge and no count, so Basic still signs in', async () => { + useSecret({ inline: SECRET }); + const s = new WebServer(0, false, true, '127.0.0.1', undefined, false, '/codeman'); + await s.start(); + extraServers.push(s); + const port = s.boundPort; + const cases = [ + ['/CODEMAN/webview/x', 403], + ['/%63odeman/webview/x', 403], + ['//codeman/webview/x', 403], + ['/x/../codeman/webview/x', 403], + ['/CODEMAN/html-view/x', 404], + ] as const; + for (let i = 0; i < 60; i++) { + const [rawPath, status] = cases[i % cases.length]; + const res = await rawGet(port, rawPath); + expect(res.status, rawPath).toBe(status); + expect(res.challenge, rawPath).toBeUndefined(); + } + const ok = await rawGet(port, '/codeman/api/me', { authorization: basic('bob', 'bobpass123') }); + expect(ok.status).toBe(200); + }); +}); + describe('trusted-proxy sign-in is off without its preconditions', () => { + it('keeps the normal challenge for capability paths', async () => { + useSecret(); + try { + const app = appOf(await freshServer()); + for (const url of ['/webview/x', `/html-view/${'A'.repeat(24)}/index.html`]) { + const res = await app.inject({ + method: 'GET', + url, + remoteAddress: '127.0.0.1', + headers: { host: 'localhost' }, + }); + expect(res.statusCode, url).toBe(401); + expect(res.headers['www-authenticate'], url).toMatch(/Basic/); + } + } finally { + useSecret({ inline: SECRET }); + } + }); + it('ignores the headers when no secret is configured', async () => { useSecret(); try {