8000 Show a Forbidden page for Account Console 401/403 API errors by edewit · Pull Request #55664 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
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
2 changes: 2 additions & 0 deletions js/apps/account-ui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import { KeycloakProvider } from "@keycloak/keycloak-ui-shared";
</KeycloakProvider>
```

`KeycloakProvider` includes an `ErrorBoundaryProvider`. To show the Account Console Forbidden / unexpected-error dialog for API failures, also wrap the tree in `ErrorBoundaryFallback` with your fallback UI (as the built-in Account Console does with `ErrorRenderer`).

### Translation

For the translation we use `react-i18next` you can [set it up](https://react.i18next.com/) as described on their website.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ error-invalid-value='{{0}}' has invalid value.
pageNotFound=The requested page was not found.
somethingWentWrong=Something went wrong
somethingWentWrongDescription=Sorry, an unexpected error has occurred.
forbidden=Forbidden
needAccessRights=You do not have access rights to this request. Contact your administrator.
tryAgain=Try again
rolesScope=If there is no role scope mapping defined, each user is permitted to use this client scope. If there are role scope mappings defined, the user must be a member of at least one of the roles.
unShareError=Could not un-share the resource due to\: {{error}}
Expand Down
23 changes: 19 additions & 4 deletions js/apps/account-ui/src/api/parse-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import { CONTENT_TYPE_HEADER, CONTENT_TYPE_JSON } from "./constants";

export class ApiError extends Error {
description?: string;
status: number;

constructor(message: string, description?: string) {
constructor(message: string, status: number, description?: string) {
super(message);
this.status = status;
this.description = description;
}
}
Expand All @@ -18,8 +20,9 @@ export async function parseResponse<T>(response: Response): Promise<T> {
const isJSON = contentType ? contentType.includes(CONTENT_TYPE_JSON) : false;

if (!isJSON) {
throw new Error(
throw new ApiError(
`Expected response to have a JSON content type, got '${contentType}' instead.`,
response.status,
);
}

Expand All @@ -30,12 +33,13 @@ export async function parseResponse<T>(response: Response): Promise<T> {
const description = getNetworkErrorDescription(data);

if (!message) {
throw new Error(
throw new ApiError(
"Unable to retrieve error message from response, no matching key found.",
response.status,
Comment thread
Copilot marked this conversation as resolved.
Resolved
);
}

throw new ApiError(message, description);
throw new ApiError(message, response.status, description);
}

return data as T;
Expand All @@ -45,6 +49,17 @@ async function parseJSON(response: Response): Promise<unknown> {
try {
return await response.json();
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
throw error;
}

if (!response.ok) {
throw new ApiError(
"Unable to parse response as valid JSON.",
response.status,
);
}

throw new Error("Unable to parse response as valid JSON.", {
cause: error,
});
Expand Down
10 changes: 8 additions & 2 deletions js/apps/account-ui/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import "@patternfly/patternfly/patternfly-addons.css";
import "@patternfly/react-core/dist/styles/base.css";

import { KeycloakProvider } from "@keycloak/keycloak-ui-shared";
import {
ErrorBoundaryFallback,
KeycloakProvider,
} from "@keycloak/keycloak-ui-shared";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { environment } from "./environment";
import { i18n } from "./i18n";
import { ErrorRenderer } from "./root/ErrorRenderer";
import { Root } from "./root/Root";

// Initialize required components before rendering app.
Expand All @@ -17,7 +21,9 @@ const root = createRoot(container!);
root.render(
<StrictMode>
<KeycloakProvider environment={environment}>
<Root />
<ErrorBoundaryFallback fallback={ErrorRenderer}>
<Root />
</ErrorBoundaryFallback>
</KeycloakProvider>
</StrictMode>,
);
25 changes: 11 additions & 14 deletions js/apps/account-ui/src/organizations/Organizations.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import OrganizationRepresentation from "@keycloak/keycloak-admin-client/lib/defs/organizationRepresentation";
import {
ErrorBoundaryProvider,
KeycloakSpinner,
ListEmptyState,
OrganizationTable,
Expand Down Expand Up @@ -30,19 +29,17 @@ export const Organizations = () => {

return (
<Page title={t("organizations")} description={t("organizationDescription")}>
<ErrorBoundaryProvider>
<OrganizationTable
link={({ children }) => <span>{children}</span>}
loader={userOrgs}
compactToolbar
searchPlaceholderKey="filterByName"
>
<ListEmptyState
message={t("emptyUserOrganizations")}
instructions={t("emptyUserOrganizationsInstructions")}
/>
</OrganizationTable>
</ErrorBoundaryProvider>
<OrganizationTable
link={({ children }) => <span>{children}</span>}
loader={userOrgs}
compactToolbar
searchPlaceholderKey="filterByName"
>
Comment on lines +32 to +37
<ListEmptyState
message={t("emptyUserOrganizations")}
instructions={t("emptyUserOrganizationsInstructions")}
/>
</OrganizationTable>
</Page>
);
};
Expand Down
78 changes: 78 additions & 0 deletions js/apps/account-ui/src/root/ErrorRenderer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import {
useEnvironment,
type FallbackProps,
} from "@keycloak/keycloak-ui-shared";
import {
Button,
Content,
Modal,
ModalBody,
ModalFooter,
ModalHeader,
ModalVariant,
Page,
} from "@patternfly/react-core";
import { useTranslation } from "react-i18next";
import { ApiError } from "../api/parse-response";

function getHttpStatus(error: Error): number | undefined {
if (error instanceof ApiError) {
return error.status;
}

if ("status" in error && typeof error.status === "number") {
return error.status;
}

return undefined;
}

export const ErrorRenderer = ({ error }: FallbackProps) => {
const { t } = useTranslation();
const { keycloak } = useEnvironment();
const status = getHttpStatus(error);
const isPermissionError = status === 401 || status === 403;
const title = t(isPermissionError ? "forbidden" : "somethingWentWrong");

console.error(error);

return (
<Page>
<Modal variant={ModalVariant.small} isOpen aria-label={title}>
<ModalHeader title={title} titleIconVariant="danger" />
<ModalBody>
<Content>
<Content component="p">
{t(
isPermissionError
? "needAccessRights"
: "somethingWentWrongDescription",
)}
</Content>
</Content>
</ModalBody>
<ModalFooter>
{isPermissionError ? (
<Button
key="signOut"
variant="primary"
=> keycloak.logout()}
>
{t("signOut")}
</Button>
) : (
<Button
key="tryAgain"
variant="primary"
=> {
location.href = location.origin + location.pathname;
}}
>
{t("tryAgain")}
</Button>
)}
</ModalFooter>
</Modal>
</Page>
);
};
31 changes: 24 additions & 7 deletions js/apps/account-ui/src/utils/usePromise.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useOptionalErrorBoundary } from "@keycloak/keycloak-ui-shared";
import type { DependencyList } from "react";
import { useEffect, useState } from "react";

Expand Down Expand Up @@ -38,6 +39,10 @@
* usePromise((signal) => fetch(`/api/products/${id}`, { signal }).then((res) => res.json()), setProduct, [id]);
* ```
*
* When an ErrorBoundaryProvider is present, failures are reported through it.
* Without a provider, failures are rethrown during render so KeycloakProvider-only
* consumers keep working.
*
* @param factory Function that creates the Promise.
* @param callback Function that gets called with the value of the Promise when it resolves.
* @param deps If present, Promise will be recreated if the values in the list change.
Expand All @@ -47,32 +52,44 @@
callback: PromiseResolvedFn<T>,
deps: DependencyList = [],
) {
const errorBoundary = useOptionalErrorBoundary();
const [error, setError] = useState<unknown>();

useEffect(() => {
const controller = new AbortController();
const { signal } = controller;

async function handlePromise() {
// Try to resolve the Promise, if it fails, check if it was aborted.
try {
callback(await factory(signal));
} catch (error) {
// Ignore errors caused by aborting the Promise.
if (error instanceof Error && error.name === "AbortError") {
} catch (caught) {
// Ignore failures from aborted requests, including JSON parse wrapping.
if (signal.aborted) {
return;
}

if (caught instanceof Error && caught.name === "AbortError") {
return;
}

const nextError =
caught instanceof Error ? caught : new Error(String(caught));

if (errorBoundary) {
errorBoundary.showBoundary(nextError);
return;
}

setError(error);
setError(nextError);
}
}

void handlePromise();

// Abort the Promise when the component unmounts, or the dependencies change.
return () => controller.abort();
}, deps);

Check warning on line 90 in js/apps/account-ui/src/utils/usePromise.ts

View workflow job for this annotation

GitHub Actions / Account UI

React Hook useEffect has missing dependencies: 'callback', 'errorBoundary', and 'factory'. Either include them or remove the dependency array. If 'callback' changes too often, find the parent component that defines it and wrap that definition in useCallback

Check warning on line 90 in js/apps/account-ui/src/utils/usePromise.ts

View workflow job for this annotation

GitHub Actions / Account UI

React Hook useEffect was passed a dependency list that is not an array literal. This means we can't statically verify whether you've passed the correct dependencies

// Rethrow other errors.
// Rethrow when no error boundary is present (library / quickstart consumers).
if (error) {
throw error;
}
Expand Down
29 changes: 13 additions & 16 deletions js/apps/admin-ui/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
ErrorBoundaryFallback,
ErrorBoundaryProvider,
KeycloakSpinner,
mainPageContentId,
} from "@keycloak/keycloak-ui-shared";
Expand All @@ -22,21 +21,19 @@
import { Banners } from "./Banners";

export const AppContexts = ({ children }: PropsWithChildren) => (
<ErrorBoundaryProvider>
<ErrorBoundaryFallback fallback={ErrorRenderer}>
<ServerInfoProvider>
<RealmContextProvider>
<WhoAmIContextProvider>
<RecentRealmsProvider>
<AccessContextProvider>
<SubGroups>{children}</SubGroups>
</AccessContextProvider>
</RecentRealmsProvider>
</WhoAmIContextProvider>
</RealmContextProvider>
</ServerInfoProvider>
</ErrorBoundaryFallback>
</ErrorBoundaryProvider>
<ErrorBoundaryFallback fallback={ErrorRenderer}>
<ServerInfoProvider>
<RealmContextProvider>
<WhoAmIContextProvider>
<RecentRealmsProvider>
<AccessContextProvider>
<SubGroups>{children}</SubGroups>
</AccessContextProvider>
</RecentRealmsProvider>
</WhoAmIContextProvider>
</RealmContextProvider>
</ServerInfoProvider>
</ErrorBoundaryFallback>
);

export const App = () => {
Expand All @@ -44,7 +41,7 @@
useEffect(() => {
if (!hrefEndsWithHashSlash) return;
history.replaceState(null, "", location.pathname);
}, [hrefEndsWithHashSlash, location.pathname]);

Check warning on line 44 in js/apps/admin-ui/src/App.tsx

View workflow job for this annotation

GitHub Actions / Admin UI

React Hook useEffect has an unnecessary dependency: 'location.pathname'. Either exclude it or remove the dependency array. Outer scope values like 'location.pathname' aren't valid dependencies because mutating them doesn't re-render the component

return (
<AdminClientProvider>
Expand Down
1 change: 1 addition & 0 deletions js/libs/ui-shared-pf6/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export { KeycloakSpinner } from "./controls/KeycloakSpinner";
export { useFetch } from "./utils/useFetch";
export {
useErrorBoundary,
useOptionalErrorBoundary,
ErrorBoundaryFallback,
ErrorBoundaryProvider,
} from "./utils/ErrorBoundary";
Expand Down
3 changes: 3 additions & 0 deletions js/libs/ui-shared-pf6/src/utils/ErrorBoundary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
type FunctionComponent,
type GetDerivedStateFromError,
type ReactNode,
useContext,
} from "react";
import { createNamedContext } from "./createNamedContext";
import { useRequiredContext } from "./useRequiredContext";
Expand All @@ -19,6 +20,8 @@ const ErrorBoundaryContext = createNamedContext<

export const useErrorBoundary = () => useRequiredContext(ErrorBoundaryContext);

export const useOptionalErrorBoundary = () => useContext(ErrorBoundaryContext);

export interface ErrorBoundaryProviderProps {
children: ReactNode;
}
Expand Down
9 changes: 6 additions & 3 deletions js/libs/ui-shared/src/context/KeycloakContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
} from "react";
import { AlertProvider } from "../alerts/Alerts";
import { LoadingSpinner } from "../controls/LoadingSpinner";
import { ErrorBoundaryProvider } from "../utils/ErrorBoundary";
import { stripForeignAuthResponse } from "../utils/stripForeignAuthResponse";
import { ErrorPage } from "./ErrorPage";
import { Help } from "./HelpContext";
Expand Down Expand Up @@ -64,7 +65,7 @@
keycloak: externalKeycloak,
children,
}: PropsWithChildren<KeycloakContextProps<T>>) => {
KeycloakEnvContext = createKeycloakEnvContext<T>();

Check warning on line 68 in js/libs/ui-shared/src/context/KeycloakContext.tsx

View workflow job for this annotation

GitHub Actions / UI Shared

Unexpected reassignment of a variable which was defined outside of the component. Components and hooks should be pure and side-effect free, but variable reassignment is a form of side-effect. If this variable is used in rendering, use useState instead. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render)
const calledOnce = useRef(false);
const [init, setInit] = useState(!!externalKeycloak);
const [error, setError] = useState<unknown>();
Expand Down Expand Up @@ -132,7 +133,7 @@
.catch((error) => setError(error));

calledOnce.current = true;
}, [keycloak, externalKeycloak]);

Check warning on line 136 in js/libs/ui-shared/src/context/KeycloakContext.tsx

View workflow job for this annotation

GitHub Actions / UI Shared

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

// Children have mounted (and their effects ran) by the time this runs, so they can subscribe.
useEffect(() => {
Expand Down Expand Up @@ -163,9 +164,11 @@
subscribeActionUpdate,
}}
>
<AlertProvider>
<Help>{children}</Help>
</AlertProvider>
<ErrorBoundaryProvider>
<AlertProvider>
<Help>{children}</Help>
</AlertProvider>
</ErrorBoundaryProvider>
</KeycloakEnvContext.Provider>
);
};
1 change: 1 addition & 0 deletions js/libs/ui-shared/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export { LoadingSpinner } from "./controls/LoadingSpinner";
export { useFetch } from "./utils/useFetch";
export {
useErrorBoundary,
useOptionalErrorBoundary,
ErrorBoundaryFallback,
ErrorBoundaryProvider,
} from "./utils/ErrorBoundary";
Expand Down
Loading
Loading
0