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

Multi-user mode only accepted Codeman passwords over HTTP Basic, so a team with an
identity provider (Entra ID, Google, Keycloak, ...) had to sign in twice, with no link
between the two identities.

With a shared secret configured (CODEMAN_TRUSTED_PROXY_SECRET_FILE, or
CODEMAN_TRUSTED_PROXY_SECRET; at least 32 printable ASCII characters), an authenticating
reverse proxy on the same host (oauth2-proxy behind Caddy or nginx, mod_auth_openidc,
Authelia) forwards X-Codeman-Proxy-Secret and X-Codeman-User, and the request signs in
as that existing, enabled account. CODEMAN_TRUSTED_PROXY_USER_HEADER renames the
username header. The feature is experimental (docs/versioning-policy.md): its settings,
headers and the viaTrustedProxy field may change until promoted.

- Accepted only from a loopback socket (isLoopbackIp, now shared with the hook-secret
  bypass) with a timing-safe secret match.
- The secret is read once at the start of WebServer.start(), before sessions are spawned
  or restored, and both variables are then removed from process.env, since every
  session inherits Codeman's environment. The secret file's resolved path stays in the
  module for the sensitive-path blocklist.
- A configured setup that cannot be used stops the start, like the first boot without
  users, with a message that says why and never contains the secret: both variables
  set; a secret file that is unreadable, empty, or readable by group or others (not
  checked on Windows); a short or non-ASCII secret; a secret with multi-user mode off;
  a rejected username header name. getTrustedProxyConfig() returns null for the same
  cases as a second layer.
- Both headers are read and deleted from every request by the first auth hook, in every
  auth mode, so no exemption or route (e.g. the web-tab relay) can forward the secret.
  The relay's drop list names them too, including a configured username header.
- Fails closed once the secret header is present, even empty: a wrong secret or a
  non-loopback source is 401; a missing username, or one with no enabled account, is a
  plain 403 with no challenge. None of these falls through to cookie or Basic. A
  username header without the secret is ignored.
- The username is matched exactly: normalizeUsername(), then the user store's username
  rule, no other transformation. A header sent twice arrives joined ("alice, bob") and
  is refused.
- The secret is compared before the failure bucket, so a correct secret always passes;
  only failures are throttled, in their own per-IP bucket.
- Checked before the session cookie; a cookie on the same request is neither used nor
  refreshed, and no cookie is minted: the proxy authorizes every new request and
  WebSocket upgrade.
- mustChangePassword does not gate a proxy sign-in, and GET /api/me reports
  mustChangePassword: false and viaTrustedProxy: true. Proxy sign-ins update the
  last-login time at most every 15 minutes.
- The username header is removed from every request, so its name is validated by shape
  (an X-... extension header or Remote-User; standard and reserved headers refused).
- 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, by prefix on a path normalised the way a proxy's matcher sees it
  (case-insensitive, percent-decoded, dot segments resolved), whatever the token looks
  like: the proxy has to let these paths through without its sign-in, so they must not
  reach the Basic check, prompt or failure bucket. Without a proxy they keep the normal
  401.
- The configured secret file is on the isSensitivePath blocklist.
- The startup log says "Trusted-proxy sign-in enabled (experimental)".
- Single-user mode, the Host/Origin guard and the hook-secret bypass are otherwise
  unchanged.

Docs: security-architecture §10a, architecture-invariants, versioning-policy (new
experimental subsection), Settings-Reference, web-tabs and its wiki page, multi-user-plan,
the CLAUDE.md summary line, and a Caddy + oauth2-proxy walkthrough in the Multi-User Mode
wiki page (web tabs and HTML view bypass the sign-in and never get the secret; the proxy
removes its own session cookie; hook endpoints and their /api/v1 aliases are blocked;
optional username from an IdP claim; what the secret does not protect against).
Changeset included.
This commit is contained in:
13768039+zomby1 committed 2026-11-24 21:41:53 +01:00
1 parent 5548c17c4a
commit 8480bba908
19 files changed
+2024 -16

No files matched your search

+2
View File
@@ -636,6 +636,8 @@ Further detail: the refused egress targets are `169.254.0.0/16`, `fe80::/10`, `f
**Multi-user mode** (opt-in `--multiuser` / `CODEMAN_MULTIUSER=1`, OFF by default; shipped 1.5.0 via PR #161, design `docs/multi-user-plan.md`): named users with individually scrypt-hashed passwords in `~/.codeman/users.json` (via `src/user-store.ts`: atomic 0600 write, short-TTL cache, SERIALIZED read-modify-write so a fire-and-forget `touchLastLogin` can't clobber a concurrent route write, last-admin invariants). Gated everywhere by `isMultiUserMode()` (`src/config/multiuser.ts`); when OFF, behavior is byte-identical to single-user (all scoping helpers short-circuit). ⚠️ **Not a security boundary at the agent layer** — every session still runs as the SAME OS account; this separates WORKSPACES, it does not sandbox users (Docker cases are the isolation story). Auth: a PARALLEL async branch in `middleware/auth.ts` (single-user branch untouched) verifies `username:password` against the store, mints identity-carrying cookies (`AuthSessionRecord` gains `username`/`role`/`mustChangePassword`), decorates `req.authUser` (Fastify augmentation; single-user leaves it undefined and the ownership helpers default to a synthetic admin), enforces a per-username failure bucket + the `mustChangePassword` lockbox. Ownership threads through `Session.owner` (stamped from `req.authUser`/`job.owner` at every `new Session()`, round-tripped via `MuxSession.owner` on recovery); `findSessionOrFail(ctx,id,req)` does a NOT_FOUND owner check; list endpoints + `getLightState` + SSE (`deriveSseHint` routes session-scoped events by owner, fail-closed; machine-level + host-plan telemetry admin-only) + WS + search + file-preview all filter by owner. §6.3 permission policy: non-granted users are forced to `--permission-mode auto` (via `resolveClaudeModeForUser` at all spawn sites, incl. one-shots because `buildPromptArgs` now respects the session mode), and shell mode / cron `launchCommand` require the `canBypassPermissions` grant. Cases live in per-user `~/codeman-users/<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.
+2 -2
View File
@@ -184,8 +184,8 @@ All handlers: multi-user mode only (404 otherwise), `requireAdmin`, Zod schemas
| `GET /api/admin/users` | List users + stats: role, disabled, createdAt, lastLoginAt, live session count, case count, space disk usage (best-effort async walk, cached 60s), active cookie-session count |
| `POST /api/admin/users` | Create: `{ username, role, password? }`. No password given: generate a one-time password, return it ONCE in the response, set `mustChangePassword` |
| `PATCH /api/admin/users/:username` | `{ role?, disabled?, canBypassPermissions? }`. Demoting/disabling the last enabled admin: 409 `LAST_ADMIN`. Disable also revokes cookie sessions. `canBypassPermissions` is the section 6.3 grant (default false) |
| `POST /api/admin/users/:username/reset-password` | Generates one-time password (returned once), sets `mustChangePassword`, revokes cookie sessions |
| `POST /api/admin/users/:username/logout` | Revoke all cookie sessions for that user. Honest limit under Basic auth: the browser silently re-sends cached credentials and gets a fresh cookie on the next request, so logout only truly ends QR-issued sessions; to actually lock someone out, disable the account or reset the password. Say so in the panel tooltip until Phase 6 |
| `POST /api/admin/users/:username/reset-password` | Generates one-time password (returned once), sets `mustChangePassword`, revokes cookie sessions. Does not end a trusted-proxy sign-in, which uses no password and holds no cookie |
| `POST /api/admin/users/:username/logout` | Revoke all cookie sessions for that user. Honest limit under Basic auth: the browser silently re-sends cached credentials and gets a fresh cookie on the next request, so logout only truly ends QR-issued sessions; to actually lock someone out, disable the account or reset the password. For a person who signs in through a trusted reverse proxy, neither logout nor a reset ends access (no cookie, no password): disable or delete the account. Say so in the panel tooltip until Phase 6 |
| `DELETE /api/admin/users/:username` | `{ deleteSpace?: boolean }` (default false). Refuses last admin. Kills the user's live sessions first (normal kill flow, incl. docker/remote teardown per case), revokes cookies, removes from store. With `deleteSpace`: guarded recursive delete of `~/codeman-users/<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) |
+141
View File
@@ -590,6 +590,144 @@ Full feature guide: [`docker-cases.md`](docker-cases.md).
- **Clone Repo does not lend the server's git sign-in to non-admins.** A clone writes only inside the caller's own case space, so it is not admin-gated, but the server account's git credential helpers (the Docker image's opt-in `gh`/`az` helpers, or any `gh auth setup-git`) are shared by every user. A non-admin's clone and preflight therefore run with `git -c credential.helper=`, which empties the helper list including the URL-scoped entries (`cloneWithoutCredentialHelpers` in `case-routes.ts`, argv pinned in `test/git-clone.test.ts`). This closes the Clone Repo path only: the account's SSH keys still apply to an `ssh://` URL, and a non-admin's agent sessions run as the same account, consistent with the first bullet above. Docker cases are a second route to the same sign-in: with `CODEMAN_AGENT_IMAGE_INSTALL_GH`/`_AZ` on, a non-admin's Docker case with credential seeding on (the default) receives a copy of the server account's `gh`/`az` sign-in, exactly as it receives the Claude and Codex credentials.
- **Admin actions are audited** append‑only to `~/.codeman/admin-audit.jsonl` (acting admin, action, target, IP). Passwords set by an admin create/reset are one‑time (returned once, force change). Under Basic auth, `logout` only truly ends QR‑issued sessions — to lock someone out, disable the account or reset the password (a proper login form is a deferred Phase 6).
### Trusted reverse‑proxy sign‑in (opt‑in, multi‑user only)
A shared secret lets an authenticating reverse proxy on the same host (oauth2‑proxy behind
Caddy or nginx, Apache `mod_auth_openidc`, Authelia, …) sign people in through an identity
provider such as Entra ID, Google or Keycloak, in place of the Basic prompt. Source:
`src/config/trusted-proxy.ts`, `checkTrustedProxyIdentity` and
`registerTrustedProxyHeaderStrip` in `middleware/auth.ts`; tests in
`test/trusted-proxy-auth.test.ts`; a worked Caddy + oauth2‑proxy setup in
[`docs/wiki/Multi-User-Mode.md`](wiki/Multi-User-Mode.md#single-sign-on-through-a-reverse-proxy).
**Experimental** ([versioning-policy.md](versioning-policy.md)): the three settings, the two
headers and the `viaTrustedProxy` field of `GET /api/me` may change until they are promoted
by an explicit decision.
"Trusted proxy" names this sign-in only. It is not forwarded-address trust: Codeman still
does not read `X-Forwarded-For`, `trustProxy` stays `false`, and `req.ip` stays the socket
peer (§3).
- **What the proxy sends.** After it has authenticated the person, the proxy adds
`X-Codeman-Proxy-Secret: <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`). The prefix is judged
the way a proxy's path matcher would (`capabilityPrefixOf`: case‑insensitive,
percent‑decoded, dot segments and doubled slashes resolved), since the proxy forwards
every such spelling without its sign‑in. Otherwise anonymous
requests through the proxy could probe passwords and fill the per‑IP bucket, which
behind the proxy is always `127.0.0.1`, locking out Basic sign‑in from loopback.
Without a proxy configured these paths keep the normal `401` challenge. One limit
follows from the exemption being by prefix: a sandboxed frame's request that lands
outside its prefix goes through the proxy's sign-in without a cookie and fails there,
so the `Referer` form and the lost-frame recovery page (§10b) are not reachable for
sandboxed frames behind the proxy.
- **The proxy's own session cookie.** A cookie-based proxy's session cookie is a sign-in
for the whole site. Codeman does not know its name, and the web-tab relay forwards
browser cookies (all but `codeman_session`) to a dashboard opened in trusted mode. The
proxy must remove its cookie from every request it forwards to Codeman, on the
capability paths and after its own sign-in check; the wiki example does.
- **Unchanged:** the Host allowlist and Origin guard (set `CODEMAN_ALLOWED_HOSTS` to the
proxy's hostname), the hook‑secret loopback bypass (a proxy should still refuse
`/api/hook-event`, `/api/status-telemetry` and their `/api/v1/` aliases from outside;
local hooks call the loopback port directly), and Basic sign‑in for requests without
the secret header. Admin actions through the proxy are audited with IP `127.0.0.1`, as
with any reverse proxy.
- **Not supported:** Docker Compose installs where Codeman runs in a container and the
proxy on the host; the proxy then connects from the bridge address, not loopback.
---
## 10b. Web tabs (dashboard proxy)
@@ -629,6 +767,8 @@ Opt-in by a click, macOS only, admin-only in multi-user mode on every verb. The
| Env / flag | Effect |
|------------|--------|
| `CODEMAN_PASSWORD` (+ `CODEMAN_USERNAME`) | Enable HTTP Basic auth |
| `CODEMAN_TRUSTED_PROXY_SECRET_FILE` / `CODEMAN_TRUSTED_PROXY_SECRET` | Multi‑user only: trust a same‑host authenticating reverse proxy that presents this secret (≥ 32 printable ASCII chars; the file variant is preferred; both variables are removed from the environment once read; a setup that cannot be used stops the start) and a username header. Experimental — see §10a |
| `CODEMAN_TRUSTED_PROXY_USER_HEADER` | Header the trusted proxy puts the Codeman username in (default `X-Codeman-User`) |
| `--host` / `CODEMAN_HOST` | Bind host (default `127.0.0.1`) |
| `CODEMAN_ALLOWED_HOSTS` | Extra `Host`/`Origin` allowlist entries for reverse proxies (comma‑separated; exact host, or leading‑dot `.suffix` for subdomains) — see §3 |
| `--base-url` / `CODEMAN_BASE_URL` | Sub‑path prefix Codeman is mounted under behind a reverse proxy, e.g. `/codeman` (default `/`); the proxy must forward the prefix unchanged. Independent of `CODEMAN_ALLOWED_HOSTS` |
@@ -650,6 +790,7 @@ Opt-in by a click, macOS only, admin-only in multi-user mode on every verb. The
| Bind‑host classification, env‑flag parsing, Host/Origin allowlist (`buildHostPolicy` / `isAllowedRequestHost` / `isAllowedRequestOrigin`) | `src/web/network-auth-policy.ts` |
| Start‑and‑warn policy | `src/web/server.ts` (`WebServer.start()`) |
| Auth pipeline, rate limiting, security headers, CORS, Host/Origin guard (`registerHostGuard`) | `src/web/middleware/auth.ts` |
| Trusted reverse‑proxy sign‑in: secret loading, header names, header stripping | `src/config/trusted-proxy.ts` |
| File‑path containment (realpath‑before‑check) | `src/web/route-helpers.ts` (`validateSessionFilePath`) |
| File routes, caps, SVG handling, download blocklist | `src/web/routes/file-routes.ts` |
| Instance/socket/data‑dir scoping | `src/config/instance.ts` |
+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.
+312 -1
View File
@@ -112,7 +112,318 @@ casually; they do not make the account a sandbox.
Each user authenticates with their own name and password rather than the shared
`CODEMAN_PASSWORD`. Logins are individually revocable: disable, reset, or delete an account
at any time, and existing browser sessions can be revoked.
at any time, and existing browser sessions can be revoked. A person who signs in through a
reverse proxy (next section) uses no Codeman password and holds no browser session, so a
password reset or a logout does not end their access: disable or delete the account.
## Single sign-on through a reverse proxy
Instead of Codeman passwords, people can sign in through your identity provider (Entra ID,
Google Workspace, Keycloak, Okta, ...). An authenticating reverse proxy on the same host
does the sign-in and tells Codeman who the person is. Codeman still decides who has an
account: the username must name an existing, enabled user, or the request gets `403`.
**Experimental.** The settings, the two headers and the `viaTrustedProxy` field of
`GET /api/me` may still change (see
[`docs/versioning-policy.md`](https://github.com/Ark0N/Codeman/blob/master/docs/versioning-policy.md)).
"Trusted proxy" here means only this sign-in. It does not make Codeman read
`X-Forwarded-For` or any other forwarded address: the client address stays the address of
the socket, which behind the proxy is `127.0.0.1`.
```
browser --HTTPS--> Caddy --forward_auth--> oauth2-proxy (127.0.0.1:4180) --> identity provider
\--reverse_proxy--> Codeman (127.0.0.1:3000, multi-user mode)
```
On every request the proxy adds two headers:
| Header | Value |
|---|---|
| `X-Codeman-Proxy-Secret` | the shared secret |
| `X-Codeman-User` | the Codeman username (another name can be set with `CODEMAN_TRUSTED_PROXY_USER_HEADER`: an `X-…` header such as `X-Forwarded-User`, or `Remote-User`; standard and reserved headers are refused, because the header is removed from every request) |
Codeman believes them only from a loopback connection with the matching secret, so keep
Codeman bound to `127.0.0.1` and the proxy on the same host. It removes both headers from
every request before anything else sees them. The exact rules are in
[`docs/security-architecture.md` §10a](https://github.com/Ark0N/Codeman/blob/master/docs/security-architecture.md).
The secret keeps other local processes from claiming an identity. It does not protect
against anything that runs as Codeman's own OS account, which includes every agent session:
such a process can read the secret and sign in as anyone, an admin included, over loopback.
That is the same exposure as editing `users.json`, which the same account can also do (see
[Read this before enabling it](#read-this-before-enabling-it)).
### Codeman
```bash
install -m 600 /dev/null ~/.codeman/proxy-secret
openssl rand -hex 32 > ~/.codeman/proxy-secret # the shared secret, also given to the proxy
codeman users add alice --admin # accounts still come from Codeman
CODEMAN_MULTIUSER=1 \
CODEMAN_ALLOWED_HOSTS=codeman.example.com \
CODEMAN_TRUSTED_PROXY_SECRET_FILE=~/.codeman/proxy-secret \
codeman web # stays on 127.0.0.1:3000
```
The startup log says `Trusted-proxy sign-in enabled (experimental)`. A setup that cannot be
used stops the start, with a message that says why:
- the secret file cannot be read, is empty, or can be read by group or others (`chmod 600`
it; the mode is not checked on Windows);
- the secret is shorter than 32 characters or not printable ASCII;
- both `CODEMAN_TRUSTED_PROXY_SECRET_FILE` and `CODEMAN_TRUSTED_PROXY_SECRET` are set;
- a secret is set without multi-user mode;
- `CODEMAN_TRUSTED_PROXY_USER_HEADER` names a header that is not allowed.
In a systemd unit, give the file as an absolute path (systemd does not expand `~`; `%h`
works in a user unit; in a system unit write the full path). Codeman's downloads and
attachments refuse the configured secret file.
`CODEMAN_TRUSTED_PROXY_SECRET` (the value itself) works too. Codeman reads the settings
once and removes both variables from its environment, so sessions started later don't
inherit them. That is all it does: the value stays visible in `/proc/<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_expire = "12h" # sign in again after this (default 168h)
cookie_refresh = "1h" # re-check with the provider this often
scope = "openid email profile offline_access" # offline_access: a refresh token (Entra ID)
```
Client ID, client secret and cookie secret go in the environment
(`OAUTH2_PROXY_CLIENT_ID`, `OAUTH2_PROXY_CLIENT_SECRET`, `OAUTH2_PROXY_COOKIE_SECRET`).
For Entra ID add `oidc_email_claim = "preferred_username"`. Without `cookie_refresh`, a
person disabled at the provider keeps access until the cookie expires. `cookie_refresh`
needs a refresh token: without one (for Entra ID, without `offline_access` in the scope),
oauth2-proxy can't refresh, and people are sent back through sign-in whenever the ID token
expires, about hourly.
### Caddy
Give Caddy the same secret through its environment, not in the Caddyfile (which is often
world-readable): for the packaged service, a systemd drop-in with
`EnvironmentFile=/etc/caddy/codeman-proxy.env` (mode 0600) containing
`CODEMAN_TRUSTED_PROXY_SECRET=<secret>`. Keep the `{env.…}` placeholder below; a `{$…}`
placeholder would put the value into the adapted config, which local processes can read
from Caddy's admin port.
```caddyfile
codeman.example.com {
# Signed-in identity -> Codeman username (case-sensitive: use the spelling your
# provider returns). Unlisted people get an empty username and are refused below.
map {http.request.header.X-Auth-Request-Email} {codeman_user} {
alice@example.com alice
default ""
}
# Hooks call 127.0.0.1:3000 directly; never expose them (or their /api/v1 aliases).
@hooks path /api/hook-event /api/status-telemetry /api/v1/hook-event /api/v1/status-telemetry
# Web tabs and rendered HTML files authenticate by the capability in their URL: their
# sandboxed frames send no cookies, so they can't pass the sign-in below.
@capability path /webview/* /html-view/*
# `route` keeps the order as written. Without it Caddy sorts directives itself, and
# `handle` would run before `respond`, or forward_auth before request_header.
route {
respond @hooks 403
handle /oauth2/* {
reverse_proxy 127.0.0.1:4180 {
header_up X-Real-IP {remote_host}
header_up X-Forwarded-Uri {uri}
}
}
handle @capability {
# No sign-in and no secret: Codeman checks the capability itself. No password
# either: these paths must never reach Codeman's password check or prompt.
request_header -X-Codeman-Proxy-Secret
request_header -X-Codeman-User
request_header -Authorization
# oauth2-proxy's cookie is a sign-in for this whole site. Codeman never needs
# it, and its web-tab relay forwards browser cookies to a dashboard opened in
# trusted mode.
request_header Cookie "(^|;\s*)_oauth2_proxy[^=;]*=[^;]*" ""
reverse_proxy 127.0.0.1:3000 {
header_down -WWW-Authenticate
}
}
handle {
route {
# Only oauth2-proxy and this file may set identity headers.
request_header -X-Auth-Request-Email
request_header -X-Codeman-Proxy-Secret
request_header -X-Codeman-User
forward_auth 127.0.0.1:4180 {
uri /oauth2/auth
copy_headers X-Auth-Request-Email
@unauthenticated status 401
handle_response @unauthenticated {
redir * /oauth2/start?rd={scheme}://{hostport}{uri}
}
}
@nouser vars {codeman_user} ""
respond @nouser "No Codeman account for this sign-in" 403
# After forward_auth, which needs it: remove oauth2-proxy's cookie.
request_header Cookie "(^|;\s*)_oauth2_proxy[^=;]*=[^;]*" ""
reverse_proxy 127.0.0.1:3000 {
header_up X-Codeman-Proxy-Secret {env.CODEMAN_TRUSTED_PROXY_SECRET}
header_up X-Codeman-User {codeman_user}
}
}
}
}
}
```
This example was run with Caddy 2.11.9 and oauth2-proxy 7.15.6. What it relies on, because
Codeman cannot see a mistake here:
- **The proxy removes what the client sent.** The `request_header -…` lines delete any
copy of the identity headers that arrived from outside, and `header_up` replaces a
header, it never appends. The username therefore only ever comes from the sign-in result.
- **The secret is added only behind the sign-in**, never on the `/webview/*` and
`/html-view/*` route.
- **The proxy's own cookie stops at the proxy.** The `request_header Cookie …` lines remove
it on both routes. With a different `cookie_name` in oauth2-proxy, change the name in
the pattern.
Check the order Caddy will actually use with
`caddy adapt --config Caddyfile --adapter caddyfile` before going live. With
`CODEMAN_BASE_URL` (a sub-path mount), prefix the paths in `@hooks` and `@capability`.
To check that a forged header is ignored, run this in the browser console of the signed-in
page. It must show your own username:
```js
fetch('/api/me', { headers: { 'X-Codeman-User': 'someone-else' } }).then((r) => r.json()).then(console.log)
```
### Taking the username from the identity provider instead
The `map` is a list you maintain. If your provider can put the Codeman username into the
ID token (for example the AD logon name: Entra ID can add it with a claims mapping policy
that emits `user.onpremisessamaccountname` as a custom claim; the app then needs
`acceptMappedClaims` enabled), let oauth2-proxy return that claim as a header. That needs
oauth2-proxy 7.15.5 or later with its alpha config (`--alpha-config`), and the claim must
be listed in the provider's `additionalClaims`, otherwise the header stays empty:
```yaml
providers:
- id: idp
provider: oidc
# ... clientID, clientSecretFile, oidcConfig ...
additionalClaims:
- samaccountname
injectResponseHeaders:
- name: X-Auth-Request-Codeman-User
values:
- claimSource:
claim: samaccountname
```
In the Caddyfile, drop the `map` and replace the inner `route` of the last `handle`:
```caddyfile
route {
request_header -X-Auth-Request-Email
request_header -X-Auth-Request-Codeman-User
request_header -X-Codeman-Proxy-Secret
request_header -X-Codeman-User
forward_auth 127.0.0.1:4180 {
uri /oauth2/auth
copy_headers X-Auth-Request-Email X-Auth-Request-Codeman-User
@unauthenticated status 401
handle_response @unauthenticated {
redir * /oauth2/start?rd={scheme}://{hostport}{uri}
}
}
@nouser vars {http.request.header.X-Auth-Request-Codeman-User} ""
respond @nouser "No Codeman username for this sign-in" 403
request_header Cookie "(^|;\s*)_oauth2_proxy[^=;]*=[^;]*" ""
reverse_proxy 127.0.0.1:3000 {
header_up X-Codeman-Proxy-Secret {env.CODEMAN_TRUSTED_PROXY_SECRET}
header_up X-Codeman-User {http.request.header.X-Auth-Request-Codeman-User}
}
}
```
Adding a person is then: allow them at the identity provider, and
`codeman users add <name>`. Codeman usernames allow letters, digits, `_` and `-` only, so
the claim must fit that. A browser that signed in before the claim existed needs to sign
out (`/oauth2/sign_out`) and in again.
### Things to know
- **No Codeman cookie is issued** for proxy sign-ins. The proxy authorizes every new
request and WebSocket upgrade, but a terminal or live-update connection that is already
open stays open until it disconnects.
- **Cutting someone off:** disable their Codeman account (new requests are refused), then
use **Logout** for them in the Admin Panel, which also revokes the web-tab and HTML-view
links they opened (disabling alone doesn't, and those links don't need the proxy's
sign-in). Deleting the account does both. Logout alone, or a password reset, does not
cut off a proxy sign-in: it holds no cookie and uses no password, so the next request
signs the person in again. Connections already open stay open until they disconnect.
- **Web tabs and HTML view behind the proxy:** with trusted-proxy sign-in configured, a
path under those prefixes without a live capability, malformed ones included, is refused
(`403` / `404`) without a password check,
prompt or failure count, so anonymous requests can't probe passwords or lock out the
password sign-in.
- **When the proxy session expires**, API calls and the live-update stream get a redirect
to the sign-in page instead of a `401`; reload the page. The `rd=` return address is not
URL-encoded, so a query string with `&` loses everything after the first one.
- **`mustChangePassword` is ignored** for proxy sign-ins, since no Codeman password was
used, and `GET /api/me` reports it as `false` for them. A person's own "Revoke all" and logout end Codeman cookies, not the proxy's
session; sign out of the proxy at `/oauth2/sign_out`.
- **A wrong or empty secret is refused outright** (and failures are rate-limited per IP);
it never falls back to the cookie or password sign-in.
- **Sandboxed web tabs:** a request the dashboard makes outside its
`/webview/<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
@@ -299,6 +299,9 @@ Some things are configured before the server starts, not in the UI:
| `CODEMAN_ALLOWED_HOSTS` | Extra Host and Origin allowlist entries for a reverse proxy. |
| `CODEMAN_INSTANCE` | Scopes the data directory and tmux socket together. Required for a second instance. |
| `CODEMAN_MULTIUSER` | Enables multi-user mode. |
| `CODEMAN_TRUSTED_PROXY_SECRET_FILE` | Experimental, multi-user only. A file (mode 600) holding the secret that lets an authenticating reverse proxy on the same host sign people in (single sign-on). A setup that cannot be used stops the start. See [Multi-User Mode](Multi-User-Mode#single-sign-on-through-a-reverse-proxy). |
| `CODEMAN_TRUSTED_PROXY_SECRET` | The same secret given directly. Both variables are read once at startup and then removed from the environment, so sessions don't inherit them; the file variant is preferred. |
| `CODEMAN_TRUSTED_PROXY_USER_HEADER` | Header that proxy puts the Codeman username in. `X-Codeman-User` by default; only an `X-…` header or `Remote-User` is accepted. |
| `CODEMAN_GESTURE` | Makes gesture control available to be enabled. |
| `CODEMAN_DOCKER_BRIDGE_HOOKS` | Lets in-container hooks reach the host on a loopback bind. |
| `CODEMAN_FILE_PICKER_ROOTS` | Extra roots for the path picker. |
+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