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

Commit

Permalink
OIDC: Persist details in session storage, create store (#11302)
Browse files Browse the repository at this point in the history
* utils to persist clientId and issuer after oidc authentication

* add dep oidc-client-ts

* persist issuer and clientId after successful oidc auth

* add OidcClientStore

* comments and tidy

* format
  • Loading branch information
Kerry authored Jul 20, 2023
1 parent 882c85a commit 0b0d77c
Show file tree
Hide file tree
Showing 11 changed files with 446 additions and 2 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
"matrix-widget-api": "^1.4.0",
"memoize-one": "^6.0.0",
"minimist": "^1.2.5",
"oidc-client-ts": "^2.2.4",
"opus-recorder": "^8.0.3",
"pako": "^2.0.3",
"png-chunks-extract": "^1.0.0",
Expand Down
7 changes: 6 additions & 1 deletion src/Lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ import { OverwriteLoginPayload } from "./dispatcher/payloads/OverwriteLoginPaylo
import { SdkContextClass } from "./contexts/SDKContext";
import { messageForLoginError } from "./utils/ErrorUtils";
import { completeOidcLogin } from "./utils/oidc/authorize";
import { persistOidcAuthenticatedSettings } from "./utils/oidc/persistOidcSettings";

const HOMESERVER_URL_KEY = "mx_hs_url";
const ID_SERVER_URL_KEY = "mx_is_url";
Expand Down Expand Up @@ -215,7 +216,9 @@ export async function attemptDelegatedAuthLogin(
*/
async function attemptOidcNativeLogin(queryParams: QueryDict): Promise<boolean> {
try {
const { accessToken, homeserverUrl, identityServerUrl } = await completeOidcLogin(queryParams);
const { accessToken, homeserverUrl, identityServerUrl, clientId, issuer } = await completeOidcLogin(
queryParams,
);

const {
user_id: userId,
Expand All @@ -234,6 +237,8 @@ async function attemptOidcNativeLogin(queryParams: QueryDict): Promise<boolean>

logger.debug("Logged in via OIDC native flow");
await onSuccessfulDelegatedAuthLogin(credentials);
// this needs to happen after success handler which clears storages
persistOidcAuthenticatedSettings(clientId, issuer);
return true;
} catch (error) {
logger.error("Failed to login via OIDC", error);
Expand Down
14 changes: 14 additions & 0 deletions src/contexts/SDKContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import TypingStore from "../stores/TypingStore";
import { UserProfilesStore } from "../stores/UserProfilesStore";
import { WidgetLayoutStore } from "../stores/widgets/WidgetLayoutStore";
import { WidgetPermissionStore } from "../stores/widgets/WidgetPermissionStore";
import { OidcClientStore } from "../stores/oidc/OidcClientStore";
import WidgetStore from "../stores/WidgetStore";
import {
VoiceBroadcastPlaybacksStore,
Expand Down Expand Up @@ -80,6 +81,7 @@ export class SdkContextClass {
protected _VoiceBroadcastPlaybacksStore?: VoiceBroadcastPlaybacksStore;
protected _AccountPasswordStore?: AccountPasswordStore;
protected _UserProfilesStore?: UserProfilesStore;
protected _OidcClientStore?: OidcClientStore;

/**
* Automatically construct stores which need to be created eagerly so they can register with
Expand Down Expand Up @@ -203,6 +205,18 @@ export class SdkContextClass {
return this._UserProfilesStore;
}

public get oidcClientStore(): OidcClientStore {
if (!this.client) {
throw new Error("Unable to create OidcClientStore without a client");
}

if (!this._OidcClientStore) {
this._OidcClientStore = new OidcClientStore(this.client);
}

return this._OidcClientStore;
}

public onLoggedOut(): void {
this._UserProfilesStore = undefined;
}
Expand Down
88 changes: 88 additions & 0 deletions src/stores/oidc/OidcClientStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
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 { IDelegatedAuthConfig, MatrixClient, M_AUTHENTICATION } from "matrix-js-sdk/src/client";
import { discoverAndValidateAuthenticationConfig } from "matrix-js-sdk/src/oidc/discovery";
import { logger } from "matrix-js-sdk/src/logger";
import { OidcClient } from "oidc-client-ts";

import { getStoredOidcTokenIssuer, getStoredOidcClientId } from "../../utils/oidc/persistOidcSettings";

/**
* @experimental
* Stores information about configured OIDC provider
*/
export class OidcClientStore {
private oidcClient?: OidcClient;
private initialisingOidcClientPromise: Promise<void> | undefined;
private authenticatedIssuer?: string;
private _accountManagementEndpoint?: string;

public constructor(private readonly matrixClient: MatrixClient) {
this.authenticatedIssuer = getStoredOidcTokenIssuer();
// don't bother initialising store when we didnt authenticate via oidc
if (this.authenticatedIssuer) {
this.getOidcClient();
}
}

/**
* True when the active user is authenticated via OIDC
*/
public get isUserAuthenticatedWithOidc(): boolean {
return !!this.authenticatedIssuer;
}

public get accountManagementEndpoint(): string | undefined {
return this._accountManagementEndpoint;
}

private async getOidcClient(): Promise<OidcClient | undefined> {
if (!this.oidcClient && !this.initialisingOidcClientPromise) {
this.initialisingOidcClientPromise = this.initOidcClient();
}
await this.initialisingOidcClientPromise;
this.initialisingOidcClientPromise = undefined;
return this.oidcClient;
}

private async initOidcClient(): Promise<void> {
const wellKnown = this.matrixClient.getClientWellKnown();
if (!wellKnown) {
logger.error("Cannot initialise OidcClientStore: client well known required.");
return;
}

const delegatedAuthConfig = M_AUTHENTICATION.findIn<IDelegatedAuthConfig>(wellKnown) ?? undefined;
try {
const clientId = getStoredOidcClientId();
const { account, metadata, signingKeys } = await discoverAndValidateAuthenticationConfig(
delegatedAuthConfig,
);
// if no account endpoint is configured default to the issuer
this._accountManagementEndpoint = account ?? metadata.issuer;
this.oidcClient = new OidcClient({
...metadata,
authority: metadata.issuer,
signingKeys,
redirect_uri: window.location.origin,
client_id: clientId,
});
} catch (error) {
logger.error("Failed to initialise OidcClientStore", error);
}
}
}
7 changes: 6 additions & 1 deletion src/utils/oidc/authorize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,20 @@ export const completeOidcLogin = async (
homeserverUrl: string;
identityServerUrl?: string;
accessToken: string;
clientId: string;
issuer: string;
}> => {
const { code, state } = getCodeAndStateFromQueryParams(queryParams);
const { homeserverUrl, tokenResponse, identityServerUrl } = await completeAuthorizationCodeGrant(code, state);
const { homeserverUrl, tokenResponse, identityServerUrl, oidcClientSettings } =
await completeAuthorizationCodeGrant(code, state);

// @TODO(kerrya) do something with the refresh token https://github.com/vector-im/element-web/issues/25444

return {
homeserverUrl: homeserverUrl,
identityServerUrl: identityServerUrl,
accessToken: tokenResponse.access_token,
clientId: oidcClientSettings.clientId,
issuer: oidcClientSettings.issuer,
};
};
51 changes: 51 additions & 0 deletions src/utils/oidc/persistOidcSettings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
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.
*/

const clientIdStorageKey = "mx_oidc_client_id";
const tokenIssuerStorageKey = "mx_oidc_token_issuer";

/**
* Persists oidc clientId and issuer in session storage
* Only set after successful authentication
* @param clientId
* @param issuer
*/
export const persistOidcAuthenticatedSettings = (clientId: string, issuer: string): void => {
sessionStorage.setItem(clientIdStorageKey, clientId);
sessionStorage.setItem(tokenIssuerStorageKey, issuer);
};

/**
* Retrieve stored oidc issuer from session storage
* When user has token from OIDC issuer, this will be set
* @returns issuer or undefined
*/
export const getStoredOidcTokenIssuer = (): string | undefined => {
return sessionStorage.getItem(tokenIssuerStorageKey) ?? undefined;
};

/**
* Retrieves stored oidc client id from session storage
* @returns clientId
* @throws when clientId is not found in session storage
*/
export const getStoredOidcClientId = (): string => {
const clientId = sessionStorage.getItem(clientIdStorageKey);
if (!clientId) {
throw new Error("Oidc client id not found in storage");
}
return clientId;
};
18 changes: 18 additions & 0 deletions test/components/structures/MatrixChat-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -887,6 +887,15 @@ describe("<MatrixChat />", () => {

expect(loginClient.clearStores).not.toHaveBeenCalled();
});

it("should not store clientId or issuer", async () => {
getComponent({ realQueryParams });

await flushPromises();

expect(sessionStorageSetSpy).not.toHaveBeenCalledWith("mx_oidc_client_id", clientId);
expect(sessionStorageSetSpy).not.toHaveBeenCalledWith("mx_oidc_token_issuer", issuer);
});
});

describe("when login succeeds", () => {
Expand All @@ -911,6 +920,15 @@ describe("<MatrixChat />", () => {
expect(localStorageSetSpy).toHaveBeenCalledWith("mx_device_id", deviceId);
});

it("should store clientId and issuer in session storage", async () => {
getComponent({ realQueryParams });

await flushPromises();

expect(sessionStorageSetSpy).toHaveBeenCalledWith("mx_oidc_client_id", clientId);
expect(sessionStorageSetSpy).toHaveBeenCalledWith("mx_oidc_token_issuer", issuer);
});

it("should set logged in and start MatrixClient", async () => {
getComponent({ realQueryParams });

Expand Down
14 changes: 14 additions & 0 deletions test/contexts/SdkContext-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
import { MatrixClient } from "matrix-js-sdk/src/matrix";

import { SdkContextClass } from "../../src/contexts/SDKContext";
import { OidcClientStore } from "../../src/stores/oidc/OidcClientStore";
import { UserProfilesStore } from "../../src/stores/UserProfilesStore";
import { VoiceBroadcastPreRecordingStore } from "../../src/voice-broadcast";
import { createTestClient } from "../test-utils";
Expand Down Expand Up @@ -52,6 +53,12 @@ describe("SdkContextClass", () => {
}).toThrow("Unable to create UserProfilesStore without a client");
});

it("oidcClientStore should raise an error without a client", () => {
expect(() => {
sdkContext.oidcClientStore;
}).toThrow("Unable to create OidcClientStore without a client");
});

describe("when SDKContext has a client", () => {
beforeEach(() => {
sdkContext.client = client;
Expand All @@ -69,5 +76,12 @@ describe("SdkContextClass", () => {
sdkContext.onLoggedOut();
expect(sdkContext.userProfilesStore).not.toBe(store);
});

it("oidcClientstore should return a OidcClientStore", () => {
const store = sdkContext.oidcClientStore;
expect(store).toBeInstanceOf(OidcClientStore);
// it should return the same instance
expect(sdkContext.oidcClientStore).toBe(store);
});
});
});
Loading

0 comments on commit 0b0d77c

Please sign in to comment.