SIGN IN SIGN UP

fix(auth): extract identity even when auth is bypassed (#68)

When AUTH_TRUSTED_NETWORKS or AUTH_ENABLED=false short-circuits the
auth middleware, we were also losing the request's identity — every
bypassed call looked like a brand-new anonymous user.

That broke a real scenario users reported: deployment has CIDR bypass
on (interim fix for an earlier auth issue) AND now also enables
CODEAPI_JWT_*. LibreChat 0.8.5's bash_tool POSTs /exec with a valid
Bearer JWT, but the CIDR bypass fires first → middleware returns
early without ever parsing the JWT → request.state.user_id stays
unset → orchestrator falls through to "create new session" because
the cross-user isolation check needs a user_id to match against the
upload session → /mnt/data shows only code.sh and the uploaded file
is invisible.

Fix: in `_should_skip_auth`, both bypass branches now call a new
`_extract_best_effort_identity(request, scope)` helper that:

  1. Tries to verify the Bearer JWT if codeapi_jwt_enabled is on
     (so the JWT-signed identity is trusted), setting
     scope.state.user_id = claims.sub. A failed JWT in bypass mode
     does NOT 401 — the bypass already allowed the request; we just
     log and continue without an identity.
  2. Falls back to `User-Id` / `X-User-Id` header (unsigned, trusted
     because the bypass already trusted the boundary that delivered
     it).
  3. If neither is present, leaves user_id unset (genuine anonymous).

This preserves the original bypass semantics (no auth-key check)
while restoring the file-ownership graph for the legitimate identity
already present in the request.

5 new tests in test_security_middleware.py cover: JWT-bypass identity
extraction (CIDR), JWT-bypass extraction (AUTH_ENABLED=false), User-Id
header fallback during bypass, invalid JWT during bypass (anonymous
fallback, no 401), and the truly-anonymous case.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
A
Aron committed
b13fa9e9d5e7f7f8fe356b1ca6ee08db34efdfbd
Parent: afac333
Committed by GitHub <noreply@github.com> on 5/22/2026, 11:39:58 AM