Path: blob/main/extensions/github-authentication/src/flows.ts
5222 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import * as path from 'path';6import { ProgressLocation, Uri, commands, env, l10n, window, workspace } from 'vscode';7import { Log } from './common/logger';8import { Config } from './config';9import { UriEventHandler } from './github';10import { fetching } from './node/fetch';11import { crypto } from './node/crypto';12import { LoopbackAuthServer } from './node/authServer';13import { promiseFromEvent } from './common/utils';14import { isHostedGitHubEnterprise } from './common/env';15import { NETWORK_ERROR, TIMED_OUT_ERROR, USER_CANCELLATION_ERROR } from './common/errors';1617interface IGitHubDeviceCodeResponse {18device_code: string;19user_code: string;20verification_uri: string;21interval: number;22}2324interface IFlowOptions {25// GitHub.com26readonly supportsGitHubDotCom: boolean;27// A GitHub Enterprise Server that is hosted by an organization28readonly supportsGitHubEnterpriseServer: boolean;29// A GitHub Enterprise Server that is hosted by GitHub for an organization30readonly supportsHostedGitHubEnterprise: boolean;3132// Runtimes - there are constraints on which runtimes support which flows33readonly supportsWebWorkerExtensionHost: boolean;34readonly supportsRemoteExtensionHost: boolean;3536// Clients - see `isSupportedClient` in `common/env.ts` for what constitutes a supported client37readonly supportsSupportedClients: boolean;38readonly supportsUnsupportedClients: boolean;3940// Configurations - some flows require a client secret41readonly supportsNoClientSecret: boolean;42}4344export const enum GitHubTarget {45DotCom,46Enterprise,47HostedEnterprise48}4950export const enum ExtensionHost {51WebWorker,52Remote,53Local54}5556export interface IFlowQuery {57target: GitHubTarget;58extensionHost: ExtensionHost;59isSupportedClient: boolean;60}6162interface IFlowTriggerOptions {63/**64* The scopes to request for the OAuth flow.65*/66scopes: string;67/**68* The base URI for the flow. This is used to determine which GitHub instance to authenticate against.69*/70baseUri: Uri;71/**72* The specific auth provider to use for the flow.73*/74signInProvider?: GitHubSocialSignInProvider;75/**76* Extra parameters to include in the OAuth flow.77*/78extraAuthorizeParameters?: Record<string, string>;79/**80* The Uri that the OAuth flow will redirect to. (i.e. vscode.dev/redirect)81*/82redirectUri: Uri;83/**84* The Uri to redirect to after redirecting to the redirect Uri. (i.e. vscode://....)85*/86callbackUri: Uri;87/**88* The enterprise URI for the flow, if applicable.89*/90enterpriseUri?: Uri;91/**92* The existing login which will be used to pre-fill the login prompt.93*/94existingLogin?: string;95/**96* The nonce for this particular flow. This is used to prevent replay attacks.97*/98nonce: string;99/**100* The instance of the Uri Handler for this extension101*/102uriHandler: UriEventHandler;103/**104* The logger to use for this flow.105*/106logger: Log;107}108109interface IFlow {110label: string;111options: IFlowOptions;112trigger(options: IFlowTriggerOptions): Promise<string>;113}114115/**116* Generates a cryptographically secure random string for PKCE code verifier.117* @param length The length of the string to generate118* @returns A random hex string119*/120function generateRandomString(length: number): string {121const array = new Uint8Array(length);122crypto.getRandomValues(array);123return Array.from(array)124.map(b => b.toString(16).padStart(2, '0'))125.join('')126.substring(0, length);127}128129/**130* Generates a PKCE code challenge from a code verifier using SHA-256.131* @param codeVerifier The code verifier string132* @returns A base64url-encoded SHA-256 hash of the code verifier133*/134async function generateCodeChallenge(codeVerifier: string): Promise<string> {135const encoder = new TextEncoder();136const data = encoder.encode(codeVerifier);137const digest = await crypto.subtle.digest('SHA-256', data);138139// Base64url encode the digest140const base64String = btoa(String.fromCharCode(...new Uint8Array(digest)));141return base64String142.replace(/\+/g, '-')143.replace(/\//g, '_')144.replace(/=+$/, '');145}146147async function exchangeCodeForToken(148logger: Log,149endpointUri: Uri,150redirectUri: Uri,151code: string,152codeVerifier: string,153enterpriseUri?: Uri154): Promise<string> {155logger.info('Exchanging code for token...');156157const clientSecret = Config.gitHubClientSecret;158if (!clientSecret) {159throw new Error('No client secret configured for GitHub authentication.');160}161162const body = new URLSearchParams([163['code', code],164['client_id', Config.gitHubClientId],165['redirect_uri', redirectUri.toString(true)],166['client_secret', clientSecret],167['code_verifier', codeVerifier]168]);169if (enterpriseUri) {170body.append('github_enterprise', enterpriseUri.toString(true));171}172const result = await fetching(endpointUri.toString(true), {173logger,174retryFallbacks: true,175expectJSON: true,176method: 'POST',177headers: {178Accept: 'application/json',179'Content-Type': 'application/x-www-form-urlencoded',180},181body: body.toString()182});183184if (result.ok) {185const json = await result.json();186logger.info('Token exchange success!');187return json.access_token;188} else {189const text = await result.text();190const error = new Error(text);191error.name = 'GitHubTokenExchangeError';192throw error;193}194}195196class UrlHandlerFlow implements IFlow {197label = l10n.t('url handler');198options: IFlowOptions = {199supportsGitHubDotCom: true,200// Supporting GHES would be challenging because different versions201// used a different client ID. We could try to detect the version202// and use the right one, but that's a lot of work when we have203// other flows that work well.204supportsGitHubEnterpriseServer: false,205supportsHostedGitHubEnterprise: true,206supportsRemoteExtensionHost: true,207supportsWebWorkerExtensionHost: true,208// exchanging a code for a token requires a client secret209supportsNoClientSecret: false,210supportsSupportedClients: true,211supportsUnsupportedClients: false212};213214async trigger({215scopes,216baseUri,217redirectUri,218callbackUri,219enterpriseUri,220nonce,221signInProvider,222extraAuthorizeParameters,223uriHandler,224existingLogin,225logger,226}: IFlowTriggerOptions): Promise<string> {227logger.info(`Trying without local server... (${scopes})`);228return await window.withProgress<string>({229location: ProgressLocation.Notification,230title: l10n.t({231message: 'Signing in to {0}...',232args: [baseUri.authority],233comment: ['The {0} will be a url, e.g. github.com']234}),235cancellable: true236}, async (_, token) => {237// Generate PKCE parameters238const codeVerifier = generateRandomString(64);239const codeChallenge = await generateCodeChallenge(codeVerifier);240241const promise = uriHandler.waitForCode(logger, scopes, nonce, token);242243const searchParams = new URLSearchParams([244['client_id', Config.gitHubClientId],245['redirect_uri', redirectUri.toString(true)],246['scope', scopes],247['state', encodeURIComponent(callbackUri.toString(true))],248['code_challenge', codeChallenge],249['code_challenge_method', 'S256']250]);251if (existingLogin) {252searchParams.append('login', existingLogin);253} else {254searchParams.append('prompt', 'select_account');255}256if (signInProvider) {257searchParams.append('provider', signInProvider);258}259if (extraAuthorizeParameters) {260for (const [key, value] of Object.entries(extraAuthorizeParameters)) {261searchParams.append(key, value);262}263}264265// The extra toString, parse is apparently needed for env.openExternal266// to open the correct URL.267const uri = Uri.parse(baseUri.with({268path: '/login/oauth/authorize',269query: searchParams.toString()270}).toString(true));271await env.openExternal(uri);272273const code = await promise;274275const proxyEndpoints: { [providerId: string]: string } | undefined = await commands.executeCommand('workbench.getCodeExchangeProxyEndpoints');276const endpointUrl = proxyEndpoints?.github277? Uri.parse(`${proxyEndpoints.github}login/oauth/access_token`)278: baseUri.with({ path: '/login/oauth/access_token' });279280const accessToken = await exchangeCodeForToken(logger, endpointUrl, redirectUri, code, codeVerifier, enterpriseUri);281return accessToken;282});283}284}285286class LocalServerFlow implements IFlow {287label = l10n.t('local server');288options: IFlowOptions = {289supportsGitHubDotCom: true,290// Supporting GHES would be challenging because different versions291// used a different client ID. We could try to detect the version292// and use the right one, but that's a lot of work when we have293// other flows that work well.294supportsGitHubEnterpriseServer: false,295supportsHostedGitHubEnterprise: true,296// Opening a port on the remote side can't be open in the browser on297// the client side so this flow won't work in remote extension hosts298supportsRemoteExtensionHost: false,299// Web worker can't open a port to listen for the redirect300supportsWebWorkerExtensionHost: false,301// exchanging a code for a token requires a client secret302supportsNoClientSecret: false,303supportsSupportedClients: true,304supportsUnsupportedClients: true305};306async trigger({307scopes,308baseUri,309redirectUri,310callbackUri,311enterpriseUri,312signInProvider,313extraAuthorizeParameters,314existingLogin,315logger316}: IFlowTriggerOptions): Promise<string> {317logger.info(`Trying with local server... (${scopes})`);318return await window.withProgress<string>({319location: ProgressLocation.Notification,320title: l10n.t({321message: 'Signing in to {0}...',322args: [baseUri.authority],323comment: ['The {0} will be a url, e.g. github.com']324}),325cancellable: true326}, async (_, token) => {327// Generate PKCE parameters328const codeVerifier = generateRandomString(64);329const codeChallenge = await generateCodeChallenge(codeVerifier);330331const searchParams = new URLSearchParams([332['client_id', Config.gitHubClientId],333['redirect_uri', redirectUri.toString(true)],334['scope', scopes],335['code_challenge', codeChallenge],336['code_challenge_method', 'S256']337]);338if (existingLogin) {339searchParams.append('login', existingLogin);340} else {341searchParams.append('prompt', 'select_account');342}343if (signInProvider) {344searchParams.append('provider', signInProvider);345}346if (extraAuthorizeParameters) {347for (const [key, value] of Object.entries(extraAuthorizeParameters)) {348searchParams.append(key, value);349}350}351352const loginUrl = baseUri.with({353path: '/login/oauth/authorize',354query: searchParams.toString()355});356const server = new LoopbackAuthServer(path.join(__dirname, '../media'), loginUrl.toString(true), callbackUri.toString(true), env.isAppPortable);357const port = await server.start();358359let codeToExchange;360try {361env.openExternal(Uri.parse(`http://127.0.0.1:${port}/signin?nonce=${encodeURIComponent(server.nonce)}`));362const { code } = await Promise.race([363server.waitForOAuthResponse(),364new Promise<any>((_, reject) => setTimeout(() => reject(TIMED_OUT_ERROR), 300_000)), // 5min timeout365promiseFromEvent<any, any>(token.onCancellationRequested, (_, __, reject) => { reject(USER_CANCELLATION_ERROR); }).promise366]);367codeToExchange = code;368} finally {369setTimeout(() => {370void server.stop();371}, 5000);372}373374const accessToken = await exchangeCodeForToken(375logger,376baseUri.with({ path: '/login/oauth/access_token' }),377redirectUri,378codeToExchange,379codeVerifier,380enterpriseUri);381return accessToken;382});383}384}385386class DeviceCodeFlow implements IFlow {387label = l10n.t('device code');388options: IFlowOptions = {389supportsGitHubDotCom: true,390supportsGitHubEnterpriseServer: true,391supportsHostedGitHubEnterprise: true,392supportsRemoteExtensionHost: true,393// CORS prevents this from working in web workers394supportsWebWorkerExtensionHost: false,395supportsNoClientSecret: true,396supportsSupportedClients: true,397supportsUnsupportedClients: true398};399async trigger({ scopes, baseUri, signInProvider, extraAuthorizeParameters, logger }: IFlowTriggerOptions) {400logger.info(`Trying device code flow... (${scopes})`);401402// Get initial device code403const uri = baseUri.with({404path: '/login/device/code',405query: `client_id=${Config.gitHubClientId}&scope=${scopes}`406});407const result = await fetching(uri.toString(true), {408logger,409retryFallbacks: true,410expectJSON: true,411method: 'POST',412headers: {413Accept: 'application/json'414}415});416if (!result.ok) {417throw new Error(`Failed to get one-time code: ${await result.text()}`);418}419420const json = await result.json() as IGitHubDeviceCodeResponse;421422const button = l10n.t('Copy & Continue to {0}', signInProvider ? GitHubSocialSignInProviderLabels[signInProvider] : l10n.t('GitHub'));423const modalResult = await window.showInformationMessage(424l10n.t({ message: 'Your Code: {0}', args: [json.user_code], comment: ['The {0} will be a code, e.g. 123-456'] }),425{426modal: true,427detail: l10n.t('To finish authenticating, navigate to GitHub and paste in the above one-time code.')428}, button);429430if (modalResult !== button) {431throw new Error(USER_CANCELLATION_ERROR);432}433434await env.clipboard.writeText(json.user_code);435436let open = Uri.parse(json.verification_uri);437const query = new URLSearchParams(open.query);438if (signInProvider) {439query.set('provider', signInProvider);440}441if (extraAuthorizeParameters) {442for (const [key, value] of Object.entries(extraAuthorizeParameters)) {443query.set(key, value);444}445}446if (signInProvider || extraAuthorizeParameters) {447open = open.with({ query: query.toString() });448}449const uriToOpen = await env.asExternalUri(open);450await env.openExternal(uriToOpen);451452return await this.waitForDeviceCodeAccessToken(logger, baseUri, json);453}454455private async waitForDeviceCodeAccessToken(456logger: Log,457baseUri: Uri,458json: IGitHubDeviceCodeResponse,459): Promise<string> {460return await window.withProgress<string>({461location: ProgressLocation.Notification,462cancellable: true,463title: l10n.t({464message: 'Open [{0}]({0}) in a new tab and paste your one-time code: {1}',465args: [json.verification_uri, json.user_code],466comment: [467'The [{0}]({0}) will be a url and the {1} will be a code, e.g. 123-456',468'{Locked="[{0}]({0})"}'469]470})471}, async (_, token) => {472const refreshTokenUri = baseUri.with({473path: '/login/oauth/access_token',474query: `client_id=${Config.gitHubClientId}&device_code=${json.device_code}&grant_type=urn:ietf:params:oauth:grant-type:device_code`475});476477// Try for 2 minutes478const attempts = 120 / json.interval;479for (let i = 0; i < attempts; i++) {480await new Promise(resolve => setTimeout(resolve, json.interval * 1000));481if (token.isCancellationRequested) {482throw new Error(USER_CANCELLATION_ERROR);483}484let accessTokenResult;485try {486accessTokenResult = await fetching(refreshTokenUri.toString(true), {487logger,488retryFallbacks: true,489expectJSON: true,490method: 'POST',491headers: {492Accept: 'application/json'493}494});495} catch {496continue;497}498499if (!accessTokenResult.ok) {500continue;501}502503const accessTokenJson = await accessTokenResult.json();504505if (accessTokenJson.error === 'authorization_pending') {506continue;507}508509if (accessTokenJson.error) {510throw new Error(accessTokenJson.error_description);511}512513return accessTokenJson.access_token;514}515516throw new Error(TIMED_OUT_ERROR);517});518}519}520521class PatFlow implements IFlow {522label = l10n.t('personal access token');523options: IFlowOptions = {524supportsGitHubDotCom: true,525supportsGitHubEnterpriseServer: true,526supportsHostedGitHubEnterprise: true,527supportsRemoteExtensionHost: true,528supportsWebWorkerExtensionHost: true,529supportsNoClientSecret: true,530// PATs can't be used with Settings Sync so we don't enable this flow531// for supported clients532supportsSupportedClients: false,533supportsUnsupportedClients: true534};535536async trigger({ scopes, baseUri, logger, enterpriseUri }: IFlowTriggerOptions) {537logger.info(`Trying to retrieve PAT... (${scopes})`);538539const button = l10n.t('Continue to GitHub');540const modalResult = await window.showInformationMessage(541l10n.t('Continue to GitHub to create a Personal Access Token (PAT)'),542{543modal: true,544detail: l10n.t('To finish authenticating, navigate to GitHub to create a PAT then paste the PAT into the input box.')545}, button);546547if (modalResult !== button) {548throw new Error(USER_CANCELLATION_ERROR);549}550551const description = `${env.appName} (${scopes})`;552const uriToOpen = await env.asExternalUri(baseUri.with({ path: '/settings/tokens/new', query: `description=${description}&scopes=${scopes.split(' ').join(',')}` }));553await env.openExternal(uriToOpen);554const token = await window.showInputBox({ placeHolder: `ghp_1a2b3c4...`, prompt: `GitHub Personal Access Token - ${scopes}`, ignoreFocusOut: true });555if (!token) { throw new Error(USER_CANCELLATION_ERROR); }556557const appUri = !enterpriseUri || isHostedGitHubEnterprise(enterpriseUri)558? Uri.parse(`${baseUri.scheme}://api.${baseUri.authority}`)559: Uri.parse(`${baseUri.scheme}://${baseUri.authority}/api/v3`);560561const tokenScopes = await this.getScopes(token, appUri, logger); // Example: ['repo', 'user']562const scopesList = scopes.split(' '); // Example: 'read:user repo user:email'563if (!scopesList.every(scope => {564const included = tokenScopes.includes(scope);565if (included || !scope.includes(':')) {566return included;567}568569return scope.split(':').some(splitScopes => {570return tokenScopes.includes(splitScopes);571});572})) {573throw new Error(`The provided token does not match the requested scopes: ${scopes}`);574}575576return token;577}578579private async getScopes(token: string, serverUri: Uri, logger: Log): Promise<string[]> {580try {581logger.info('Getting token scopes...');582const result = await fetching(serverUri.toString(), {583logger,584retryFallbacks: true,585expectJSON: false,586headers: {587Authorization: `token ${token}`,588'User-Agent': `${env.appName} (${env.appHost})`589}590});591592if (result.ok) {593const scopes = result.headers.get('X-OAuth-Scopes');594return scopes ? scopes.split(',').map(scope => scope.trim()) : [];595} else {596logger.error(`Getting scopes failed: ${result.statusText}`);597throw new Error(result.statusText);598}599} catch (ex) {600logger.error(ex.message);601throw new Error(NETWORK_ERROR);602}603}604}605606const allFlows: IFlow[] = [607new LocalServerFlow(),608new UrlHandlerFlow(),609new DeviceCodeFlow(),610new PatFlow()611];612613export function getFlows(query: IFlowQuery) {614const validFlows = allFlows.filter(flow => {615let useFlow: boolean = true;616switch (query.target) {617case GitHubTarget.DotCom:618useFlow &&= flow.options.supportsGitHubDotCom;619break;620case GitHubTarget.Enterprise:621useFlow &&= flow.options.supportsGitHubEnterpriseServer;622break;623case GitHubTarget.HostedEnterprise:624useFlow &&= flow.options.supportsHostedGitHubEnterprise;625break;626}627628switch (query.extensionHost) {629case ExtensionHost.Remote:630useFlow &&= flow.options.supportsRemoteExtensionHost;631break;632case ExtensionHost.WebWorker:633useFlow &&= flow.options.supportsWebWorkerExtensionHost;634break;635}636637if (!Config.gitHubClientSecret) {638useFlow &&= flow.options.supportsNoClientSecret;639}640641if (query.isSupportedClient) {642// TODO: revisit how we support PAT in GHES but not DotCom... but this works for now since643// there isn't another flow that has supportsSupportedClients = false644useFlow &&= (flow.options.supportsSupportedClients || query.target !== GitHubTarget.DotCom);645} else {646useFlow &&= flow.options.supportsUnsupportedClients;647}648return useFlow;649});650651const preferDeviceCodeFlow = workspace.getConfiguration('github-authentication').get<boolean>('preferDeviceCodeFlow', false);652if (preferDeviceCodeFlow) {653return [654...validFlows.filter(flow => flow instanceof DeviceCodeFlow),655...validFlows.filter(flow => !(flow instanceof DeviceCodeFlow))656];657}658659return validFlows;660}661662/**663* Social authentication providers for GitHub664*/665export const enum GitHubSocialSignInProvider {666Google = 'google',667Apple = 'apple',668}669670const GitHubSocialSignInProviderLabels = {671[GitHubSocialSignInProvider.Google]: l10n.t('Google'),672[GitHubSocialSignInProvider.Apple]: l10n.t('Apple'),673};674675export function isSocialSignInProvider(provider: unknown): provider is GitHubSocialSignInProvider {676return provider === GitHubSocialSignInProvider.Google || provider === GitHubSocialSignInProvider.Apple;677}678679680