LibreChat/packages/api/src/utils/oidc.ts
Danny Avila db225c0919
🔐 feat: Admin Config Secrets v2 (MCP and Azure Credentials, Re-entry, Env Allowlist, Rebinding) (#17353)
* 🔐 feat: Admin Config Secrets v2 (MCP and Azure Credentials, Re-entry, Env Allowlist, Rebinding)

The admin config API stored MCP server credentials and Azure group keys in plaintext, returned
them to config readers, let an admin who cannot read a stored credential send it to a host of
their choosing, and let override values reference any environment variable. MCP credentials
and Azure keys, in `groups` and in the `groupMap` the Azure clients read, are now encrypted
with masked previews, hidden from every read and decrypted once after the merge. A write that
keeps a stored MCP credential or web search key while changing where it is sent must enter it
again, judged by the value the written document holds. `${VAR}` references in overrides are
limited to an allowlist, named where a change batch leaves them, and the merge drops a
credential a layer moves to a new destination without entering it, listing it in write
responses only for sections the caller can read. A custom endpoint's key is bound to its base
URL, its provider and the destination options in addParams and dropParams (such as the
anthropicApiUrl the native Anthropic client sends to), matched across layers under the name the
merge folds (ollama is Ollama). A restated `${VAR}` counts as entered, so allowlisted names
are not bound to a destination. Azure's `${INSTANCE_NAME}` and `${DEPLOYMENT_NAME}` stay
templates in a group's `baseURL`, and a scheduled job's MCP consent no longer depends on the
masked previews that change when an admin rotates the key in place.

* ♻️ refactor: Move the MCP Key Re-entry Guard Out of the Binding Helpers to Break an Import Cycle

With #17351's OpenID provisioning on dev, the app config service reached itself through the
rebinding guard: app/service -> app/overrides -> app/rebinding -> mcp/registry/binding ->
mcp/errors (and mcp/types) -> mcp/oauth/obo -> utils/identity -> auth/openid -> auth/provision
-> app/resolve -> app/service. The binding helpers are pure diffs; only
requireApiKeyReentryForRebinding needs the MCP error class, so it moves to
mcp/registry/reentry.ts, and the helpers take MCPOptions from librechat-data-provider as
mcp/headers.ts does. No behaviour changes.

* 🧪 test: Drop a Base-Held Endpoint Key That a Lower-Priority Profile Moves

Base merges first since #17352, so a profile below Base's priority still
lands over it. The rebinding guard drops the key Base stores for a custom
endpoint whose baseURL the profile changes, and the PATCH response lists
it in `ignored`.

* 🔐 fix: Serve Admin Azure Group Keys and Keep Deployment Keys at Their Own Destinations

Azure groups a profile writes now take effect: the merge resolves a layer's
`endpoints.azureOpenAI.groups` as AppService resolves librechat.yaml's
(`resolveAzureGroups`, shared with `azureConfigSetup`) into the `groupMap`,
`modelGroupMap`, model list and assistant models the Azure clients read. A
layer's groups replace the groups below whole, as its array does; groups that
do not resolve stay unread with a warning. The rebinding guard judges the
resolved groups like any `groupMap` entry, and an Azure group's destination now
also covers a deployment name its base URL takes its host from and the
destination options of its `addParams`/`dropParams`.

A write that keeps a stored Azure group key (in `groups` or `groupMap`) while
changing where the group sends it answers 400 `CONFIG_SECRET_REENTRY_REQUIRED`
on PUT, PATCH, field deletes, tombstones and change batches, judged as the
document resolves over librechat.yaml and on each `groups` item as written.

OCR fills an empty key from `OCR_API_KEY` only for its default destination (no
base URL, or `${OCR_BASEURL}`), so a key the guard dropped for an override's
`${VAR}` base URL is not replaced by the deployment's. The env reference policy
includes the `${OCR_API_KEY}` loading fills in for an `ocr` section without a
key, so a client can write back what GET `/base` returned.

The custom endpoint guard no longer needs the layer's overrides to name an
entry: an entry changed some other way is judged as inherited (positional
tombstones inside the list are not applied by the merge, so none reached one).

A web search URL a layer points at a `${VAR}` other than librechat.yaml's
without entering its key is set back: web search sends the deployment's key,
or its client's environment default, to any `${VAR}` URL.

* 🔐 fix: Keep Azure Assistants Served, Opaque Keys as Entered and Batch Env Checks on the End State

Azure assistants: a profile's `groups` replace the groups below whole, so
groups with no model that supports assistants under librechat.yaml's
`assistants: true` left `assistants` on with an empty `assistantModels`, and
the Azure Assistants initializer picked `assistantModels[0]` (undefined).
`azureConfigSetup` refuses that combination at startup; the merge now turns
`assistants` off when none of the models it leaves supports them, with a
warning, judged on the merged result so a later layer whose groups serve
assistants keeps them on. The check is `lacksAzureAssistantModels`, shared
with `azureConfigSetup`.

Opaque credentials: every runtime reader of the OCR, speech, web search and
Langfuse keys uses the decrypted value as is (`resolveConfigSecret`,
`resolveStoredConfigSecret`, `decryptConfigSecret`), so a `${...}` inside a
key the write encrypts is part of the key. Those fields are marked `opaque`:
the write-time check skips a value the write encrypts there, and the runtime
pass keeps their ciphertext instead of blanking it. A whole `${VAR}`
reference there, which the field passes through and its reader resolves, is
still checked, and so is stored plaintext. Custom endpoint (`initializeCustom`),
Azure group (`mapModelToAzureConfig`) and MCP (`processMCPEnv`) credentials
are expanded by their clients once decrypted and stay checked; the Assistants
keys have no reader yet and stay checked too.

Change batches: env references are judged on the document the batch leaves,
as its other issues are. An issue counts only when the end state still holds
a disallowed reference (ciphertext by its plaintext) where the batch sent one,
at a location the batch changed, so a value a later op removes or replaces
(`set ocr.baseURL`, then `unset ocr`) is no longer refused, and a stored
reference the batch puts back where it was is left to merge time.

* 🔐 fix: Proxy-Bound OAuth Secrets, Consistent Azure Group State, Batch Issues by Entry Key and Loaded Web Search References

- The MCP proxy is part of the OAuth client secret's binding (user tier, admin re-entry and the
  merge's rebinding guard share `getChangedOAuthSecretBindingFields`): the access token the
  secret obtains travels through it.
- A tombstone of `endpoints.azureOpenAI.groups` resolves the groups to none in the merge (empty
  `groupMap`, `modelGroupMap` and model lists, so the model list does not fall back to the
  environment's defaults), and removes what they resolve to in `applyConfigTombstones`.
- The merged Azure model lists name only models a merged group serves
  (`narrowAzureServedModels`), so an override's `assistantModels` no group serves no longer keeps
  Azure assistants on.
- `/changes` env issues are held by entry identity (`toConfigIdentityPath`), followed through
  renames and resolved on the batch's end state, so a removal or rename no longer shifts them.
- References loading librechat.yaml introduces (OCR's `${OCR_API_KEY}`, the web search defaults)
  are allowed at the location they are loaded at, so GET /base's sections are accepted written
  back, and nowhere else.

* 🔐 fix: Re-entry for Endpoint, OCR and Speech Keys, Own Keys Bound Over Base and User Key Destinations Kept

- The document that stores a custom endpoint, OCR or speech key can no longer
  move its destination without the key: PUT, PATCH, field deletes, tombstones
  and change batches answer CONFIG_SECRET_REENTRY_REQUIRED at the changed field
  (getBoundKeyReentryIssues), judged by value as the document alone sends it.
- A profile's own key for an endpoint, MCP server, OCR or speech service, or
  Azure groupMap group that Base defines is bound to that destination when it
  is entered: the rebinding guard reports a fingerprint of where it goes, the
  write stores it beside the key (<secret>Binding), and the guard keeps the key
  there until a lower layer moves it. Reads and the merged config leave the
  fingerprint out; kept keys carry it; client values are replaced.
- An inherited custom endpoint or MCP server that sends a credential each user
  holds (user_provided, customUserVars, apiKey.source user, OpenID or Graph
  token placeholders) keeps its destination: a layer's move is set back and
  listed in ignored.
2026-10-23 06:37:54 +02:00

326 lines
11 KiB
TypeScript

import { logger } from '@librechat/data-schemas';
import type { IUser, OIDCTokens } from '@librechat/data-schemas';
import { OPENID_EXPIRY_BUFFER_SECONDS } from '~/oauth/expiry';
export interface OpenIDTokenInfo {
accessToken?: string;
idToken?: string;
expiresAt?: number;
idTokenExpiresAt?: number;
userId?: string;
userEmail?: string;
userName?: string;
claims?: Record<string, unknown>;
}
function isFederatedTokens(obj: unknown): obj is OIDCTokens {
if (!obj || typeof obj !== 'object') {
return false;
}
return 'access_token' in obj || 'id_token' in obj || 'expires_at' in obj;
}
export const OPENID_TOKEN_FIELDS = [
'ACCESS_TOKEN',
'ID_TOKEN',
'USER_ID',
'USER_EMAIL',
'USER_NAME',
'EXPIRES_AT',
] as const;
export type OpenIDTokenField = (typeof OPENID_TOKEN_FIELDS)[number];
/**
* Placeholder for Microsoft Graph API access token.
* This placeholder is resolved asynchronously via OBO (On-Behalf-Of) flow
* and requires special handling outside the synchronous processMCPEnv pipeline.
*/
export const GRAPH_TOKEN_PLACEHOLDER = '{{LIBRECHAT_GRAPH_ACCESS_TOKEN}}';
/**
* The subset of OpenID placeholders that cannot resolve without a usable token
* set. Identity metadata (`USER_ID`, `USER_EMAIL`, `USER_NAME`) comes from the
* user document and `EXPIRES_AT` is only ever a hint, so those must keep their
* pre-existing literal-then-strip behaviour when the token set is invalid
* rather than raising re-auth. Non-global so `exec` stays stateless, and
* unknown names are excluded so a typo stays literal and diagnosable.
*/
export const OPENID_CREDENTIAL_PLACEHOLDER_PATTERN: RegExp =
/\{\{LIBRECHAT_OPENID_(?:ACCESS_TOKEN|ID_TOKEN|TOKEN)\}\}/;
/**
* Whether a value names a credential LibreChat fills in for each user: an OpenID token, or the
* Microsoft Graph token the OBO flow obtains. Identity and request placeholders are not.
*/
export function hasUserCredentialPlaceholder(value: string): boolean {
return (
OPENID_CREDENTIAL_PLACEHOLDER_PATTERN.test(value) || value.includes(GRAPH_TOKEN_PLACEHOLDER)
);
}
/**
* Default Microsoft Graph API scopes for OBO token exchange.
* Can be overridden via GRAPH_API_SCOPES environment variable.
*/
export const DEFAULT_GRAPH_SCOPES = 'https://graph.microsoft.com/.default';
/** Claims consulted when deciding whether a verified JWT is an access token rather than an ID token. */
export interface JwtTypeClaims {
aud?: string | string[];
scp?: unknown;
scope?: unknown;
at_hash?: unknown;
c_hash?: unknown;
}
/** The configured audiences a verified JWT is weighed against. */
export interface AccessTokenAudiences {
/** Audiences that name a protected resource rather than the OIDC client. */
resources?: ReadonlySet<string>;
/** The OIDC client id, so an `aud` that still names it is not read as resource-bound. */
clientId?: string;
}
/** RFC 9068 media type for a JWT access token, as it appears in the `typ` header (compared case-insensitively). */
const ACCESS_TOKEN_JWT_TYPES = new Set(['at+jwt', 'application/at+jwt']);
function decodeJwtHeaderType(token: string): string | undefined {
try {
const header = JSON.parse(Buffer.from(token.split('.')[0], 'base64').toString());
return typeof header?.typ === 'string' ? header.typ.toLowerCase() : undefined;
} catch {
return undefined;
}
}
function audienceList(aud: string | string[] | undefined): string[] {
if (typeof aud === 'string') {
return [aud];
}
return Array.isArray(aud) ? aud : [];
}
/**
* Decides whether a verified bearer JWT is an OAuth 2.0 access token, so it may stand in for a
* stored access token. Passing this strategy's audience check does not settle the question: an
* OIDC ID token is minted for the client id and satisfies the same check, and using one as the
* On-Behalf-Of assertion is rejected by the IdP (Entra answers `AADSTS240002`).
*
* Only two signals distinguish the two by specification rather than by provider convention:
* - an RFC 9068 `at+jwt` header type, which is defined for access tokens alone;
* - an `aud` that omits the OIDC client id, which OIDC Core §2 requires every ID token to carry,
* so a token without it cannot be an ID token for this deployment.
*
* Claim presence is deliberately not proof on its own. Providers add claims freely in both
* directions — Keycloak has emitted `nonce` and `auth_time` in access tokens, and maps `scope`
* into ID tokens — so `scp`/`scope` only qualifies a token whose audience has already ruled out
* an ID token. While the client id is in `aud` the token may be either, and it fails closed.
*
* `at_hash` and `c_hash` veto regardless, since they exist only to bind an ID token to its
* companion access token or code.
*/
export function isAccessTokenJwt(
token: string | undefined,
claims: JwtTypeClaims | undefined,
audiences?: AccessTokenAudiences,
): boolean {
if (!token || !claims) {
return false;
}
if (claims.at_hash != null || claims.c_hash != null) {
return false;
}
const headerType = decodeJwtHeaderType(token);
if (headerType != null && ACCESS_TOKEN_JWT_TYPES.has(headerType)) {
return true;
}
/** Without a configured client id the audience can rule nothing out, so nothing but `at+jwt` qualifies */
if (audiences?.clientId == null) {
return false;
}
const tokenAudiences = audienceList(claims.aud);
if (tokenAudiences.includes(audiences.clientId)) {
return false;
}
if (audiences.resources?.size) {
if (tokenAudiences.some((audience) => audiences.resources!.has(audience))) {
return true;
}
}
return claims.scp != null || claims.scope != null;
}
/**
* Signals that the stored OpenID credentials cannot satisfy a placeholder, so the user must
* re-authenticate. `ErrorController` maps this to a 401, and `statusCode` additionally lets
* status-reading callers (the agent generation path's `getInitializationFailure`) answer 401
* instead of a bare 500. Deliberately carries no `body`, so the structural `isCustomError`
* guard cannot capture it ahead of the explicit mapping.
*/
export class OpenIDReauthRequiredError extends Error {
readonly statusCode = 401;
constructor(message: string) {
super(message);
this.name = 'OpenIDReauthRequiredError';
}
}
export function extractOpenIDTokenInfo(
user: Partial<IUser> | null | undefined,
): OpenIDTokenInfo | null {
if (!user) {
return null;
}
try {
if (user.provider !== 'openid' && !user.openidId) {
return null;
}
const tokenInfo: OpenIDTokenInfo = {};
const federated = user.federatedTokens;
const openid = user.openidTokens;
if (federated && isFederatedTokens(federated)) {
logger.debug('[extractOpenIDTokenInfo] Found federatedTokens:', {
has_access_token: !!federated.access_token,
has_id_token: !!federated.id_token,
has_refresh_token: !!federated.refresh_token,
expires_at: federated.expires_at,
});
tokenInfo.accessToken = federated.access_token;
tokenInfo.idToken = federated.id_token;
tokenInfo.expiresAt = federated.expires_at;
} else if (openid && isFederatedTokens(openid)) {
logger.debug('[extractOpenIDTokenInfo] Found openidTokens');
tokenInfo.accessToken = openid.access_token;
tokenInfo.idToken = openid.id_token;
tokenInfo.expiresAt = openid.expires_at;
}
tokenInfo.userId = user.openidId || user.id;
tokenInfo.userEmail = user.email;
tokenInfo.userName = user.name || user.username;
if (tokenInfo.idToken) {
try {
const payload = JSON.parse(
Buffer.from(tokenInfo.idToken.split('.')[1], 'base64').toString(),
);
tokenInfo.claims = payload;
/** Cached profile claims, not an authentication assertion: stale claims stay usable for identity fields even when the ID token itself is expired */
if (payload.sub) tokenInfo.userId = payload.sub;
if (payload.email) tokenInfo.userEmail = payload.email;
if (payload.name) tokenInfo.userName = payload.name;
if (typeof payload.exp === 'number') {
tokenInfo.idTokenExpiresAt = payload.exp;
}
} catch (jwtError) {
logger.warn('Could not parse ID token claims:', jwtError);
}
}
return tokenInfo;
} catch (error) {
logger.error('Error extracting OpenID token info:', error);
return null;
}
}
/** Advisory freshness check, not a security boundary: the ID token signature is not verified here. `exp` is REQUIRED in an ID token, so a missing value means the token is malformed or unparseable and fails closed. */
function isIdTokenCurrent(tokenInfo: OpenIDTokenInfo): boolean {
if (tokenInfo.idTokenExpiresAt == null) {
return false;
}
return Math.floor(Date.now() / 1000) < tokenInfo.idTokenExpiresAt - OPENID_EXPIRY_BUFFER_SECONDS;
}
export function isOpenIDTokenValid(tokenInfo: OpenIDTokenInfo | null): boolean {
if (!tokenInfo || !tokenInfo.accessToken) {
return false;
}
if (tokenInfo.expiresAt != null) {
const now = Math.floor(Date.now() / 1000);
if (now >= tokenInfo.expiresAt - OPENID_EXPIRY_BUFFER_SECONDS) {
logger.warn('OpenID token has expired');
return false;
}
}
return true;
}
/**
* @param fields Restricts which placeholders may resolve. Callers holding a token set whose
* access token is unusable pass `['ID_TOKEN']`, so the ID token resolves on its own expiry while
* every other placeholder keeps its literal-then-strip behaviour.
*/
export function processOpenIDPlaceholders(
value: string,
tokenInfo: OpenIDTokenInfo | null,
fields: readonly OpenIDTokenField[] = OPENID_TOKEN_FIELDS,
): string {
if (!tokenInfo || typeof value !== 'string') {
return value;
}
let processedValue = value;
for (const field of fields) {
const placeholder = `{{LIBRECHAT_OPENID_${field}}}`;
if (!processedValue.includes(placeholder)) {
continue;
}
let replacementValue = '';
switch (field) {
case 'ACCESS_TOKEN':
replacementValue = tokenInfo.accessToken || '';
break;
case 'ID_TOKEN':
if (!tokenInfo.idToken || !isIdTokenCurrent(tokenInfo)) {
logger.warn('OpenID ID token is expired or unavailable; re-authentication is required');
throw new OpenIDReauthRequiredError(
'OpenID ID token is expired or unavailable; re-authentication is required to resolve {{LIBRECHAT_OPENID_ID_TOKEN}}',
);
}
replacementValue = tokenInfo.idToken;
break;
case 'USER_ID':
replacementValue = tokenInfo.userId || '';
break;
case 'USER_EMAIL':
replacementValue = tokenInfo.userEmail || '';
break;
case 'USER_NAME':
replacementValue = tokenInfo.userName || '';
break;
case 'EXPIRES_AT':
/** The stored token-set expires_at only: the ID token exp never stands in for it */
replacementValue = tokenInfo.expiresAt != null ? String(tokenInfo.expiresAt) : '';
break;
}
processedValue = processedValue.replace(new RegExp(placeholder, 'g'), replacementValue);
}
const genericPlaceholder = '{{LIBRECHAT_OPENID_TOKEN}}';
if (fields.includes('ACCESS_TOKEN') && processedValue.includes(genericPlaceholder)) {
const replacementValue = tokenInfo.accessToken || '';
processedValue = processedValue.replace(new RegExp(genericPlaceholder, 'g'), replacementValue);
}
return processedValue;
}