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

misc: send usernames to APM #593

Merged
merged 1 commit into from
Dec 18, 2024
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
11 changes: 7 additions & 4 deletions src/lib/http/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ const logger = scopedLogger('auth');
const TOKEN_TTL = 2 * 60 * 1000;

export type Token = {
user_created?: string,
user_created: string | null,
user_github_username: string | null,
value: string,
expire: Date | null,
scopes: string[],
Expand Down Expand Up @@ -85,8 +86,10 @@ export class Auth {
}

async fetchTokens (filter: Partial<Row> = {}) {
const rows = await this.sql(GP_TOKENS_TABLE).where(filter)
.select<Row[]>([ 'user_created', 'value', 'expire', 'origins', 'date_last_used', 'scopes' ]);
const rows = await this.sql(GP_TOKENS_TABLE)
.leftJoin(USERS_TABLE, 'user_created', `${USERS_TABLE}.id`)
.where(filter)
.select<Row[]>([ 'user_created', 'value', 'expire', 'origins', 'date_last_used', 'scopes', 'github_username as user_github_username' ]);

const tokens: Token[] = rows.map(row => ({
...row,
Expand Down Expand Up @@ -127,7 +130,7 @@ export class Auth {
}

await this.updateLastUsedDate(token);
return { userId: token.user_created, scopes: token.scopes, hashedToken: token.value };
return { userId: token.user_created, username: token.user_github_username, scopes: token.scopes, hashedToken: token.value };
}

private async updateLastUsedDate (token: Token) {
Expand Down
11 changes: 6 additions & 5 deletions src/lib/http/middleware/authenticate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type SessionCookiePayload = {
role?: string;
app_access?: number;
admin_access?: number;
github_username?: string;
};

export const authenticate = (): ExtendedMiddleware => {
Expand All @@ -38,15 +39,15 @@ export const authenticate = (): ExtendedMiddleware => {
return;
}

ctx.state.user = { id: result.userId, scopes: result.scopes, authMode: 'token', hashedToken: result.hashedToken };
apmAgent.setUserContext({ id: result.userId || 'anonymous-token' });
ctx.state.user = { id: result.userId, username: result.username, scopes: result.scopes, authMode: 'token', hashedToken: result.hashedToken };
apmAgent.setUserContext({ id: result.userId || 'anonymous-token', username: result.username || 'anonymous-token' });
} else if (sessionCookie) {
try {
const result = await jwtVerify<SessionCookiePayload>(sessionCookie, sessionKey);

if (result.payload.id && result.payload.app_access) {
ctx.state.user = { id: result.payload.id, authMode: 'cookie' };
apmAgent.setUserContext({ id: result.payload.id });
ctx.state.user = { id: result.payload.id, username: result.payload.github_username || null, authMode: 'cookie' };
apmAgent.setUserContext({ id: result.payload.id, username: result.payload.github_username || `ID(${result.payload.id})` });
}
} catch {}
}
Expand All @@ -56,4 +57,4 @@ export const authenticate = (): ExtendedMiddleware => {
};

export type AuthenticateOptions = { session: { cookieName: string, cookieSecret: string } };
export type AuthenticateState = { user?: { id: string | undefined, scopes?: string[], hashedToken?: string, authMode: 'cookie' | 'token' } };
export type AuthenticateState = { user?: { id: string | null, username: string | null, scopes?: string[], hashedToken?: string, authMode: 'cookie' | 'token' } };
17 changes: 17 additions & 0 deletions test/tests/unit/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,14 @@ describe('Auth', () => {
update: updateStub,
select: selectStub,
});
const leftJoinStub = sandbox.stub().returns({
where: whereStub,
update: updateStub,
select: selectStub,
});
const sqlStub = sandbox.stub().returns({
where: whereStub,
leftJoin: leftJoinStub,
}) as sinon.SinonStub<any[], any> & {raw: any};

beforeEach(() => {
Expand All @@ -29,6 +35,7 @@ describe('Auth', () => {
selectStub.onCall(1).resolves([{
value: '/bSluuDrAPX9zIiZZ/hxEKARwOg+e//EdJgCFpmApbg=',
user_created: 'user1',
user_github_username: 'gh_user1',
}]);

selectStub.onCall(2).resolves([]);
Expand All @@ -39,16 +46,19 @@ describe('Auth', () => {
const user1 = await auth.validate('hf2fnprguymlgliirdk7qv23664c2xcr', 'https://jsdelivr.com');
expect(user1).to.deep.equal({
userId: 'user1',
username: 'gh_user1',
scopes: [],
hashedToken: '/bSluuDrAPX9zIiZZ/hxEKARwOg+e//EdJgCFpmApbg=',
});

const user2 = await auth.validate('vumzijbzihrskmc2hj34yw22batpibmt', 'https://jsdelivr.com');
expect(user2).to.equal(null);

// should work without a username too
selectStub.onCall(3).resolves([{
value: '8YZ2pZoGQxfOeEGvUUkagX1yizZckq3weL+IN0chvU0=',
user_created: 'user2',
user_github_username: null,
}]);

selectStub.onCall(4).resolves([]);
Expand All @@ -60,6 +70,7 @@ describe('Auth', () => {
const user2afterSync = await auth.validate('vumzijbzihrskmc2hj34yw22batpibmt', 'https://jsdelivr.com');
expect(user2afterSync).to.deep.equal({
userId: 'user2',
username: null,
scopes: [],
hashedToken: '8YZ2pZoGQxfOeEGvUUkagX1yizZckq3weL+IN0chvU0=',
});
Expand All @@ -73,6 +84,7 @@ describe('Auth', () => {
selectStub.resolves([{
value: '/bSluuDrAPX9zIiZZ/hxEKARwOg+e//EdJgCFpmApbg=',
user_created: 'user1',
user_github_username: 'gh_user1',
}]);

await auth.syncTokens();
Expand All @@ -84,6 +96,7 @@ describe('Auth', () => {

expect(user).to.deep.equal({
userId: 'user1',
username: 'gh_user1',
scopes: [],
hashedToken: '/bSluuDrAPX9zIiZZ/hxEKARwOg+e//EdJgCFpmApbg=',
});
Expand All @@ -97,6 +110,7 @@ describe('Auth', () => {
selectStub.resolves([{
value: '/bSluuDrAPX9zIiZZ/hxEKARwOg+e//EdJgCFpmApbg=',
user_created: 'user1',
user_github_username: 'gh_user1',
}]);

const user = await auth.validate('hf2fnprguymlgliirdk7qv23664c2xcr', 'https://jsdelivr.com');
Expand All @@ -106,6 +120,7 @@ describe('Auth', () => {

expect(user).to.deep.equal({
userId: 'user1',
username: 'gh_user1',
scopes: [],
hashedToken: '/bSluuDrAPX9zIiZZ/hxEKARwOg+e//EdJgCFpmApbg=',
});
Expand All @@ -119,6 +134,7 @@ describe('Auth', () => {
selectStub.resolves([{
value: '/bSluuDrAPX9zIiZZ/hxEKARwOg+e//EdJgCFpmApbg=',
user_created: 'user1',
user_github_username: 'gh_user1',
date_last_used: new Date(),
}]);

Expand All @@ -136,6 +152,7 @@ describe('Auth', () => {
selectStub.resolves([{
value: '/bSluuDrAPX9zIiZZ/hxEKARwOg+e//EdJgCFpmApbg=',
user_created: 'user1',
user_github_username: 'gh_user1',
}]);

await auth.validate('hf2fnprguymlgliirdk7qv23664c2xcr', 'https://jsdelivr.com');
Expand Down
Loading