From 363de086fce46b8bc8925c508cee70f75f3db84e Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Wed, 18 Nov 2026 17:33:53 +0100 Subject: [PATCH 1/4] fix(auth): stop counting credential-less requests as failed logins After a server restart every cookie session is gone (they live in memory). An open tab's background requests then carry only the dead cookie and no Authorization header. Each one was counted as a failed login: ten filled the single-user per-IP bucket within seconds, and the 429 that followed carries no WWW-Authenticate challenge, so the browser never showed its login dialog again and reloading could not recover for 15 minutes. Behind a tunnel all clients share 127.0.0.1, so every device was locked out. Multi-user mode had the same shape against its per-IP pre-gate, which refuses even a correct password once full. A request with no Authorization header is not a guess and runs no password check, so it is now challenged with a plain 401 and not counted, in both modes and even while the IP is limited. Wrong and malformed credentials are counted and limited exactly as before. Co-Authored-By: Claude Opus 5.5 --- src/web/middleware/auth.ts | 29 ++++++++++++++++++++++++++--- test/auth-security.test.ts | 28 ++++++++++++++++++++++++++++ test/multiuser-auth.test.ts | 23 ++++++++++++++++++++++- 3 files changed, 76 insertions(+), 4 deletions(-) diff --git a/src/web/middleware/auth.ts b/src/web/middleware/auth.ts index ea7c7767..e1c0bcad 100644 --- a/src/web/middleware/auth.ts +++ b/src/web/middleware/auth.ts @@ -66,6 +66,12 @@ function sendAuthRateLimit(reply: FastifyReply, failures: StaleExpirationMap= AUTH_FAILURE_MAX) { @@ -703,6 +719,14 @@ function registerMultiUserAuthHook( // which is every reload after a restart: cookie sessions live in memory, so the // browser replays its cached Basic header on many parallel requests at once. A // request with no verify in flight for its credentials is gated as normal. + // No Authorization header at all is not a guess and runs no scrypt: challenge it + // before the gates, without counting. Counting it let an open tab's background + // requests after a restart (cookie sessions live in memory) fill the per-IP bucket, + // which then refused even the correct password, and a 429 never re-prompts a browser. + if (!req.headers.authorization) { + challengeBasicAuth(reply); + return; + } const creds = parseBasicAuth(req.headers.authorization); const normUser = creds ? creds.username.trim().toLowerCase() : ''; const flightKey = creds ? verifyFlightKey(clientIp, normUser, creds.password) : ''; @@ -746,10 +770,9 @@ function registerMultiUserAuthHook( return; } - // No credentials presented: count against the per-IP bucket and challenge. + // A malformed Authorization header: count against the per-IP bucket and challenge. authFailures.set(clientIp, ipFail + 1); - reply.header('WWW-Authenticate', 'Basic realm="Codeman"'); - reply.code(401).send('Unauthorized'); + challengeBasicAuth(reply); }); } diff --git a/test/auth-security.test.ts b/test/auth-security.test.ts index 712bd5f5..83dd208d 100644 --- a/test/auth-security.test.ts +++ b/test/auth-security.test.ts @@ -244,6 +244,34 @@ describe('Auth Security', () => { expect(wrongAfterRecovery.status).toBe(401); }); + + it('should not count requests without credentials (restart with a tab open)', async () => { + // After a restart the open tab's background requests carry only a dead cookie. + for (let i = 0; i < AUTH_FAILURE_MAX * 3; i++) { + const res = await fetch(`${rateBaseUrl}/api/status`, { + headers: { Cookie: 'codeman_session=stale-from-before-restart' }, + }); + expect(res.status).toBe(401); + expect(res.headers.get('www-authenticate')).toBe('Basic realm="Codeman"'); + } + + // None of them were guesses: the wrong-password bucket is still empty. + await exhaustAuthFailures(rateBaseUrl, 'cod-no-creds'); + }); + + it('should keep challenging requests without credentials during lockout', async () => { + await exhaustAuthFailures(rateBaseUrl, 'cod-challenge'); + + // A 429 never makes a browser show its login dialog; a 401 challenge does. + const res = await fetch(`${rateBaseUrl}/api/status`); + expect(res.status).toBe(401); + expect(res.headers.get('www-authenticate')).toBe('Basic realm="Codeman"'); + + const wrong = await fetch(`${rateBaseUrl}/api/status`, { + headers: { Authorization: basicAuthHeader(TEST_USER, 'still-wrong') }, + }); + expect(wrong.status).toBe(429); + }); }); describe('Hook Event Endpoint', () => { diff --git a/test/multiuser-auth.test.ts b/test/multiuser-auth.test.ts index 196e779e..e73c8309 100644 --- a/test/multiuser-auth.test.ts +++ b/test/multiuser-auth.test.ts @@ -112,7 +112,7 @@ async function startIpServer() { const app = (s as unknown as { app: FastifyInstance }).app; const login = (ip: string, user: string, pass: string) => app.inject({ method: 'GET', url: '/api/status', headers: { authorization: basic(user, pass) }, remoteAddress: ip }); - return { login, buckets: s as unknown as FailureBuckets }; + return { app, login, buckets: s as unknown as FailureBuckets }; } describe('multi-user auth', () => { @@ -270,6 +270,27 @@ describe('multi-user auth', () => { expect((await login(ipA, 'bob', 'bobpass123')).statusCode).toBe(429); }); + it('requests without credentials are challenged, not counted, even past the per-IP cap', async () => { + const { app, login, buckets } = await startIpServer(); + const ip = '203.0.113.40'; + const bare = () => + app.inject({ + method: 'GET', + url: '/api/status', + headers: { cookie: 'codeman_session=stale-from-before-restart' }, + remoteAddress: ip, + }); + + // An open tab after a restart: many cookie-only requests, none of them a guess. + for (let i = 0; i < AUTH_IP_FAILURE_MAX + 5; i++) { + const res = await bare(); + expect(res.statusCode, `request ${i + 1}`).toBe(401); + expect(res.headers['www-authenticate']).toBe('Basic realm="Codeman"'); + } + expect(buckets.authFailures.get(ip)).toBeUndefined(); + expect((await login(ip, 'alice', 'alicepass1')).statusCode).toBe(200); + }); + it('per-IP pre-gate: a concurrent burst from one IP reaches the verify at most AUTH_IP_FAILURE_MAX times', async () => { const { login, buckets } = await startIpServer(); const ip = '203.0.113.40'; From ad08cb957dc030039754ca9bde286029962b60ba Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Fri, 20 Nov 2026 20:36:03 +0100 Subject: [PATCH 2/4] test(auth): malformed headers still fill the bucket; document the challenge Review on #838. The unchanged half had no test: send the cap's worth of `Authorization: Bearer x` and expect the next request to be 429, in single-user and multi-user mode. Both fail if the header-less skip is widened to malformed headers. docs/security-architecture.md gets a pipeline step for the header-less challenge (not counted, even during a lockout), and the Rate limit rows in CLAUDE.md and docs/architecture-invariants.md say so, so a later change cannot bring the counting back unnoticed. auth.ts uses challengeBasicAuth() at the two spots that still inlined it, with a blank comment line before the new paragraph. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/architecture-invariants.md | 2 +- docs/security-architecture.md | 18 +++++++++++++----- src/web/middleware/auth.ts | 7 +++---- test/auth-security.test.ts | 15 +++++++++++++++ test/multiuser-auth.test.ts | 13 +++++++++++++ 6 files changed, 46 insertions(+), 11 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 9472b727..60222edd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -301,7 +301,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). 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 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 | | **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 | diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index e17a089b..8f965656 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -1353,7 +1353,7 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u | **CSRF / Origin** | Always-on cross-site Origin guard rejects state-changing requests from foreign origins (covers self-update, session create/input, settings/tunnel toggles). **A missing Origin is allowed** so curl/CLI and Claude Code hooks keep working. The global body parser keeps `text/plain` RAW (no auto-JSON-parse, which had enabled simple-request CSRF); `/api/crash-diag` self-parses. WebSocket upgrade validates Origin+Host (anti-CSWSH) in `ws-routes.ts`. Added in `c669518` (closes 2026-06-09 review CRITICALs) | | **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 logins/IP → 429 (15min decay). Multi-user mode instead has two gates checked before scrypt, so past either even a correct password from that IP gets 429: 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) (`AUTH_FAILURE_MAX`; the same account still logs in from another IP). A 10-per-username bucket (multi-user only) is checked after the verify: 429 to failed guesses from the 10th on, from any IP, never to a correct password. QR has separate limiter | +| **Rate limit** | 10 failed logins/IP → 429 (15min decay). Multi-user mode instead has two gates checked before scrypt, so past either even a correct password from that IP gets 429: 50/IP (`AUTH_IP_FAILURE_MAX`) and 10 per (username, IP) (`AUTH_FAILURE_MAX`; the same account still logs in from another IP). A 10-per-username bucket (multi-user only) is checked after the verify: 429 to failed guesses from the 10th on, from any IP, never to a correct password. A request with NO `Authorization` header is never counted and always gets the 401 challenge, since a 429 never re-prompts a browser; a malformed one is counted. QR has separate limiter | | **Hook bypass** | `/api/hook-event` (and `/api/status-telemetry`, the statusLine exporter) skip Basic auth (localhost-only, schema-validated). When auth is active (`CODEMAN_PASSWORD` set), the loopback bypass requires the per-instance `X-Codeman-Hook-Secret` header **unconditionally** — COD-54 introduced it tunnel-gated; COD-91 (PR #127) made it always-on because Codeman can't detect a user's own loopback reverse proxy (own cloudflared/`tailscale serve`/nginx → 127.0.0.1), closing that residual plain-bypass gap. Hook curls cat the secret file at exec time via `$CODEMAN_HOOK_SECRET_FILE` (session env, `config/hook-secret.ts`); a missing/wrong secret gets 401 and rate-limits in a dedicated bucket (never locks out login). Tunnel enable **refuses** without a login (`CODEMAN_PASSWORD` or multi-user mode) unless exposure is acknowledged — via `CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL=1` / `--allow-unauthenticated-tunnel` (#706; until then the guard took `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK=1`, COD-55, which `install.sh` writes for every passwordless LAN install, so the bind acknowledgement silently published the tunnel too) **or** the per-request `acknowledgeUnauthTunnel:true` action field (1.1.9). With no login the browser asks BEFORE every enable (welcome link, tunnel panel, an App Settings save that turns it on) through `_confirmTunnelEnable()`, reading `loginConfigured` from `GET /api/tunnel/status`, and on confirm sends that flag; the 403 handler stays the fallback when the status read fails (server logs a loud warning on every passwordless tunnel start; curl/API stay refused without password/env/flag). The flag is an action field, never persisted | | **Env vars** | `CODEMAN_MUX` (managed session), `CODEMAN_API_URL` (auto-set for hooks), `CODEMAN_ALLOWED_HOSTS` (extra Host/Origin allowlist entries for reverse proxies, comma-separated; bare `.suffix` matches subdomains), `CODEMAN_DOCKER_BRIDGE_HOOKS`=1 (opt-in hooks-only listener on the docker bridge gateway so in-container hooks reach a loopback-bound server; bind IP from `CODEMAN_DOCKER_BRIDGE_HOST` or auto-detect) | | **Validation** | Zod schemas, Unicode-aware path allowlist regex, env prefix allowlist (`CLAUDE_CODE_*`/`OPENCODE_*`/`CODEX_*`/`GEMINI_*`/`GOOGLE_*`/`ANTIGRAVITY_*`/`PI_*`) | diff --git a/docs/security-architecture.md b/docs/security-architecture.md index f97ee389..2c331428 100644 --- a/docs/security-architecture.md +++ b/docs/security-architecture.md @@ -136,11 +136,19 @@ loopback bind matters. The auth pipeline (`src/web/middleware/auth.ts`, so misfiring hooks can never lock out the login path. 2. **Session cookie** check — a valid `codeman_session` cookie short‑circuits to allow. -3. **HTTP Basic** check — correct credentials short‑circuit to allow and clear +3. **No `Authorization` header** — return `401` with the `WWW-Authenticate` + challenge, **without counting it** and even while the IP is locked out (both + modes; in multi-user mode this comes before the pre-verify gates). Such a + request is no guess and runs no password check. Counting it let an open tab's + background requests after a restart (cookie sessions live in memory) fill the + bucket in seconds, and a `429` carries no challenge, so the browser never showed + its login dialog again. +4. **HTTP Basic** check — correct credentials short‑circuit to allow and clear that IP's failure counter. -4. **Rate‑limit gate** — if neither cookie nor credentials passed and the IP is - locked out, return `429` with a `Retry-After` header. -5. Otherwise return `401`, incrementing the IP's failure counter. +5. **Rate‑limit gate** — if the credentials did not pass and the IP is locked + out, return `429` with a `Retry-After` header. +6. Otherwise (wrong credentials, or an `Authorization` header that is not valid + Basic) return `401`, incrementing the IP's failure counter. ### Session cookies @@ -154,7 +162,7 @@ by presence in a server‑side map, so they cannot be forged offline. Failed logins are tracked **per IP**: 10 failures (`AUTH_FAILURE_MAX`) → `429`, with a 15‑minute decay. Multi-user mode replaces that with three buckets, all with the same decay: a wider per-IP **pre-gate** of 50 failures (`AUTH_IP_FAILURE_MAX`), checked before the scrypt verify, which bounds scrypt cost from one source and tolerates many users behind one egress IP; a **per-(username, IP)** gate of 10 failures (`AUTH_FAILURE_MAX`), also checked before the verify, which is what caps verified guesses against one account from one source; and a **per-username** bucket, checked after the verify, that answers `429` to failed guesses from the 10th on, from any IP (the count is incremented before the check). The last two exist in multi-user mode only. So the wider per-IP cap does not widen guessing against any one account from one IP, and other IPs cannot lock an account out. The QR path has its own separate limiter. -The lockout check sits **after** the cookie/credential checks (step 4, not first). +The lockout check sits **after** the cookie/credential checks (step 5, not first). This is deliberate: a user with a **valid cookie or correct password recovers immediately** even while an attacker is hammering the same IP — important because all traffic through a tunnel shares one source IP (loopback). Wrong credentials diff --git a/src/web/middleware/auth.ts b/src/web/middleware/auth.ts index e1c0bcad..7f3018c8 100644 --- a/src/web/middleware/auth.ts +++ b/src/web/middleware/auth.ts @@ -511,8 +511,7 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas // Auth failed — track failure count authFailures.set(clientIp, failures + 1); - reply.header('WWW-Authenticate', 'Basic realm="Codeman"'); - reply.code(401).send('Unauthorized'); + challengeBasicAuth(reply); }); return state; @@ -638,8 +637,7 @@ function registerMultiUserAuthHook( sendAuthRateLimit(reply, userFailures, normUser); return; } - reply.header('WWW-Authenticate', 'Basic realm="Codeman"'); - reply.code(401).send('Unauthorized'); + challengeBasicAuth(reply); }; app.addHook('onRequest', async (req, reply) => { @@ -719,6 +717,7 @@ function registerMultiUserAuthHook( // which is every reload after a restart: cookie sessions live in memory, so the // browser replays its cached Basic header on many parallel requests at once. A // request with no verify in flight for its credentials is gated as normal. + // // No Authorization header at all is not a guess and runs no scrypt: challenge it // before the gates, without counting. Counting it let an open tab's background // requests after a restart (cookie sessions live in memory) fill the per-IP bucket, diff --git a/test/auth-security.test.ts b/test/auth-security.test.ts index 83dd208d..1f36deb1 100644 --- a/test/auth-security.test.ts +++ b/test/auth-security.test.ts @@ -272,6 +272,21 @@ describe('Auth Security', () => { }); expect(wrong.status).toBe(429); }); + + it('should still count malformed authorization headers and rate-limit them', async () => { + // The other side of the line: a header that is present but not valid Basic + // is a failed login, counted like a wrong password. + for (let i = 0; i < AUTH_FAILURE_MAX; i++) { + const res = await fetch(`${rateBaseUrl}/api/status`, { + headers: { Authorization: 'Bearer x' }, + }); + expect(res.status, `request ${i + 1}`).toBe(401); + } + const res = await fetch(`${rateBaseUrl}/api/status`, { + headers: { Authorization: 'Bearer x' }, + }); + expect(res.status).toBe(429); + }); }); describe('Hook Event Endpoint', () => { diff --git a/test/multiuser-auth.test.ts b/test/multiuser-auth.test.ts index e73c8309..83492170 100644 --- a/test/multiuser-auth.test.ts +++ b/test/multiuser-auth.test.ts @@ -291,6 +291,19 @@ describe('multi-user auth', () => { expect((await login(ip, 'alice', 'alicepass1')).statusCode).toBe(200); }); + it('malformed authorization headers are still counted against the per-IP cap', async () => { + const { app } = await startIpServer(); + const ip = '203.0.113.41'; + const malformed = () => + app.inject({ method: 'GET', url: '/api/status', headers: { authorization: 'Bearer x' }, remoteAddress: ip }); + + // Present but not valid Basic: a failed login, unlike a request with no header. + for (let i = 0; i < AUTH_IP_FAILURE_MAX; i++) { + expect((await malformed()).statusCode, `request ${i + 1}`).toBe(401); + } + expect((await malformed()).statusCode).toBe(429); + }); + it('per-IP pre-gate: a concurrent burst from one IP reaches the verify at most AUTH_IP_FAILURE_MAX times', async () => { const { login, buckets } = await startIpServer(); const ip = '203.0.113.40'; From cc2b7d9c258686922c2a8f44dce6f77aacd558c7 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Sat, 21 Nov 2026 00:08:26 +0100 Subject: [PATCH 3/4] docs(auth): list the no-header step after the Basic check; changeset The pipeline list said it "runs in this order" but put the no-header challenge before the HTTP Basic check, while single-user auth.ts checks the correct password first. Swap steps 3 and 4. Note in the README and the Security / Remote-Access wiki pages that a request with no credentials is never counted, and add the patch changeset. Co-Authored-By: Claude Opus 5.5 --- .changeset/auth-no-header-not-counted.md | 5 +++++ README.md | 2 +- docs/security-architecture.md | 20 +++++++++++--------- docs/wiki/Remote-Access.md | 3 ++- docs/wiki/Security.md | 2 +- 5 files changed, 20 insertions(+), 12 deletions(-) create mode 100644 .changeset/auth-no-header-not-counted.md diff --git a/.changeset/auth-no-header-not-counted.md b/.changeset/auth-no-header-not-counted.md new file mode 100644 index 00000000..75dd0570 --- /dev/null +++ b/.changeset/auth-no-header-not-counted.md @@ -0,0 +1,5 @@ +--- +'aicodeman': patch +--- + +A request with no `Authorization` header always gets the `401` login challenge and is no longer counted as a failed login. After a server restart (cookie sessions live in memory) an open tab's background requests carry only the dead cookie; ten of them used to fill the per-IP bucket in seconds, and the `429` that followed carries no challenge, so the browser never asked for the password again and every user behind the same tunnel IP was locked out for the 15-minute decay. Wrong passwords and malformed `Authorization` headers are still counted and rate-limited as before, in both single-user and multi-user mode. diff --git a/README.md b/README.md index 2f71aec8..24cacabb 100644 --- a/README.md +++ b/README.md @@ -708,7 +708,7 @@ By default Codeman launches sessions with `--dangerously-skip-permissions`, so t - **Loopback by default** — the server binary binds `127.0.0.1`, reachable only from the same machine, so the no-password default is safe out of the box (the guided installer asks about network access and configures the binding + password for you). Binding a non-loopback host without `CODEMAN_PASSWORD` _starts but prints a loud warning_ with three concrete fixes (set a password, loopback + an authenticated tunnel, or explicitly acknowledge with `--allow-unauthenticated-network`) - **Optional auth, real sessions** — HTTP Basic via `CODEMAN_USERNAME` (default `admin`) / `CODEMAN_PASSWORD`. Success issues an opaque 256-bit `codeman_session` cookie (`randomBytes(32)`) — validated server-side, not client-signed, so it can't be forged offline (24h TTL, auto-extend, device-context audit log) -- **Per-IP rate limiting** — 10 failed attempts → `429` with `Retry-After` (15-min decay). A valid cookie or correct password recovers _immediately_ even while an attacker hammers the same IP — important because all tunnel traffic shares one loopback IP. Multi-user mode allows 50 failures per IP instead, plus 10 failed guesses per account from one IP; both are checked before the password, so past either a correct password from that IP also waits for the decay, while the account still logs in from another IP. QR auth has its own separate limiter +- **Per-IP rate limiting** — 10 failed attempts → `429` with `Retry-After` (15-min decay). A valid cookie or correct password recovers _immediately_ even while an attacker hammers the same IP — important because all tunnel traffic shares one loopback IP. Multi-user mode allows 50 failures per IP instead, plus 10 failed guesses per account from one IP; both are checked before the password, so past either a correct password from that IP also waits for the decay, while the account still logs in from another IP. A request with no credentials (an open tab after a restart) is never counted and always gets the login prompt. QR auth has its own separate limiter - **Configurable permission mode** - `--dangerously-skip-permissions` is only the default. **App Settings → Agents & CLIs → Claude → Startup Mode** can switch new sessions to Anthropic's classifier-guarded `auto` mode (low-prompt, needs Claude Code 2.1.207+), `normal` prompting, or an explicit allowed-tools list. In multi-user mode, non-granted users are forced to `auto`, and shell sessions / skip-permissions require an explicit per-user grant ### Always-on browser hardening (v0.9.5) diff --git a/docs/security-architecture.md b/docs/security-architecture.md index 2c331428..c9a3de1c 100644 --- a/docs/security-architecture.md +++ b/docs/security-architecture.md @@ -136,15 +136,16 @@ loopback bind matters. The auth pipeline (`src/web/middleware/auth.ts`, so misfiring hooks can never lock out the login path. 2. **Session cookie** check — a valid `codeman_session` cookie short‑circuits to allow. -3. **No `Authorization` header** — return `401` with the `WWW-Authenticate` - challenge, **without counting it** and even while the IP is locked out (both - modes; in multi-user mode this comes before the pre-verify gates). Such a - request is no guess and runs no password check. Counting it let an open tab's - background requests after a restart (cookie sessions live in memory) fill the - bucket in seconds, and a `429` carries no challenge, so the browser never showed - its login dialog again. -4. **HTTP Basic** check — correct credentials short‑circuit to allow and clear +3. **HTTP Basic** check — correct credentials short‑circuit to allow and clear that IP's failure counter. +4. **No `Authorization` header** — return `401` with the `WWW-Authenticate` + challenge, **without counting it** and even while the IP is locked out (both + modes; in multi-user mode this comes before the pre-verify gates and the + verify, which a missing header could never pass). Such a request is no guess + and runs no password check. Counting it let an open tab's background requests + after a restart (cookie sessions live in memory) fill the bucket in seconds, + and a `429` carries no challenge, so the browser never showed its login dialog + again. 5. **Rate‑limit gate** — if the credentials did not pass and the IP is locked out, return `429` with a `Retry-After` header. 6. Otherwise (wrong credentials, or an `Authorization` header that is not valid @@ -160,7 +161,8 @@ by presence in a server‑side map, so they cannot be forged offline. ### Rate limiting / lockout recovery Failed logins are tracked **per IP**: 10 failures (`AUTH_FAILURE_MAX`) → `429`, with a 15‑minute decay. Multi-user mode replaces that with three buckets, all with the same decay: a wider per-IP **pre-gate** of 50 failures (`AUTH_IP_FAILURE_MAX`), checked before the scrypt verify, which bounds scrypt cost from one source and tolerates many users behind one egress IP; a **per-(username, IP)** gate of 10 failures (`AUTH_FAILURE_MAX`), also checked before the verify, which is what caps verified guesses against one account from one source; and a **per-username** bucket, checked after the verify, that answers `429` to failed guesses from the 10th on, from any IP (the count is incremented before the check). The last two exist in multi-user mode only. So the wider per-IP cap does not widen guessing against any one account from one IP, and other IPs cannot lock an account out. -The QR path has its own separate limiter. +A request with no `Authorization` header is never counted (step 4), so an open +tab after a restart cannot fill any bucket. The QR path has its own separate limiter. The lockout check sits **after** the cookie/credential checks (step 5, not first). This is deliberate: a user with a **valid cookie or correct password recovers diff --git a/docs/wiki/Remote-Access.md b/docs/wiki/Remote-Access.md index 49e577cb..22e67943 100644 --- a/docs/wiki/Remote-Access.md +++ b/docs/wiki/Remote-Access.md @@ -236,7 +236,8 @@ Notes and current limits: The first request prompts for HTTP Basic credentials. On success the server issues an opaque `codeman_session` cookie (24 hour lifetime, extended on activity, validated server-side so it cannot be forged offline). Ten failed attempts from one IP produce a `429` with a 15 -minute decay. +minute decay. A request with no credentials, such as an open tab whose cookie a restart +invalidated, is never counted and always gets the login prompt. A valid cookie or a correct password recovers immediately even while an attacker is hammering the same IP, which matters because all tunnel traffic arrives from one loopback address. diff --git a/docs/wiki/Security.md b/docs/wiki/Security.md index 3e631a91..58fcf560 100644 --- a/docs/wiki/Security.md +++ b/docs/wiki/Security.md @@ -54,7 +54,7 @@ When authentication is enabled: | ------------------- | ------------------------------------------------------------------------------------------------ | | **HTTP Basic** | `CODEMAN_USERNAME` (default `admin`) and `CODEMAN_PASSWORD`. | | **Session cookie** | A 256-bit opaque token validated server side, so it cannot be forged offline. 24 hours, extended on activity, with a device-context audit trail. | -| **Rate limiting** | Ten failed attempts per IP produce a `429` with a 15 minute decay. A correct password or valid cookie recovers immediately even under attack, which matters because all tunnel traffic shares one loopback address. In multi-user mode the per-IP cap is 50, and each account allows ten failed guesses from any one IP. Both are checked before the password, so past either a correct password from that IP also waits for the decay (the account still logs in from another IP, and a valid cookie keeps working). From the tenth failed guess on, an account's wrong guesses get a `429` from every IP, which never refuses a correct password. | +| **Rate limiting** | Ten failed attempts per IP produce a `429` with a 15 minute decay. A correct password or valid cookie recovers immediately even under attack, which matters because all tunnel traffic shares one loopback address. In multi-user mode the per-IP cap is 50, and each account allows ten failed guesses from any one IP. Both are checked before the password, so past either a correct password from that IP also waits for the decay (the account still logs in from another IP, and a valid cookie keeps working). From the tenth failed guess on, an account's wrong guesses get a `429` from every IP, which never refuses a correct password. A request with no credentials at all (such as an open tab after a restart) is never counted and always gets the login prompt. | | **QR auth** | Single-use 60-second tokens with their own separate rate limiter, so a mistyped password cannot lock out QR login. | | **Hook endpoints** | The hook and telemetry endpoints skip Basic auth because they are called from localhost by the CLI, but when auth is on, that bypass additionally requires a per-instance hook secret. | From 5ff018772ec0dd1459f664f19dfb981a2d8d5979 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Sat, 21 Nov 2026 00:09:25 +0100 Subject: [PATCH 4/4] test(auth): multi-user still challenges a header-less request during lockout The single-user suite pinned this; the multi-user one only showed that header-less requests are not counted. Fill the per-IP bucket with malformed headers, then expect 401 + challenge for no header and 429 for another malformed one. Fails on master. Co-Authored-By: Claude Opus 5.5 --- test/multiuser-auth.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/test/multiuser-auth.test.ts b/test/multiuser-auth.test.ts index 83492170..7982d082 100644 --- a/test/multiuser-auth.test.ts +++ b/test/multiuser-auth.test.ts @@ -304,6 +304,20 @@ describe('multi-user auth', () => { expect((await malformed()).statusCode).toBe(429); }); + it('requests without credentials still get the challenge while the IP is locked out', async () => { + const { app } = await startIpServer(); + const ip = '203.0.113.42'; + const malformed = () => + app.inject({ method: 'GET', url: '/api/status', headers: { authorization: 'Bearer x' }, remoteAddress: ip }); + for (let i = 0; i < AUTH_IP_FAILURE_MAX; i++) await malformed(); + + // A 429 never makes a browser show its login dialog; a 401 challenge does. + const bare = await app.inject({ method: 'GET', url: '/api/status', remoteAddress: ip }); + expect(bare.statusCode).toBe(401); + expect(bare.headers['www-authenticate']).toBe('Basic realm="Codeman"'); + expect((await malformed()).statusCode).toBe(429); + }); + it('per-IP pre-gate: a concurrent burst from one IP reaches the verify at most AUTH_IP_FAILURE_MAX times', async () => { const { login, buckets } = await startIpServer(); const ip = '203.0.113.40';