|
| 1 | +/* |
| 2 | +Copyright 2022 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 { logger } from "matrix-js-sdk/src/logger"; |
| 18 | +import { MatrixClient } from "matrix-js-sdk/src"; |
| 19 | +import { randomString } from "matrix-js-sdk/src/randomstring"; |
| 20 | +import Mutex from "idb-mutex"; |
| 21 | +import { Optional } from "matrix-events-sdk"; |
| 22 | + |
| 23 | +import { IMatrixClientCreds, MatrixClientPeg } from "./MatrixClientPeg"; |
| 24 | +import { getRenewedStoredSessionVars, hydrateSessionInPlace } from "./Lifecycle"; |
| 25 | +import { IDB_SUPPORTED } from "./utils/StorageManager"; |
| 26 | + |
| 27 | +export interface IRenewedMatrixClientCreds extends Pick<IMatrixClientCreds, |
| 28 | + "accessToken" | "accessTokenExpiryTs" | "accessTokenRefreshToken"> {} |
| 29 | + |
| 30 | +const LOCALSTORAGE_UPDATED_BY_KEY = "mx_token_updated_by"; |
| 31 | + |
| 32 | +const CLIENT_ID = randomString(64); |
| 33 | + |
| 34 | +export class TokenLifecycle { |
| 35 | + public static readonly instance = new TokenLifecycle(); |
| 36 | + |
| 37 | + private refreshAtTimerId: number; |
| 38 | + private mutex: Mutex; |
| 39 | + |
| 40 | + protected constructor() { |
| 41 | + // we only really want one of these floating around, so private-ish |
| 42 | + // constructor. Protected allows for unit tests. |
| 43 | + |
| 44 | + // Don't try to create a mutex if it'll explode |
| 45 | + if (IDB_SUPPORTED) { |
| 46 | + this.mutex = new Mutex("token_refresh", null, { |
| 47 | + expiry: 120000, // 2 minutes - enough time for the refresh request to time out |
| 48 | + }); |
| 49 | + } |
| 50 | + |
| 51 | + // Watch for other tabs causing token refreshes, so we can react to them too. |
| 52 | + window.addEventListener("storage", (ev: StorageEvent) => { |
| 53 | + if (ev.key === LOCALSTORAGE_UPDATED_BY_KEY) { |
| 54 | + const updateBy = localStorage.getItem(LOCALSTORAGE_UPDATED_BY_KEY); |
| 55 | + if (!updateBy || updateBy === CLIENT_ID) return; // ignore deletions & echos |
| 56 | + |
| 57 | + logger.info("TokenLifecycle#storageWatch: Token update received"); |
| 58 | + |
| 59 | + // noinspection JSIgnoredPromiseFromCall |
| 60 | + this.forceHydration(); |
| 61 | + } |
| 62 | + }); |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Can the client reasonably support token refreshes? |
| 67 | + */ |
| 68 | + public get isFeasible(): boolean { |
| 69 | + return IDB_SUPPORTED; |
| 70 | + } |
| 71 | + |
| 72 | + // noinspection JSMethodCanBeStatic |
| 73 | + private get fiveMinutesAgo(): number { |
| 74 | + return Date.now() - 300000; |
| 75 | + } |
| 76 | + |
| 77 | + // noinspection JSMethodCanBeStatic |
| 78 | + private get fiveMinutesFromNow(): number { |
| 79 | + return Date.now() + 300000; |
| 80 | + } |
| 81 | + |
| 82 | + public flagNewCredentialsPersisted() { |
| 83 | + logger.info("TokenLifecycle#flagPersisted: Credentials marked as persisted - flagging for other tabs"); |
| 84 | + if (localStorage.getItem(LOCALSTORAGE_UPDATED_BY_KEY) !== CLIENT_ID) { |
| 85 | + localStorage.setItem(LOCALSTORAGE_UPDATED_BY_KEY, CLIENT_ID); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * Attempts a token renewal, if renewal is needed/possible. If renewal is not possible |
| 91 | + * then this will return falsy. Otherwise, the new token's details (credentials) will |
| 92 | + * be returned or an error if something went wrong. |
| 93 | + * @param {IMatrixClientCreds} credentials The input credentials. |
| 94 | + * @param {MatrixClient} client A client set up with those credentials. |
| 95 | + * @returns {Promise<Optional<IRenewedMatrixClientCreds>>} Resolves to the new credentials, |
| 96 | + * or falsy if renewal not possible/needed. Throws on error. |
| 97 | + */ |
| 98 | + public async tryTokenExchangeIfNeeded( |
| 99 | + credentials: IMatrixClientCreds, |
| 100 | + client: MatrixClient, |
| 101 | + ): Promise<Optional<IRenewedMatrixClientCreds>> { |
| 102 | + if (!credentials.accessTokenExpiryTs && credentials.accessTokenRefreshToken) { |
| 103 | + logger.warn( |
| 104 | + "TokenLifecycle#tryExchange: Got a refresh token, but no expiration time. The server is " + |
| 105 | + "not compliant with the specification and might result in unexpected logouts.", |
| 106 | + ); |
| 107 | + } |
| 108 | + |
| 109 | + if (!this.isFeasible) { |
| 110 | + logger.warn("TokenLifecycle#tryExchange: Client cannot do token refreshes reliably"); |
| 111 | + return; |
| 112 | + } |
| 113 | + |
| 114 | + if (credentials.accessTokenExpiryTs && credentials.accessTokenRefreshToken) { |
| 115 | + if (this.fiveMinutesAgo >= credentials.accessTokenExpiryTs) { |
| 116 | + logger.info("TokenLifecycle#tryExchange: Token has or will expire soon, refreshing"); |
| 117 | + return await this.doTokenRefresh(credentials, client); |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + // noinspection JSMethodCanBeStatic |
| 123 | + private async doTokenRefresh( |
| 124 | + credentials: IMatrixClientCreds, |
| 125 | + client: MatrixClient, |
| 126 | + ): Promise<Optional<IRenewedMatrixClientCreds>> { |
| 127 | + try { |
| 128 | + logger.info("TokenLifecycle#doRefresh: Acquiring lock"); |
| 129 | + await this.mutex.lock(); |
| 130 | + logger.info("TokenLifecycle#doRefresh: Lock acquired"); |
| 131 | + |
| 132 | + logger.info("TokenLifecycle#doRefresh: Performing refresh"); |
| 133 | + localStorage.removeItem(LOCALSTORAGE_UPDATED_BY_KEY); |
| 134 | + const newCreds = await client.refreshToken(credentials.accessTokenRefreshToken); |
| 135 | + return { |
| 136 | + // We use the browser's local time to do two things: |
| 137 | + // 1. Avoid having to write code that counts down and stores a "time left" variable |
| 138 | + // 2. Work around any time drift weirdness by assuming the user's local machine will |
| 139 | + // drift consistently with itself. |
| 140 | + // We additionally add our own safety buffer when renewing tokens to avoid cases where |
| 141 | + // the time drift is accelerating. |
| 142 | + accessTokenExpiryTs: Date.now() + newCreds.expires_in_ms, |
| 143 | + accessToken: newCreds.access_token, |
| 144 | + accessTokenRefreshToken: newCreds.refresh_token, |
| 145 | + }; |
| 146 | + } catch (e) { |
| 147 | + logger.error("TokenLifecycle#doRefresh: Error refreshing token: ", e); |
| 148 | + if (e.errcode === "M_UNKNOWN_TOKEN") { |
| 149 | + // Emit the logout manually because the function inhibits it. |
| 150 | + client.emit("Session.logged_out", e); |
| 151 | + } else { |
| 152 | + throw e; // we can't do anything with it, so re-throw |
| 153 | + } |
| 154 | + } finally { |
| 155 | + logger.info("TokenLifecycle#doRefresh: Releasing lock"); |
| 156 | + await this.mutex.unlock(); |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + public startTimers(credentials: IMatrixClientCreds) { |
| 161 | + this.stopTimers(); |
| 162 | + |
| 163 | + if (!credentials.accessTokenExpiryTs && credentials.accessTokenRefreshToken) { |
| 164 | + logger.warn( |
| 165 | + "TokenLifecycle#start: Got a refresh token, but no expiration time. The server is " + |
| 166 | + "not compliant with the specification and might result in unexpected logouts.", |
| 167 | + ); |
| 168 | + } |
| 169 | + |
| 170 | + if (!this.isFeasible) { |
| 171 | + logger.warn("TokenLifecycle#start: Not starting refresh timers - browser unsupported"); |
| 172 | + } |
| 173 | + |
| 174 | + if (credentials.accessTokenExpiryTs && credentials.accessTokenRefreshToken) { |
| 175 | + // We schedule the refresh task for 5 minutes before the expiration timestamp as |
| 176 | + // a safety buffer. We assume/hope that servers won't be expiring tokens faster |
| 177 | + // than every 5 minutes, but we do need to consider cases where the expiration is |
| 178 | + // fairly quick (<10 minutes, for example). |
| 179 | + let relativeTime = credentials.accessTokenExpiryTs - this.fiveMinutesFromNow; |
| 180 | + if (relativeTime <= 0) { |
| 181 | + logger.warn(`TokenLifecycle#start: Refresh was set for ${relativeTime}ms - readjusting`); |
| 182 | + relativeTime = Math.floor(Math.random() * 5000) + 30000; // 30 seconds + 5s jitter |
| 183 | + } |
| 184 | + this.refreshAtTimerId = setTimeout(() => { |
| 185 | + // noinspection JSIgnoredPromiseFromCall |
| 186 | + this.forceTokenExchange(); |
| 187 | + }, relativeTime); |
| 188 | + logger.info(`TokenLifecycle#start: Refresh timer set for ${relativeTime}ms from now`); |
| 189 | + } else { |
| 190 | + logger.info("TokenLifecycle#start: Not setting a refresh timer - token not renewable"); |
| 191 | + } |
| 192 | + } |
| 193 | + |
| 194 | + public stopTimers() { |
| 195 | + clearTimeout(this.refreshAtTimerId); |
| 196 | + logger.info("TokenLifecycle#stop: Stopped refresh timer (if it was running)"); |
| 197 | + } |
| 198 | + |
| 199 | + private async forceTokenExchange() { |
| 200 | + const credentials = MatrixClientPeg.getCredentials(); |
| 201 | + await this.rehydrate(await this.doTokenRefresh(credentials, MatrixClientPeg.get())); |
| 202 | + this.flagNewCredentialsPersisted(); |
| 203 | + } |
| 204 | + |
| 205 | + private async forceHydration() { |
| 206 | + const { |
| 207 | + accessToken, |
| 208 | + accessTokenRefreshToken, |
| 209 | + accessTokenExpiryTs, |
| 210 | + } = await getRenewedStoredSessionVars(); |
| 211 | + return this.rehydrate({ accessToken, accessTokenRefreshToken, accessTokenExpiryTs }); |
| 212 | + } |
| 213 | + |
| 214 | + private async rehydrate(newCreds: IRenewedMatrixClientCreds) { |
| 215 | + const credentials = MatrixClientPeg.getCredentials(); |
| 216 | + try { |
| 217 | + if (!newCreds) { |
| 218 | + logger.error("TokenLifecycle#expireExchange: Expecting new credentials, got nothing. Rescheduling."); |
| 219 | + this.startTimers(credentials); |
| 220 | + } else { |
| 221 | + logger.info("TokenLifecycle#expireExchange: Updating client credentials using rehydration"); |
| 222 | + await hydrateSessionInPlace({ |
| 223 | + ...credentials, |
| 224 | + ...newCreds, // override from credentials |
| 225 | + }); |
| 226 | + // hydrateSessionInPlace will ultimately call back to startTimers() for us, so no need to do it here. |
| 227 | + } |
| 228 | + } catch (e) { |
| 229 | + logger.error("TokenLifecycle#expireExchange: Error getting new credentials. Rescheduling.", e); |
| 230 | + this.startTimers(credentials); |
| 231 | + } |
| 232 | + } |
| 233 | +} |
0 commit comments