Repository navigation
fix(auth): recover from expired-token 401s instead of hanging the UI - #31103
Conversation
…31102) When an access token expires mid-session, the first 401'd request could be parked forever (spinner, no redirect): the Axios interceptor queued it behind a cross-tab localStorage "refresh in progress" flag that no in-tab driver would ever drain, and refreshToken() returned undefined to concurrent callers. - interceptor: a single in-tab refresh driver that ALWAYS drains pendingRequests (retry on new token, else reject + logout) — nothing is left parked - TokenService.refreshToken(): coalesce concurrent refreshes into one in-flight promise; wait for a sibling tab instead of racing it or returning undefined - LoginAPI: logout via POST (GET /auth/logout returns 405); renewToken throws when the refresh response has no access token (drop the dead 302 check) - backend: MultiUrlJwkProvider returns 401 (AuthenticationException) for an unknown signing-key id, keeping 500 only for genuine server errors Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
❌ PR checklist incompleteThis PR cannot be merged until the following are addressed on its linked issue:
The fields live on the linked issue in the Shipping project (open the issue → right sidebar → Projects). After you set them, re-run this check (or push a commit) — issue/project changes do not re-trigger it automatically. Maintainers can bypass this check by adding the |
|
| Count | Rule |
|---|---|
| 9 | react-hooks/exhaustive-deps |
| 4 | i18next/no-literal-string |
| 3 | sonarjs/no-nested-functions |
| 2 | sonarjs/no-duplicate-string |
| 1 | sonarjs/cyclomatic-complexity |
All findings
| Location | Rule | Message | |
|---|---|---|---|
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.test.tsx:123:71 |
i18next/no-literal-string |
disallow literal string: Logout |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.test.tsx:143:75 |
i18next/no-literal-string |
disallow literal string: Logout |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.test.tsx:175:14 |
i18next/no-literal-string |
disallow literal string: <button data-testid="login-button" onClick={() => { expect(typeof onLoginHandler).toBe('function'); onLoginHandler(); }}> Login </butto |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.test.tsx:195:17 |
i18next/no-literal-string |
disallow literal string: ConsumerComponent |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.test.tsx:242:26 |
sonarjs/no-duplicate-string |
Define a constant instead of duplicating this literal 8 times. |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.test.tsx:452:14 |
sonarjs/no-duplicate-string |
Define a constant instead of duplicating this literal 3 times. |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.tsx:193:9 |
react-hooks/exhaustive-deps |
The 'onLoginHandler' function makes the dependencies of useMemo Hook (at line 824) change on every render. Move it inside the useMemo callback. Alternatively, w |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.tsx:265:6 |
react-hooks/exhaustive-deps |
React Hook useCallback has missing dependencies: 'navigate', 'setApplicationLoading', 'setCurrentUser', and 'setIsAuthenticated'. Either include them or remove |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.tsx:323:9 |
react-hooks/exhaustive-deps |
The 'resetUserDetails' function makes the dependencies of useMemo Hook (at line 824) change on every render. To fix this, wrap the definition of 'resetUserDetai |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.tsx:404:6 |
react-hooks/exhaustive-deps |
React Hook useEffect has a missing dependency: 'startTokenExpiryTimer'. Either include it or remove the dependency array. |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.tsx:447:6 |
react-hooks/exhaustive-deps |
React Hook useEffect has a missing dependency: 'startTokenExpiryTimer'. Either include it or remove the dependency array. |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.tsx:457:9 |
react-hooks/exhaustive-deps |
The 'handleFailedLogin' function makes the dependencies of useMemo Hook (at line 824) change on every render. Move it inside the useMemo callback. Alternatively |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.tsx:514:5 |
react-hooks/exhaustive-deps |
React Hook useCallback has missing dependencies: 'authConfig?.provider', 'handledVerifiedUser', 'navigate', 'resetUserDetails', and 'startTokenExpiryTimer'. Eit |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.tsx:559:9 |
react-hooks/exhaustive-deps |
The 'initializeAxiosInterceptors' function makes the dependencies of useMemo Hook (at line 824) change on every render. To fix this, wrap the definition of 'ini |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.tsx:627:67 |
sonarjs/no-nested-functions |
Refactor this code to not nest functions more than 4 levels deep. |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.tsx:646:37 |
sonarjs/no-nested-functions |
Refactor this code to not nest functions more than 4 levels deep. |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.tsx:655:27 |
sonarjs/no-nested-functions |
Refactor this code to not nest functions more than 4 levels deep. |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.tsx:724:30 |
sonarjs/cyclomatic-complexity |
{"message":"Function has a complexity of 17 which is greater than 10 authorized.","cost":7,"secondaryLocations":[{"line":724,"column":29,"endLine":724,"endColum |
| 🟡 | src/components/Auth/AuthProviders/AuthProvider.tsx:813:6 |
react-hooks/exhaustive-deps |
React Hook useEffect has missing dependencies: 'cleanup', 'fetchAuthConfig', 'initializeAxiosInterceptors', and 'startTokenExpiryTimer'. Either include them or |
Fix locally (fast - only checks files changed in this branch):
make ui-checkstyle-changedThere was a problem hiding this comment.
Pull request overview
This PR improves auth resilience when an access token expires mid-session by ensuring the UI reliably refreshes tokens, retries queued requests (instead of hanging), and cleanly falls back to logout when refresh cannot succeed. It also aligns backend JWT key-resolution failures with a 401 response so the UI can treat key-rotation/stale-token scenarios as auth failures rather than fatal server errors.
Changes:
- Reworked the UI 401 interceptor flow to always drain/reject the queued requests from a single in-tab refresh “driver”.
- Updated token refresh/logout utilities to coalesce concurrent refreshes, wait (bounded) for sibling-tab refreshes, use POST logout, and treat “refresh without accessToken” as a failure.
- Backend: map unknown JWT
kidtoAuthenticationException(401) and updated tests accordingly.
Reviewed changes
Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| openmetadata-ui/src/main/resources/ui/src/utils/Auth/TokenService/TokenServiceUtil.ts | Coalesces concurrent refreshes and adds bounded sibling-tab wait logic for refresh coordination. |
| openmetadata-ui/src/main/resources/ui/src/utils/Auth/TokenService/TokenServiceUtil.test.ts | Updates/expands Jest coverage for concurrent refresh coalescing and sibling-tab refresh wait. |
| openmetadata-ui/src/main/resources/ui/src/rest/LoginAPI.ts | Uses POST for logout; renewToken now throws when accessToken is missing (removes dead 302 logic). |
| openmetadata-ui/src/main/resources/ui/src/components/Auth/AuthProviders/AuthProvider.tsx | Ensures 401 recovery uses a single in-tab refresh driver and always drains queued requests. |
| openmetadata-ui/src/main/resources/ui/src/components/Auth/AuthProviders/AuthProvider.test.tsx | Adds a test verifying a normal 401 triggers refresh and retries (no parked spinner). |
| openmetadata-ui/src/main/resources/ui/src/components/Auth/AppAuthenticators/GenericAuthenticator.tsx | Adapts to renewToken signature change (drops now-unused navigate argument). |
| openmetadata-service/src/main/java/org/openmetadata/service/security/MultiUrlJwkProvider.java | Converts unknown kid to 401 while preserving 500 for genuine server failures. |
| openmetadata-service/src/test/java/org/openmetadata/service/security/MultiUrlJwkProviderTest.java | Updates assertions to expect AuthenticationException on unknown kid. |
| this.setRefreshInProgress(); | ||
| const newToken = await this.fetchNewToken(); | ||
| if (newToken) { | ||
| // Wait for the new token to be persisted in SW+IndexedDB before notifying. | ||
| const persisted = await this.waitForTokenPersistence(oldToken); | ||
| if (!persisted) { | ||
| // eslint-disable-next-line no-console | ||
| console.warn('Token persistence timed out, proceeding with callback'); | ||
| } | ||
| this.refreshSuccessCallback?.(); | ||
| // Notify all tabs that the token has been refreshed. | ||
| localStorage.setItem(REFRESHED_KEY, 'true'); | ||
| } | ||
|
|
||
| return newToken; |
| result = | ||
| AuthenticationException.getInvalidTokenException( | ||
| "Token signing key not found in configured public keys"); | ||
| } else { | ||
| result = new UnhandledServerException(cacheException.getMessage()); | ||
| } |
…ss, keep cause Follow-up to the review on #31103: - TokenService.refreshToken(force): the 401 interceptor now forces a refresh so a token that only looks valid locally (clock skew / server-side revocation) is refreshed instead of short-circuiting to null and logging the user out. - performRefresh detects success by a persisted token change, not the renewer's return value — OIDC silent renew resolves void and writes the token via an iframe side effect, which was being misread as a failure (→ logout). - MultiUrlJwkProvider chains the underlying cause (AuthenticationException and UnhandledServerException) so server-side JWKS failures stay debuggable. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
Thanks for the reviews — addressed the three code findings in a16c38f:
Added unit tests for the void-renew and forced-401 cases ( |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 8 out of 8 changed files in this pull request and generated no new comments.
Suppressed comments (1)
openmetadata-ui/src/main/resources/ui/src/utils/Auth/TokenService/TokenServiceUtil.ts:107
- The inline comment uses the term "ponytail", which is unclear and reads like an accidental placeholder. Please rephrase to a more standard note explaining the bounded (~1s) wait for a sibling tab refresh.
// Another tab is already refreshing: wait for it to broadcast a new token
// rather than racing a second /auth/refresh (which would rotate the refresh
// token out from under the first request and 401 this tab).
// ponytail: waits ~1s for the sibling then returns null so the caller logs
// out cleanly — never an unbounded hang. Add cross-tab leader election if
// multi-tab refresh churn ever shows up.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 10 out of 10 changed files in this pull request and generated 1 comment.
Suppressed comments (1)
openmetadata-service/src/main/java/org/openmetadata/service/security/MultiUrlJwkProvider.java:100
CacheLoader.load()always throws aSigningKeyNotFoundException(and only adds otherJwkExceptions as suppressed). With the new mapping, that means JWKS endpoint fetch failures can also be reported as 401, even though the comment says those should remain 500.
Consider treating SigningKeyNotFoundException as 401 only when all suppressed exceptions are also SigningKeyNotFoundException; otherwise return UnhandledServerException so genuine JWKS retrieval failures still surface as 500.
if (cause instanceof SigningKeyNotFoundException signingKeyNotFound) {
// Unknown key id means the token was signed by a key we do not trust (IdP
// key rotation, wrong issuer, a stale token). That is an authentication
// failure (401), not a server error (500) — returning 500 makes the client
// treat a re-authenticable session as a fatal error and hang instead of
// refreshing or redirecting to login.
result =
AuthenticationException.getInvalidTokenException(
"Token signing key not found in configured public keys", signingKeyNotFound);
} else {
// Genuine server-side failure (e.g. a JWKS endpoint fetch error); keep the
// cause chained so production logs show the real reason.
result = new UnhandledServerException("JWKS key resolution failed", cause);
}
| export const logoutUser = async () => { | ||
| const response = await axiosClient.get(`${BASE_URL}/logout`); | ||
| // Logout is exposed as POST only; a GET returns 405 (see AuthLogoutServlet). | ||
| const response = await axiosClient.post(`${BASE_URL}/logout`); | ||
|
|
|
Code Review ✅ Approved 3 resolved / 3 findingsHardens token refresh and 401 interceptor recovery in AuthProvider and TokenServiceUtil, addressing the coalesced refresh returning null, slow token persistence logout, and void-renewer non-persistence findings. All findings resolved successfully. ✅ 3 resolved✅ Edge Case: Coalesced refresh can return null to a concurrent 401 caller
✅ Bug: Slow token persistence now forces a logout instead of succeeding
✅ Edge Case: void-renewer non-persistence returns stale token (false success)
OptionsDisplay: compact → Showing less information. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source |



Describe your changes
Fixes #31102.
When an access token (JWT) expires mid-session, the first API request after expiry returns
401. The UI is supposed to silently refresh the token and retry the request, but the failed request could be parked indefinitely — a spinner with no redirect — until an unrelated backgroundloggedInUserpoll forced alogout → loginup to a minute later. The server session was still valid the whole time; only the client-side 401 recovery failed.Root cause
pendingRequestsarray, but only the request that starts the refresh drains the queue — and the "refresh already in progress?" gate read a cross-tablocalStorageflag. When that flag was set by another tab, or left stale by a prior refresh, every 401 took the "just queue it" branch and nothing ever drained it, so the request promise never settled.refreshToken()returnedundefinedto concurrent callers, which the interceptor treated as a failure and logged the user out even while a refresh was succeeding.GET /api/v1/auth/logout, but the endpoint isPOST-only (AuthLogoutServletreturns405), so server-side logout never completed.renewToken()'sstatus === 302branch was dead code — browsers (XHR) auto-follow 3xx — so a refresh that redirected an expired session came back as a truthy body with an emptyaccessToken(false success → retry loop instead of clean redirect).kid(MultiUrlJwkProviderwrappedSigningKeyNotFoundExceptioninUnhandledServerException). The UI only recovers on 401, so IdP key-rotation / stale-token cases surfaced as a hard error.Changes
AuthProvider.tsx— a single in-tab refresh driver that always drainspendingRequests(retry every queued request on a new token, otherwise reject them and log out). Removes the cross-tab-flag branch that orphaned requests. Hardened theloggedInUserbody check with optional chaining.TokenServiceUtil.ts—refreshToken()coalesces concurrent refreshes into one in-flight promise, and waits (bounded) for a sibling tab's refresh instead of racing it or returningundefined.LoginAPI.ts— logout viaPOST;renewToken()throws when the refresh response has noaccessToken(dead 302 branch removed).GenericAuthenticator.tsx— drop the now-unusednavigateargument.MultiUrlJwkProvider.java— return401(AuthenticationException) for an unknown signing-key id; keep500only for genuine server errors (e.g. a JWKS fetch failure).Type of change
How was this patch tested
TokenServiceUtil.test.ts: concurrent-refresh coalescing + sibling-tab wait (replaces the test that asserted the buggyundefinedreturn).AuthProvider.test.tsx: a normal 401 now refreshes the token and retries the request instead of hanging.MultiUrlJwkProviderTestnow asserts an unknownkidthrowsAuthenticationException(401), notUnhandledServerException(500).Checklist
spotless:applyrun clean