Skip to content

Commit e9f13a8

Browse files
committed
[auth] Add tests for BearerAuth.tryAuthFromHeaders
1 parent cebc8ff commit e9f13a8

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

components/server/src/auth/bearer-authenticator.spec.db.ts

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { Request } from "express";
1818
import { WithResourceAccessGuard } from "./resource-access";
1919
import { WithFunctionAccessGuard } from "./function-access";
2020
import { fail } from "assert";
21+
import { SubjectId } from "./subject-id";
2122

2223
function toDateTime(date: Date): string {
2324
return date.toISOString().replace("T", " ").replace("Z", "");
@@ -62,7 +63,7 @@ describe("BearerAuth", () => {
6263
testUser = await userService.createUser({
6364
identity: {
6465
authId: "gh-user-1",
65-
authName: "user",
66+
authName: "testUser",
6667
authProviderId: "public-github",
6768
},
6869
});
@@ -110,6 +111,35 @@ describe("BearerAuth", () => {
110111
await expectError(async () => bearerAuth.authExpressRequest(req), "cannot find token");
111112
});
112113

114+
it("tryAuthFromHeaders should successfully authenticate BearerToken (PAT)", async () => {
115+
const pat1 = await insertPat(testUser.id, "pat-1");
116+
117+
const headers = {
118+
authorization: `Bearer ${pat1}`,
119+
};
120+
const subjectId = await bearerAuth.tryAuthFromHeaders(headers);
121+
122+
expect(subjectId?.toString()).to.equal(SubjectId.fromUserId(testUser.id).toString());
123+
});
124+
125+
it("tryAuthFromHeaders should return undefined with missing BearerToken in header", async () => {
126+
await insertPat(testUser.id, "pat-1");
127+
128+
const headers = {
129+
authorization: `Bearer `, // missing
130+
};
131+
expect(await bearerAuth.tryAuthFromHeaders(headers)).to.be.undefined;
132+
});
133+
134+
it("tryAuthFromHeaders should fail to authenticate with missing BearerToken from DB (PAT)", async () => {
135+
const patNotStored = "gitpod_pat_GrvGthczSRf3ypqFhNtcRiN5fK6CV7rdCkkPLfpbc_4";
136+
137+
const headers = {
138+
authorization: `Bearer ${patNotStored}`,
139+
};
140+
await expectError(async () => bearerAuth.tryAuthFromHeaders(headers), "cannot find token");
141+
});
142+
113143
async function expectError(fun: () => Promise<any>, message: string) {
114144
try {
115145
await fun();

0 commit comments

Comments
 (0)