mirror of
https://github.com/Novaloop-AG/healthchat-web.git
synced 2026-12-03 21:51:06 +00:00
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:
committed by
GitHub
parent
38e29c51c4
commit
2bc9656957
@@ -12,7 +12,7 @@ import { vi, describe, it, expect, afterAll, beforeEach } from "vitest";
|
||||
import fetchMock from "@fetch-mock/vitest";
|
||||
import { MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||
import { mockPlatformPeg, unmockPlatformPeg } from "test-utils";
|
||||
import { makeDelegatedAuthConfig } from "test-utils/oidc";
|
||||
import { makeDelegatedAuthMetadata } from "test-utils/auth";
|
||||
import { type RefCallback } from "react";
|
||||
|
||||
import { loadApp } from "./app.tsx";
|
||||
@@ -54,7 +54,7 @@ describe("sso_redirect_options", () => {
|
||||
oidc_static_clients: { [issuer]: { client_id: "12345" } },
|
||||
});
|
||||
// Signal we support v1.1 to pass the minimum js-sdk compatibility bar
|
||||
// Signal we support v1.15 to use stable Native OIDC support
|
||||
// Signal we support v1.15 to use stable Native OAuth2 support
|
||||
fetchMock.get("https://synapse/_matrix/client/versions", { versions: ["v1.1", "v1.15"] });
|
||||
});
|
||||
|
||||
@@ -69,17 +69,18 @@ describe("sso_redirect_options", () => {
|
||||
expect(startSingleSignOnSpy).toHaveBeenCalledWith(expect.any(MatrixClient), "sso", "/room/#room:server");
|
||||
});
|
||||
|
||||
it("should redirect for native OIDC", async () => {
|
||||
const authConfig = { ...makeDelegatedAuthConfig(issuer), response_modes_supported: ["query", "fragment"] };
|
||||
it("should redirect for native OAuth2", async () => {
|
||||
const authConfig = {
|
||||
...makeDelegatedAuthMetadata(issuer),
|
||||
response_modes_supported: ["query", "fragment"],
|
||||
};
|
||||
fetchMock.get("https://synapse/_matrix/client/v1/auth_metadata", authConfig);
|
||||
fetchMock.get(`${authConfig.issuer}.well-known/openid-configuration`, authConfig);
|
||||
fetchMock.get(authConfig.jwks_uri!, { keys: [] });
|
||||
|
||||
const startOidcLoginSpy = vi.spyOn(window.location, "href", "set");
|
||||
const startOAuthLoginSpy = vi.spyOn(window.location, "href", "set");
|
||||
|
||||
await loadApp({}, vi.fn() as RefCallback<MatrixChat>);
|
||||
expect(startOidcLoginSpy).toHaveBeenCalledWith(
|
||||
"https://auth.org/auth?client_id=12345&redirect_uri=https%3A%2F%2Fapp.element.io%2F%3Fno_universal_links%3Dtrue&response_type=code&scope=openid+urn%3Amatrix%3Aorg.matrix.msc2967.client%3Aapi%3A*+urn%3Amatrix%3Aorg.matrix.msc2967.client%3Adevice%3AABCDEFGHIJ&nonce=ABCDEFGHIJ&state=10000000100040008000100000000000&code_challenge=awE81eIsGff70JahvrTqWRbGKLI10ooyo_Xm1sxuZvU&code_challenge_method=S256&response_mode=fragment",
|
||||
expect(startOAuthLoginSpy).toHaveBeenCalledWith(
|
||||
"https://auth.org/auth?response_type=code&response_mode=fragment&client_id=12345&redirect_uri=https%3A%2F%2Fapp.element.io%2F%3Fno_universal_links%3Dtrue&scope=urn%3Amatrix%3Aclient%3Aapi%3A*+urn%3Amatrix%3Aclient%3Adevice%3AABCDEFGHIJ&state=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef&code_challenge_method=S256&code_challenge=ymW9_yTzfYF1Km4N7W4OC6jQ7xoj91DUulQHWfmrROM",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@ import { RoomView } from "../components/structures/RoomView";
|
||||
import RoomAvatar from "../components/views/avatars/RoomAvatar";
|
||||
import { ModuleNotificationDecoration } from "../modules/components/ModuleNotificationDecoration";
|
||||
import Login from "../Login.ts";
|
||||
import { startOidcLogin } from "../utils/oidc/authorize.ts";
|
||||
import { startOAuthLogin } from "../utils/oauth/authorize.ts";
|
||||
|
||||
logger.log(`Application is running in ${process.env.NODE_ENV} mode`);
|
||||
|
||||
@@ -44,7 +44,7 @@ function onTokenLoginCompleted(urlParams: URLParams, fragmentAfterLogin: string)
|
||||
const url = new URL(window.location.href);
|
||||
|
||||
// if we did a token login, we're now left with the login token as query param in the url; clear it out
|
||||
for (const param in { ...urlParams.legacy_sso, ...urlParams.oidc_query }) {
|
||||
for (const param in { ...urlParams.legacy_sso }) {
|
||||
url.searchParams.delete(param);
|
||||
}
|
||||
|
||||
@@ -68,9 +68,9 @@ async function redirectToSso(config: ValidatedServerConfig): Promise<boolean> {
|
||||
});
|
||||
const flows = await login.getFlows();
|
||||
|
||||
const nativeOidcFlow = flows.find((flow) => "clientId" in flow);
|
||||
if (nativeOidcFlow && config.delegatedAuthentication) {
|
||||
await startOidcLogin(config.delegatedAuthentication, nativeOidcFlow.clientId, config.hsUrl, config.isUrl);
|
||||
const nativeOAuthFlow = flows.find((flow) => "clientId" in flow);
|
||||
if (nativeOAuthFlow && config.delegatedAuthentication) {
|
||||
await startOAuthLogin(config.delegatedAuthentication, nativeOAuthFlow.clientId, config.hsUrl, config.isUrl);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ export async function loadApp(urlParams: URLParams, matrixChatRef: React.Ref<Mat
|
||||
// Before we continue, let's see if we're supposed to do an SSO redirect
|
||||
const [userId] = await Lifecycle.getStoredSessionOwner();
|
||||
const hasPossibleToken = !!userId;
|
||||
const isReturningFromSso = !!urlParams.legacy_sso || !!urlParams.oidc_fragment || !!urlParams.oidc_query;
|
||||
const isReturningFromSso = !!urlParams.legacy_sso || !!urlParams.oauth2;
|
||||
const ssoRedirects = config.sso_redirect_options || {};
|
||||
let autoRedirect = ssoRedirects.immediate === true;
|
||||
// XXX: This path matching is a bit brittle, but better to do it early instead of in the app code.
|
||||
|
||||
@@ -86,7 +86,7 @@ describe("ElectronPlatform", () => {
|
||||
it("should return oidc client state as expected", async () => {
|
||||
const platform = new ElectronPlatform();
|
||||
await platform.getConfig();
|
||||
expect(platform.getOidcClientState()).toMatchInlineSnapshot(`":element-desktop-ssoid:session-id"`);
|
||||
expect(platform.getOAuthClientState()).toMatchInlineSnapshot(`":element-desktop-ssoid:session-id"`);
|
||||
});
|
||||
|
||||
it("dispatches view settings action on preferences event", () => {
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
type MatrixClient,
|
||||
type Room,
|
||||
type MatrixEvent,
|
||||
type OidcRegistrationClientMetadata,
|
||||
type OAuthRegistrationRequest,
|
||||
} from "matrix-js-sdk/src/matrix";
|
||||
import React from "react";
|
||||
import { logger } from "matrix-js-sdk/src/logger";
|
||||
@@ -531,28 +531,28 @@ export default class ElectronPlatform extends BasePlatform {
|
||||
return (SdkConfig.get() as unknown as Record<string, string>)["web_base_url"] ?? "https://app.element.io";
|
||||
}
|
||||
|
||||
public get defaultOidcClientUri(): string {
|
||||
public get defaultOAuthClientUri(): string {
|
||||
// Default to element.io as our scheme `io.element.desktop` is within its scope on default MAS policies
|
||||
return "https://element.io";
|
||||
}
|
||||
|
||||
public async getOidcClientMetadata(): Promise<OidcRegistrationClientMetadata> {
|
||||
const baseMetadata = await super.getOidcClientMetadata();
|
||||
public async getOAuthClientMetadata(): Promise<OAuthRegistrationRequest> {
|
||||
const baseMetadata = await super.getOAuthClientMetadata();
|
||||
return {
|
||||
...baseMetadata,
|
||||
applicationType: "native",
|
||||
application_type: "native",
|
||||
};
|
||||
}
|
||||
|
||||
public getOidcClientState(): string {
|
||||
public getOAuthClientState(): string {
|
||||
return `:${SSO_ID_KEY}:${this.sessionId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The URL to return to after a successful OIDC authentication
|
||||
*/
|
||||
public getOidcCallbackUrl(): URL {
|
||||
const url = super.getOidcCallbackUrl();
|
||||
public getOAuthCallbackUrl(): URL {
|
||||
const url = super.getOAuthCallbackUrl();
|
||||
url.protocol = this.protocol;
|
||||
// Trim the double slash into a single slash to comply with https://datatracker.ietf.org/doc/html/rfc8252#section-7.1
|
||||
if (url.href.startsWith(`${url.protocol}//`)) {
|
||||
|
||||
@@ -269,7 +269,7 @@ describe("WebPlatform", () => {
|
||||
expect(spy).toHaveBeenCalledWith(expect.anything(), { bgColor: "#f00" });
|
||||
});
|
||||
|
||||
describe("getOidcCallbackUrl()", () => {
|
||||
describe("getOAuthCallbackUrl()", () => {
|
||||
it("should not include the 'updated' query param in the redirect URI", () => {
|
||||
Object.defineProperty(window, "location", {
|
||||
value: {
|
||||
@@ -280,7 +280,7 @@ describe("WebPlatform", () => {
|
||||
writable: true,
|
||||
});
|
||||
const platform = new WebPlatform();
|
||||
const url = platform.getOidcCallbackUrl();
|
||||
const url = platform.getOAuthCallbackUrl();
|
||||
|
||||
expect(url.searchParams.has("updated")).toBe(false);
|
||||
expect(url.searchParams.get("no_universal_links")).toEqual("true");
|
||||
|
||||
@@ -45,18 +45,11 @@ describe("parseUrlParameters", () => {
|
||||
expect(parsed.params.legacy_sso?.loginToken).toEqual("foobar");
|
||||
});
|
||||
|
||||
it("should parse oidc parameters from fragment", () => {
|
||||
it("should parse oauth2 parameters from fragment", () => {
|
||||
const u = new URL("https://app.element.io/#code=foobar&state=barfoo");
|
||||
const parsed = parseAppUrl(u);
|
||||
expect(parsed.params.oidc_fragment?.code).toEqual("foobar");
|
||||
expect(parsed.params.oidc_fragment?.state).toEqual("barfoo");
|
||||
});
|
||||
|
||||
it("should parse oidc parameters from query", () => {
|
||||
const u = new URL("https://app.element.io/?code=foobar&state=barfoo");
|
||||
const parsed = parseAppUrl(u);
|
||||
expect(parsed.params.oidc_query?.code).toEqual("foobar");
|
||||
expect(parsed.params.oidc_query?.state).toEqual("barfoo");
|
||||
expect(parsed.params.oauth2?.code).toEqual("foobar");
|
||||
expect(parsed.params.oauth2?.state).toEqual("barfoo");
|
||||
});
|
||||
|
||||
it("should parse guest parameters", () => {
|
||||
|
||||
@@ -54,16 +54,11 @@ const urlParameterConfig = {
|
||||
keys: ["loginToken"],
|
||||
location: "query",
|
||||
},
|
||||
// Fragment params for OIDC login, added by the Identity Provider
|
||||
oidc_fragment: {
|
||||
// Fragment params for OAuth2 login, added by the Identity Provider
|
||||
oauth2: {
|
||||
keys: ["code", "state"],
|
||||
location: "fragment",
|
||||
},
|
||||
// Query params for OIDC login, added by the Identity Provider, used as fallback when fragment is unsupported
|
||||
oidc_query: {
|
||||
keys: ["code", "state"],
|
||||
location: "query",
|
||||
},
|
||||
// Fragment params relating to 3pid (email) invites, added in url within the invite email itself
|
||||
threepid: {
|
||||
keys: ["client_secret", "session_id", "hs_url", "is_url", "sid"],
|
||||
|
||||
Reference in New Issue
Block a user