Merge #854: feat(auth): sign in through a trusted reverse proxy in multi-user mode (experimental)

This commit is contained in:
Codeman maintainer committed 2026-12-03 10:15:13 +01:00
commit 01380d8b26
20 files changed
+2374 -22

No files matched your search

+5
View File
@@ -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.
+1 -1
View File
@@ -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/<cap>/...`). ⚠️ 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)
+26 -4
View File
@@ -59,10 +59,13 @@ payload return `{ "success": true, "data": {} }`.
> to 600 s. Proxy operators and HTTP clients with a global read timeout need to know
> that before pointing them at Codeman.
⚠️ **A `401` is the one status that is not an envelope.** Authentication is rejected
⚠️ **A `401` is not an envelope.** Authentication is rejected
in a request hook, before any handler runs, and it replies with the bare string
`Unauthorized` (`Unauthorized: hook secret required` on the hook path) plus
`WWW-Authenticate: Basic realm="Codeman"`. There is no `success`, no `error`, and no
`Unauthorized` plus `WWW-Authenticate: Basic realm="Codeman"` (on the hook path it is
`Unauthorized: hook secret required`, without that header). With trusted-proxy sign-in on (experimental,
see [Authentication](#authentication)) the same hook has more plain-text replies: a `401`
without `WWW-Authenticate`, a `403` and a `503` for a refused proxy identity, and a `403`
or `404` for a `/webview/` or `/html-view/` path without a live capability. There is no `success`, no `error`, and no
`errorCode`, because the wrapping hook only wraps object payloads. So a client that
pipes every response straight into a JSON parser dies with a parse error rather than
reporting an auth failure, which is a confusing way to discover that a password is
@@ -1021,7 +1024,8 @@ by the owner's decision the page may load from and send requests to any host), `
`Referrer-Policy: no-referrer` and `Access-Control-Allow-Origin: *`. A `Range`
request is answered with `206` + `Content-Range` (`416` past the end), like
`file-raw`. Every refusal is a plain-text `404 Not found`; with a password set, an
unknown or revoked capability is the auth hook's `401` instead.
unknown or revoked capability is the auth hook's `401` instead. With trusted-proxy sign-in
on it is the hook's plain-text `404`, with no challenge.
## Session lineage (`parentSessionId`)
@@ -1939,6 +1943,24 @@ Optional HTTP Basic (`CODEMAN_USERNAME`/`CODEMAN_PASSWORD`) → opaque
`401 UNAUTHORIZED`; rate-limited requests get `429 RATE_LIMITED`. See
[`security-architecture.md`](security-architecture.md).
**Trusted-proxy sign-in (experimental, multi-user mode, off unless a secret is
configured).** An authenticating reverse proxy on the same host sends
`X-Codeman-Proxy-Secret` and `X-Codeman-User` over loopback, and the request runs as that
existing, enabled account. No cookie is issued, and `GET /api/me` reports
`viaTrustedProxy: true`. The hook's refusals on this path are plain text, not envelopes:
| Status | When |
|---|---|
| `401`, no `WWW-Authenticate` | the secret is wrong, or the request did not arrive over loopback |
| `403` | the secret is right, but there is no username or no enabled account with that name |
| `503` | the user store cannot be read |
| `429` | too many wrong secrets from one address |
With the feature on, a path under `/webview/` or `/html-view/` without a live capability is
answered by the hook before any credential is looked at: plain-text `403` for a web tab,
`404` for an HTML view, no challenge. See
[`security-architecture.md` §10a](security-architecture.md).
## SSE event channel
`GET /api/events` is a Server-Sent Events stream (`text/event-stream`); each
+2
View File
@@ -640,6 +640,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/<name>/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.
+3 -3
View File
@@ -184,11 +184,11 @@ 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/<username>` (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/<case>` 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) |
| Self-service `GET /api/me` | `{ username, role, mustChangePassword, multiUser, viaTrustedProxy }` (works in single-user mode too: synthetic admin without `viaTrustedProxy`; the frontend uses it to decide whether to render admin UI). For a trusted-proxy sign-in `viaTrustedProxy` is `true` and `mustChangePassword` is reported as `false` |
| Self-service `POST /api/me/password` | `{ currentPassword, newPassword }`, verifies current, min length 8, revokes other sessions, clears `mustChangePassword` |
**Audit log**: append-only `~/.codeman/admin-audit.jsonl` (same idiom as `session-lifecycle.jsonl`): timestamp, acting admin, action, target, request IP. User management without an audit trail is not acceptable even for a homelab tool.
+151
View File
@@ -600,6 +600,154 @@ 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: <secret>` and `X-Codeman-User: <codeman username>`. 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/<pid>/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`). Two requests under a
dead web‑tab capability have no route status to copy and get the hook's `403` as well: a
WebSocket upgrade is refused at the handshake (the route alone accepts it and closes
with `4003`), and `GET /webview/<cap>` without the trailing slash is not redirected
(the route alone answers `302`). 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. Under a base path (`CODEMAN_BASE_URL`) the
mount prefix is judged the same way: the server strips only its literal spelling, so
the refusal looks for the capability prefix in the normalised path as it arrives and,
when that path starts with the mount prefix, once more with the mount prefix removed.
A match in either form is refused. The path as it arrives comes first, because under
a mount named like a capability prefix (`/webview`) the literal mount is already gone.
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)
@@ -639,6 +787,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` |
@@ -660,6 +810,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` |
+19
View File
@@ -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:
+6 -1
View File
@@ -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.
+363 -1
View File
@@ -112,7 +112,369 @@ 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/<pid>/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/<tenant-id>/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_samesite = "lax" # never sent from a sandboxed web-tab frame
cookie_expire = "12h" # sign in again after this (default 168h)
cookie_refresh = "1h" # re-check with the provider this often
cookie_csrf_per_request = true # one CSRF cookie per sign-in, so parallel ones don't collide
cookie_csrf_per_request_limit = 5
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.
Set `cookie_samesite`. oauth2-proxy puts no `SameSite` attribute on its cookie unless it is
configured, and browsers disagree about a cookie without one. With `lax`, a sandboxed
web-tab frame does not send the proxy's cookie in any browser.
The username Codeman gets is only as trustworthy as the claim it comes from:
- **Register the app as single-tenant.** The proxy trusts values that the administrators
of the signing-in person's tenant control, so only your own tenant may sign in.
- **`email` and `preferred_username` are mutable.** An administrator can change them, and
an address can be given to another person later. That person then gets the Codeman
account the address maps to, until you remove its row from the `map` below. Go through
the table when people leave or are renamed.
### 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=<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 {
# Only a page navigation can complete a sign-in. A background request
# (fetch, the live-update stream, a WebSocket) gets a 401. A client
# that sends no Sec-Fetch-Mode header is still redirected.
@background {
header Sec-Fetch-Mode *
not header Sec-Fetch-Mode navigate
}
route {
respond @background "Sign-in required" 401
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}
# Codeman needs only the two headers above.
header_up -X-Auth-Request-Email
}
}
}
}
}
```
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.
- **A background request is not sent to the sign-in.** A request with a `Sec-Fetch-Mode`
other than `navigate` gets a `401`. Page navigations are redirected as before, and so
are clients that send no such header (command-line tools, old browsers). Without that
rule an open Codeman page whose proxy session has ended starts a sign-in with every
background request that follows the redirect, which `fetch()` and the live-update stream
do. Each one replaces oauth2-proxy's CSRF cookie, and the person's real sign-in then
ends on oauth2-proxy's error page ("CSRF token mismatch"). `cookie_csrf_per_request`
covers the remaining case of several tabs signing in at once.
- **oauth2-proxy's identity headers stop at the proxy too.** `header_up -X-Auth-Request-Email`
removes the address on the way to Codeman, because the web-tab relay passes headers it
does not know on to dashboards.
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, which belongs only on a single-tenant app registration), 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 {
@background {
header Sec-Fetch-Mode *
not header Sec-Fetch-Mode navigate
}
route {
respond @background "Sign-in required" 401
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}
header_up -X-Auth-Request-Email
header_up -X-Auth-Request-Codeman-User
}
}
```
Adding a person is then: allow them at the identity provider, and
`codeman users add <name>`. Codeman usernames allow letters, digits, `_` and `-` only, so
the claim must fit that. A logon name with a dot (`jane.doe`) does not: for such accounts
keep the `map`. 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 the proxy's
`401`. An open Codeman page then shows "No connection to the Codeman server" and does
not recover by itself: reload it to sign in again. 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/<capability>/` 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
+3
View File
@@ -300,6 +300,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. |
+4 -1
View File
@@ -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
+280
View File
@@ -0,0 +1,280 @@
/**
* @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: <the shared secret>
* X-Codeman-User: <codeman username>
*
* 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`, `trustedProxySecretFileRealPath`) for the
* sensitive-path blocklist.
*
* A configured setup that can't be used stops the server from starting
* (`trustedProxyConfigError`, thrown from `WebServer.start()`), so a typo never falls
* 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, realpathSync, 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;
/** That path with symlinks resolved, when it could be resolved. */
fileRealPath?: 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;
const fileRealPath = filePath ? realPathOrUndefined(filePath) : 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, fileRealPath };
return loaded;
}
function realPathOrUndefined(path: string): string | undefined {
try {
return realpathSync(path);
} catch {
return undefined;
}
}
/**
* Read the secret now and remove both variables from `process.env`. Called first in
* `WebServer.start()` and again (a no-op then) at auth setup, before any session is
* 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;
}
/**
* The secret file's path with symlinks resolved, or null (not configured, or it can't be
* resolved). Resolved once when the secret is read; before that, from the environment.
*/
export function trustedProxySecretFileRealPath(): string | null {
if (loaded) return loaded.fileRealPath ?? null;
const file = trustedProxySecretFilePath();
return (file && realPathOrUndefined(file)) ?? null;
}
/** Test-only: forget the cached secret so the next call re-reads the environment. */
export function resetTrustedProxySecretForTests(): void {
loaded = null;
}
/** 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 ?? ''),
};
}
+6
View File
@@ -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. */
+245 -7
View File
@@ -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<string, number> | null;
/** Per-(username, client IP) Basic-auth failure bucket (multi-user only). */
userIpFailures: StaleExpirationMap<string, number> | null;
/** Wrong trusted-proxy secret presentations, per client IP (multi-user + proxy secret only). */
proxySecretFailures: StaleExpirationMap<string, number> | null;
}
/** Rate-limit response for a client that exceeded the failure cap. */
@@ -118,9 +137,7 @@ function checkHookSecretBypass(
hookSecretFailures: StaleExpirationMap<string, number>
): '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)) {
@@ -141,6 +158,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<FastifyRequest, PresentedProxyHeaders>();
/** 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<string, number>,
lastLoginTouched: Map<string, number>
): 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<ReturnType<typeof findUser>>;
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,
@@ -275,6 +397,80 @@ 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.
*
* `rawUrl` has been through `stripBasePath()`, which removes the mount prefix only in its
* literal spelling, so under `basePath` a re-spelled prefix (`/CODEMAN/webview/x`,
* `/%63odeman/...`, `//codeman/...`, `/x/../codeman/...`) is still in front. So the
* normalised path is judged as it is first, and only when that is no capability path and
* it starts with the lower-cased base path, once more with the base path removed once.
* Either match counts. As it is comes first because the literal prefix may already be
* gone: under a mount named `/webview`, `/webview/webview/x` arrives as `/webview/x`, and
* removing the base again would lose the capability prefix itself.
*/
export function capabilityPrefixOf(rawUrl: string, basePath = ''): '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();
const asIs = capabilityPrefixOfNormalised(path);
if (asIs) return asIs;
const base = basePath.toLowerCase();
return base && path.startsWith(`${base}/`) ? capabilityPrefixOfNormalised(path.slice(base.length)) : null;
}
function capabilityPrefixOfNormalised(path: string): 'webview' | 'html-view' | null {
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, basePath = ''): boolean {
const kind = capabilityPrefixOf(req.url ?? '', basePath);
if (kind === 'webview') {
reply.code(403).type('text/plain').send('Forbidden: unknown or expired webview capability');
return true;
}
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);
@@ -329,12 +525,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;
@@ -395,6 +597,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<string, number>({
ttlMs: AUTH_FAILURE_WINDOW_MS,
refreshOnGet: false,
});
}
registerMultiUserAuthHook(
app,
https,
@@ -403,7 +614,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<string, number>() }
: null
);
return state;
}
@@ -534,7 +748,12 @@ function registerMultiUserAuthHook(
hookSecretFailures: StaleExpirationMap<string, number>,
userFailures: StaleExpirationMap<string, number>,
userIpFailures: StaleExpirationMap<string, number>,
basePath = ''
basePath = '',
trustedProxy: {
config: TrustedProxyConfig;
failures: StaleExpirationMap<string, number>;
lastLoginTouched: Map<string, number>;
} | null = null
): void {
const setSessionCookie = (reply: FastifyReply, token: string) =>
reply.setCookie(AUTH_COOKIE_NAME, token, {
@@ -658,6 +877,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, basePath)) return;
// 0. Trusted reverse-proxy identity, checked BEFORE the cookie: when the proxy
// vouches for a person on this request, that is authoritative, and a stale cookie
// 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;
+6 -2
View File
@@ -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,
},
};
});
+17
View File
@@ -34,6 +34,7 @@
import { homedir } from 'node:os';
import { join } from 'node:path';
import { trustedProxySecretFilePath, trustedProxySecretFileRealPath } from '../config/trusted-proxy.js';
const SENSITIVE_PATTERNS: RegExp[] = [
// System account databases.
@@ -81,6 +82,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 +157,18 @@ 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, as configured and with symlinks resolved (resolved once).
*/
function isTrustedProxySecretFile(absPath: string): boolean {
const file = trustedProxySecretFilePath();
if (!file) return false;
return absPath === file || absPath === trustedProxySecretFileRealPath();
}
/**
* Returns true if the given ABSOLUTE, symlink-resolved path matches the
* sensitive-file blocklist and must not be served to the browser.
@@ -162,6 +178,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));
}
+26
View File
@@ -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<string, number> | null = null;
private userFailures: StaleExpirationMap<string, number> | null = null;
private userIpFailures: StaleExpirationMap<string, number> | null = null;
private proxySecretFailures: StaleExpirationMap<string, number> | 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<void> {
// 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();
+11 -1
View File
@@ -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<string, string> {
const headers: Record<string, string> = {};
// 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;
}
+61 -1
View File
@@ -16,9 +16,12 @@
* feature), so the "stays attachable" cases matter just as much: over-blocking
* breaks the publish skill and the review-card loop.
*/
import { homedir } from 'node:os';
import { mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { homedir, tmpdir } from 'node:os';
import { join } from 'node:path';
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 +83,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 +240,60 @@ 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;
}
});
it.skipIf(process.platform === 'win32')(
'blocks the file under its real path when the setting names a symlink, and the other way round',
() => {
const prev = process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE;
const dir = realpathSync(mkdtempSync(join(tmpdir(), 'tp-secret-link-')));
const real = join(dir, 'real.key');
const link = join(dir, 'link.key');
writeFileSync(real, 'x', { mode: 0o600 });
symlinkSync(real, link);
try {
// The setting names the symlink; a caller resolves the served path to the target.
process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = link;
resetTrustedProxySecretForTests();
expect(isSensitivePath(real)).toBe(true);
initTrustedProxySecret(); // resolved once here, then answered from the cache
expect(isSensitivePath(real)).toBe(true);
expect(isSensitivePath(join(dir, 'other.key'))).toBe(false);
// The setting names the target; the symlink resolves to it.
process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = real;
resetTrustedProxySecretForTests();
initTrustedProxySecret();
expect(isSensitivePath(realpathSync(link))).toBe(true);
} finally {
resetTrustedProxySecretForTests();
if (prev === undefined) delete process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE;
else process.env.CODEMAN_TRUSTED_PROXY_SECRET_FILE = prev;
rmSync(dir, { recursive: true, force: true });
}
}
);
});
});
File diff suppressed because it is too large. Load diff