diff --git a/.changeset/trusted-proxy-sign-in.md b/.changeset/trusted-proxy-sign-in.md new file mode 100644 index 00000000..c2d1813a --- /dev/null +++ b/.changeset/trusted-proxy-sign-in.md @@ -0,0 +1,5 @@ +--- +'aicodeman': minor +--- + +Multi-user mode can sign people in through an authenticating reverse proxy on the same host (single sign-on with Entra ID, Google Workspace, Keycloak and others). With `CODEMAN_TRUSTED_PROXY_SECRET_FILE` set, a loopback request that carries the secret in `X-Codeman-Proxy-Secret` and a username in `X-Codeman-User` signs in as that existing, enabled account. Off by default and experimental. The wiki's Multi-User Mode page has a Caddy and oauth2-proxy walkthrough. diff --git a/CLAUDE.md b/CLAUDE.md index 7f6d7d16..beb722d9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -273,7 +273,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin **Web tabs** (dashboard URLs as tabs): a saved URL renders as a tab beside sessions, **NOT a `SessionMode`**, and is proxied through Codeman's own origin (`/webview//...`). ⚠️ The proxy is NOT an API surface: its capability-based auth exemption stays fenced to safe methods and non-route paths (`test/webview-auth-exemption.test.ts`). ⚠️ Iframes omit `allow-same-origin` unless `trusted`, and `Authorization`/`codeman_session` are stripped upstream in both modes. ⚠️ **Egress guard**: link-local and cloud-metadata targets are refused at save time, by a sync hostname check at each connect (IP literals skip DNS), AND on the resolved address (`webview-egress.ts`); use the `undici` package's own `fetch` + `Agent`, never Node's global fetch. ⚠️ Loopback links in agent output auto-open as proxied web tabs (`openLinkThroughWebTabIfLoopback`), but never auto-route `*.localhost` (prompt-injectable DNS). Capabilities are revoked on logout (`revokeOwner`). → [architecture-invariants#web-tabs](docs/architecture-invariants.md#web-tabs), `docs/web-tabs.md` -**Multi-user mode** (opt-in `--multiuser` / `CODEMAN_MULTIUSER=1`, OFF by default): named users with scrypt-hashed passwords in `~/.codeman/users.json`. Gated everywhere by `isMultiUserMode()`; when OFF, behavior is byte-identical to single-user because every scoping helper short-circuits. ⚠️ **Not a security boundary at the agent layer**: every session still runs as the SAME OS account. This separates WORKSPACES; it does not sandbox users (Docker cases are the isolation story). Ownership threads through `Session.owner` and is enforced in `findSessionOrFail`, list endpoints, SSE routing (fail-closed), WS, search, and file-preview. ⚠️ `settings.json` is ONE server-wide file, so every write to it is admin-only (`PUT /api/settings`, `/api/execution/model-config`, `/api/cases/order`, plus `PUT /api/config`: 403 `FORBIDDEN` before parsing), a non-admin's quick-start/Ralph start skips `lastUsedCase`, its GET hides `voiceSettings.apiKey`/`caseOrder`/`lastUsedCase`/`lastPickedCase`/`caseSettings` from a non-admin (`settingsForNonAdmin`), and the browser skips those writes for a non-admin via `_settingsReadOnly()` (settings-ui.js; also true once a write came back 403 `FORBIDDEN`, since `/api/me` can be slow or fail; their run mode and respawn presets stay per-device, `_applyOwnSettings`) (`test/routes/system-routes-settings-admin-only.test.ts`). System ops are admin-only too (`/api/system/update`, `/api/system/span-displays`, `/api/tunnel/qr/regenerate`, `/api/cleanup-state`), and a non-admin's `/api/auth/revoke` revokes only their own logins (`test/routes/system-routes-system-ops-admin-only.test.ts`). → [architecture-invariants#multi-user-mode](docs/architecture-invariants.md#multi-user-mode), `docs/multi-user-plan.md` +**Multi-user mode** (opt-in `--multiuser` / `CODEMAN_MULTIUSER=1`, OFF by default): named users with scrypt-hashed passwords in `~/.codeman/users.json`. Gated everywhere by `isMultiUserMode()`; when OFF, behavior is byte-identical to single-user because every scoping helper short-circuits. ⚠️ **Not a security boundary at the agent layer**: every session still runs as the SAME OS account. This separates WORKSPACES; it does not sandbox users (Docker cases are the isolation story). Ownership threads through `Session.owner` and is enforced in `findSessionOrFail`, list endpoints, SSE routing (fail-closed), WS, search, and file-preview. ⚠️ `settings.json` is ONE server-wide file, so every write to it is admin-only (`PUT /api/settings`, `/api/execution/model-config`, `/api/cases/order`, plus `PUT /api/config`: 403 `FORBIDDEN` before parsing), a non-admin's quick-start/Ralph start skips `lastUsedCase`, its GET hides `voiceSettings.apiKey`/`caseOrder`/`lastUsedCase`/`lastPickedCase`/`caseSettings` from a non-admin (`settingsForNonAdmin`), and the browser skips those writes for a non-admin via `_settingsReadOnly()` (settings-ui.js; also true once a write came back 403 `FORBIDDEN`, since `/api/me` can be slow or fail; their run mode and respawn presets stay per-device, `_applyOwnSettings`) (`test/routes/system-routes-settings-admin-only.test.ts`). System ops are admin-only too (`/api/system/update`, `/api/system/span-displays`, `/api/tunnel/qr/regenerate`, `/api/cleanup-state`), and a non-admin's `/api/auth/revoke` revokes only their own logins (`test/routes/system-routes-system-ops-admin-only.test.ts`). **Trusted reverse-proxy sign-in** (experimental, opt-in `CODEMAN_TRUSTED_PROXY_SECRET_FILE`, `src/config/trusted-proxy.ts`): a same-host authenticating proxy signs requests in via `X-Codeman-Proxy-Secret` + `X-Codeman-User`. ⚠️ Never read or forward request headers ahead of the first auth hook (it deletes those two from every request), and never re-read the secret from the environment (the settings are read once and both variables deleted, since sessions inherit Codeman's env; a setup that cannot be used stops the start). → [architecture-invariants#multi-user-mode](docs/architecture-invariants.md#multi-user-mode), `docs/multi-user-plan.md` **Away digest**: `GET /api/away-digest` aggregates what happened while you were away from the lifecycle log, run-summary events, live sessions, token stats, and recent subagents. Pure aggregator in `web/away-digest.ts`. ⚠️ Returns `{success:true,digest}`, a legacy raw-ish shape consistent with the other raw GET handlers in `system-routes.ts`; frontend and tests read `.digest`. → [architecture-invariants#away-digest](docs/architecture-invariants.md#away-digest) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index a10b1f72..d8ac0830 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -636,6 +636,8 @@ Further detail: the refused egress targets are `169.254.0.0/16`, `fe80::/10`, `f **Multi-user mode** (opt-in `--multiuser` / `CODEMAN_MULTIUSER=1`, OFF by default; shipped 1.5.0 via PR #161, design `docs/multi-user-plan.md`): named users with individually scrypt-hashed passwords in `~/.codeman/users.json` (via `src/user-store.ts`: atomic 0600 write, short-TTL cache, SERIALIZED read-modify-write so a fire-and-forget `touchLastLogin` can't clobber a concurrent route write, last-admin invariants). Gated everywhere by `isMultiUserMode()` (`src/config/multiuser.ts`); when OFF, behavior is byte-identical to single-user (all scoping helpers short-circuit). ⚠️ **Not a security boundary at the agent layer** — every session still runs as the SAME OS account; this separates WORKSPACES, it does not sandbox users (Docker cases are the isolation story). Auth: a PARALLEL async branch in `middleware/auth.ts` (single-user branch untouched) verifies `username:password` against the store, mints identity-carrying cookies (`AuthSessionRecord` gains `username`/`role`/`mustChangePassword`), decorates `req.authUser` (Fastify augmentation; single-user leaves it undefined and the ownership helpers default to a synthetic admin), enforces a per-username failure bucket + the `mustChangePassword` lockbox. Ownership threads through `Session.owner` (stamped from `req.authUser`/`job.owner` at every `new Session()`, round-tripped via `MuxSession.owner` on recovery); `findSessionOrFail(ctx,id,req)` does a NOT_FOUND owner check; list endpoints + `getLightState` + SSE (`deriveSseHint` routes session-scoped events by owner, fail-closed; machine-level + host-plan telemetry admin-only) + WS + search + file-preview all filter by owner. §6.3 permission policy: non-granted users are forced to `--permission-mode auto` (via `resolveClaudeModeForUser` at all spawn sites, incl. one-shots because `buildPromptArgs` now respects the session mode), and shell mode / cron `launchCommand` require the `canBypassPermissions` grant. Cases live in per-user `~/codeman-users//cases` (`resolveCasesDir`); a non-admin's `workingDir` is realpath-confined there; host CRUD is admin-only. Admin API `src/web/routes/admin-routes.ts` (`/api/admin/users*`, one-time passwords, audit log `admin-audit.jsonl`) + self-service `/api/me` + `/api/me/password` (`me-routes.ts`); frontend `public/admin-ui.js` (identity boot, change-password modal + interceptor, admin Users tab, and the header **Admin Panel** button `#adminPanelBtn`: ships `btn-admin-panel--hidden`, revealed for admins in multi-user mode, phone-hidden via mobile.css; opens the full Admin Panel modal with user CRUD, per-user permission toggles, and case-folder list/delete via `GET/DELETE /api/admin/users/:username/cases[/:caseName]`; live-refreshes on SSE `admin:usersChanged`, wired in app.js). CLI `codeman users add|passwd|list|rm`. Per-user session cap via `sessionCapacityState`/`sessionCapacityMessage`. Tests: `test/user-store.test.ts`, `test/multiuser-auth.test.ts`, `test/ownership-scoping.test.ts`, `test/admin-routes.test.ts`, `test/admin-ui.test.ts`. +**Trusted reverse-proxy sign-in** (experimental per `docs/versioning-policy.md`; opt-in `CODEMAN_TRUSTED_PROXY_SECRET_FILE` / `CODEMAN_TRUSTED_PROXY_SECRET`, multi-user only; `src/config/trusted-proxy.ts`, `registerTrustedProxyHeaderStrip` + `checkTrustedProxyIdentity` in `middleware/auth.ts`, full rules in `docs/security-architecture.md` §10a): a same-host authenticating proxy (oauth2-proxy, mod_auth_openidc, ...) presents `X-Codeman-Proxy-Secret` + `X-Codeman-User` and the request signs in as that EXISTING, enabled account. ⚠️ The headers are read and DELETED from every request by the first auth hook (right after the Host guard, every auth mode), before any exemption or route: the web-tab relay copies request headers, and must never see the secret. ⚠️ The secret is read ONCE at auth setup (before sessions are restored) and both variables are deleted from `process.env`, since every session inherits Codeman's env; don't add a code path that re-reads them from the env later (the secret file's path is kept in the module for `isSensitivePath`). ⚠️ A configured setup that cannot be used (unreadable, empty or group/other-readable file, short or non-ASCII secret, both variables, single-user mode, rejected header name) STOPS THE START; it is never silently off. The check is step 0 of the multi-user hook, BEFORE the cookie, and fail-closed: once the secret header is present (even empty), a wrong secret / non-loopback `req.ip` (401) or a missing, invalid, unknown or disabled username (403, no challenge) is refused and never falls through to cookie or Basic. The username is matched exactly (`normalizeUsername()` + the username rule, no other transformation); the loopback test is `isLoopbackIp`, shared with the hook-secret bypass. The secret is compared BEFORE the failure bucket (own per-IP `proxySecretFailures`), so a correct secret always passes and only failures are throttled. No cookie is minted. `req.authUser.viaTrustedProxy` skips the `mustChangePassword` lockbox and makes `GET /api/me` report `mustChangePassword: false`. ⚠️ The username header is removed from EVERY request, so `CODEMAN_TRUSTED_PROXY_USER_HEADER` is validated by shape (`X-…` or `Remote-User`, reserved names refused) and a rejected name stops the start; the configured name is also on the web-tab relay's drop list. With the feature configured, a `/webview/` or `/html-view/` request the capability exemptions don't let through is refused with the route's own 403/404 BEFORE the credential checks (`serveRefusedCapabilityPath`), by prefix on a normalised path (`capabilityPrefixOf`), not by token shape: the proxy lets those paths through without its sign-in, so they must never reach the Basic check, prompt or failure bucket. The configured secret file is on the `isSensitivePath` blocklist. Tests: `test/trusted-proxy-auth.test.ts`, `test/sensitive-path.test.ts`. + ### Agent-created case marker **Agent-created case marker** (`src/agent-case-marker.ts`): a case directory `POST /api/quick-start` **creates** for an agent-driven spawn gets a `.codeman-agent-case.json` marker, so the scratch workspaces a long orchestration leaves behind (one per worker, and deleting the session does not remove them) can still be told apart from the user's real projects months later. `GET /api/cases` publishes it as `agentCreated`; `GET /api/cases/agent-created` is the read-only cleanup listing, adding `inUse` (a live session's `workingDir` is that case) and `modifiedAt`; Add Case → Manage badges each one and offers a review-then-delete sweep. The signal is the skill preamble's `X-Codeman-Agent-Origin` header (or an `agentOrigin` body field), falling back to a RESOLVED `parentSessionId` — nothing in the browser UI sets lineage, so a create request naming its spawning session came from an agent by construction, and that fallback is what still labels workers spawned by a stale skill copy. diff --git a/docs/multi-user-plan.md b/docs/multi-user-plan.md index f9652944..a2f71a12 100644 --- a/docs/multi-user-plan.md +++ b/docs/multi-user-plan.md @@ -184,8 +184,8 @@ All handlers: multi-user mode only (404 otherwise), `requireAdmin`, Zod schemas | `GET /api/admin/users` | List users + stats: role, disabled, createdAt, lastLoginAt, live session count, case count, space disk usage (best-effort async walk, cached 60s), active cookie-session count | | `POST /api/admin/users` | Create: `{ username, role, password? }`. No password given: generate a one-time password, return it ONCE in the response, set `mustChangePassword` | | `PATCH /api/admin/users/:username` | `{ role?, disabled?, canBypassPermissions? }`. Demoting/disabling the last enabled admin: 409 `LAST_ADMIN`. Disable also revokes cookie sessions. `canBypassPermissions` is the section 6.3 grant (default false) | -| `POST /api/admin/users/:username/reset-password` | Generates one-time password (returned once), sets `mustChangePassword`, revokes cookie sessions | -| `POST /api/admin/users/:username/logout` | Revoke all cookie sessions for that user. Honest limit under Basic auth: the browser silently re-sends cached credentials and gets a fresh cookie on the next request, so logout only truly ends QR-issued sessions; to actually lock someone out, disable the account or reset the password. Say so in the panel tooltip until Phase 6 | +| `POST /api/admin/users/:username/reset-password` | Generates one-time password (returned once), sets `mustChangePassword`, revokes cookie sessions. Does not end a trusted-proxy sign-in, which uses no password and holds no cookie | +| `POST /api/admin/users/:username/logout` | Revoke all cookie sessions for that user. Honest limit under Basic auth: the browser silently re-sends cached credentials and gets a fresh cookie on the next request, so logout only truly ends QR-issued sessions; to actually lock someone out, disable the account or reset the password. For a person who signs in through a trusted reverse proxy, neither logout nor a reset ends access (no cookie, no password): disable or delete the account. Say so in the panel tooltip until Phase 6 | | `DELETE /api/admin/users/:username` | `{ deleteSpace?: boolean }` (default false). Refuses last admin. Kills the user's live sessions first (normal kill flow, incl. docker/remote teardown per case), revokes cookies, removes from store. With `deleteSpace`: guarded recursive delete of `~/codeman-users/` (realpath must be inside `USER_SPACES_DIR`, top-level dir must not be a symlink), plus their registry entries and push subscriptions | | `POST /api/admin/cases/assign` | Move a legacy `~/codeman-cases/` into a user's space (`fs.rename`) | | Self-service `GET /api/me` | `{ username, role, mustChangePassword }` (works in single-user mode too: synthetic admin; the frontend uses it to decide whether to render admin UI) | diff --git a/docs/security-architecture.md b/docs/security-architecture.md index f97ee389..b6522d74 100644 --- a/docs/security-architecture.md +++ b/docs/security-architecture.md @@ -590,6 +590,144 @@ Full feature guide: [`docker-cases.md`](docker-cases.md). - **Clone Repo does not lend the server's git sign-in to non-admins.** A clone writes only inside the caller's own case space, so it is not admin-gated, but the server account's git credential helpers (the Docker image's opt-in `gh`/`az` helpers, or any `gh auth setup-git`) are shared by every user. A non-admin's clone and preflight therefore run with `git -c credential.helper=`, which empties the helper list including the URL-scoped entries (`cloneWithoutCredentialHelpers` in `case-routes.ts`, argv pinned in `test/git-clone.test.ts`). This closes the Clone Repo path only: the account's SSH keys still apply to an `ssh://` URL, and a non-admin's agent sessions run as the same account, consistent with the first bullet above. Docker cases are a second route to the same sign-in: with `CODEMAN_AGENT_IMAGE_INSTALL_GH`/`_AZ` on, a non-admin's Docker case with credential seeding on (the default) receives a copy of the server account's `gh`/`az` sign-in, exactly as it receives the Claude and Codex credentials. - **Admin actions are audited** append‑only to `~/.codeman/admin-audit.jsonl` (acting admin, action, target, IP). Passwords set by an admin create/reset are one‑time (returned once, force change). Under Basic auth, `logout` only truly ends QR‑issued sessions — to lock someone out, disable the account or reset the password (a proper login form is a deferred Phase 6). +### Trusted reverse‑proxy sign‑in (opt‑in, multi‑user only) + +A shared secret lets an authenticating reverse proxy on the same host (oauth2‑proxy behind +Caddy or nginx, Apache `mod_auth_openidc`, Authelia, …) sign people in through an identity +provider such as Entra ID, Google or Keycloak, in place of the Basic prompt. Source: +`src/config/trusted-proxy.ts`, `checkTrustedProxyIdentity` and +`registerTrustedProxyHeaderStrip` in `middleware/auth.ts`; tests in +`test/trusted-proxy-auth.test.ts`; a worked Caddy + oauth2‑proxy setup in +[`docs/wiki/Multi-User-Mode.md`](wiki/Multi-User-Mode.md#single-sign-on-through-a-reverse-proxy). + +**Experimental** ([versioning-policy.md](versioning-policy.md)): the three settings, the two +headers and the `viaTrustedProxy` field of `GET /api/me` may change until they are promoted +by an explicit decision. + +"Trusted proxy" names this sign-in only. It is not forwarded-address trust: Codeman still +does not read `X-Forwarded-For`, `trustProxy` stays `false`, and `req.ip` stays the socket +peer (§3). + +- **What the proxy sends.** After it has authenticated the person, the proxy adds + `X-Codeman-Proxy-Secret: ` and `X-Codeman-User: `. It must + delete both headers from the incoming client request first. The username header can be + renamed with `CODEMAN_TRUSTED_PROXY_USER_HEADER`, but only to an `X-…` extension header + or `Remote-User`, never a reserved one (`X-Forwarded-For/Host/Proto/…`, `X-Real-IP`, + `X-Codeman-*`, CSRF/method-override headers; `X-Forwarded-User/Email/Preferred-Username` + are allowed): the header is removed from every request, so it must not be one anything + else needs. A rejected name stops the start (see below), so it is never removed. +- **The secret.** At least 32 printable ASCII characters, from + `CODEMAN_TRUSTED_PROXY_SECRET_FILE` (preferred: a 0600 file, so only a path is in the + environment, like the hook secret's `CODEMAN_HOOK_SECRET_FILE`) or + `CODEMAN_TRUSTED_PROXY_SECRET`. It is read once at auth setup, before any session is + spawned or restored, and both variables are then deleted from `process.env`, because + every session inherits Codeman's environment. That keeps them out of child processes + and nothing more: an inline secret stays visible in `/proc//environ` for the life + of the server. A tmux server + that an earlier Codeman started with the variable set keeps its own copy of that + environment until it is restarted. A configured setup that cannot be used stops the start + with a message that says why, as the first boot without users does: a secret file that + is unreadable, empty, or readable by group or others (the mode is not checked on + Windows); a short or non-ASCII secret; both + variables set; a secret set in single-user mode; a rejected username header name. The + length floor matters because a correct secret is never refused, so the limiter only + turns a `401` into a `429` and the secret's entropy is what slows a guesser. The configured file (any name) and + `~/.codeman*/proxy-secret` are on the `isSensitivePath` blocklist, so downloads and + attachments refuse them. +- **What the secret separates.** Every local process reaches the loopback port, so + loopback alone proves nothing; the secret is what a local process lacks. It is not a + boundary against code that can read the secret file or Codeman's memory, i.e. anything + running as Codeman's OS account, which includes every agent session (the multi‑user + threat model at the top of §10a: sessions share that account). Said plainly: any session that + runs as Codeman's OS account can read the secret and sign in as anyone, an admin + included, over loopback. That is the same class as editing `users.json`, which that + account can also do. +- **When Codeman believes it.** Only when ALL hold: multi‑user mode is on; a valid secret + is configured; the request arrives on a **loopback socket** (`req.ip`, which ignores + `X‑Forwarded‑For`, §3); and the presented secret matches + (`timingSafeEqual` on equal lengths, like the hook secret). The loopback test is one + function, `isLoopbackIp`, shared with the hook-secret bypass, so the two secret-gated + 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 + 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 + admin still decides who has an account. Unknown or disabled → `403`. The value is matched + exactly: `normalizeUsername()` (trimmed, lower-cased, as for Basic logins), then the + username rule, and nothing else. No domain is cut off and no character replaced, so an + email address names no account, and a header that arrives twice (Node joins it as + `admin, bob`) is refused, never split. Mapping the IdP's identity onto a Codeman + username is the proxy's job. +- **Fails closed once the secret header is present, even empty.** A wrong or empty secret, + a non‑loopback source, or a missing username is refused outright and never falls + through to the cookie or Basic paths, so a misconfigured proxy cannot degrade into + another identity. A username header WITHOUT the secret header is ignored, and normal + auth applies. With a valid secret, a missing username or an unknown or disabled account + gets a plain `403` with no `WWW-Authenticate`. +- **Rate limiting.** The secret is compared first, like the hook secret: a correct secret + always passes, so junk requests from other local processes (which share `127.0.0.1` + with the proxy) cannot lock sign‑in out. Only failures are counted, per IP, in their + own bucket (`AUTH_FAILURE_MAX` per `AUTH_FAILURE_WINDOW_MS`, then `429`), separate from + the Basic and hook buckets. +- **Precedence and lifetime.** Checked before the session cookie (the proxy's identity is + authoritative on that request; a stale cookie from an earlier Basic login in the same + browser does not override it, and is neither read nor refreshed). No `codeman_session` cookie is minted: the proxy + authorizes every new request and WebSocket upgrade. A terminal WebSocket or SSE stream + that is already open stays open until it disconnects: neither ending the proxy session + nor disabling the account closes it. Disabling the account refuses new authenticated + requests and upgrades; it does NOT revoke the account's web‑tab / HTML‑view + capabilities, which behind the proxy are reachable without its sign‑in, so to cut + someone off also use the Admin Panel **Logout** for them (it revokes both capability + stores) or delete the account. A password reset or Logout alone does not + cut off a proxy sign-in: it uses no password and holds no cookie, so the next request the + proxy vouches for signs the person in again. Proxy sign-ins update the account's + last-login time at most every 15 minutes, throttled in memory before the user store is + touched. +- **`mustChangePassword`** does not gate a proxy sign‑in (no Codeman password was used), + and `GET /api/me` reports `mustChangePassword: false` plus `viaTrustedProxy: true`, so + the browser does not force a password change. The account's Codeman password still + works wherever the loopback port is reachable without the proxy (an SSH tunnel, the + managed tunnel), and such a request is not covered by the identity provider's MFA. + Password sign-in has to stay: Codeman's own clients (`codeman agent`, `mcp`, `notify`, + `attach`, `tui`, the skill) sign in with Basic on loopback. For an account used only + through the proxy, create it without a password; the generated one-time password can be + discarded, and the pending `mustChangePassword` then only shows as a label. A user's own logout / "Revoke all" ends Codeman cookies, not the + proxy's session (`/oauth2/sign_out` does that). +- **Web tabs and rendered HTML files** authenticate by the capability in their URL, + because their sandboxed frames send no cookies, not even the proxy's. The proxy must + therefore let `/webview/*` and `/html-view/*` through without its own sign‑in (and + without adding the secret, and without forwarding `Authorization`); the wiki example + does. With trusted‑proxy sign‑in configured, a request under those prefixes that the + capability exemptions do not let through, whatever its token looks like, is refused with + the route's own answer + (`403` web tab, `404` HTML view) BEFORE the credential checks: no Basic challenge, no + password check, no failure count (`serveRefusedCapabilityPath`). The prefix is judged + the way a proxy's path matcher would (`capabilityPrefixOf`: case‑insensitive, + percent‑decoded, dot segments and doubled slashes resolved), since the proxy forwards + every such spelling without its sign‑in. Otherwise anonymous + requests through the proxy could probe passwords and fill the per‑IP bucket, which + behind the proxy is always `127.0.0.1`, locking out Basic sign‑in from loopback. + Without a proxy configured these paths keep the normal `401` challenge. One limit + follows from the exemption being by prefix: a sandboxed frame's request that lands + outside its prefix goes through the proxy's sign-in without a cookie and fails there, + so the `Referer` form and the lost-frame recovery page (§10b) are not reachable for + sandboxed frames behind the proxy. +- **The proxy's own session cookie.** A cookie-based proxy's session cookie is a sign-in + for the whole site. Codeman does not know its name, and the web-tab relay forwards + browser cookies (all but `codeman_session`) to a dashboard opened in trusted mode. The + proxy must remove its cookie from every request it forwards to Codeman, on the + capability paths and after its own sign-in check; the wiki example does. +- **Unchanged:** the Host allowlist and Origin guard (set `CODEMAN_ALLOWED_HOSTS` to the + proxy's hostname), the hook‑secret loopback bypass (a proxy should still refuse + `/api/hook-event`, `/api/status-telemetry` and their `/api/v1/` aliases from outside; + local hooks call the loopback port directly), and Basic sign‑in for requests without + the secret header. Admin actions through the proxy are audited with IP `127.0.0.1`, as + with any reverse proxy. +- **Not supported:** Docker Compose installs where Codeman runs in a container and the + proxy on the host; the proxy then connects from the bridge address, not loopback. + --- ## 10b. Web tabs (dashboard proxy) @@ -629,6 +767,8 @@ Opt-in by a click, macOS only, admin-only in multi-user mode on every verb. The | Env / flag | Effect | |------------|--------| | `CODEMAN_PASSWORD` (+ `CODEMAN_USERNAME`) | Enable HTTP Basic auth | +| `CODEMAN_TRUSTED_PROXY_SECRET_FILE` / `CODEMAN_TRUSTED_PROXY_SECRET` | Multi‑user only: trust a same‑host authenticating reverse proxy that presents this secret (≥ 32 printable ASCII chars; the file variant is preferred; both variables are removed from the environment once read; a setup that cannot be used stops the start) and a username header. Experimental — see §10a | +| `CODEMAN_TRUSTED_PROXY_USER_HEADER` | Header the trusted proxy puts the Codeman username in (default `X-Codeman-User`) | | `--host` / `CODEMAN_HOST` | Bind host (default `127.0.0.1`) | | `CODEMAN_ALLOWED_HOSTS` | Extra `Host`/`Origin` allowlist entries for reverse proxies (comma‑separated; exact host, or leading‑dot `.suffix` for subdomains) — see §3 | | `--base-url` / `CODEMAN_BASE_URL` | Sub‑path prefix Codeman is mounted under behind a reverse proxy, e.g. `/codeman` (default `/`); the proxy must forward the prefix unchanged. Independent of `CODEMAN_ALLOWED_HOSTS` | @@ -650,6 +790,7 @@ Opt-in by a click, macOS only, admin-only in multi-user mode on every verb. The | Bind‑host classification, env‑flag parsing, Host/Origin allowlist (`buildHostPolicy` / `isAllowedRequestHost` / `isAllowedRequestOrigin`) | `src/web/network-auth-policy.ts` | | Start‑and‑warn policy | `src/web/server.ts` (`WebServer.start()`) | | Auth pipeline, rate limiting, security headers, CORS, Host/Origin guard (`registerHostGuard`) | `src/web/middleware/auth.ts` | +| Trusted reverse‑proxy sign‑in: secret loading, header names, header stripping | `src/config/trusted-proxy.ts` | | File‑path containment (realpath‑before‑check) | `src/web/route-helpers.ts` (`validateSessionFilePath`) | | File routes, caps, SVG handling, download blocklist | `src/web/routes/file-routes.ts` | | Instance/socket/data‑dir scoping | `src/config/instance.ts` | diff --git a/docs/versioning-policy.md b/docs/versioning-policy.md index 7f2bab92..aa88e2b7 100644 --- a/docs/versioning-policy.md +++ b/docs/versioning-policy.md @@ -110,6 +110,25 @@ any other endpoint. On-disk state (`local-model.json`, the `local-model/` folder internal, as for every other file in the data directory. Promotion to stable requires an explicit documented decision. +### Experimental trusted-proxy sign-in + +Sign-in through an authenticating reverse proxy in multi-user mode +([security-architecture.md](security-architecture.md) §10a) is labeled experimental, so +item 3 above applies to all of its surface: the environment variables +`CODEMAN_TRUSTED_PROXY_SECRET_FILE`, `CODEMAN_TRUSTED_PROXY_SECRET` and +`CODEMAN_TRUSTED_PROXY_USER_HEADER`, the request headers `X-Codeman-Proxy-Secret` and +`X-Codeman-User`, the `viaTrustedProxy` field of `GET /api/v1/me` (and its `/api` alias), +the status codes and messages of its refusals, and the conditions under which a +configured setup stops the start. They may change or be removed in a MINOR or PATCH +release. + +It is off unless a secret is configured. With it off, sign-in works as before. Three +things still apply: the identity headers (the two above and a configured username +header) are dropped on arrival, downloads and attachments refuse the secret file, and a +trusted-proxy setting that cannot be used stops the start. The other fields +of `GET /api/v1/me` keep their existing guarantees. Promotion to stable requires an +explicit documented decision. + ## Deprecation policy When we need to change a covered surface: diff --git a/docs/web-tabs.md b/docs/web-tabs.md index 64c8baa4..95c66c36 100644 --- a/docs/web-tabs.md +++ b/docs/web-tabs.md @@ -107,7 +107,12 @@ similar). The sandboxed frame is opaque-origin, so its stylesheet, script, and A requests do not carry the proxy's authentication cookie; the proxy redirects them to the login provider, where CORS/CSP kills them, and the embedded app renders unstyled or broken while the Codeman page around it works fine. Trusted mode -(**Open sandboxed** off) keeps a real origin and the cookie, so it works. The +(**Open sandboxed** off) keeps a real origin and the cookie, so it works. ⚠️ In trusted +mode the relay forwards the browser's cookies to the dashboard, all but +`codeman_session`, and that includes the proxy's own session cookie unless the proxy +removes it from the requests it forwards to Codeman (the Caddy example in +[`docs/wiki/Multi-User-Mode.md`](wiki/Multi-User-Mode.md#single-sign-on-through-a-reverse-proxy) +does). The **Test** button cannot catch this: it checks that the Codeman *server* can reach the upstream, not that a sandboxed *browser* frame can load assets through the public authentication layer. diff --git a/docs/wiki/Multi-User-Mode.md b/docs/wiki/Multi-User-Mode.md index 9b4a6c38..df4be852 100644 --- a/docs/wiki/Multi-User-Mode.md +++ b/docs/wiki/Multi-User-Mode.md @@ -112,7 +112,318 @@ casually; they do not make the account a sandbox. Each user authenticates with their own name and password rather than the shared `CODEMAN_PASSWORD`. Logins are individually revocable: disable, reset, or delete an account -at any time, and existing browser sessions can be revoked. +at any time, and existing browser sessions can be revoked. A person who signs in through a +reverse proxy (next section) uses no Codeman password and holds no browser session, so a +password reset or a logout does not end their access: disable or delete the account. + +## Single sign-on through a reverse proxy + +Instead of Codeman passwords, people can sign in through your identity provider (Entra ID, +Google Workspace, Keycloak, Okta, ...). An authenticating reverse proxy on the same host +does the sign-in and tells Codeman who the person is. Codeman still decides who has an +account: the username must name an existing, enabled user, or the request gets `403`. + +**Experimental.** The settings, the two headers and the `viaTrustedProxy` field of +`GET /api/me` may still change (see +[`docs/versioning-policy.md`](https://github.com/Ark0N/Codeman/blob/master/docs/versioning-policy.md)). + +"Trusted proxy" here means only this sign-in. It does not make Codeman read +`X-Forwarded-For` or any other forwarded address: the client address stays the address of +the socket, which behind the proxy is `127.0.0.1`. + +``` +browser --HTTPS--> Caddy --forward_auth--> oauth2-proxy (127.0.0.1:4180) --> identity provider + \--reverse_proxy--> Codeman (127.0.0.1:3000, multi-user mode) +``` + +On every request the proxy adds two headers: + +| Header | Value | +|---|---| +| `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 +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). + +The secret keeps other local processes from claiming an identity. It does not protect +against anything that runs as Codeman's own OS account, which includes every agent session: +such a process can read the secret and sign in as anyone, an admin included, over loopback. +That is the same exposure as editing `users.json`, which the same account can also do (see +[Read this before enabling it](#read-this-before-enabling-it)). + +### Codeman + +```bash +install -m 600 /dev/null ~/.codeman/proxy-secret +openssl rand -hex 32 > ~/.codeman/proxy-secret # the shared secret, also given to the proxy +codeman users add alice --admin # accounts still come from Codeman +CODEMAN_MULTIUSER=1 \ +CODEMAN_ALLOWED_HOSTS=codeman.example.com \ +CODEMAN_TRUSTED_PROXY_SECRET_FILE=~/.codeman/proxy-secret \ +codeman web # stays on 127.0.0.1:3000 +``` + +The startup log says `Trusted-proxy sign-in enabled (experimental)`. A setup that cannot be +used stops the start, with a message that says why: + +- the secret file cannot be read, is empty, or can be read by group or others (`chmod 600` + it; the mode is not checked on Windows); +- the secret is shorter than 32 characters or not printable ASCII; +- both `CODEMAN_TRUSTED_PROXY_SECRET_FILE` and `CODEMAN_TRUSTED_PROXY_SECRET` are set; +- a secret is set without multi-user mode; +- `CODEMAN_TRUSTED_PROXY_USER_HEADER` names a header that is not allowed. + +In a systemd unit, give the file as an absolute path (systemd does not expand `~`; `%h` +works in a user unit; in a system unit write the full path). Codeman's downloads and +attachments refuse the configured secret file. + +`CODEMAN_TRUSTED_PROXY_SECRET` (the value itself) works too. Codeman reads the settings +once and removes both variables from its environment, so sessions started later don't +inherit them. That is all it does: the value stays visible in `/proc//environ` for as +long as the server runs, and a tmux server started earlier with it set keeps its own copy +until restarted. Prefer the file. + +Password sign-in stays available for requests that reach Codeman without the proxy. +Codeman's own tools need it: `codeman agent`, `mcp`, `notify`, `attach` and `tui` and the +Codeman skill sign in on loopback with `CODEMAN_USERNAME` / `CODEMAN_PASSWORD`. Such a +request is not checked by the identity provider, so its MFA does not apply to it. For a +person who only ever signs in through the proxy, create the account without a password: +Codeman generates a random one-time password, which you can discard. The account then +keeps its `must-change-pw` label in the Admin Panel; the label has no effect on proxy +sign-ins. + +### oauth2-proxy + +Register an OIDC app with your identity provider (redirect URI +`https://codeman.example.com/oauth2/callback`) and restrict it to the people who should +get in. A minimal `oauth2-proxy.cfg`: + +```toml +http_address = "127.0.0.1:4180" +reverse_proxy = true +provider = "oidc" +oidc_issuer_url = "https://login.microsoftonline.com//v2.0" # your provider +redirect_url = "https://codeman.example.com/oauth2/callback" +whitelist_domains = ["codeman.example.com"] +email_domains = ["example.com"] +set_xauthrequest = true # return the identity as X-Auth-Request-* headers +skip_provider_button = true +upstreams = ["static://202"] # forward_auth only, nothing to proxy +cookie_secure = true +cookie_expire = "12h" # sign in again after this (default 168h) +cookie_refresh = "1h" # re-check with the provider this often +scope = "openid email profile offline_access" # offline_access: a refresh token (Entra ID) +``` + +Client ID, client secret and cookie secret go in the environment +(`OAUTH2_PROXY_CLIENT_ID`, `OAUTH2_PROXY_CLIENT_SECRET`, `OAUTH2_PROXY_COOKIE_SECRET`). +For Entra ID add `oidc_email_claim = "preferred_username"`. Without `cookie_refresh`, a +person disabled at the provider keeps access until the cookie expires. `cookie_refresh` +needs a refresh token: without one (for Entra ID, without `offline_access` in the scope), +oauth2-proxy can't refresh, and people are sent back through sign-in whenever the ID token +expires, about hourly. + +### Caddy + +Give Caddy the same secret through its environment, not in the Caddyfile (which is often +world-readable): for the packaged service, a systemd drop-in with +`EnvironmentFile=/etc/caddy/codeman-proxy.env` (mode 0600) containing +`CODEMAN_TRUSTED_PROXY_SECRET=`. Keep the `{env.…}` placeholder below; a `{$…}` +placeholder would put the value into the adapted config, which local processes can read +from Caddy's admin port. + +```caddyfile +codeman.example.com { + # Signed-in identity -> Codeman username (case-sensitive: use the spelling your + # provider returns). Unlisted people get an empty username and are refused below. + map {http.request.header.X-Auth-Request-Email} {codeman_user} { + alice@example.com alice + default "" + } + + # Hooks call 127.0.0.1:3000 directly; never expose them (or their /api/v1 aliases). + @hooks path /api/hook-event /api/status-telemetry /api/v1/hook-event /api/v1/status-telemetry + # Web tabs and rendered HTML files authenticate by the capability in their URL: their + # sandboxed frames send no cookies, so they can't pass the sign-in below. + @capability path /webview/* /html-view/* + + # `route` keeps the order as written. Without it Caddy sorts directives itself, and + # `handle` would run before `respond`, or forward_auth before request_header. + route { + respond @hooks 403 + + handle /oauth2/* { + reverse_proxy 127.0.0.1:4180 { + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + handle @capability { + # No sign-in and no secret: Codeman checks the capability itself. No password + # either: these paths must never reach Codeman's password check or prompt. + request_header -X-Codeman-Proxy-Secret + request_header -X-Codeman-User + request_header -Authorization + # oauth2-proxy's cookie is a sign-in for this whole site. Codeman never needs + # it, and its web-tab relay forwards browser cookies to a dashboard opened in + # trusted mode. + request_header Cookie "(^|;\s*)_oauth2_proxy[^=;]*=[^;]*" "" + reverse_proxy 127.0.0.1:3000 { + header_down -WWW-Authenticate + } + } + + handle { + route { + # Only oauth2-proxy and this file may set identity headers. + request_header -X-Auth-Request-Email + request_header -X-Codeman-Proxy-Secret + request_header -X-Codeman-User + + forward_auth 127.0.0.1:4180 { + uri /oauth2/auth + copy_headers X-Auth-Request-Email + @unauthenticated status 401 + handle_response @unauthenticated { + redir * /oauth2/start?rd={scheme}://{hostport}{uri} + } + } + + @nouser vars {codeman_user} "" + respond @nouser "No Codeman account for this sign-in" 403 + + # After forward_auth, which needs it: remove oauth2-proxy's cookie. + request_header Cookie "(^|;\s*)_oauth2_proxy[^=;]*=[^;]*" "" + + reverse_proxy 127.0.0.1:3000 { + header_up X-Codeman-Proxy-Secret {env.CODEMAN_TRUSTED_PROXY_SECRET} + header_up X-Codeman-User {codeman_user} + } + } + } + } +} +``` + +This example was run with Caddy 2.11.9 and oauth2-proxy 7.15.6. What it relies on, because +Codeman cannot see a mistake here: + +- **The proxy removes what the client sent.** The `request_header -…` lines delete any + copy of the identity headers that arrived from outside, and `header_up` replaces a + header, it never appends. The username therefore only ever comes from the sign-in result. +- **The secret is added only behind the sign-in**, never on the `/webview/*` and + `/html-view/*` route. +- **The proxy's own cookie stops at the proxy.** The `request_header Cookie …` lines remove + it on both routes. With a different `cookie_name` in oauth2-proxy, change the name in + the pattern. + +Check the order Caddy will actually use with +`caddy adapt --config Caddyfile --adapter caddyfile` before going live. With +`CODEMAN_BASE_URL` (a sub-path mount), prefix the paths in `@hooks` and `@capability`. + +To check that a forged header is ignored, run this in the browser console of the signed-in +page. It must show your own username: + +```js +fetch('/api/me', { headers: { 'X-Codeman-User': 'someone-else' } }).then((r) => r.json()).then(console.log) +``` + +### Taking the username from the identity provider instead + +The `map` is a list you maintain. If your provider can put the Codeman username into the +ID token (for example the AD logon name: Entra ID can add it with a claims mapping policy +that emits `user.onpremisessamaccountname` as a custom claim; the app then needs +`acceptMappedClaims` enabled), let oauth2-proxy return that claim as a header. That needs +oauth2-proxy 7.15.5 or later with its alpha config (`--alpha-config`), and the claim must +be listed in the provider's `additionalClaims`, otherwise the header stays empty: + +```yaml +providers: + - id: idp + provider: oidc + # ... clientID, clientSecretFile, oidcConfig ... + additionalClaims: + - samaccountname +injectResponseHeaders: + - name: X-Auth-Request-Codeman-User + values: + - claimSource: + claim: samaccountname +``` + +In the Caddyfile, drop the `map` and replace the inner `route` of the last `handle`: + +```caddyfile +route { + request_header -X-Auth-Request-Email + request_header -X-Auth-Request-Codeman-User + request_header -X-Codeman-Proxy-Secret + request_header -X-Codeman-User + + forward_auth 127.0.0.1:4180 { + uri /oauth2/auth + copy_headers X-Auth-Request-Email X-Auth-Request-Codeman-User + @unauthenticated status 401 + handle_response @unauthenticated { + redir * /oauth2/start?rd={scheme}://{hostport}{uri} + } + } + + @nouser vars {http.request.header.X-Auth-Request-Codeman-User} "" + respond @nouser "No Codeman username for this sign-in" 403 + + request_header Cookie "(^|;\s*)_oauth2_proxy[^=;]*=[^;]*" "" + + reverse_proxy 127.0.0.1:3000 { + header_up X-Codeman-Proxy-Secret {env.CODEMAN_TRUSTED_PROXY_SECRET} + header_up X-Codeman-User {http.request.header.X-Auth-Request-Codeman-User} + } +} +``` + +Adding a person is then: allow them at the identity provider, and +`codeman users add `. Codeman usernames allow letters, digits, `_` and `-` only, so +the claim must fit that. A browser that signed in before the claim existed needs to sign +out (`/oauth2/sign_out`) and in again. + +### Things to know + +- **No Codeman cookie is issued** for proxy sign-ins. The proxy authorizes every new + request and WebSocket upgrade, but a terminal or live-update connection that is already + open stays open until it disconnects. +- **Cutting someone off:** disable their Codeman account (new requests are refused), then + use **Logout** for them in the Admin Panel, which also revokes the web-tab and HTML-view + links they opened (disabling alone doesn't, and those links don't need the proxy's + sign-in). Deleting the account does both. Logout alone, or a password reset, does not + cut off a proxy sign-in: it holds no cookie and uses no password, so the next request + signs the person in again. Connections already open stay open until they disconnect. +- **Web tabs and HTML view behind the proxy:** with trusted-proxy sign-in configured, a + path under those prefixes without a live capability, malformed ones included, is refused + (`403` / `404`) without a password check, + prompt or failure count, so anonymous requests can't probe passwords or lock out the + password sign-in. +- **When the proxy session expires**, API calls and the live-update stream get a redirect + to the sign-in page instead of a `401`; reload the page. The `rd=` return address is not + URL-encoded, so a query string with `&` loses everything after the first one. +- **`mustChangePassword` is ignored** for proxy sign-ins, since no Codeman password was + used, and `GET /api/me` reports it as `false` for them. A person's own "Revoke all" and logout end Codeman cookies, not the proxy's + session; sign out of the proxy at `/oauth2/sign_out`. +- **A wrong or empty secret is refused outright** (and failures are rate-limited per IP); + it never falls back to the cookie or password sign-in. +- **Sandboxed web tabs:** a request the dashboard makes outside its + `/webview//` prefix (a root-absolute asset the rewriting missed, or a page + that reloads itself) goes through the proxy's sign-in, carries no cookie and fails + there. Codeman's `Referer` relay and lost-frame recovery never see it. Dashboards that + use relative URLs work; for the others use trusted mode or a new browser tab. +- **Trusted web tabs** forward the browser's cookies to their dashboard. The proxy's + sign-in cookie would be among them, which is why the Caddy example removes it. +- **Docker Compose installs** can't use this: the proxy on the host reaches the container + from the bridge address, not loopback. +- **Audit log:** admin actions through the proxy are recorded with IP `127.0.0.1`. ## Gotchas diff --git a/docs/wiki/Settings-Reference.md b/docs/wiki/Settings-Reference.md index 5bfd53a2..4c92a38f 100644 --- a/docs/wiki/Settings-Reference.md +++ b/docs/wiki/Settings-Reference.md @@ -299,6 +299,9 @@ Some things are configured before the server starts, not in the UI: | `CODEMAN_ALLOWED_HOSTS` | Extra Host and Origin allowlist entries for a reverse proxy. | | `CODEMAN_INSTANCE` | Scopes the data directory and tmux socket together. Required for a second instance. | | `CODEMAN_MULTIUSER` | Enables multi-user mode. | +| `CODEMAN_TRUSTED_PROXY_SECRET_FILE` | Experimental, multi-user only. A file (mode 600) holding the secret that lets an authenticating reverse proxy on the same host sign people in (single sign-on). A setup that cannot be used stops the start. See [Multi-User Mode](Multi-User-Mode#single-sign-on-through-a-reverse-proxy). | +| `CODEMAN_TRUSTED_PROXY_SECRET` | The same secret given directly. Both variables are read once at startup and then removed from the environment, so sessions don't inherit them; the file variant is preferred. | +| `CODEMAN_TRUSTED_PROXY_USER_HEADER` | Header that proxy puts the Codeman username in. `X-Codeman-User` by default; only an `X-…` header or `Remote-User` is accepted. | | `CODEMAN_GESTURE` | Makes gesture control available to be enabled. | | `CODEMAN_DOCKER_BRIDGE_HOOKS` | Lets in-container hooks reach the host on a loopback bind. | | `CODEMAN_FILE_PICKER_ROOTS` | Extra roots for the path picker. | diff --git a/docs/wiki/Web-Tabs.md b/docs/wiki/Web-Tabs.md index b22e5010..56857762 100644 --- a/docs/wiki/Web-Tabs.md +++ b/docs/wiki/Web-Tabs.md @@ -97,7 +97,10 @@ The reason: an opaque-origin frame's stylesheet, script, and API requests do not proxy's authentication cookie. The proxy redirects them to the login provider, and CORS or CSP kills them there. -Trusted mode keeps a real origin and the cookie, so it works. Test cannot catch this, because +Trusted mode keeps a real origin and the cookie, so it works. In trusted mode Codeman +forwards the browser's cookies to the dashboard, and that includes the proxy's own session +cookie unless the proxy removes it from what it forwards to Codeman (the Caddy example in +[Multi-User Mode](Multi-User-Mode#single-sign-on-through-a-reverse-proxy) does). Test cannot catch this, because it checks the server's reach, not the browser's. ## Security notes diff --git a/src/config/trusted-proxy.ts b/src/config/trusted-proxy.ts new file mode 100644 index 00000000..8307bd1a --- /dev/null +++ b/src/config/trusted-proxy.ts @@ -0,0 +1,258 @@ +/** + * @fileoverview Trusted reverse-proxy identity (multi-user mode, opt-in, off by default). + * + * Lets an authenticating reverse proxy on the same host (oauth2-proxy behind Caddy or + * nginx, Apache mod_auth_openidc, Authelia, ...) sign users in through an identity + * provider such as Entra ID, Google or Keycloak, instead of the Basic-auth password + * prompt. The proxy authenticates the person and forwards two headers: + * + * X-Codeman-Proxy-Secret: + * X-Codeman-User: + * + * Codeman accepts the identity only when ALL of these hold: + * - multi-user mode is on (the username must name an existing, enabled account; there + * is no auto-provisioning, so an admin still decides who has an account); + * - a secret is configured: at least 32 printable ASCII characters, from + * `CODEMAN_TRUSTED_PROXY_SECRET_FILE` (preferred) or `CODEMAN_TRUSTED_PROXY_SECRET`; + * - the request arrives over a loopback socket (`req.ip`, which ignores + * X-Forwarded-For because Fastify runs with `trustProxy: false`); + * - the presented secret matches (timing-safe). + * + * What the secret does and does not separate: every process on the host reaches the + * loopback port, so loopback alone proves nothing, and the secret is what a local process + * lacks. It is not a boundary against code that can read the secret file or Codeman's + * memory, i.e. anything running as Codeman's OS account (see the multi-user threat + * model: sessions share that account). To keep it out of the obvious places, the value + * 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. + * + * A configured setup that can't be used stops the server from starting + * (`trustedProxyConfigError`, thrown from `WebServer.start()`), so a typo never falls + * back silently to password sign-in. + * + * The two headers are taken off every request before anything else sees them + * (`takeTrustedProxyHeaders`, called from the first auth hook), so nothing downstream, + * e.g. the web-tab relay, can forward or log them. + */ + +import { readFileSync, statSync } from 'node:fs'; +import type { IncomingHttpHeaders } from 'node:http'; +import { resolve } from 'node:path'; + +/** Header carrying the shared secret that proves the request came through the proxy. */ +export const TRUSTED_PROXY_SECRET_HEADER = 'x-codeman-proxy-secret'; + +/** Default header carrying the authenticated Codeman username. */ +export const DEFAULT_TRUSTED_PROXY_USER_HEADER = 'x-codeman-user'; + +/** Minimum secret length; a shorter secret stops the server from starting. */ +export const TRUSTED_PROXY_SECRET_MIN_LENGTH = 32; + +/** + * The username header is deleted from EVERY request (see takeTrustedProxyHeaders), so it + * must never be a header anything else needs. Allowed by shape, not by a deny list of + * standard headers: an `X-...` extension header (minus the reserved ones below) or the + * conventional `Remote-User`. + */ +const USER_HEADER_RE = /^x-[a-z0-9][a-z0-9-]*$/; +/** Identity headers authenticating proxies commonly send; allowed despite the reserved prefix. */ +const ALLOWED_FORWARDED_IDENTITY_HEADERS = new Set([ + 'x-forwarded-user', + 'x-forwarded-email', + 'x-forwarded-preferred-username', +]); +const RESERVED_USER_HEADER_PREFIXES = ['x-forwarded-', 'x-codeman-']; +const RESERVED_USER_HEADERS = new Set([ + 'x-real-ip', + 'x-requested-with', + 'x-http-method-override', + 'x-csrf-token', + 'x-xsrf-token', +]); + +/** Resolved trusted-proxy configuration, or null when the feature is off. */ +export interface TrustedProxyConfig { + secret: string; + /** Lower-cased header name the username is read from. */ + userHeader: string; +} + +interface LoadedSecret { + secret?: string; + /** Why a configured secret can't be used (never contains the secret). */ + problem?: string; + /** Absolute path of `CODEMAN_TRUSTED_PROXY_SECRET_FILE`, when it was set. */ + filePath?: string; +} + +let loaded: LoadedSecret | null = null; + +/** + * Read the secret once, then delete `CODEMAN_TRUSTED_PROXY_SECRET` and + * `CODEMAN_TRUSTED_PROXY_SECRET_FILE` from `process.env` so sessions spawned later don't + * inherit either. Cached for the process lifetime. + */ +function loadSecret(): LoadedSecret { + if (loaded) return loaded; + const inline = process.env.CODEMAN_TRUSTED_PROXY_SECRET?.trim(); + const file = process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE?.trim(); + delete process.env.CODEMAN_TRUSTED_PROXY_SECRET; + delete process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE; + const filePath = file ? resolve(file) : undefined; + + let secret: string | undefined; + let problem: string | undefined; + if (inline && file) { + problem = 'both CODEMAN_TRUSTED_PROXY_SECRET and CODEMAN_TRUSTED_PROXY_SECRET_FILE are set; set only one'; + } else if (file) { + try { + secret = readFileSync(file, 'utf-8').trim() || undefined; + if (!secret) problem = `CODEMAN_TRUSTED_PROXY_SECRET_FILE (${file}) is empty`; + // POSIX modes only; Windows reports synthetic ones. + else if (process.platform !== 'win32' && (statSync(file).mode & 0o077) !== 0) { + problem = `CODEMAN_TRUSTED_PROXY_SECRET_FILE (${file}) is readable by other users; chmod 600 it`; + } + } catch (err) { + problem = `cannot read CODEMAN_TRUSTED_PROXY_SECRET_FILE (${file}): ${(err as NodeJS.ErrnoException).code ?? 'error'}`; + } + } else if (inline) { + secret = inline; + } + if (secret && !problem) { + if (secret.length < TRUSTED_PROXY_SECRET_MIN_LENGTH) { + problem = `the trusted-proxy secret is shorter than ${TRUSTED_PROXY_SECRET_MIN_LENGTH} characters (generate one with: openssl rand -hex 32)`; + } else if (!/^[\x21-\x7e]+$/.test(secret)) { + // Header bytes arrive as latin1 and the env/file value as UTF-8, so anything outside + // printable ASCII could never match. + problem = + 'the trusted-proxy secret must be printable ASCII without spaces (generate one with: openssl rand -hex 32)'; + } + } + loaded = { secret, problem, filePath }; + return loaded; +} + +/** + * 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 + * spawned or restored, in every mode. + */ +export function initTrustedProxySecret(): void { + loadSecret(); +} + +/** + * Absolute path of the configured secret file, or null. After the secret was read the + * variable is gone from `process.env`, so this answers from the cached value; before + * that, from the environment. Never reads the file. + */ +export function trustedProxySecretFilePath(): string | null { + if (loaded) return loaded.filePath ?? null; + const file = process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE?.trim(); + return file ? resolve(file) : null; +} + +/** Test-only: forget the cached secret so the next call re-reads the environment. */ +export function resetTrustedProxySecretForTests(): void { + loaded = null; +} + +/** The configured username header (lower-cased), or the default. Not validated. */ +function rawUserHeader(): string { + return process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER?.trim().toLowerCase() || DEFAULT_TRUSTED_PROXY_USER_HEADER; +} + +/** Why the configured username header can't be used, or null when it is fine. */ +function userHeaderProblem(name: string): string | null { + if (name === DEFAULT_TRUSTED_PROXY_USER_HEADER || name === 'remote-user') return null; + if (ALLOWED_FORWARDED_IDENTITY_HEADERS.has(name)) return null; + if (!USER_HEADER_RE.test(name)) { + return `CODEMAN_TRUSTED_PROXY_USER_HEADER (${name}) must be an X-... header or Remote-User`; + } + if (RESERVED_USER_HEADERS.has(name) || RESERVED_USER_HEADER_PREFIXES.some((p) => name.startsWith(p))) { + return `CODEMAN_TRUSTED_PROXY_USER_HEADER may not be ${name} (reserved)`; + } + return null; +} + +/** + * The username header to strip and read: the configured one when it is usable, the default + * otherwise. Resolve it once (at auth setup) and pass it to `takeTrustedProxyHeaders`. A + * rejected name is never used, so a careless setting can't strip a header others need. + */ +export function resolveTrustedProxyUserHeader(): string { + const name = rawUserHeader(); + return userHeaderProblem(name) ? DEFAULT_TRUSTED_PROXY_USER_HEADER : name; +} + +/** + * The active configuration, or null when the feature is off: no usable secret, an + * unusable username header, or single-user mode (no named accounts to map onto). The + * unusable cases also stop the start (`trustedProxyConfigError`); this is the second layer. + */ +export function getTrustedProxyConfig(multiUser: boolean): TrustedProxyConfig | null { + const { secret, problem } = loadSecret(); + if (!multiUser || !secret || problem) return null; + const userHeader = rawUserHeader(); + if (userHeaderProblem(userHeader)) return null; + return { secret, userHeader }; +} + +/** + * Why a configured trusted-proxy setup can't be used, as the message for the start-up + * refusal, or null when it is fine (not configured, or valid). Never includes the secret. + * Refused: both secret variables set; a secret file that can't be read, is empty or is + * readable by group or others (not checked on Windows); a secret shorter than 32 + * characters or not printable ASCII; a secret with multi-user mode off; and a + * `CODEMAN_TRUSTED_PROXY_USER_HEADER` the validation rejects (set at all, secret or not). + */ +export function trustedProxyConfigError(multiUser: boolean): string | null { + const { secret, problem } = loadSecret(); + let reason: string | null = null; + if (problem) reason = problem; + else if (secret && !multiUser) reason = 'a trusted-proxy secret is set but multi-user mode is off'; + else if (process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER?.trim()) reason = userHeaderProblem(rawUserHeader()); + return reason + ? `Trusted-proxy sign-in is misconfigured: ${reason}. Fix or remove the setting and start again.` + : null; +} + +/** What a request presented, after `takeTrustedProxyHeaders` removed the headers. */ +export interface PresentedProxyHeaders { + /** True when the secret header was present at all, even empty. */ + secretPresent: boolean; + /** The presented secret (duplicates joined with ", ", so they never match). */ + secret: string; + /** + * The presented username exactly as sent ('' when absent). The auth hook normalizes and + * validates it with the user store's own rule. A duplicated header arrives joined + * ("alice, bob"), which that rule rejects, so it is refused with 403. + */ + user: string; +} + +/** + * 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. + */ +export function takeTrustedProxyHeaders( + headers: IncomingHttpHeaders, + userHeader: string = DEFAULT_TRUSTED_PROXY_USER_HEADER +): PresentedProxyHeaders { + const rawSecret = headers[TRUSTED_PROXY_SECRET_HEADER]; + const rawUser = headers[userHeader]; + delete headers[TRUSTED_PROXY_SECRET_HEADER]; + delete headers[DEFAULT_TRUSTED_PROXY_USER_HEADER]; + delete headers[userHeader]; + + return { + secretPresent: rawSecret !== undefined, + secret: Array.isArray(rawSecret) ? rawSecret.join(', ') : (rawSecret ?? ''), + user: Array.isArray(rawUser) ? rawUser.join(', ') : (rawUser ?? ''), + }; +} diff --git a/src/types/user.ts b/src/types/user.ts index 904cbb9f..511fe815 100644 --- a/src/types/user.ts +++ b/src/types/user.ts @@ -50,6 +50,12 @@ export interface UsersFile { export interface AuthUser { username: string; role: UserRole; + /** + * True when a trusted reverse proxy vouched for this request (see + * src/config/trusted-proxy.ts), so no Codeman password was involved. Absent for + * cookie, Basic and QR sign-ins. + */ + viaTrustedProxy?: boolean; } /** Admin-facing projection of a user: never carries the password hash. */ diff --git a/src/web/middleware/auth.ts b/src/web/middleware/auth.ts index ea7c7767..b5b7be06 100644 --- a/src/web/middleware/auth.ts +++ b/src/web/middleware/auth.ts @@ -10,6 +10,7 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; +import { posix } from 'node:path'; import { StaleExpirationMap } from '../../utils/index.js'; import type { AuthSessionRecord } from '../ports/auth-port.js'; import { isAllowedRequestHost, isAllowedRequestOrigin, type HostPolicy } from '../network-auth-policy.js'; @@ -22,9 +23,25 @@ import { } from '../../config/auth-config.js'; import { getHookSecret, HOOK_SECRET_HEADER } from '../../config/hook-secret.js'; import { isMultiUserMode } from '../../config/multiuser.js'; -import { findUser, setPassword, touchLastLogin, verifyPassword } from '../../user-store.js'; +import { + getTrustedProxyConfig, + initTrustedProxySecret, + resolveTrustedProxyUserHeader, + takeTrustedProxyHeaders, + type PresentedProxyHeaders, + type TrustedProxyConfig, +} from '../../config/trusted-proxy.js'; +import { + findUser, + isValidUsername, + normalizeUsername, + setPassword, + touchLastLogin, + verifyPassword, +} from '../../user-store.js'; import { webviewCapabilities } from '../../webview-capabilities.js'; -import { capabilityFromHtmlViewPath, htmlViewCapabilities } from '../../html-view-capabilities.js'; +import { capabilityFromHtmlViewPath, HTML_VIEW_PREFIX, htmlViewCapabilities } from '../../html-view-capabilities.js'; +import { WEBVIEW_PROXY_PREFIX } from '../../config/webview-limits.js'; import { capabilityFromProxyPath, capabilityFromReferer, @@ -56,6 +73,8 @@ interface AuthState { userFailures: StaleExpirationMap | null; /** Per-(username, client IP) Basic-auth failure bucket (multi-user only). */ userIpFailures: StaleExpirationMap | null; + /** Wrong trusted-proxy secret presentations, per client IP (multi-user + proxy secret only). */ + proxySecretFailures: StaleExpirationMap | null; } /** Rate-limit response for a client that exceeded the failure cap. */ @@ -112,9 +131,7 @@ function checkHookSecretBypass( hookSecretFailures: StaleExpirationMap ): 'bypass' | 'rejected' | 'continue' { if ((req.url === '/api/hook-event' || req.url === '/api/status-telemetry') && req.method === 'POST') { - const ip = req.ip; - const isLoopback = ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1'; - if (isLoopback) { + if (isLoopbackIp(req.ip)) { const presented = Buffer.from(req.headers[HOOK_SECRET_HEADER.toLowerCase()]?.toString() ?? ''); const expected = Buffer.from(getHookSecret()); if (presented.length === expected.length && timingSafeEqual(presented, expected)) { @@ -135,6 +152,111 @@ function checkHookSecretBypass( return 'continue'; } +/** Whether a socket address is loopback. The one test both secret-gated paths (hook, proxy) use. */ +function isLoopbackIp(ip: string): boolean { + return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1'; +} + +/** + * The trusted-proxy headers each request presented, keyed by request. Filled by the first + * auth hook (`registerTrustedProxyHeaderStrip`), which also deletes the headers from the + * request; read by `checkTrustedProxyIdentity`. A WeakMap, so nothing outlives the request. + */ +const presentedProxyHeaders = new WeakMap(); + +/** Minimum interval between `touchLastLogin` writes for proxy sign-ins, per user. */ +const PROXY_LAST_LOGIN_INTERVAL_MS = 15 * 60 * 1000; + +/** + * Take the trusted-proxy headers off EVERY request before any other auth logic, route or + * exemption (web-tab relay, HTML view, QR) can see them, in every auth mode. Registered + * first in `registerAuthMiddleware`, i.e. right after the Host guard. + */ +function registerTrustedProxyHeaderStrip(app: FastifyInstance): void { + const userHeader = resolveTrustedProxyUserHeader(); + app.addHook('onRequest', (req, _reply, done) => { + presentedProxyHeaders.set(req, takeTrustedProxyHeaders(req.headers, userHeader)); + done(); + }); +} + +/** + * Trusted reverse-proxy identity (see src/config/trusted-proxy.ts). Returns: + * - 'continue' : no proxy secret header; fall through to cookie / Basic auth + * - 'authenticated' : req.authUser is set from the proxy's username header + * - 'rejected' : a reply was already sent + * + * Fails CLOSED once the secret header is present at all, even empty: a wrong secret or a + * non-loopback source (401), or a missing username, one the user store's rule rejects, + * or one with no enabled account (403, no challenge) is refused outright and never falls + * through to the cookie or Basic paths, so a misconfigured proxy cannot silently degrade + * into some other identity. A username header WITHOUT the secret header is ignored + * (normal auth applies). + * + * The username is matched exactly, by the store's own rule (`normalizeUsername`, then + * `isValidUsername`): no cutting at `@`, no character replacement. A duplicated header + * arrives joined ("alice, bob") and fails that rule. + * + * The secret is compared BEFORE the failure bucket is consulted, like the hook secret: + * a correct secret always passes, so local junk requests (which share 127.0.0.1 with + * the proxy) cannot lock sign-in out. Only failures are counted and throttled, in their + * own per-IP bucket, so a broken proxy cannot lock out the Basic or hook paths either. + */ +async function checkTrustedProxyIdentity( + req: FastifyRequest, + reply: FastifyReply, + config: TrustedProxyConfig, + proxySecretFailures: StaleExpirationMap, + lastLoginTouched: Map +): Promise<'continue' | 'authenticated' | 'rejected'> { + const presented = presentedProxyHeaders.get(req); + if (!presented?.secretPresent) return 'continue'; + + const clientIp = req.ip; + const given = Buffer.from(presented.secret); + const expected = Buffer.from(config.secret); + const secretOk = isLoopbackIp(clientIp) && given.length === expected.length && timingSafeEqual(given, expected); + if (!secretOk) { + const failures = proxySecretFailures.get(clientIp) ?? 0; + if (failures >= AUTH_FAILURE_MAX) { + sendAuthRateLimit(reply, proxySecretFailures, clientIp); + return 'rejected'; + } + proxySecretFailures.set(clientIp, failures + 1); + reply.code(401).send('Unauthorized: trusted proxy secret rejected'); + return 'rejected'; + } + + // The proxy vouched for the request, so none of the refusals below is a failed guess: + // 403, no challenge, no bucket. + const username = normalizeUsername(presented.user); + if (!username) { + reply.code(403).send('Forbidden: trusted proxy sent no username'); + return 'rejected'; + } + let user: Awaited>; + try { + user = isValidUsername(username) ? await findUser(username) : undefined; + } catch { + reply.code(503).send('Service Unavailable: user store unreadable'); + return 'rejected'; + } + if (!user || user.disabled) { + reply.code(403).send('Forbidden: no enabled Codeman account for this user'); + return 'rejected'; + } + // No mustChangePassword lockbox: the person did not sign in with a Codeman password, + // so a pending one-time password has nothing to do with this request. + req.authUser = { username: user.username, role: user.role, viaTrustedProxy: true }; + // Keep "last login" meaningful for proxy sign-ins, without a store write per request. + const now = Date.now(); + if (now - (lastLoginTouched.get(user.username) ?? 0) >= PROXY_LAST_LOGIN_INTERVAL_MS) { + lastLoginTouched.set(user.username, now); + void touchLastLogin(user.username).catch(() => {}); + } + return 'authenticated'; +} + /** * Requests that a `mustChangePassword` user may still reach: the identity probe, * the password-change endpoint, and any non-API path (static assets / index.html, @@ -269,6 +391,64 @@ export function isLostWebviewRootFrame(req: FastifyRequest): boolean { return !carriesAuthCredentials(req.headers, AUTH_COOKIE_NAME); } +/** + * Which capability prefix a request falls under, judged the way a reverse proxy's path + * matcher does: query dropped, percent-decoded once, dot segments and doubled slashes + * resolved, case-insensitive. A proxy forwards everything it matches this way WITHOUT its + * 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. + */ +export function capabilityPrefixOf(rawUrl: string): 'webview' | 'html-view' | null { + let path = rawUrl.split('?')[0]; + try { + path = decodeURIComponent(path); + } catch { + // Malformed escape: judge the raw path. + } + // Fold U+0130 (capital I with dot above) to a plain "i" first: Go's lowercasing, which + // Caddy's matcher uses, does that, while toLowerCase() yields "i" + U+0307 and would miss + // the prefix. Written as an escape so Unicode normalisation can't split it. + path = posix + .normalize(path) + .replace(/\u0130/g, 'i') + .toLowerCase(); + if (path.startsWith(`${WEBVIEW_PROXY_PREFIX}/`)) return 'webview'; + if (path.startsWith(`${HTML_VIEW_PREFIX}/`)) return 'html-view'; + return null; +} + +/** + * A request under a capability prefix (`/webview/...`, `/html-view/...`, judged by + * `capabilityPrefixOf`) that the capability exemptions above did NOT let through: no live + * capability, whatever the token looks like (or a method the exemption never covers). + * Refused here with what the route answers an authenticated caller for an unknown + * capability (403 for a web tab, 404 for an HTML view), WITHOUT a Basic challenge and + * WITHOUT counting a failure. + * + * Only used when trusted-proxy sign-in is configured. There, these paths reach Codeman + * WITHOUT the proxy's own sign-in (their sandboxed frames carry no credentials, so the + * proxy has to let them through; see the trusted-proxy docs). Falling through to the + * credential checks would expose the password check and a `WWW-Authenticate` prompt to + * anyone who can reach the proxy, and let anonymous requests fill the per-IP failure + * bucket, which behind the proxy is always 127.0.0.1, locking out Basic sign-in from + * loopback. Without a proxy, these paths keep the normal 401 challenge. + * + * @returns true when the reply was sent. + */ +function serveRefusedCapabilityPath(req: FastifyRequest, reply: FastifyReply): boolean { + const kind = capabilityPrefixOf(req.url ?? ''); + if (kind === 'webview') { + reply.code(403).type('text/plain').send('Forbidden: unknown or expired webview capability'); + return true; + } + if (kind === 'html-view') { + reply.code(404).header('Content-Type', 'text/plain; charset=utf-8').send('Not found'); + return true; + } + return false; +} + /** Send the static recovery page (lostWebviewFramePage) with its own CSP, uncached. */ export function sendLostWebviewFramePage(reply: FastifyReply): FastifyReply { reply.header('content-security-policy', LOST_FRAME_PAGE_CSP); @@ -323,12 +503,18 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas hookSecretFailures: null, userFailures: null, userIpFailures: null, + proxySecretFailures: null, }; // Always declare req.authUser so downstream reads are safe (single-user leaves it // undefined; the ownership helpers then default to a synthetic admin). if (!app.hasRequestDecorator('authUser')) app.decorateRequest('authUser', undefined); + // First, in every auth mode: take the trusted-proxy headers off the request, so no + // later hook, exemption or route (e.g. the web-tab relay) can forward the secret. + registerTrustedProxyHeaderStrip(app); + initTrustedProxySecret(); + const multiUser = isMultiUserMode(); const authPassword = process.env.CODEMAN_PASSWORD; @@ -387,6 +573,15 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas ttlMs: AUTH_FAILURE_WINDOW_MS, refreshOnGet: false, }); + // Trusted reverse-proxy identity (opt-in). Its own failure bucket, like the hook + // secret's, so wrong proxy secrets never count against the Basic login path. + const trustedProxy = getTrustedProxyConfig(true); + if (trustedProxy) { + state.proxySecretFailures = new StaleExpirationMap({ + ttlMs: AUTH_FAILURE_WINDOW_MS, + refreshOnGet: false, + }); + } registerMultiUserAuthHook( app, https, @@ -395,7 +590,10 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean, bas hookSecretFailures, state.userFailures, state.userIpFailures, - basePath + basePath, + trustedProxy && state.proxySecretFailures + ? { config: trustedProxy, failures: state.proxySecretFailures, lastLoginTouched: new Map() } + : null ); return state; } @@ -517,7 +715,12 @@ function registerMultiUserAuthHook( hookSecretFailures: StaleExpirationMap, userFailures: StaleExpirationMap, userIpFailures: StaleExpirationMap, - basePath = '' + basePath = '', + trustedProxy: { + config: TrustedProxyConfig; + failures: StaleExpirationMap; + lastLoginTouched: Map; + } | null = null ): void { const setSessionCookie = (reply: FastifyReply, token: string) => reply.setCookie(AUTH_COOKIE_NAME, token, { @@ -642,6 +845,25 @@ function registerMultiUserAuthHook( if (hasValidHtmlViewCapability(req)) return; // A web-tab frame that lost its prefix: hand it back to its tab, no credentials involved. 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; + + // 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 + // from an earlier Basic login in the same browser must not override it. No cookie + // is minted: the proxy presents the identity on every new request and WebSocket + // upgrade. A stream that is already open is not re-checked. + if (trustedProxy) { + const proxied = await checkTrustedProxyIdentity( + req, + reply, + trustedProxy.config, + trustedProxy.failures, + trustedProxy.lastLoginTouched + ); + if (proxied !== 'continue') return; + } const clientIp = req.ip; diff --git a/src/web/routes/me-routes.ts b/src/web/routes/me-routes.ts index ef1ba082..870bf5ed 100644 --- a/src/web/routes/me-routes.ts +++ b/src/web/routes/me-routes.ts @@ -1,7 +1,7 @@ /** * @fileoverview Self-service identity routes (multi-user + single-user). * - * - GET /api/me : who am I ({ username, role, mustChangePassword }). + * - GET /api/me : who am I ({ username, role, mustChangePassword, viaTrustedProxy }). * Works in single-user mode too, returning the synthetic * admin so the frontend has one "am I admin" code path. * - POST /api/me/password : change my own password (verifies the current one, @@ -35,13 +35,17 @@ export function registerMeRoutes(app: FastifyInstance, ctx: AuthPort): void { } const user = getAuthUser(req); const record = await findUser(user.username); + // A trusted-proxy sign-in never used the Codeman password, so a pending one-time + // password must not open the forced change-password modal (admin-ui.js). + const viaTrustedProxy = !!user.viaTrustedProxy; return { success: true, data: { username: user.username, role: user.role, - mustChangePassword: !!record?.mustChangePassword, + mustChangePassword: viaTrustedProxy ? false : !!record?.mustChangePassword, multiUser: true, + viaTrustedProxy, }, }; }); diff --git a/src/web/sensitive-path.ts b/src/web/sensitive-path.ts index a39f3cfb..ebc9d486 100644 --- a/src/web/sensitive-path.ts +++ b/src/web/sensitive-path.ts @@ -33,7 +33,9 @@ */ import { homedir } from 'node:os'; +import { realpathSync } from 'node:fs'; import { join } from 'node:path'; +import { trustedProxySecretFilePath } from '../config/trusted-proxy.js'; const SENSITIVE_PATTERNS: RegExp[] = [ // System account databases. @@ -81,6 +83,9 @@ const SENSITIVE_PATTERNS: RegExp[] = [ // Named individually so the surrounding trees stay attachable (see above). /\/\.claude\/\.credentials\.json$/, /\/\.codeman[^/]*\/hook-secret$/, + // Trusted reverse-proxy secret under its documented name (the configured path, whatever + // its name, is checked separately in isSensitivePath). + /\/\.codeman[^/]*\/proxy-secret$/, /\/\.codeman[^/]*\/users\.json$/, // The data dir's `.env` is the CODEMAN_USERNAME/PASSWORD fallback `codeman attach` // reads. Named here as well as in DOTENV_PATTERNS so `allowDotenv` (the File @@ -153,6 +158,23 @@ const DOTENV_PATTERNS: RegExp[] = [/\/\.env$/, /\/\.env\./]; */ const HOME_SENSITIVE_MEMBERS = ['.claude.json', '.claude/settings.json', '.claude/settings.local.json']; +/** + * 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. + */ +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; + } +} + /** * Returns true if the given ABSOLUTE, symlink-resolved path matches the * sensitive-file blocklist and must not be served to the browser. @@ -162,6 +184,7 @@ const HOME_SENSITIVE_MEMBERS = ['.claude.json', '.claude/settings.json', '.claud export function isSensitivePath(absPath: string, opts: { allowDotenv?: boolean } = {}): boolean { if (!opts.allowDotenv && DOTENV_PATTERNS.some((pattern) => pattern.test(absPath))) return true; if (SENSITIVE_PATTERNS.some((pattern) => pattern.test(absPath))) return true; + if (isTrustedProxySecretFile(absPath)) return true; const home = homedir(); return HOME_SENSITIVE_MEMBERS.some((member) => absPath === join(home, member)); } diff --git a/src/web/server.ts b/src/web/server.ts index 289a8a50..293afe61 100644 --- a/src/web/server.ts +++ b/src/web/server.ts @@ -216,6 +216,7 @@ import { sendLostWebviewFramePage, } from './middleware/auth.js'; import { isMultiUserMode } from '../config/multiuser.js'; +import { getTrustedProxyConfig, initTrustedProxySecret, trustedProxyConfigError } from '../config/trusted-proxy.js'; import { bootstrapInitialAdmin, findUser, hasUsers, resolveClaudeModeForUsername } from '../user-store.js'; import { installRouteErrorHandler } from './route-error-handler.js'; import { installEmptyApiPostParser } from './request-body-parser.js'; @@ -586,6 +587,7 @@ export class WebServer extends EventEmitter { private hookSecretFailures: StaleExpirationMap | null = null; private userFailures: StaleExpirationMap | null = null; private userIpFailures: StaleExpirationMap | null = null; + private proxySecretFailures: StaleExpirationMap | null = null; private pushStore: PushSubscriptionStore = new PushSubscriptionStore(); /** ntfy / Slack / Discord / generic webhook for the push events; config in webhook.json (0600). */ private webhookNotifier = new WebhookNotifier(() => readWebhookConfig(getDataDir()), webviewFetch); @@ -1119,6 +1121,7 @@ export class WebServer extends EventEmitter { this.hookSecretFailures = authState.hookSecretFailures; this.userFailures = authState.userFailures; this.userIpFailures = authState.userIpFailures; + this.proxySecretFailures = authState.proxySecretFailures; } // Bodyless API POSTs may arrive as empty chunked streams through a proxy. @@ -3470,6 +3473,14 @@ export class WebServer extends EventEmitter { } async start(): Promise { + // Trusted reverse-proxy sign-in (opt-in): read the secret now, which also removes it + // and the file path from process.env, and refuse to start on a configured setup that + // can't be used, so a typo never falls back silently to password sign-in. Not skipped + // in test mode: the refusal itself is under test. + initTrustedProxySecret(); + const proxyConfigError = trustedProxyConfigError(isMultiUserMode()); + if (proxyConfigError) throw new Error(proxyConfigError); + // Multi-user first boot: create the initial admin from CODEMAN_USERNAME/PASSWORD // if there are no users yet, else refuse to start (there would be no way in). if (isMultiUserMode() && !this.testMode) { @@ -3661,6 +3672,17 @@ export class WebServer extends EventEmitter { } } + // Trusted reverse-proxy sign-in (opt-in): say when it is on. An unusable setup never + // gets here (refused at the top of start()). + const proxyConfig = getTrustedProxyConfig(isMultiUserMode()); + if (proxyConfig) { + console.log( + palette.muted( + `Trusted-proxy sign-in enabled (experimental): loopback requests with the proxy secret sign in as the account named in ${proxyConfig.userHeader}.` + ) + ); + } + // Set API URL for child processes (MCP server, spawned sessions) const apiHost = this.host === '0.0.0.0' || this.host === 'localhost' || this.host === '::1' ? '127.0.0.1' : this.host; @@ -4886,6 +4908,10 @@ export class WebServer extends EventEmitter { this.userIpFailures.dispose(); this.userIpFailures = null; } + if (this.proxySecretFailures) { + this.proxySecretFailures.dispose(); + this.proxySecretFailures = null; + } this.activePlanOrchestrators.clear(); this.cleaningUp.clear(); this.killingSessions.clear(); diff --git a/src/web/webview-proxy.ts b/src/web/webview-proxy.ts index 6e242013..f4579424 100644 --- a/src/web/webview-proxy.ts +++ b/src/web/webview-proxy.ts @@ -45,6 +45,7 @@ import { createHash } from 'node:crypto'; import { WEBVIEW_PROXY_PREFIX } from '../config/webview-limits.js'; import { stripBasePath } from '../config/base-path.js'; +import { resolveTrustedProxyUserHeader } from '../config/trusted-proxy.js'; /** Headers that are per-connection and must never be relayed in either direction. */ const HOP_BY_HOP = new Set([ @@ -76,6 +77,12 @@ const DROP_REQUEST_HEADERS = new Set([ 'origin', 'referer', 'x-codeman-hook-secret', + // Trusted reverse-proxy sign-in headers. The auth middleware already deletes them from + // every request (takeTrustedProxyHeaders); listed here too so the relay never forwards + // them even if that ever changes. A custom username header name + // (CODEMAN_TRUSTED_PROXY_USER_HEADER) is added per request in buildUpstreamRequestHeaders. + 'x-codeman-proxy-secret', + 'x-codeman-user', ]); /** Response headers dropped on the way back to the browser. */ @@ -409,10 +416,13 @@ export function buildUpstreamRequestHeaders( } ): Record { const headers: Record = {}; + // The configured trusted-proxy username header (the default name is already in + // DROP_REQUEST_HEADERS). Only ever a name that passed validation. + const proxyUserHeader = resolveTrustedProxyUserHeader(); for (const [key, value] of Object.entries(incoming)) { const lower = key.toLowerCase(); - if (DROP_REQUEST_HEADERS.has(lower)) continue; + if (DROP_REQUEST_HEADERS.has(lower) || lower === proxyUserHeader) continue; if (value === undefined) continue; headers[lower] = Array.isArray(value) ? value.join(', ') : value; } diff --git a/test/sensitive-path.test.ts b/test/sensitive-path.test.ts index 518f8539..f215b6ff 100644 --- a/test/sensitive-path.test.ts +++ b/test/sensitive-path.test.ts @@ -19,6 +19,7 @@ import { homedir } from 'node:os'; import { describe, expect, it } from 'vitest'; import { isSensitivePath } from '../src/web/sensitive-path.js'; +import { initTrustedProxySecret, resetTrustedProxySecretForTests } from '../src/config/trusted-proxy.js'; const HOME = '/home/dev'; const dotenvPaths: Array<[string, string]> = [ @@ -80,6 +81,7 @@ describe('isSensitivePath', () => { ['codeman hook secret', `${HOME}/.codeman/hook-secret`], ['codeman user table', `${HOME}/.codeman/users.json`], ['codeman hook secret on a named instance', `${HOME}/.codeman-beta/hook-secret`], + ['codeman trusted-proxy secret (documented name)', `${HOME}/.codeman/proxy-secret`], // state.json persists SessionState.envOverrides, and the env allowlist // admits key-shaped names (GEMINI_API_KEY, CLAUDE_CODE_*), so it can hold // a live credential. Named once .json became previewable from outside the @@ -236,4 +238,29 @@ describe('isSensitivePath', () => { expect(isSensitivePath(path)).toBe(false); }); }); + + describe('the configured trusted-proxy secret file', () => { + it('blocks CODEMAN_TRUSTED_PROXY_SECRET_FILE whatever its name, and only while configured', () => { + const prev = process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE; + const file = '/srv/secrets/codeman-sso.key'; + try { + delete process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE; + resetTrustedProxySecretForTests(); + expect(isSensitivePath(file)).toBe(false); + process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = file; + expect(isSensitivePath(file)).toBe(true); + expect(isSensitivePath('/srv/secrets/other.txt')).toBe(false); + // Once the secret is read, the variable is gone from process.env (so sessions don't + // inherit it); the path stays blocked through the trusted-proxy module. + initTrustedProxySecret(); + expect(process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE).toBeUndefined(); + expect(isSensitivePath(file)).toBe(true); + expect(isSensitivePath('/srv/secrets/other.txt')).toBe(false); + } finally { + resetTrustedProxySecretForTests(); + if (prev === undefined) delete process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE; + else process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = prev; + } + }); + }); }); diff --git a/test/trusted-proxy-auth.test.ts b/test/trusted-proxy-auth.test.ts new file mode 100644 index 00000000..654d8b07 --- /dev/null +++ b/test/trusted-proxy-auth.test.ts @@ -0,0 +1,943 @@ +/** + * @fileoverview Trusted reverse-proxy identity (multi-user mode): an authenticating + * proxy on the same host forwards `X-Codeman-Proxy-Secret` + `X-Codeman-User`, and + * Codeman signs the request in as that account. See src/config/trusted-proxy.ts. + * + * Live servers on ephemeral ports. Real fetches arrive from loopback; inject's + * `remoteAddress` stands in for other sources. The secret is read once per process and + * then removed from the environment, so tests that change it call `useSecret()`. + */ + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs/promises'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import type { AddressInfo } from 'node:net'; +import Fastify, { type FastifyInstance } from 'fastify'; +import fastifyCookie from '@fastify/cookie'; +import fastifyWebsocket from '@fastify/websocket'; +import WebSocket from 'ws'; +import { WebServer } from '../src/web/server.js'; +import { TmuxManager } from '../src/tmux-manager.js'; +import { createUser, invalidateUsersCache, updateUser } from '../src/user-store.js'; +import { AUTH_FAILURE_MAX } from '../src/config/auth-config.js'; +import { + getTrustedProxyConfig, + initTrustedProxySecret, + resetTrustedProxySecretForTests, + takeTrustedProxyHeaders, + trustedProxyConfigError, + trustedProxySecretFilePath, +} from '../src/config/trusted-proxy.js'; +import { capabilityPrefixOf, registerAuthMiddleware } from '../src/web/middleware/auth.js'; +import { registerWsRoutes } from '../src/web/routes/ws-routes.js'; +import { buildUpstreamRequestHeaders } from '../src/web/webview-proxy.js'; +import { createMockRouteContext } from './mocks/index.js'; +import { getLifecycleLog } from '../src/session-lifecycle-log.js'; + +vi.spyOn(TmuxManager, 'isTmuxAvailable').mockReturnValue(true); + +const SECRET = 'a'.repeat(24) + 'b'.repeat(24); // 48 chars + +function basic(user: string, pass: string): string { + return 'Basic ' + Buffer.from(`${user}:${pass}`).toString('base64'); +} + +function cookieFrom(res: Response): string | null { + const raw = res.headers.get('set-cookie'); + const m = raw?.match(/codeman_session=([^;]+)/); + return m ? `codeman_session=${m[1]}` : null; +} + +/** + * Configure the secret the next server will read: the inline env var, the file variant, + * or none. Resets the once-per-process cache (in production the value is read once). + */ +function useSecret(opts: { inline?: string; file?: string } = {}): void { + delete process.env.CODEMAN_TRUSTED_PROXY_SECRET; + delete process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE; + if (opts.inline !== undefined) process.env.CODEMAN_TRUSTED_PROXY_SECRET = opts.inline; + if (opts.file !== undefined) process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = opts.file; + resetTrustedProxySecretForTests(); +} + +const ENV_KEYS = [ + 'CODEMAN_DATA_DIR', + 'CODEMAN_USER_SPACES_DIR', + 'CODEMAN_MULTIUSER', + 'CODEMAN_PASSWORD', + 'CODEMAN_USERNAME', + 'CODEMAN_TRUSTED_PROXY_SECRET', + 'CODEMAN_TRUSTED_PROXY_SECRET_FILE', + 'CODEMAN_TRUSTED_PROXY_USER_HEADER', +] as const; + +let server: WebServer; +const extraServers: WebServer[] = []; +let dataDir: string; +let spacesDir: string; +const saved: Record = {}; + +beforeAll(async () => { + dataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'tp-auth-data-')); + spacesDir = await fs.mkdtemp(path.join(os.tmpdir(), 'tp-auth-spaces-')); + for (const k of ENV_KEYS) saved[k] = process.env[k]; + process.env.CODEMAN_DATA_DIR = dataDir; + process.env.CODEMAN_USER_SPACES_DIR = spacesDir; + process.env.CODEMAN_MULTIUSER = '1'; + delete process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER; + delete process.env.CODEMAN_PASSWORD; + delete process.env.CODEMAN_USERNAME; + useSecret({ inline: SECRET }); + invalidateUsersCache(); + + await createUser({ username: 'alice', role: 'admin', password: 'alicepass1' }); + await createUser({ username: 'bob', role: 'user', password: 'bobpass123' }); + await createUser({ username: 'carol', role: 'user', password: 'carolpass1' }); + await updateUser('carol', { disabled: true }); + await createUser({ username: 'dave', role: 'user', password: 'davepass12', mustChangePassword: true }); + await createUser({ username: 'erin', role: 'user', password: 'erinpass12' }); + await createUser({ username: 'frank', role: 'user', password: 'frankpass1' }); + + server = new WebServer(0, false, true); + await server.start(); +}); + +afterAll(async () => { + await server?.stop(); + for (const s of extraServers) await s.stop().catch(() => {}); + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + resetTrustedProxySecretForTests(); + invalidateUsersCache(); + // stop() queues a lifecycle-log append; let it land before the data dir goes. + await (getLifecycleLog() as unknown as { writeQueue: Promise }).writeQueue; + await fs.rm(dataDir, { recursive: true, force: true }).catch(() => {}); + await fs.rm(spacesDir, { recursive: true, force: true }).catch(() => {}); +}); + +const url = (p: string) => `http://localhost:${server.boundPort}${p}`; + +function proxied(user: string | null, secret: string | null = SECRET, extra: Record = {}) { + const headers: Record = { ...extra }; + if (secret !== null) headers['X-Codeman-Proxy-Secret'] = secret; + if (user !== null) headers['X-Codeman-User'] = user; + return headers; +} + +async function me(headers: Record): Promise { + return fetch(url('/api/me'), { headers }); +} + +/** A fresh server (empty failure buckets) with the current env and secret. */ +async function freshServer(): Promise { + const s = new WebServer(0, false, true); + await s.start(); + extraServers.push(s); + return s; +} + +function appOf(s: WebServer): FastifyInstance { + return (s as unknown as { app: FastifyInstance }).app; +} + +/** inject() a GET /api/me from a chosen source address. */ +function injectMe(app: FastifyInstance, remoteAddress: string, headers: Record) { + return app.inject({ method: 'GET', url: '/api/me', remoteAddress, headers: { host: 'localhost', ...headers } }); +} + +describe('trusted-proxy config', () => { + afterAll(() => useSecret({ inline: SECRET })); + + it('is off in single-user mode, without a secret, or with a short / non-ASCII secret', () => { + useSecret({ inline: SECRET }); + expect(getTrustedProxyConfig(false)).toBeNull(); + expect(trustedProxyConfigError(false)).toMatch(/multi-user mode is off/); + expect(trustedProxyConfigError(true)).toBeNull(); + useSecret(); + expect(getTrustedProxyConfig(true)).toBeNull(); + expect(trustedProxyConfigError(true)).toBeNull(); + expect(trustedProxyConfigError(false)).toBeNull(); + useSecret({ inline: 'short' }); + expect(getTrustedProxyConfig(true)).toBeNull(); + expect(trustedProxyConfigError(true)).toMatch(/shorter than 32/); + useSecret({ inline: 'ü'.repeat(40) }); + expect(getTrustedProxyConfig(true)).toBeNull(); + expect(trustedProxyConfigError(true)).toMatch(/printable ASCII/); + }); + + it('removes the inline secret from the environment once read, so sessions do not inherit it', () => { + useSecret({ inline: SECRET }); + expect(getTrustedProxyConfig(true)?.secret).toBe(SECRET); + expect(process.env.CODEMAN_TRUSTED_PROXY_SECRET).toBeUndefined(); + // ...and the cached value keeps working. + expect(getTrustedProxyConfig(true)?.secret).toBe(SECRET); + }); + + it('reads the secret from CODEMAN_TRUSTED_PROXY_SECRET_FILE', async () => { + const file = path.join(dataDir, 'proxy-secret'); + await fs.writeFile(file, `${SECRET}\n`, { mode: 0o600 }); + useSecret({ file }); + expect(getTrustedProxyConfig(true)?.secret).toBe(SECRET); + expect(trustedProxyConfigError(true)).toBeNull(); + useSecret({ file: path.join(dataDir, 'missing') }); + expect(getTrustedProxyConfig(true)).toBeNull(); + expect(trustedProxyConfigError(true)).toMatch(/cannot read CODEMAN_TRUSTED_PROXY_SECRET_FILE/); + useSecret({ inline: SECRET, file }); + expect(getTrustedProxyConfig(true)).toBeNull(); + expect(trustedProxyConfigError(true)).toMatch(/set only one/); + }); + + it.skipIf(process.platform === 'win32')('refuses a secret file readable by group or others', async () => { + const file = path.join(dataDir, 'proxy-secret-mode'); + await fs.writeFile(file, SECRET, { mode: 0o600 }); + try { + for (const mode of [0o640, 0o604, 0o644]) { + await fs.chmod(file, mode); + useSecret({ file }); + expect(getTrustedProxyConfig(true), mode.toString(8)).toBeNull(); + expect(trustedProxyConfigError(true), mode.toString(8)).toMatch(/readable by other users; chmod 600/); + } + await fs.chmod(file, 0o400); + useSecret({ file }); + expect(getTrustedProxyConfig(true)?.secret).toBe(SECRET); + } finally { + await fs.rm(file, { force: true }); + } + }); + + it('removes both variables from the environment once read, and keeps the file path for the blocklist', async () => { + const file = path.join(dataDir, 'proxy-secret-env'); + await fs.writeFile(file, SECRET, { mode: 0o600 }); + try { + useSecret({ file }); + // Before the read, the path comes from the environment. + expect(trustedProxySecretFilePath()).toBe(file); + initTrustedProxySecret(); + expect(process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE).toBeUndefined(); + expect(process.env.CODEMAN_TRUSTED_PROXY_SECRET).toBeUndefined(); + expect(trustedProxySecretFilePath()).toBe(file); + expect(getTrustedProxyConfig(true)?.secret).toBe(SECRET); + // Both set (refused): both are still removed. + useSecret({ inline: SECRET, file }); + initTrustedProxySecret(); + expect(process.env.CODEMAN_TRUSTED_PROXY_SECRET).toBeUndefined(); + expect(process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE).toBeUndefined(); + // A relative path is kept resolved. + useSecret({ file: path.relative(process.cwd(), file) }); + initTrustedProxySecret(); + expect(trustedProxySecretFilePath()).toBe(file); + useSecret(); + initTrustedProxySecret(); + expect(trustedProxySecretFilePath()).toBeNull(); + } finally { + await fs.rm(file, { force: true }); + } + }); + + it('defaults the user header, honours an override, and refuses unusable header names', () => { + useSecret({ inline: SECRET }); + expect(getTrustedProxyConfig(true)).toEqual({ secret: SECRET, userHeader: 'x-codeman-user' }); + try { + process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER = 'X-Forwarded-User'; + expect(getTrustedProxyConfig(true)?.userHeader).toBe('x-forwarded-user'); + for (const bad of [ + 'Authorization', + 'cookie', + 'Content-Type', + 'Origin', + 'Upgrade', + 'Sec-WebSocket-Key', + 'X-Forwarded-For', + 'X-Real-IP', + 'x-codeman-proxy-secret', + 'X-Codeman-Hook-Secret', + 'not a header', + ]) { + process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER = bad; + expect(getTrustedProxyConfig(true)).toBeNull(); + expect(trustedProxyConfigError(true)).toMatch(/CODEMAN_TRUSTED_PROXY_USER_HEADER/); + } + // Refused even without a secret or multi-user mode: the setting itself is unusable. + useSecret(); + process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER = 'Authorization'; + expect(trustedProxyConfigError(false)).toMatch(/CODEMAN_TRUSTED_PROXY_USER_HEADER/); + useSecret({ inline: SECRET }); + for (const ok of ['X-Forwarded-User', 'Remote-User', 'X-Auth-Request-User', 'X-Remote-User']) { + process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER = ok; + expect(getTrustedProxyConfig(true)?.userHeader).toBe(ok.toLowerCase()); + expect(trustedProxyConfigError(true)).toBeNull(); + } + } finally { + delete process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER; + } + }); +}); + +describe('takeTrustedProxyHeaders', () => { + it('reads and deletes the secret and username headers', () => { + const headers: Record = { + 'x-codeman-proxy-secret': SECRET, + 'x-codeman-user': ' Bob ', + accept: '*/*', + }; + // The username is returned as sent: the auth hook applies the user store's rule. + expect(takeTrustedProxyHeaders(headers)).toEqual({ secretPresent: true, secret: SECRET, user: ' Bob ' }); + expect(headers).toEqual({ accept: '*/*' }); + }); + + it('marks an empty secret header as present and joins duplicates so they never match', () => { + expect(takeTrustedProxyHeaders({ 'x-codeman-proxy-secret': '' })).toMatchObject({ secretPresent: true }); + expect(takeTrustedProxyHeaders({ 'x-codeman-proxy-secret': [SECRET, SECRET] }).secret).toBe(`${SECRET}, ${SECRET}`); + expect(takeTrustedProxyHeaders({ 'x-codeman-user': ['alice', 'bob'] }).user).toBe('alice, bob'); + expect(takeTrustedProxyHeaders({ accept: '*/*' })).toEqual({ secretPresent: false, secret: '', user: '' }); + }); +}); + +describe('capabilityPrefixOf judges a path the way a proxy matcher does', () => { + it.each([ + ['/webview/x', 'webview'], + ['/webview/', 'webview'], + ['/webview/x?q=1', 'webview'], + [`/webview/${'a'.repeat(200)}/y`, 'webview'], + ['/webview/bad*token!/z', 'webview'], + ['/WEBVIEW/x', 'webview'], + ['/%77ebview/x', 'webview'], + ['//webview/x', 'webview'], + ['/a/../webview/x', 'webview'], + ['/html-view/x', 'html-view'], + ['/HTML-View/a/b', 'html-view'], + ['/html-view%2Fx', 'html-view'], + ['/WEBV%C4%B0EW/x', 'webview'], // U+0130 İ: Caddy's matcher folds it to "i" + ['/HTML-V%C4%B0EW/a', 'html-view'], + ['/webv%C4%B1ew/x', null], // U+0131 dotless ı: folded to "i" by neither side + ['/webview', null], + ['/webviewfoo', null], + ['/webviewfoo/x', null], + ['/html-view', null], + ['/html-viewer/x', null], + ['/', null], + ['/api/me', null], + ['/api/webviews', null], + ['/x/webview/y', null], + ['/webview/../api/me', null], + ] as const)('%s -> %s', (url, expected) => { + expect(capabilityPrefixOf(url)).toBe(expected); + }); +}); + +describe('the web-tab relay never forwards the trusted-proxy headers', () => { + it('drops them in buildUpstreamRequestHeaders, trusted or not', () => { + for (const forwardCookies of [false, true]) { + const headers = buildUpstreamRequestHeaders( + { 'x-codeman-proxy-secret': SECRET, 'x-codeman-user': 'alice', accept: '*/*' }, + new URL('http://127.0.0.1:4000/panel'), + { forwardCookies, sessionCookieName: 'codeman_session' } + ); + expect(headers['x-codeman-proxy-secret']).toBeUndefined(); + expect(headers['x-codeman-user']).toBeUndefined(); + expect(headers.accept).toBe('*/*'); + } + }); + + it('drops a custom username header too, and only the configured one', () => { + const incoming = { 'x-auth-request-user': 'alice', 'x-codeman-user': 'alice', 'x-other': 'keep' }; + const build = () => + buildUpstreamRequestHeaders(incoming, new URL('http://127.0.0.1:4000/panel'), { + forwardCookies: true, + sessionCookieName: 'codeman_session', + }); + try { + process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER = 'X-Auth-Request-User'; + const headers = build(); + expect(headers['x-auth-request-user']).toBeUndefined(); + expect(headers['x-codeman-user']).toBeUndefined(); + expect(headers['x-other']).toBe('keep'); + // A rejected name is never used, so the header it names is not dropped. + process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER = 'Accept'; + expect( + buildUpstreamRequestHeaders({ accept: '*/*' }, new URL('http://127.0.0.1:4000/'), { + forwardCookies: false, + sessionCookieName: 'codeman_session', + }).accept + ).toBe('*/*'); + } finally { + delete process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER; + } + // Not configured: an ordinary header of that name is relayed. + expect(build()['x-auth-request-user']).toBe('alice'); + }); +}); + +describe('the auth middleware strips the headers before any route sees them', () => { + /** A bare app with the real auth middleware and a route that echoes what it received. */ + async function echoApp(): Promise { + const app = Fastify(); + await app.register(fastifyCookie); + registerAuthMiddleware(app, false); + app.get('/echo', async (req) => ({ headers: req.headers, user: req.authUser?.username ?? null })); + app.post('/echo', async (req) => ({ headers: req.headers, body: req.body })); + await app.ready(); + return app; + } + + it('in multi-user mode, for a signed-in proxy request', async () => { + useSecret({ inline: SECRET }); + const app = await echoApp(); + try { + const res = await app.inject({ + method: 'GET', + url: '/echo', + remoteAddress: '127.0.0.1', + headers: proxied('bob'), + }); + expect(res.statusCode).toBe(200); + const body = res.json(); + expect(body.user).toBe('bob'); + expect(body.headers['x-codeman-proxy-secret']).toBeUndefined(); + expect(body.headers['x-codeman-user']).toBeUndefined(); + } finally { + await app.close(); + } + }); + + it('strips a custom username header as well', async () => { + useSecret({ inline: SECRET }); + process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER = 'X-Forwarded-User'; + const app = await echoApp(); + try { + const res = await app.inject({ + method: 'GET', + url: '/echo', + remoteAddress: '127.0.0.1', + headers: { 'x-codeman-proxy-secret': SECRET, 'x-forwarded-user': 'bob' }, + }); + expect(res.statusCode).toBe(200); + expect(res.json().user).toBe('bob'); + expect(res.json().headers['x-forwarded-user']).toBeUndefined(); + } finally { + delete process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER; + await app.close(); + } + }); + + it('never strips a header named by a rejected CODEMAN_TRUSTED_PROXY_USER_HEADER', async () => { + const prev = process.env.CODEMAN_MULTIUSER; + delete process.env.CODEMAN_MULTIUSER; + process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER = 'Content-Type'; + useSecret(); + const app = await echoApp(); + try { + const res = await app.inject({ method: 'POST', url: '/echo', payload: { a: 1 } }); + expect(res.statusCode).toBe(200); + expect(res.json().body).toEqual({ a: 1 }); + expect(res.json().headers['content-type']).toMatch(/application\/json/); + } finally { + process.env.CODEMAN_MULTIUSER = prev; + delete process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER; + await app.close(); + useSecret({ inline: SECRET }); + } + }); + + it('in single-user mode without a password (no auth at all)', async () => { + const prev = process.env.CODEMAN_MULTIUSER; + delete process.env.CODEMAN_MULTIUSER; + useSecret({ inline: SECRET }); + const app = await echoApp(); + try { + const res = await app.inject({ + method: 'GET', + url: '/echo', + remoteAddress: '127.0.0.1', + headers: proxied('bob'), + }); + expect(res.statusCode).toBe(200); + expect(res.json().headers['x-codeman-proxy-secret']).toBeUndefined(); + expect(res.json().headers['x-codeman-user']).toBeUndefined(); + expect(process.env.CODEMAN_TRUSTED_PROXY_SECRET).toBeUndefined(); + } finally { + process.env.CODEMAN_MULTIUSER = prev; + await app.close(); + useSecret({ inline: SECRET }); + } + }); +}); + +describe('trusted-proxy sign-in', () => { + it('signs a loopback request with the secret in as the named account, without a cookie', async () => { + const res = await me(proxied('bob')); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.data).toMatchObject({ username: 'bob', role: 'user', viaTrustedProxy: true }); + expect(cookieFrom(res)).toBeNull(); + }); + + it('removes the inline secret from the process environment when the server starts', async () => { + useSecret({ inline: SECRET }); + expect(process.env.CODEMAN_TRUSTED_PROXY_SECRET).toBe(SECRET); + const app = appOf(await freshServer()); + expect(process.env.CODEMAN_TRUSTED_PROXY_SECRET).toBeUndefined(); + expect((await injectMe(app, '127.0.0.1', proxied('bob'))).statusCode).toBe(200); + }); + + it('normalizes the username case and keeps the account role', async () => { + const res = await me(proxied(' ALICE ')); + expect(res.status).toBe(200); + expect((await res.json()).data).toMatchObject({ username: 'alice', role: 'admin' }); + }); + + it('ignores a username header that comes without the secret (normal auth applies)', async () => { + const res = await me(proxied('alice', null)); + expect(res.status).toBe(401); + expect(res.headers.get('www-authenticate')).toMatch(/Basic/); + }); + + it('refuses a wrong secret outright, even alongside valid Basic credentials', async () => { + const res = await me(proxied('alice', 'x'.repeat(48), { Authorization: basic('bob', 'bobpass123') })); + expect(res.status).toBe(401); + expect(await res.text()).toMatch(/proxy secret rejected/); + expect(res.headers.get('www-authenticate')).toBeNull(); + }); + + it('refuses an EMPTY secret header instead of falling back to a cookie or Basic', async () => { + const login = await me({ Authorization: basic('bob', 'bobpass123') }); + const cookie = cookieFrom(login)!; + for (const extra of [{ Cookie: cookie }, { Authorization: basic('bob', 'bobpass123') }]) { + const res = await me(proxied('alice', '', extra)); + expect(res.status).toBe(401); + expect(await res.text()).toMatch(/proxy secret rejected/); + } + }); + + it('refuses a duplicated secret header', async () => { + const s = await freshServer(); + const res = await injectMe(appOf(s), '127.0.0.1', { + 'x-codeman-proxy-secret': [SECRET, SECRET], + 'x-codeman-user': 'bob', + }); + expect(res.statusCode).toBe(401); + expect(res.body).toMatch(/proxy secret rejected/); + }); + + it('refuses a correct secret with no username with 403 and no challenge', async () => { + for (const user of [null, '', ' ']) { + const res = await me(proxied(user)); + expect(res.status, JSON.stringify(user)).toBe(403); + expect(await res.text()).toMatch(/no username/); + expect(res.headers.get('www-authenticate')).toBeNull(); + } + }); + + it('matches the username exactly by the user store rule: no trimming at @, no replacement', async () => { + for (const user of ['bob@example.com', 'bob.smith', 'b ob', 'bob\\x', 'DOMAIN\\bob', 'b']) { + const res = await me(proxied(user)); + expect(res.status, user).toBe(403); + expect(await res.text()).toMatch(/no enabled Codeman account/); + expect(res.headers.get('www-authenticate')).toBeNull(); + } + }); + + it('refuses a name the store rule rejects even when users.json holds it (hand-edited)', async () => { + const file = path.join(dataDir, 'users.json'); + const original = await fs.readFile(file, 'utf-8'); + const parsed = JSON.parse(original) as { users: Array<{ username: string }> }; + const bob = parsed.users.find((u) => u.username === 'bob')!; + parsed.users.push({ ...bob, username: 'bob.smith' }); + await fs.writeFile(file, JSON.stringify(parsed), { mode: 0o600 }); + invalidateUsersCache(); + try { + const res = await me(proxied('bob.smith')); + expect(res.status).toBe(403); + expect(await res.text()).toMatch(/no enabled Codeman account/); + } finally { + await fs.writeFile(file, original, { mode: 0o600 }); + invalidateUsersCache(); + } + }); + + it('refuses a username header sent twice, even when both names exist', async () => { + // Two real header lines over a socket: Node joins them into "alice, bob". + const { status, body } = await new Promise<{ status: number; body: string }>((resolve, reject) => { + const req = http.request( + { + host: '127.0.0.1', + port: server.boundPort, + path: '/api/me', + headers: { host: 'localhost', 'x-codeman-proxy-secret': SECRET, 'x-codeman-user': ['alice', 'bob'] }, + }, + (res) => { + let data = ''; + res.on('data', (c) => (data += c)); + res.on('end', () => resolve({ status: res.statusCode ?? 0, body: data })); + } + ); + req.on('error', reject); + req.end(); + }); + expect(status).toBe(403); + expect(body).toMatch(/no enabled Codeman account/); + }); + + it('refuses unknown and disabled accounts with 403 (no auto-provisioning)', async () => { + const unknown = await me(proxied('mallory')); + expect(unknown.status).toBe(403); + expect(await unknown.text()).toMatch(/no enabled Codeman account/); + expect((await me(proxied('carol'))).status).toBe(403); + }); + + it('refuses an account disabled between two requests', async () => { + expect((await me(proxied('frank'))).status).toBe(200); + await updateUser('frank', { disabled: true }); + invalidateUsersCache(); + expect((await me(proxied('frank'))).status).toBe(403); + }); + + it('does not apply the mustChangePassword lockbox to a proxy sign-in', async () => { + const res = await fetch(url('/api/sessions'), { headers: proxied('dave') }); + expect(res.status).toBe(200); + // /api/me must not tell the browser to force a password change it never used. + const meProxy = (await (await me(proxied('dave'))).json()).data; + expect(meProxy).toMatchObject({ username: 'dave', mustChangePassword: false, viaTrustedProxy: true }); + const meBasic = (await (await me({ Authorization: basic('dave', 'davepass12') })).json()).data; + expect(meBasic).toMatchObject({ username: 'dave', mustChangePassword: true, viaTrustedProxy: false }); + // ...while the same account over Basic is still locked into changing its password. + const viaBasic = await fetch(url('/api/sessions'), { headers: { Authorization: basic('dave', 'davepass12') } }); + expect(viaBasic.status).toBe(403); + }); + + it('ignores and does not refresh a live cookie under a proxy identity', async () => { + const s = await freshServer(); + const app = appOf(s); + const login = await injectMe(app, '127.0.0.1', { authorization: basic('alice', 'alicepass1') }); + expect(login.statusCode).toBe(200); + const token = /codeman_session=([^;]+)/.exec(String(login.headers['set-cookie']))![1]; + const sessions = (s as unknown as { authSessions: { getRemainingTtl(k: string): number | undefined } }) + .authSessions; + const realNow = Date.now(); + const ttlAtLogin = sessions.getRemainingTtl(token)!; + // A minute later, a proxy request for bob carries alice's cookie. + const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(realNow + 60_000); + try { + const res = await injectMe(app, '127.0.0.1', proxied('bob', SECRET, { cookie: `codeman_session=${token}` })); + expect(res.statusCode).toBe(200); + expect(res.json().data).toMatchObject({ username: 'bob', viaTrustedProxy: true }); + expect(res.headers['set-cookie']).toBeUndefined(); + // Alice's session was not touched: its remaining lifetime shrank by the minute. + expect(sessions.getRemainingTtl(token)!).toBeLessThanOrEqual(ttlAtLogin - 60_000 + 1000); + } finally { + nowSpy.mockRestore(); + } + // ...and the cookie itself is still alice's, alive. + const again = await injectMe(app, '127.0.0.1', { cookie: `codeman_session=${token}` }); + expect(again.statusCode).toBe(200); + expect(again.json().data.username).toBe('alice'); + }); + + it('takes precedence over an existing cookie from another account', async () => { + const login = await me({ Authorization: basic('bob', 'bobpass123') }); + const cookie = cookieFrom(login); + expect(cookie).toBeTruthy(); + const res = await me(proxied('alice', SECRET, { Cookie: cookie! })); + expect(res.status).toBe(200); + expect((await res.json()).data.username).toBe('alice'); + }); + + it('does not open the hook endpoint: it still needs the hook secret', async () => { + const res = await fetch(url('/api/hook-event'), { + method: 'POST', + headers: { ...proxied('alice'), 'content-type': 'application/json' }, + body: JSON.stringify({ event: 'stop', sessionId: 'x' }), + }); + expect(res.status).toBe(401); + expect(await res.text()).toMatch(/hook secret required/); + }); + + it('authenticates a terminal WebSocket upgrade through the full server', async () => { + const code = await new Promise((resolve, reject) => { + const ws = new WebSocket(`ws://127.0.0.1:${server.boundPort}/ws/sessions/nonexistent/terminal`, { + headers: proxied('bob'), + }); + const timer = setTimeout(() => { + ws.terminate(); + reject(new Error('WS did not close within timeout')); + }, 8000); + ws.on('close', (c) => { + clearTimeout(timer); + resolve(c); + }); + ws.on('error', () => { + /* the close handler resolves */ + }); + }); + // 4004 = the upgrade passed auth and reached the session lookup. Refusals are covered + // through inject() above; this file drives only accepted upgrades over a real socket. + expect(code).toBe(4004); + }); + + it('leaves Basic and cookie sign-in working for requests without the secret', async () => { + const login = await me({ Authorization: basic('bob', 'bobpass123') }); + expect(login.status).toBe(200); + const again = await me({ Cookie: cookieFrom(login)! }); + expect(again.status).toBe(200); + }); + + it('accepts IPv6 and IPv4-mapped loopback, refuses any other source', async () => { + const app = appOf(await freshServer()); + for (const ip of ['::1', '::ffff:127.0.0.1']) { + expect((await injectMe(app, ip, proxied('bob'))).statusCode).toBe(200); + } + for (const ip of ['10.1.2.3', '127.0.0.2']) { + const res = await injectMe(app, ip, proxied('alice')); + expect(res.statusCode).toBe(401); + expect(res.body).toMatch(/proxy secret rejected/); + expect(res.headers['www-authenticate']).toBeUndefined(); + } + }); + + it('throttles wrong secrets per IP but never refuses the correct one, and leaves Basic usable', async () => { + const app = appOf(await freshServer()); + const wrong = proxied('alice', 'y'.repeat(48)); + for (let i = 0; i < AUTH_FAILURE_MAX; i++) { + expect((await injectMe(app, '127.0.0.1', wrong)).statusCode).toBe(401); + } + expect((await injectMe(app, '127.0.0.1', wrong)).statusCode).toBe(429); + // Local junk requests share 127.0.0.1 with the proxy: they must not lock sign-in out. + const ok = await injectMe(app, '127.0.0.1', proxied('alice')); + expect(ok.statusCode).toBe(200); + expect(ok.json().data.username).toBe('alice'); + // ...and the Basic path from the same IP is untouched. + expect((await injectMe(app, '127.0.0.1', { authorization: basic('bob', 'bobpass123') })).statusCode).toBe(200); + }); + + it('refuses any path without a live capability under the capability prefixes, with no password check, prompt or failure count', async () => { + const app = appOf(await freshServer()); + const webviewPaths = [ + `/webview/${'Z'.repeat(32)}/x`, // well-formed, unknown + '/webview/x', // malformed token (too short) + '/webview/', + `/webview/${'a'.repeat(200)}/y`, // overlong token + '/webview/bad*token!/z', // invalid characters + '/WEBVIEW/x', // re-spelled the way a proxy's matcher still forwards it + '/%77ebview/x', + '/WEBV%C4%B0EW/x', + '/webview/x?q=1', + ]; + const htmlPaths = [`/html-view/${'A'.repeat(24)}/index.html`, '/html-view/x']; + // Negative case, sent once before the loop so its single count doesn't blur the result: + // a lookalike prefix is NOT a capability path and keeps the ordinary challenge. + const lookalike = await app.inject({ + method: 'GET', + url: '/webviewfoo', + remoteAddress: '127.0.0.1', + headers: { host: 'localhost' }, + }); + expect(lookalike.statusCode).toBe(401); + expect(lookalike.headers['www-authenticate']).toMatch(/Basic/); + + const all = [...webviewPaths.map((u) => [u, 403] as const), ...htmlPaths.map((u) => [u, 404] as const)]; + for (let i = 0; i < 60; i++) { + const [url, status] = all[i % all.length]; + // Alternate wrong Basic credentials (not even checked) and no credentials at all, + // which is what arrives through the documented Caddy route. + const headers: Record = { host: 'localhost' }; + if (i % 2) headers.authorization = basic('bob', 'wrong-password'); + const res = await app.inject({ method: 'GET', url, remoteAddress: '127.0.0.1', headers }); + expect(res.statusCode, url).toBe(status); + expect(res.headers['www-authenticate'], url).toBeUndefined(); + } + // 60 such requests did not fill the per-IP bucket: Basic from loopback still works. + expect((await injectMe(app, '127.0.0.1', { authorization: basic('bob', 'bobpass123') })).statusCode).toBe(200); + }); + + it('honours a custom user header and no longer reads the default one', async () => { + process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER = 'X-Forwarded-User'; + try { + const app = appOf(await freshServer()); + const ok = await injectMe(app, '127.0.0.1', { 'x-codeman-proxy-secret': SECRET, 'x-forwarded-user': 'bob' }); + expect(ok.statusCode).toBe(200); + expect(ok.json().data.username).toBe('bob'); + const old = await injectMe(app, '127.0.0.1', proxied('bob')); + expect(old.statusCode).toBe(403); + expect(old.body).toMatch(/no username/); + } finally { + delete process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER; + } + }); +}); + +describe('terminal WebSocket through a proxy sign-in is owner-scoped', () => { + let app: FastifyInstance; + let port = 0; + + beforeAll(async () => { + useSecret({ inline: SECRET }); + app = Fastify(); + await app.register(fastifyCookie); + registerAuthMiddleware(app, false); + await app.register(fastifyWebsocket); + const ctx = createMockRouteContext({ sessionId: 'bobs-session' }); + (ctx.sessions.get('bobs-session') as unknown as { owner?: string }).owner = 'bob'; + registerWsRoutes(app, ctx as never, () => ({ bindHost: '127.0.0.1', allowedHosts: [], tunnelHost: null })); + await app.listen({ port: 0, host: '127.0.0.1' }); + port = (app.server.address() as AddressInfo).port; + }); + + afterAll(async () => { + await app.close(); + }); + + /** Open the terminal WebSocket for bob's session as `user`. */ + function open(user: string): WebSocket { + return new WebSocket(`ws://127.0.0.1:${port}/ws/sessions/bobs-session/terminal`, { headers: proxied(user) }); + } + + /** Resolves with the close code; never decided by a timer racing the server. */ + function closeCode(ws: WebSocket): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + ws.terminate(); + reject(new Error('WS did not close within timeout')); + }, 5000); + ws.on('close', (code) => { + clearTimeout(timer); + resolve(code); + }); + ws.on('error', () => { + /* the close handler resolves */ + }); + }); + } + + /** True when the socket opened and the SERVER did not close it within `ms`. */ + function staysOpen(ws: WebSocket, ms = 1000): Promise { + return new Promise((resolve) => { + let closedByServer = false; + ws.on('close', () => { + closedByServer = true; + }); + ws.on('error', () => { + /* reported through close */ + }); + ws.on('open', () => { + setTimeout(() => { + resolve(!closedByServer); + ws.close(); + }, ms); + }); + }); + } + + /** Accepted upgrades only, like the full-server WebSocket test above. */ + it('lets the owner and an admin attach, and closes it for another user with 4003', async () => { + expect(await staysOpen(open('bob'))).toBe(true); + expect(await staysOpen(open('alice'))).toBe(true); + expect(await closeCode(open('erin'))).toBe(4003); + }); +}); + +describe('trusted-proxy sign-in is off without its preconditions', () => { + it('ignores the headers when no secret is configured', async () => { + useSecret(); + try { + const res = await injectMe(appOf(await freshServer()), '127.0.0.1', proxied('alice')); + expect(res.statusCode).toBe(401); + expect(res.headers['www-authenticate']).toMatch(/Basic/); + } finally { + useSecret({ inline: SECRET }); + } + }); +}); + +describe('a configured setup that cannot be used stops the start', () => { + afterAll(() => useSecret({ inline: SECRET })); + + /** start() a new server with the current env; resolves with the refusal message, or null. */ + async function startError(): Promise { + const s = new WebServer(0, false, true); + try { + await s.start(); + extraServers.push(s); + return null; + } catch (err) { + await s.stop().catch(() => {}); + return (err as Error).message; + } + } + + /** Assert the refusal, that it names the reason, and that it never carries the secret. */ + async function expectRefusal(reason: RegExp): Promise { + const message = await startError(); + expect(message).toMatch(/^Trusted-proxy sign-in is misconfigured: /); + expect(message).toMatch(reason); + expect(message).not.toContain(SECRET); + expect(message).not.toContain('short-secret'); + } + + it('starts with a valid setup', async () => { + useSecret({ inline: SECRET }); + expect(await startError()).toBeNull(); + }); + + it('refuses both secret variables at once', async () => { + const file = path.join(dataDir, 'refuse-both'); + await fs.writeFile(file, SECRET, { mode: 0o600 }); + useSecret({ inline: SECRET, file }); + await expectRefusal(/set only one/); + await fs.rm(file, { force: true }); + }); + + it('refuses an unreadable or empty secret file', async () => { + useSecret({ file: path.join(dataDir, 'no-such-secret') }); + await expectRefusal(/cannot read CODEMAN_TRUSTED_PROXY_SECRET_FILE .*ENOENT/); + const empty = path.join(dataDir, 'empty-secret'); + await fs.writeFile(empty, ' \n', { mode: 0o600 }); + useSecret({ file: empty }); + await expectRefusal(/is empty/); + await fs.rm(empty, { force: true }); + }); + + it.skipIf(process.platform === 'win32')('refuses a secret file readable by group or others', async () => { + const file = path.join(dataDir, 'refuse-mode'); + await fs.writeFile(file, SECRET, { mode: 0o640 }); + await fs.chmod(file, 0o640); + useSecret({ file }); + await expectRefusal(/readable by other users; chmod 600/); + await fs.rm(file, { force: true }); + }); + + it('refuses a short or non-ASCII secret', async () => { + useSecret({ inline: 'short-secret' }); + await expectRefusal(/shorter than 32/); + useSecret({ inline: `${SECRET} ${SECRET}` }); + await expectRefusal(/printable ASCII/); + }); + + it('refuses a secret with multi-user mode off', async () => { + const prevMulti = process.env.CODEMAN_MULTIUSER; + delete process.env.CODEMAN_MULTIUSER; + process.env.CODEMAN_PASSWORD = 'singlepass1'; + try { + useSecret({ inline: SECRET }); + await expectRefusal(/multi-user mode is off/); + // Read and removed even so: nothing is left for a later spawn to inherit. + expect(process.env.CODEMAN_TRUSTED_PROXY_SECRET).toBeUndefined(); + } finally { + process.env.CODEMAN_MULTIUSER = prevMulti; + delete process.env.CODEMAN_PASSWORD; + } + }); + + it('refuses a username header name the validation rejects', async () => { + useSecret({ inline: SECRET }); + process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER = 'Authorization'; + try { + await expectRefusal(/CODEMAN_TRUSTED_PROXY_USER_HEADER/); + } finally { + delete process.env.CODEMAN_TRUSTED_PROXY_USER_HEADER; + } + }); +});