mirror of
https://github.com/ckaczor/azuredatastudio.git
synced 2026-01-14 01:25:37 -05:00
Merge from vscode 79a1f5a5ca0c6c53db617aa1fa5a2396d2caebe2
This commit is contained in:
@@ -1,102 +0,0 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import { Uri, env } from 'vscode';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
export interface ClientDetails {
|
||||
id?: string;
|
||||
secret?: string;
|
||||
}
|
||||
|
||||
export interface ClientConfig {
|
||||
OSS: ClientDetails;
|
||||
INSIDERS: ClientDetails;
|
||||
STABLE: ClientDetails;
|
||||
EXPLORATION: ClientDetails;
|
||||
|
||||
VSO: ClientDetails;
|
||||
VSO_PPE: ClientDetails;
|
||||
VSO_DEV: ClientDetails;
|
||||
|
||||
GITHUB_APP: ClientDetails;
|
||||
}
|
||||
|
||||
export class Registrar {
|
||||
private _config: ClientConfig;
|
||||
|
||||
constructor() {
|
||||
try {
|
||||
const fileContents = fs.readFileSync(path.join(env.appRoot, 'extensions/github-authentication/src/common/config.json')).toString();
|
||||
this._config = JSON.parse(fileContents);
|
||||
} catch (e) {
|
||||
this._config = {
|
||||
OSS: {},
|
||||
INSIDERS: {},
|
||||
STABLE: {},
|
||||
EXPLORATION: {},
|
||||
VSO: {},
|
||||
VSO_PPE: {},
|
||||
VSO_DEV: {},
|
||||
GITHUB_APP: {}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
getGitHubAppDetails(): ClientDetails {
|
||||
if (!this._config.GITHUB_APP.id || !this._config.GITHUB_APP.secret) {
|
||||
throw new Error(`No GitHub App client configuration available`);
|
||||
}
|
||||
|
||||
return this._config.GITHUB_APP;
|
||||
}
|
||||
|
||||
getClientDetails(callbackUri: Uri): ClientDetails {
|
||||
let details: ClientDetails | undefined;
|
||||
switch (callbackUri.scheme) {
|
||||
case 'code-oss':
|
||||
details = this._config.OSS;
|
||||
break;
|
||||
|
||||
case 'vscode-insiders':
|
||||
details = this._config.INSIDERS;
|
||||
break;
|
||||
|
||||
case 'vscode':
|
||||
details = this._config.STABLE;
|
||||
break;
|
||||
|
||||
case 'vscode-exploration':
|
||||
details = this._config.EXPLORATION;
|
||||
break;
|
||||
|
||||
case 'https':
|
||||
switch (callbackUri.authority) {
|
||||
case 'online.visualstudio.com':
|
||||
details = this._config.VSO;
|
||||
break;
|
||||
case 'online-ppe.core.vsengsaas.visualstudio.com':
|
||||
details = this._config.VSO_PPE;
|
||||
break;
|
||||
case 'online.dev.core.vsengsaas.visualstudio.com':
|
||||
details = this._config.VSO_DEV;
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unrecognized callback ${callbackUri}`);
|
||||
}
|
||||
|
||||
if (!details.id || !details.secret) {
|
||||
throw new Error(`No client configuration available for ${callbackUri}`);
|
||||
}
|
||||
|
||||
return details;
|
||||
}
|
||||
}
|
||||
|
||||
const ClientRegistrar = new Registrar();
|
||||
export default ClientRegistrar;
|
||||
@@ -25,6 +25,7 @@ export async function activate(context: vscode.ExtensionContext) {
|
||||
vscode.authentication.registerAuthenticationProvider({
|
||||
id: 'github',
|
||||
displayName: 'GitHub',
|
||||
supportsMultipleAccounts: false,
|
||||
onDidChangeSessions: onDidChangeSessions.event,
|
||||
getSessions: () => Promise.resolve(loginService.sessions),
|
||||
login: async (scopeList: string[]) => {
|
||||
|
||||
@@ -21,20 +21,8 @@ interface SessionData {
|
||||
accessToken: string;
|
||||
}
|
||||
|
||||
// TODO remove
|
||||
interface OldSessionData {
|
||||
id: string;
|
||||
accountName: string;
|
||||
scopes: string[];
|
||||
accessToken: string;
|
||||
}
|
||||
|
||||
function isOldSessionData(x: any): x is OldSessionData {
|
||||
return !!x.accountName;
|
||||
}
|
||||
|
||||
export class GitHubAuthenticationProvider {
|
||||
private _sessions: vscode.AuthenticationSession[] = [];
|
||||
private _sessions: vscode.AuthenticationSession2[] = [];
|
||||
private _githubServer = new GitHubServer();
|
||||
|
||||
public async initialize(): Promise<void> {
|
||||
@@ -44,14 +32,12 @@ export class GitHubAuthenticationProvider {
|
||||
// Ignore, network request failed
|
||||
}
|
||||
|
||||
// TODO revert Cannot validate tokens from auth server, no available clientId
|
||||
// await this.validateSessions();
|
||||
this.pollForChange();
|
||||
}
|
||||
|
||||
private pollForChange() {
|
||||
setTimeout(async () => {
|
||||
let storedSessions: vscode.AuthenticationSession[];
|
||||
let storedSessions: vscode.AuthenticationSession2[];
|
||||
try {
|
||||
storedSessions = await this.readSessions();
|
||||
} catch (e) {
|
||||
@@ -94,13 +80,13 @@ export class GitHubAuthenticationProvider {
|
||||
}, 1000 * 30);
|
||||
}
|
||||
|
||||
private async readSessions(): Promise<vscode.AuthenticationSession[]> {
|
||||
private async readSessions(): Promise<vscode.AuthenticationSession2[]> {
|
||||
const storedSessions = await keychain.getToken();
|
||||
if (storedSessions) {
|
||||
try {
|
||||
const sessionData: (SessionData | OldSessionData)[] = JSON.parse(storedSessions);
|
||||
const sessionPromises = sessionData.map(async (session: SessionData | OldSessionData): Promise<vscode.AuthenticationSession> => {
|
||||
const needsUserInfo = isOldSessionData(session) || !session.account;
|
||||
const sessionData: SessionData[] = JSON.parse(storedSessions);
|
||||
const sessionPromises = sessionData.map(async (session: SessionData): Promise<vscode.AuthenticationSession2> => {
|
||||
const needsUserInfo = !session.account;
|
||||
let userInfo: { id: string, accountName: string };
|
||||
if (needsUserInfo) {
|
||||
userInfo = await this._githubServer.getUserInfo(session.accessToken);
|
||||
@@ -109,15 +95,11 @@ export class GitHubAuthenticationProvider {
|
||||
return {
|
||||
id: session.id,
|
||||
account: {
|
||||
displayName: isOldSessionData(session)
|
||||
? session.accountName
|
||||
: session.account?.displayName ?? userInfo!.accountName,
|
||||
id: isOldSessionData(session)
|
||||
? userInfo!.id
|
||||
: session.account?.id ?? userInfo!.id
|
||||
displayName: session.account?.displayName ?? userInfo!.accountName,
|
||||
id: session.account?.id ?? userInfo!.id
|
||||
},
|
||||
scopes: session.scopes,
|
||||
getAccessToken: () => Promise.resolve(session.accessToken)
|
||||
accessToken: session.accessToken
|
||||
};
|
||||
});
|
||||
|
||||
@@ -136,57 +118,30 @@ export class GitHubAuthenticationProvider {
|
||||
}
|
||||
|
||||
private async storeSessions(): Promise<void> {
|
||||
const sessionData: SessionData[] = await Promise.all(this._sessions.map(async session => {
|
||||
const resolvedAccessToken = await session.getAccessToken();
|
||||
return {
|
||||
id: session.id,
|
||||
account: session.account,
|
||||
scopes: session.scopes,
|
||||
accessToken: resolvedAccessToken
|
||||
};
|
||||
}));
|
||||
|
||||
await keychain.setToken(JSON.stringify(sessionData));
|
||||
await keychain.setToken(JSON.stringify(this._sessions));
|
||||
}
|
||||
|
||||
get sessions(): vscode.AuthenticationSession[] {
|
||||
get sessions(): vscode.AuthenticationSession2[] {
|
||||
return this._sessions;
|
||||
}
|
||||
|
||||
public async login(scopes: string): Promise<vscode.AuthenticationSession> {
|
||||
const token = scopes === 'vso' ? await this.loginAndInstallApp(scopes) : await this._githubServer.login(scopes);
|
||||
public async login(scopes: string): Promise<vscode.AuthenticationSession2> {
|
||||
const token = await this._githubServer.login(scopes);
|
||||
const session = await this.tokenToSession(token, scopes.split(' '));
|
||||
await this.setToken(session);
|
||||
return session;
|
||||
}
|
||||
|
||||
public async loginAndInstallApp(scopes: string): Promise<string> {
|
||||
const token = await this._githubServer.login(scopes);
|
||||
const hasUserInstallation = await this._githubServer.hasUserInstallation(token);
|
||||
if (hasUserInstallation) {
|
||||
return token;
|
||||
} else {
|
||||
return this._githubServer.installApp();
|
||||
}
|
||||
}
|
||||
|
||||
public async manuallyProvideToken(): Promise<void> {
|
||||
this._githubServer.manuallyProvideToken();
|
||||
}
|
||||
|
||||
private async tokenToSession(token: string, scopes: string[]): Promise<vscode.AuthenticationSession> {
|
||||
private async tokenToSession(token: string, scopes: string[]): Promise<vscode.AuthenticationSession2> {
|
||||
const userInfo = await this._githubServer.getUserInfo(token);
|
||||
return {
|
||||
id: uuid(),
|
||||
getAccessToken: () => Promise.resolve(token),
|
||||
account: {
|
||||
displayName: userInfo.accountName,
|
||||
id: userInfo.id
|
||||
},
|
||||
scopes: scopes
|
||||
};
|
||||
return new vscode.AuthenticationSession2(uuid(), token, { displayName: userInfo.accountName, id: userInfo.id }, scopes);
|
||||
}
|
||||
private async setToken(session: vscode.AuthenticationSession): Promise<void> {
|
||||
|
||||
private async setToken(session: vscode.AuthenticationSession2): Promise<void> {
|
||||
const sessionIndex = this._sessions.findIndex(s => s.id === session.id);
|
||||
if (sessionIndex > -1) {
|
||||
this._sessions.splice(sessionIndex, 1, session);
|
||||
@@ -201,14 +156,6 @@ export class GitHubAuthenticationProvider {
|
||||
const sessionIndex = this._sessions.findIndex(session => session.id === id);
|
||||
if (sessionIndex > -1) {
|
||||
this._sessions.splice(sessionIndex, 1);
|
||||
// TODO revert
|
||||
// Cannot revoke tokens from auth server, no clientId available
|
||||
// const token = await session.getAccessToken();
|
||||
// try {
|
||||
// await this._githubServer.revokeToken(token);
|
||||
// } catch (_) {
|
||||
// // ignore, should still remove from keychain
|
||||
// }
|
||||
}
|
||||
|
||||
await this.storeSessions();
|
||||
|
||||
@@ -9,7 +9,6 @@ import * as vscode from 'vscode';
|
||||
import * as uuid from 'uuid';
|
||||
import { PromiseAdapter, promiseFromEvent } from './common/utils';
|
||||
import Logger from './common/logger';
|
||||
import ClientRegistrar from './common/clientRegistrar';
|
||||
|
||||
const localize = nls.loadMessageBundle();
|
||||
|
||||
@@ -24,8 +23,8 @@ class UriEventHandler extends vscode.EventEmitter<vscode.Uri> implements vscode.
|
||||
|
||||
export const uriHandler = new UriEventHandler;
|
||||
|
||||
const exchangeCodeForToken: (state: string, host: string, getPath: (code: string) => string) => PromiseAdapter<vscode.Uri, string> =
|
||||
(state, host, getPath) => async (uri, resolve, reject) => {
|
||||
const exchangeCodeForToken: (state: string) => PromiseAdapter<vscode.Uri, string> =
|
||||
(state) => async (uri, resolve, reject) => {
|
||||
Logger.info('Exchanging code for token...');
|
||||
const query = parseQuery(uri);
|
||||
const code = query.code;
|
||||
@@ -36,8 +35,8 @@ const exchangeCodeForToken: (state: string, host: string, getPath: (code: string
|
||||
}
|
||||
|
||||
const post = https.request({
|
||||
host: host,
|
||||
path: getPath(code),
|
||||
host: AUTH_RELAY_SERVER,
|
||||
path: `/token?code=${code}&state=${state}`,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json'
|
||||
@@ -81,26 +80,13 @@ export class GitHubServer {
|
||||
|
||||
const state = uuid();
|
||||
const callbackUri = await vscode.env.asExternalUri(vscode.Uri.parse(`${vscode.env.uriScheme}://vscode.github-authentication/did-authenticate`));
|
||||
let uri = vscode.Uri.parse(`https://${AUTH_RELAY_SERVER}/authorize/?callbackUri=${encodeURIComponent(callbackUri.toString())}&scope=${scopes}&state=${state}&responseType=code`);
|
||||
if (scopes === 'vso') {
|
||||
const clientDetails = ClientRegistrar.getGitHubAppDetails();
|
||||
uri = vscode.Uri.parse(`https://github.com/login/oauth/authorize?redirect_uri=${encodeURIComponent(callbackUri.toString())}&scope=${scopes}&state=${state}&client_id=${clientDetails.id}`);
|
||||
}
|
||||
const uri = vscode.Uri.parse(`https://${AUTH_RELAY_SERVER}/authorize/?callbackUri=${encodeURIComponent(callbackUri.toString())}&scope=${scopes}&state=${state}&responseType=code`);
|
||||
|
||||
vscode.env.openExternal(uri);
|
||||
|
||||
return promiseFromEvent(uriHandler.event, exchangeCodeForToken(state,
|
||||
scopes === 'vso' ? 'github.com' : AUTH_RELAY_SERVER,
|
||||
(code) => {
|
||||
if (scopes === 'vso') {
|
||||
const clientDetails = ClientRegistrar.getGitHubAppDetails();
|
||||
return `/login/oauth/access_token?client_id=${clientDetails.id}&client_secret=${clientDetails.secret}&state=${state}&code=${code}`;
|
||||
} else {
|
||||
return `/token?code=${code}&state=${state}`;
|
||||
}
|
||||
})).finally(() => {
|
||||
this.updateStatusBarItem(false);
|
||||
});
|
||||
return promiseFromEvent(uriHandler.event, exchangeCodeForToken(state)).finally(() => {
|
||||
this.updateStatusBarItem(false);
|
||||
});
|
||||
}
|
||||
|
||||
private updateStatusBarItem(isStart?: boolean) {
|
||||
@@ -130,51 +116,6 @@ export class GitHubServer {
|
||||
}
|
||||
}
|
||||
|
||||
public async hasUserInstallation(token: string): Promise<boolean> {
|
||||
return new Promise((resolve, reject) => {
|
||||
Logger.info('Getting user installations...');
|
||||
const post = https.request({
|
||||
host: 'api.github.com',
|
||||
path: `/user/installations`,
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'application/vnd.github.machine-man-preview+json',
|
||||
Authorization: `token ${token}`,
|
||||
'User-Agent': 'Visual-Studio-Code'
|
||||
}
|
||||
}, result => {
|
||||
const buffer: Buffer[] = [];
|
||||
result.on('data', (chunk: Buffer) => {
|
||||
buffer.push(chunk);
|
||||
});
|
||||
result.on('end', () => {
|
||||
if (result.statusCode === 200) {
|
||||
const json = JSON.parse(Buffer.concat(buffer).toString());
|
||||
Logger.info('Got installation info!');
|
||||
const hasInstallation = json.installations.some((installation: { app_slug: string }) => installation.app_slug === 'microsoft-visual-studio-code');
|
||||
resolve(hasInstallation);
|
||||
} else {
|
||||
reject(new Error(result.statusMessage));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
post.end();
|
||||
post.on('error', err => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public async installApp(): Promise<string> {
|
||||
const clientDetails = ClientRegistrar.getGitHubAppDetails();
|
||||
const state = uuid();
|
||||
const uri = vscode.Uri.parse(`https://github.com/apps/microsoft-visual-studio-code/installations/new?state=${state}`);
|
||||
|
||||
vscode.env.openExternal(uri);
|
||||
return promiseFromEvent(uriHandler.event, exchangeCodeForToken(state, 'github.com', (code) => `/login/oauth/access_token?client_id=${clientDetails.id}&client_secret=${clientDetails.secret}&state=${state}&code=${code}`));
|
||||
}
|
||||
|
||||
public async getUserInfo(token: string): Promise<{ id: string, accountName: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
Logger.info('Getting account info...');
|
||||
@@ -210,91 +151,4 @@ export class GitHubServer {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public async validateToken(token: string): Promise<void> {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const callbackUri = await vscode.env.asExternalUri(vscode.Uri.parse(`${vscode.env.uriScheme}://vscode.github-authentication/did-authenticate`));
|
||||
const clientDetails = ClientRegistrar.getClientDetails(callbackUri);
|
||||
const detailsString = `${clientDetails.id}:${clientDetails.secret}`;
|
||||
|
||||
const payload = JSON.stringify({ access_token: token });
|
||||
|
||||
Logger.info('Validating token...');
|
||||
const post = https.request({
|
||||
host: 'api.github.com',
|
||||
path: `/applications/${clientDetails.id}/token`,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Basic ${Buffer.from(detailsString).toString('base64')}`,
|
||||
'User-Agent': 'Visual-Studio-Code',
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(payload)
|
||||
}
|
||||
}, result => {
|
||||
const buffer: Buffer[] = [];
|
||||
result.on('data', (chunk: Buffer) => {
|
||||
buffer.push(chunk);
|
||||
});
|
||||
result.on('end', () => {
|
||||
if (result.statusCode === 200) {
|
||||
Logger.info('Validated token!');
|
||||
resolve();
|
||||
} else {
|
||||
Logger.info(`Validating token failed: ${result.statusMessage}`);
|
||||
reject(new Error(result.statusMessage));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
post.write(payload);
|
||||
post.end();
|
||||
post.on('error', err => {
|
||||
Logger.error(err.message);
|
||||
reject(new Error(NETWORK_ERROR));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public async revokeToken(token: string): Promise<void> {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const callbackUri = await vscode.env.asExternalUri(vscode.Uri.parse(`${vscode.env.uriScheme}://vscode.github-authentication/did-authenticate`));
|
||||
const clientDetails = ClientRegistrar.getClientDetails(callbackUri);
|
||||
const detailsString = `${clientDetails.id}:${clientDetails.secret}`;
|
||||
|
||||
const payload = JSON.stringify({ access_token: token });
|
||||
|
||||
Logger.info('Revoking token...');
|
||||
const post = https.request({
|
||||
host: 'api.github.com',
|
||||
path: `/applications/${clientDetails.id}/token`,
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
Authorization: `Basic ${Buffer.from(detailsString).toString('base64')}`,
|
||||
'User-Agent': 'Visual-Studio-Code',
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(payload)
|
||||
}
|
||||
}, result => {
|
||||
const buffer: Buffer[] = [];
|
||||
result.on('data', (chunk: Buffer) => {
|
||||
buffer.push(chunk);
|
||||
});
|
||||
result.on('end', () => {
|
||||
if (result.statusCode === 204) {
|
||||
Logger.info('Revoked token!');
|
||||
resolve();
|
||||
} else {
|
||||
Logger.info(`Revoking token failed: ${result.statusMessage}`);
|
||||
reject(new Error(result.statusMessage));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
post.write(payload);
|
||||
post.end();
|
||||
post.on('error', err => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user