Path: blob/main/extensions/github-authentication/src/flows.ts
3314 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 } 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,174expectJSON: true,175method: 'POST',176headers: {177Accept: 'application/json',178'Content-Type': 'application/x-www-form-urlencoded',179},180body: body.toString()181});182183if (result.ok) {184const json = await result.json();185logger.info('Token exchange success!');186return json.access_token;187} else {188const text = await result.text();189const error = new Error(text);190error.name = 'GitHubTokenExchangeError';191throw error;192}193}194195class UrlHandlerFlow implements IFlow {196label = l10n.t('url handler');197options: IFlowOptions = {198supportsGitHubDotCom: true,199// Supporting GHES would be challenging because different versions200// used a different client ID. We could try to detect the version201// and use the right one, but that's a lot of work when we have202// other flows that work well.203supportsGitHubEnterpriseServer: false,204supportsHostedGitHubEnterprise: true,205supportsRemoteExtensionHost: true,206supportsWebWorkerExtensionHost: true,207// exchanging a code for a token requires a client secret208supportsNoClientSecret: false,209supportsSupportedClients: true,210supportsUnsupportedClients: false211};212213async trigger({214scopes,215baseUri,216redirectUri,217callbackUri,218enterpriseUri,219nonce,220signInProvider,221extraAuthorizeParameters,222uriHandler,223existingLogin,224logger,225}: IFlowTriggerOptions): Promise<string> {226logger.info(`Trying without local server... (${scopes})`);227return await window.withProgress<string>({228location: ProgressLocation.Notification,229title: l10n.t({230message: 'Signing in to {0}...',231args: [baseUri.authority],232comment: ['The {0} will be a url, e.g. github.com']233}),234cancellable: true235}, async (_, token) => {236// Generate PKCE parameters237const codeVerifier = generateRandomString(64);238const codeChallenge = await generateCodeChallenge(codeVerifier);239240const promise = uriHandler.waitForCode(logger, scopes, nonce, token);241242const searchParams = new URLSearchParams([243['client_id', Config.gitHubClientId],244['redirect_uri', redirectUri.toString(true)],245['scope', scopes],246['state', encodeURIComponent(callbackUri.toString(true))],247['code_challenge', codeChallenge],248['code_challenge_method', 'S256']249]);250if (existingLogin) {251searchParams.append('login', existingLogin);252} else {253searchParams.append('prompt', 'select_account');254}255if (signInProvider) {256searchParams.append('provider', signInProvider);257}258if (extraAuthorizeParameters) {259for (const [key, value] of Object.entries(extraAuthorizeParameters)) {260searchParams.append(key, value);261}262}263264// The extra toString, parse is apparently needed for env.openExternal265// to open the correct URL.266const uri = Uri.parse(baseUri.with({267path: '/login/oauth/authorize',268query: searchParams.toString()269}).toString(true));270await env.openExternal(uri);271272const code = await promise;273274const proxyEndpoints: { [providerId: string]: string } | undefined = await commands.executeCommand('workbench.getCodeExchangeProxyEndpoints');275const endpointUrl = proxyEndpoints?.github276? Uri.parse(`${proxyEndpoints.github}login/oauth/access_token`)277: baseUri.with({ path: '/login/oauth/access_token' });278279const accessToken = await exchangeCodeForToken(logger, endpointUrl, redirectUri, code, codeVerifier, enterpriseUri);280return accessToken;281});282}283}284285class LocalServerFlow implements IFlow {286label = l10n.t('local server');287options: IFlowOptions = {288supportsGitHubDotCom: true,289// Supporting GHES would be challenging because different versions290// used a different client ID. We could try to detect the version291// and use the right one, but that's a lot of work when we have292// other flows that work well.293supportsGitHubEnterpriseServer: false,294supportsHostedGitHubEnterprise: true,295// Opening a port on the remote side can't be open in the browser on296// the client side so this flow won't work in remote extension hosts297supportsRemoteExtensionHost: false,298// Web worker can't open a port to listen for the redirect299supportsWebWorkerExtensionHost: false,300// exchanging a code for a token requires a client secret301supportsNoClientSecret: false,302supportsSupportedClients: true,303supportsUnsupportedClients: true304};305async trigger({306scopes,307baseUri,308redirectUri,309callbackUri,310enterpriseUri,311signInProvider,312extraAuthorizeParameters,313existingLogin,314logger315}: IFlowTriggerOptions): Promise<string> {316logger.info(`Trying with local server... (${scopes})`);317return await window.withProgress<string>({318location: ProgressLocation.Notification,319title: l10n.t({320message: 'Signing in to {0}...',321args: [baseUri.authority],322comment: ['The {0} will be a url, e.g. github.com']323}),324cancellable: true325}, async (_, token) => {326// Generate PKCE parameters327const codeVerifier = generateRandomString(64);328const codeChallenge = await generateCodeChallenge(codeVerifier);329330const searchParams = new URLSearchParams([331['client_id', Config.gitHubClientId],332['redirect_uri', redirectUri.toString(true)],333['scope', scopes],334['code_challenge', codeChallenge],335['code_challenge_method', 'S256']336]);337if (existingLogin) {338searchParams.append('login', existingLogin);339} else {340searchParams.append('prompt', 'select_account');341}342if (signInProvider) {343searchParams.append('provider', signInProvider);344}345if (extraAuthorizeParameters) {346for (const [key, value] of Object.entries(extraAuthorizeParameters)) {347searchParams.append(key, value);348}349}350351const loginUrl = baseUri.with({352path: '/login/oauth/authorize',353query: searchParams.toString()354});355const server = new LoopbackAuthServer(path.join(__dirname, '../media'), loginUrl.toString(true), callbackUri.toString(true));356const port = await server.start();357358let codeToExchange;359try {360env.openExternal(Uri.parse(`http://127.0.0.1:${port}/signin?nonce=${encodeURIComponent(server.nonce)}`));361const { code } = await Promise.race([362server.waitForOAuthResponse(),363new Promise<any>((_, reject) => setTimeout(() => reject(TIMED_OUT_ERROR), 300_000)), // 5min timeout364promiseFromEvent<any, any>(token.onCancellationRequested, (_, __, reject) => { reject(USER_CANCELLATION_ERROR); }).promise365]);366codeToExchange = code;367} finally {368setTimeout(() => {369void server.stop();370}, 5000);371}372373const accessToken = await exchangeCodeForToken(374logger,375baseUri.with({ path: '/login/oauth/access_token' }),376redirectUri,377codeToExchange,378codeVerifier,379enterpriseUri);380return accessToken;381});382}383}384385class DeviceCodeFlow implements IFlow {386label = l10n.t('device code');387options: IFlowOptions = {388supportsGitHubDotCom: true,389supportsGitHubEnterpriseServer: true,390supportsHostedGitHubEnterprise: true,391supportsRemoteExtensionHost: true,392// CORS prevents this from working in web workers393supportsWebWorkerExtensionHost: false,394supportsNoClientSecret: true,395supportsSupportedClients: true,396supportsUnsupportedClients: true397};398async trigger({ scopes, baseUri, signInProvider, extraAuthorizeParameters, logger }: IFlowTriggerOptions) {399logger.info(`Trying device code flow... (${scopes})`);400401// Get initial device code402const uri = baseUri.with({403path: '/login/device/code',404query: `client_id=${Config.gitHubClientId}&scope=${scopes}`405});406const result = await fetching(uri.toString(true), {407logger,408expectJSON: true,409method: 'POST',410headers: {411Accept: 'application/json'412}413});414if (!result.ok) {415throw new Error(`Failed to get one-time code: ${await result.text()}`);416}417418const json = await result.json() as IGitHubDeviceCodeResponse;419420const button = l10n.t('Copy & Continue to {0}', signInProvider ? GitHubSocialSignInProviderLabels[signInProvider] : l10n.t('GitHub'));421const modalResult = await window.showInformationMessage(422l10n.t({ message: 'Your Code: {0}', args: [json.user_code], comment: ['The {0} will be a code, e.g. 123-456'] }),423{424modal: true,425detail: l10n.t('To finish authenticating, navigate to GitHub and paste in the above one-time code.')426}, button);427428if (modalResult !== button) {429throw new Error(USER_CANCELLATION_ERROR);430}431432await env.clipboard.writeText(json.user_code);433434let open = Uri.parse(json.verification_uri);435const query = new URLSearchParams(open.query);436if (signInProvider) {437query.set('provider', signInProvider);438}439if (extraAuthorizeParameters) {440for (const [key, value] of Object.entries(extraAuthorizeParameters)) {441query.set(key, value);442}443}444if (signInProvider || extraAuthorizeParameters) {445open = open.with({ query: query.toString() });446}447const uriToOpen = await env.asExternalUri(open);448await env.openExternal(uriToOpen);449450return await this.waitForDeviceCodeAccessToken(logger, baseUri, json);451}452453private async waitForDeviceCodeAccessToken(454logger: Log,455baseUri: Uri,456json: IGitHubDeviceCodeResponse,457): Promise<string> {458return await window.withProgress<string>({459location: ProgressLocation.Notification,460cancellable: true,461title: l10n.t({462message: 'Open [{0}]({0}) in a new tab and paste your one-time code: {1}',463args: [json.verification_uri, json.user_code],464comment: [465'The [{0}]({0}) will be a url and the {1} will be a code, e.g. 123-456',466'{Locked="[{0}]({0})"}'467]468})469}, async (_, token) => {470const refreshTokenUri = baseUri.with({471path: '/login/oauth/access_token',472query: `client_id=${Config.gitHubClientId}&device_code=${json.device_code}&grant_type=urn:ietf:params:oauth:grant-type:device_code`473});474475// Try for 2 minutes476const attempts = 120 / json.interval;477for (let i = 0; i < attempts; i++) {478await new Promise(resolve => setTimeout(resolve, json.interval * 1000));479if (token.isCancellationRequested) {480throw new Error(USER_CANCELLATION_ERROR);481}482let accessTokenResult;483try {484accessTokenResult = await fetching(refreshTokenUri.toString(true), {485logger,486expectJSON: true,487method: 'POST',488headers: {489Accept: 'application/json'490}491});492} catch {493continue;494}495496if (!accessTokenResult.ok) {497continue;498}499500const accessTokenJson = await accessTokenResult.json();501502if (accessTokenJson.error === 'authorization_pending') {503continue;504}505506if (accessTokenJson.error) {507throw new Error(accessTokenJson.error_description);508}509510return accessTokenJson.access_token;511}512513throw new Error(TIMED_OUT_ERROR);514});515}516}517518class PatFlow implements IFlow {519label = l10n.t('personal access token');520options: IFlowOptions = {521supportsGitHubDotCom: true,522supportsGitHubEnterpriseServer: true,523supportsHostedGitHubEnterprise: true,524supportsRemoteExtensionHost: true,525supportsWebWorkerExtensionHost: true,526supportsNoClientSecret: true,527// PATs can't be used with Settings Sync so we don't enable this flow528// for supported clients529supportsSupportedClients: false,530supportsUnsupportedClients: true531};532533async trigger({ scopes, baseUri, logger, enterpriseUri }: IFlowTriggerOptions) {534logger.info(`Trying to retrieve PAT... (${scopes})`);535536const button = l10n.t('Continue to GitHub');537const modalResult = await window.showInformationMessage(538l10n.t('Continue to GitHub to create a Personal Access Token (PAT)'),539{540modal: true,541detail: l10n.t('To finish authenticating, navigate to GitHub to create a PAT then paste the PAT into the input box.')542}, button);543544if (modalResult !== button) {545throw new Error(USER_CANCELLATION_ERROR);546}547548const description = `${env.appName} (${scopes})`;549const uriToOpen = await env.asExternalUri(baseUri.with({ path: '/settings/tokens/new', query: `description=${description}&scopes=${scopes.split(' ').join(',')}` }));550await env.openExternal(uriToOpen);551const token = await window.showInputBox({ placeHolder: `ghp_1a2b3c4...`, prompt: `GitHub Personal Access Token - ${scopes}`, ignoreFocusOut: true });552if (!token) { throw new Error(USER_CANCELLATION_ERROR); }553554const appUri = !enterpriseUri || isHostedGitHubEnterprise(enterpriseUri)555? Uri.parse(`${baseUri.scheme}://api.${baseUri.authority}`)556: Uri.parse(`${baseUri.scheme}://${baseUri.authority}/api/v3`);557558const tokenScopes = await this.getScopes(token, appUri, logger); // Example: ['repo', 'user']559const scopesList = scopes.split(' '); // Example: 'read:user repo user:email'560if (!scopesList.every(scope => {561const included = tokenScopes.includes(scope);562if (included || !scope.includes(':')) {563return included;564}565566return scope.split(':').some(splitScopes => {567return tokenScopes.includes(splitScopes);568});569})) {570throw new Error(`The provided token does not match the requested scopes: ${scopes}`);571}572573return token;574}575576private async getScopes(token: string, serverUri: Uri, logger: Log): Promise<string[]> {577try {578logger.info('Getting token scopes...');579const result = await fetching(serverUri.toString(), {580logger,581expectJSON: false,582headers: {583Authorization: `token ${token}`,584'User-Agent': `${env.appName} (${env.appHost})`585}586});587588if (result.ok) {589const scopes = result.headers.get('X-OAuth-Scopes');590return scopes ? scopes.split(',').map(scope => scope.trim()) : [];591} else {592logger.error(`Getting scopes failed: ${result.statusText}`);593throw new Error(result.statusText);594}595} catch (ex) {596logger.error(ex.message);597throw new Error(NETWORK_ERROR);598}599}600}601602const allFlows: IFlow[] = [603new LocalServerFlow(),604new UrlHandlerFlow(),605new DeviceCodeFlow(),606new PatFlow()607];608609export function getFlows(query: IFlowQuery) {610return allFlows.filter(flow => {611let useFlow: boolean = true;612switch (query.target) {613case GitHubTarget.DotCom:614useFlow &&= flow.options.supportsGitHubDotCom;615break;616case GitHubTarget.Enterprise:617useFlow &&= flow.options.supportsGitHubEnterpriseServer;618break;619case GitHubTarget.HostedEnterprise:620useFlow &&= flow.options.supportsHostedGitHubEnterprise;621break;622}623624switch (query.extensionHost) {625case ExtensionHost.Remote:626useFlow &&= flow.options.supportsRemoteExtensionHost;627break;628case ExtensionHost.WebWorker:629useFlow &&= flow.options.supportsWebWorkerExtensionHost;630break;631}632633if (!Config.gitHubClientSecret) {634useFlow &&= flow.options.supportsNoClientSecret;635}636637if (query.isSupportedClient) {638// TODO: revisit how we support PAT in GHES but not DotCom... but this works for now since639// there isn't another flow that has supportsSupportedClients = false640useFlow &&= (flow.options.supportsSupportedClients || query.target !== GitHubTarget.DotCom);641} else {642useFlow &&= flow.options.supportsUnsupportedClients;643}644return useFlow;645});646}647648/**649* Social authentication providers for GitHub650*/651export const enum GitHubSocialSignInProvider {652Google = 'google',653Apple = 'apple',654}655656const GitHubSocialSignInProviderLabels = {657[GitHubSocialSignInProvider.Google]: l10n.t('Google'),658[GitHubSocialSignInProvider.Apple]: l10n.t('Apple'),659};660661export function isSocialSignInProvider(provider: unknown): provider is GitHubSocialSignInProvider {662return provider === GitHubSocialSignInProvider.Google || provider === GitHubSocialSignInProvider.Apple;663}664665666