Adapt OAuth2 implementation to Matrix Spec v1.18 (#34026)

* Adapt OAuth2 implementation to Matrix Spec v1.18

* Handle more cases of oidc->oauth

* Fix test

* Fix read back of oauth2 context

* Iterate

* Fix tests

* Discard changes to apps/web/playwright/e2e/settings/account-user-settings-tab.spec.ts

* Fix test

* Fix test

* Fix test

* Potential fix for pull request finding 'Unused variable, import, function or class'

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Iterate

* Iterate

* Fix test

---------

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
This commit is contained in:
Michael Telatynski
2026-07-08 09:02:25 +01:00
committed by GitHub
parent 38e29c51c4
commit 2bc9656957
69 changed files with 761 additions and 1738 deletions
@@ -340,11 +340,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
);
// remove the loginToken or auth code from the URL regardless
if (
!!this.props.urlParams.legacy_sso ||
!!this.props.urlParams.oidc_fragment ||
!!this.props.urlParams.oidc_query
) {
if (!!this.props.urlParams.legacy_sso || !!this.props.urlParams.oauth2) {
this.props.onTokenLoginCompleted(this.props.urlParams, this.getFragmentAfterLogin());
}
@@ -696,7 +692,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
case "logout":
this.stores.legacyCallHandler.hangupAllCalls();
Promise.all([...[...CallStore.instance.connectedCalls].map((call) => call.disconnect())]).finally(() =>
Lifecycle.logout(this.stores.oidcClientStore),
Lifecycle.logout(),
);
break;
case "require_registration":
@@ -13,7 +13,7 @@ import { type SSOFlow, SSOAction } from "matrix-js-sdk/src/matrix";
import { Button } from "@vector-im/compound-web";
import { _t, UserFriendlyError } from "../../../languageHandler";
import Login, { type ClientLoginFlow, type OidcNativeFlow } from "../../../Login";
import Login, { type ClientLoginFlow, type OAuthNativeFlow } from "../../../Login";
import { messageForConnectionError, messageForLoginError } from "../../../utils/ErrorUtils";
import AutoDiscoveryUtils from "../../../utils/AutoDiscoveryUtils";
import AuthPage from "../../views/auth/AuthPage";
@@ -31,7 +31,7 @@ import AuthHeader from "../../views/auth/AuthHeader";
import AccessibleButton, { type ButtonEvent } from "../../views/elements/AccessibleButton";
import { type ValidatedServerConfig } from "../../../utils/ValidatedServerConfig";
import { filterBoolean } from "../../../utils/arrays";
import { startOidcLogin } from "../../../utils/oidc/authorize";
import { startOAuthLogin } from "../../../utils/oauth/authorize";
import { ModuleApi } from "../../../modules/Api.ts";
interface IProps {
@@ -122,7 +122,7 @@ 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(),
"oauthNativeFlow": () => this.renderOAuth2Step(),
};
}
@@ -402,7 +402,7 @@ 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 = ["oidcNativeFlow", "m.login.password", "m.login.sso"];
const order = ["oauthNativeFlow", "m.login.password", "m.login.sso"];
const flows = filterBoolean(order.map((type) => this.state.flows?.find((flow) => flow.type === type)));
return (
@@ -434,15 +434,15 @@ class LoginComponent extends React.PureComponent<IProps, IState> {
);
};
private renderOidcNativeStep = (): React.ReactNode => {
const flow = this.state.flows!.find((flow) => flow.type === "oidcNativeFlow")! as OidcNativeFlow;
private renderOAuth2Step = (): React.ReactNode => {
const flow = this.state.flows!.find((flow) => flow.type === "oauthNativeFlow")! as OAuthNativeFlow;
return (
<Button
className="mx_Login_fullWidthButton"
kind="primary"
size="md"
onClick={async () => {
await startOidcLogin(
await startOAuthLogin(
this.props.serverConfig.delegatedAuthentication!,
flow.clientId,
this.props.serverConfig.hsUrl,
@@ -32,7 +32,7 @@ import * as Lifecycle from "../../../Lifecycle";
import { type IMatrixClientCreds } from "../../../utils/createMatrixClient";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
import AuthPage from "../../views/auth/AuthPage";
import Login, { type OidcNativeFlow } from "../../../Login";
import Login, { type OAuthNativeFlow } from "../../../Login";
import dis from "../../../dispatcher/dispatcher";
import SSOButtons from "../../views/elements/SSOButtons";
import ServerPicker from "../../views/elements/ServerPicker";
@@ -46,7 +46,7 @@ import { AuthHeaderDisplay } from "./header/AuthHeaderDisplay";
import { AuthHeaderProvider } from "./header/AuthHeaderProvider";
import SettingsStore from "../../../settings/SettingsStore";
import { type ValidatedServerConfig } from "../../../utils/ValidatedServerConfig";
import { startOidcLogin } from "../../../utils/oidc/authorize";
import { startOAuthLogin } from "../../../utils/oauth/authorize";
const debuglog = (...args: any[]): void => {
if (SettingsStore.getValue("debug_registration")) {
@@ -124,7 +124,7 @@ interface IState {
ssoFlow?: SSOFlow;
// the OIDC native login flow, when supported and enabled
// if present, must be used for registration
oidcNativeFlow?: OidcNativeFlow;
oauthNativeFlow?: OAuthNativeFlow;
}
export default class Registration extends React.Component<IProps, IState> {
@@ -225,12 +225,12 @@ export default class Registration extends React.Component<IProps, IState> {
this.loginLogic.setDelegatedAuthentication(serverConfig.delegatedAuthentication);
let ssoFlow: SSOFlow | undefined;
let oidcNativeFlow: OidcNativeFlow | undefined;
let oauthNativeFlow: OAuthNativeFlow | undefined;
try {
const loginFlows = await this.loginLogic.getFlows(true);
if (serverConfig !== this.latestServerConfig) return; // discard, serverConfig changed from under us
ssoFlow = loginFlows.find((f) => f.type === "m.login.sso" || f.type === "m.login.cas") as SSOFlow;
oidcNativeFlow = loginFlows.find((f) => f.type === "oidcNativeFlow") as OidcNativeFlow;
oauthNativeFlow = loginFlows.find((f) => f.type === "oauthNativeFlow") as OAuthNativeFlow;
} catch (e) {
if (serverConfig !== this.latestServerConfig) return; // discard, serverConfig changed from under us
logger.error("Failed to get login flows to check for SSO support", e);
@@ -241,10 +241,10 @@ export default class Registration extends React.Component<IProps, IState> {
({ flows }) => ({
matrixClient: cli,
ssoFlow,
oidcNativeFlow,
oauthNativeFlow,
// if we are using oidc native we won't continue with flow discovery on HS
// so set an empty array to indicate flows are no longer loading
flows: oidcNativeFlow ? [] : flows,
flows: oauthNativeFlow ? [] : flows,
busy: false,
}),
resolve,
@@ -253,7 +253,7 @@ export default class Registration extends React.Component<IProps, IState> {
// don't need to check with homeserver for login flows
// since we are going to use OIDC native flow
if (oidcNativeFlow) {
if (oauthNativeFlow) {
return;
}
@@ -546,16 +546,16 @@ export default class Registration extends React.Component<IProps, IState> {
<Spinner />
</div>
);
} else if (this.state.matrixClient && this.state.oidcNativeFlow) {
} else if (this.state.matrixClient && this.state.oauthNativeFlow) {
return (
<Button
className="mx_Login_fullWidthButton"
kind="primary"
size="md"
onClick={async () => {
await startOidcLogin(
await startOAuthLogin(
this.props.serverConfig.delegatedAuthentication!,
this.state.oidcNativeFlow!.clientId,
this.state.oauthNativeFlow!.clientId,
this.props.serverConfig.hsUrl,
this.props.serverConfig.isUrl,
true /* isRegistration */,
@@ -26,7 +26,6 @@ import AccessibleButton from "../../views/elements/AccessibleButton";
import Spinner from "../../views/elements/Spinner";
import AuthHeader from "../../views/auth/AuthHeader";
import AuthBody from "../../views/auth/AuthBody";
import { SDKContext } from "../../../contexts/SDKContext";
import { type URLParams } from "../../../vector/url_utils.ts";
enum LoginView {
@@ -61,9 +60,6 @@ interface IState {
}
export default class SoftLogout extends React.Component<IProps, IState> {
public static contextType = SDKContext;
declare public context: React.ContextType<typeof SDKContext>;
public constructor(props: IProps) {
super(props);
@@ -92,7 +88,7 @@ export default class SoftLogout extends React.Component<IProps, IState> {
if (!wipeData) return;
logger.log("Clearing data from soft-logged-out session");
Lifecycle.logout(this.context.oidcClientStore);
Lifecycle.logout();
});
};
@@ -18,17 +18,24 @@ import {
signInByGeneratingQR,
} from "matrix-js-sdk/src/rendezvous";
import { logger } from "matrix-js-sdk/src/logger";
import { AutoDiscovery, MatrixClient, OAuthGrantType, type OidcClientConfig, type XOR } from "matrix-js-sdk/src/matrix";
import {
AutoDiscovery,
MatrixClient,
OAuthGrantType,
type ValidatedAuthMetadata,
type XOR,
} from "matrix-js-sdk/src/matrix";
import { sleep } from "matrix-js-sdk/src/utils";
import { secureRandomString } from "matrix-js-sdk/src/randomstring";
import { Click, Mode, Phase } from "./LoginWithQR-types";
import LoginWithQRFlow from "./LoginWithQRFlow";
import { type CompleteOidcLoginResponse } from "../../../utils/oidc/authorize";
import { getOidcClientId } from "../../../utils/oidc/registerClient.ts";
import { type CompleteOAuthLoginResponse } from "../../../utils/oauth/authorize";
import { getOAuthClientId } from "../../../utils/oauth/registerClient.ts";
import SdkConfig from "../../../SdkConfig.ts";
import { type Context } from "../../../utils/oauth/persistOAuthSettings.ts";
export type QrLoginCredentials = Omit<CompleteOidcLoginResponse, "idTokenClaims"> &
export type QrLoginCredentials = CompleteOAuthLoginResponse &
Awaited<ReturnType<MSC4108SignInWithQR["shareSecrets"]>> & {
deviceId: string;
};
@@ -101,26 +108,10 @@ interface IState {
*/
failureReason?: FailureReason;
/**
* TODO
* Details of the server we are logging into, set after initial protocol negotiation.
*/
loginServerDetails?: {
/**
* TODO
*/
homeserverUrl: string;
/**
* TODO
*/
identityServerUrl?: string;
/**
* TODO
*/
metadata: OidcClientConfig;
/**
* TODO
*/
clientId: string;
};
loginServerDetails?: Pick<Context, "homeserverUrl" | "identityServerUrl" | "metadata"> &
Pick<Context["authContext"], "clientId">;
}
export enum LoginWithQRFailureReason {
@@ -141,7 +132,7 @@ export type FailureReason = RendezvousFailureReason | LoginWithQRFailureReason;
*/
async function resolveServerURLs(
serverNameOrBaseUrl: string,
): Promise<Pick<Partial<NonNullable<IState["loginServerDetails"]>>, "homeserverUrl" | "identityServerUrl">> {
): Promise<Pick<Partial<Context>, "homeserverUrl" | "identityServerUrl">> {
if (serverNameOrBaseUrl.startsWith("http://") || serverNameOrBaseUrl.startsWith("https://")) {
// treat as base URL and skip discovery
return {
@@ -262,7 +253,7 @@ export default class LoginWithQR extends React.Component<Props, IState> {
throw new Error("Failed to discover homeserver URL");
}
let metadata: OidcClientConfig;
let metadata: ValidatedAuthMetadata;
let clientId: string;
try {
// Create a new client as the homeserver URL may not be the same as we used for the secure channel
@@ -270,7 +261,7 @@ export default class LoginWithQR extends React.Component<Props, IState> {
if (!metadata.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {
throw new Error("Server does not support Device Authorization Grant");
}
clientId = await getOidcClientId(metadata, SdkConfig.get().oidc_static_clients);
clientId = await getOAuthClientId(metadata, SdkConfig.get().oidc_static_clients);
} catch (e) {
this.setState({
phase: Phase.Error,
@@ -355,8 +346,6 @@ export default class LoginWithQR extends React.Component<Props, IState> {
refreshToken: tokenResponse.refresh_token,
homeserverUrl,
clientId,
idToken: tokenResponse.id_token,
issuer: metadata!.issuer,
identityServerUrl,
secrets,
deviceId,
@@ -15,7 +15,7 @@ import {
type SSOFlow,
type SSOAction,
type IIdentityProvider,
DELEGATED_OIDC_COMPATIBILITY,
OAUTH_AWARE_PREFERRED_FLOW_FIELD,
} from "matrix-js-sdk/src/matrix";
import { type Signup } from "@matrix-org/analytics-events/types/typescript/Signup";
import { Button, Tooltip } from "@vector-im/compound-web";
@@ -90,7 +90,7 @@ const SSOButton: React.FC<ISSOButtonProps> = ({
let label: string;
if (idp) {
label = _t("auth|continue_with_idp", { provider: idp.name });
} else if (DELEGATED_OIDC_COMPATIBILITY.findIn<boolean>(flow)) {
} else if (OAUTH_AWARE_PREFERRED_FLOW_FIELD.findIn<boolean>(flow)) {
label = _t("action|continue");
} else {
label = _t("auth|sign_in_with_sso");
@@ -18,7 +18,7 @@ import ToggleSwitch from "../../elements/ToggleSwitch";
import { DeviceDetailHeading } from "./DeviceDetailHeading";
import { DeviceVerificationStatusCard } from "./DeviceVerificationStatusCard";
import { type ExtendedDevice } from "./types";
import { getManageDeviceUrl } from "../../../../utils/oidc/urls.ts";
import { getManageDeviceUrl } from "../../../../utils/oauth/urls.ts";
interface Props {
device: ExtendedDevice;
@@ -23,9 +23,8 @@ import ChangePassword from "../../ChangePassword";
import SettingsTab from "../SettingsTab";
import { SettingsSection } from "../../shared/SettingsSection";
import { SettingsSubsection, SettingsSubsectionText } from "../../shared/SettingsSubsection";
import { SDKContext } from "../../../../../contexts/SDKContext";
import { UserPersonalInfoSettings } from "../../UserPersonalInfoSettings";
import { useMatrixClientContext } from "../../../../../contexts/MatrixClientContext";
import { SDKContext } from "../../../../../contexts/SDKContext.ts";
interface IProps {
closeSettingsFn: () => void;
@@ -90,8 +89,8 @@ const AccountUserSettingsTab: React.FC<IProps> = ({ closeSettingsFn }) => {
const [canSetAvatar, setCanSetAvatar] = React.useState<boolean>(false);
const [canChangePassword, setCanChangePassword] = React.useState<boolean>(false);
const cli = useMatrixClientContext();
const sdkContext = useContext(SDKContext);
const cli = sdkContext.client!;
useEffect(() => {
(async () => {
@@ -103,8 +102,8 @@ const AccountUserSettingsTab: React.FC<IProps> = ({ closeSettingsFn }) => {
// the enabled flag value.
const canChangePassword = !changePasswordCap || changePasswordCap["enabled"] !== false;
await sdkContext.oidcClientStore.readyPromise; // wait for the store to be ready
const externalAccountManagementUrl = sdkContext.oidcClientStore.accountManagementEndpoint;
const authMetadata = await cli.getAuthMetadata().catch(() => {});
const externalAccountManagementUrl = authMetadata?.account_management_uri;
// https://spec.matrix.org/v1.7/client-server-api/#m3pid_changes-capability
// We support as far back as v1.1 which doesn't have m.3pid_changes
// so the behaviour for when it is missing has to be assume true
@@ -121,7 +120,7 @@ const AccountUserSettingsTab: React.FC<IProps> = ({ closeSettingsFn }) => {
setExternalAccountManagementUrl(externalAccountManagementUrl);
setCanChangePassword(canChangePassword);
})();
}, [cli, sdkContext.oidcClientStore]);
}, [cli]);
const onPasswordChangeError = useCallback((err: Error): void => {
logger.error("Failed to change password: " + err);
@@ -31,7 +31,7 @@ import QuestionDialog from "../../../dialogs/QuestionDialog";
import { type FilterVariation } from "../../devices/filter";
import { OtherSessionsSectionHeading } from "../../devices/OtherSessionsSectionHeading";
import { SettingsSection } from "../../shared/SettingsSection";
import { getManageDeviceUrl } from "../../../../../utils/oidc/urls.ts";
import { getManageDeviceUrl } from "../../../../../utils/oauth/urls.ts";
import { SDKContext } from "../../../../../contexts/SDKContext";
import Spinner from "../../../elements/Spinner";
@@ -154,12 +154,12 @@ const SessionManagerTab: React.FC<{
* See https://github.com/matrix-org/matrix-spec-proposals/pull/3824
*/
const accountManagement = useAsyncMemo(async () => {
await sdkContext.oidcClientStore.readyPromise; // wait for the store to be ready
const authMetadata = await matrixClient.getAuthMetadata().catch(() => {});
return {
endpoint: sdkContext.oidcClientStore.accountManagementEndpoint,
actionsSupported: sdkContext.oidcClientStore.accountManagementActionsSupported,
endpoint: authMetadata?.account_management_uri,
actionsSupported: authMetadata?.account_management_actions_supported,
};
}, [sdkContext.oidcClientStore]);
}, [matrixClient]);
const disableMultipleSignout = !!accountManagement?.endpoint;
const userId = matrixClient?.getUserId();
const currentUserMember = (userId && matrixClient?.getUser(userId)) || undefined;
@@ -82,7 +82,6 @@ import { KeyboardShortcut } from "../settings/KeyboardShortcut";
import { ModuleApi } from "../../../modules/Api.ts";
import { useModuleSpacePanelItems } from "../../../modules/ExtrasApi.ts";
import { UserMenuViewModel } from "../../../viewmodels/menus/UserMenuViewModel.ts";
import { useMatrixClientContext } from "../../../contexts/MatrixClientContext.tsx";
import { SDKContext } from "../../../contexts/SDKContext.ts";
import { OwnProfileStore } from "../../../stores/OwnProfileStore.ts";
@@ -390,7 +389,8 @@ const InnerSpacePanel = React.memo<IInnerSpacePanelProps>(
);
const SpacePanel: React.FC = () => {
const client = useMatrixClientContext();
const sdkContext = useContext(SDKContext);
const client = sdkContext.client!;
const [dragging, setDragging] = useState(false);
const [isPanelCollapsed, setPanelCollapsed] = useState(true);
const ref = useRef<HTMLDivElement>(null);
@@ -398,7 +398,6 @@ const SpacePanel: React.FC = () => {
if (ref.current) UIStore.instance.trackElementDimensions("SpacePanel", ref.current);
return () => UIStore.instance.stopTrackingElementDimensions("SpacePanel");
}, []);
const sdkContext = useContext(SDKContext);
useDispatcher(defaultDispatcher, (payload: ActionPayload) => {
if (payload.action === Action.ToggleSpacePanel) {
@@ -413,7 +412,6 @@ const SpacePanel: React.FC = () => {
defaultDispatcher,
client,
isPanelCollapsed,
sdkContext.oidcClientStore.accountManagementEndpoint,
),
);