mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-12-05 01:29:32 +01:00
fix(auth): the review items of #854 that go on top
- The strip removed the proxy headers from req.headers only, while req.raw.rawHeaders and req.raw.headersDistinct still held the secret. takeTrustedProxyHeaders() now takes the raw message and removes them from both. A plain splice is not enough on a real IncomingMessage: its headers and headersDistinct getters are lazy and walk rawHeaders up to the count stored at parse time, so one that first runs after the splice throws. Both are read (cached) first. Two tests, each caught by its mutation: the stripping test checks the raw list, and a real http request checks all three views and that the getters still answer. - CLAUDE.md's Rate limit row names the trusted-proxy secret's own bucket. - The wiki lists the loopback addresses the check accepts, as the contributor offered. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a117955490
commit
4be36b0404
6 files changed
+113
-8
No files matched your search
@@ -303,7 +303,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin
|
||||
| **CSRF / Origin** | Always-on cross-site Origin guard on state-changing requests. **A missing Origin is allowed** so curl/CLI and hooks keep working. ⚠️ The body parser keeps `text/plain` RAW; auto-JSON-parsing it enabled simple-request CSRF |
|
||||
| **QR Auth** | Single-use 6-char tokens (60s TTL) for tunnel login. See `docs/qr-auth-plan.md` |
|
||||
| **Sessions** | 24h cookie (`codeman_session`), auto-extend, device context audit |
|
||||
| **Rate limit** | 10 failed auth/IP → 429 (15min decay). Multi-user mode instead checks 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) BEFORE the password, so past either even a correct password from that IP waits (the account still logs in from another IP), plus 10 per username AFTER it (429 to wrong guesses from any IP, never to a correct password). A request with NO `Authorization` header (or an empty one, which carries no guess either) is never counted and always gets the 401 challenge (a 429 never re-prompts a browser); a malformed one is counted. QR and hook-secret have separate buckets, so neither can lock out login |
|
||||
| **Rate limit** | 10 failed auth/IP → 429 (15min decay). Multi-user mode instead checks 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) BEFORE the password, so past either even a correct password from that IP waits (the account still logs in from another IP), plus 10 per username AFTER it (429 to wrong guesses from any IP, never to a correct password). A request with NO `Authorization` header (or an empty one, which carries no guess either) is never counted and always gets the 401 challenge (a 429 never re-prompts a browser); a malformed one is counted. QR, hook-secret and the trusted-proxy secret (multi-user, opt-in) have separate buckets, so none of them can lock out login |
|
||||
| **Hook bypass** | `/api/hook-event` + `/api/status-telemetry` skip Basic auth (localhost-only, schema-validated), but when auth is active the loopback bypass requires `X-Codeman-Hook-Secret` **unconditionally** (Codeman cannot detect a user's own loopback reverse proxy) |
|
||||
| **Lost-frame page** | The THIRD unauthenticated 200, beside the two hook routes, and the only one decided by request headers alone: a `GET`/`HEAD` carrying `Sec-Fetch-Dest: iframe\|frame`, `Accept: text/html` and mode `navigate` (or none), for a path that is NOT a registered route (never `/api/`, `/ws/`, `/q/`), is answered BEFORE the credential checks with the static web-tab recovery page (`lostWebviewFramePage`: no reflected input, `default-src 'none'` plus its own script hash, `no-store`). `/` is the one registered route also admitted, only when the request carries neither `codeman_session` nor `Authorization` (nothing in Codeman frames its own root; a sandboxed frame has neither), since the landing page masks to exactly `/` and its reload otherwise rendered Codeman inside the web tab. ⚠️ A non-browser client can set those headers, so an unauthenticated caller can tell a registered route (401) from a non-route (200) and enumerate the route table; accepted, the routes are public in `docs/api-reference.md`. Pinned by `test/webview-auth-exemption.test.ts` + `test/webview-lost-root-frame.test.ts` |
|
||||
| **Tunnel** | Enabling a tunnel **refuses** without a login (`CODEMAN_PASSWORD` or multi-user mode) unless exposure is acknowledged via `CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL=1` / `--allow-unauthenticated-tunnel` or the per-request `acknowledgeUnauthTunnel:true` action field (never persisted). `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK` acknowledges the BIND only and never satisfies this guard (#706: `install.sh` writes it for every passwordless LAN install). The authorization is decided ONCE per request, running or not, and required again at the `start()` site: the settings-file awaits between them let a concurrent stop land, and an unauthorized enable never writes `tunnelEnabled:true`. With no login the browser asks before every enable (welcome link, tunnel panel, App Settings save that turns it on) through ONE helper, `_confirmTunnelEnable()` (settings-ui.js), which reads `loginConfigured` from `GET /api/tunnel/status` (computed in the route by the guard's own test, never in `TunnelManager`); the 403 handler is the fallback when that read fails |
|
||||
|
||||
@@ -660,7 +660,9 @@ peer (§3).
|
||||
loopback paths cannot drift apart.
|
||||
- **The headers never travel further.** The first auth hook, right after the Host guard
|
||||
and in every auth mode, reads both headers and deletes them from the request, before
|
||||
any exemption (QR, web‑tab and HTML‑view capabilities) or route runs. So the web‑tab
|
||||
any exemption (QR, web‑tab and HTML‑view capabilities) or route runs. They go from all
|
||||
three views Node keeps of a request: `headers`, the raw `rawHeaders` list and
|
||||
`headersDistinct`. So the web‑tab
|
||||
relay cannot forward the secret to a dashboard (as a second layer the relay also drops both default names and
|
||||
the configured username header; its WebSocket leg sends only `origin` and `cookie`).
|
||||
- **No auto‑provisioning.** The username must name an existing, enabled account, so an
|
||||
|
||||
@@ -143,8 +143,9 @@ On every request the proxy adds two headers:
|
||||
| `X-Codeman-Proxy-Secret` | the shared secret |
|
||||
| `X-Codeman-User` | the Codeman username (another name can be set with `CODEMAN_TRUSTED_PROXY_USER_HEADER`: an `X-…` header such as `X-Forwarded-User`, or `Remote-User`; standard and reserved headers are refused, because the header is removed from every request) |
|
||||
|
||||
Codeman believes them only from a loopback connection with the matching secret, so keep
|
||||
Codeman bound to `127.0.0.1` and the proxy on the same host. It removes both headers from
|
||||
Codeman believes them only from a loopback connection (`127.0.0.1`, `::1` or
|
||||
`::ffff:127.0.0.1`) with the matching secret, so keep Codeman bound to `127.0.0.1` and the
|
||||
proxy on the same host. It removes both headers from
|
||||
every request before anything else sees them. The exact rules are in
|
||||
[`docs/security-architecture.md` §10a](https://github.com/Ark0N/Codeman/blob/master/docs/security-architecture.md).
|
||||
|
||||
|
||||
@@ -255,19 +255,57 @@ export interface PresentedProxyHeaders {
|
||||
user: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The two other views Node keeps of a request's headers, beside `headers`: the flat
|
||||
* `[name, value, ...]` list as received and the per-name arrays. Both are optional
|
||||
* because a light-my-request message (`app.inject`) may lack `headersDistinct`.
|
||||
*/
|
||||
export interface RawHeaderViews {
|
||||
headers?: IncomingHttpHeaders;
|
||||
rawHeaders?: string[];
|
||||
headersDistinct?: NodeJS.Dict<string[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove `names` (lowercase) from `raw.rawHeaders` and `raw.headersDistinct`, in place.
|
||||
*
|
||||
* ⚠️ Order matters on a real `http.IncomingMessage`: its `headers` and `headersDistinct`
|
||||
* getters are LAZY and walk `rawHeaders` up to a header count stored when the request was
|
||||
* parsed, so a getter that first runs after a splice reads past the shortened array and
|
||||
* throws. Both are therefore read (and so cached) BEFORE `rawHeaders` shrinks, and later
|
||||
* reads return the cached, already stripped objects.
|
||||
*/
|
||||
function stripRawHeaderViews(raw: RawHeaderViews, names: readonly string[]): void {
|
||||
void raw.headers;
|
||||
const distinct = raw.headersDistinct;
|
||||
if (distinct && typeof distinct === 'object') {
|
||||
for (const name of names) delete distinct[name];
|
||||
}
|
||||
const list = raw.rawHeaders;
|
||||
if (!Array.isArray(list)) return;
|
||||
for (let i = list.length - 2; i >= 0; i -= 2) {
|
||||
const name = list[i];
|
||||
if (typeof name === 'string' && names.includes(name.toLowerCase())) list.splice(i, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the trusted-proxy headers and DELETE them from `headers`, so nothing that later
|
||||
* copies request headers (the web-tab relay, logging) ever sees the secret. Removes the
|
||||
* secret header, the default username header and `userHeader` (from
|
||||
* `resolveTrustedProxyUserHeader`, so always a usable name), whether or not the feature is
|
||||
* on: a proxy may send them to an instance that has it off.
|
||||
* on: a proxy may send them to an instance that has it off. Given the raw message (`raw`,
|
||||
* the auth hook passes `req.raw`), it removes them from `rawHeaders` and `headersDistinct`
|
||||
* too, so no view of the request still holds the secret.
|
||||
*/
|
||||
export function takeTrustedProxyHeaders(
|
||||
headers: IncomingHttpHeaders,
|
||||
userHeader: string = DEFAULT_TRUSTED_PROXY_USER_HEADER
|
||||
userHeader: string = DEFAULT_TRUSTED_PROXY_USER_HEADER,
|
||||
raw?: RawHeaderViews
|
||||
): PresentedProxyHeaders {
|
||||
const rawSecret = headers[TRUSTED_PROXY_SECRET_HEADER];
|
||||
const rawUser = headers[userHeader];
|
||||
if (raw) stripRawHeaderViews(raw, [TRUSTED_PROXY_SECRET_HEADER, DEFAULT_TRUSTED_PROXY_USER_HEADER, userHeader]);
|
||||
delete headers[TRUSTED_PROXY_SECRET_HEADER];
|
||||
delete headers[DEFAULT_TRUSTED_PROXY_USER_HEADER];
|
||||
delete headers[userHeader];
|
||||
|
||||
@@ -181,7 +181,7 @@ const PROXY_LAST_LOGIN_INTERVAL_MS = 15 * 60 * 1000;
|
||||
function registerTrustedProxyHeaderStrip(app: FastifyInstance): void {
|
||||
const userHeader = resolveTrustedProxyUserHeader();
|
||||
app.addHook('onRequest', (req, _reply, done) => {
|
||||
presentedProxyHeaders.set(req, takeTrustedProxyHeaders(req.headers, userHeader));
|
||||
presentedProxyHeaders.set(req, takeTrustedProxyHeaders(req.headers, userHeader, req.raw));
|
||||
done();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -310,6 +310,61 @@ describe('takeTrustedProxyHeaders', () => {
|
||||
expect(takeTrustedProxyHeaders({ 'x-codeman-user': ['alice', 'bob'] }).user).toBe('alice, bob');
|
||||
expect(takeTrustedProxyHeaders({ accept: '*/*' })).toEqual({ secretPresent: false, secret: '', user: '' });
|
||||
});
|
||||
|
||||
it('removes them from the raw message too: rawHeaders and headersDistinct, on a real request', async () => {
|
||||
let seen: { raw: string[]; distinct: Record<string, string[]>; headers: Record<string, unknown> } | null = null;
|
||||
let failure: unknown = null;
|
||||
const server = http.createServer((req, res) => {
|
||||
try {
|
||||
takeTrustedProxyHeaders(req.headers, 'x-forwarded-user', req);
|
||||
// Read the lazy getters AFTER the splice: they must answer from their cache, not
|
||||
// walk the shortened rawHeaders with the count stored at parse time (that throws).
|
||||
seen = { raw: [...req.rawHeaders], distinct: { ...req.headersDistinct }, headers: { ...req.headers } };
|
||||
} catch (err) {
|
||||
failure = err;
|
||||
}
|
||||
res.end();
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
try {
|
||||
const { port } = server.address() as AddressInfo;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const req = http.get(
|
||||
{
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
path: '/',
|
||||
headers: {
|
||||
'X-Codeman-Proxy-Secret': SECRET,
|
||||
'X-Codeman-User': 'alice',
|
||||
'X-Forwarded-User': 'bob',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
res.resume();
|
||||
res.on('end', resolve);
|
||||
}
|
||||
);
|
||||
req.on('error', reject);
|
||||
});
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
expect(failure).toBeNull();
|
||||
const result = seen!;
|
||||
const rawNames = result.raw.filter((_, i) => i % 2 === 0).map((name) => name.toLowerCase());
|
||||
for (const name of ['x-codeman-proxy-secret', 'x-codeman-user', 'x-forwarded-user']) {
|
||||
expect(rawNames).not.toContain(name);
|
||||
expect(result.distinct[name]).toBeUndefined();
|
||||
expect(result.headers[name]).toBeUndefined();
|
||||
}
|
||||
expect(result.raw).not.toContain(SECRET);
|
||||
// Everything else is left as it was, in all three views.
|
||||
expect(rawNames).toContain('accept');
|
||||
expect(result.distinct.accept).toEqual(['*/*']);
|
||||
expect(result.headers.accept).toBe('*/*');
|
||||
});
|
||||
});
|
||||
|
||||
describe('capabilityPrefixOf judges a path the way a proxy matcher does', () => {
|
||||
@@ -413,7 +468,11 @@ describe('the auth middleware strips the headers before any route sees them', ()
|
||||
const app = Fastify();
|
||||
await app.register(fastifyCookie);
|
||||
registerAuthMiddleware(app, false);
|
||||
app.get('/echo', async (req) => ({ headers: req.headers, user: req.authUser?.username ?? null }));
|
||||
app.get('/echo', async (req) => ({
|
||||
headers: req.headers,
|
||||
rawHeaders: req.raw.rawHeaders,
|
||||
user: req.authUser?.username ?? null,
|
||||
}));
|
||||
app.post('/echo', async (req) => ({ headers: req.headers, body: req.body }));
|
||||
await app.ready();
|
||||
return app;
|
||||
@@ -434,6 +493,11 @@ describe('the auth middleware strips the headers before any route sees them', ()
|
||||
expect(body.user).toBe('bob');
|
||||
expect(body.headers['x-codeman-proxy-secret']).toBeUndefined();
|
||||
expect(body.headers['x-codeman-user']).toBeUndefined();
|
||||
// Not in the raw list either (section 10a: the headers travel no further).
|
||||
const rawNames = (body.rawHeaders as string[]).filter((_, i) => i % 2 === 0).map((n) => n.toLowerCase());
|
||||
expect(rawNames).not.toContain('x-codeman-proxy-secret');
|
||||
expect(rawNames).not.toContain('x-codeman-user');
|
||||
expect(body.rawHeaders).not.toContain(SECRET);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user