/
authentication-service.ts
456 lines (389 loc) · 19.5 KB
/
authentication-service.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
// *****************************************************************************
// Copyright (C) 2020 Red Hat, Inc. and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// code copied and modified from https://github.com/microsoft/vscode/blob/1.47.3/src/vs/workbench/services/authentication/browser/authenticationService.ts
import { injectable, inject, postConstruct } from 'inversify';
import { Emitter, Event } from '../common/event';
import { StorageService } from '../browser/storage-service';
import { Disposable, DisposableCollection } from '../common/disposable';
import { ACCOUNTS_MENU, ACCOUNTS_SUBMENU, MenuModelRegistry } from '../common/menu';
import { Command, CommandRegistry } from '../common/command';
import { nls } from '../common/nls';
export interface AuthenticationSessionAccountInformation {
readonly id: string;
readonly label: string;
}
export interface AuthenticationSession {
id: string;
accessToken: string;
account: AuthenticationSessionAccountInformation;
scopes: ReadonlyArray<string>;
}
export interface AuthenticationProviderInformation {
id: string;
label: string;
}
/** Should match the definition from the theia/vscode types */
export interface AuthenticationProviderAuthenticationSessionsChangeEvent {
readonly added: readonly AuthenticationSession[] | undefined;
readonly removed: readonly AuthenticationSession[] | undefined;
readonly changed: readonly AuthenticationSession[] | undefined;
}
export interface SessionRequest {
disposables: Disposable[];
requestingExtensionIds: string[];
}
export interface SessionRequestInfo {
[scopes: string]: SessionRequest;
}
/**
* Our authentication provider should at least contain the following information:
* - The signature of authentication providers from vscode
* - Registration information about the provider (id, label)
* - Provider options (supportsMultipleAccounts)
*
* Additionally, we provide the possibility to sign out of a specific account name.
*/
export interface AuthenticationProvider {
id: string;
label: string;
supportsMultipleAccounts: boolean;
hasSessions(): boolean;
signOut(accountName: string): Promise<void>;
updateSessionItems(event: AuthenticationProviderAuthenticationSessionsChangeEvent): Promise<void>;
/**
* @deprecated use `createSession` instead.
*/
login(scopes: string[]): Promise<AuthenticationSession>;
/**
* @deprecated use `removeSession` instead.
*/
logout(sessionId: string): Promise<void>;
/**
* An [event](#Event) which fires when the array of sessions has changed, or data
* within a session has changed.
*/
readonly onDidChangeSessions: Event<AuthenticationProviderAuthenticationSessionsChangeEvent>;
/**
* Get a list of sessions.
* @param scopes An optional list of scopes. If provided, the sessions returned should match
* these permissions, otherwise all sessions should be returned.
* @returns A promise that resolves to an array of authentication sessions.
*/
getSessions(scopes?: string[]): Thenable<ReadonlyArray<AuthenticationSession>>;
/**
* Prompts a user to login.
* @param scopes A list of scopes, permissions, that the new session should be created with.
* @returns A promise that resolves to an authentication session.
*/
createSession(scopes: string[]): Thenable<AuthenticationSession>;
/**
* Removes the session corresponding to session id.
* @param sessionId The id of the session to remove.
*/
removeSession(sessionId: string): Thenable<void>;
}
export const AuthenticationService = Symbol('AuthenticationService');
export interface AuthenticationService {
isAuthenticationProviderRegistered(id: string): boolean;
getProviderIds(): string[];
registerAuthenticationProvider(id: string, provider: AuthenticationProvider): void;
unregisterAuthenticationProvider(id: string): void;
requestNewSession(id: string, scopes: string[], extensionId: string, extensionName: string): void;
updateSessions(providerId: string, event: AuthenticationProviderAuthenticationSessionsChangeEvent): void;
readonly onDidRegisterAuthenticationProvider: Event<AuthenticationProviderInformation>;
readonly onDidUnregisterAuthenticationProvider: Event<AuthenticationProviderInformation>;
readonly onDidChangeSessions: Event<{ providerId: string, label: string, event: AuthenticationProviderAuthenticationSessionsChangeEvent }>;
getSessions(providerId: string, scopes?: string[]): Promise<ReadonlyArray<AuthenticationSession>>;
getLabel(providerId: string): string;
supportsMultipleAccounts(providerId: string): boolean;
login(providerId: string, scopes: string[]): Promise<AuthenticationSession>;
logout(providerId: string, sessionId: string): Promise<void>;
signOutOfAccount(providerId: string, accountName: string): Promise<void>;
}
export interface SessionChangeEvent {
providerId: string,
label: string,
event: AuthenticationProviderAuthenticationSessionsChangeEvent
}
@injectable()
export class AuthenticationServiceImpl implements AuthenticationService {
private noAccountsMenuItem: Disposable | undefined;
private noAccountsCommand: Command = { id: 'noAccounts' };
private signInRequestItems = new Map<string, SessionRequestInfo>();
private sessionMap = new Map<string, DisposableCollection>();
protected authenticationProviders: Map<string, AuthenticationProvider> = new Map<string, AuthenticationProvider>();
private onDidRegisterAuthenticationProviderEmitter: Emitter<AuthenticationProviderInformation> = new Emitter<AuthenticationProviderInformation>();
readonly onDidRegisterAuthenticationProvider: Event<AuthenticationProviderInformation> = this.onDidRegisterAuthenticationProviderEmitter.event;
private onDidUnregisterAuthenticationProviderEmitter: Emitter<AuthenticationProviderInformation> = new Emitter<AuthenticationProviderInformation>();
readonly onDidUnregisterAuthenticationProvider: Event<AuthenticationProviderInformation> = this.onDidUnregisterAuthenticationProviderEmitter.event;
private onDidChangeSessionsEmitter: Emitter<SessionChangeEvent> = new Emitter<SessionChangeEvent>();
readonly onDidChangeSessions: Event<SessionChangeEvent> = this.onDidChangeSessionsEmitter.event;
@inject(MenuModelRegistry) protected readonly menus: MenuModelRegistry;
@inject(CommandRegistry) protected readonly commands: CommandRegistry;
@inject(StorageService) protected readonly storageService: StorageService;
@postConstruct()
init(): void {
this.onDidChangeSessions(event => this.handleSessionChange(event));
this.commands.registerCommand(this.noAccountsCommand, {
execute: () => { },
isEnabled: () => false
});
}
protected async handleSessionChange(changeEvent: SessionChangeEvent): Promise<void> {
if (changeEvent.event.added && changeEvent.event.added.length > 0) {
const sessions = await this.getSessions(changeEvent.providerId);
sessions.forEach(session => {
if (!this.sessionMap.get(session.id)) {
this.sessionMap.set(session.id, this.createAccountUi(changeEvent.providerId, changeEvent.label, session));
}
});
}
for (const removed of changeEvent.event.removed || []) {
const sessionId = typeof removed === 'string' ? removed : removed?.id;
if (sessionId) {
this.sessionMap.get(sessionId)?.dispose();
this.sessionMap.delete(sessionId);
}
}
}
protected createAccountUi(providerId: string, providerLabel: string, session: AuthenticationSession): DisposableCollection {
// unregister old commands and menus if present (there is only one per account but there may be several sessions per account)
const providerAccountId = `account-sign-out-${providerId}-${session.account.id}`;
this.commands.unregisterCommand(providerAccountId);
const providerAccountSubmenu = [...ACCOUNTS_SUBMENU, providerAccountId];
this.menus.unregisterMenuAction({ commandId: providerAccountId }, providerAccountSubmenu);
// register new command and menu entry for the sessions account
const disposables = new DisposableCollection();
disposables.push(this.commands.registerCommand({ id: providerAccountId }, {
execute: async () => {
this.signOutOfAccount(providerId, session.account.label);
}
}));
this.menus.registerSubmenu(providerAccountSubmenu, `${session.account.label} (${providerLabel})`);
disposables.push(this.menus.registerMenuAction(providerAccountSubmenu, {
label: nls.localizeByDefault('Sign Out'),
commandId: providerAccountId
}));
return disposables;
}
getProviderIds(): string[] {
const providerIds: string[] = [];
this.authenticationProviders.forEach(provider => {
providerIds.push(provider.id);
});
return providerIds;
}
isAuthenticationProviderRegistered(id: string): boolean {
return this.authenticationProviders.has(id);
}
private updateAccountsMenuItem(): void {
let hasSession = false;
this.authenticationProviders.forEach(async provider => {
hasSession = hasSession || provider.hasSessions();
});
if (hasSession && this.noAccountsMenuItem) {
this.noAccountsMenuItem.dispose();
this.noAccountsMenuItem = undefined;
}
if (!hasSession && !this.noAccountsMenuItem) {
this.noAccountsMenuItem = this.menus.registerMenuAction(ACCOUNTS_MENU, {
label: 'You are not signed in to any accounts',
order: '0',
commandId: this.noAccountsCommand.id
});
}
}
registerAuthenticationProvider(id: string, authenticationProvider: AuthenticationProvider): void {
if (this.authenticationProviders.get(id)) {
throw new Error(`An authentication provider with id '${id}' is already registered.`);
}
this.authenticationProviders.set(id, authenticationProvider);
this.onDidRegisterAuthenticationProviderEmitter.fire({ id, label: authenticationProvider.label });
this.updateAccountsMenuItem();
console.log(`An authentication provider with id '${id}' was registered.`);
}
unregisterAuthenticationProvider(id: string): void {
const provider = this.authenticationProviders.get(id);
if (provider) {
this.authenticationProviders.delete(id);
this.onDidUnregisterAuthenticationProviderEmitter.fire({ id, label: provider.label });
this.updateAccountsMenuItem();
} else {
console.error(`Failed to unregister an authentication provider. A provider with id '${id}' was not found.`);
}
}
async updateSessions(id: string, event: AuthenticationProviderAuthenticationSessionsChangeEvent): Promise<void> {
const provider = this.authenticationProviders.get(id);
if (provider) {
await provider.updateSessionItems(event);
this.onDidChangeSessionsEmitter.fire({ providerId: id, label: provider.label, event: event });
this.updateAccountsMenuItem();
if (event.added) {
await this.updateNewSessionRequests(provider);
}
} else {
console.error(`Failed to update an authentication session. An authentication provider with id '${id}' was not found.`);
}
}
private async updateNewSessionRequests(provider: AuthenticationProvider): Promise<void> {
const existingRequestsForProvider = this.signInRequestItems.get(provider.id);
if (!existingRequestsForProvider) {
return;
}
const sessions = await provider.getSessions();
Object.keys(existingRequestsForProvider).forEach(requestedScopes => {
if (sessions.some(session => session.scopes.slice().sort().join('') === requestedScopes)) {
const sessionRequest = existingRequestsForProvider[requestedScopes];
if (sessionRequest) {
sessionRequest.disposables.forEach(item => item.dispose());
}
delete existingRequestsForProvider[requestedScopes];
if (Object.keys(existingRequestsForProvider).length === 0) {
this.signInRequestItems.delete(provider.id);
} else {
this.signInRequestItems.set(provider.id, existingRequestsForProvider);
}
}
});
}
async requestNewSession(providerId: string, scopes: string[], extensionId: string, extensionName: string): Promise<void> {
let provider = this.authenticationProviders.get(providerId);
if (!provider) {
// Activate has already been called for the authentication provider, but it cannot block on registering itself
// since this is sync and returns a disposable. So, wait for registration event to fire that indicates the
// provider is now in the map.
await new Promise<void>((resolve, _) => {
this.onDidRegisterAuthenticationProvider(e => {
if (e.id === providerId) {
provider = this.authenticationProviders.get(providerId);
resolve(undefined);
}
});
});
}
if (provider) {
const providerRequests = this.signInRequestItems.get(providerId);
const scopesList = scopes.sort().join('');
const extensionHasExistingRequest = providerRequests
&& providerRequests[scopesList]
&& providerRequests[scopesList].requestingExtensionIds.indexOf(extensionId) > -1;
if (extensionHasExistingRequest) {
return;
}
const menuItem = this.menus.registerMenuAction(ACCOUNTS_SUBMENU, {
label: `Sign in to use ${extensionName} (1)`,
order: '1',
commandId: `${extensionId}signIn`,
});
const signInCommand = this.commands.registerCommand({ id: `${extensionId}signIn` }, {
execute: async () => {
const session = await this.login(providerId, scopes);
// Add extension to allow list since user explicitly signed in on behalf of it
const allowList = await readAllowedExtensions(this.storageService, providerId, session.account.label);
if (!allowList.find(allowed => allowed.id === extensionId)) {
allowList.push({ id: extensionId, name: extensionName });
this.storageService.setData(`authentication-trusted-extensions-${providerId}-${session.account.label}`, JSON.stringify(allowList));
}
// And also set it as the preferred account for the extension
this.storageService.setData(`authentication-session-${extensionName}-${providerId}`, session.id);
}
});
if (providerRequests) {
const existingRequest = providerRequests[scopesList] || { disposables: [], requestingExtensionIds: [] };
providerRequests[scopesList] = {
disposables: [...existingRequest.disposables, menuItem, signInCommand],
requestingExtensionIds: [...existingRequest.requestingExtensionIds, extensionId]
};
this.signInRequestItems.set(providerId, providerRequests);
} else {
this.signInRequestItems.set(providerId, {
[scopesList]: {
disposables: [menuItem, signInCommand],
requestingExtensionIds: [extensionId]
}
});
}
}
}
getLabel(id: string): string {
const authProvider = this.authenticationProviders.get(id);
if (authProvider) {
return authProvider.label;
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
supportsMultipleAccounts(id: string): boolean {
const authProvider = this.authenticationProviders.get(id);
if (authProvider) {
return authProvider.supportsMultipleAccounts;
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
async getSessions(id: string, scopes?: string[]): Promise<ReadonlyArray<AuthenticationSession>> {
const authProvider = this.authenticationProviders.get(id);
if (authProvider) {
return authProvider.getSessions(scopes);
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
async login(id: string, scopes: string[]): Promise<AuthenticationSession> {
const authProvider = this.authenticationProviders.get(id);
if (authProvider) {
return authProvider.createSession(scopes);
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
async logout(id: string, sessionId: string): Promise<void> {
const authProvider = this.authenticationProviders.get(id);
if (authProvider) {
return authProvider.removeSession(sessionId);
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
async signOutOfAccount(id: string, accountName: string): Promise<void> {
const authProvider = this.authenticationProviders.get(id);
if (authProvider) {
return authProvider.signOut(accountName);
} else {
throw new Error(`No authentication provider '${id}' is currently registered.`);
}
}
}
export interface AllowedExtension {
id: string;
name: string;
}
export async function readAllowedExtensions(storageService: StorageService, providerId: string, accountName: string): Promise<AllowedExtension[]> {
let trustedExtensions: AllowedExtension[] = [];
try {
const trustedExtensionSrc: string | undefined = await storageService.getData(`authentication-trusted-extensions-${providerId}-${accountName}`);
if (trustedExtensionSrc) {
trustedExtensions = JSON.parse(trustedExtensionSrc);
}
} catch (err) {
console.error(err);
}
return trustedExtensions;
}