Skip to content

fix(auth): recover from expired-token 401s instead of hanging the UI - #31103

Merged
mohityadav766 merged 5 commits into
mainfrom
fix/auth-401-refresh-recovery
Aug 11, 2026
Merged

mohityadav766 merged 5 commits into
mainfrom
fix/auth-401-refresh-recovery

Conversation

@mohityadav766

Copy link
Copy Markdown
Member

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 background loggedInUser poll forced a logout → login up to a minute later. The server session was still valid the whole time; only the client-side 401 recovery failed.

Root cause

  • Orphaned request queue (primary): the Axios 401 interceptor queued the failed request in a module-level pendingRequests array, but only the request that starts the refresh drains the queue — and the "refresh already in progress?" gate read a cross-tab localStorage flag. 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() returned undefined to concurrent callers, which the interceptor treated as a failure and logged the user out even while a refresh was succeeding.
  • Logout used GET /api/v1/auth/logout, but the endpoint is POST-only (AuthLogoutServlet returns 405), so server-side logout never completed.
  • renewToken()'s status === 302 branch was dead code — browsers (XHR) auto-follow 3xx — so a refresh that redirected an expired session came back as a truthy body with an empty accessToken (false success → retry loop instead of clean redirect).
  • The backend returned 500, not 401, for an unknown JWT kid (MultiUrlJwkProvider wrapped SigningKeyNotFoundException in UnhandledServerException). 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 drains pendingRequests (retry every queued request on a new token, otherwise reject them and log out). Removes the cross-tab-flag branch that orphaned requests. Hardened the loggedInUser body 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 returning undefined.
  • LoginAPI.ts — logout via POST; renewToken() throws when the refresh response has no accessToken (dead 302 branch removed).
  • GenericAuthenticator.tsx — drop the now-unused navigate argument.
  • MultiUrlJwkProvider.java — return 401 (AuthenticationException) for an unknown signing-key id; keep 500 only for genuine server errors (e.g. a JWKS fetch failure).

Type of change

  • Bug fix (non-breaking change which fixes an issue)

How was this patch tested

  • UI (Jest) — affected suites green (33 tests):
    • TokenServiceUtil.test.ts: concurrent-refresh coalescing + sibling-tab wait (replaces the test that asserted the buggy undefined return).
    • AuthProvider.test.tsx: a normal 401 now refreshes the token and retries the request instead of hanging.
  • Backend (JUnit) — MultiUrlJwkProviderTest now asserts an unknown kid throws AuthenticationException (401), not UnhandledServerException (500).

Checklist

  • I have performed a self-review of my code
  • I have added unit tests that fail without this change
  • UI lint (ESLint + Prettier + organize-imports) and backend spotless:apply run clean

…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>
Copilot AI review requested due to automatic review settings August 6, 2026 10:56
@mohityadav766
mohityadav766 requested review from a team as code owners August 6, 2026 10:56
@github-actions

github-actions Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

This 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 skip-pr-checks label.

@github-actions github-actions Bot added backend safe to test Add this label to run secure Github workflows on PRs labels Aug 6, 2026
@github-actions

github-actions Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ UI Checkstyle passed — lint findings in changed files

🔍 ESLint findings in this PR's files — 0 error(s), 19 warning(s)

Errors block the build. Warnings do not yet — they are rules whose backlog is still
being worked down, listed so this PR does not add to it. See docs/ui-code-quality-gate.md.

0 error(s), 19 warning(s) across 2 changed file(s).

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-changed

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 kid to AuthenticationException (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.

Comment on lines +119 to +133
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;
Comment on lines +92 to +97
result =
AuthenticationException.getInvalidTokenException(
"Token signing key not found in configured public keys");
} else {
result = new UnhandledServerException(cacheException.getMessage());
}
@github-actions

github-actions Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Jest test Coverage

UI tests summary

Lines Statements Branches Functions
Coverage: 66%
66.22% (78161/118021) 50.22% (47205/93992) 51.44% (14224/27647)

…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>
Copilot AI review requested due to automatic review settings August 6, 2026 11:19
@mohityadav766

Copy link
Copy Markdown
Member Author

Thanks for the reviews — addressed the three code findings in a16c38f:

  • gitar-bot (null on a concurrent/locally-valid 401): the 401 interceptor now calls refreshToken(true) — a forced refresh skips the local-expiry short-circuit, so a token the server has rejected (clock skew / revocation) is actually refreshed instead of triggering a spurious logout.
  • Copilot (TokenServiceUtil.ts, void-returning silent renew): performRefresh now determines success by a persisted token change, not the renewer's return value — OIDC signInSilently resolves void and writes the token via an iframe side effect, which was being misread as a failure.
  • Copilot (MultiUrlJwkProvider.java): the underlying cause is now chained on both the AuthenticationException (401) and UnhandledServerException (500) paths, so genuine JWKS-fetch failures stay debuggable.

Added unit tests for the void-renew and forced-401 cases (TokenServiceUtil.test.ts); MultiUrlJwkProviderTest still green (6/6).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copilot AI review requested due to automatic review settings August 7, 2026 10:09

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 a SigningKeyNotFoundException (and only adds other JwkExceptions 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);
    }

Comment on lines 41 to 44
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`);

@sonarqubecloud

sonarqubecloud Bot commented Aug 7, 2026

Copy link
Copy Markdown

@mohityadav766
mohityadav766 added this pull request to the merge queue Aug 11, 2026
Merged via the queue into main with commit a9cf586 Aug 11, 2026
115 of 117 checks passed
@mohityadav766
mohityadav766 deleted the fix/auth-401-refresh-recovery branch August 11, 2026 08:25
@gitar-bot

gitar-bot Bot commented Aug 11, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 3 resolved / 3 findings

Hardens 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

📄 openmetadata-ui/src/main/resources/ui/src/utils/Auth/TokenService/TokenServiceUtil.ts:89-103 📄 openmetadata-ui/src/main/resources/ui/src/components/Auth/AuthProviders/AuthProvider.tsx:639-653
refreshToken() now coalesces every concurrent caller onto one inFlightRefresh promise, and performRefresh() returns null (a no-op) when the local token check finds it not-yet-expired (!isExpired && timeoutExpiry > 0). If the proactive expiry timer starts a refresh a moment before a genuine 401 arrives (e.g. client clock behind the server, so the token is valid locally but rejected server-side), the 401 interceptor coalesces onto that null-returning promise and treats null as failure — running drainPendingRequests(false) + resetUserDetails(true), i.e. a spurious logout instead of a real refresh. This is the exact hang/logout class the PR aims to fix. Consider having the interceptor distinguish 'no refresh needed' (null) from 'refresh failed', or force performRefresh to actually refresh when invoked from the 401 path.

✅ Bug: Slow token persistence now forces a logout instead of succeeding

📄 openmetadata-ui/src/main/resources/ui/src/utils/Auth/TokenService/TokenServiceUtil.ts:135-143 📄 openmetadata-ui/src/main/resources/ui/src/utils/Auth/TokenService/TokenServiceUtil.ts:187-201
Previously a persistence timeout only logged a warning and still returned the new token as success. The rewritten performRefresh now returns null when waitForTokenPersistence (bounded to ~1s: 20×50ms) does not observe the stored token change, which the 401/interceptor path treats as failure and logs the user out. A genuinely successful renew whose token write lags beyond 1s (slow ServiceWorker/IndexedDB write) will now cause a spurious logout where the old code recovered. Consider distinguishing a persistence timeout from a renew failure, or extending/retrying the persistence window before giving up.

✅ Edge Case: void-renewer non-persistence returns stale token (false success)

📄 openmetadata-ui/src/main/resources/ui/src/utils/Auth/TokenService/TokenServiceUtil.ts:131-138
On the success path, when the renewer resolves void (OIDC silent renew) but the new token never lands in storage, waitForTokenPersistence times out yet execution still falls through to return (await getOidcToken()) || renewResult. getOidcToken() returns the old, expired token (truthy), so the 401 interceptor treats it as success and retries the request — which 401s again, starts another refresh, and can loop indefinitely (~1s/iteration), reintroducing the very hang this PR fixes. It also fires refreshSuccessCallback and broadcasts REFRESHED_KEY='true' to sibling tabs when no refresh actually occurred. Track whether persistence succeeded and return null (clean logout) when a void renewer's token never lands.

Options

Display: compact → Showing less information.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Auth: expired-token 401 hangs the UI on a spinner instead of silently refreshing the session

5 participants