forked from get-convex/convex-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthentication_manager.ts
470 lines (444 loc) · 15.1 KB
/
authentication_manager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
import { Logger } from "../logging.js";
import { LocalSyncState } from "./local_state.js";
import { AuthError, Transition } from "./protocol.js";
import jwtDecode from "jwt-decode";
// setTimout uses 32 bit integer, so it can only
// schedule about 24 days in the future.
const MAXIMUM_REFRESH_DELAY = 20 * 24 * 60 * 60 * 1000; // 20 days
const TOKEN_CONFIRMATION_RETRIES = 2;
/**
* An async function returning the JWT-encoded OpenID Connect Identity Token
* if available.
*
* `forceRefreshToken` is `true` if the server rejected a previously
* returned token, and the client should try to fetch a new one.
*
* See {@link ConvexReactClient.setAuth}.
*
* @public
*/
export type AuthTokenFetcher = (args: {
forceRefreshToken: boolean;
}) => Promise<string | null | undefined>;
/**
* What is provided to the client.
*/
type AuthConfig = {
fetchToken: AuthTokenFetcher;
onAuthChange: (isAuthenticated: boolean) => void;
};
/**
* In general we take 3 steps:
* 1. Fetch a possibly cached token
* 2. Immediately fetch a fresh token without using a cache
* 3. Repeat step 2 before the end of the fresh token's lifetime
*
* When we fetch without using a cache we know when the token
* will expire, and can schedule refetching it.
*
* If we get an error before a scheduled refetch, we go back
* to step 2.
*/
type AuthState =
| { state: "noAuth" }
| {
state: "waitingForServerConfirmationOfCachedToken";
config: AuthConfig;
hasRetried: boolean;
}
| {
state: "initialRefetch";
config: AuthConfig;
}
| {
state: "waitingForServerConfirmationOfFreshToken";
config: AuthConfig;
hadAuth: boolean;
token: string;
}
| {
state: "waitingForScheduledRefetch";
config: AuthConfig;
refetchTokenTimeoutId: ReturnType<typeof setTimeout>;
}
// Special/weird state when we got a valid token
// but could not fetch a new one.
| {
state: "notRefetching";
config: AuthConfig;
};
/**
* Handles the state transitions for auth. The server is the source
* of truth.
*/
export class AuthenticationManager {
private authState: AuthState = { state: "noAuth" };
// Used to detect races involving `setConfig` calls
// while a token is being fetched.
private configVersion = 0;
// Shared by the BaseClient so that the auth manager can easily inspect it
private readonly syncState: LocalSyncState;
// Passed down by BaseClient, sends a message to the server
private readonly authenticate: (token: string) => void;
private readonly stopSocket: () => Promise<void>;
private readonly restartSocket: () => void;
private readonly pauseSocket: () => void;
private readonly resumeSocket: () => void;
// Passed down by BaseClient, sends a message to the server
private readonly clearAuth: () => void;
private readonly logger: Logger;
private readonly refreshTokenLeewaySeconds: number;
private tokenConfirmationRetries = TOKEN_CONFIRMATION_RETRIES;
constructor(
syncState: LocalSyncState,
callbacks: {
authenticate: (token: string) => void;
stopSocket: () => Promise<void>;
restartSocket: () => void;
pauseSocket: () => void;
resumeSocket: () => void;
clearAuth: () => void;
},
config: {
refreshTokenLeewaySeconds: number;
logger: Logger;
},
) {
this.syncState = syncState;
this.authenticate = callbacks.authenticate;
this.stopSocket = callbacks.stopSocket;
this.restartSocket = callbacks.restartSocket;
this.pauseSocket = callbacks.pauseSocket;
this.resumeSocket = callbacks.resumeSocket;
this.clearAuth = callbacks.clearAuth;
this.logger = config.logger;
this.refreshTokenLeewaySeconds = config.refreshTokenLeewaySeconds;
}
async setConfig(
fetchToken: AuthTokenFetcher,
onChange: (isAuthenticated: boolean) => void,
) {
this.resetAuthState();
this._logVerbose("pausing WS for auth token fetch");
this.pauseSocket();
const token = await this.fetchTokenAndGuardAgainstRace(fetchToken, {
forceRefreshToken: false,
});
if (token.isFromOutdatedConfig) {
return;
}
if (token.value) {
this.setAuthState({
state: "waitingForServerConfirmationOfCachedToken",
config: { fetchToken, onAuthChange: onChange },
hasRetried: false,
});
this.authenticate(token.value);
} else {
this.setAuthState({
state: "initialRefetch",
config: { fetchToken, onAuthChange: onChange },
});
// Try again with `forceRefreshToken: true`
await this.refetchToken();
}
this._logVerbose("resuming WS after auth token fetch");
this.resumeSocket();
}
onTransition(serverMessage: Transition) {
if (
!this.syncState.isCurrentOrNewerAuthVersion(
serverMessage.endVersion.identity,
)
) {
// This is a stale transition - client has moved on to
// a newer auth version.
return;
}
if (
serverMessage.endVersion.identity <= serverMessage.startVersion.identity
) {
// This transition did not change auth - it is not a response to Authenticate.
return;
}
if (this.authState.state === "waitingForServerConfirmationOfCachedToken") {
this._logVerbose("server confirmed auth token is valid");
void this.refetchToken();
this.authState.config.onAuthChange(true);
return;
}
if (this.authState.state === "waitingForServerConfirmationOfFreshToken") {
this._logVerbose("server confirmed new auth token is valid");
this.scheduleTokenRefetch(this.authState.token);
this.tokenConfirmationRetries = TOKEN_CONFIRMATION_RETRIES;
if (!this.authState.hadAuth) {
this.authState.config.onAuthChange(true);
}
}
}
onAuthError(serverMessage: AuthError) {
// If auth error comes from a query/mutation/action and the client
// is waiting for the server to confirm a token, ignore.
// TODO: This shouldn't rely on a specific error text, make less brittle.
// May require backend changes.
if (
serverMessage.error === "Convex token identity expired" &&
(this.authState.state === "waitingForServerConfirmationOfFreshToken" ||
this.authState.state === "waitingForServerConfirmationOfCachedToken")
) {
this._logVerbose("ignoring non-auth token expired error");
return;
}
const { baseVersion } = serverMessage;
// Versioned AuthErrors are ignored if the client advanced to
// a newer auth identity
if (baseVersion !== null && baseVersion !== undefined) {
// Error are reporting the previous version, since the server
// didn't advance, hence `+ 1`.
if (!this.syncState.isCurrentOrNewerAuthVersion(baseVersion + 1)) {
this._logVerbose("ignoring auth error for previous auth attempt");
return;
}
void this.tryToReauthenticate(serverMessage);
return;
}
// TODO: Remove after all AuthErrors are versioned
void this.tryToReauthenticate(serverMessage);
}
// This is similar to `refetchToken` defined below, in fact we
// don't represent them as different states, but it is different
// in that we pause the WebSocket so that mutations
// don't retry with bad auth.
private async tryToReauthenticate(serverMessage: AuthError) {
this._logVerbose(`attempting to reauthenticate: ${serverMessage.error}`);
if (
// No way to fetch another token, kaboom
this.authState.state === "noAuth" ||
// We failed on a fresh token, trying another one won't help
(this.authState.state === "waitingForServerConfirmationOfFreshToken" &&
this.tokenConfirmationRetries <= 0)
) {
this.logger.error(
`Failed to authenticate: "${serverMessage.error}", check your server auth config`,
);
if (this.syncState.hasAuth()) {
this.syncState.clearAuth();
}
if (this.authState.state !== "noAuth") {
this.setAndReportAuthFailed(this.authState.config.onAuthChange);
}
return;
}
if (this.authState.state === "waitingForServerConfirmationOfFreshToken") {
this.tokenConfirmationRetries--;
this._logVerbose(
`retrying reauthentication, ${this.tokenConfirmationRetries} retries remaining`,
);
}
await this.stopSocket();
const token = await this.fetchTokenAndGuardAgainstRace(
this.authState.config.fetchToken,
{
forceRefreshToken: true,
},
);
if (token.isFromOutdatedConfig) {
return;
}
if (token.value && this.syncState.isNewAuth(token.value)) {
this.authenticate(token.value);
this.setAuthState({
state: "waitingForServerConfirmationOfFreshToken",
config: this.authState.config,
token: token.value,
hadAuth:
this.authState.state === "notRefetching" ||
this.authState.state === "waitingForScheduledRefetch",
});
} else {
this._logVerbose("reauthentication failed, could not fetch a new token");
if (this.syncState.hasAuth()) {
this.syncState.clearAuth();
}
this.setAndReportAuthFailed(this.authState.config.onAuthChange);
}
this.restartSocket();
}
// Force refetch the token and schedule another refetch
// before the token expires - an active client should never
// need to reauthenticate.
private async refetchToken() {
if (this.authState.state === "noAuth") {
return;
}
this._logVerbose("refetching auth token");
const token = await this.fetchTokenAndGuardAgainstRace(
this.authState.config.fetchToken,
{
forceRefreshToken: true,
},
);
if (token.isFromOutdatedConfig) {
return;
}
if (token.value) {
if (this.syncState.isNewAuth(token.value)) {
this.setAuthState({
state: "waitingForServerConfirmationOfFreshToken",
hadAuth: this.syncState.hasAuth(),
token: token.value,
config: this.authState.config,
});
this.authenticate(token.value);
} else {
this.setAuthState({
state: "notRefetching",
config: this.authState.config,
});
}
} else {
this._logVerbose("refetching token failed");
if (this.syncState.hasAuth()) {
this.clearAuth();
}
this.setAndReportAuthFailed(this.authState.config.onAuthChange);
}
// Restart in case this refetch was triggered via schedule during
// a reauthentication attempt.
this._logVerbose(
"restarting WS after auth token fetch (if currently stopped)",
);
this.restartSocket();
}
private scheduleTokenRefetch(token: string) {
if (this.authState.state === "noAuth") {
return;
}
const decodedToken = this.decodeToken(token);
if (!decodedToken) {
// This is no longer really possible, because
// we wait on server response before scheduling token refetch,
// and the server currently requires JWT tokens.
this.logger.error(
"Auth token is not a valid JWT, cannot refetch the token",
);
return;
}
// iat: issued at time, UTC seconds timestamp at which the JWT was issued
// exp: expiration time, UTC seconds timestamp at which the JWT will expire
const { iat, exp } = decodedToken as { iat?: number; exp?: number };
if (!iat || !exp) {
this.logger.error(
"Auth token does not have required fields, cannot refetch the token",
);
return;
}
// Because the client and server clocks may be out of sync,
// we only know that the token will expire after `exp - iat`,
// and since we just fetched a fresh one we know when that
// will happen.
const tokenValiditySeconds = exp - iat;
if (tokenValiditySeconds <= 2) {
this.logger.error(
"Auth token does not live long enough, cannot refetch the token",
);
return;
}
// Attempt to refresh the token `refreshTokenLeewaySeconds` before it expires,
// or immediately if the token is already expiring soon.
let delay = Math.min(
MAXIMUM_REFRESH_DELAY,
(tokenValiditySeconds - this.refreshTokenLeewaySeconds) * 1000,
);
if (delay <= 0) {
// Refetch immediately, but this might be due to configuring a `refreshTokenLeewaySeconds`
// that is too large compared to the token's actual lifetime.
this.logger.warn(
`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${tokenValiditySeconds}s`,
);
delay = 0;
}
const refetchTokenTimeoutId = setTimeout(() => {
this._logVerbose("running scheduled token refetch");
void this.refetchToken();
}, delay);
this.setAuthState({
state: "waitingForScheduledRefetch",
refetchTokenTimeoutId,
config: this.authState.config,
});
this._logVerbose(
`scheduled preemptive auth token refetching in ${delay}ms`,
);
}
// Protects against simultaneous calls to `setConfig`
// while we're fetching a token
private async fetchTokenAndGuardAgainstRace(
fetchToken: AuthTokenFetcher,
fetchArgs: {
forceRefreshToken: boolean;
},
) {
const originalConfigVersion = ++this.configVersion;
this._logVerbose(
`fetching token with config version ${originalConfigVersion}`,
);
const token = await fetchToken(fetchArgs);
if (this.configVersion !== originalConfigVersion) {
// This is a stale config
this._logVerbose(
`stale config version, expected ${originalConfigVersion}, got ${this.configVersion}`,
);
return { isFromOutdatedConfig: true };
}
return { isFromOutdatedConfig: false, value: token };
}
stop() {
this.resetAuthState();
// Bump this in case we are mid-token-fetch when we get stopped
this.configVersion++;
this._logVerbose(`config version bumped to ${this.configVersion}`);
}
private setAndReportAuthFailed(
onAuthChange: (authenticated: boolean) => void,
) {
onAuthChange(false);
this.resetAuthState();
}
private resetAuthState() {
this.setAuthState({ state: "noAuth" });
}
private setAuthState(newAuth: AuthState) {
const authStateForLog =
newAuth.state === "waitingForServerConfirmationOfFreshToken"
? {
hadAuth: newAuth.hadAuth,
state: newAuth.state,
token: `...${newAuth.token.slice(-7)}`,
}
: { state: newAuth.state };
this._logVerbose(
`setting auth state to ${JSON.stringify(authStateForLog)}`,
);
if (this.authState.state === "waitingForScheduledRefetch") {
clearTimeout(this.authState.refetchTokenTimeoutId);
// The waitingForScheduledRefetch state is the most quiesced authed state.
// Let the syncState know that auth is in a good state, so it can reset failure backoffs
this.syncState.markAuthCompletion();
}
this.authState = newAuth;
}
private decodeToken(token: string) {
try {
return jwtDecode(token);
} catch (e) {
this._logVerbose(
`Error decoding token: ${e instanceof Error ? e.message : "Unknown error"}`,
);
return null;
}
}
private _logVerbose(message: string) {
this.logger.logVerbose(`${message} [v${this.configVersion}]`);
}
}