fix(auth): refuse capability paths under any spelling of the base path

Under CODEMAN_BASE_URL the server strips the mount prefix only in its
literal spelling, so /CODEMAN/webview/x, /%63odeman/webview/x,
//codeman/webview/x or /x/../codeman/webview/x reached the credential
checks with the prefix still in front. A proxy's path matcher lets
those through without its sign-in, so they got a Basic challenge and
filled the per-IP failure bucket. capabilityPrefixOf() now takes the
base path and, after its normalisation, removes the lower-cased base
path once when the path starts with it. The exemptions are unchanged.

The secret file's real path is now resolved once, when the secret is
read, instead of on every sensitive-path check.

Tests for behaviour that had none: the last-login throttle for proxy
sign-ins, the 503 for an unreadable user store with a valid cookie or
Basic credentials, removal of X-Codeman-User when another username
header is configured, the normal challenge on capability paths with
the feature off, the secret file reached through a symlink, and the
reserved username header names.
This commit is contained in:
13768039+zomby1 committed 2026-11-25 09:36:56 +01:00
1 parent 8480bba908
commit 3658dc516f
5 files changed
+239 -46

No files matched your search

+25 -3
View File
@@ -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;
+11 -4
View File
@@ -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
+3 -9
View File
@@ -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();
}
/**