Repository navigation
Expand file tree
/
Copy pathsecretsManager.ts
More file actions
386 lines (343 loc) · 10.9 KB
/
Copy pathsecretsManager.ts
File metadata and controls
386 lines (343 loc) · 10.9 KB
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
import { z } from "zod";
import { toSafeHost } from "../common/url";
import { isValidDeploymentUrl } from "../common/validation";
import { DeploymentSchema, type Deployment } from "../deployment/types";
import type { OAuth2ClientRegistrationResponse } from "coder/site/src/api/typesGenerated";
import type { SecretStorage, Disposable } from "vscode";
import type { Logger } from "../logging/logger";
import type { MementoManager } from "./mementoManager";
// Per-deployment keys ensure atomic operations (multiple windows writing to a
// shared key could drop data) and enable proper VS Code change events.
const SESSION_KEY_PREFIX = "coder.session.";
const OAUTH_CLIENT_PREFIX = "coder.oauth.client.";
type SecretKeyPrefix = typeof SESSION_KEY_PREFIX | typeof OAUTH_CLIENT_PREFIX;
const CURRENT_DEPLOYMENT_KEY = "coder.currentDeployment";
const DEFAULT_MAX_DEPLOYMENTS = 10;
const LEGACY_SESSION_TOKEN_KEY = "sessionToken";
const CurrentDeploymentStateSchema = z.object({
deployment: DeploymentSchema.nullable(),
});
export type CurrentDeploymentState = z.infer<
typeof CurrentDeploymentStateSchema
>;
/**
* OAuth token data stored alongside session auth.
* When present, indicates the session is authenticated via OAuth.
*/
const OAuthTokenDataSchema = z.object({
refresh_token: z.string().optional(),
scope: z.string(),
expiry_timestamp: z.number(),
/** Registration the tokens were issued to; if absent, the stored registration is used. */
registration: z
.object({ client_id: z.string(), client_secret: z.string().optional() })
.optional(),
});
export type OAuthTokenData = z.infer<typeof OAuthTokenDataSchema>;
const SessionAuthSchema = z.object({
url: z.string(),
token: z.string(),
/** Username the session was created for, used to detect account switches */
username: z.string().optional(),
/** If present, this session uses OAuth authentication */
oauth: OAuthTokenDataSchema.optional(),
});
export type SessionAuth = z.infer<typeof SessionAuthSchema>;
export class SecretsManager {
constructor(
private readonly secrets: SecretStorage,
private readonly mementoManager: MementoManager,
private readonly logger: Logger,
) {}
private buildKey(prefix: SecretKeyPrefix, safeHostname: string): string {
return `${prefix}${safeHostname}`;
}
private assertSessionAuthHostname(safeHostname: string, url: string): void {
let authHostname: string;
try {
authHostname = toSafeHost(url);
} catch {
throw new Error(
`Session auth hostname mismatch: expected "${safeHostname}", got an invalid URL`,
);
}
if (authHostname !== safeHostname) {
throw new Error(
`Session auth hostname mismatch: expected "${safeHostname}", got "${authHostname}"`,
);
}
}
private async getSecret<T>(
prefix: SecretKeyPrefix,
safeHostname: string,
): Promise<T | undefined> {
try {
const data = await this.secrets.get(this.buildKey(prefix, safeHostname));
if (!data) {
return undefined;
}
return JSON.parse(data) as T;
} catch {
return undefined;
}
}
private async setSecret<T>(
prefix: SecretKeyPrefix,
safeHostname: string,
value: T,
): Promise<void> {
await this.secrets.store(
this.buildKey(prefix, safeHostname),
JSON.stringify(value),
);
await this.recordDeploymentAccess(safeHostname);
}
private async clearSecret(
prefix: SecretKeyPrefix,
safeHostname: string,
): Promise<void> {
await this.secrets.delete(this.buildKey(prefix, safeHostname));
}
/**
* Sets the current deployment and triggers a cross-window sync event.
*/
public async setCurrentDeployment(
deployment: Deployment | undefined,
): Promise<void> {
const state = CurrentDeploymentStateSchema.parse({
deployment: deployment ?? null,
});
// Add timestamp for cross-window change detection
const stateWithTimestamp = {
...state,
timestamp: new Date().toISOString(),
};
await this.secrets.store(
CURRENT_DEPLOYMENT_KEY,
JSON.stringify(stateWithTimestamp),
);
}
/**
* Gets the current deployment from storage.
*/
public async getCurrentDeployment(): Promise<Deployment | null> {
try {
const data = await this.secrets.get(CURRENT_DEPLOYMENT_KEY);
if (!data) {
return null;
}
const parsed: unknown = JSON.parse(data);
const result = CurrentDeploymentStateSchema.safeParse(parsed);
const deployment = result.success ? result.data.deployment : null;
// Treat an invalid URL stored by an older version as signed out, so the
// next sign-in replaces it.
if (!deployment) {
return null;
}
if (!isValidDeploymentUrl(deployment.url)) {
this.logger.warn("Ignoring current deployment with an invalid URL");
return null;
}
// Older versions stored the bare hostname for every origin.
return { ...deployment, safeHostname: toSafeHost(deployment.url) };
} catch {
return null;
}
}
/**
* Listens for deployment changes from any VS Code window.
* Fires when login, logout, or deployment switch occurs.
*/
public onDidChangeCurrentDeployment(
listener: (state: CurrentDeploymentState) => void | Promise<void>,
): Disposable {
return this.secrets.onDidChange(async (e) => {
if (e.key !== CURRENT_DEPLOYMENT_KEY) {
return;
}
const deployment = await this.getCurrentDeployment();
try {
await listener({ deployment });
} catch (err) {
this.logger.error(
"Error in onDidChangeCurrentDeployment listener",
err,
);
}
});
}
/**
* Listen for changes to a specific deployment's session auth.
*/
public onDidChangeSessionAuth(
safeHostname: string,
listener: (auth: SessionAuth | undefined) => void | Promise<void>,
): Disposable {
const sessionKey = this.buildKey(SESSION_KEY_PREFIX, safeHostname);
return this.secrets.onDidChange(async (e) => {
if (e.key !== sessionKey) {
return;
}
const auth = await this.getSessionAuth(safeHostname);
try {
await listener(auth);
} catch (err) {
this.logger.error("Error in onDidChangeSessionAuth listener", err);
}
});
}
/** By origin label; callers with a URL use `getSessionAuthForUrl`. */
public async getSessionAuth(
safeHostname: string,
): Promise<SessionAuth | undefined> {
const data = await this.getSecret<unknown>(
SESSION_KEY_PREFIX,
safeHostname,
);
if (!data) {
return undefined;
}
const result = SessionAuthSchema.safeParse(data);
if (!result.success) {
return undefined;
}
try {
this.assertSessionAuthHostname(safeHostname, result.data.url);
} catch (error) {
this.logger.warn("Ignoring stored session auth:", error);
return undefined;
}
// Treat an invalid URL stored by an older version as missing, so connecting
// prompts a sign-in instead of failing.
if (!isValidDeploymentUrl(result.data.url)) {
this.logger.warn(
`Ignoring stored session auth for ${safeHostname}: the URL is invalid`,
);
return undefined;
}
return result.data;
}
/**
* The stored session auth for `url`'s origin. Fails closed on an
* unparsable URL.
*/
public async getSessionAuthForUrl(
url: string,
): Promise<SessionAuth | undefined> {
let safeHostname: string;
try {
safeHostname = toSafeHost(url);
} catch {
return undefined;
}
return this.getSessionAuth(safeHostname);
}
/**
* Store session auth for a deployment.
*
* @throws If the auth URL is invalid or its hostname does not match the
* deployment.
*/
public async setSessionAuth(
safeHostname: string,
auth: SessionAuth,
): Promise<void> {
// Parse through schema to strip any extra fields
const state = SessionAuthSchema.parse(auth);
this.assertSessionAuthHostname(safeHostname, state.url);
await this.setSecret(SESSION_KEY_PREFIX, safeHostname, state);
}
private clearSessionAuth(safeHostname: string): Promise<void> {
return this.clearSecret(SESSION_KEY_PREFIX, safeHostname);
}
/**
* Record that a deployment was accessed by updating its timestamp.
* Prunes deployments beyond maxCount, clearing their auth data.
*/
public async recordDeploymentAccess(
safeHostname: string,
maxCount = DEFAULT_MAX_DEPLOYMENTS,
): Promise<void> {
await this.mementoManager.updateDeploymentAccess(safeHostname);
// Prune if needed - errors here shouldn't block deployment access
try {
const allHostnames = await this.getKnownSafeHostnames();
const toRemove = allHostnames.slice(maxCount);
await Promise.all(toRemove.map((h) => this.clearAllAuthData(h)));
} catch {
this.logger.warn("Failed to prune old deployments");
}
}
/**
* Clear all auth data for a deployment, including its memento-backed
* state (access timestamp, surfaced banners), so both stores stay in sync.
*/
public async clearAllAuthData(safeHostname: string): Promise<void> {
await Promise.all([
this.clearSessionAuth(safeHostname),
this.clearOAuthClientRegistration(safeHostname),
this.mementoManager.clearDeploymentData(safeHostname),
]);
}
/**
* Get all known hostnames, ordered by most recently accessed.
* Derives the list from actual session secrets stored.
*/
public async getKnownSafeHostnames(): Promise<string[]> {
const keys = await this.secrets.keys();
const sessionHostnames = keys
.filter((k) => k.startsWith(SESSION_KEY_PREFIX))
.map((k) => k.slice(SESSION_KEY_PREFIX.length));
// Sort by access timestamp (most recent first)
const withTimestamps = sessionHostnames.map((hostname) => ({
hostname,
accessedAt: this.mementoManager.getDeploymentAccess(hostname) ?? "",
}));
withTimestamps.sort((a, b) => b.accessedAt.localeCompare(a.accessedAt));
return withTimestamps.map((w) => w.hostname);
}
/**
* Migrate from legacy flat sessionToken storage to new format.
* Also sets the current deployment if none exists.
*/
public async migrateFromLegacyStorage(): Promise<string | undefined> {
const legacyUrl = this.mementoManager.getLegacyUrl();
if (!legacyUrl) {
return undefined;
}
const safeHostname = toSafeHost(legacyUrl);
const oldToken = await this.secrets.get(LEGACY_SESSION_TOKEN_KEY);
const existing = await this.getSessionAuth(safeHostname);
if (!existing) {
await this.setSessionAuth(safeHostname, {
url: legacyUrl,
token: oldToken ?? "",
});
}
// Also set as current deployment if none exists
const currentDeployment = await this.getCurrentDeployment();
if (!currentDeployment) {
await this.setCurrentDeployment({ url: legacyUrl, safeHostname });
}
await this.secrets.delete(LEGACY_SESSION_TOKEN_KEY);
await this.mementoManager.clearLegacyUrl();
return safeHostname;
}
public getOAuthClientRegistration(
safeHostname: string,
): Promise<OAuth2ClientRegistrationResponse | undefined> {
return this.getSecret<OAuth2ClientRegistrationResponse>(
OAUTH_CLIENT_PREFIX,
safeHostname,
);
}
public setOAuthClientRegistration(
safeHostname: string,
registration: OAuth2ClientRegistrationResponse,
): Promise<void> {
return this.setSecret(OAUTH_CLIENT_PREFIX, safeHostname, registration);
}
public clearOAuthClientRegistration(safeHostname: string): Promise<void> {
return this.clearSecret(OAUTH_CLIENT_PREFIX, safeHostname);
}
}