Repository navigation
🧑💼 feat: Apply OpenID Back-Channel Logout to Admin Sessions - #18439
AtefBellaaj wants to merge 17 commits into
Conversation
85d4bbc to
f05841b
Compare
f05841b to
a8a0993
Compare
a8a0993 to
d2d0ea0
Compare
d2d0ea0 to
9a0159a
Compare
9a0159a to
a6bd954
Compare
a6bd954 to
abafd23
Compare
abafd23 to
6adde5b
Compare
danny-avila
left a comment
There was a problem hiding this comment.
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 inpackages/api. The integration spec reimplements the sequence and already differs: it maps grant errors withmapAdminAuthError, the route usesmapAdminRefreshError. rateLimits.adminRefreshis not in the docs orlibrechat.example.yaml.
| ); | ||
| throw coordinationUnavailable(error); | ||
| } | ||
| throw error; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| const mode = await deps.getMode?.(); | ||
| if (mode === 'record') { | ||
| logger.warn( | ||
| '[adminRefresh] Failed to persist the refreshed session; tolerating in record mode', |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
|
||
| 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), |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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') || |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
6adde5b to
cac7f32
Compare
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| const userId = lookup.binding?.userId ?? options.userId; | ||
| if (!userId) { | ||
| return { refreshToken, bridged: false }; | ||
| } |
There was a problem hiding this comment.
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 👍 / 👎.
| const mapped = mapAdminAuthError(error); | ||
| if (mapped) { | ||
| return res.status(mapped.status).json(mapped.body); |
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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 👍 / 👎.
|
Reply to this review: Both points were right.
|
aa7317d to
b2ef1e8
Compare
Related to AI-2415.
…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.
b2ef1e8 to
4d52096
Compare
Pull Request
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:
persistOpenIDAdminProviderSessionBinding) and puts it in the exchange code.exchangeAdminCodechecks the provider session before it returns tokens.The refresh sequence (prepare, grant, apply, and the error mapping) lives in
refreshAdminOpenIdSessioninpackages/api/src/auth/openid/providerSession/adminRefresh.ts. The route only wires its dependencies, and the integration spec calls the same function.A denial answers
401witherror_code: OPENID_SESSION_ENDED. An unavailable check answers503withAUTH_SESSION_CHECK_UNAVAILABLE.recordandenforcemean 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 / 503When the check is unavailable, the exchange code goes back into the cache with its remaining lifetime (
restoreCacheEntryfrom #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: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.invalid_grant,interaction_required,login_required,consent_required401 REFRESH_FAILED: the panel signs the admin outinvalid_client,unauthorized_client,unsupported_grant_type,invalid_scope,invalid_request500 OPENID_CLIENT_MISCONFIGURED, logged as an error: the server's OAuth client is wrong, and a retry cannot succeed503 AUTH_SESSION_CHECK_UNAVAILABLE: retryableConcurrent admin refreshes. Admin refreshes of one refresh token share a grant flight, like token-reuse refreshes in the main app.
401 OPENID_SESSION_ENDEDwhen it loses the flight. Without this, a retry with a spent token after a denial passed the precheck and received the recorded grant result.recordmode 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/refreshwas behindloginLimiter, 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 underrateLimits.adminRefresh: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:portsuffix 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, sologViolation, which counts per user, cannot record it./oauth/exchangestays onloginLimiter. The setting is documented inlibrechat.example.yaml.Type of change
Testing
Tested environments/configuration:
registration.openidBackchannelLogout.modeset torecordand toenforce, with OpenID login to the admin panel.Automated tests:
adminAuthErrors.spec.ts,providerSession/adminRefresh.spec.ts,providerSession/adminRefreshDeps.spec.ts,providerSession/binding.spec.tsandproviderSession/adminRefreshRecovery.integration.spec.ts.exchange.spec.ts,refresh.spec.ts,providerSession/callback.spec.ts,images/session.spec.tsandoauth.spec.js.api/server/routes/admin/auth.refresh.test.jsfor the admin route wiring and the separate limiter budget. The mapping table cases are inadminAuthErrors.spec.ts. The flight takeover after a thrown grant, the unbound retry and the Session-row write failure are inadminRefreshRecovery.integration.spec.ts.googleRefresh.spec.ts,middleware/adminRefreshLimiter.spec.ts(including the warning on a rejection), anddata-providerconfig.adminRefresh.spec.ts.Screenshots / recordings
No user-facing change in LibreChat. The admin panel receives the new
401and503responses.Risk / compatibility
offkeeps today's admin flow, and LibreChat stores no binding.recordmode allows it, andenforcemode denies it, the same as a legacy session.offhas no binding. After a switch toenforce, that session must sign in once.401 OPENID_SESSION_ENDEDas a sign-out and503 AUTH_SESSION_CHECK_UNAVAILABLEas retryable. It must also handle the new500 OPENID_CLIENT_MISCONFIGUREDas an error that a retry will not fix.off. A provider outage during admin refresh now answers 503 instead of401 REFRESH_FAILED. A panel that does not retry on 503 will show an error instead of signing the admin out.rateLimits.adminRefresh. Without it, renewal allows 30 requests per minute per IP. Before, it sharedloginLimiter's 7 per 5 minutes.Checklist