LibreChat/api/strategies/openIdJwtStrategy.js

115 lines
4 KiB
JavaScript
Raw Normal View History

🆔 feat: Add OpenID Connect Federated Provider Token Support (#9931) * feat: Add OpenID Connect federated provider token support Implements support for passing federated provider tokens (Cognito, Azure AD, Auth0) as variables in LibreChat's librechat.yaml configuration for both custom endpoints and MCP servers. Features: - New LIBRECHAT_OPENID_* template variables for federated provider tokens - JWT claims parsing from ID tokens without verification (for claim extraction) - Token validation with expiration checking - Support for multiple token storage locations (federatedTokens, openidTokens) - Integration with existing template variable system - Comprehensive test suite with Cognito-specific scenarios - Provider-agnostic design supporting Cognito, Azure AD, Auth0, etc. Security: - Server-side only token processing - Automatic token expiration validation - Graceful fallbacks for missing/invalid tokens - No client-side token exposure 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: Add federated token propagation to OIDC authentication strategies Adds federatedTokens object to user during authentication to enable federated provider token template variables in LibreChat configuration. Changes: - OpenID JWT Strategy: Extract raw JWT from Authorization header and attach as federatedTokens.access_token to enable {{LIBRECHAT_OPENID_TOKEN}} placeholder resolution - OpenID Strategy: Attach tokenset tokens as federatedTokens object to standardize token access across both authentication strategies This enables proper token propagation for custom endpoints and MCP servers that require federated provider tokens for authorization. Resolves missing token issue reported by @ramden in PR #9931 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Denis Ramic <denis.ramic@nfon.com> Co-Authored-By: Claude <noreply@anthropic.com> * test: Add federatedTokens validation tests for OIDC strategies Adds comprehensive test coverage for the federated token propagation feature implemented in the authentication strategies. Tests added: - Verify federatedTokens object is attached to user with correct structure (access_token, refresh_token, expires_at) - Verify both tokenset and federatedTokens are present in user object - Ensure tokens from OIDC provider are correctly propagated Also fixes existing test suite by adding missing mocks: - isEmailDomainAllowed function mock - findOpenIDUser function mock These tests validate the fix from commit 5874ba29f that enables {{LIBRECHAT_OPENID_TOKEN}} template variable functionality. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * docs: Remove implementation documentation file The PR description already contains all necessary implementation details. This documentation file is redundant and was requested to be removed. * fix: skip s256 check * fix(openid): handle missing refresh token in Cognito token refresh response When OPENID_REUSE_TOKENS=true, the token refresh flow was failing because Cognito (and most OAuth providers) don't return a new refresh token in the refresh grant response - they only return new access and ID tokens. Changes: - Modified setOpenIDAuthTokens() to accept optional existingRefreshToken parameter - Updated validation to only require access_token (refresh_token now optional) - Added logic to reuse existing refresh token when not provided in tokenset - Updated refreshController to pass original refresh token as fallback - Added comments explaining standard OAuth 2.0 refresh token behavior This fixes the "Token is not present. User is not authenticated." error that occurred during silent token refresh with Cognito as the OpenID provider. Fixes: Authentication loop with OPENID_REUSE_TOKENS=true and AWS Cognito * fix(openid): extract refresh token from cookies for template variable replacement When OPENID_REUSE_TOKENS=true, the openIdJwtStrategy populates user.federatedTokens to enable template variable replacement (e.g., {{LIBRECHAT_OPENID_ACCESS_TOKEN}}). However, the refresh_token field was incorrectly sourced from payload.refresh_token, which is always undefined because: 1. JWTs don't contain refresh tokens in their payload 2. The JWT itself IS the access token 3. Refresh tokens are separate opaque tokens stored in HTTP-only cookies This caused extractOpenIDTokenInfo() to receive incomplete federatedTokens, resulting in template variables remaining unreplaced in headers. **Root Cause:** - Line 90: `refresh_token: payload.refresh_token` (always undefined) - JWTs only contain access token data in their claims - Refresh tokens are separate, stored securely in cookies **Solution:** - Import `cookie` module to parse cookies from request - Extract refresh token from `refreshToken` cookie - Populate federatedTokens with both access token (JWT) and refresh token (from cookie) **Impact:** - Template variables like {{LIBRECHAT_OPENID_ACCESS_TOKEN}} now work correctly - Headers in librechat.yaml are properly replaced with actual tokens - MCP server authentication with federated tokens now functional **Technical Details:** - passReqToCallback=true in JWT strategy provides req object access - Refresh token extracted via cookies.parse(req.headers.cookie).refreshToken - Falls back gracefully if cookie header or refreshToken is missing 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: re-resolve headers on each request to pick up fresh federatedTokens - OpenAIClient now re-resolves headers in chatCompletion() before each API call - This ensures template variables like {{LIBRECHAT_OPENID_TOKEN}} are replaced with actual token values from req.user.federatedTokens - initialize.js now stores original template headers instead of pre-resolved ones - Fixes template variable replacement when OPENID_REUSE_TOKENS=true The issue was that headers were only resolved once during client initialization, before openIdJwtStrategy had populated user.federatedTokens. Now headers are re-resolved on every request with the current user's fresh tokens. * debug: add logging to track header resolution in OpenAIClient * debug: log tokenset structure after refresh to diagnose missing access_token * fix: set federatedTokens on user object after OAuth refresh - After successful OAuth token refresh, the user object was not being updated with federatedTokens - This caused template variable resolution to fail on subsequent requests - Now sets user.federatedTokens with access_token, id_token, refresh_token and expires_at from the refreshed tokenset - Fixes template variables like {{LIBRECHAT_OPENID_TOKEN}} not being replaced after token refresh - Related to PR #9931 (OpenID federated token support) * fix(openid): pass user object through agent chain for template variable resolution Root cause: buildAgentContext in agents/run.ts called resolveHeaders without the user parameter, preventing OpenID federated token template variables from being resolved in agent runtime parameters. Changes: - packages/api/src/agents/run.ts: Add user parameter to createRun signature - packages/api/src/agents/run.ts: Pass user to resolveHeaders in buildAgentContext - api/server/controllers/agents/client.js: Pass user when calling createRun - api/server/services/Endpoints/bedrock/options.js: Add resolveHeaders call with debug logging - api/server/services/Endpoints/custom/initialize.js: Add debug logging - packages/api/src/utils/env.ts: Add comprehensive debug logging and stack traces - packages/api/src/utils/oidc.ts: Fix eslint errors (unused type, explicit any) This ensures template variables like {{LIBRECHAT_OPENID_TOKEN}} and {{LIBRECHAT_USER_OPENIDID}} are properly resolved in both custom endpoint headers and Bedrock AgentCore runtime parameters. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: remove debug logging from OpenID token template feature Removed excessive debug logging that was added during development to make the PR more suitable for upstream review: - Removed 7 debug statements from OpenAIClient.js - Removed all console.log statements from packages/api/src/utils/env.ts - Removed debug logging from bedrock/options.js - Removed debug logging from custom/initialize.js - Removed debug statement from AuthController.js This reduces the changeset by ~50 lines while maintaining full functionality of the OpenID federated token template variable feature. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * test(openid): add comprehensive unit tests for template variable substitution - Add 34 unit tests for OIDC token utilities (oidc.spec.ts) - Test coverage for token extraction, validation, and placeholder processing - Integration tests for full OpenID token flow - All tests pass with comprehensive edge case coverage 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * test: fix OpenID federated tokens test failures - Add serverMetadata() mock to openid-client mock configuration * Fixes TypeError in openIdJwtStrategy.js where serverMetadata() was being called * Mock now returns jwks_uri and end_session_endpoint as expected by the code - Update outdated initialize.spec.js test * Remove test expecting resolveHeaders call during initialization * Header resolution was refactored to be deferred until LLM request time * Update test to verify options are returned correctly with useLegacyContent flag Fixes #9931 CI failures for backend unit tests 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * chore: fix package-lock.json conflict * chore: sync package-log with upstream * chore: cleanup * fix: use createSafeUser * fix: fix createSafeUser signature * chore: remove comments * chore: purge comments * fix: update Jest testPathPattern to testPathPatterns for Jest 30+ compatibility --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Denis Ramic <denis.ramic@nfon.com> Co-authored-by: kristjanaapro <kristjana@apro.is> chore: import order and add back JSDoc for OpenID JWT callback
2025-11-21 14:44:52 +00:00
const cookies = require('cookie');
const jwksRsa = require('jwks-rsa');
const { logger } = require('@librechat/data-schemas');
const { HttpsProxyAgent } = require('https-proxy-agent');
const { SystemRoles } = require('librechat-data-provider');
*️⃣ feat: Reuse OpenID Auth Tokens (#7397) * feat: integrate OpenID Connect support with token reuse - Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality. - Implemented OpenID token refresh logic in `AuthController`. - Enhanced `LogoutController` to handle OpenID logout and session termination. - Updated JWT authentication middleware to support OpenID token provider. - Modified OAuth routes to accommodate OpenID authentication and token management. - Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies. - Upgraded OpenID strategy with user info fetching and token exchange protocol. - Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens. - Added caching mechanism for exchanged OpenID tokens. - Updated configuration to include OpenID exchanged tokens cache key. - updated .env.example to include the new env variables needed for the feature. * fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables * fix: update Jest configuration and tests for OpenID strategy integration * fix: update OpenID strategy to include callback URL in setup * fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront) * fix: fixed code formatting * Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests * fix eslint errors: Format mock file openid-client. * ✨ feat: Add PKCE support for OpenID and default handling in strategy setup --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-22 14:19:24 +02:00
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
const { isEnabled, findOpenIDUser } = require('@librechat/api');
*️⃣ feat: Reuse OpenID Auth Tokens (#7397) * feat: integrate OpenID Connect support with token reuse - Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality. - Implemented OpenID token refresh logic in `AuthController`. - Enhanced `LogoutController` to handle OpenID logout and session termination. - Updated JWT authentication middleware to support OpenID token provider. - Modified OAuth routes to accommodate OpenID authentication and token management. - Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies. - Upgraded OpenID strategy with user info fetching and token exchange protocol. - Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens. - Added caching mechanism for exchanged OpenID tokens. - Updated configuration to include OpenID exchanged tokens cache key. - updated .env.example to include the new env variables needed for the feature. * fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables * fix: update Jest configuration and tests for OpenID strategy integration * fix: update OpenID strategy to include callback URL in setup * fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront) * fix: fixed code formatting * Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests * fix eslint errors: Format mock file openid-client. * ✨ feat: Add PKCE support for OpenID and default handling in strategy setup --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-22 14:19:24 +02:00
const { updateUser, findUser } = require('~/models');
*️⃣ feat: Reuse OpenID Auth Tokens (#7397) * feat: integrate OpenID Connect support with token reuse - Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality. - Implemented OpenID token refresh logic in `AuthController`. - Enhanced `LogoutController` to handle OpenID logout and session termination. - Updated JWT authentication middleware to support OpenID token provider. - Modified OAuth routes to accommodate OpenID authentication and token management. - Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies. - Upgraded OpenID strategy with user info fetching and token exchange protocol. - Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens. - Added caching mechanism for exchanged OpenID tokens. - Updated configuration to include OpenID exchanged tokens cache key. - updated .env.example to include the new env variables needed for the feature. * fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables * fix: update Jest configuration and tests for OpenID strategy integration * fix: update OpenID strategy to include callback URL in setup * fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront) * fix: fixed code formatting * Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests * fix eslint errors: Format mock file openid-client. * ✨ feat: Add PKCE support for OpenID and default handling in strategy setup --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-22 14:19:24 +02:00
/**
* @function openIdJwtLogin
* @param {import('openid-client').Configuration} openIdConfig - Configuration object for the JWT strategy.
* @returns {JwtStrategy}
* @description This function creates a JWT strategy for OpenID authentication.
* It uses the jwks-rsa library to retrieve the signing key from a JWKS endpoint.
* The strategy extracts the JWT from the Authorization header as a Bearer token.
* The JWT is then verified using the signing key, and the user is retrieved from the database.
*
* Includes email fallback mechanism:
* 1. Primary lookup: Search user by openidId (sub claim)
* 2. Fallback lookup: If not found, search by email claim
* 3. User migration: If found by email without openidId, migrate the user by adding openidId
* 4. Provider validation: Ensures users registered with other providers cannot use OpenID
*
* This enables seamless migration for existing users when SharePoint integration is enabled.
*️⃣ feat: Reuse OpenID Auth Tokens (#7397) * feat: integrate OpenID Connect support with token reuse - Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality. - Implemented OpenID token refresh logic in `AuthController`. - Enhanced `LogoutController` to handle OpenID logout and session termination. - Updated JWT authentication middleware to support OpenID token provider. - Modified OAuth routes to accommodate OpenID authentication and token management. - Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies. - Upgraded OpenID strategy with user info fetching and token exchange protocol. - Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens. - Added caching mechanism for exchanged OpenID tokens. - Updated configuration to include OpenID exchanged tokens cache key. - updated .env.example to include the new env variables needed for the feature. * fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables * fix: update Jest configuration and tests for OpenID strategy integration * fix: update OpenID strategy to include callback URL in setup * fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront) * fix: fixed code formatting * Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests * fix eslint errors: Format mock file openid-client. * ✨ feat: Add PKCE support for OpenID and default handling in strategy setup --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-22 14:19:24 +02:00
*/
const openIdJwtLogin = (openIdConfig) => {
let jwksRsaOptions = {
cache: isEnabled(process.env.OPENID_JWKS_URL_CACHE_ENABLED) || true,
cacheMaxAge: process.env.OPENID_JWKS_URL_CACHE_TIME
? eval(process.env.OPENID_JWKS_URL_CACHE_TIME)
: 60000,
jwksUri: openIdConfig.serverMetadata().jwks_uri,
};
if (process.env.PROXY) {
jwksRsaOptions.requestAgent = new HttpsProxyAgent(process.env.PROXY);
}
return new JwtStrategy(
*️⃣ feat: Reuse OpenID Auth Tokens (#7397) * feat: integrate OpenID Connect support with token reuse - Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality. - Implemented OpenID token refresh logic in `AuthController`. - Enhanced `LogoutController` to handle OpenID logout and session termination. - Updated JWT authentication middleware to support OpenID token provider. - Modified OAuth routes to accommodate OpenID authentication and token management. - Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies. - Upgraded OpenID strategy with user info fetching and token exchange protocol. - Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens. - Added caching mechanism for exchanged OpenID tokens. - Updated configuration to include OpenID exchanged tokens cache key. - updated .env.example to include the new env variables needed for the feature. * fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables * fix: update Jest configuration and tests for OpenID strategy integration * fix: update OpenID strategy to include callback URL in setup * fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront) * fix: fixed code formatting * Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests * fix eslint errors: Format mock file openid-client. * ✨ feat: Add PKCE support for OpenID and default handling in strategy setup --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-22 14:19:24 +02:00
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKeyProvider: jwksRsa.passportJwtSecret(jwksRsaOptions),
🆔 feat: Add OpenID Connect Federated Provider Token Support (#9931) * feat: Add OpenID Connect federated provider token support Implements support for passing federated provider tokens (Cognito, Azure AD, Auth0) as variables in LibreChat's librechat.yaml configuration for both custom endpoints and MCP servers. Features: - New LIBRECHAT_OPENID_* template variables for federated provider tokens - JWT claims parsing from ID tokens without verification (for claim extraction) - Token validation with expiration checking - Support for multiple token storage locations (federatedTokens, openidTokens) - Integration with existing template variable system - Comprehensive test suite with Cognito-specific scenarios - Provider-agnostic design supporting Cognito, Azure AD, Auth0, etc. Security: - Server-side only token processing - Automatic token expiration validation - Graceful fallbacks for missing/invalid tokens - No client-side token exposure 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: Add federated token propagation to OIDC authentication strategies Adds federatedTokens object to user during authentication to enable federated provider token template variables in LibreChat configuration. Changes: - OpenID JWT Strategy: Extract raw JWT from Authorization header and attach as federatedTokens.access_token to enable {{LIBRECHAT_OPENID_TOKEN}} placeholder resolution - OpenID Strategy: Attach tokenset tokens as federatedTokens object to standardize token access across both authentication strategies This enables proper token propagation for custom endpoints and MCP servers that require federated provider tokens for authorization. Resolves missing token issue reported by @ramden in PR #9931 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Denis Ramic <denis.ramic@nfon.com> Co-Authored-By: Claude <noreply@anthropic.com> * test: Add federatedTokens validation tests for OIDC strategies Adds comprehensive test coverage for the federated token propagation feature implemented in the authentication strategies. Tests added: - Verify federatedTokens object is attached to user with correct structure (access_token, refresh_token, expires_at) - Verify both tokenset and federatedTokens are present in user object - Ensure tokens from OIDC provider are correctly propagated Also fixes existing test suite by adding missing mocks: - isEmailDomainAllowed function mock - findOpenIDUser function mock These tests validate the fix from commit 5874ba29f that enables {{LIBRECHAT_OPENID_TOKEN}} template variable functionality. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * docs: Remove implementation documentation file The PR description already contains all necessary implementation details. This documentation file is redundant and was requested to be removed. * fix: skip s256 check * fix(openid): handle missing refresh token in Cognito token refresh response When OPENID_REUSE_TOKENS=true, the token refresh flow was failing because Cognito (and most OAuth providers) don't return a new refresh token in the refresh grant response - they only return new access and ID tokens. Changes: - Modified setOpenIDAuthTokens() to accept optional existingRefreshToken parameter - Updated validation to only require access_token (refresh_token now optional) - Added logic to reuse existing refresh token when not provided in tokenset - Updated refreshController to pass original refresh token as fallback - Added comments explaining standard OAuth 2.0 refresh token behavior This fixes the "Token is not present. User is not authenticated." error that occurred during silent token refresh with Cognito as the OpenID provider. Fixes: Authentication loop with OPENID_REUSE_TOKENS=true and AWS Cognito * fix(openid): extract refresh token from cookies for template variable replacement When OPENID_REUSE_TOKENS=true, the openIdJwtStrategy populates user.federatedTokens to enable template variable replacement (e.g., {{LIBRECHAT_OPENID_ACCESS_TOKEN}}). However, the refresh_token field was incorrectly sourced from payload.refresh_token, which is always undefined because: 1. JWTs don't contain refresh tokens in their payload 2. The JWT itself IS the access token 3. Refresh tokens are separate opaque tokens stored in HTTP-only cookies This caused extractOpenIDTokenInfo() to receive incomplete federatedTokens, resulting in template variables remaining unreplaced in headers. **Root Cause:** - Line 90: `refresh_token: payload.refresh_token` (always undefined) - JWTs only contain access token data in their claims - Refresh tokens are separate, stored securely in cookies **Solution:** - Import `cookie` module to parse cookies from request - Extract refresh token from `refreshToken` cookie - Populate federatedTokens with both access token (JWT) and refresh token (from cookie) **Impact:** - Template variables like {{LIBRECHAT_OPENID_ACCESS_TOKEN}} now work correctly - Headers in librechat.yaml are properly replaced with actual tokens - MCP server authentication with federated tokens now functional **Technical Details:** - passReqToCallback=true in JWT strategy provides req object access - Refresh token extracted via cookies.parse(req.headers.cookie).refreshToken - Falls back gracefully if cookie header or refreshToken is missing 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: re-resolve headers on each request to pick up fresh federatedTokens - OpenAIClient now re-resolves headers in chatCompletion() before each API call - This ensures template variables like {{LIBRECHAT_OPENID_TOKEN}} are replaced with actual token values from req.user.federatedTokens - initialize.js now stores original template headers instead of pre-resolved ones - Fixes template variable replacement when OPENID_REUSE_TOKENS=true The issue was that headers were only resolved once during client initialization, before openIdJwtStrategy had populated user.federatedTokens. Now headers are re-resolved on every request with the current user's fresh tokens. * debug: add logging to track header resolution in OpenAIClient * debug: log tokenset structure after refresh to diagnose missing access_token * fix: set federatedTokens on user object after OAuth refresh - After successful OAuth token refresh, the user object was not being updated with federatedTokens - This caused template variable resolution to fail on subsequent requests - Now sets user.federatedTokens with access_token, id_token, refresh_token and expires_at from the refreshed tokenset - Fixes template variables like {{LIBRECHAT_OPENID_TOKEN}} not being replaced after token refresh - Related to PR #9931 (OpenID federated token support) * fix(openid): pass user object through agent chain for template variable resolution Root cause: buildAgentContext in agents/run.ts called resolveHeaders without the user parameter, preventing OpenID federated token template variables from being resolved in agent runtime parameters. Changes: - packages/api/src/agents/run.ts: Add user parameter to createRun signature - packages/api/src/agents/run.ts: Pass user to resolveHeaders in buildAgentContext - api/server/controllers/agents/client.js: Pass user when calling createRun - api/server/services/Endpoints/bedrock/options.js: Add resolveHeaders call with debug logging - api/server/services/Endpoints/custom/initialize.js: Add debug logging - packages/api/src/utils/env.ts: Add comprehensive debug logging and stack traces - packages/api/src/utils/oidc.ts: Fix eslint errors (unused type, explicit any) This ensures template variables like {{LIBRECHAT_OPENID_TOKEN}} and {{LIBRECHAT_USER_OPENIDID}} are properly resolved in both custom endpoint headers and Bedrock AgentCore runtime parameters. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: remove debug logging from OpenID token template feature Removed excessive debug logging that was added during development to make the PR more suitable for upstream review: - Removed 7 debug statements from OpenAIClient.js - Removed all console.log statements from packages/api/src/utils/env.ts - Removed debug logging from bedrock/options.js - Removed debug logging from custom/initialize.js - Removed debug statement from AuthController.js This reduces the changeset by ~50 lines while maintaining full functionality of the OpenID federated token template variable feature. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * test(openid): add comprehensive unit tests for template variable substitution - Add 34 unit tests for OIDC token utilities (oidc.spec.ts) - Test coverage for token extraction, validation, and placeholder processing - Integration tests for full OpenID token flow - All tests pass with comprehensive edge case coverage 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * test: fix OpenID federated tokens test failures - Add serverMetadata() mock to openid-client mock configuration * Fixes TypeError in openIdJwtStrategy.js where serverMetadata() was being called * Mock now returns jwks_uri and end_session_endpoint as expected by the code - Update outdated initialize.spec.js test * Remove test expecting resolveHeaders call during initialization * Header resolution was refactored to be deferred until LLM request time * Update test to verify options are returned correctly with useLegacyContent flag Fixes #9931 CI failures for backend unit tests 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * chore: fix package-lock.json conflict * chore: sync package-log with upstream * chore: cleanup * fix: use createSafeUser * fix: fix createSafeUser signature * chore: remove comments * chore: purge comments * fix: update Jest testPathPattern to testPathPatterns for Jest 30+ compatibility --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Denis Ramic <denis.ramic@nfon.com> Co-authored-by: kristjanaapro <kristjana@apro.is> chore: import order and add back JSDoc for OpenID JWT callback
2025-11-21 14:44:52 +00:00
passReqToCallback: true,
*️⃣ feat: Reuse OpenID Auth Tokens (#7397) * feat: integrate OpenID Connect support with token reuse - Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality. - Implemented OpenID token refresh logic in `AuthController`. - Enhanced `LogoutController` to handle OpenID logout and session termination. - Updated JWT authentication middleware to support OpenID token provider. - Modified OAuth routes to accommodate OpenID authentication and token management. - Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies. - Upgraded OpenID strategy with user info fetching and token exchange protocol. - Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens. - Added caching mechanism for exchanged OpenID tokens. - Updated configuration to include OpenID exchanged tokens cache key. - updated .env.example to include the new env variables needed for the feature. * fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables * fix: update Jest configuration and tests for OpenID strategy integration * fix: update OpenID strategy to include callback URL in setup * fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront) * fix: fixed code formatting * Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests * fix eslint errors: Format mock file openid-client. * ✨ feat: Add PKCE support for OpenID and default handling in strategy setup --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-22 14:19:24 +02:00
},
/**
🆔 feat: Add OpenID Connect Federated Provider Token Support (#9931) * feat: Add OpenID Connect federated provider token support Implements support for passing federated provider tokens (Cognito, Azure AD, Auth0) as variables in LibreChat's librechat.yaml configuration for both custom endpoints and MCP servers. Features: - New LIBRECHAT_OPENID_* template variables for federated provider tokens - JWT claims parsing from ID tokens without verification (for claim extraction) - Token validation with expiration checking - Support for multiple token storage locations (federatedTokens, openidTokens) - Integration with existing template variable system - Comprehensive test suite with Cognito-specific scenarios - Provider-agnostic design supporting Cognito, Azure AD, Auth0, etc. Security: - Server-side only token processing - Automatic token expiration validation - Graceful fallbacks for missing/invalid tokens - No client-side token exposure 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: Add federated token propagation to OIDC authentication strategies Adds federatedTokens object to user during authentication to enable federated provider token template variables in LibreChat configuration. Changes: - OpenID JWT Strategy: Extract raw JWT from Authorization header and attach as federatedTokens.access_token to enable {{LIBRECHAT_OPENID_TOKEN}} placeholder resolution - OpenID Strategy: Attach tokenset tokens as federatedTokens object to standardize token access across both authentication strategies This enables proper token propagation for custom endpoints and MCP servers that require federated provider tokens for authorization. Resolves missing token issue reported by @ramden in PR #9931 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Denis Ramic <denis.ramic@nfon.com> Co-Authored-By: Claude <noreply@anthropic.com> * test: Add federatedTokens validation tests for OIDC strategies Adds comprehensive test coverage for the federated token propagation feature implemented in the authentication strategies. Tests added: - Verify federatedTokens object is attached to user with correct structure (access_token, refresh_token, expires_at) - Verify both tokenset and federatedTokens are present in user object - Ensure tokens from OIDC provider are correctly propagated Also fixes existing test suite by adding missing mocks: - isEmailDomainAllowed function mock - findOpenIDUser function mock These tests validate the fix from commit 5874ba29f that enables {{LIBRECHAT_OPENID_TOKEN}} template variable functionality. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * docs: Remove implementation documentation file The PR description already contains all necessary implementation details. This documentation file is redundant and was requested to be removed. * fix: skip s256 check * fix(openid): handle missing refresh token in Cognito token refresh response When OPENID_REUSE_TOKENS=true, the token refresh flow was failing because Cognito (and most OAuth providers) don't return a new refresh token in the refresh grant response - they only return new access and ID tokens. Changes: - Modified setOpenIDAuthTokens() to accept optional existingRefreshToken parameter - Updated validation to only require access_token (refresh_token now optional) - Added logic to reuse existing refresh token when not provided in tokenset - Updated refreshController to pass original refresh token as fallback - Added comments explaining standard OAuth 2.0 refresh token behavior This fixes the "Token is not present. User is not authenticated." error that occurred during silent token refresh with Cognito as the OpenID provider. Fixes: Authentication loop with OPENID_REUSE_TOKENS=true and AWS Cognito * fix(openid): extract refresh token from cookies for template variable replacement When OPENID_REUSE_TOKENS=true, the openIdJwtStrategy populates user.federatedTokens to enable template variable replacement (e.g., {{LIBRECHAT_OPENID_ACCESS_TOKEN}}). However, the refresh_token field was incorrectly sourced from payload.refresh_token, which is always undefined because: 1. JWTs don't contain refresh tokens in their payload 2. The JWT itself IS the access token 3. Refresh tokens are separate opaque tokens stored in HTTP-only cookies This caused extractOpenIDTokenInfo() to receive incomplete federatedTokens, resulting in template variables remaining unreplaced in headers. **Root Cause:** - Line 90: `refresh_token: payload.refresh_token` (always undefined) - JWTs only contain access token data in their claims - Refresh tokens are separate, stored securely in cookies **Solution:** - Import `cookie` module to parse cookies from request - Extract refresh token from `refreshToken` cookie - Populate federatedTokens with both access token (JWT) and refresh token (from cookie) **Impact:** - Template variables like {{LIBRECHAT_OPENID_ACCESS_TOKEN}} now work correctly - Headers in librechat.yaml are properly replaced with actual tokens - MCP server authentication with federated tokens now functional **Technical Details:** - passReqToCallback=true in JWT strategy provides req object access - Refresh token extracted via cookies.parse(req.headers.cookie).refreshToken - Falls back gracefully if cookie header or refreshToken is missing 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: re-resolve headers on each request to pick up fresh federatedTokens - OpenAIClient now re-resolves headers in chatCompletion() before each API call - This ensures template variables like {{LIBRECHAT_OPENID_TOKEN}} are replaced with actual token values from req.user.federatedTokens - initialize.js now stores original template headers instead of pre-resolved ones - Fixes template variable replacement when OPENID_REUSE_TOKENS=true The issue was that headers were only resolved once during client initialization, before openIdJwtStrategy had populated user.federatedTokens. Now headers are re-resolved on every request with the current user's fresh tokens. * debug: add logging to track header resolution in OpenAIClient * debug: log tokenset structure after refresh to diagnose missing access_token * fix: set federatedTokens on user object after OAuth refresh - After successful OAuth token refresh, the user object was not being updated with federatedTokens - This caused template variable resolution to fail on subsequent requests - Now sets user.federatedTokens with access_token, id_token, refresh_token and expires_at from the refreshed tokenset - Fixes template variables like {{LIBRECHAT_OPENID_TOKEN}} not being replaced after token refresh - Related to PR #9931 (OpenID federated token support) * fix(openid): pass user object through agent chain for template variable resolution Root cause: buildAgentContext in agents/run.ts called resolveHeaders without the user parameter, preventing OpenID federated token template variables from being resolved in agent runtime parameters. Changes: - packages/api/src/agents/run.ts: Add user parameter to createRun signature - packages/api/src/agents/run.ts: Pass user to resolveHeaders in buildAgentContext - api/server/controllers/agents/client.js: Pass user when calling createRun - api/server/services/Endpoints/bedrock/options.js: Add resolveHeaders call with debug logging - api/server/services/Endpoints/custom/initialize.js: Add debug logging - packages/api/src/utils/env.ts: Add comprehensive debug logging and stack traces - packages/api/src/utils/oidc.ts: Fix eslint errors (unused type, explicit any) This ensures template variables like {{LIBRECHAT_OPENID_TOKEN}} and {{LIBRECHAT_USER_OPENIDID}} are properly resolved in both custom endpoint headers and Bedrock AgentCore runtime parameters. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: remove debug logging from OpenID token template feature Removed excessive debug logging that was added during development to make the PR more suitable for upstream review: - Removed 7 debug statements from OpenAIClient.js - Removed all console.log statements from packages/api/src/utils/env.ts - Removed debug logging from bedrock/options.js - Removed debug logging from custom/initialize.js - Removed debug statement from AuthController.js This reduces the changeset by ~50 lines while maintaining full functionality of the OpenID federated token template variable feature. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * test(openid): add comprehensive unit tests for template variable substitution - Add 34 unit tests for OIDC token utilities (oidc.spec.ts) - Test coverage for token extraction, validation, and placeholder processing - Integration tests for full OpenID token flow - All tests pass with comprehensive edge case coverage 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * test: fix OpenID federated tokens test failures - Add serverMetadata() mock to openid-client mock configuration * Fixes TypeError in openIdJwtStrategy.js where serverMetadata() was being called * Mock now returns jwks_uri and end_session_endpoint as expected by the code - Update outdated initialize.spec.js test * Remove test expecting resolveHeaders call during initialization * Header resolution was refactored to be deferred until LLM request time * Update test to verify options are returned correctly with useLegacyContent flag Fixes #9931 CI failures for backend unit tests 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * chore: fix package-lock.json conflict * chore: sync package-log with upstream * chore: cleanup * fix: use createSafeUser * fix: fix createSafeUser signature * chore: remove comments * chore: purge comments * fix: update Jest testPathPattern to testPathPatterns for Jest 30+ compatibility --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Denis Ramic <denis.ramic@nfon.com> Co-authored-by: kristjanaapro <kristjana@apro.is> chore: import order and add back JSDoc for OpenID JWT callback
2025-11-21 14:44:52 +00:00
* @param {import('@librechat/api').ServerRequest} req
* @param {import('openid-client').IDToken} payload
* @param {import('passport-jwt').VerifyCallback} done
*/
🆔 feat: Add OpenID Connect Federated Provider Token Support (#9931) * feat: Add OpenID Connect federated provider token support Implements support for passing federated provider tokens (Cognito, Azure AD, Auth0) as variables in LibreChat's librechat.yaml configuration for both custom endpoints and MCP servers. Features: - New LIBRECHAT_OPENID_* template variables for federated provider tokens - JWT claims parsing from ID tokens without verification (for claim extraction) - Token validation with expiration checking - Support for multiple token storage locations (federatedTokens, openidTokens) - Integration with existing template variable system - Comprehensive test suite with Cognito-specific scenarios - Provider-agnostic design supporting Cognito, Azure AD, Auth0, etc. Security: - Server-side only token processing - Automatic token expiration validation - Graceful fallbacks for missing/invalid tokens - No client-side token exposure 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: Add federated token propagation to OIDC authentication strategies Adds federatedTokens object to user during authentication to enable federated provider token template variables in LibreChat configuration. Changes: - OpenID JWT Strategy: Extract raw JWT from Authorization header and attach as federatedTokens.access_token to enable {{LIBRECHAT_OPENID_TOKEN}} placeholder resolution - OpenID Strategy: Attach tokenset tokens as federatedTokens object to standardize token access across both authentication strategies This enables proper token propagation for custom endpoints and MCP servers that require federated provider tokens for authorization. Resolves missing token issue reported by @ramden in PR #9931 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Denis Ramic <denis.ramic@nfon.com> Co-Authored-By: Claude <noreply@anthropic.com> * test: Add federatedTokens validation tests for OIDC strategies Adds comprehensive test coverage for the federated token propagation feature implemented in the authentication strategies. Tests added: - Verify federatedTokens object is attached to user with correct structure (access_token, refresh_token, expires_at) - Verify both tokenset and federatedTokens are present in user object - Ensure tokens from OIDC provider are correctly propagated Also fixes existing test suite by adding missing mocks: - isEmailDomainAllowed function mock - findOpenIDUser function mock These tests validate the fix from commit 5874ba29f that enables {{LIBRECHAT_OPENID_TOKEN}} template variable functionality. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * docs: Remove implementation documentation file The PR description already contains all necessary implementation details. This documentation file is redundant and was requested to be removed. * fix: skip s256 check * fix(openid): handle missing refresh token in Cognito token refresh response When OPENID_REUSE_TOKENS=true, the token refresh flow was failing because Cognito (and most OAuth providers) don't return a new refresh token in the refresh grant response - they only return new access and ID tokens. Changes: - Modified setOpenIDAuthTokens() to accept optional existingRefreshToken parameter - Updated validation to only require access_token (refresh_token now optional) - Added logic to reuse existing refresh token when not provided in tokenset - Updated refreshController to pass original refresh token as fallback - Added comments explaining standard OAuth 2.0 refresh token behavior This fixes the "Token is not present. User is not authenticated." error that occurred during silent token refresh with Cognito as the OpenID provider. Fixes: Authentication loop with OPENID_REUSE_TOKENS=true and AWS Cognito * fix(openid): extract refresh token from cookies for template variable replacement When OPENID_REUSE_TOKENS=true, the openIdJwtStrategy populates user.federatedTokens to enable template variable replacement (e.g., {{LIBRECHAT_OPENID_ACCESS_TOKEN}}). However, the refresh_token field was incorrectly sourced from payload.refresh_token, which is always undefined because: 1. JWTs don't contain refresh tokens in their payload 2. The JWT itself IS the access token 3. Refresh tokens are separate opaque tokens stored in HTTP-only cookies This caused extractOpenIDTokenInfo() to receive incomplete federatedTokens, resulting in template variables remaining unreplaced in headers. **Root Cause:** - Line 90: `refresh_token: payload.refresh_token` (always undefined) - JWTs only contain access token data in their claims - Refresh tokens are separate, stored securely in cookies **Solution:** - Import `cookie` module to parse cookies from request - Extract refresh token from `refreshToken` cookie - Populate federatedTokens with both access token (JWT) and refresh token (from cookie) **Impact:** - Template variables like {{LIBRECHAT_OPENID_ACCESS_TOKEN}} now work correctly - Headers in librechat.yaml are properly replaced with actual tokens - MCP server authentication with federated tokens now functional **Technical Details:** - passReqToCallback=true in JWT strategy provides req object access - Refresh token extracted via cookies.parse(req.headers.cookie).refreshToken - Falls back gracefully if cookie header or refreshToken is missing 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: re-resolve headers on each request to pick up fresh federatedTokens - OpenAIClient now re-resolves headers in chatCompletion() before each API call - This ensures template variables like {{LIBRECHAT_OPENID_TOKEN}} are replaced with actual token values from req.user.federatedTokens - initialize.js now stores original template headers instead of pre-resolved ones - Fixes template variable replacement when OPENID_REUSE_TOKENS=true The issue was that headers were only resolved once during client initialization, before openIdJwtStrategy had populated user.federatedTokens. Now headers are re-resolved on every request with the current user's fresh tokens. * debug: add logging to track header resolution in OpenAIClient * debug: log tokenset structure after refresh to diagnose missing access_token * fix: set federatedTokens on user object after OAuth refresh - After successful OAuth token refresh, the user object was not being updated with federatedTokens - This caused template variable resolution to fail on subsequent requests - Now sets user.federatedTokens with access_token, id_token, refresh_token and expires_at from the refreshed tokenset - Fixes template variables like {{LIBRECHAT_OPENID_TOKEN}} not being replaced after token refresh - Related to PR #9931 (OpenID federated token support) * fix(openid): pass user object through agent chain for template variable resolution Root cause: buildAgentContext in agents/run.ts called resolveHeaders without the user parameter, preventing OpenID federated token template variables from being resolved in agent runtime parameters. Changes: - packages/api/src/agents/run.ts: Add user parameter to createRun signature - packages/api/src/agents/run.ts: Pass user to resolveHeaders in buildAgentContext - api/server/controllers/agents/client.js: Pass user when calling createRun - api/server/services/Endpoints/bedrock/options.js: Add resolveHeaders call with debug logging - api/server/services/Endpoints/custom/initialize.js: Add debug logging - packages/api/src/utils/env.ts: Add comprehensive debug logging and stack traces - packages/api/src/utils/oidc.ts: Fix eslint errors (unused type, explicit any) This ensures template variables like {{LIBRECHAT_OPENID_TOKEN}} and {{LIBRECHAT_USER_OPENIDID}} are properly resolved in both custom endpoint headers and Bedrock AgentCore runtime parameters. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: remove debug logging from OpenID token template feature Removed excessive debug logging that was added during development to make the PR more suitable for upstream review: - Removed 7 debug statements from OpenAIClient.js - Removed all console.log statements from packages/api/src/utils/env.ts - Removed debug logging from bedrock/options.js - Removed debug logging from custom/initialize.js - Removed debug statement from AuthController.js This reduces the changeset by ~50 lines while maintaining full functionality of the OpenID federated token template variable feature. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * test(openid): add comprehensive unit tests for template variable substitution - Add 34 unit tests for OIDC token utilities (oidc.spec.ts) - Test coverage for token extraction, validation, and placeholder processing - Integration tests for full OpenID token flow - All tests pass with comprehensive edge case coverage 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * test: fix OpenID federated tokens test failures - Add serverMetadata() mock to openid-client mock configuration * Fixes TypeError in openIdJwtStrategy.js where serverMetadata() was being called * Mock now returns jwks_uri and end_session_endpoint as expected by the code - Update outdated initialize.spec.js test * Remove test expecting resolveHeaders call during initialization * Header resolution was refactored to be deferred until LLM request time * Update test to verify options are returned correctly with useLegacyContent flag Fixes #9931 CI failures for backend unit tests 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * chore: fix package-lock.json conflict * chore: sync package-log with upstream * chore: cleanup * fix: use createSafeUser * fix: fix createSafeUser signature * chore: remove comments * chore: purge comments * fix: update Jest testPathPattern to testPathPatterns for Jest 30+ compatibility --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Denis Ramic <denis.ramic@nfon.com> Co-authored-by: kristjanaapro <kristjana@apro.is> chore: import order and add back JSDoc for OpenID JWT callback
2025-11-21 14:44:52 +00:00
async (req, payload, done) => {
*️⃣ feat: Reuse OpenID Auth Tokens (#7397) * feat: integrate OpenID Connect support with token reuse - Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality. - Implemented OpenID token refresh logic in `AuthController`. - Enhanced `LogoutController` to handle OpenID logout and session termination. - Updated JWT authentication middleware to support OpenID token provider. - Modified OAuth routes to accommodate OpenID authentication and token management. - Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies. - Upgraded OpenID strategy with user info fetching and token exchange protocol. - Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens. - Added caching mechanism for exchanged OpenID tokens. - Updated configuration to include OpenID exchanged tokens cache key. - updated .env.example to include the new env variables needed for the feature. * fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables * fix: update Jest configuration and tests for OpenID strategy integration * fix: update OpenID strategy to include callback URL in setup * fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront) * fix: fixed code formatting * Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests * fix eslint errors: Format mock file openid-client. * ✨ feat: Add PKCE support for OpenID and default handling in strategy setup --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-22 14:19:24 +02:00
try {
🆔 feat: Add OpenID Connect Federated Provider Token Support (#9931) * feat: Add OpenID Connect federated provider token support Implements support for passing federated provider tokens (Cognito, Azure AD, Auth0) as variables in LibreChat's librechat.yaml configuration for both custom endpoints and MCP servers. Features: - New LIBRECHAT_OPENID_* template variables for federated provider tokens - JWT claims parsing from ID tokens without verification (for claim extraction) - Token validation with expiration checking - Support for multiple token storage locations (federatedTokens, openidTokens) - Integration with existing template variable system - Comprehensive test suite with Cognito-specific scenarios - Provider-agnostic design supporting Cognito, Azure AD, Auth0, etc. Security: - Server-side only token processing - Automatic token expiration validation - Graceful fallbacks for missing/invalid tokens - No client-side token exposure 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: Add federated token propagation to OIDC authentication strategies Adds federatedTokens object to user during authentication to enable federated provider token template variables in LibreChat configuration. Changes: - OpenID JWT Strategy: Extract raw JWT from Authorization header and attach as federatedTokens.access_token to enable {{LIBRECHAT_OPENID_TOKEN}} placeholder resolution - OpenID Strategy: Attach tokenset tokens as federatedTokens object to standardize token access across both authentication strategies This enables proper token propagation for custom endpoints and MCP servers that require federated provider tokens for authorization. Resolves missing token issue reported by @ramden in PR #9931 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Denis Ramic <denis.ramic@nfon.com> Co-Authored-By: Claude <noreply@anthropic.com> * test: Add federatedTokens validation tests for OIDC strategies Adds comprehensive test coverage for the federated token propagation feature implemented in the authentication strategies. Tests added: - Verify federatedTokens object is attached to user with correct structure (access_token, refresh_token, expires_at) - Verify both tokenset and federatedTokens are present in user object - Ensure tokens from OIDC provider are correctly propagated Also fixes existing test suite by adding missing mocks: - isEmailDomainAllowed function mock - findOpenIDUser function mock These tests validate the fix from commit 5874ba29f that enables {{LIBRECHAT_OPENID_TOKEN}} template variable functionality. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * docs: Remove implementation documentation file The PR description already contains all necessary implementation details. This documentation file is redundant and was requested to be removed. * fix: skip s256 check * fix(openid): handle missing refresh token in Cognito token refresh response When OPENID_REUSE_TOKENS=true, the token refresh flow was failing because Cognito (and most OAuth providers) don't return a new refresh token in the refresh grant response - they only return new access and ID tokens. Changes: - Modified setOpenIDAuthTokens() to accept optional existingRefreshToken parameter - Updated validation to only require access_token (refresh_token now optional) - Added logic to reuse existing refresh token when not provided in tokenset - Updated refreshController to pass original refresh token as fallback - Added comments explaining standard OAuth 2.0 refresh token behavior This fixes the "Token is not present. User is not authenticated." error that occurred during silent token refresh with Cognito as the OpenID provider. Fixes: Authentication loop with OPENID_REUSE_TOKENS=true and AWS Cognito * fix(openid): extract refresh token from cookies for template variable replacement When OPENID_REUSE_TOKENS=true, the openIdJwtStrategy populates user.federatedTokens to enable template variable replacement (e.g., {{LIBRECHAT_OPENID_ACCESS_TOKEN}}). However, the refresh_token field was incorrectly sourced from payload.refresh_token, which is always undefined because: 1. JWTs don't contain refresh tokens in their payload 2. The JWT itself IS the access token 3. Refresh tokens are separate opaque tokens stored in HTTP-only cookies This caused extractOpenIDTokenInfo() to receive incomplete federatedTokens, resulting in template variables remaining unreplaced in headers. **Root Cause:** - Line 90: `refresh_token: payload.refresh_token` (always undefined) - JWTs only contain access token data in their claims - Refresh tokens are separate, stored securely in cookies **Solution:** - Import `cookie` module to parse cookies from request - Extract refresh token from `refreshToken` cookie - Populate federatedTokens with both access token (JWT) and refresh token (from cookie) **Impact:** - Template variables like {{LIBRECHAT_OPENID_ACCESS_TOKEN}} now work correctly - Headers in librechat.yaml are properly replaced with actual tokens - MCP server authentication with federated tokens now functional **Technical Details:** - passReqToCallback=true in JWT strategy provides req object access - Refresh token extracted via cookies.parse(req.headers.cookie).refreshToken - Falls back gracefully if cookie header or refreshToken is missing 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: re-resolve headers on each request to pick up fresh federatedTokens - OpenAIClient now re-resolves headers in chatCompletion() before each API call - This ensures template variables like {{LIBRECHAT_OPENID_TOKEN}} are replaced with actual token values from req.user.federatedTokens - initialize.js now stores original template headers instead of pre-resolved ones - Fixes template variable replacement when OPENID_REUSE_TOKENS=true The issue was that headers were only resolved once during client initialization, before openIdJwtStrategy had populated user.federatedTokens. Now headers are re-resolved on every request with the current user's fresh tokens. * debug: add logging to track header resolution in OpenAIClient * debug: log tokenset structure after refresh to diagnose missing access_token * fix: set federatedTokens on user object after OAuth refresh - After successful OAuth token refresh, the user object was not being updated with federatedTokens - This caused template variable resolution to fail on subsequent requests - Now sets user.federatedTokens with access_token, id_token, refresh_token and expires_at from the refreshed tokenset - Fixes template variables like {{LIBRECHAT_OPENID_TOKEN}} not being replaced after token refresh - Related to PR #9931 (OpenID federated token support) * fix(openid): pass user object through agent chain for template variable resolution Root cause: buildAgentContext in agents/run.ts called resolveHeaders without the user parameter, preventing OpenID federated token template variables from being resolved in agent runtime parameters. Changes: - packages/api/src/agents/run.ts: Add user parameter to createRun signature - packages/api/src/agents/run.ts: Pass user to resolveHeaders in buildAgentContext - api/server/controllers/agents/client.js: Pass user when calling createRun - api/server/services/Endpoints/bedrock/options.js: Add resolveHeaders call with debug logging - api/server/services/Endpoints/custom/initialize.js: Add debug logging - packages/api/src/utils/env.ts: Add comprehensive debug logging and stack traces - packages/api/src/utils/oidc.ts: Fix eslint errors (unused type, explicit any) This ensures template variables like {{LIBRECHAT_OPENID_TOKEN}} and {{LIBRECHAT_USER_OPENIDID}} are properly resolved in both custom endpoint headers and Bedrock AgentCore runtime parameters. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: remove debug logging from OpenID token template feature Removed excessive debug logging that was added during development to make the PR more suitable for upstream review: - Removed 7 debug statements from OpenAIClient.js - Removed all console.log statements from packages/api/src/utils/env.ts - Removed debug logging from bedrock/options.js - Removed debug logging from custom/initialize.js - Removed debug statement from AuthController.js This reduces the changeset by ~50 lines while maintaining full functionality of the OpenID federated token template variable feature. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * test(openid): add comprehensive unit tests for template variable substitution - Add 34 unit tests for OIDC token utilities (oidc.spec.ts) - Test coverage for token extraction, validation, and placeholder processing - Integration tests for full OpenID token flow - All tests pass with comprehensive edge case coverage 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * test: fix OpenID federated tokens test failures - Add serverMetadata() mock to openid-client mock configuration * Fixes TypeError in openIdJwtStrategy.js where serverMetadata() was being called * Mock now returns jwks_uri and end_session_endpoint as expected by the code - Update outdated initialize.spec.js test * Remove test expecting resolveHeaders call during initialization * Header resolution was refactored to be deferred until LLM request time * Update test to verify options are returned correctly with useLegacyContent flag Fixes #9931 CI failures for backend unit tests 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * chore: fix package-lock.json conflict * chore: sync package-log with upstream * chore: cleanup * fix: use createSafeUser * fix: fix createSafeUser signature * chore: remove comments * chore: purge comments * fix: update Jest testPathPattern to testPathPatterns for Jest 30+ compatibility --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Denis Ramic <denis.ramic@nfon.com> Co-authored-by: kristjanaapro <kristjana@apro.is> chore: import order and add back JSDoc for OpenID JWT callback
2025-11-21 14:44:52 +00:00
const authHeader = req.headers.authorization;
const rawToken = authHeader?.replace('Bearer ', '');
const { user, error, migration } = await findOpenIDUser({
findUser,
email: payload?.email,
openidId: payload?.sub,
idOnTheSource: payload?.oid,
strategyName: 'openIdJwtLogin',
});
if (error) {
done(null, false, { message: error });
return;
}
*️⃣ feat: Reuse OpenID Auth Tokens (#7397) * feat: integrate OpenID Connect support with token reuse - Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality. - Implemented OpenID token refresh logic in `AuthController`. - Enhanced `LogoutController` to handle OpenID logout and session termination. - Updated JWT authentication middleware to support OpenID token provider. - Modified OAuth routes to accommodate OpenID authentication and token management. - Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies. - Upgraded OpenID strategy with user info fetching and token exchange protocol. - Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens. - Added caching mechanism for exchanged OpenID tokens. - Updated configuration to include OpenID exchanged tokens cache key. - updated .env.example to include the new env variables needed for the feature. * fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables * fix: update Jest configuration and tests for OpenID strategy integration * fix: update OpenID strategy to include callback URL in setup * fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront) * fix: fixed code formatting * Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests * fix eslint errors: Format mock file openid-client. * ✨ feat: Add PKCE support for OpenID and default handling in strategy setup --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-22 14:19:24 +02:00
if (user) {
user.id = user._id.toString();
const updateData = {};
if (migration) {
updateData.provider = 'openid';
updateData.openidId = payload?.sub;
}
*️⃣ feat: Reuse OpenID Auth Tokens (#7397) * feat: integrate OpenID Connect support with token reuse - Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality. - Implemented OpenID token refresh logic in `AuthController`. - Enhanced `LogoutController` to handle OpenID logout and session termination. - Updated JWT authentication middleware to support OpenID token provider. - Modified OAuth routes to accommodate OpenID authentication and token management. - Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies. - Upgraded OpenID strategy with user info fetching and token exchange protocol. - Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens. - Added caching mechanism for exchanged OpenID tokens. - Updated configuration to include OpenID exchanged tokens cache key. - updated .env.example to include the new env variables needed for the feature. * fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables * fix: update Jest configuration and tests for OpenID strategy integration * fix: update OpenID strategy to include callback URL in setup * fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront) * fix: fixed code formatting * Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests * fix eslint errors: Format mock file openid-client. * ✨ feat: Add PKCE support for OpenID and default handling in strategy setup --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-22 14:19:24 +02:00
if (!user.role) {
user.role = SystemRoles.USER;
updateData.role = user.role;
*️⃣ feat: Reuse OpenID Auth Tokens (#7397) * feat: integrate OpenID Connect support with token reuse - Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality. - Implemented OpenID token refresh logic in `AuthController`. - Enhanced `LogoutController` to handle OpenID logout and session termination. - Updated JWT authentication middleware to support OpenID token provider. - Modified OAuth routes to accommodate OpenID authentication and token management. - Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies. - Upgraded OpenID strategy with user info fetching and token exchange protocol. - Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens. - Added caching mechanism for exchanged OpenID tokens. - Updated configuration to include OpenID exchanged tokens cache key. - updated .env.example to include the new env variables needed for the feature. * fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables * fix: update Jest configuration and tests for OpenID strategy integration * fix: update OpenID strategy to include callback URL in setup * fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront) * fix: fixed code formatting * Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests * fix eslint errors: Format mock file openid-client. * ✨ feat: Add PKCE support for OpenID and default handling in strategy setup --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-22 14:19:24 +02:00
}
if (Object.keys(updateData).length > 0) {
await updateUser(user.id, updateData);
}
🆔 feat: Add OpenID Connect Federated Provider Token Support (#9931) * feat: Add OpenID Connect federated provider token support Implements support for passing federated provider tokens (Cognito, Azure AD, Auth0) as variables in LibreChat's librechat.yaml configuration for both custom endpoints and MCP servers. Features: - New LIBRECHAT_OPENID_* template variables for federated provider tokens - JWT claims parsing from ID tokens without verification (for claim extraction) - Token validation with expiration checking - Support for multiple token storage locations (federatedTokens, openidTokens) - Integration with existing template variable system - Comprehensive test suite with Cognito-specific scenarios - Provider-agnostic design supporting Cognito, Azure AD, Auth0, etc. Security: - Server-side only token processing - Automatic token expiration validation - Graceful fallbacks for missing/invalid tokens - No client-side token exposure 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: Add federated token propagation to OIDC authentication strategies Adds federatedTokens object to user during authentication to enable federated provider token template variables in LibreChat configuration. Changes: - OpenID JWT Strategy: Extract raw JWT from Authorization header and attach as federatedTokens.access_token to enable {{LIBRECHAT_OPENID_TOKEN}} placeholder resolution - OpenID Strategy: Attach tokenset tokens as federatedTokens object to standardize token access across both authentication strategies This enables proper token propagation for custom endpoints and MCP servers that require federated provider tokens for authorization. Resolves missing token issue reported by @ramden in PR #9931 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Denis Ramic <denis.ramic@nfon.com> Co-Authored-By: Claude <noreply@anthropic.com> * test: Add federatedTokens validation tests for OIDC strategies Adds comprehensive test coverage for the federated token propagation feature implemented in the authentication strategies. Tests added: - Verify federatedTokens object is attached to user with correct structure (access_token, refresh_token, expires_at) - Verify both tokenset and federatedTokens are present in user object - Ensure tokens from OIDC provider are correctly propagated Also fixes existing test suite by adding missing mocks: - isEmailDomainAllowed function mock - findOpenIDUser function mock These tests validate the fix from commit 5874ba29f that enables {{LIBRECHAT_OPENID_TOKEN}} template variable functionality. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * docs: Remove implementation documentation file The PR description already contains all necessary implementation details. This documentation file is redundant and was requested to be removed. * fix: skip s256 check * fix(openid): handle missing refresh token in Cognito token refresh response When OPENID_REUSE_TOKENS=true, the token refresh flow was failing because Cognito (and most OAuth providers) don't return a new refresh token in the refresh grant response - they only return new access and ID tokens. Changes: - Modified setOpenIDAuthTokens() to accept optional existingRefreshToken parameter - Updated validation to only require access_token (refresh_token now optional) - Added logic to reuse existing refresh token when not provided in tokenset - Updated refreshController to pass original refresh token as fallback - Added comments explaining standard OAuth 2.0 refresh token behavior This fixes the "Token is not present. User is not authenticated." error that occurred during silent token refresh with Cognito as the OpenID provider. Fixes: Authentication loop with OPENID_REUSE_TOKENS=true and AWS Cognito * fix(openid): extract refresh token from cookies for template variable replacement When OPENID_REUSE_TOKENS=true, the openIdJwtStrategy populates user.federatedTokens to enable template variable replacement (e.g., {{LIBRECHAT_OPENID_ACCESS_TOKEN}}). However, the refresh_token field was incorrectly sourced from payload.refresh_token, which is always undefined because: 1. JWTs don't contain refresh tokens in their payload 2. The JWT itself IS the access token 3. Refresh tokens are separate opaque tokens stored in HTTP-only cookies This caused extractOpenIDTokenInfo() to receive incomplete federatedTokens, resulting in template variables remaining unreplaced in headers. **Root Cause:** - Line 90: `refresh_token: payload.refresh_token` (always undefined) - JWTs only contain access token data in their claims - Refresh tokens are separate, stored securely in cookies **Solution:** - Import `cookie` module to parse cookies from request - Extract refresh token from `refreshToken` cookie - Populate federatedTokens with both access token (JWT) and refresh token (from cookie) **Impact:** - Template variables like {{LIBRECHAT_OPENID_ACCESS_TOKEN}} now work correctly - Headers in librechat.yaml are properly replaced with actual tokens - MCP server authentication with federated tokens now functional **Technical Details:** - passReqToCallback=true in JWT strategy provides req object access - Refresh token extracted via cookies.parse(req.headers.cookie).refreshToken - Falls back gracefully if cookie header or refreshToken is missing 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: re-resolve headers on each request to pick up fresh federatedTokens - OpenAIClient now re-resolves headers in chatCompletion() before each API call - This ensures template variables like {{LIBRECHAT_OPENID_TOKEN}} are replaced with actual token values from req.user.federatedTokens - initialize.js now stores original template headers instead of pre-resolved ones - Fixes template variable replacement when OPENID_REUSE_TOKENS=true The issue was that headers were only resolved once during client initialization, before openIdJwtStrategy had populated user.federatedTokens. Now headers are re-resolved on every request with the current user's fresh tokens. * debug: add logging to track header resolution in OpenAIClient * debug: log tokenset structure after refresh to diagnose missing access_token * fix: set federatedTokens on user object after OAuth refresh - After successful OAuth token refresh, the user object was not being updated with federatedTokens - This caused template variable resolution to fail on subsequent requests - Now sets user.federatedTokens with access_token, id_token, refresh_token and expires_at from the refreshed tokenset - Fixes template variables like {{LIBRECHAT_OPENID_TOKEN}} not being replaced after token refresh - Related to PR #9931 (OpenID federated token support) * fix(openid): pass user object through agent chain for template variable resolution Root cause: buildAgentContext in agents/run.ts called resolveHeaders without the user parameter, preventing OpenID federated token template variables from being resolved in agent runtime parameters. Changes: - packages/api/src/agents/run.ts: Add user parameter to createRun signature - packages/api/src/agents/run.ts: Pass user to resolveHeaders in buildAgentContext - api/server/controllers/agents/client.js: Pass user when calling createRun - api/server/services/Endpoints/bedrock/options.js: Add resolveHeaders call with debug logging - api/server/services/Endpoints/custom/initialize.js: Add debug logging - packages/api/src/utils/env.ts: Add comprehensive debug logging and stack traces - packages/api/src/utils/oidc.ts: Fix eslint errors (unused type, explicit any) This ensures template variables like {{LIBRECHAT_OPENID_TOKEN}} and {{LIBRECHAT_USER_OPENIDID}} are properly resolved in both custom endpoint headers and Bedrock AgentCore runtime parameters. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: remove debug logging from OpenID token template feature Removed excessive debug logging that was added during development to make the PR more suitable for upstream review: - Removed 7 debug statements from OpenAIClient.js - Removed all console.log statements from packages/api/src/utils/env.ts - Removed debug logging from bedrock/options.js - Removed debug logging from custom/initialize.js - Removed debug statement from AuthController.js This reduces the changeset by ~50 lines while maintaining full functionality of the OpenID federated token template variable feature. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * test(openid): add comprehensive unit tests for template variable substitution - Add 34 unit tests for OIDC token utilities (oidc.spec.ts) - Test coverage for token extraction, validation, and placeholder processing - Integration tests for full OpenID token flow - All tests pass with comprehensive edge case coverage 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com> * test: fix OpenID federated tokens test failures - Add serverMetadata() mock to openid-client mock configuration * Fixes TypeError in openIdJwtStrategy.js where serverMetadata() was being called * Mock now returns jwks_uri and end_session_endpoint as expected by the code - Update outdated initialize.spec.js test * Remove test expecting resolveHeaders call during initialization * Header resolution was refactored to be deferred until LLM request time * Update test to verify options are returned correctly with useLegacyContent flag Fixes #9931 CI failures for backend unit tests 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * chore: fix package-lock.json conflict * chore: sync package-log with upstream * chore: cleanup * fix: use createSafeUser * fix: fix createSafeUser signature * chore: remove comments * chore: purge comments * fix: update Jest testPathPattern to testPathPatterns for Jest 30+ compatibility --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Denis Ramic <denis.ramic@nfon.com> Co-authored-by: kristjanaapro <kristjana@apro.is> chore: import order and add back JSDoc for OpenID JWT callback
2025-11-21 14:44:52 +00:00
const cookieHeader = req.headers.cookie;
const parsedCookies = cookieHeader ? cookies.parse(cookieHeader) : {};
const accessToken = parsedCookies.openid_access_token;
const refreshToken = parsedCookies.refreshToken;
user.federatedTokens = {
access_token: accessToken || rawToken,
id_token: rawToken,
refresh_token: refreshToken,
expires_at: payload.exp,
};
*️⃣ feat: Reuse OpenID Auth Tokens (#7397) * feat: integrate OpenID Connect support with token reuse - Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality. - Implemented OpenID token refresh logic in `AuthController`. - Enhanced `LogoutController` to handle OpenID logout and session termination. - Updated JWT authentication middleware to support OpenID token provider. - Modified OAuth routes to accommodate OpenID authentication and token management. - Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies. - Upgraded OpenID strategy with user info fetching and token exchange protocol. - Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens. - Added caching mechanism for exchanged OpenID tokens. - Updated configuration to include OpenID exchanged tokens cache key. - updated .env.example to include the new env variables needed for the feature. * fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables * fix: update Jest configuration and tests for OpenID strategy integration * fix: update OpenID strategy to include callback URL in setup * fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront) * fix: fixed code formatting * Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests * fix eslint errors: Format mock file openid-client. * ✨ feat: Add PKCE support for OpenID and default handling in strategy setup --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-22 14:19:24 +02:00
done(null, user);
} else {
logger.warn(
'[openIdJwtLogin] openId JwtStrategy => no user found with the sub claims: ' +
payload?.sub +
(payload?.email ? ' or email: ' + payload.email : ''),
*️⃣ feat: Reuse OpenID Auth Tokens (#7397) * feat: integrate OpenID Connect support with token reuse - Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality. - Implemented OpenID token refresh logic in `AuthController`. - Enhanced `LogoutController` to handle OpenID logout and session termination. - Updated JWT authentication middleware to support OpenID token provider. - Modified OAuth routes to accommodate OpenID authentication and token management. - Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies. - Upgraded OpenID strategy with user info fetching and token exchange protocol. - Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens. - Added caching mechanism for exchanged OpenID tokens. - Updated configuration to include OpenID exchanged tokens cache key. - updated .env.example to include the new env variables needed for the feature. * fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables * fix: update Jest configuration and tests for OpenID strategy integration * fix: update OpenID strategy to include callback URL in setup * fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront) * fix: fixed code formatting * Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests * fix eslint errors: Format mock file openid-client. * ✨ feat: Add PKCE support for OpenID and default handling in strategy setup --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-22 14:19:24 +02:00
);
done(null, false);
}
} catch (err) {
done(err, false);
}
},
);
};
*️⃣ feat: Reuse OpenID Auth Tokens (#7397) * feat: integrate OpenID Connect support with token reuse - Added `jwks-rsa` and `new-openid-client` dependencies for OpenID Connect functionality. - Implemented OpenID token refresh logic in `AuthController`. - Enhanced `LogoutController` to handle OpenID logout and session termination. - Updated JWT authentication middleware to support OpenID token provider. - Modified OAuth routes to accommodate OpenID authentication and token management. - Created `setOpenIDAuthTokens` function to manage OpenID tokens in cookies. - Upgraded OpenID strategy with user info fetching and token exchange protocol. - Introduced `openIdJwtLogin` strategy for handling OpenID JWT tokens. - Added caching mechanism for exchanged OpenID tokens. - Updated configuration to include OpenID exchanged tokens cache key. - updated .env.example to include the new env variables needed for the feature. * fix: update return type in downloadImage documentation for clarity and fixed openIdJwtLogin env variables * fix: update Jest configuration and tests for OpenID strategy integration * fix: update OpenID strategy to include callback URL in setup * fix: fix optionalJwtAuth middleware to support OpenID token reuse and improve currentUrl method in CustomOpenIDStrategy to override the dynamic host issue related to proxy (e.g. cloudfront) * fix: fixed code formatting * Fix: Add mocks for openid-client and passport strategy in Jest configuration to fix unit tests * fix eslint errors: Format mock file openid-client. * ✨ feat: Add PKCE support for OpenID and default handling in strategy setup --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Ruben Talstra <RubenTalstra1211@outlook.com>
2025-05-22 14:19:24 +02:00
module.exports = openIdJwtLogin;