🔒 fix: Secure Cookie Localhost Bypass and OpenID Token Selection in AuthService (#11782)

* 🔒 fix: Secure Cookie Localhost Bypass and OpenID Token Selection in AuthService

  Two independent bugs in `api/server/services/AuthService.js` cause complete
  authentication failure when using `OPENID_REUSE_TOKENS=true` with Microsoft
  Entra ID (or Auth0) on `http://localhost` with `NODE_ENV=production`:

  Bug 1: `secure: isProduction` prevents auth cookies on localhost

  PR #11518 introduced `shouldUseSecureCookie()` in `socialLogins.js` to handle
  the case where `NODE_ENV=production` but the server runs on `http://localhost`.
  However, `AuthService.js` was not updated — it still used `secure: isProduction`
  in 6 cookie locations across `setAuthTokens()` and `setOpenIDAuthTokens()`.

  The `token_provider` cookie being dropped is critical: without it,
  `requireJwtAuth` middleware defaults to the `jwt` strategy instead of
  `openidJwt`, causing all authenticated requests to return 401.

  Bug 2: `setOpenIDAuthTokens()` returns `access_token` instead of `id_token`

  The `openIdJwtStrategy` validates the Bearer token via JWKS. For Entra ID
  without `OPENID_AUDIENCE`, the `access_token` is a Microsoft Graph API token
  (opaque or signed for a different audience), which fails JWKS validation.

  The `id_token` is always a standard JWT signed by the IdP's JWKS keys with
  the app's `client_id` as audience — which is what the strategy expects.
  This is the same root cause as issue #8796 (Auth0 encrypted access tokens).

  Changes:

  - Consolidate `shouldUseSecureCookie()` into `packages/api/src/oauth/csrf.ts`
    as a shared, typed utility exported from `@librechat/api`, replacing the
    duplicate definitions in `AuthService.js` and `socialLogins.js`
  - Move `isProduction` check inside the function body so it is evaluated at
    call time rather than module load time
  - Fix `packages/api/src/oauth/csrf.ts` which also used bare
    `secure: isProduction` for CSRF and session cookies (same localhost bug)
  - Return `tokenset.id_token || tokenset.access_token` from
    `setOpenIDAuthTokens()` so JWKS validation works with standard OIDC
    providers; falls back to `access_token` for backward compatibility
  - Add 15 tests for `shouldUseSecureCookie()` covering production/dev modes,
    localhost variants, edge cases, and a documented IPv6 bracket limitation
  - Add 13 tests for `setOpenIDAuthTokens()` covering token selection,
    session storage, cookie secure flag delegation, and edge cases

  Refs: #8796, #11518, #11236, #9931

* chore: Adjust Import Order and Type Definitions in AgentPanel Component

- Reordered imports in `AgentPanel.tsx` for better organization and clarity.
- Updated type imports to ensure proper usage of `FieldNamesMarkedBoolean` and `TranslationKeys`.
- Removed redundant imports to streamline the codebase.
This commit is contained in:
Danny Avila 2026-02-13 10:35:51 -05:00 committed by GitHub
parent 3888dfa489
commit 2e42378b16
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 431 additions and 50 deletions

View file

@ -0,0 +1,99 @@
import { shouldUseSecureCookie } from './csrf';
describe('shouldUseSecureCookie', () => {
const originalEnv = process.env;
beforeEach(() => {
process.env = { ...originalEnv };
});
afterAll(() => {
process.env = originalEnv;
});
it('should return true in production with a non-localhost domain', () => {
process.env.NODE_ENV = 'production';
process.env.DOMAIN_SERVER = 'https://myapp.example.com';
expect(shouldUseSecureCookie()).toBe(true);
});
it('should return false in development regardless of domain', () => {
process.env.NODE_ENV = 'development';
process.env.DOMAIN_SERVER = 'https://myapp.example.com';
expect(shouldUseSecureCookie()).toBe(false);
});
it('should return false when NODE_ENV is not set', () => {
delete process.env.NODE_ENV;
process.env.DOMAIN_SERVER = 'https://myapp.example.com';
expect(shouldUseSecureCookie()).toBe(false);
});
describe('localhost detection in production', () => {
beforeEach(() => {
process.env.NODE_ENV = 'production';
});
it('should return false for http://localhost:3080', () => {
process.env.DOMAIN_SERVER = 'http://localhost:3080';
expect(shouldUseSecureCookie()).toBe(false);
});
it('should return false for https://localhost:3080', () => {
process.env.DOMAIN_SERVER = 'https://localhost:3080';
expect(shouldUseSecureCookie()).toBe(false);
});
it('should return false for http://localhost (no port)', () => {
process.env.DOMAIN_SERVER = 'http://localhost';
expect(shouldUseSecureCookie()).toBe(false);
});
it('should return false for http://127.0.0.1:3080', () => {
process.env.DOMAIN_SERVER = 'http://127.0.0.1:3080';
expect(shouldUseSecureCookie()).toBe(false);
});
it('should return true for http://[::1]:3080 (IPv6 loopback — not detected due to URL bracket parsing)', () => {
// Known limitation: new URL('http://[::1]:3080').hostname returns '[::1]' (with brackets)
// but the check compares against '::1' (without brackets). IPv6 localhost is rare in practice.
process.env.DOMAIN_SERVER = 'http://[::1]:3080';
expect(shouldUseSecureCookie()).toBe(true);
});
it('should return false for subdomain of localhost', () => {
process.env.DOMAIN_SERVER = 'http://app.localhost:3080';
expect(shouldUseSecureCookie()).toBe(false);
});
it('should return true for a domain containing "localhost" as a substring but not as hostname', () => {
process.env.DOMAIN_SERVER = 'https://notlocalhost.example.com';
expect(shouldUseSecureCookie()).toBe(true);
});
it('should return true for a regular production domain', () => {
process.env.DOMAIN_SERVER = 'https://chat.example.com';
expect(shouldUseSecureCookie()).toBe(true);
});
it('should return true when DOMAIN_SERVER is empty (conservative default)', () => {
process.env.DOMAIN_SERVER = '';
expect(shouldUseSecureCookie()).toBe(true);
});
it('should return true when DOMAIN_SERVER is not set (conservative default)', () => {
delete process.env.DOMAIN_SERVER;
expect(shouldUseSecureCookie()).toBe(true);
});
it('should handle DOMAIN_SERVER without protocol prefix', () => {
process.env.DOMAIN_SERVER = 'localhost:3080';
expect(shouldUseSecureCookie()).toBe(false);
});
it('should handle case-insensitive hostnames', () => {
process.env.DOMAIN_SERVER = 'http://LOCALHOST:3080';
expect(shouldUseSecureCookie()).toBe(false);
});
});
});

View file

@ -8,7 +8,37 @@ export const OAUTH_SESSION_COOKIE = 'oauth_session';
export const OAUTH_SESSION_MAX_AGE = 24 * 60 * 60 * 1000;
export const OAUTH_SESSION_COOKIE_PATH = '/api';
const isProduction = process.env.NODE_ENV === 'production';
/**
* Determines if secure cookies should be used.
* Returns `true` in production unless the server is running on localhost (HTTP).
* This allows cookies to work on `http://localhost` during local development
* even when `NODE_ENV=production` (common in Docker Compose setups).
*/
export function shouldUseSecureCookie(): boolean {
const isProduction = process.env.NODE_ENV === 'production';
const domainServer = process.env.DOMAIN_SERVER || '';
let hostname = '';
if (domainServer) {
try {
const normalized = /^https?:\/\//i.test(domainServer)
? domainServer
: `http://${domainServer}`;
const url = new URL(normalized);
hostname = (url.hostname || '').toLowerCase();
} catch {
hostname = domainServer.toLowerCase();
}
}
const isLocalhost =
hostname === 'localhost' ||
hostname === '127.0.0.1' ||
hostname === '::1' ||
hostname.endsWith('.localhost');
return isProduction && !isLocalhost;
}
/** Generates an HMAC-based token for OAuth CSRF protection */
export function generateOAuthCsrfToken(flowId: string, secret?: string): string {
@ -23,7 +53,7 @@ export function generateOAuthCsrfToken(flowId: string, secret?: string): string
export function setOAuthCsrfCookie(res: Response, flowId: string, cookiePath: string): void {
res.cookie(OAUTH_CSRF_COOKIE, generateOAuthCsrfToken(flowId), {
httpOnly: true,
secure: isProduction,
secure: shouldUseSecureCookie(),
sameSite: 'lax',
maxAge: OAUTH_CSRF_MAX_AGE,
path: cookiePath,
@ -68,7 +98,7 @@ export function setOAuthSession(req: Request, res: Response, next: NextFunction)
export function setOAuthSessionCookie(res: Response, userId: string): void {
res.cookie(OAUTH_SESSION_COOKIE, generateOAuthCsrfToken(userId), {
httpOnly: true,
secure: isProduction,
secure: shouldUseSecureCookie(),
sameSite: 'lax',
maxAge: OAUTH_SESSION_MAX_AGE,
path: OAUTH_SESSION_COOKIE_PATH,