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

OIDC: navigate to authorization endpoint #11096

Merged
merged 40 commits into from
Jun 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
c2a78d1
add delegatedauthentication to validated server config
Jun 7, 2023
f946b85
dynamic client registration functions
Jun 9, 2023
223d3ff
Merge branch 'develop' into kerry/25466/oidc-validate-wk-mauthenticat…
Jun 11, 2023
f83499e
Merge branch 'kerry/25466/oidc-validate-wk-mauthentication-2' into ke…
Jun 11, 2023
4201725
test OP registration functions
Jun 12, 2023
314105d
add stubbed nativeOidc flow setup in Login
Jun 12, 2023
6fe2d35
cover more error cases in Login
Jun 12, 2023
c473f11
Merge branch 'kerry/25468/test-login' into kerry/25468/oidc-client-re…
Jun 12, 2023
19dc425
tidy
Jun 12, 2023
94d5c36
test dynamic client registration in Login
Jun 12, 2023
67f6c2e
comment oidc_static_clients
Jun 12, 2023
8df0929
register oidc inside Login.getFlows
Jun 12, 2023
0d4de13
Merge branch 'develop' into kerry/25466/oidc-validate-wk-mauthenticat…
Jun 12, 2023
1a53ad0
strict fixes
Jun 12, 2023
f9aaa28
remove unused code
Jun 12, 2023
9faa9c8
and imports
Jun 12, 2023
0f76ffa
Merge branch 'kerry/25466/oidc-validate-wk-mauthentication-2' into ke…
Jun 13, 2023
4dfa18d
Merge branch 'develop' into kerry/25468/oidc-client-registration
Jun 13, 2023
e920229
comments
Jun 13, 2023
5389d5c
comments 2
Jun 13, 2023
af63a90
util functions to get static client id
Jun 13, 2023
9c89f41
check static client ids in login flow
Jun 13, 2023
056a713
Merge branch 'kerry/25468/oidc-client-static-reg' into kerry/25468/oi…
Jun 13, 2023
422823e
remove dead code
Jun 14, 2023
8483b2f
Merge branch 'kerry/25468/oidc-client-static-reg' into kerry/25468/oi…
Jun 14, 2023
a76cde9
OidcRegistrationClientMetadata type
Jun 14, 2023
e1e22f3
Merge branch 'develop' into kerry/25468/oidc-client-static-reg
Jun 14, 2023
f4a2ff2
Merge branch 'kerry/25468/oidc-client-static-reg' into kerry/25468/oi…
Jun 14, 2023
52d03c2
navigate to oidc authorize url
Jun 14, 2023
3c499da
navigate to oidc authorize url
Jun 15, 2023
551670f
test
Jun 15, 2023
423af53
Merge branch 'develop' into kerry/25574/oidc-authorization-endpoint
Jun 22, 2023
b100d6d
adjust for js-sdk code
Jun 23, 2023
72ff46a
update test for response_mode query
Jun 23, 2023
857df8d
use new types
Jun 26, 2023
dbd54c5
Merge branch 'develop' into kerry/25574/oidc-authorization-endpoint
Jun 27, 2023
599baa2
strict
Jun 27, 2023
ffbc140
Merge branch 'develop' into kerry/25574/oidc-authorization-endpoint
Jun 28, 2023
88e0cf2
tidy
Jun 28, 2023
e2b90d4
Merge branch 'develop' into kerry/25574/oidc-authorization-endpoint
Jun 28, 2023
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
5 changes: 5 additions & 0 deletions res/css/structures/auth/_Login.pcss
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,8 @@ div.mx_AccessibleButton_kind_link.mx_Login_forgot {
align-content: center;
padding: 14px;
}

.mx_Login_fullWidthButton {
width: 100%;
margin-bottom: 16px;
}
25 changes: 23 additions & 2 deletions src/components/structures/auth/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { logger } from "matrix-js-sdk/src/logger";
import { ISSOFlow, SSOAction } from "matrix-js-sdk/src/@types/auth";

import { _t, _td, UserFriendlyError } from "../../../languageHandler";
import Login, { ClientLoginFlow } from "../../../Login";
import Login, { ClientLoginFlow, OidcNativeFlow } from "../../../Login";
import { messageForConnectionError, messageForLoginError } from "../../../utils/ErrorUtils";
import AutoDiscoveryUtils from "../../../utils/AutoDiscoveryUtils";
import AuthPage from "../../views/auth/AuthPage";
Expand All @@ -39,6 +39,7 @@ import AccessibleButton, { ButtonEvent } from "../../views/elements/AccessibleBu
import { ValidatedServerConfig } from "../../../utils/ValidatedServerConfig";
import { filterBoolean } from "../../../utils/arrays";
import { Features } from "../../../settings/Settings";
import { startOidcLogin } from "../../../utils/oidc/authorize";

// These are used in several places, and come from the js-sdk's autodiscovery
// stuff. We define them here so that they'll be picked up by i18n.
Expand Down Expand Up @@ -146,6 +147,7 @@ export default class LoginComponent extends React.PureComponent<IProps, IState>
"m.login.cas": () => this.renderSsoStep("cas"),
// eslint-disable-next-line @typescript-eslint/naming-convention
"m.login.sso": () => this.renderSsoStep("sso"),
"oidcNativeFlow": () => this.renderOidcNativeStep(),
};
}

Expand Down Expand Up @@ -433,7 +435,7 @@ export default class LoginComponent extends React.PureComponent<IProps, IState>
if (!this.state.flows) return null;

// this is the ideal order we want to show the flows in
const order = ["m.login.password", "m.login.sso"];
const order = ["oidcNativeFlow", "m.login.password", "m.login.sso"];

const flows = filterBoolean(order.map((type) => this.state.flows?.find((flow) => flow.type === type)));
return (
Expand Down Expand Up @@ -466,6 +468,25 @@ export default class LoginComponent extends React.PureComponent<IProps, IState>
);
};

private renderOidcNativeStep = (): React.ReactNode => {
const flow = this.state.flows!.find((flow) => flow.type === "oidcNativeFlow")! as OidcNativeFlow;
return (
<AccessibleButton
className="mx_Login_fullWidthButton"
kind="primary"
onClick={async () => {
await startOidcLogin(
this.props.serverConfig.delegatedAuthentication!,
flow.clientId,
this.props.serverConfig.hsUrl,
);
}}
>
{_t("Continue")}
</AccessibleButton>
);
};

private renderSsoStep = (loginType: "cas" | "sso"): JSX.Element => {
const flow = this.state.flows?.find((flow) => flow.type === "m.login." + loginType) as ISSOFlow;

Expand Down
73 changes: 73 additions & 0 deletions src/utils/oidc/authorize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
Copyright 2023 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import {
AuthorizationParams,
generateAuthorizationParams,
generateAuthorizationUrl,
} from "matrix-js-sdk/src/oidc/authorize";

import { ValidatedDelegatedAuthConfig } from "../ValidatedServerConfig";

/**
* Store authorization params for retrieval when returning from OIDC OP
* @param authorizationParams from `generateAuthorizationParams`
* @param delegatedAuthConfig used for future interactions with OP
* @param clientId this client's id as registered with configured issuer
* @param homeserver target homeserver
*/
const storeAuthorizationParams = (
{ redirectUri, state, nonce, codeVerifier }: AuthorizationParams,
{ issuer }: ValidatedDelegatedAuthConfig,
clientId: string,
homeserver: string,
): void => {
window.sessionStorage.setItem(`oidc_${state}_nonce`, nonce);
window.sessionStorage.setItem(`oidc_${state}_redirectUri`, redirectUri);
window.sessionStorage.setItem(`oidc_${state}_codeVerifier`, codeVerifier);
window.sessionStorage.setItem(`oidc_${state}_clientId`, clientId);
window.sessionStorage.setItem(`oidc_${state}_issuer`, issuer);
window.sessionStorage.setItem(`oidc_${state}_homeserver`, homeserver);
};

/**
* Start OIDC authorization code flow
* Generates auth params, stores them in session storage and
* Navigates to configured authorization endpoint
* @param delegatedAuthConfig from discovery
* @param clientId this client's id as registered with configured issuer
* @param homeserver target homeserver
* @returns Promise that resolves after we have navigated to auth endpoint
*/
export const startOidcLogin = async (
delegatedAuthConfig: ValidatedDelegatedAuthConfig,
clientId: string,
homeserver: string,
): Promise<void> => {
// TODO(kerrya) afterloginfragment https://github.com/vector-im/element-web/issues/25656
const redirectUri = window.location.origin;
const authParams = generateAuthorizationParams({ redirectUri });

storeAuthorizationParams(authParams, delegatedAuthConfig, clientId, homeserver);

const authorizationUrl = await generateAuthorizationUrl(
delegatedAuthConfig.authorizationEndpoint,
clientId,
authParams,
);

window.location.href = authorizationUrl;
};
1 change: 0 additions & 1 deletion src/utils/oidc/registerClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ const getStaticOidcClientId = (issuer: string, staticOidcClients?: Record<string
*/
export const getOidcClientId = async (
delegatedAuthConfig: ValidatedDelegatedAuthConfig,
// these are used in the following PR
clientName: string,
baseUrl: string,
staticOidcClients?: Record<string, string>,
Expand Down
7 changes: 2 additions & 5 deletions test/components/structures/auth/Login-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -409,18 +409,15 @@ describe("Login", function () {
});

// short term during active development, UI will be added in next PRs
it("should show error when oidc native flow is correctly configured but not supported by UI", async () => {
it("should show continue button when oidc native flow is correctly configured", async () => {
fetchMock.post(delegatedAuth.registrationEndpoint, { client_id: "abc123" });
getComponent(hsUrl, isUrl, delegatedAuth);

await waitForElementToBeRemoved(() => screen.queryAllByLabelText("Loading…"));

// did not continue with matrix login
expect(mockClient.loginFlows).not.toHaveBeenCalled();
// no oidc native UI yet
expect(
screen.getByText("This homeserver doesn't offer any login flows which are supported by this client."),
).toBeInTheDocument();
expect(screen.getByText("Continue")).toBeInTheDocument();
});

/**
Expand Down
102 changes: 102 additions & 0 deletions test/utils/oidc/authorize-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*
Copyright 2023 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import fetchMockJest from "fetch-mock-jest";
import * as randomStringUtils from "matrix-js-sdk/src/randomstring";

import { startOidcLogin } from "../../../src/utils/oidc/authorize";

describe("startOidcLogin()", () => {
const issuer = "https://auth.com/";
const authorizationEndpoint = "https://auth.com/authorization";
const homeserver = "https://matrix.org";
const clientId = "xyz789";
const baseUrl = "https://test.com";

const delegatedAuthConfig = {
issuer,
registrationEndpoint: issuer + "registration",
authorizationEndpoint,
tokenEndpoint: issuer + "token",
};

const sessionStorageGetSpy = jest.spyOn(sessionStorage.__proto__, "setItem").mockReturnValue(undefined);
const randomStringMockImpl = (length: number) => new Array(length).fill("x").join("");

// to restore later
const realWindowLocation = window.location;

beforeEach(() => {
fetchMockJest.mockClear();
fetchMockJest.resetBehavior();

sessionStorageGetSpy.mockClear();

// @ts-ignore allow delete of non-optional prop
delete window.location;
// @ts-ignore ugly mocking
window.location = {
href: baseUrl,
origin: baseUrl,
};

jest.spyOn(randomStringUtils, "randomString").mockRestore();
});

afterAll(() => {
window.location = realWindowLocation;
});

it("should store authorization params in session storage", async () => {
jest.spyOn(randomStringUtils, "randomString").mockReset().mockImplementation(randomStringMockImpl);
await startOidcLogin(delegatedAuthConfig, clientId, homeserver);

const state = randomStringUtils.randomString(8);

expect(sessionStorageGetSpy).toHaveBeenCalledWith(`oidc_${state}_nonce`, randomStringUtils.randomString(8));
expect(sessionStorageGetSpy).toHaveBeenCalledWith(`oidc_${state}_redirectUri`, baseUrl);
expect(sessionStorageGetSpy).toHaveBeenCalledWith(
`oidc_${state}_codeVerifier`,
randomStringUtils.randomString(64),
);
expect(sessionStorageGetSpy).toHaveBeenCalledWith(`oidc_${state}_clientId`, clientId);
expect(sessionStorageGetSpy).toHaveBeenCalledWith(`oidc_${state}_issuer`, issuer);
expect(sessionStorageGetSpy).toHaveBeenCalledWith(`oidc_${state}_homeserver`, homeserver);
});

it("navigates to authorization endpoint with correct parameters", async () => {
await startOidcLogin(delegatedAuthConfig, clientId, homeserver);

const expectedScopeWithoutDeviceId = `openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:`;

const authUrl = new URL(window.location.href);

expect(authUrl.searchParams.get("response_mode")).toEqual("query");
expect(authUrl.searchParams.get("response_type")).toEqual("code");
expect(authUrl.searchParams.get("client_id")).toEqual(clientId);
expect(authUrl.searchParams.get("code_challenge_method")).toEqual("S256");

// scope ends with a 10char randomstring deviceId
const scope = authUrl.searchParams.get("scope")!;
expect(scope.substring(0, scope.length - 10)).toEqual(expectedScopeWithoutDeviceId);
expect(scope.substring(scope.length - 10)).toBeTruthy();

// random string, just check they are set
expect(authUrl.searchParams.has("state")).toBeTruthy();
expect(authUrl.searchParams.has("nonce")).toBeTruthy();
expect(authUrl.searchParams.has("code_challenge")).toBeTruthy();
});
});