Skip to content

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

Open
zomby1 wants to merge 11 commits into
Ark0N:masterfrom
zomby1:feat/trusted-proxy-auth
Open

zomby1 wants to merge 11 commits into
Ark0N:masterfrom
zomby1:feat/trusted-proxy-auth

Conversation

@zomby1

@zomby1 zomby1 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Closes #846

Problem

Multi-user mode only accepts Codeman passwords over HTTP Basic, so a team with an identity provider signs in twice and the two identities are not linked.

Change

With a shared secret configured (CODEMAN_TRUSTED_PROXY_SECRET_FILE or CODEMAN_TRUSTED_PROXY_SECRET), an authenticating reverse proxy on the same host sends X-Codeman-Proxy-Secret and X-Codeman-User, and the request signs in as that existing, enabled account. Off by default, multi-user mode only, and labelled experimental in docs/versioning-policy.md.

  • src/config/trusted-proxy.ts (new): loads and validates the settings once, removes both secret variables from process.env, reads and removes the two headers.
  • src/web/middleware/auth.ts:
    • a first hook strips the two headers from every request, in every mode, also with no login configured;
    • checkTrustedProxyIdentity runs before the cookie check: loopback only, timingSafeEqual on equal lengths, fails closed, its own failure bucket, no cookie. The loopback test is isLoopbackIp(), now shared with checkHookSecretBypass();
    • the username goes through normalizeUsername() and isValidUsername() and nothing else. A missing, invalid, unknown or disabled one gets a plain 403;
    • serveRefusedCapabilityPath: with the feature on, a /webview/ or /html-view/ request without a live capability is answered by the hook before any credential is evaluated or counted.
  • src/web/server.ts: a configured setup that cannot be used stops the start, like the first boot without users.
  • src/web/routes/me-routes.ts: GET /api/me adds viaTrustedProxy and reports mustChangePassword: false for proxy sign-ins.
  • src/web/webview-proxy.ts, src/web/sensitive-path.ts: both default header names and the configured one are on the relay's drop list; the secret file is refused by downloads and attachments.
  • Docs: docs/security-architecture.md §10a, docs/versioning-policy.md, docs/architecture-invariants.md, docs/multi-user-plan.md, docs/web-tabs.md, CLAUDE.md, the wiki settings reference, and a Caddy + oauth2-proxy walkthrough in the multi-user wiki page.

Your checklist from #846

  • Nothing passes the hook without an identity. On the two capability prefixes the hook answers itself, with the status the route gives (403 for web tabs, 404 for HTML view), no challenge, nothing counted.
  • Start-up refusal. Both variables set; a secret file that is unreadable, empty, or readable by group or others (the mode is not checked on Windows); a secret shorter than 32 characters or not printable ASCII; a secret without multi-user mode; a rejected CODEMAN_TRUSTED_PROXY_USER_HEADER. The message never contains the secret.
  • Username. Matched exactly. A header that arrives twice (alice, bob) is refused, also when both accounts exist. With a valid proxy identity the codeman_session cookie is ignored and not refreshed.
  • User header name. Only an X-… header or Remote-User, with reserved names refused. X-Codeman-User is removed whichever name is configured.
  • Environment. Both variables are removed. The docs say what that does not do: an inline secret stays in /proc/<pid>/environ, and any session running as Codeman's OS account can read the secret and sign in as anyone over loopback.
  • lastLoginAt. An in-memory throttle (15 minutes per user) sits in front of touchLastLogin().
  • Walkthrough. The proxy removes client-sent copies of both headers, sets the username from the sign-in result, adds the secret only behind the sign-in, and removes its own session cookie before anything reaches Codeman. Run with Caddy 2.11.9 and oauth2-proxy 7.15.6.

Behaviour with the feature off

  • The two request headers, and a configured username header, are dropped on arrival.
  • Downloads and attachments refuse a file named proxy-secret in the data dir.
  • A secret set without multi-user mode, or a rejected header name, stops the start.

Tests

  • test/trusted-proxy-auth.test.ts (92 tests) and test/sensitive-path.test.ts: configuration and each start-up refusal, header stripping, sign-in and refusal paths, the username rule, source address, rate limiting, capability paths, the relay drop list, WebSocket upgrade and owner scoping.
  • npm run typecheck, lint, format:check, check:frontend-syntax, check:frontend-dead, check:public-assets, check:browser-excludes, check:lockfile, check:plugin: pass.
  • npm test: all 17,408 tests pass (764 files, 13 skipped).

Manual test

Running on my own install behind Caddy + oauth2-proxy. The app, API, SSE, terminal and web tabs work for the signed-in account. Forged identity headers are ignored, unknown accounts are refused, no session inherits the secret, and a trusted web tab no longer receives the proxy's session cookie.

Follow-ups, not in this PR

  • A relay-side list of extra cookie names to drop, covering buildUpstreamRequestHeaders() and the WebSocket leg's filterCookieHeader() call.
  • A per-account proxy identity on the user record, matched exactly, so email-based providers need no mapping table in the proxy.
  • Revoking an account's web-tab and HTML-view capabilities when it is disabled.

…e (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.
@Ark0N

Ark0N commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks for this, and for working through the whole #846 list. The PR lets multi-user mode sign people in through an authenticating reverse proxy on the same host, off by default and experimental.

I ran your Caddy example with Caddy 2.11.9 against a real server, with a stub in place of oauth2-proxy. I tried a forged X-Codeman-User (once and twice), a forged secret, a forged X-Auth-Request-Email, a Connection: header trick and another account's Basic credentials, and every request still signed in as the proxy's user. The proxy cookie and Authorization never reached the capability route's upstream. The claim-based variant behaves the same, and the full suite passes here.

Needed before merge:

  1. CODEMAN_BASE_URL gets around the capability refusal (src/web/middleware/auth.ts:402). capabilityPrefixOf() normalises the path, but before that the mount prefix is only stripped in its literal spelling. On a server mounted at /codeman, Caddy exempts all of these, and each one reaches the Basic check, gets a challenge and is counted: /CODEMAN/webview/x, /%63odeman/webview/x, //codeman/webview/x, /x/../codeman/webview/x, /CODEMAN/html-view/x. Through Caddy, 60 anonymous requests filled the per-IP bucket, and a correct password from 127.0.0.1 then got 429. Please pass basePath into serveRefusedCapabilityPath() and capabilityPrefixOf(), and after the normalisation strip the lower-cased base path when the path starts with it plus /. Add those spellings to the table test, plus one server test with a base path. The root mount is fine.

  2. Some of the new behaviour has no test. Each of these changes left test/trusted-proxy-auth.test.ts and test/sensitive-path.test.ts green:

    • removing the 15 minute lastLoginAt throttle, or never calling touchLastLogin() (auth.ts:253)
    • falling through to cookie and Basic when the user store is unreadable, instead of the 503 (auth.ts:241)
    • leaving X-Codeman-User on the request when another header is configured (src/config/trusted-proxy.ts:250)
    • applying the capability refusal with the feature off (auth.ts:850)
    • dropping the realpath comparison for the secret file (src/web/sensitive-path.ts:167)
    • allowing the reserved names such as X-Requested-With (src/config/trusted-proxy.ts:67)

    One assertion each is enough.

Please include these in the same push:

  1. docs/wiki/Multi-User-Mode.md:223 and :339: the points from my last comment on Multi-user mode: sign in through an authenticating reverse proxy (SSO) #846 are missing. The app registration is single-tenant, and acceptMappedClaims belongs only on a single-tenant app. email and preferred_username are mutable. An address given to someone else takes the Codeman account with it until its row is removed. A logon name with a dot needs the mapping table.
  2. docs/api-reference.md needs three updates. Line 978: with the feature on, an unknown HTML-view capability is the hook's 404, not the 401. Line 62: a 401 is no longer the only response that is not an envelope, because the proxy refusals are plain-text 401 without a challenge, 403 and 503. The Authentication section at line 1891 needs one too.
  3. docs/wiki/Multi-User-Mode.md:215: add cookie_samesite = "lax" to the oauth2-proxy config. The docs say sandboxed frames do not send the proxy's cookie, but oauth2-proxy sets no SameSite attribute unless it is configured.

Nits:

  • src/web/sensitive-path.ts:167: resolve the secret file's real path once in loadSecret() instead of calling realpathSync() for every served file.
  • docs/wiki/Multi-User-Mode.md:289: remove X-Auth-Request-Email on the way to Codeman (header_up -X-Auth-Request-Email), because the relay copies headers it does not know to dashboards.
  • docs/multi-user-plan.md:191: the GET /api/me row lacks viaTrustedProxy.

One question from #846 is still open, and this review does not settle it: whether a dead capability under /webview/ answers 403, as the branch does, or 404 like /html-view/. I am not asking for a change there in this round.

Items 1 and 2 have to be in before this can merge.

Under CODEMAN_BASE_URL the server strips the mount prefix only in its
literal spelling, so /CODEMAN/webview/x, /%63odeman/webview/x,
//codeman/webview/x or /x/../codeman/webview/x reached the credential
checks with the prefix still in front. A proxy's path matcher lets
those through without its sign-in, so they got a Basic challenge and
filled the per-IP failure bucket. capabilityPrefixOf() now takes the
base path and, after its normalisation, removes the lower-cased base
path once when the path starts with it. The exemptions are unchanged.

The secret file's real path is now resolved once, when the secret is
read, instead of on every sensitive-path check.

Tests for behaviour that had none: the last-login throttle for proxy
sign-ins, the 503 for an unreadable user store with a valid cookie or
Basic credentials, removal of X-Codeman-User when another username
header is configured, the normal challenge on capability paths with
the feature off, the secret file reached through a symlink, and the
reserved username header names.
…replies

The walkthrough now says the app registration is single-tenant, that email and
preferred_username are mutable, and that a logon name with a dot needs the map.
oauth2-proxy gets cookie_samesite = lax, and its identity headers are removed on
the way to Codeman. The API reference lists the hook's plain-text replies for a
proxy sign-in and the 404 for an unknown HTML-view capability.
The server strips the literal mount prefix before the auth hook runs, so
under a base path named /webview, /html-view or starting with one of
them, /webview/webview/x arrives as /webview/x. Removing the base path
again in capabilityPrefixOf() then took the capability prefix itself,
and such paths reached the Basic check and its failure count.

The normalised path is now judged as it is first, and only when that is
no capability path, once more with the base path removed once. Either
match counts, so this can only add refusals, never an exemption.
Background requests from an open page followed the redirect to the sign-in
start, and each one replaced oauth2-proxy's CSRF cookie, so a real sign-in
could end on its CSRF error page. The example now answers them with 401 and
uses one CSRF cookie per sign-in.
Under a dead web-tab capability, GET /webview/<cap> without the trailing
slash and a WebSocket upgrade have no route status to copy (the route
alone redirects, or accepts and closes with 4003). With trusted-proxy
sign-in on, the hook answers both with 403, no challenge and no count.
The refusal test sends each of them more often than the per-IP failure
limit, before its final Basic sign-in, so a counted one turns that
sign-in into a 429.
…copy

A WebSocket upgrade and GET /webview/<cap> without the trailing slash get the
hook's 403 under a dead web-tab capability. Say so in section 10a, next to the
statuses.
The rule answers a request with a non-navigation Sec-Fetch-Mode with 401. A
client that sends no such header is redirected as before, and a WebSocket
handshake never followed the redirect.
@zomby1

zomby1 commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review, and for running the example. All of it is in the new commits.

1. Base path. capabilityPrefixOf() and serveRefusedCapabilityPath() take the base path now. After the normalisation, a path that starts with the lower-cased base path plus / is also judged with the base path removed once. Your five spellings are in the table test, with rows that must stay unmatched (/codemanx/webview/x, /other/webview/x). A server test mounted at /codeman sends 60 of them with the path exactly as written, gets 403 or 404 without a challenge each time, and then signs in with a correct password.

One case beyond your list: a mount that is itself named /webview or /html-view (or starts with one). The server has already removed the literal mount there, so removing the base path again would lose the capability prefix. The path is therefore judged as it arrives first, and a match in either form is refused. That has its own table rows and a server test mounted at /webview.

2. Tests. One for each of your six. I checked each the way you did: reverted the behaviour, saw the test fail, restored it.

  • last login: called at 0 minutes, not at 14, again at 15
  • unreadable user store: 503, also when the request carries a valid cookie or valid Basic credentials
  • X-Codeman-User is removed when another header is configured
  • feature off: both prefixes keep the normal 401 challenge
  • the secret file is refused under its real path when the setting names a symlink
  • the reserved names are refused

3. Claims. The walkthrough says the app registration is single-tenant and that acceptMappedClaims belongs only there. It also says email and preferred_username are mutable, that a reassigned address takes the account with it until its row is removed, and that a logon name with a dot needs the mapping table.

4. docs/api-reference.md. The three places are updated. The Authentication section has a short table of the plain-text replies on the proxy path. While there I corrected one older sentence: the hook-path 401 carries no WWW-Authenticate.

5. cookie_samesite = "lax" is in the oauth2-proxy config, with the reason.

Nits. The real path is resolved once in loadSecret(). header_up -X-Auth-Request-Email is in both examples, and the claim variant also removes its own header; I ran both on Caddy 2.11.9. The GET /api/me row has viaTrustedProxy.

From your note on #846. The sentence for the two requests is in §10a, next to the statuses. The capability test asserts both: an upgrade request under a dead capability gets the 403, and GET /webview/<cap> without the trailing slash gets the 403 and no Location. Each is sent more often than the per-IP limit, and a correct password still signs in afterwards.

npm test: 17,408 tests pass (764 files, 13 skipped).

One more fix in the walkthrough, which I found while using it. The signed-in route of the Caddy example redirected every request without a proxy session to /oauth2/start. When the session ends while a Codeman page is open, its background requests (fetch, the live-update stream) follow that redirect on every retry. Each one replaces oauth2-proxy's CSRF cookie, and in my setup the real sign-in after a reload then ended on oauth2-proxy's "CSRF token mismatch" page. The example now answers a request with a non-navigation Sec-Fetch-Mode with 401. Page navigations, and clients that send no such header, are redirected as before. It also sets cookie_csrf_per_request = true for several tabs signing in at once. I ran it on Caddy 2.11.9 with oauth2-proxy 7.15.6: after the session ends, one reload signs in directly.

Not in this PR: once the session has ended, the open page ends up showing "No connection to the Codeman server" until the person reloads it. The walkthrough says so. I'd like to send a small frontend follow-up that detects the proxy's 401 and offers to sign in again, if you agree.

@Ark0N

Ark0N commented Nov 26, 2026

Copy link
Copy Markdown
Owner

Thanks for the second round, and for checking each new test by reverting its behaviour first. This PR lets multi-user mode sign people in through an authenticating reverse proxy on the same host. It is off by default and experimental.

Both blocking items are in. Your five base-path spellings and the mount named /webview are refused without a challenge. I also reverted six behaviours one at a time (the base-path strip, the last-login throttle, the 503 on an unreadable store, the refusal with the feature off, the realpath comparison for the secret file, and the reserved header names), and a test failed each time. typecheck, lint, format:check, check:frontend-syntax and the full suite pass here. The one failure I saw came from this machine's sandbox refusing a chown in an unrelated test.

There are two small things I will apply at merge time, so there is nothing for you to push:

  1. src/config/trusted-proxy.ts:271: the strip removes the headers from req.headers only. req.raw.rawHeaders and req.raw.headersDistinct still hold the secret (checked on Node 22.22). Nothing reads them today, but section 10a says the headers never travel further. I will drop the pairs from rawHeaders in the strip hook as well and add an assertion to the stripping test.
  2. CLAUDE.md:306: the Rate limit row names the QR and hook-secret buckets as separate. I will add the trusted-proxy secret's bucket to it.

You asked about a frontend follow-up that detects the proxy's 401 and offers to sign in again. That is a separate decision. It is still open, and this review does not answer it.

Once the unit test job is green, the next step is to merge with those two changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Multi-user mode: sign in through an authenticating reverse proxy (SSO)

2 participants