Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public static AuthenticationException getInvalidTokenException(String reason) {

public static AuthenticationException getInvalidTokenException(String reason, Exception e) {
String msg = String.format("Not Authorized! %s due to %s", reason, e);
return new AuthenticationException(msg);
return new AuthenticationException(msg, e);
}

public static AuthenticationException getExpiredTokenException() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.jetbrains.annotations.NotNull;
import org.openmetadata.service.exception.UnhandledServerException;
Expand Down Expand Up @@ -68,10 +70,33 @@ public MultiUrlJwkProvider(List<URL> publicKeyUris) {

@Override
public Jwk get(String keyId) {
Jwk signingKey;
try {
return CACHE.get(keyId);
} catch (Exception e) {
throw new UnhandledServerException(e.getMessage());
signingKey = CACHE.get(keyId);
} catch (ExecutionException | UncheckedExecutionException e) {
throw toAuthenticationOrServerException(e);
}
return signingKey;
}

private RuntimeException toAuthenticationOrServerException(Exception cacheException) {
Throwable cause =
cacheException.getCause() != null ? cacheException.getCause() : cacheException;
RuntimeException result;
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);
}
return result;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.openmetadata.service.security;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
Expand All @@ -19,7 +20,6 @@
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;
import org.mockito.MockedStatic;
import org.openmetadata.service.exception.UnhandledServerException;
import org.openmetadata.service.security.jwt.JWKSKey;
import org.openmetadata.service.security.jwt.JWKSResponse;
import org.openmetadata.service.security.jwt.JWTTokenGenerator;
Expand Down Expand Up @@ -85,7 +85,11 @@ void testLocalJwkProviderThrowsExceptionForNonMatchingKid() {
when(mockGenerator.getJWKSResponse()).thenReturn(jwksResponse);
mockedStatic.when(JWTTokenGenerator::getInstance).thenReturn(mockGenerator);
MultiUrlJwkProvider provider = new MultiUrlJwkProvider(List.of());
assertThrows(UnhandledServerException.class, () -> provider.get(UNKNOWN_KID));
// An unknown key id is an authentication failure (401), not a 500, and it
// must chain the underlying cause so server logs keep the real reason.
AuthenticationException ex =
assertThrows(AuthenticationException.class, () -> provider.get(UNKNOWN_KID));
assertInstanceOf(SigningKeyNotFoundException.class, ex.getCause());
}
}

Expand Down Expand Up @@ -125,7 +129,7 @@ void testFallbackToExternalProviderWhenLocalFails() throws Exception {
Jwk externalResult = provider.get(EXTERNAL_KID);
assertNotNull(externalResult);
assertEquals(EXTERNAL_KID, externalResult.getId());
assertThrows(UnhandledServerException.class, () -> provider.get(UNKNOWN_KID));
assertThrows(AuthenticationException.class, () -> provider.get(UNKNOWN_KID));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
* limitations under the License.
*/
import { forwardRef, Fragment, ReactNode, useImperativeHandle } from 'react';
import { useNavigate } from 'react-router-dom';
import { ROUTES } from '../../../constants/constants';
import { useApplicationStore } from '../../../hooks/useApplicationStore';
import { logoutUser, renewToken } from '../../../rest/LoginAPI';
Expand All @@ -22,7 +21,6 @@ export const GenericAuthenticator = forwardRef(
({ children }: { children: ReactNode }, ref) => {
const { setIsAuthenticated, setIsSigningUp } = useApplicationStore();
const { handleSuccessfulLogout } = useAuthProvider();
const navigate = useNavigate();

const handleLogin = () => {
setIsAuthenticated(false);
Expand All @@ -41,7 +39,7 @@ export const GenericAuthenticator = forwardRef(
};

const handleSilentSignIn = async () => {
const resp = await renewToken(navigate);
const resp = await renewToken();
await setOidcToken(resp.accessToken);

return resp;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ jest.mock('../../../hooks/useCustomLocation/useCustomLocation', () => {
});

jest.mock('react-router-dom', () => ({
useNavigate: jest.fn(),
useNavigate: jest.fn().mockReturnValue(jest.fn()),
}));

jest.mock('../../../rest/miscAPI', () => ({
Expand Down Expand Up @@ -494,4 +494,73 @@ describe('Test axios response interceptor', () => {
expect(mockRefreshToken).toHaveBeenCalledTimes(0);
}
});

it('should refresh the token and retry a normal 401 request', async () => {
const mockUse = jest.spyOn(axiosClient.interceptors.response, 'use');
const mockAxios = jest.fn().mockResolvedValue({ data: 'retried' });

jest.spyOn(axiosClient, 'request').mockImplementation(mockAxios);
mockRefreshToken.mockReset();
mockRefreshToken.mockResolvedValue('newToken');

await act(async () => {
render(<WrapperComponent />);
});

const [, errorHandler] = mockUse.mock.calls[0];
const mockError = {
response: {
status: 401,
data: { message: 'Expired token!' },
},
config: {
url: '/tables/name/foo',
headers: {},
baseURL: '',
},
};

const result = await errorHandler?.(mockError);

// The queued request is retried with the refreshed token, never left parked.
expect(mockRefreshToken).toHaveBeenCalled();
expect(mockAxios).toHaveBeenCalledWith(mockError.config);
expect(result).toEqual({ data: 'retried' });
});

it('should refresh loggedInUser on an unknown signing-key 401, not only on expiry', async () => {
const mockUse = jest.spyOn(axiosClient.interceptors.response, 'use');
const mockAxios = jest.fn().mockResolvedValue({ data: 'ok' });

jest.spyOn(axiosClient, 'request').mockImplementation(mockAxios);
mockRefreshToken.mockReset();
mockRefreshToken.mockResolvedValue('newToken');

await act(async () => {
render(<WrapperComponent />);
});

const [, errorHandler] = mockUse.mock.calls[0];
const mockError = {
response: {
status: 401,
data: {
message:
'Not Authorized! Token signing key not found in configured public keys',
},
},
config: {
url: '/users/loggedInUser',
headers: {},
baseURL: '',
},
};

const result = await errorHandler?.(mockError);

// IdP key-rotation 401 on the polled endpoint must refresh + retry, not log out.
expect(mockRefreshToken).toHaveBeenCalled();
expect(mockAxios).toHaveBeenCalledWith(mockError.config);
expect(result).toEqual({ data: 'ok' });
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { DEFAULT_APP_MODE } from '../../../constants/appMode.constants';
import { UN_AUTHORIZED_EXCLUDED_PATHS } from '../../../constants/Auth.constants';
import {
REFRESHABLE_AUTH_ERRORS,
UN_AUTHORIZED_EXCLUDED_PATHS,
} from '../../../constants/Auth.constants';
import {
APP_ROUTER_ROUTES as ROUTES,
REDIRECT_PATHNAME,
Expand Down Expand Up @@ -128,6 +131,12 @@
config: InternalAxiosRequestConfig<unknown>;
}[] = [];

// True while THIS tab is driving a token refresh and draining `pendingRequests`.
// Kept in memory (not the cross-tab localStorage flag) so a sibling tab's
// refresh can never leave this tab's queued 401s without a driver to settle
// them — the bug that hung the UI on a spinner.
let isRefreshDriverActive = false;

type AuthContextType = {
onLoginHandler: () => void;
onLogoutHandler: () => void;
Expand Down Expand Up @@ -181,7 +190,7 @@

const clientType = authConfig?.clientType ?? ClientType.Public;

const onLoginHandler = () => {

Check warning on line 193 in openmetadata-ui/src/main/resources/ui/src/components/Auth/AuthProviders/AuthProvider.tsx

View workflow job for this annotation

GitHub Actions / checkstyle

The 'onLoginHandler' function makes the dependencies of useMemo Hook (at line 824) change on every render. Move it inside the useMemo callback. Alternatively, wrap the definition of 'onLoginHandler' in its own useCallback() Hook
setApplicationLoading(true);

let attempts = 0;
Expand Down Expand Up @@ -253,7 +262,7 @@

// Upon logout, redirect to the login page
navigate(ROUTES.SIGNIN);
}, [timeoutId]);

Check warning on line 265 in openmetadata-ui/src/main/resources/ui/src/components/Auth/AuthProviders/AuthProvider.tsx

View workflow job for this annotation

GitHub Actions / checkstyle

React Hook useCallback has missing dependencies: 'navigate', 'setApplicationLoading', 'setCurrentUser', and 'setIsAuthenticated'. Either include them or remove the dependency array

const handledVerifiedUser = () => {
if (!applicationRoutesClass.isProtectedRoute(location.pathname)) {
Expand Down Expand Up @@ -311,7 +320,7 @@
});
}, []);

const resetUserDetails = (forceLogout = false) => {

Check warning on line 323 in openmetadata-ui/src/main/resources/ui/src/components/Auth/AuthProviders/AuthProvider.tsx

View workflow job for this annotation

GitHub Actions / checkstyle

The 'resetUserDetails' function makes the dependencies of useMemo Hook (at line 824) change on every render. To fix this, wrap the definition of 'resetUserDetails' in its own useCallback() Hook
setCurrentUser({} as User);
clearOidcToken();
setIsAuthenticated(false);
Expand Down Expand Up @@ -392,7 +401,7 @@
// After every refresh success, start timer again
tokenService.current.updateRefreshSuccessCallback(startTokenExpiryTimer);
}
}, [authenticatorRef.current?.renewIdToken]);

Check warning on line 404 in openmetadata-ui/src/main/resources/ui/src/components/Auth/AuthProviders/AuthProvider.tsx

View workflow job for this annotation

GitHub Actions / checkstyle

React Hook useEffect has a missing dependency: 'startTokenExpiryTimer'. Either include it or remove the dependency array

// When the tab becomes visible after being backgrounded, browsers may have
// throttled or suspended the proactive renewal timer. Check token freshness
Expand Down Expand Up @@ -435,7 +444,7 @@
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, []);

Check warning on line 447 in openmetadata-ui/src/main/resources/ui/src/components/Auth/AuthProviders/AuthProvider.tsx

View workflow job for this annotation

GitHub Actions / checkstyle

React Hook useEffect has a missing dependency: 'startTokenExpiryTimer'. Either include it or remove the dependency array

/**
* Performs cleanup around timers
Expand All @@ -445,7 +454,7 @@
clearTimeout(timeoutId);
}, [timeoutId]);

const handleFailedLogin = () => {

Check warning on line 457 in openmetadata-ui/src/main/resources/ui/src/components/Auth/AuthProviders/AuthProvider.tsx

View workflow job for this annotation

GitHub Actions / checkstyle

The 'handleFailedLogin' function makes the dependencies of useMemo Hook (at line 824) change on every render. Move it inside the useMemo callback. Alternatively, wrap the definition of 'handleFailedLogin' in its own useCallback() Hook
setIsSigningUp(false);
setIsAuthenticated(false);
setApplicationLoading(false);
Expand Down Expand Up @@ -502,7 +511,7 @@
setApplicationLoading(false);
}
},
[

Check warning on line 514 in openmetadata-ui/src/main/resources/ui/src/components/Auth/AuthProviders/AuthProvider.tsx

View workflow job for this annotation

GitHub Actions / checkstyle

React Hook useCallback has missing dependencies: 'authConfig?.provider', 'handledVerifiedUser', 'navigate', 'resetUserDetails', and 'startTokenExpiryTimer'. Either include them or remove the dependency array
authConfig?.enableSelfSignup,
clientType,
authorizerConfig?.principalDomain,
Expand Down Expand Up @@ -593,67 +602,61 @@
if (
UN_AUTHORIZED_EXCLUDED_PATHS.includes(error.config.url) ||
(error.config.url === '/users/loggedInUser' &&
!error.response.data.message.includes('Expired token!'))
!REFRESHABLE_AUTH_ERRORS.some((authError) =>
(error.response.data?.message ?? '').includes(authError)
))
) {
throw error;
}
handleStoreProtectedRedirectPath();

// If 401 error and refresh is not in progress, trigger the refresh
if (tokenService.current?.isTokenUpdateInProgress()) {
// If refresh is in progress, queue the request
return new Promise((resolve, reject) => {
pendingRequests.push({
resolve,
reject,
config: error.config,
});
});
} else {
// Start the refresh process
return new Promise((resolve, reject) => {
// Add this request to the pending queue
pendingRequests.push({
resolve,
reject,
config: error.config,
});

// Reject every queued 401'd request with the given error and
// clear the queue. Called on any path where the refresh does
// not yield a new token (null-return or thrown error) so the
// callers don't hang waiting for a retry that will never come.
const rejectPending = (rejectionError: unknown) => {
pendingRequests.forEach(({ reject }) =>
reject(rejectionError)
// Queue the failed request, then ensure exactly one refresh drives
// the queue in THIS tab. Every 401 lands in pendingRequests; the
// first arrival starts the refresh and, once it settles, ALWAYS
// drains the queue — retry with the new token, or reject + log out.
// Nothing is left parked. The previous code queued behind a
// cross-tab localStorage flag that no in-tab driver would clear,
// hanging the request (and the UI spinner) indefinitely.
return new Promise((resolve, reject) => {
pendingRequests.push({ resolve, reject, config: error.config });
if (isRefreshDriverActive) {
return;
}
isRefreshDriverActive = true;

const drainPendingRequests = (hasNewToken: boolean) => {
const queued = pendingRequests;
pendingRequests = [];
isRefreshDriverActive = false;
if (hasNewToken) {
queued.forEach(
({ resolve: onResolve, reject: onReject, config }) =>

Check failure on line 633 in openmetadata-ui/src/main/resources/ui/src/components/Auth/AuthProviders/AuthProvider.tsx

View check run for this annotation

SonarQubeCloud / [open-metadata-ui] SonarCloud Code Analysis

Refactor this code to not nest functions more than 5 levels deep.

See more on https://sonarcloud.io/project/issues?id=open-metadata-ui&issues=AZ_WxmPZeGWW4WieKuf8&open=AZ_WxmPZeGWW4WieKuf8&pullRequest=31103
axiosClient
.request(config)
.then(onResolve)
.catch(onReject)
);
pendingRequests = [];
};

// Refresh the token and retry the requests in the queue
tokenService.current
.refreshToken()
.then(async (token) => {
if (token) {
// Retry the pending requests
await initializeAxiosInterceptors();
pendingRequests.forEach(({ resolve, reject, config }) => {
axiosClient.request(config).then(resolve).catch(reject);
});

// Clear the queue after retrying
pendingRequests = [];
} else {
rejectPending(error);
resetUserDetails(true);
}
})
.catch((refreshError) => {
rejectPending(refreshError);
} else {
queued.forEach(({ reject: onReject }) => onReject(error));
}
};

tokenService.current
.refreshToken()
.then(async (token) => {
if (token) {
await initializeAxiosInterceptors();
drainPendingRequests(true);
} else {
drainPendingRequests(false);
resetUserDetails(true);
});
});
}
}
})
.catch(() => {
drainPendingRequests(false);
resetUserDetails(true);
});
});
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,13 @@ export const UN_AUTHORIZED_EXCLUDED_PATHS = [
'/auth/refresh',
'/users/login',
];

// 401 messages on the polled `/users/loggedInUser` that a silent token refresh
// can actually fix (so the interceptor should refresh rather than log out).
// Kept as substrings to match the backend's `Not Authorized! ...` wrapping.
export const REFRESHABLE_AUTH_ERRORS = [
'Expired token!',
// Unknown JWT signing-key id (IdP key rotation / stale token) — a refresh
// mints a token signed with a currently-published key.
'Token signing key not found',
];
Comment thread
chirag-madlani marked this conversation as resolved.
Resolved
Loading
Loading