-
Notifications
You must be signed in to change notification settings - Fork 788
Expand file tree
/
Copy pathcredentials.ts
More file actions
679 lines (604 loc) · 25.9 KB
/
Copy pathcredentials.ts
File metadata and controls
679 lines (604 loc) · 25.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
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Octokit } from '@octokit/rest';
import { ApolloClient, InMemoryCache } from 'apollo-boost';
import { setContext } from 'apollo-link-context';
import { createHttpLink } from 'apollo-link-http';
import fetch from 'cross-fetch';
import * as vscode from 'vscode';
import { IAccount } from './interface';
import { LoggingApolloClient, LoggingOctokit, RateLogger } from './loggingOctokit';
import { convertRESTUserToAccount, getEnterpriseUri, hasEnterpriseUri, isEnterprise } from './utils';
import { AuthProvider } from '../common/authentication';
import { commands } from '../common/executeCommands';
import { Disposable } from '../common/lifecycle';
import Logger from '../common/logger';
import * as PersistentState from '../common/persistentState';
import { GITHUB_ENTERPRISE, URI } from '../common/settingKeys';
import { initBasedOnSettingChange } from '../common/settingsUtils';
import { ITelemetry } from '../common/telemetry';
import { agent } from '../env/node/net';
const TRY_AGAIN = vscode.l10n.t('Try again?');
const CANCEL = vscode.l10n.t('Cancel');
const SIGNIN_COMMAND = vscode.l10n.t('Sign In');
const IGNORE_COMMAND = vscode.l10n.t('Don\'t Show Again');
const PROMPT_FOR_SIGN_IN_SCOPE = vscode.l10n.t('prompt for sign in');
const PROMPT_FOR_SIGN_IN_STORAGE_KEY = 'login';
// If the scopes are changed, make sure to notify all interested parties to make sure this won't cause problems.
const SCOPES_OLDEST = ['read:user', 'user:email', 'repo'];
const SCOPES_OLD = ['read:user', 'user:email', 'repo', 'workflow'];
const SCOPES_WITH_ADDITIONAL = ['read:user', 'user:email', 'repo', 'workflow', 'project', 'read:org'];
const LAST_USED_SCOPES_GITHUB_KEY = 'githubPullRequest.lastUsedScopes';
const LAST_USED_SCOPES_ENTERPRISE_KEY = 'githubPullRequest.lastUsedScopesEnterprise';
type AuthenticationSessionGetter = (
authProviderId: string,
scopes: readonly string[],
options: vscode.AuthenticationGetSessionOptions,
) => Thenable<vscode.AuthenticationSession | undefined>;
interface ExistingSession {
session: vscode.AuthenticationSession;
scopes: string[];
}
export async function findExistingSession(
authProviderId: AuthProvider,
getSession: AuthenticationSessionGetter = (providerId, scopes, options) => vscode.authentication.getSession(providerId, scopes, options),
): Promise<ExistingSession | undefined> {
// Establish the preferred account with the normal scopes before looking for broader sessions.
// Otherwise, a single broader session from another account can override the workspace preference.
const scopePreferences = [
{ scopes: SCOPES_OLD, broaderScopes: [SCOPES_WITH_ADDITIONAL] },
{ scopes: SCOPES_OLDEST, broaderScopes: [SCOPES_WITH_ADDITIONAL, SCOPES_OLD] },
{ scopes: SCOPES_WITH_ADDITIONAL, broaderScopes: [] },
];
for (const preference of scopePreferences) {
const session = await getSession(authProviderId, preference.scopes, { silent: true });
if (!session) {
continue;
}
for (const broaderScopes of preference.broaderScopes) {
const broaderSession = await getSession(authProviderId, broaderScopes, { silent: true, account: session.account });
if (broaderSession) {
return { session: broaderSession, scopes: broaderScopes };
}
}
return { session, scopes: preference.scopes };
}
}
export interface GitHub {
octokit: LoggingOctokit;
graphql: LoggingApolloClient;
currentUser?: Promise<IAccount>;
isEmu?: Promise<boolean>;
}
interface AuthResult {
canceled: boolean;
}
export class CredentialStore extends Disposable {
private static readonly ID = 'Authentication';
private _githubAPI: GitHub | undefined;
private _sessionId: string | undefined;
private _githubEnterpriseAPI: GitHub | undefined;
private _enterpriseSessionId: string | undefined;
private _isInitialized: boolean = false;
private _onDidInitialize: vscode.EventEmitter<void> = new vscode.EventEmitter();
public readonly onDidInitialize: vscode.Event<void> = this._onDidInitialize.event;
private _scopes: string[] = SCOPES_OLD;
private _scopesEnterprise: string[] = SCOPES_OLD;
private _isSamling: boolean = false;
private _handlingAuthError: Map<AuthProvider, Promise<AuthResult>> = new Map();
private _lastAuthErrorHandledAt: Map<AuthProvider, number> = new Map();
// Cooldown long enough to absorb retries from in-flight requests that were
// issued with the now-invalid token, but short enough that a token that
// is invalidated again soon after re-auth will still trigger another prompt.
private static readonly AUTH_ERROR_COOLDOWN_MS = 60_000;
private _onDidChangeSessions: vscode.EventEmitter<vscode.AuthenticationSessionsChangeEvent> = new vscode.EventEmitter();
public readonly onDidChangeSessions = this._onDidChangeSessions.event;
private _onDidGetSession: vscode.EventEmitter<void> = new vscode.EventEmitter();
public readonly onDidGetSession = this._onDidGetSession.event;
private _onDidUpgradeSession: vscode.EventEmitter<void> = new vscode.EventEmitter();
public readonly onDidUpgradeSession = this._onDidUpgradeSession.event;
constructor(private readonly _telemetry: ITelemetry, private readonly context: vscode.ExtensionContext) {
super();
this.setScopesFromState();
this._register(vscode.authentication.onDidChangeSessions((e) => this.handlOnDidChangeSessions(e)));
}
private async handlOnDidChangeSessions(e: vscode.AuthenticationSessionsChangeEvent) {
const currentProvider = (e.provider.id === AuthProvider.github && this._githubAPI) ? AuthProvider.github : ((e.provider.id === AuthProvider.githubEnterprise && this._githubEnterpriseAPI) ? AuthProvider.githubEnterprise : undefined);
if ((this._githubAPI || this._githubEnterpriseAPI) && !currentProvider) {
return;
}
let sessionChanged = false;
if (currentProvider) {
const newSession = await this.getSession(currentProvider, { silent: true }, currentProvider === AuthProvider.github ? this._scopes : this._scopesEnterprise, false);
const currentSessionId = currentProvider === AuthProvider.github ? this._sessionId : this._enterpriseSessionId;
if (newSession.session?.id === currentSessionId) {
return;
}
sessionChanged = true;
if (currentProvider === AuthProvider.github) {
this._githubAPI = undefined;
this._sessionId = undefined;
} else {
this._githubEnterpriseAPI = undefined;
this._enterpriseSessionId = undefined;
}
}
const promises: Promise<any>[] = [];
if (!this.isAuthenticated(AuthProvider.github)) {
promises.push(this.initialize(AuthProvider.github));
}
if (!this.isAuthenticated(AuthProvider.githubEnterprise) && hasEnterpriseUri()) {
promises.push(this.initialize(AuthProvider.githubEnterprise));
}
await Promise.all(promises);
if (this.isAnyAuthenticated()) {
this._onDidGetSession.fire();
if (sessionChanged && !this._isSamling) {
this._onDidChangeSessions.fire(e);
}
} else if (!this._isSamling) {
this._onDidChangeSessions.fire(e);
}
}
private allScopesIncluded(actualScopes: string[], requiredScopes: string[]) {
return requiredScopes.every(scope => actualScopes.includes(scope));
}
private setScopesFromState() {
this._scopes = this.context.globalState.get(LAST_USED_SCOPES_GITHUB_KEY, SCOPES_OLD);
this._scopesEnterprise = this.context.globalState.get(LAST_USED_SCOPES_ENTERPRISE_KEY, SCOPES_OLD);
}
get scopes() {
return this._scopes;
}
private async saveScopesInState() {
await this.context.globalState.update(LAST_USED_SCOPES_GITHUB_KEY, this._scopes);
await this.context.globalState.update(LAST_USED_SCOPES_ENTERPRISE_KEY, this._scopesEnterprise);
}
private async tryInitializeFromEnvironmentToken(authProviderId: AuthProvider): Promise<AuthResult | undefined> {
if (isEnterprise(authProviderId)) {
return undefined;
}
const token = process.env.GITHUB_OAUTH_TOKEN;
if (!token) {
return undefined;
}
Logger.debug('Attempting authentication using GITHUB_OAUTH_TOKEN environment variable.', CredentialStore.ID);
try {
const github = await this.createHub(token, authProviderId);
this._githubAPI = github;
this._sessionId = 'environment-token';
if (!this._isInitialized) {
this._isInitialized = true;
this._onDidInitialize.fire();
}
Logger.appendLine('Successfully authenticated using GITHUB_OAUTH_TOKEN environment variable.', CredentialStore.ID);
return { canceled: false };
} catch (e) {
Logger.error(`Failed to authenticate using GITHUB_OAUTH_TOKEN: ${e.message}`, CredentialStore.ID);
return undefined;
}
}
private async initialize(authProviderId: AuthProvider, getAuthSessionOptions: vscode.AuthenticationGetSessionOptions = {}, scopes: string[] = (!isEnterprise(authProviderId) ? this._scopes : this._scopesEnterprise), requireScopes?: boolean): Promise<AuthResult> {
Logger.debug(`Initializing GitHub${getGitHubSuffix(authProviderId)} authentication provider.`, 'Authentication');
if (isEnterprise(authProviderId)) {
if (!hasEnterpriseUri()) {
Logger.debug(`GitHub Enterprise provider selected without URI.`, 'Authentication');
return { canceled: false };
}
}
const envResult = await this.tryInitializeFromEnvironmentToken(authProviderId);
if (envResult) {
return envResult;
}
if (getAuthSessionOptions.createIfNone === undefined && getAuthSessionOptions.forceNewSession === undefined) {
getAuthSessionOptions.createIfNone = false;
}
let session: vscode.AuthenticationSession | undefined = undefined;
let isNew: boolean = false;
let usedScopes: string[] | undefined = SCOPES_OLD;
const oldScopes = this._scopes;
const oldEnterpriseScopes = this._scopesEnterprise;
const authResult: AuthResult = { canceled: false };
try {
// Set scopes before getting the session to prevent new session events from using the old scopes.
if (!isEnterprise(authProviderId)) {
this._scopes = scopes;
} else {
this._scopesEnterprise = scopes;
}
const result = await this.getSession(authProviderId, getAuthSessionOptions, scopes, !!requireScopes);
usedScopes = result.scopes;
session = result.session;
isNew = result.isNew;
} catch (e) {
this._scopes = oldScopes;
this._scopesEnterprise = oldEnterpriseScopes;
const userCanceld = (e.message === 'User did not consent to login.');
if (userCanceld) {
authResult.canceled = true;
}
if (getAuthSessionOptions.forceNewSession && userCanceld) {
// There are cases where a forced login may not be 100% needed, so just continue as usual if
// the user didn't consent to the login prompt.
} else {
throw e;
}
}
if (session) {
if (!isEnterprise(authProviderId)) {
this._sessionId = session.id;
} else {
this._enterpriseSessionId = session.id;
}
let github: GitHub | undefined;
try {
github = await this.createHub(session.accessToken, authProviderId);
} catch (e) {
if ((e.message === 'Bad credentials') && !getAuthSessionOptions.forceNewSession) {
Logger.debug(`Creating hub failed ${e.message}`, CredentialStore.ID);
getAuthSessionOptions.forceNewSession = true;
getAuthSessionOptions.silent = false;
return this.initialize(authProviderId, getAuthSessionOptions, scopes, requireScopes);
} else {
// console.log because we need to see if we can learn more from the error object.
console.log(e);
Logger.error(`Creating hub failed ${e.message}`, CredentialStore.ID);
vscode.window.showErrorMessage(vscode.l10n.t('Unable to sign in with the provided credentials'));
}
}
if (!isEnterprise(authProviderId)) {
Logger.debug('Setting hub and scopes', CredentialStore.ID);
this._githubAPI = github;
this._scopes = usedScopes;
} else {
Logger.debug('Setting enterprise hub and scopes', CredentialStore.ID);
this._githubEnterpriseAPI = github;
this._scopesEnterprise = usedScopes;
}
await this.saveScopesInState();
if (!this._isInitialized || (isNew && !this._isSamling)) {
this._isInitialized = true;
this._onDidInitialize.fire();
}
if (isNew) {
/* __GDPR__
"auth.session" : {}
*/
this._telemetry.sendTelemetryEvent('auth.session');
}
return authResult;
} else {
Logger.debug(`No GitHub${getGitHubSuffix(authProviderId)} token found.`, CredentialStore.ID);
return authResult;
}
}
private async doCreate(options: vscode.AuthenticationGetSessionOptions, additionalScopes: boolean = false): Promise<AuthResult> {
let enterprise: AuthResult | undefined;
const initializeEnterprise = async () => {
enterprise = await this.initialize(AuthProvider.githubEnterprise, options, additionalScopes ? SCOPES_WITH_ADDITIONAL : undefined, additionalScopes);
};
if (hasEnterpriseUri()) {
await initializeEnterprise();
} else {
// Listen for changes to the enterprise URI and try again if it changes.
initBasedOnSettingChange(GITHUB_ENTERPRISE, URI, hasEnterpriseUri, initializeEnterprise, this.context.subscriptions);
}
const githubOptions = { ...options };
if (enterprise && !enterprise.canceled) {
githubOptions.silent = true;
}
const github = await this.initialize(AuthProvider.github, githubOptions, additionalScopes ? SCOPES_WITH_ADDITIONAL : undefined, additionalScopes);
return {
canceled: github.canceled || !!(enterprise && enterprise.canceled)
};
}
public async create(options: vscode.AuthenticationGetSessionOptions = {}, additionalScopes: boolean = false) {
return this.doCreate(options, additionalScopes);
}
public async recreate(reason?: string): Promise<AuthResult> {
return this.doCreate({ forceNewSession: reason ? { detail: reason } : true });
}
/**
* Handles authentication errors that surface from API calls (e.g. "Bad credentials"
* or 401 Unauthorized). Triggers a re-authentication prompt for the affected
* provider, deduplicating concurrent requests so we don't show multiple prompts
* when many in-flight calls fail at once.
*/
public async handleAuthError(authProviderId: AuthProvider): Promise<AuthResult> {
// Only prompt if we currently believe we are authenticated for this provider.
// Otherwise the regular sign-in flow will handle it.
if (!this.isAuthenticated(authProviderId)) {
return { canceled: true };
}
const inFlight = this._handlingAuthError.get(authProviderId);
if (inFlight) {
return inFlight;
}
// In-flight requests that were issued with the now-invalid token may continue
// to fail with auth errors for a short period after a successful re-auth.
// Suppress re-prompting for a cooldown window to avoid repeatedly nagging the
// user.
const lastHandled = this._lastAuthErrorHandledAt.get(authProviderId);
if (lastHandled !== undefined && (Date.now() - lastHandled) < CredentialStore.AUTH_ERROR_COOLDOWN_MS) {
return { canceled: true };
}
Logger.appendLine(`Detected invalid GitHub${getGitHubSuffix(authProviderId)} credentials; prompting for re-authentication.`, CredentialStore.ID);
/* __GDPR__
"auth.badCredentials" : {}
*/
this._telemetry.sendTelemetryEvent('auth.badCredentials');
const reason = vscode.l10n.t('Your GitHub{0} authentication session is no longer valid. Please sign in again.', getGitHubSuffix(authProviderId));
const promise = (async () => {
try {
// Force re-auth only for the affected provider, not both. Going through
// recreate()/doCreate() would prompt re-auth for both GitHub.com and
// GitHub Enterprise when both are configured.
return await this.initialize(authProviderId, { forceNewSession: { detail: reason } });
} finally {
this._handlingAuthError.delete(authProviderId);
this._lastAuthErrorHandledAt.set(authProviderId, Date.now());
}
})();
this._handlingAuthError.set(authProviderId, promise);
return promise;
}
public async reset() {
this._githubAPI = undefined;
this._githubEnterpriseAPI = undefined;
return this.create();
}
public isAnyAuthenticated() {
return this.isAuthenticated(AuthProvider.github) || this.isAuthenticated(AuthProvider.githubEnterprise);
}
public isAuthenticated(authProviderId: AuthProvider): boolean {
if (!isEnterprise(authProviderId)) {
return !!this._githubAPI;
}
return !!this._githubEnterpriseAPI;
}
public isAuthenticatedWithAdditionalScopes(authProviderId: AuthProvider): boolean {
if (!isEnterprise(authProviderId)) {
return !!this._githubAPI && this.allScopesIncluded(this._scopes, SCOPES_WITH_ADDITIONAL);
}
return !!this._githubEnterpriseAPI && this.allScopesIncluded(this._scopesEnterprise, SCOPES_WITH_ADDITIONAL);
}
public getHub(authProviderId: AuthProvider): GitHub | undefined {
if (!isEnterprise(authProviderId)) {
return this._githubAPI;
}
return this._githubEnterpriseAPI;
}
public areScopesOld(authProviderId: AuthProvider): boolean {
if (!isEnterprise(authProviderId)) {
return !this.allScopesIncluded(this._scopes, SCOPES_OLD);
}
return !this.allScopesIncluded(this._scopesEnterprise, SCOPES_OLD);
}
async tryPromptForCopilotAuth(): Promise<boolean> {
if (this.isAnyAuthenticated()) {
return true;
}
const chatSetupResult = await commands.executeCommand(commands.CHAT_SETUP_ACTION_ID, 'agent', { additionalScopes: this.scopes });
if (!chatSetupResult) {
return false;
}
const result = await this.create({ createIfNone: { detail: vscode.l10n.t('Sign in to start delegating tasks to the GitHub coding agent.') } });
/* __GDPR__
"remoteAgent.command.auth" : {
"succeeded" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this._telemetry.sendTelemetryEvent('remoteAgent.command.auth', {
succeeded: result.canceled ? 'false' : 'true'
});
if (result.canceled) {
return false;
}
return true;
}
public areScopesExtra(authProviderId: AuthProvider): boolean {
if (!isEnterprise(authProviderId)) {
return this.allScopesIncluded(this._scopes, SCOPES_WITH_ADDITIONAL);
}
return this.allScopesIncluded(this._scopesEnterprise, SCOPES_WITH_ADDITIONAL);
}
public async getHubEnsureAdditionalScopes(authProviderId: AuthProvider): Promise<GitHub | undefined> {
const hasScopesAlready = this.isAuthenticatedWithAdditionalScopes(authProviderId);
await this.initialize(authProviderId, { createIfNone: !hasScopesAlready }, SCOPES_WITH_ADDITIONAL, true);
if (!hasScopesAlready) {
this._onDidUpgradeSession.fire();
}
return this.getHub(authProviderId);
}
public async getHubOrLogin(authProviderId: AuthProvider): Promise<GitHub | undefined> {
if (!isEnterprise(authProviderId)) {
return this._githubAPI ?? (await this.login(authProviderId));
}
return this._githubEnterpriseAPI ?? (await this.login(authProviderId));
}
public async showSignInNotification(authProviderId: AuthProvider): Promise<GitHub | undefined> {
if (PersistentState.fetch(PROMPT_FOR_SIGN_IN_SCOPE, PROMPT_FOR_SIGN_IN_STORAGE_KEY) === false) {
return;
}
const result = await vscode.window.showInformationMessage(
vscode.l10n.t('In order to use the Pull Requests functionality, you must sign in to GitHub{0}', getGitHubSuffix(authProviderId)),
SIGNIN_COMMAND,
IGNORE_COMMAND,
);
if (result === SIGNIN_COMMAND) {
return await this.login(authProviderId);
} else {
// user cancelled sign in, remember that and don't ask again
PersistentState.store(PROMPT_FOR_SIGN_IN_SCOPE, PROMPT_FOR_SIGN_IN_STORAGE_KEY, false);
/* __GDPR__
"auth.cancel" : {}
*/
this._telemetry.sendTelemetryEvent('auth.cancel');
}
}
public async login(authProviderId: AuthProvider): Promise<GitHub | undefined> {
/* __GDPR__
"auth.start" : {}
*/
this._telemetry.sendTelemetryEvent('auth.start');
const errorPrefix = vscode.l10n.t('Error signing in to GitHub{0}', getGitHubSuffix(authProviderId));
let retry: boolean = true;
let octokit: GitHub | undefined = undefined;
const sessionOptions: vscode.AuthenticationGetSessionOptions = { createIfNone: true };
let isCanceled: boolean = false;
while (retry) {
try {
await this.initialize(authProviderId, sessionOptions);
} catch (e) {
Logger.error(`Login error: ${errorPrefix}: ${e}`, CredentialStore.ID);
if (e instanceof Error && e.stack) {
Logger.error(e.stack, CredentialStore.ID);
}
if (e.message === 'Cancelled') {
isCanceled = true;
}
}
octokit = this.getHub(authProviderId);
if (octokit || isCanceled) {
retry = false;
} else {
retry = (await vscode.window.showErrorMessage(errorPrefix, TRY_AGAIN, CANCEL)) === TRY_AGAIN;
if (retry) {
sessionOptions.forceNewSession = true;
sessionOptions.createIfNone = undefined;
}
}
}
if (octokit) {
/* __GDPR__
"auth.success" : {}
*/
this._telemetry.sendTelemetryEvent('auth.success');
} else {
/* __GDPR__
"auth.fail" : {}
*/
this._telemetry.sendTelemetryEvent('auth.fail');
}
return octokit;
}
public async showSamlMessageAndAuth(organizations: string[]): Promise<AuthResult> {
this._isSamling = true;
const result = await this.recreate(vscode.l10n.t('GitHub Pull Requests requires that you provide SAML access to your organization ({0}) when you sign in.', organizations.join(', ')));
this._isSamling = false;
return result;
}
public async isCurrentUser(authProviderId: AuthProvider, username: string): Promise<boolean> {
const api = authProviderId === AuthProvider.github ? this._githubAPI : this._githubEnterpriseAPI;
return (await api?.currentUser)?.login === username;
}
public async getIsEmu(authProviderId: AuthProvider): Promise<boolean> {
const github = this.getHub(authProviderId);
return !!(await github?.isEmu);
}
public getCurrentUser(authProviderId: AuthProvider): Promise<IAccount> {
const github = this.getHub(authProviderId);
const octokit = github?.octokit;
return (octokit && github?.currentUser)!;
}
private setCurrentUser(github: GitHub): void {
const getUser: ReturnType<typeof github.octokit.api.users.getAuthenticated> = new Promise((resolve, reject) => {
Logger.debug('Getting current user', CredentialStore.ID);
github.octokit.call(github.octokit.api.users.getAuthenticated, {}).then(result => {
Logger.debug(`Got current user ${result.data.login}`, CredentialStore.ID);
resolve(result);
}).catch(e => {
Logger.error(`Failed to get current user: ${e}, ${e.message}`, CredentialStore.ID);
reject(e);
});
});
github.currentUser = getUser.then(result => convertRESTUserToAccount(result.data));
github.isEmu = getUser.then(result => result.data.plan?.name === 'emu_user');
}
private async getSession(authProviderId: AuthProvider, getAuthSessionOptions: vscode.AuthenticationGetSessionOptions, scopes: string[], requireScopes: boolean): Promise<{ session: vscode.AuthenticationSession | undefined, isNew: boolean, scopes: string[] }> {
const existingSession = (getAuthSessionOptions.forceNewSession || requireScopes) ? undefined : await findExistingSession(authProviderId);
if (existingSession?.session) {
return { session: existingSession.session, isNew: false, scopes: existingSession.scopes };
}
const session = await vscode.authentication.getSession(authProviderId, requireScopes ? scopes : SCOPES_OLD, getAuthSessionOptions);
return { session, isNew: !!session, scopes: requireScopes ? scopes : SCOPES_OLD };
}
private async createHub(token: string, authProviderId: AuthProvider): Promise<GitHub> {
let baseUrl = 'https://api.github.com';
let enterpriseServerUri: vscode.Uri | undefined;
Logger.appendLine(`Creating hub for ${isEnterprise(authProviderId) ? 'enterprise' : '.com'}`, CredentialStore.ID);
if (isEnterprise(authProviderId)) {
enterpriseServerUri = getEnterpriseUri();
}
const isGhe = enterpriseServerUri?.authority.endsWith('ghe.com');
if (enterpriseServerUri) {
Logger.appendLine(`Enterprise server authority ${enterpriseServerUri.authority}`, CredentialStore.ID);
if (isGhe) {
baseUrl = `${enterpriseServerUri.scheme}://api.${enterpriseServerUri.authority}`;
} else {
baseUrl = `${enterpriseServerUri.scheme}://${enterpriseServerUri.authority}/api/v3`;
}
}
let fetchCore: ((url: string, options: { headers?: Record<string, string> }) => any) | undefined;
if (vscode.env.uiKind === vscode.UIKind.Web) {
fetchCore = (url: string, options: { headers?: Record<string, string> }) => {
if (options.headers !== undefined) {
const { 'user-agent': userAgent, ...headers } = options.headers;
if (userAgent) {
options.headers = headers;
}
}
return fetch(url, options);
};
}
const octokit = new Octokit({
request: { agent, fetch: fetchCore },
userAgent: 'GitHub VSCode Pull Requests',
// `shadow-cat-preview` is required for Draft PR API access -- https://developer.github.com/v3/previews/#draft-pull-requests
previews: ['shadow-cat-preview', 'merge-info-preview'],
auth: `${token || ''}`,
baseUrl: baseUrl,
});
let graphQLBaseUrl = baseUrl;
if (enterpriseServerUri && !isGhe) {
graphQLBaseUrl = `${enterpriseServerUri.scheme}://${enterpriseServerUri.authority}/api`;
}
const graphql = new ApolloClient({
link: link(graphQLBaseUrl, token || ''),
cache: new InMemoryCache(),
defaultOptions: {
query: {
fetchPolicy: 'no-cache',
},
},
});
const rateLogger = new RateLogger(this._telemetry, isEnterprise(authProviderId), (_e) => {
void this.handleAuthError(authProviderId);
});
const github: GitHub = {
octokit: new LoggingOctokit(octokit, rateLogger),
graphql: new LoggingApolloClient(graphql, rateLogger),
};
this.setCurrentUser(github);
return github;
}
}
const link = (url: string, token: string) =>
setContext((_, { headers }) => ({
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
Accept: 'application/vnd.github.merge-info-preview'
},
})).concat(
createHttpLink({
uri: `${url}/graphql`,
// https://github.com/apollographql/apollo-link/issues/513
fetch: fetch as (((input: URL | string, init?: RequestInit) => Promise<Response>) | undefined),
}),
);
function getGitHubSuffix(authProviderId: AuthProvider) {
return !isEnterprise(authProviderId) ? '' : ' Enterprise';
}