Skip to content

[fga] Introduce GitpodTokenService #18502

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

Merged
merged 1 commit into from
Aug 16, 2023
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
10 changes: 9 additions & 1 deletion components/server/src/authorization/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,15 @@ export type UserResourceType = "user";

export type UserRelation = "self" | "organization" | "installation";

export type UserPermission = "read_info" | "write_info" | "delete" | "make_admin" | "read_ssh" | "write_ssh";
export type UserPermission =
| "read_info"
| "write_info"
| "delete"
| "make_admin"
| "read_ssh"
| "write_ssh"
| "read_tokens"
| "write_tokens";

export type InstallationResourceType = "installation";

Expand Down
2 changes: 2 additions & 0 deletions components/server/src/container-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ import { UserService } from "./user/user-service";
import { RelationshipUpdater } from "./authorization/relationship-updater";
import { WorkspaceService } from "./workspace/workspace-service";
import { SSHKeyService } from "./user/sshkey-service";
import { GitpodTokenService } from "./user/gitpod-token-service";

export const productionContainerModule = new ContainerModule(
(bind, unbind, isBound, rebind, unbindAsync, onActivation, onDeactivation) => {
Expand All @@ -145,6 +146,7 @@ export const productionContainerModule = new ContainerModule(
bind(AuthorizationService).to(AuthorizationServiceImpl).inSingletonScope();

bind(SSHKeyService).toSelf().inSingletonScope();
bind(GitpodTokenService).toSelf().inSingletonScope();

bind(TokenService).toSelf().inSingletonScope();
bind(TokenProvider).toService(TokenService);
Expand Down
132 changes: 132 additions & 0 deletions components/server/src/user/gitpod-token-service.spec.db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/**
* Copyright (c) 2023 Gitpod GmbH. All rights reserved.
* Licensed under the GNU Affero General Public License (AGPL).
* See License.AGPL.txt in the project root for license information.
*/

import { BUILTIN_INSTLLATION_ADMIN_USER_ID, TypeORM } from "@gitpod/gitpod-db/lib";
import { GitpodTokenType, Organization, User } from "@gitpod/gitpod-protocol";
import { Experiments } from "@gitpod/gitpod-protocol/lib/experiments/configcat-server";
import * as chai from "chai";
import { Container } from "inversify";
import "mocha";
import { createTestContainer } from "../test/service-testing-container-module";
import { resetDB } from "@gitpod/gitpod-db/lib/test/reset-db";
import { OrganizationService } from "../orgs/organization-service";
import { UserService } from "./user-service";
import { expectError } from "../test/expect-utils";
import { ErrorCodes } from "@gitpod/gitpod-protocol/lib/messaging/error";
import { GitpodTokenService } from "./gitpod-token-service";

const expect = chai.expect;

describe("GitpodTokenService", async () => {
let container: Container;
let gs: GitpodTokenService;

let member: User;
let stranger: User;
let org: Organization;

beforeEach(async () => {
container = createTestContainer();
Experiments.configureTestingClient({
centralizedPermissions: true,
});

const orgService = container.get<OrganizationService>(OrganizationService);
org = await orgService.createOrganization(BUILTIN_INSTLLATION_ADMIN_USER_ID, "myOrg");
const invite = await orgService.getOrCreateInvite(BUILTIN_INSTLLATION_ADMIN_USER_ID, org.id);

const userService = container.get<UserService>(UserService);
member = await userService.createUser({
organizationId: org.id,
identity: {
authId: "foo",
authName: "bar",
authProviderId: "github",
primaryEmail: "[email protected]",
},
});
await orgService.joinOrganization(member.id, invite.id);
stranger = await userService.createUser({
identity: {
authId: "foo2",
authName: "bar2",
authProviderId: "github",
},
});

gs = container.get(GitpodTokenService);
});

afterEach(async () => {
// Clean-up database
await resetDB(container.get(TypeORM));
});

it("should generate a new gitpod token", async () => {
const resp1 = await gs.getGitpodTokens(member.id, member.id);
expect(resp1.length).to.equal(0);

await gs.generateNewGitpodToken(member.id, member.id, { name: "token1", type: GitpodTokenType.API_AUTH_TOKEN });

const resp2 = await gs.getGitpodTokens(member.id, member.id);
expect(resp2.length).to.equal(1);

await expectError(ErrorCodes.NOT_FOUND, gs.getGitpodTokens(stranger.id, member.id));
await expectError(
ErrorCodes.NOT_FOUND,
gs.generateNewGitpodToken(stranger.id, member.id, { name: "token2", type: GitpodTokenType.API_AUTH_TOKEN }),
);
});

it("should list gitpod tokens", async () => {
await gs.generateNewGitpodToken(member.id, member.id, { name: "token1", type: GitpodTokenType.API_AUTH_TOKEN });
await gs.generateNewGitpodToken(member.id, member.id, { name: "token2", type: GitpodTokenType.API_AUTH_TOKEN });

const tokens = await gs.getGitpodTokens(member.id, member.id);
expect(tokens.length).to.equal(2);
expect(tokens.some((t) => t.name === "token1")).to.be.true;
expect(tokens.some((t) => t.name === "token2")).to.be.true;

await expectError(ErrorCodes.NOT_FOUND, gs.getGitpodTokens(stranger.id, member.id));
});

it("should return gitpod token", async () => {
await gs.generateNewGitpodToken(member.id, member.id, {
name: "token1",
type: GitpodTokenType.API_AUTH_TOKEN,
scopes: ["user:email", "read:user"],
});

const tokens = await gs.getGitpodTokens(member.id, member.id);
expect(tokens.length).to.equal(1);

const token = await gs.findGitpodToken(member.id, member.id, tokens[0].tokenHash);
expect(token).to.not.be.undefined;

await expectError(ErrorCodes.NOT_FOUND, gs.findGitpodToken(stranger.id, member.id, tokens[0].tokenHash));
});

it("should delete gitpod tokens", async () => {
await gs.generateNewGitpodToken(member.id, member.id, {
name: "token1",
type: GitpodTokenType.API_AUTH_TOKEN,
});
await gs.generateNewGitpodToken(member.id, member.id, {
name: "token2",
type: GitpodTokenType.API_AUTH_TOKEN,
});

const tokens = await gs.getGitpodTokens(member.id, member.id);
expect(tokens.length).to.equal(2);

await gs.deleteGitpodToken(member.id, member.id, tokens[0].tokenHash);

const tokens2 = await gs.getGitpodTokens(member.id, member.id);
expect(tokens2.length).to.equal(1);

await expectError(ErrorCodes.NOT_FOUND, gs.deleteGitpodToken(stranger.id, member.id, tokens[1].tokenHash));
});
});
82 changes: 82 additions & 0 deletions components/server/src/user/gitpod-token-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/**
* Copyright (c) 2023 Gitpod GmbH. All rights reserved.
* Licensed under the GNU Affero General Public License (AGPL).
* See License.AGPL.txt in the project root for license information.
*/

import * as crypto from "crypto";
import { DBGitpodToken, UserDB } from "@gitpod/gitpod-db/lib";
import { GitpodToken, GitpodTokenType } from "@gitpod/gitpod-protocol";
import { log } from "@gitpod/gitpod-protocol/lib/util/logging";
import { inject, injectable } from "inversify";
import { Authorizer } from "../authorization/authorizer";

@injectable()
export class GitpodTokenService {
constructor(
@inject(UserDB) private readonly userDB: UserDB,
@inject(Authorizer) private readonly auth: Authorizer,
) {}

async getGitpodTokens(requestorId: string, userId: string): Promise<GitpodToken[]> {
await this.auth.checkPermissionOnUser(requestorId, "read_tokens", userId);
const gitpodTokens = await this.userDB.findAllGitpodTokensOfUser(userId);
return gitpodTokens.filter((v) => !v.deleted);
}

async generateNewGitpodToken(
requestorId: string,
userId: string,
options: { name?: string; type: GitpodTokenType; scopes?: string[] },
oldPermissionCheck?: (dbToken: DBGitpodToken) => Promise<void>, // @deprecated
): Promise<string> {
await this.auth.checkPermissionOnUser(requestorId, "write_tokens", userId);
const token = crypto.randomBytes(30).toString("hex");
const tokenHash = crypto.createHash("sha256").update(token, "utf8").digest("hex");
const dbToken: DBGitpodToken = {
tokenHash,
name: options.name,
type: options.type,
userId,
scopes: options.scopes || [],
created: new Date().toISOString(),
};
if (oldPermissionCheck) {
await oldPermissionCheck(dbToken);
}
await this.userDB.storeGitpodToken(dbToken);
return token;
}

async findGitpodToken(requestorId: string, userId: string, tokenHash: string): Promise<GitpodToken | undefined> {
await this.auth.checkPermissionOnUser(requestorId, "read_tokens", userId);
let token: GitpodToken | undefined;
try {
token = await this.userDB.findGitpodTokensOfUser(userId, tokenHash);
} catch (error) {
log.error({ userId }, "failed to resolve gitpod token: ", error);
}
if (token?.deleted) {
token = undefined;
}
return token;
}

async deleteGitpodToken(
requestorId: string,
userId: string,
tokenHash: string,
oldPermissionCheck?: (token: GitpodToken) => Promise<void>, // @deprecated
): Promise<void> {
await this.auth.checkPermissionOnUser(requestorId, "write_tokens", userId);
const existingTokens = await this.getGitpodTokens(requestorId, userId);
const tkn = existingTokens.find((token) => token.tokenHash === tokenHash);
if (!tkn) {
throw new Error(`User ${requestorId} tries to delete a token ${tokenHash} that does not exist.`);
}
if (oldPermissionCheck) {
await oldPermissionCheck(tkn);
}
await this.userDB.deleteGitpodToken(tokenHash);
}
}
53 changes: 16 additions & 37 deletions components/server/src/workspace/gitpod-server-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import {
WorkspaceDB,
DBWithTracing,
TracedWorkspaceDB,
DBGitpodToken,
EmailDomainFilterDB,
TeamDB,
RedisPublisher,
DBGitpodToken,
} from "@gitpod/gitpod-db/lib";
import { BlockedRepositoryDB } from "@gitpod/gitpod-db/lib/blocked-repository-db";
import {
Expand Down Expand Up @@ -112,7 +112,6 @@ import {
StopWorkspacePolicy,
TakeSnapshotRequest,
} from "@gitpod/ws-manager/lib/core_pb";
import * as crypto from "crypto";
import { inject, injectable } from "inversify";
import { URL } from "url";
import { v4 as uuidv4, validate as uuidValidate } from "uuid";
Expand Down Expand Up @@ -192,6 +191,7 @@ import { UsageService } from "../orgs/usage-service";
import { UserService } from "../user/user-service";
import { SSHKeyService } from "../user/sshkey-service";
import { StartWorkspaceOptions, WorkspaceService } from "./workspace-service";
import { GitpodTokenService } from "../user/gitpod-token-service";

// shortcut
export const traceWI = (ctx: TraceContext, wi: Omit<LogContext, "userId">) => TraceContext.setOWI(ctx, wi); // userId is already taken care of in WebsocketConnectionManager
Expand Down Expand Up @@ -234,6 +234,7 @@ export class GitpodServerImpl implements GitpodServerWithTracing, Disposable {
@inject(IAnalyticsWriter) private readonly analytics: IAnalyticsWriter,
@inject(AuthorizationService) private readonly authorizationService: AuthorizationService,
@inject(SSHKeyService) private readonly sshKeyservice: SSHKeyService,
@inject(GitpodTokenService) private readonly gitpodTokenService: GitpodTokenService,

@inject(TeamDB) private readonly teamDB: TeamDB,
@inject(OrganizationService) private readonly organizationService: OrganizationService,
Expand Down Expand Up @@ -2892,9 +2893,9 @@ export class GitpodServerImpl implements GitpodServerWithTracing, Disposable {

public async getGitpodTokens(ctx: TraceContext): Promise<GitpodToken[]> {
const user = await this.checkAndBlockUser("getGitpodTokens");
const res = (await this.userDB.findAllGitpodTokensOfUser(user.id)).filter((v) => !v.deleted);
await Promise.all(res.map((tkn) => this.guardAccess({ kind: "gitpodToken", subject: tkn }, "get")));
return res;
const gitpodTokens = await this.gitpodTokenService.getGitpodTokens(user.id, user.id);
await Promise.all(gitpodTokens.map((tkn) => this.guardAccess({ kind: "gitpodToken", subject: tkn }, "get")));
return gitpodTokens;
}

public async generateNewGitpodToken(
Expand All @@ -2904,51 +2905,29 @@ export class GitpodServerImpl implements GitpodServerWithTracing, Disposable {
traceAPIParams(ctx, { options });

const user = await this.checkAndBlockUser("generateNewGitpodToken");
const token = crypto.randomBytes(30).toString("hex");
const tokenHash = crypto.createHash("sha256").update(token, "utf8").digest("hex");
const dbToken: DBGitpodToken = {
tokenHash,
name: options.name,
type: options.type,
userId: user.id,
scopes: options.scopes || [],
created: new Date().toISOString(),
};
await this.guardAccess({ kind: "gitpodToken", subject: dbToken }, "create");

await this.userDB.storeGitpodToken(dbToken);
return token;
return this.gitpodTokenService.generateNewGitpodToken(user.id, user.id, options, (dbToken: DBGitpodToken) => {
return this.guardAccess({ kind: "gitpodToken", subject: dbToken }, "create");
});
}

public async getGitpodTokenScopes(ctx: TraceContext, tokenHash: string): Promise<string[]> {
traceAPIParams(ctx, {}); // do not trace tokenHash

const user = await this.checkAndBlockUser("getGitpodTokenScopes");
let token: GitpodToken | undefined;
try {
token = await this.userDB.findGitpodTokensOfUser(user.id, tokenHash);
} catch (error) {
log.error({ userId: user.id }, "failed to resolve gitpod token: ", error);
return [];
const gitpodToken = await this.gitpodTokenService.findGitpodToken(user.id, user.id, tokenHash);
if (gitpodToken) {
await this.guardAccess({ kind: "gitpodToken", subject: gitpodToken }, "get");
}
if (!token || token.deleted) {
return [];
}
await this.guardAccess({ kind: "gitpodToken", subject: token }, "get");
return token.scopes;
return gitpodToken?.scopes ?? [];
}

public async deleteGitpodToken(ctx: TraceContext, tokenHash: string): Promise<void> {
traceAPIParams(ctx, {}); // do not trace tokenHash

const user = await this.checkAndBlockUser("deleteGitpodToken");
const existingTokens = await this.getGitpodTokens(ctx); // all tokens for logged in user
const tkn = existingTokens.find((token) => token.tokenHash === tokenHash);
if (!tkn) {
throw new Error(`User ${user.id} tries to delete a token ${tokenHash} that does not exist.`);
}
await this.guardAccess({ kind: "gitpodToken", subject: tkn }, "delete");
return this.userDB.deleteGitpodToken(tokenHash);
return this.gitpodTokenService.deleteGitpodToken(user.id, user.id, tokenHash, (token: GitpodToken) => {
return this.guardAccess({ kind: "gitpodToken", subject: token }, "delete");
});
}

async guessGitTokenScopes(ctx: TraceContext, params: GuessGitTokenScopesParams): Promise<GuessedGitTokenScopes> {
Expand Down
3 changes: 3 additions & 0 deletions components/spicedb/schema/schema.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ schema: |-

permission read_ssh = self
permission write_ssh = self

permission read_tokens = self
permission write_tokens = self
}

// There's only one global installation
Expand Down