Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit 1d9c24e

Browse files
Kerryrichvdh
andauthored
OIDC: add friendly errors (#11184)
* add delegatedauthentication to validated server config * dynamic client registration functions * test OP registration functions * add stubbed nativeOidc flow setup in Login * cover more error cases in Login * tidy * test dynamic client registration in Login * comment oidc_static_clients * register oidc inside Login.getFlows * strict fixes * remove unused code * and imports * comments * comments 2 * util functions to get static client id * check static client ids in login flow * remove dead code * OidcRegistrationClientMetadata type * navigate to oidc authorize url * exchange code for token * navigate to oidc authorize url * navigate to oidc authorize url * test * adjust for js-sdk code * login with oidc native flow: messy version * tidy * update test for response_mode query * tidy up some TODOs * use new types * add identityServerUrl to stored params * unit test completeOidcLogin * test tokenlogin * strict * whitespace * tidy * unit test oidc login flow in MatrixChat * strict * tidy * extract success/failure handlers from token login function * typo * use for no homeserver error dialog too * reuse post-token login functions, test * shuffle testing utils around * shuffle testing utils around * i18n * tidy * Update src/Lifecycle.ts Co-authored-by: Richard van der Hoff <1389908+richvdh@users.noreply.github.com> * tidy * comment * update tests for id token validation * move try again responsibility * prettier * add friendly error messages for oidc authorization failures * i18n * update for new translations, tidy --------- Co-authored-by: Richard van der Hoff <1389908+richvdh@users.noreply.github.com>
1 parent eb7ce66 commit 1d9c24e

File tree

6 files changed

+84
-11
lines changed

6 files changed

+84
-11
lines changed

src/Lifecycle.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ import { OverwriteLoginPayload } from "./dispatcher/payloads/OverwriteLoginPaylo
6565
import { SdkContextClass } from "./contexts/SDKContext";
6666
import { messageForLoginError } from "./utils/ErrorUtils";
6767
import { completeOidcLogin } from "./utils/oidc/authorize";
68+
import { getOidcErrorMessage } from "./utils/oidc/error";
6869
import { OidcClientStore } from "./stores/oidc/OidcClientStore";
6970
import {
7071
getStoredOidcClientId,
@@ -306,8 +307,7 @@ async function attemptOidcNativeLogin(queryParams: QueryDict): Promise<boolean>
306307
} catch (error) {
307308
logger.error("Failed to login via OIDC", error);
308309

309-
// TODO(kerrya) nice error messages https://github.com/vector-im/element-web/issues/25665
310-
await onFailedDelegatedAuthLogin(_t("auth|oidc|error_generic"));
310+
await onFailedDelegatedAuthLogin(getOidcErrorMessage(error as Error));
311311
return false;
312312
}
313313
}

src/i18n/strings/en_EN.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,9 +228,10 @@
228228
"msisdn_field_required_invalid": "Enter phone number",
229229
"no_hs_url_provided": "No homeserver URL provided",
230230
"oidc": {
231-
"error_generic": "Something went wrong.",
232231
"error_title": "We couldn't log you in",
233-
"logout_redirect_warning": "You will be redirected to your server's authentication provider to complete sign out."
232+
"generic_auth_error": "Something went wrong during authentication. Go to the sign in page and try again.",
233+
"logout_redirect_warning": "You will be redirected to your server's authentication provider to complete sign out.",
234+
"missing_or_invalid_stored_state": "We asked the browser to remember which homeserver you use to let you sign in, but unfortunately your browser has forgotten it. Go to the sign in page and try again."
234235
},
235236
"password_field_keep_going_prompt": "Keep going…",
236237
"password_field_label": "Enter password",

src/utils/oidc/authorize.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ import { OidcClientConfig } from "matrix-js-sdk/src/matrix";
2020
import { randomString } from "matrix-js-sdk/src/randomstring";
2121
import { IdTokenClaims } from "oidc-client-ts";
2222

23+
import { OidcClientError } from "./error";
24+
2325
/**
2426
* Start OIDC authorization code flow
2527
* Generates auth params, stores them in session storage and
@@ -68,7 +70,7 @@ const getCodeAndStateFromQueryParams = (queryParams: QueryDict): { code: string;
6870
const state = queryParams["state"];
6971

7072
if (!code || typeof code !== "string" || !state || typeof state !== "string") {
71-
throw new Error("Invalid query parameters for OIDC native login. `code` and `state` are required.");
73+
throw new Error(OidcClientError.InvalidQueryParameters);
7274
}
7375
return { code, state };
7476
};

src/utils/oidc/error.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
Copyright 2023 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import { ReactNode } from "react";
18+
import { OidcError } from "matrix-js-sdk/src/oidc/error";
19+
20+
import { _t } from "../../languageHandler";
21+
22+
/**
23+
* Errors thrown by EW during OIDC native flow authentication.
24+
* Intended to be logged, not read by users.
25+
*/
26+
export enum OidcClientError {
27+
InvalidQueryParameters = "Invalid query parameters for OIDC native login. `code` and `state` are required.",
28+
}
29+
30+
/**
31+
* Get a friendly translated error message for user consumption
32+
* based on error encountered during authentication
33+
* @param error
34+
* @returns a friendly translated error message for user consumption
35+
*/
36+
export const getOidcErrorMessage = (error: Error): string | ReactNode => {
37+
switch (error.message) {
38+
case OidcError.MissingOrInvalidStoredState:
39+
return _t("auth|oidc|missing_or_invalid_stored_state");
40+
case OidcClientError.InvalidQueryParameters:
41+
case OidcError.CodeExchangeFailed:
42+
case OidcError.InvalidBearerTokenResponse:
43+
case OidcError.InvalidIdToken:
44+
default:
45+
return _t("auth|oidc|generic_auth_error");
46+
}
47+
};

test/components/structures/MatrixChat-test.tsx

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import {
4444
unmockClientPeg,
4545
} from "../../test-utils";
4646
import * as leaveRoomUtils from "../../../src/utils/leave-behaviour";
47+
import { OidcClientError } from "../../../src/utils/oidc/error";
4748
import * as voiceBroadcastUtils from "../../../src/voice-broadcast/utils/cleanUpBroadcasts";
4849
import LegacyCallHandler from "../../../src/LegacyCallHandler";
4950
import { CallStore } from "../../../src/stores/CallStore";
@@ -915,10 +916,13 @@ describe("<MatrixChat />", () => {
915916

916917
let loginClient!: ReturnType<typeof getMockClientWithEventEmitter>;
917918

918-
// for now when OIDC fails for any reason we just bump back to welcome
919-
// error handling screens in https://github.com/vector-im/element-web/issues/25665
920-
const expectOIDCError = async (): Promise<void> => {
919+
const expectOIDCError = async (
920+
errorMessage = "Something went wrong during authentication. Go to the sign in page and try again.",
921+
): Promise<void> => {
921922
await flushPromises();
923+
const dialog = await screen.findByRole("dialog");
924+
925+
expect(within(dialog).getByText(errorMessage)).toBeInTheDocument();
922926
// just check we're back on welcome page
923927
expect(document.querySelector(".mx_Welcome")!).toBeInTheDocument();
924928
};
@@ -972,7 +976,7 @@ describe("<MatrixChat />", () => {
972976

973977
expect(logger.error).toHaveBeenCalledWith(
974978
"Failed to login via OIDC",
975-
new Error("Invalid query parameters for OIDC native login. `code` and `state` are required."),
979+
new Error(OidcClientError.InvalidQueryParameters),
976980
);
977981

978982
await expectOIDCError();
@@ -1027,6 +1031,24 @@ describe("<MatrixChat />", () => {
10271031
mocked(completeAuthorizationCodeGrant).mockRejectedValue(new Error(OidcError.CodeExchangeFailed));
10281032
});
10291033

1034+
it("should log and return to welcome page with correct error when login state is not found", async () => {
1035+
mocked(completeAuthorizationCodeGrant).mockRejectedValue(
1036+
new Error(OidcError.MissingOrInvalidStoredState),
1037+
);
1038+
getComponent({ realQueryParams });
1039+
1040+
await flushPromises();
1041+
1042+
expect(logger.error).toHaveBeenCalledWith(
1043+
"Failed to login via OIDC",
1044+
new Error(OidcError.MissingOrInvalidStoredState),
1045+
);
1046+
1047+
await expectOIDCError(
1048+
"We asked the browser to remember which homeserver you use to let you sign in, but unfortunately your browser has forgotten it. Go to the sign in page and try again.",
1049+
);
1050+
});
1051+
10301052
it("should log and return to welcome page", async () => {
10311053
getComponent({ realQueryParams });
10321054

test/utils/oidc/authorize-test.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { mocked } from "jest-mock";
2222

2323
import { completeOidcLogin, startOidcLogin } from "../../../src/utils/oidc/authorize";
2424
import { makeDelegatedAuthConfig } from "../../test-utils/oidc";
25+
import { OidcClientError } from "../../../src/utils/oidc/error";
2526

2627
jest.unmock("matrix-js-sdk/src/randomstring");
2728

@@ -125,8 +126,8 @@ describe("OIDC authorization", () => {
125126
});
126127

127128
it("should throw when query params do not include state and code", async () => {
128-
await expect(completeOidcLogin({})).rejects.toThrow(
129-
"Invalid query parameters for OIDC native login. `code` and `state` are required.",
129+
await expect(async () => await completeOidcLogin({})).rejects.toThrow(
130+
OidcClientError.InvalidQueryParameters,
130131
);
131132
});
132133

0 commit comments

Comments
 (0)