use-github-pat.patch 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. diff --git a/extensions/github-authentication/src/githubServer.ts b/extensions/github-authentication/src/githubServer.ts
  2. index 3002e937c81..9674d8d2089 100644
  3. --- a/extensions/github-authentication/src/githubServer.ts
  4. +++ b/extensions/github-authentication/src/githubServer.ts
  5. @@ -3,41 +3,13 @@
  6. * Licensed under the MIT License. See License.txt in the project root for license information.
  7. *--------------------------------------------------------------------------------------------*/
  8. -import * as nls from 'vscode-nls';
  9. import * as vscode from 'vscode';
  10. import fetch, { Response } from 'node-fetch';
  11. -import { v4 as uuid } from 'uuid';
  12. -import { PromiseAdapter, promiseFromEvent } from './common/utils';
  13. import { ExperimentationTelemetry } from './experimentationService';
  14. import { AuthProviderType } from './github';
  15. import { Log } from './common/logger';
  16. -import { isSupportedEnvironment } from './common/env';
  17. -
  18. -const localize = nls.loadMessageBundle();
  19. -const CLIENT_ID = '01ab8ac9400c4e429b23';
  20. const NETWORK_ERROR = 'network error';
  21. -const AUTH_RELAY_SERVER = 'vscode-auth.github.com';
  22. -// const AUTH_RELAY_STAGING_SERVER = 'client-auth-staging-14a768b.herokuapp.com';
  23. -
  24. -class UriEventHandler extends vscode.EventEmitter<vscode.Uri> implements vscode.UriHandler {
  25. - constructor(private readonly Logger: Log) {
  26. - super();
  27. - }
  28. -
  29. - public handleUri(uri: vscode.Uri) {
  30. - this.Logger.trace('Handling Uri...');
  31. - this.fire(uri);
  32. - }
  33. -}
  34. -
  35. -function parseQuery(uri: vscode.Uri) {
  36. - return uri.query.split('&').reduce((prev: any, current) => {
  37. - const queryString = current.split('=');
  38. - prev[queryString[0]] = queryString[1];
  39. - return prev;
  40. - }, {});
  41. -}
  42. export interface IGitHubServer extends vscode.Disposable {
  43. login(scopes: string): Promise<string>;
  44. @@ -47,13 +19,6 @@ export interface IGitHubServer extends vscode.Disposable {
  45. type: AuthProviderType;
  46. }
  47. -interface IGitHubDeviceCodeResponse {
  48. - device_code: string;
  49. - user_code: string;
  50. - verification_uri: string;
  51. - interval: number;
  52. -}
  53. -
  54. async function getScopes(token: string, serverUri: vscode.Uri, logger: Log): Promise<string[]> {
  55. try {
  56. logger.info('Getting token scopes...');
  57. @@ -115,315 +80,49 @@ async function getUserInfo(token: string, serverUri: vscode.Uri, logger: Log): P
  58. export class GitHubServer implements IGitHubServer {
  59. friendlyName = 'GitHub';
  60. type = AuthProviderType.github;
  61. - private _statusBarItem: vscode.StatusBarItem | undefined;
  62. - private _onDidManuallyProvideToken = new vscode.EventEmitter<string | undefined>();
  63. -
  64. - private _pendingStates = new Map<string, string[]>();
  65. - private _codeExchangePromises = new Map<string, { promise: Promise<string>, cancel: vscode.EventEmitter<void> }>();
  66. - private _statusBarCommandId = `${this.type}.provide-manually`;
  67. - private _disposable: vscode.Disposable;
  68. - private _uriHandler = new UriEventHandler(this._logger);
  69. constructor(private readonly _supportDeviceCodeFlow: boolean, private readonly _logger: Log, private readonly _telemetryReporter: ExperimentationTelemetry) {
  70. - this._disposable = vscode.Disposable.from(
  71. - vscode.commands.registerCommand(this._statusBarCommandId, () => this.manuallyProvideUri()),
  72. - vscode.window.registerUriHandler(this._uriHandler));
  73. + this._supportDeviceCodeFlow;
  74. }
  75. dispose() {
  76. - this._disposable.dispose();
  77. - }
  78. -
  79. - // TODO@joaomoreno TODO@TylerLeonhardt
  80. - private async isNoCorsEnvironment(): Promise<boolean> {
  81. - const uri = await vscode.env.asExternalUri(vscode.Uri.parse(`${vscode.env.uriScheme}://vscode.github-authentication/dummy`));
  82. - return (uri.scheme === 'https' && /^((insiders\.)?vscode|github)\./.test(uri.authority)) || (uri.scheme === 'http' && /^localhost/.test(uri.authority));
  83. }
  84. public async login(scopes: string): Promise<string> {
  85. this._logger.info(`Logging in for the following scopes: ${scopes}`);
  86. - const callbackUri = await vscode.env.asExternalUri(vscode.Uri.parse(`${vscode.env.uriScheme}://vscode.github-authentication/did-authenticate`));
  87. -
  88. - if (!isSupportedEnvironment(callbackUri)) {
  89. - const token = this._supportDeviceCodeFlow
  90. - ? await this.doDeviceCodeFlow(scopes)
  91. - : await vscode.window.showInputBox({ prompt: 'GitHub Personal Access Token', ignoreFocusOut: true });
  92. -
  93. - if (!token) { throw new Error('No token provided'); }
  94. -
  95. - const tokenScopes = await getScopes(token, this.getServerUri('/'), this._logger); // Example: ['repo', 'user']
  96. - const scopesList = scopes.split(' '); // Example: 'read:user repo user:email'
  97. - if (!scopesList.every(scope => {
  98. - const included = tokenScopes.includes(scope);
  99. - if (included || !scope.includes(':')) {
  100. - return included;
  101. - }
  102. -
  103. - return scope.split(':').some(splitScopes => {
  104. - return tokenScopes.includes(splitScopes);
  105. - });
  106. - })) {
  107. - throw new Error(`The provided token does not match the requested scopes: ${scopes}`);
  108. - }
  109. -
  110. - return token;
  111. - }
  112. -
  113. - this.updateStatusBarItem(true);
  114. -
  115. - const state = uuid();
  116. - const existingStates = this._pendingStates.get(scopes) || [];
  117. - this._pendingStates.set(scopes, [...existingStates, state]);
  118. -
  119. - const uri = vscode.Uri.parse(`https://${AUTH_RELAY_SERVER}/authorize/?callbackUri=${encodeURIComponent(callbackUri.toString())}&scope=${scopes}&state=${state}&responseType=code&authServer=https://github.com`);
  120. - await vscode.env.openExternal(uri);
  121. -
  122. - // Register a single listener for the URI callback, in case the user starts the login process multiple times
  123. - // before completing it.
  124. - let codeExchangePromise = this._codeExchangePromises.get(scopes);
  125. - if (!codeExchangePromise) {
  126. - codeExchangePromise = promiseFromEvent(this._uriHandler.event, this.exchangeCodeForToken(scopes));
  127. - this._codeExchangePromises.set(scopes, codeExchangePromise);
  128. - }
  129. -
  130. - return Promise.race([
  131. - codeExchangePromise.promise,
  132. - promiseFromEvent<string | undefined, string>(this._onDidManuallyProvideToken.event, (token: string | undefined, resolve, reject): void => {
  133. - if (!token) {
  134. - reject('Cancelled');
  135. - } else {
  136. - resolve(token);
  137. - }
  138. - }).promise,
  139. - new Promise<string>((_, reject) => setTimeout(() => reject('Cancelled'), 60000))
  140. - ]).finally(() => {
  141. - this._pendingStates.delete(scopes);
  142. - codeExchangePromise?.cancel.fire();
  143. - this._codeExchangePromises.delete(scopes);
  144. - this.updateStatusBarItem(false);
  145. - });
  146. - }
  147. -
  148. - private async doDeviceCodeFlow(scopes: string): Promise<string> {
  149. - // Get initial device code
  150. - const uri = `https://github.com/login/device/code?client_id=${CLIENT_ID}&scope=${scopes}`;
  151. - const result = await fetch(uri, {
  152. - method: 'POST',
  153. - headers: {
  154. - Accept: 'application/json'
  155. - }
  156. - });
  157. - if (!result.ok) {
  158. - throw new Error(`Failed to get one-time code: ${await result.text()}`);
  159. - }
  160. -
  161. - const json = await result.json() as IGitHubDeviceCodeResponse;
  162. -
  163. -
  164. - const modalResult = await vscode.window.showInformationMessage(
  165. - localize('code.title', "Your Code: {0}", json.user_code),
  166. - {
  167. - modal: true,
  168. - detail: localize('code.detail', "To finish authenticating, navigate to GitHub and paste in the above one-time code.")
  169. - }, 'Copy & Continue to GitHub');
  170. -
  171. - if (modalResult !== 'Copy & Continue to GitHub') {
  172. - throw new Error('Cancelled');
  173. - }
  174. -
  175. - await vscode.env.clipboard.writeText(json.user_code);
  176. -
  177. - const uriToOpen = await vscode.env.asExternalUri(vscode.Uri.parse(json.verification_uri));
  178. - await vscode.env.openExternal(uriToOpen);
  179. -
  180. - return await vscode.window.withProgress<string>({
  181. - location: vscode.ProgressLocation.Notification,
  182. - cancellable: true,
  183. - title: localize(
  184. - 'progress',
  185. - "Open [{0}]({0}) in a new tab and paste your one-time code: {1}",
  186. - json.verification_uri,
  187. - json.user_code)
  188. - }, async (_, token) => {
  189. - return await this.waitForDeviceCodeAccessToken(json, token);
  190. - });
  191. - }
  192. -
  193. - private async waitForDeviceCodeAccessToken(
  194. - json: IGitHubDeviceCodeResponse,
  195. - token: vscode.CancellationToken
  196. - ): Promise<string> {
  197. -
  198. - const refreshTokenUri = `https://github.com/login/oauth/access_token?client_id=${CLIENT_ID}&device_code=${json.device_code}&grant_type=urn:ietf:params:oauth:grant-type:device_code`;
  199. -
  200. - // Try for 2 minutes
  201. - const attempts = 120 / json.interval;
  202. - for (let i = 0; i < attempts; i++) {
  203. - await new Promise(resolve => setTimeout(resolve, json.interval * 1000));
  204. - if (token.isCancellationRequested) {
  205. - throw new Error('Cancelled');
  206. - }
  207. - let accessTokenResult;
  208. - try {
  209. - accessTokenResult = await fetch(refreshTokenUri, {
  210. - method: 'POST',
  211. - headers: {
  212. - Accept: 'application/json'
  213. - }
  214. - });
  215. - } catch {
  216. - continue;
  217. - }
  218. -
  219. - if (!accessTokenResult.ok) {
  220. - continue;
  221. - }
  222. + const token = await vscode.window.showInputBox({ prompt: 'GitHub Personal Access Token', ignoreFocusOut: true });
  223. - const accessTokenJson = await accessTokenResult.json();
  224. + if (!token) { throw new Error('No token provided'); }
  225. - if (accessTokenJson.error === 'authorization_pending') {
  226. - continue;
  227. - }
  228. -
  229. - if (accessTokenJson.error) {
  230. - throw new Error(accessTokenJson.error_description);
  231. + const tokenScopes = await getScopes(token, this.getServerUri('/'), this._logger); // Example: ['repo', 'user']
  232. + const scopesList = scopes.split(' '); // Example: 'read:user repo user:email'
  233. + if (!scopesList.every(scope => {
  234. + const included = tokenScopes.includes(scope);
  235. + if (included || !scope.includes(':')) {
  236. + return included;
  237. }
  238. - return accessTokenJson.access_token;
  239. + return scope.split(':').some(splitScopes => {
  240. + return tokenScopes.includes(splitScopes);
  241. + });
  242. + })) {
  243. + throw new Error(`The provided token does not match the requested scopes: ${scopes}`);
  244. }
  245. - throw new Error('Cancelled');
  246. + return token;
  247. }
  248. - private exchangeCodeForToken: (scopes: string) => PromiseAdapter<vscode.Uri, string> =
  249. - (scopes) => async (uri, resolve, reject) => {
  250. - const query = parseQuery(uri);
  251. - const code = query.code;
  252. -
  253. - const acceptedStates = this._pendingStates.get(scopes) || [];
  254. - if (!acceptedStates.includes(query.state)) {
  255. - // A common scenario of this happening is if you:
  256. - // 1. Trigger a sign in with one set of scopes
  257. - // 2. Before finishing 1, you trigger a sign in with a different set of scopes
  258. - // In this scenario we should just return and wait for the next UriHandler event
  259. - // to run as we are probably still waiting on the user to hit 'Continue'
  260. - this._logger.info('State not found in accepted state. Skipping this execution...');
  261. - return;
  262. - }
  263. -
  264. - const url = `https://${AUTH_RELAY_SERVER}/token?code=${code}&state=${query.state}`;
  265. - this._logger.info('Exchanging code for token...');
  266. -
  267. - try {
  268. - const result = await fetch(url, {
  269. - method: 'POST',
  270. - headers: {
  271. - Accept: 'application/json'
  272. - }
  273. - });
  274. -
  275. - if (result.ok) {
  276. - const json = await result.json();
  277. - this._logger.info('Token exchange success!');
  278. - resolve(json.access_token);
  279. - } else {
  280. - reject(result.statusText);
  281. - }
  282. - } catch (ex) {
  283. - reject(ex);
  284. - }
  285. - };
  286. -
  287. private getServerUri(path: string = '') {
  288. const apiUri = vscode.Uri.parse('https://api.github.com');
  289. return vscode.Uri.parse(`${apiUri.scheme}://${apiUri.authority}${path}`);
  290. }
  291. - private updateStatusBarItem(isStart?: boolean) {
  292. - if (isStart && !this._statusBarItem) {
  293. - this._statusBarItem = vscode.window.createStatusBarItem('status.git.signIn', vscode.StatusBarAlignment.Left);
  294. - this._statusBarItem.name = localize('status.git.signIn.name', "GitHub Sign-in");
  295. - this._statusBarItem.text = localize('signingIn', "$(mark-github) Signing in to github.com...");
  296. - this._statusBarItem.command = this._statusBarCommandId;
  297. - this._statusBarItem.show();
  298. - }
  299. -
  300. - if (!isStart && this._statusBarItem) {
  301. - this._statusBarItem.dispose();
  302. - this._statusBarItem = undefined;
  303. - }
  304. - }
  305. -
  306. - private async manuallyProvideUri() {
  307. - const uri = await vscode.window.showInputBox({
  308. - prompt: 'Uri',
  309. - ignoreFocusOut: true,
  310. - validateInput(value) {
  311. - if (!value) {
  312. - return undefined;
  313. - }
  314. - const error = localize('validUri', "Please enter a valid Uri from the GitHub login page.");
  315. - try {
  316. - const uri = vscode.Uri.parse(value.trim());
  317. - if (!uri.scheme || uri.scheme === 'file') {
  318. - return error;
  319. - }
  320. - } catch (e) {
  321. - return error;
  322. - }
  323. - return undefined;
  324. - }
  325. - });
  326. - if (!uri) {
  327. - return;
  328. - }
  329. -
  330. - this._uriHandler.handleUri(vscode.Uri.parse(uri.trim()));
  331. - }
  332. -
  333. public getUserInfo(token: string): Promise<{ id: string, accountName: string }> {
  334. return getUserInfo(token, this.getServerUri('/user'), this._logger);
  335. }
  336. - public async sendAdditionalTelemetryInfo(token: string): Promise<void> {
  337. - if (!vscode.env.isTelemetryEnabled) {
  338. - return;
  339. - }
  340. - const nocors = await this.isNoCorsEnvironment();
  341. -
  342. - if (nocors) {
  343. - return;
  344. - }
  345. -
  346. - try {
  347. - const result = await fetch('https://education.github.com/api/user', {
  348. - headers: {
  349. - Authorization: `token ${token}`,
  350. - 'faculty-check-preview': 'true',
  351. - 'User-Agent': 'Visual-Studio-Code'
  352. - }
  353. - });
  354. -
  355. - if (result.ok) {
  356. - const json: { student: boolean, faculty: boolean } = await result.json();
  357. -
  358. - /* __GDPR__
  359. - "session" : {
  360. - "isEdu": { "classification": "NonIdentifiableDemographicInfo", "purpose": "FeatureInsight" }
  361. - }
  362. - */
  363. - this._telemetryReporter.sendTelemetryEvent('session', {
  364. - isEdu: json.student
  365. - ? 'student'
  366. - : json.faculty
  367. - ? 'faculty'
  368. - : 'none'
  369. - });
  370. - }
  371. - } catch (e) {
  372. - // No-op
  373. - }
  374. + public async sendAdditionalTelemetryInfo(_: string): Promise<void> {
  375. }
  376. public async checkEnterpriseVersion(token: string): Promise<void> {