-
Notifications
You must be signed in to change notification settings - Fork 1.3k
[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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
132 changes: 132 additions & 0 deletions
132
components/server/src/user/gitpod-token-service.spec.db.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.