Merge #838: fix(auth): stop counting credential-less requests as failed logins (@kkalisz)

This commit is contained in:
Codeman maintainer committed 2026-11-25 16:11:56 +01:00
commit b7bb332338
10 files changed
+147 -18

No files matched your search

+5
View File
@@ -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.
+1 -1
View File
@@ -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 | | **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` | | **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 | | **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) | | **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` | | **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 | | **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 |
+1 -1
View File
@@ -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`) - **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) - **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 - **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) ### Always-on browser hardening (v0.9.5)
+1 -1
View File
@@ -1359,7 +1359,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) | | **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` | | **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 | | **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 | | **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) | | **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_*`) | | **Validation** | Zod schemas, Unicode-aware path allowlist regex, env prefix allowlist (`CLAUDE_CODE_*`/`OPENCODE_*`/`CODEX_*`/`GEMINI_*`/`GOOGLE_*`/`ANTIGRAVITY_*`/`PI_*`) |
+15 -5
View File
@@ -138,9 +138,18 @@ loopback bind matters. The auth pipeline (`src/web/middleware/auth.ts`,
allow. allow.
3. **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. that IP's failure counter.
4. **Rate‑limit gate** — if neither cookie nor credentials passed and the IP is 4. **No `Authorization` header** — return `401` with the `WWW-Authenticate`
locked out, return `429` with a `Retry-After` header. challenge, **without counting it** and even while the IP is locked out (both
5. Otherwise return `401`, incrementing the IP's failure counter. 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
Basic) return `401`, incrementing the IP's failure counter.
### Session cookies ### Session cookies
@@ -152,9 +161,10 @@ by presence in a server‑side map, so they cannot be forged offline.
### Rate limiting / lockout recovery ### 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. 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 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 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 immediately** even while an attacker is hammering the same IP — important because
all traffic through a tunnel shares one source IP (loopback). Wrong credentials all traffic through a tunnel shares one source IP (loopback). Wrong credentials
+2 -1
View File
@@ -236,7 +236,8 @@ Notes and current limits:
The first request prompts for HTTP Basic credentials. On success the server issues an opaque 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 `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 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 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. the same IP, which matters because all tunnel traffic arrives from one loopback address.
+1 -1
View File
@@ -54,7 +54,7 @@ When authentication is enabled:
| ------------------- | ------------------------------------------------------------------------------------------------ | | ------------------- | ------------------------------------------------------------------------------------------------ |
| **HTTP Basic** | `CODEMAN_USERNAME` (default `admin`) and `CODEMAN_PASSWORD`. | | **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. | | **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. | | **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. | | **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. |
+29 -7
View File
@@ -66,6 +66,12 @@ function sendAuthRateLimit(reply: FastifyReply, failures: StaleExpirationMap<str
reply.code(429).send('Too Many Requests — try again later'); reply.code(429).send('Too Many Requests — try again later');
} }
/** 401 with a Basic challenge, so a browser shows its login dialog. */
function challengeBasicAuth(reply: FastifyReply): void {
reply.header('WWW-Authenticate', 'Basic realm="Codeman"');
reply.code(401).send('Unauthorized');
}
/** Parse a `Basic base64(user:pass)` header into its parts, or null if malformed. */ /** Parse a `Basic base64(user:pass)` header into its parts, or null if malformed. */
function parseBasicAuth(header?: string): { username: string; password: string } | null { function parseBasicAuth(header?: string): { username: string; password: string } | null {
if (!header || !header.startsWith('Basic ')) return null; if (!header || !header.startsWith('Basic ')) return null;
@@ -485,6 +491,16 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
return; return;
} }
// No credentials at all is not a guess: challenge it without counting or limiting.
// Counting it locked users out after every server restart (cookie sessions live in
// memory): an open tab's background requests carry only the dead cookie, ten of them
// filled the bucket within seconds, and the 429 that followed never re-prompted the
// browser for a password, so reloading could not recover until the window expired.
if (!auth) {
challengeBasicAuth(reply);
return;
}
// Rate limit only requests that failed to authenticate on this attempt. // Rate limit only requests that failed to authenticate on this attempt.
const failures = authFailures.get(clientIp) ?? 0; const failures = authFailures.get(clientIp) ?? 0;
if (failures >= AUTH_FAILURE_MAX) { if (failures >= AUTH_FAILURE_MAX) {
@@ -495,8 +511,7 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas
// Auth failed — track failure count // Auth failed — track failure count
authFailures.set(clientIp, failures + 1); authFailures.set(clientIp, failures + 1);
reply.header('WWW-Authenticate', 'Basic realm="Codeman"'); challengeBasicAuth(reply);
reply.code(401).send('Unauthorized');
}); });
return state; return state;
@@ -622,8 +637,7 @@ function registerMultiUserAuthHook(
sendAuthRateLimit(reply, userFailures, normUser); sendAuthRateLimit(reply, userFailures, normUser);
return; return;
} }
reply.header('WWW-Authenticate', 'Basic realm="Codeman"'); challengeBasicAuth(reply);
reply.code(401).send('Unauthorized');
}; };
app.addHook('onRequest', async (req, reply) => { app.addHook('onRequest', async (req, reply) => {
@@ -703,6 +717,15 @@ function registerMultiUserAuthHook(
// which is every reload after a restart: cookie sessions live in memory, so the // 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 // 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. // 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 creds = parseBasicAuth(req.headers.authorization);
const normUser = creds ? creds.username.trim().toLowerCase() : ''; const normUser = creds ? creds.username.trim().toLowerCase() : '';
const flightKey = creds ? verifyFlightKey(clientIp, normUser, creds.password) : ''; const flightKey = creds ? verifyFlightKey(clientIp, normUser, creds.password) : '';
@@ -746,10 +769,9 @@ function registerMultiUserAuthHook(
return; 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); authFailures.set(clientIp, ipFail + 1);
reply.header('WWW-Authenticate', 'Basic realm="Codeman"'); challengeBasicAuth(reply);
reply.code(401).send('Unauthorized');
}); });
} }
+43
View File
@@ -244,6 +244,49 @@ describe('Auth Security', () => {
expect(wrongAfterRecovery.status).toBe(401); 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);
});
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', () => { describe('Hook Event Endpoint', () => {
+49 -1
View File
@@ -112,7 +112,7 @@ async function startIpServer() {
const app = (s as unknown as { app: FastifyInstance }).app; const app = (s as unknown as { app: FastifyInstance }).app;
const login = (ip: string, user: string, pass: string) => const login = (ip: string, user: string, pass: string) =>
app.inject({ method: 'GET', url: '/api/status', headers: { authorization: basic(user, pass) }, remoteAddress: ip }); 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', () => { describe('multi-user auth', () => {
@@ -270,6 +270,54 @@ describe('multi-user auth', () => {
expect((await login(ipA, 'bob', 'bobpass123')).statusCode).toBe(429); 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('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('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 () => { 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 { login, buckets } = await startIpServer();
const ip = '203.0.113.40'; const ip = '203.0.113.40';