-
Notifications
You must be signed in to change notification settings - Fork 1.3k
[gRPC] Enable PATs to be used for authorizing with the gRPC API #19081
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
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
146 changes: 146 additions & 0 deletions
146
components/server/src/auth/bearer-authenticator.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,146 @@ | ||
/** | ||
* Copyright (c) 2022 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 { TypeORM, resetDB } from "@gitpod/gitpod-db/lib"; | ||
import { BearerAuth, PersonalAccessToken } from "./bearer-authenticator"; | ||
import { expect } from "chai"; | ||
import { describe } from "mocha"; | ||
import { Container } from "inversify"; | ||
import { createTestContainer } from "../test/service-testing-container-module"; | ||
import { Experiments } from "@gitpod/gitpod-protocol/lib/experiments/configcat-server"; | ||
import { UserService } from "../user/user-service"; | ||
import { User } from "@gitpod/gitpod-protocol"; | ||
import { Config } from "../config"; | ||
import { Request } from "express"; | ||
import { WithResourceAccessGuard } from "./resource-access"; | ||
import { WithFunctionAccessGuard } from "./function-access"; | ||
import { fail } from "assert"; | ||
import { SubjectId } from "./subject-id"; | ||
|
||
function toDateTime(date: Date): string { | ||
return date.toISOString().replace("T", " ").replace("Z", ""); | ||
} | ||
|
||
describe("BearerAuth", () => { | ||
let container: Container; | ||
let bearerAuth: BearerAuth; | ||
let userService: UserService; | ||
let typeORM: TypeORM; | ||
let testUser: User; | ||
|
||
async function insertPat(userId: string, patId: string, scopes: string[] = ["function:*"]): Promise<string> { | ||
const patValue = "someValue"; | ||
const signature = "V7BsZVjpMQRaWxS5XJE9r-Ovpxk2xT_bfFSmic4yW6g"; // depends on the value | ||
const pat = new PersonalAccessToken("doesnotmatter", patValue); | ||
|
||
const conn = await typeORM.getConnection(); | ||
await conn.query( | ||
"INSERT d_b_personal_access_token (id, userId, hash, name, scopes, expirationTime, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?)", | ||
[patId, userId, pat.hash(), patId, scopes, toDateTime(new Date("2030")), toDateTime(new Date())], | ||
); | ||
return `gitpod_pat_${signature}.${patValue}`; | ||
} | ||
|
||
beforeEach(async () => { | ||
container = createTestContainer(); | ||
Experiments.configureTestingClient({ | ||
centralizedPermissions: true, | ||
}); | ||
const oldConfig = container.get<Config>(Config); | ||
container.rebind(Config).toDynamicValue((ctx) => { | ||
return { | ||
...oldConfig, | ||
patSigningKey: "super-duper-secret-pat-signing-key", | ||
}; | ||
}); | ||
bearerAuth = container.get(BearerAuth); | ||
userService = container.get<UserService>(UserService); | ||
typeORM = container.get<TypeORM>(TypeORM); | ||
|
||
testUser = await userService.createUser({ | ||
identity: { | ||
authId: "gh-user-1", | ||
authName: "testUser", | ||
authProviderId: "public-github", | ||
}, | ||
}); | ||
}); | ||
|
||
afterEach(async () => { | ||
// Clean-up database | ||
await resetDB(container.get(TypeORM)); | ||
}); | ||
|
||
it("authExpressRequest should successfully authenticate BearerToken (PAT)", async () => { | ||
const pat1 = await insertPat(testUser.id, "pat-1"); | ||
|
||
const req = { | ||
headers: { | ||
authorization: `Bearer ${pat1}`, | ||
}, | ||
} as Request; | ||
await bearerAuth.authExpressRequest(req); | ||
|
||
expect(req.user?.id).to.equal(testUser.id); | ||
expect((req as WithResourceAccessGuard).resourceGuard).to.not.be.undefined; | ||
expect((req as WithFunctionAccessGuard).functionGuard).to.not.be.undefined; | ||
}); | ||
|
||
it("authExpressRequest should fail to authenticate with missing BearerToken in header", async () => { | ||
await insertPat(testUser.id, "pat-1"); | ||
|
||
const req = { | ||
headers: { | ||
authorization: `Bearer `, // missing | ||
}, | ||
} as Request; | ||
await expectError(async () => bearerAuth.authExpressRequest(req), "missing bearer token header"); | ||
}); | ||
|
||
it("authExpressRequest should fail to authenticate with missing BearerToken from DB (PAT)", async () => { | ||
const patNotStored = "gitpod_pat_GrvGthczSRf3ypqFhNtcRiN5fK6CV7rdCkkPLfpbc_4"; | ||
|
||
const req = { | ||
headers: { | ||
authorization: `Bearer ${patNotStored}`, | ||
}, | ||
} as Request; | ||
await expectError(async () => bearerAuth.authExpressRequest(req), "cannot find token"); | ||
}); | ||
|
||
it("tryAuthFromHeaders should successfully authenticate BearerToken (PAT)", async () => { | ||
const pat1 = await insertPat(testUser.id, "pat-1"); | ||
|
||
const headers = new Headers(); | ||
headers.set("authorization", `Bearer ${pat1}`); | ||
const subjectId = await bearerAuth.tryAuthFromHeaders(headers); | ||
|
||
expect(subjectId?.toString()).to.equal(SubjectId.fromUserId(testUser.id).toString()); | ||
}); | ||
|
||
it("tryAuthFromHeaders should return undefined with missing BearerToken in header", async () => { | ||
await insertPat(testUser.id, "pat-1"); | ||
|
||
const headers = new Headers(); | ||
headers.set("authorization", `Bearer `); // missing | ||
expect(await bearerAuth.tryAuthFromHeaders(headers)).to.be.undefined; | ||
}); | ||
|
||
it("tryAuthFromHeaders should fail to authenticate with missing BearerToken from DB (PAT)", async () => { | ||
const patNotStored = "gitpod_pat_GrvGthczSRf3ypqFhNtcRiN5fK6CV7rdCkkPLfpbc_4"; | ||
|
||
const headers = new Headers(); | ||
headers.set("authorization", `Bearer ${patNotStored}`); | ||
await expectError(async () => bearerAuth.tryAuthFromHeaders(headers), "cannot find token"); | ||
}); | ||
|
||
async function expectError(fun: () => Promise<any>, message: string) { | ||
try { | ||
await fun(); | ||
fail(`Expected error: ${message}`); | ||
} catch (err) {} | ||
} | ||
}); |
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@geropl how can we test for a regression of this path manually? to use gitpod cli with PAT?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, exactly. Still works 😉