Skip to content

🧑‍💼 feat: Apply OpenID Back-Channel Logout to Admin Sessions - #18439

Draft
AtefBellaaj wants to merge 17 commits into
atef/ai-2415-bcl-05-logout-enforcefrom
atef/ai-2415-bcl-06-logout-admin
Draft

AtefBellaaj wants to merge 17 commits into
atef/ai-2415-bcl-05-logout-enforcefrom
atef/ai-2415-bcl-06-logout-admin

Conversation

@AtefBellaaj

@AtefBellaaj AtefBellaaj commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Pull Request

Before submitting, please review the Contributing Guide.

Documentation changes belong in the LibreChat documentation repository.

Summary

Part 7 of 9 in the OpenID back-channel logout stack. It is based on #18438, and #18583 builds on it.

The admin panel signs in through its own flow. The OpenID callback gives the panel a one-time exchange code, and the panel trades the code for tokens and renews them through /api/admin/oauth/refresh. The earlier PRs do not cover this flow, so a back-channel logout does not end an admin panel session.

This PR links admin sessions to their provider session and checks it at each step:

  • The admin OpenID callback stores the provider session with the refresh token (persistOpenIDAdminProviderSessionBinding) and puts it in the exchange code.
  • exchangeAdminCode checks the provider session before it returns tokens.
  • Admin refresh checks the binding before it spends the refresh grant, and again before it returns the response. Refresh recovery does the same.

The refresh sequence (prepare, grant, apply, and the error mapping) lives in refreshAdminOpenIdSession in packages/api/src/auth/openid/providerSession/adminRefresh.ts. The route only wires its dependencies, and the integration spec calls the same function.

A denial answers 401 with error_code: OPENID_SESSION_ENDED. An unavailable check answers 503 with AUTH_SESSION_CHECK_UNAVAILABLE. record and enforce mean the same here as in the main app.

How it works

sequenceDiagram
    participant Panel as Admin panel
    participant LC as LibreChat
    participant DB as MongoDB
    participant IdP as OpenID provider

    Panel->>IdP: sign in
    IdP->>LC: admin callback (ID token with sid)
    LC->>DB: store binding: refresh token → provider session
    LC-->>Panel: redirect with exchange code { tokens, providerSession }

    Panel->>LC: POST /api/admin/oauth/exchange
    LC->>DB: authorize(providerSession)
    alt allowed
        LC-->>Panel: tokens
    else unavailable
        LC->>LC: restoreCacheEntry(code)
        LC-->>Panel: 503 AUTH_SESSION_CHECK_UNAVAILABLE
    else ended
        LC-->>Panel: 401 OPENID_SESSION_ENDED
    end

    Panel->>LC: POST /api/admin/oauth/refresh
    LC->>DB: precheck binding (before the grant)
    LC->>IdP: refresh grant
    LC->>DB: authorize again, store rotated binding
    LC-->>Panel: new tokens, or 401 / 503
Loading

When the check is unavailable, the exchange code goes back into the cache with its remaining lifetime (restoreCacheEntry from #18434), so the panel can retry the same code. After a denial, the code stays consumed.

Both admin routes map errors through one helper, mapAdminAuthError, so they send the same response shape:

mapAdminAuthError(error)
├── ProviderSessionUnavailableError  → 503 { error_code: AUTH_SESSION_CHECK_UNAVAILABLE }
├── AdminRefreshError | AdminExchangeError → error.status { error_code: error.code }
└── other                             → null (caller handles it)

Keeping renewal retryable

With this PR, an admin panel session ends when a renewal fails. That makes two older renewal behaviors more costly, so this PR changes them.

A provider outage signed the admin out. Any failed refresh grant, including a network error or a provider 5xx, answered 401 REFRESH_FAILED, and the panel treats that as a sign-out. A new helper, mapAdminRefreshError, now maps the provider's OAuth error code. A code counts only with a 400, 401 or 403 status, or no status. The OpenID route and the Google refresh (googleRefresh.ts) both use the helper.

Provider answer Response
invalid_grant, interaction_required, login_required, consent_required 401 REFRESH_FAILED: the panel signs the admin out
invalid_client, unauthorized_client, unsupported_grant_type, invalid_scope, invalid_request 500 OPENID_CLIENT_MISCONFIGURED, logged as an error: the server's OAuth client is wrong, and a retry cannot succeed
anything else: network error, 429, 5xx, a code with another status 503 AUTH_SESSION_CHECK_UNAVAILABLE: retryable

Concurrent admin refreshes. Admin refreshes of one refresh token share a grant flight, like token-reuse refreshes in the main app.

  • When the grant throws, the owner marks the flight failed, so a retry takes it over at once instead of waiting for the flight to expire.
  • A request that neither a Session row nor a bridge binds gets 401 OPENID_SESSION_ENDED when it loses the flight. Without this, a retry with a spent token after a denial passed the precheck and received the recorded grant result.
  • When the Session row for the rotated token cannot be written, the refresh answers 503 in every mode. The bridge is stored first, so a retry recovers the rotated token and writes the row. Before, record mode answered 200 and left the rotated token without a binding, so later logouts never applied to it.

Renewal shared the sign-in rate limit. /api/admin/oauth/refresh was behind loginLimiter, so an admin who opened many panel tabs could use up the sign-in budget for their IP. The route now has its own limiter, adminRefreshLimiter, configured under rateLimits.adminRefresh:

rateLimits:
  adminRefresh:
    windowMs: 60000   # default
    max: 30           # default, per IP

The admin panel's server makes these calls, so all admins of one panel share its IP and its budget. Deployments with many admins can raise max. The limiter keys on the client IP with any :port suffix removed, and IPv6 clients in the same /56 share one budget. Each rejected request logs a warning with the client IP, the window and the limit. The route has no authenticated user, so logViolation, which counts per user, cannot record it. /oauth/exchange stays on loginLimiter. The setting is documented in librechat.example.yaml.

Type of change

  • Feature
  • Documentation

Testing

Tested environments/configuration:

  • Automated tests only, with registration.openidBackchannelLogout.mode set to record and to enforce, with OpenID login to the admin panel.
  • Not yet tested against a live provider or a running admin panel.

Automated tests:

  • Added adminAuthErrors.spec.ts, providerSession/adminRefresh.spec.ts, providerSession/adminRefreshDeps.spec.ts, providerSession/binding.spec.ts and providerSession/adminRefreshRecovery.integration.spec.ts.
  • Added cases to exchange.spec.ts, refresh.spec.ts, providerSession/callback.spec.ts, images/session.spec.ts and oauth.spec.js.
  • Added api/server/routes/admin/auth.refresh.test.js for the admin route wiring and the separate limiter budget. The mapping table cases are in adminAuthErrors.spec.ts. The flight takeover after a thrown grant, the unbound retry and the Session-row write failure are in adminRefreshRecovery.integration.spec.ts.
  • Added Google outage and rejection cases to googleRefresh.spec.ts, middleware/adminRefreshLimiter.spec.ts (including the warning on a rejection), and data-provider config.adminRefresh.spec.ts.
  • Local runs on this branch: packages/api auth and providerSession specs 430/430, limiter spec 7/7, admin route specs 62/62.
  • CI runs typecheck and the full suites.

Screenshots / recordings

No user-facing change in LibreChat. The admin panel receives the new 401 and 503 responses.

Risk / compatibility

  • Mode off keeps today's admin flow, and LibreChat stores no binding.
  • An exchange code issued before this change carries no provider session. record mode allows it, and enforce mode denies it, the same as a legacy session.
  • An admin session created or rotated while the mode is off has no binding. After a switch to enforce, that session must sign in once.
  • The admin panel must treat 401 OPENID_SESSION_ENDED as a sign-out and 503 AUTH_SESSION_CHECK_UNAVAILABLE as retryable. It must also handle the new 500 OPENID_CLIENT_MISCONFIGURED as an error that a retry will not fix.
  • The renewal changes apply in every mode, including off. A provider outage during admin refresh now answers 503 instead of 401 REFRESH_FAILED. A panel that does not retry on 503 will show an error instead of signing the admin out.
  • Adds the optional config key rateLimits.adminRefresh. Without it, renewal allows 30 requests per minute per IP. Before, it shared loginLimiter's 7 per 5 minutes.

Checklist

  • I reviewed my own changes
  • Relevant tests have been added or updated
  • Existing relevant tests pass
  • The change does not introduce new warnings or errors
  • User-facing or complex behavior is documented where necessary
  • Required dependency changes have been merged/published
  • Required documentation PR: not opened yet

@AtefBellaaj
AtefBellaaj added this pull request to stack #18441 November 18, 2026 17:27
@AtefBellaaj
AtefBellaaj force-pushed the atef/ai-2415-bcl-06-logout-admin branch from 85d4bbc to f05841b Compare November 18, 2026 18:43
@AtefBellaaj
AtefBellaaj force-pushed the atef/ai-2415-bcl-06-logout-admin branch from f05841b to a8a0993 Compare November 19, 2026 08:49
@AtefBellaaj
AtefBellaaj force-pushed the atef/ai-2415-bcl-06-logout-admin branch from a8a0993 to d2d0ea0 Compare November 19, 2026 10:29
@AtefBellaaj
AtefBellaaj force-pushed the atef/ai-2415-bcl-06-logout-admin branch from d2d0ea0 to 9a0159a Compare November 19, 2026 11:06
@AtefBellaaj
AtefBellaaj force-pushed the atef/ai-2415-bcl-06-logout-admin branch from 9a0159a to a6bd954 Compare November 20, 2026 08:30
@AtefBellaaj
AtefBellaaj force-pushed the atef/ai-2415-bcl-06-logout-admin branch from a6bd954 to abafd23 Compare November 20, 2026 09:12
@AtefBellaaj
AtefBellaaj force-pushed the atef/ai-2415-bcl-06-logout-admin branch from abafd23 to 6adde5b Compare November 20, 2026 12:50

@danny-avila danny-avila left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Findings inline. Also:

  • The prepare, grant, apply sequence and its error mapping live in api/server/routes/admin/auth.js. That is logic, not wiring, so it belongs in packages/api. The integration spec reimplements the sequence and already differs: it maps grant errors with mapAdminAuthError, the route uses mapAdminRefreshError.
  • rateLimits.adminRefresh is not in the docs or librechat.example.yaml.

);
throw coordinationUnavailable(error);
}
throw error;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the grant throws, the flight is never marked failed, so it stays pending. A retry inside the 30 second lock cannot take it over and waits about 2 minutes before it gets a 503.

This is exactly the case this PR now calls retryable. The browser paths call failOpenIDRefreshFlight here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. A grant that threw left the flight pending, because the admin deps had no failOpenIDRefreshFlight. A retry then waited about 2 minutes and got a 503. Fixed in c771e6f: the owner fails the flight in the catch, as the main refresh path does. A new test makes the grant throw and checks that the retry takes over the flight at once.

if (!flight.acquired) {
/** A concurrent request with the same token owns the grant. Granting again would present a
* token the owner already spent, so this request takes the owner's result instead. */
return waitForSharedAdminTokenset(grantKey, presentedRefreshToken, deps);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

record mode: a spent refresh token still gets a fresh admin token after the provider session is revoked.

After a rotation, the completed flight for the old token stays readable for 2 minutes. The first retry with the old token is denied and the bridge is deleted. A second retry has no binding and no bridge, so the precheck passes with a null ref and this returns the recorded tokens.

Please add a test for the second retry.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, I reproduced it: in record, the second retry returned 200 with the recorded tokens and skipped the check. Fixed in e82c64a: a request that neither a Session row nor a bridge binds now gets 401 OPENID_SESSION_ENDED when it loses the admin grant flight, in record and enforce. Without a binding, LibreChat can't show that the tokens belong to a live provider session, so it doesn't return them. An unbound request that owns the flight still runs the grant itself, and off reads no bindings, so it is unchanged. There are tests for record and enforce, for off, and for your retry sequence.

Comment thread packages/api/src/auth/refresh.ts Outdated
const mode = await deps.getMode?.();
if (mode === 'record') {
logger.warn(
'[adminRefresh] Failed to persist the refreshed session; tolerating in record mode',

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this write fails once in record mode, the rotated token has no Session row. Every later refresh then has no binding, and a logout never applies to this admin session again. Switching to enforce signs it out.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. In record, a failed storeOpenIdSession was swallowed, and the session stayed unbound for good. Fixed in 7d777e7: the write failure answers 503 in every mode. The bridge is stored first, so the panel's retry recovers the rotated token and stores the row. The specs that expected the old behavior are updated.

Comment thread packages/data-provider/src/config.ts Outdated

export const adminRefreshRateLimitSchema = z.object({
windowMs: z.number().int().positive().max(2_147_483_647).default(60_000),
max: z.number().int().positive().default(120),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Before, this route shared the login limiter: 7 per 5 minutes, with violation logging. Now it is 120 per minute per IP with none, and every call with any token reaches the provider's token endpoint. A separate limiter makes sense, but is 120 the right default?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partly agreed. The old limit changed because the admin panel's server calls this route, so every admin shares that server's IP, and loginLimiter's 7 per 5 minutes ran out with a few admins. You're right that 120 a minute was too loose: in off and record mode, a junk token still reaches the provider's token endpoint. Fixed in badca6a and 3ae001a: the default is now 30 a minute per IP, and deployments with many admins can raise it with rateLimits.adminRefresh.max.

On violation logging: logViolation counts per req.user and returns when there is none, so on this route (and on the login routes, which run loginLimiter before authentication) it never recorded anything. Instead, each rejection now logs a warning with the client address (without the port), the window and the limit, so an operator can see and alert on repeated renewals from one address. A ban score for unauthenticated callers would need an IP-keyed violation count, which would also apply to login, so I've left that out of this PR.

const rejected =
typeof error === 'object' &&
error !== null &&
(('error' in error && error.error === 'invalid_grant') ||

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only invalid_grant ends the session now. Other final refusals, like interaction_required or consent_required, answer 503 forever and the panel never asks the admin to sign in again. Should these map to 401 too?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, matching only invalid_grant was too narrow. Fixed in 0d963b5. An OAuth error code counts only when the provider answered 400, 401, 403 or no status:

Provider answer Response
invalid_grant, interaction_required, login_required, consent_required 401 REFRESH_FAILED: the panel signs the admin out
invalid_client, unauthorized_client, unsupported_grant_type, invalid_scope, invalid_request 500 OPENID_CLIENT_MISCONFIGURED, logged as an error: the configuration is wrong, and a retry won't fix it
server_error, temporarily_unavailable, an unknown code, any of the codes above with another status, 5xx, 429, network errors 503 AUTH_SESSION_CHECK_UNAVAILABLE: retryable

adminAuthErrors.spec.ts has a table test that covers each row. This applies in every mode.

@lia-by-librechat lia-by-librechat Bot changed the title feat(auth): apply OpenID back-channel logout to admin panel sessions 🧑‍💼 feat: Apply OpenID Back-Channel Logout to Admin Sessions Nov 20, 2026
@AtefBellaaj
AtefBellaaj force-pushed the atef/ai-2415-bcl-06-logout-admin branch from 6adde5b to cac7f32 Compare November 20, 2026 17:07
@AtefBellaaj
AtefBellaaj removed this pull request from stack #18441 November 20, 2026 17:09
@AtefBellaaj
AtefBellaaj added this pull request to stack #18634 November 20, 2026 17:12
@AtefBellaaj

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T17:49:24.289051Z 3ae001a Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3ae001a698

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +342 to +345
const userId = lookup.binding?.userId ?? options.userId;
if (!userId) {
return { refreshToken, bridged: false };
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve recovery identity when user_id is omitted

When a client omits the optional user_id, the first refresh obtains its identity from the Session row, but storeOpenIdSession deletes that row after rotation. If the response is lost or token minting subsequently fails, retrying the same request reaches this return without consulting the bridge that the first request stored. In enforce mode the missing binding then produces 401 OPENID_SESSION_ENDED; in record mode the already-spent token is sent to the provider again. Preserve a token-keyed recovery identity, or otherwise make bridge recovery work without requiring a previously optional request field.

Useful? React with 👍 / 👎.

Comment on lines +684 to +686
const mapped = mapAdminAuthError(error);
if (mapped) {
return res.status(mapped.status).json(mapped.body);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep the new exchange error handling in TypeScript

This adds failure-classification and HTTP-response branching to a legacy CJS route. AGENTS.md explicitly says /api holds wiring, not behavior, including new branches and service calls when editing existing CJS files. Move the exchange orchestration and its error-response mapping into a TypeScript handler under packages/api, leaving this file to register the route and supply dependencies.

AGENTS.md reference: AGENTS.md:L86-L90

Useful? React with 👍 / 👎.

getProviderSessionClient,
logger,
/** Read per call, like the session it binds, so a changed env value applies. */
refreshTokenExpiryMs: math(process.env.REFRESH_TOKEN_EXPIRY, DEFAULT_REFRESH_TOKEN_EXPIRY),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Inject the callback's refresh-token lifetime

The new service method reads process.env directly even though this factory otherwise receives its configuration through dependencies. AGENTS.md requires code in packages/api to receive configuration from its caller rather than read global state. Add an injected lifetime getter, as the new admin refresh and exchange dependencies already do, and resolve the environment setting in the application wiring so independently constructed services and tests do not share an implicit process-global configuration.

AGENTS.md reference: AGENTS.md:L102-L108

Useful? React with 👍 / 👎.

@AtefBellaaj

Copy link
Copy Markdown
Collaborator Author

Reply to this review:

Both points were right.

  1. The route held the sequence. AGENTS.md keeps /api to wiring, and auth.js:796-893 held the refresh sequence. The integration spec also mapped errors with mapAdminAuthError, while the route used mapAdminRefreshError, so the spec didn't test what production runs. Fixed in 816bb18: refreshAdminOpenIdSession in packages/api runs the sequence and returns the response to send. The route only wires its dependencies, and the integration spec calls the same function.
  2. rateLimits.adminRefresh wasn't documented. It is now in librechat.example.yaml (f55f225 and badca6a), with the default and when to raise it. docs/openid-backchannel-logout.md has a new "Admin panel renewal limit" section (aa7317d) that explains why the route has its own limit, when to raise max, and the warning a rejection logs.

@AtefBellaaj
AtefBellaaj force-pushed the atef/ai-2415-bcl-06-logout-admin branch from aa7317d to b2ef1e8 Compare November 20, 2026 19:25
…ervice

createProviderSessionService now returns establishOAuthCallback and
persistOAuthAdminBinding with their dependencies bound, including the refresh-token
lifetime and storeOpenIDSession. The OAuth controller only calls them, so /api keeps
wiring and no provider-session setup.

Related to AI-2415.
A thrown grant left the admin grant flight pending, so a retry inside the lock waited for the flight to expire and then got a 503. The owner now marks the flight failed, and the retry takes it over at once.
In record mode, a retry with a spent token after a provider-session denial had no Session row and no bridge, so it passed the precheck and took the recorded grant result with a 200. A request that neither a Session row nor a bridge binds now gets 401 OPENID_SESSION_ENDED when it loses the admin grant flight, in every mode that reads bindings.
In record mode, a failed Session row write was logged and the refresh returned 200, so the rotated token had no binding and later logouts never applied to it. The write failure now answers 503 in every mode. The bridge is stored first, so a retry recovers the rotated token and stores the row.
Only invalid_grant ended the admin session, so a provider that required a new sign-in answered 503 for good. interaction_required, login_required and consent_required now answer 401 REFRESH_FAILED under the same status rule as invalid_grant. Client configuration faults (invalid_client, unauthorized_client, unsupported_grant_type, invalid_scope, invalid_request) answer 500 OPENID_CLIENT_MISCONFIGURED and log at error level. Other failures stay a retryable 503.
The /api/admin/oauth/refresh route ran the prepare, grant and apply sequence and its error mapping itself, and the integration spec copied the sequence with a different grant-error mapping. refreshAdminOpenIdSession now runs the sequence and returns the response to send. The route only wires its dependencies, and the integration spec calls the same function.
Describe rateLimits.adminRefresh, its defaults, when to raise it, and the warning a rejection logs.
@AtefBellaaj
AtefBellaaj force-pushed the atef/ai-2415-bcl-06-logout-admin branch from b2ef1e8 to 4d52096 Compare November 20, 2026 19:29

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants