Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement gitpod auth and settings sync #337

Merged
merged 1 commit into from
Apr 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 51 additions & 2 deletions extensions/gitpod/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,52 @@
],
"activationEvents": [
"*",
"onCommand:gitpod.api.autoTunnel"
"onCommand:gitpod.api.autoTunnel",
"onAuthenticationRequest:gitpod"
],
"contributes": {
"authentication": [
{
"label": "Gitpod",
"id": "gitpod"
}
],
"configuration": [
{
"title": "Gitpod",
"properties": {
"gitpod.host": {
"type": "string",
"description": "Gitpod Service URL. Update this if you are using a Gitpod self-hosted installation.",
"default": "https://gitpod.io/",
"scope": "application"
}
}
},
{
"title": "Settings sync",
"properties": {
"configurationSync.store": {
"type": "object",
"description": "Settings Sync Provider configuration.",
"scope": "application"
}
}
}
],
"commands": [
{
"command": "gitpod.syncProvider.remove",
"category": "Settings Sync",
"enablement": "gitpod.addedSyncProvider",
"title": "Disable Sign In with Gitpod"
},
{
"command": "gitpod.syncProvider.add",
"category": "Settings Sync",
"enablement": "!gitpod.addedSyncProvider",
"title": "Enable Sign In with Gitpod"
},
{
"command": "gitpod.exportLogs",
"category": "Gitpod",
Expand All @@ -47,17 +89,24 @@
"vscode:prepublish": "npm run compile"
},
"devDependencies": {
"@types/analytics-node": "^3.1.8",
"@types/crypto-js": "4.1.1",
"@types/node": "16.x",
"@types/node-fetch": "^2.5.12",
"@types/tmp": "^0.2.1",
"@types/uuid": "8.0.0",
"@types/ws": "^7.2.6",
"@types/yazl": "^2.4.2"
},
"dependencies": {
"@gitpod/gitpod-protocol": "main",
"@gitpod/local-app-api-grpcweb": "main",
"@improbable-eng/grpc-web-node-http-transport": "^0.14.0",
"analytics-node": "^6.0.0",
"node-fetch": "2.6.7",
"pkce-challenge": "^3.0.0",
"tmp": "^0.2.1",
"vscode-nls": "^5.0.0",
"uuid": "8.1.0",
"yazl": "^2.5.1"
},
"extensionDependencies": [
Expand Down
272 changes: 272 additions & 0 deletions extensions/gitpod/src/authentication.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,272 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Gitpod. All rights reserved.
*--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';
import { v4 as uuid } from 'uuid';
import { Keychain } from './common/keychain';
import { GitpodServer } from './gitpodServer';
import Log from './common/logger';
import { arrayEquals } from './common/utils';
import { Disposable } from './common/dispose';
import TelemetryReporter from './telemetryReporter';

interface SessionData {
id: string;
account?: {
label?: string;
displayName?: string;
id: string;
};
scopes: string[];
accessToken: string;
}

export default class GitpodAuthenticationProvider extends Disposable implements vscode.AuthenticationProvider {
private _sessionChangeEmitter = new vscode.EventEmitter<vscode.AuthenticationProviderAuthenticationSessionsChangeEvent>();
private _logger: Log;
private _telemetry: TelemetryReporter;
private _gitpodServer: GitpodServer;
private _keychain: Keychain;

private _sessionsPromise: Promise<vscode.AuthenticationSession[]>;

constructor(private readonly context: vscode.ExtensionContext, logger: Log, telemetry: TelemetryReporter) {
super();

this._logger = logger;
this._telemetry = telemetry;

const gitpodHost = vscode.workspace.getConfiguration('gitpod').get<string>('host')!;
const serviceUrl = new URL(gitpodHost);
this._gitpodServer = new GitpodServer(serviceUrl.toString(), this._logger);
this._keychain = new Keychain(this.context, `gitpod.auth.${serviceUrl.hostname}`, this._logger);
this._register(vscode.workspace.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('gitpod.host')) {
const gitpodHost = vscode.workspace.getConfiguration('gitpod').get<string>('host')!;
const serviceUrl = new URL(gitpodHost);
this._gitpodServer.dispose();
this._gitpodServer = new GitpodServer(serviceUrl.toString(), this._logger);
this._keychain = new Keychain(this.context, `gitpod.auth.${serviceUrl.hostname}`, this._logger);

this.checkForUpdates();
}
}));

// Contains the current state of the sessions we have available.
this._sessionsPromise = this.readSessions();

this._register(vscode.authentication.registerAuthenticationProvider('gitpod', 'Gitpod', this, { supportsMultipleAccounts: false }));
this._register(this.context.secrets.onDidChange(() => this.checkForUpdates()));
}

get onDidChangeSessions() {
return this._sessionChangeEmitter.event;
}

async getSessions(scopes?: string[]): Promise<vscode.AuthenticationSession[]> {
// For the Gitpod scope list, order doesn't matter so we immediately sort the scopes
const sortedScopes = scopes?.sort() || [];
this._logger.info(`Getting sessions for ${sortedScopes.length ? sortedScopes.join(',') : 'all scopes'}...`);
const sessions = await this._sessionsPromise;
const finalSessions = sortedScopes.length
? sessions.filter(session => arrayEquals([...session.scopes].sort(), sortedScopes))
: sessions;

this._logger.info(`Got ${finalSessions.length} sessions for ${sortedScopes?.join(',') ?? 'all scopes'}...`);
return finalSessions;
}

private async checkForUpdates() {
jeanp413 marked this conversation as resolved.
Show resolved Hide resolved
const previousSessions = await this._sessionsPromise;
this._sessionsPromise = this.readSessions();
const storedSessions = await this._sessionsPromise;

const added: vscode.AuthenticationSession[] = [];
const removed: vscode.AuthenticationSession[] = [];

storedSessions.forEach(session => {
const matchesExisting = previousSessions.some(s => s.id === session.id);
// Another window added a session to the keychain, add it to our state as well
if (!matchesExisting) {
this._logger.info('Adding session found in keychain');
added.push(session);
}
});

previousSessions.forEach(session => {
const matchesExisting = storedSessions.some(s => s.id === session.id);
// Another window has logged out, remove from our state
if (!matchesExisting) {
this._logger.info('Removing session no longer found in keychain');
removed.push(session);
}
});

if (added.length || removed.length) {
this._sessionChangeEmitter.fire({ added, removed, changed: [] });
}
}

private async readSessions(): Promise<vscode.AuthenticationSession[]> {
let sessionData: SessionData[];
try {
this._logger.info('Reading sessions from keychain...');
const storedSessions = await this._keychain.getToken();
if (!storedSessions) {
return [];
}
this._logger.info('Got stored sessions!');

try {
sessionData = JSON.parse(storedSessions);
} catch (e) {
await this._keychain.deleteToken();
throw e;
}
} catch (e) {
this._logger.error(`Error reading token: ${e}`);
return [];
}

const sessionPromises = sessionData.map(async (session: SessionData) => {
// For the Gitpod scope list, order doesn't matter so we immediately sort the scopes
const sortedScopes = session.scopes.sort();
const scopesStr = sortedScopes.join(' ');

let userInfo: { id: string; accountName: string } | undefined;
if (!session.account) {
akosyakov marked this conversation as resolved.
Show resolved Hide resolved
try {
userInfo = await this._gitpodServer.getUserInfo(session.accessToken);
this._logger.info(`Verified session with the following scopes: ${scopesStr}`);
} catch (e) {
// Remove sessions that return unauthorized response
if (e.message === 'Unauthorized') {
return undefined;
}
}
}

this._logger.trace(`Read the following session from the keychain with the following scopes: ${scopesStr}`);
return {
id: session.id,
account: {
label: session.account
? session.account.label ?? session.account.displayName ?? '<unknown>'
: userInfo?.accountName ?? '<unknown>',
id: session.account?.id ?? userInfo?.id ?? '<unknown>'
},
scopes: sortedScopes,
accessToken: session.accessToken
};
});

const verifiedSessions = (await Promise.allSettled(sessionPromises))
.filter(p => p.status === 'fulfilled')
.map(p => (p as PromiseFulfilledResult<vscode.AuthenticationSession | undefined>).value)
.filter(<T>(p?: T): p is T => Boolean(p));

this._logger.info(`Got ${verifiedSessions.length} verified sessions.`);
if (verifiedSessions.length !== sessionData.length) {
await this.storeSessions(verifiedSessions);
}

return verifiedSessions;
}

private async storeSessions(sessions: vscode.AuthenticationSession[]): Promise<void> {
this._logger.info(`Storing ${sessions.length} sessions...`);
this._sessionsPromise = Promise.resolve(sessions);
await this._keychain.setToken(JSON.stringify(sessions));
this._logger.info(`Stored ${sessions.length} sessions!`);
}

public async createSession(scopes: string[]): Promise<vscode.AuthenticationSession> {
try {
// For the Gitpod scope list, order doesn't matter so we immediately sort the scopes
const sortedScopes = scopes.sort();

this._telemetry.sendTelemetryEvent('gitpod_desktop_auth', {
kind: 'login',
scopes: JSON.stringify(sortedScopes),
});

const scopeString = sortedScopes.join(' ');
const token = await this._gitpodServer.login(scopeString);
const session = await this.tokenToSession(token, sortedScopes);

const sessions = await this._sessionsPromise;
const sessionIndex = sessions.findIndex(s => s.id === session.id || arrayEquals([...s.scopes].sort(), sortedScopes));
if (sessionIndex > -1) {
sessions.splice(sessionIndex, 1, session);
} else {
sessions.push(session);
}
await this.storeSessions(sessions);

this._sessionChangeEmitter.fire({ added: [session], removed: [], changed: [] });

this._logger.info('Login success!');

return session;
} catch (e) {
// If login was cancelled, do not notify user.
if (e === 'Cancelled' || e.message === 'Cancelled') {
this._telemetry.sendTelemetryEvent('gitpod_desktop_auth', { kind: 'login_cancelled' });
throw e;
}

this._telemetry.sendTelemetryEvent('gitpod_desktop_auth', { kind: 'login_failed' });

vscode.window.showErrorMessage(`Sign in failed: ${e}`);
this._logger.error(e);
throw e;
}
}

private async tokenToSession(token: string, scopes: string[]): Promise<vscode.AuthenticationSession> {
const userInfo = await this._gitpodServer.getUserInfo(token);
return {
id: uuid(),
accessToken: token,
account: { label: userInfo.accountName, id: userInfo.id },
scopes
};
}

public async removeSession(id: string) {
try {
this._telemetry.sendTelemetryEvent('gitpod_desktop_auth', { kind: 'logout' });

this._logger.info(`Logging out of ${id}`);

const sessions = await this._sessionsPromise;
const sessionIndex = sessions.findIndex(session => session.id === id);
if (sessionIndex > -1) {
const session = sessions[sessionIndex];
sessions.splice(sessionIndex, 1);

await this.storeSessions(sessions);

this._sessionChangeEmitter.fire({ added: [], removed: [session], changed: [] });
} else {
this._logger.error('Session not found');
}
} catch (e) {
this._telemetry.sendTelemetryEvent('gitpod_desktop_auth', { kind: 'logout_failed' });

vscode.window.showErrorMessage(`Sign out failed: ${e}`);
this._logger.error(e);
throw e;
}
}

public handleUri(uri: vscode.Uri) {
this._gitpodServer.hadleUri(uri);
}

public override dispose() {
super.dispose();
this._gitpodServer.dispose();
}
}
41 changes: 41 additions & 0 deletions extensions/gitpod/src/common/dispose.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Gitpod. All rights reserved.
*--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';

export function disposeAll(disposables: vscode.Disposable[]): void {
while (disposables.length) {
const item = disposables.pop();
if (item) {
item.dispose();
}
}
}

export abstract class Disposable {
private _isDisposed = false;

protected _disposables: vscode.Disposable[] = [];

public dispose(): any {
if (this._isDisposed) {
return;
}
this._isDisposed = true;
disposeAll(this._disposables);
}

protected _register<T extends vscode.Disposable>(value: T): T {
if (this._isDisposed) {
value.dispose();
} else {
this._disposables.push(value);
}
return value;
}

protected get isDisposed(): boolean {
return this._isDisposed;
}
}
Loading