Skip to content

Commit 0b0d77c

Browse files
author
Kerry
authored
OIDC: Persist details in session storage, create store (matrix-org#11302)
* 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
1 parent 882c85a commit 0b0d77c

File tree

11 files changed

+446
-2
lines changed

11 files changed

+446
-2
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@
101101
"matrix-widget-api": "^1.4.0",
102102
"memoize-one": "^6.0.0",
103103
"minimist": "^1.2.5",
104+
"oidc-client-ts": "^2.2.4",
104105
"opus-recorder": "^8.0.3",
105106
"pako": "^2.0.3",
106107
"png-chunks-extract": "^1.0.0",

src/Lifecycle.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ import { OverwriteLoginPayload } from "./dispatcher/payloads/OverwriteLoginPaylo
6666
import { SdkContextClass } from "./contexts/SDKContext";
6767
import { messageForLoginError } from "./utils/ErrorUtils";
6868
import { completeOidcLogin } from "./utils/oidc/authorize";
69+
import { persistOidcAuthenticatedSettings } from "./utils/oidc/persistOidcSettings";
6970

7071
const HOMESERVER_URL_KEY = "mx_hs_url";
7172
const ID_SERVER_URL_KEY = "mx_is_url";
@@ -215,7 +216,9 @@ export async function attemptDelegatedAuthLogin(
215216
*/
216217
async function attemptOidcNativeLogin(queryParams: QueryDict): Promise<boolean> {
217218
try {
218-
const { accessToken, homeserverUrl, identityServerUrl } = await completeOidcLogin(queryParams);
219+
const { accessToken, homeserverUrl, identityServerUrl, clientId, issuer } = await completeOidcLogin(
220+
queryParams,
221+
);
219222

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

235238
logger.debug("Logged in via OIDC native flow");
236239
await onSuccessfulDelegatedAuthLogin(credentials);
240+
// this needs to happen after success handler which clears storages
241+
persistOidcAuthenticatedSettings(clientId, issuer);
237242
return true;
238243
} catch (error) {
239244
logger.error("Failed to login via OIDC", error);

src/contexts/SDKContext.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import TypingStore from "../stores/TypingStore";
3131
import { UserProfilesStore } from "../stores/UserProfilesStore";
3232
import { WidgetLayoutStore } from "../stores/widgets/WidgetLayoutStore";
3333
import { WidgetPermissionStore } from "../stores/widgets/WidgetPermissionStore";
34+
import { OidcClientStore } from "../stores/oidc/OidcClientStore";
3435
import WidgetStore from "../stores/WidgetStore";
3536
import {
3637
VoiceBroadcastPlaybacksStore,
@@ -80,6 +81,7 @@ export class SdkContextClass {
8081
protected _VoiceBroadcastPlaybacksStore?: VoiceBroadcastPlaybacksStore;
8182
protected _AccountPasswordStore?: AccountPasswordStore;
8283
protected _UserProfilesStore?: UserProfilesStore;
84+
protected _OidcClientStore?: OidcClientStore;
8385

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

208+
public get oidcClientStore(): OidcClientStore {
209+
if (!this.client) {
210+
throw new Error("Unable to create OidcClientStore without a client");
211+
}
212+
213+
if (!this._OidcClientStore) {
214+
this._OidcClientStore = new OidcClientStore(this.client);
215+
}
216+
217+
return this._OidcClientStore;
218+
}
219+
206220
public onLoggedOut(): void {
207221
this._UserProfilesStore = undefined;
208222
}

src/stores/oidc/OidcClientStore.ts

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/*
2+
Copyright 2023 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import { IDelegatedAuthConfig, MatrixClient, M_AUTHENTICATION } from "matrix-js-sdk/src/client";
18+
import { discoverAndValidateAuthenticationConfig } from "matrix-js-sdk/src/oidc/discovery";
19+
import { logger } from "matrix-js-sdk/src/logger";
20+
import { OidcClient } from "oidc-client-ts";
21+
22+
import { getStoredOidcTokenIssuer, getStoredOidcClientId } from "../../utils/oidc/persistOidcSettings";
23+
24+
/**
25+
* @experimental
26+
* Stores information about configured OIDC provider
27+
*/
28+
export class OidcClientStore {
29+
private oidcClient?: OidcClient;
30+
private initialisingOidcClientPromise: Promise<void> | undefined;
31+
private authenticatedIssuer?: string;
32+
private _accountManagementEndpoint?: string;
33+
34+
public constructor(private readonly matrixClient: MatrixClient) {
35+
this.authenticatedIssuer = getStoredOidcTokenIssuer();
36+
// don't bother initialising store when we didnt authenticate via oidc
37+
if (this.authenticatedIssuer) {
38+
this.getOidcClient();
39+
}
40+
}
41+
42+
/**
43+
* True when the active user is authenticated via OIDC
44+
*/
45+
public get isUserAuthenticatedWithOidc(): boolean {
46+
return !!this.authenticatedIssuer;
47+
}
48+
49+
public get accountManagementEndpoint(): string | undefined {
50+
return this._accountManagementEndpoint;
51+
}
52+
53+
private async getOidcClient(): Promise<OidcClient | undefined> {
54+
if (!this.oidcClient && !this.initialisingOidcClientPromise) {
55+
this.initialisingOidcClientPromise = this.initOidcClient();
56+
}
57+
await this.initialisingOidcClientPromise;
58+
this.initialisingOidcClientPromise = undefined;
59+
return this.oidcClient;
60+
}
61+
62+
private async initOidcClient(): Promise<void> {
63+
const wellKnown = this.matrixClient.getClientWellKnown();
64+
if (!wellKnown) {
65+
logger.error("Cannot initialise OidcClientStore: client well known required.");
66+
return;
67+
}
68+
69+
const delegatedAuthConfig = M_AUTHENTICATION.findIn<IDelegatedAuthConfig>(wellKnown) ?? undefined;
70+
try {
71+
const clientId = getStoredOidcClientId();
72+
const { account, metadata, signingKeys } = await discoverAndValidateAuthenticationConfig(
73+
delegatedAuthConfig,
74+
);
75+
// if no account endpoint is configured default to the issuer
76+
this._accountManagementEndpoint = account ?? metadata.issuer;
77+
this.oidcClient = new OidcClient({
78+
...metadata,
79+
authority: metadata.issuer,
80+
signingKeys,
81+
redirect_uri: window.location.origin,
82+
client_id: clientId,
83+
});
84+
} catch (error) {
85+
logger.error("Failed to initialise OidcClientStore", error);
86+
}
87+
}
88+
}

src/utils/oidc/authorize.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,15 +81,20 @@ export const completeOidcLogin = async (
8181
homeserverUrl: string;
8282
identityServerUrl?: string;
8383
accessToken: string;
84+
clientId: string;
85+
issuer: string;
8486
}> => {
8587
const { code, state } = getCodeAndStateFromQueryParams(queryParams);
86-
const { homeserverUrl, tokenResponse, identityServerUrl } = await completeAuthorizationCodeGrant(code, state);
88+
const { homeserverUrl, tokenResponse, identityServerUrl, oidcClientSettings } =
89+
await completeAuthorizationCodeGrant(code, state);
8790

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

9093
return {
9194
homeserverUrl: homeserverUrl,
9295
identityServerUrl: identityServerUrl,
9396
accessToken: tokenResponse.access_token,
97+
clientId: oidcClientSettings.clientId,
98+
issuer: oidcClientSettings.issuer,
9499
};
95100
};
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
Copyright 2023 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
const clientIdStorageKey = "mx_oidc_client_id";
18+
const tokenIssuerStorageKey = "mx_oidc_token_issuer";
19+
20+
/**
21+
* Persists oidc clientId and issuer in session storage
22+
* Only set after successful authentication
23+
* @param clientId
24+
* @param issuer
25+
*/
26+
export const persistOidcAuthenticatedSettings = (clientId: string, issuer: string): void => {
27+
sessionStorage.setItem(clientIdStorageKey, clientId);
28+
sessionStorage.setItem(tokenIssuerStorageKey, issuer);
29+
};
30+
31+
/**
32+
* Retrieve stored oidc issuer from session storage
33+
* When user has token from OIDC issuer, this will be set
34+
* @returns issuer or undefined
35+
*/
36+
export const getStoredOidcTokenIssuer = (): string | undefined => {
37+
return sessionStorage.getItem(tokenIssuerStorageKey) ?? undefined;
38+
};
39+
40+
/**
41+
* Retrieves stored oidc client id from session storage
42+
* @returns clientId
43+
* @throws when clientId is not found in session storage
44+
*/
45+
export const getStoredOidcClientId = (): string => {
46+
const clientId = sessionStorage.getItem(clientIdStorageKey);
47+
if (!clientId) {
48+
throw new Error("Oidc client id not found in storage");
49+
}
50+
return clientId;
51+
};

test/components/structures/MatrixChat-test.tsx

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -887,6 +887,15 @@ describe("<MatrixChat />", () => {
887887

888888
expect(loginClient.clearStores).not.toHaveBeenCalled();
889889
});
890+
891+
it("should not store clientId or issuer", async () => {
892+
getComponent({ realQueryParams });
893+
894+
await flushPromises();
895+
896+
expect(sessionStorageSetSpy).not.toHaveBeenCalledWith("mx_oidc_client_id", clientId);
897+
expect(sessionStorageSetSpy).not.toHaveBeenCalledWith("mx_oidc_token_issuer", issuer);
898+
});
890899
});
891900

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

923+
it("should store clientId and issuer in session storage", async () => {
924+
getComponent({ realQueryParams });
925+
926+
await flushPromises();
927+
928+
expect(sessionStorageSetSpy).toHaveBeenCalledWith("mx_oidc_client_id", clientId);
929+
expect(sessionStorageSetSpy).toHaveBeenCalledWith("mx_oidc_token_issuer", issuer);
930+
});
931+
914932
it("should set logged in and start MatrixClient", async () => {
915933
getComponent({ realQueryParams });
916934

test/contexts/SdkContext-test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ limitations under the License.
1717
import { MatrixClient } from "matrix-js-sdk/src/matrix";
1818

1919
import { SdkContextClass } from "../../src/contexts/SDKContext";
20+
import { OidcClientStore } from "../../src/stores/oidc/OidcClientStore";
2021
import { UserProfilesStore } from "../../src/stores/UserProfilesStore";
2122
import { VoiceBroadcastPreRecordingStore } from "../../src/voice-broadcast";
2223
import { createTestClient } from "../test-utils";
@@ -52,6 +53,12 @@ describe("SdkContextClass", () => {
5253
}).toThrow("Unable to create UserProfilesStore without a client");
5354
});
5455

56+
it("oidcClientStore should raise an error without a client", () => {
57+
expect(() => {
58+
sdkContext.oidcClientStore;
59+
}).toThrow("Unable to create OidcClientStore without a client");
60+
});
61+
5562
describe("when SDKContext has a client", () => {
5663
beforeEach(() => {
5764
sdkContext.client = client;
@@ -69,5 +76,12 @@ describe("SdkContextClass", () => {
6976
sdkContext.onLoggedOut();
7077
expect(sdkContext.userProfilesStore).not.toBe(store);
7178
});
79+
80+
it("oidcClientstore should return a OidcClientStore", () => {
81+
const store = sdkContext.oidcClientStore;
82+
expect(store).toBeInstanceOf(OidcClientStore);
83+
// it should return the same instance
84+
expect(sdkContext.oidcClientStore).toBe(store);
85+
});
7286
});
7387
});

0 commit comments

Comments
 (0)