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

OIDC: attempt dynamic client registration #11074

Merged
merged 31 commits into from
Jun 22, 2023
Merged
Show file tree
Hide file tree
Changes from 28 commits
Commits
Show all changes
31 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
71c4b59
use registerClient from js-sdk
Jun 16, 2023
40bfc87
use OidcError from js-sdk
Jun 16, 2023
c3143f6
Merge branch 'develop' into kerry/25468/oidc-client-registration
Jun 22, 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
8 changes: 8 additions & 0 deletions src/IConfigOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,14 @@ export interface IConfigOptions {
existing_issues_url: string;
new_issue_url: string;
};

/**
* Configuration for OIDC issuers where a static client_id has been issued for the app.
* Otherwise dynamic client registration is attempted.
* The issuer URL must have a trailing `/`.
* OPTIONAL
*/
oidc_static_clients?: Record<string, string>;
}

export interface ISsoRedirectOptions {
Expand Down
64 changes: 61 additions & 3 deletions src/Login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,32 @@ limitations under the License.
import { createClient } from "matrix-js-sdk/src/matrix";
import { MatrixClient } from "matrix-js-sdk/src/client";
import { logger } from "matrix-js-sdk/src/logger";
import { DELEGATED_OIDC_COMPATIBILITY, ILoginParams, LoginFlow } from "matrix-js-sdk/src/@types/auth";
import { OidcDiscoveryError } from "matrix-js-sdk/src/oidc/validate";
import { DELEGATED_OIDC_COMPATIBILITY, ILoginFlow, ILoginParams, LoginFlow } from "matrix-js-sdk/src/@types/auth";

import { IMatrixClientCreds } from "./MatrixClientPeg";
import SecurityCustomisations from "./customisations/Security";
import { ValidatedServerConfig } from "./utils/ValidatedServerConfig";
import { getOidcClientId } from "./utils/oidc/registerClient";
import { IConfigOptions } from "./IConfigOptions";
import SdkConfig from "./SdkConfig";

export type ClientLoginFlow = LoginFlow | OidcNativeFlow;

interface ILoginOptions {
defaultDeviceDisplayName?: string;
/**
* Delegated auth config from server config
* When prop is passed we will attempt to use delegated auth
* Labs flag should be checked in parent
*/
delegatedAuthentication?: ValidatedServerConfig["delegatedAuthentication"];
}

export default class Login {
private flows: Array<LoginFlow> = [];
private flows: Array<ClientLoginFlow> = [];
private readonly defaultDeviceDisplayName?: string;
private readonly delegatedAuthentication?: ValidatedServerConfig["delegatedAuthentication"];
private tempClient: MatrixClient | null = null; // memoize

public constructor(
Expand All @@ -40,6 +54,7 @@ export default class Login {
opts: ILoginOptions,
) {
this.defaultDeviceDisplayName = opts.defaultDeviceDisplayName;
this.delegatedAuthentication = opts.delegatedAuthentication;
}

public getHomeserverUrl(): string {
Expand Down Expand Up @@ -75,7 +90,20 @@ export default class Login {
return this.tempClient;
}

public async getFlows(): Promise<Array<LoginFlow>> {
public async getFlows(): Promise<Array<ClientLoginFlow>> {
// try to use oidc native flow
try {
const oidcFlow = await tryInitOidcNativeFlow(
this.delegatedAuthentication,
SdkConfig.get().brand,
SdkConfig.get().oidc_static_clients,
);
return [oidcFlow];
} catch (error) {
logger.error(error);
}

// oidc native flow not supported, continue with matrix login
const client = this.createTemporaryClient();
const { flows }: { flows: LoginFlow[] } = await client.loginFlows();
// If an m.login.sso flow is present which is also flagged as being for MSC3824 OIDC compatibility then we only
Expand Down Expand Up @@ -151,6 +179,36 @@ export default class Login {
}
}

export interface OidcNativeFlow extends ILoginFlow {
type: "oidcNativeFlow";
clientId: string;
}
/**
* Finds static clientId for configured issuer, or attempts dynamic registration with the OP
* @param delegatedAuthConfig Auth config from ValidatedServerConfig
* @param clientName Client name to register with the OP, eg 'Element', used during client registration with OP
* @param staticOidcClients static client config from config.json, used during client registration with OP
* @returns Promise<OidcNativeFlow> when oidc native authentication flow is supported and correctly configured
* @throws when oidc native flow is not configured, client can't register with OP, or any unexpected error
*/
const tryInitOidcNativeFlow = async (
delegatedAuthConfig: ValidatedServerConfig["delegatedAuthentication"] | undefined,
brand: string,
oidcStaticClients?: IConfigOptions["oidc_static_clients"],
): Promise<OidcNativeFlow> => {
if (!delegatedAuthConfig) {
throw new Error(OidcDiscoveryError.NotSupported);
}
const clientId = await getOidcClientId(delegatedAuthConfig, brand, window.location.origin, oidcStaticClients);

const flow = {
type: "oidcNativeFlow",
clientId,
} as OidcNativeFlow;

return flow;
};

/**
* Send a login request to the given server, and format the response
* as a MatrixClientCreds
Expand Down
73 changes: 44 additions & 29 deletions src/components/structures/auth/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ limitations under the License.
import React, { ReactNode } from "react";
import classNames from "classnames";
import { logger } from "matrix-js-sdk/src/logger";
import { ISSOFlow, LoginFlow, SSOAction } from "matrix-js-sdk/src/@types/auth";
import { ISSOFlow, SSOAction } from "matrix-js-sdk/src/@types/auth";

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

// 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 All @@ -49,7 +50,6 @@ _td("Invalid identity server discovery response");
_td("Invalid base_url for m.identity_server");
_td("Identity server URL does not appear to be a valid identity server");
_td("General failure");

interface IProps {
serverConfig: ValidatedServerConfig;
// If true, the component will consider itself busy.
Expand Down Expand Up @@ -84,7 +84,7 @@ interface IState {
// can we attempt to log in or are there validation errors?
canTryLogin: boolean;

flows?: LoginFlow[];
flows?: ClientLoginFlow[];

// used for preserving form values when changing homeserver
username: string;
Expand All @@ -110,13 +110,17 @@ type OnPasswordLogin = {
*/
export default class LoginComponent extends React.PureComponent<IProps, IState> {
private unmounted = false;
private oidcNativeFlowEnabled = false;
private loginLogic!: Login;

private readonly stepRendererMap: Record<string, () => ReactNode>;

public constructor(props: IProps) {
super(props);

// only set on a config level, so we don't need to watch
this.oidcNativeFlowEnabled = SettingsStore.getValue(Features.OidcNativeFlow);

this.state = {
busy: false,
errorText: null,
Expand Down Expand Up @@ -156,7 +160,8 @@ export default class LoginComponent extends React.PureComponent<IProps, IState>
public componentDidUpdate(prevProps: IProps): void {
if (
prevProps.serverConfig.hsUrl !== this.props.serverConfig.hsUrl ||
prevProps.serverConfig.isUrl !== this.props.serverConfig.isUrl
prevProps.serverConfig.isUrl !== this.props.serverConfig.isUrl ||
prevProps.serverConfig.delegatedAuthentication !== this.props.serverConfig.delegatedAuthentication
) {
// Ensure that we end up actually logging in to the right place
this.initLoginLogic(this.props.serverConfig);
Expand Down Expand Up @@ -322,28 +327,10 @@ export default class LoginComponent extends React.PureComponent<IProps, IState>
}
};

private async initLoginLogic({ hsUrl, isUrl }: ValidatedServerConfig): Promise<void> {
let isDefaultServer = false;
if (
this.props.serverConfig.isDefault &&
hsUrl === this.props.serverConfig.hsUrl &&
isUrl === this.props.serverConfig.isUrl
) {
isDefaultServer = true;
}

const fallbackHsUrl = isDefaultServer ? this.props.fallbackHsUrl! : null;

const loginLogic = new Login(hsUrl, isUrl, fallbackHsUrl, {
defaultDeviceDisplayName: this.props.defaultDeviceDisplayName,
});
this.loginLogic = loginLogic;

this.setState({
busy: true,
loginIncorrect: false,
});

private async checkServerLiveliness({
hsUrl,
isUrl,
}: Pick<ValidatedServerConfig, "hsUrl" | "isUrl">): Promise<void> {
// Do a quick liveliness check on the URLs
try {
const { warning } = await AutoDiscoveryUtils.validateServerConfigWithStaticUrls(hsUrl, isUrl);
Expand All @@ -361,9 +348,37 @@ export default class LoginComponent extends React.PureComponent<IProps, IState>
} catch (e) {
this.setState({
busy: false,
...AutoDiscoveryUtils.authComponentStateForError(e),
...AutoDiscoveryUtils.authComponentStateForError(e as Error),
});
}
}

private async initLoginLogic({ hsUrl, isUrl }: ValidatedServerConfig): Promise<void> {
let isDefaultServer = false;
if (
this.props.serverConfig.isDefault &&
hsUrl === this.props.serverConfig.hsUrl &&
isUrl === this.props.serverConfig.isUrl
) {
isDefaultServer = true;
}

const fallbackHsUrl = isDefaultServer ? this.props.fallbackHsUrl! : null;

this.setState({
busy: true,
loginIncorrect: false,
});

await this.checkServerLiveliness({ hsUrl, isUrl });

const loginLogic = new Login(hsUrl, isUrl, fallbackHsUrl, {
defaultDeviceDisplayName: this.props.defaultDeviceDisplayName,
delegatedAuthentication: this.oidcNativeFlowEnabled
? this.props.serverConfig.delegatedAuthentication
: undefined,
});
this.loginLogic = loginLogic;

loginLogic
.getFlows()
Expand Down Expand Up @@ -401,7 +416,7 @@ export default class LoginComponent extends React.PureComponent<IProps, IState>
});
}

private isSupportedFlow = (flow: LoginFlow): boolean => {
private isSupportedFlow = (flow: ClientLoginFlow): boolean => {
// technically the flow can have multiple steps, but no one does this
// for login and loginLogic doesn't support it so we can ignore it.
if (!this.stepRendererMap[flow.type]) {
Expand Down
21 changes: 21 additions & 0 deletions src/utils/oidc/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
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.
*/

export enum OidcClientError {
DynamicRegistrationNotSupported = "Dynamic registration not supported",
DynamicRegistrationFailed = "Dynamic registration failed",
DynamicRegistrationInvalid = "Dynamic registration invalid response",
}
Loading