Skip to content

Commit

Permalink
Add tests for process-session-cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
danielnaab committed Aug 5, 2024
1 parent b55903f commit 3f6ee77
Show file tree
Hide file tree
Showing 5 changed files with 144 additions and 17 deletions.
22 changes: 16 additions & 6 deletions packages/auth/src/context/test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Cookie, Lucia } from 'lucia';
import { vi } from 'vitest';

import {
type TestDatabaseContext,
Expand All @@ -9,7 +10,18 @@ import { type AuthContext, type UserSession } from '..';
import { createTestLuciaAdapter } from '../lucia';
import { LoginGov } from '../provider';

export const createTestAuthContext = async () => {
type Options = {
getCookie: (name: string) => string | undefined;
setCookie: (cookie: Cookie) => void;
setUserSession: (userSession: UserSession) => void;
};

export const createTestAuthContext = async (opts?: Partial<Options>) => {
const options: Options = {
getCookie: opts?.getCookie || vi.fn(),
setCookie: opts?.setCookie || vi.fn(),
setUserSession: opts?.setUserSession || vi.fn(),
};
const database = await createTestDatabaseContext();
return new TestAuthContext(
database,
Expand All @@ -20,11 +32,9 @@ export const createTestAuthContext = async () => {
clientSecret: 'super-secret',
redirectURI: 'http://www.10x.gov/a2j/signin/callback',
}),
function getCookie(name) {
return '';
},
function setCookie(cookie) {},
function setUserSession({ user, session }) {}
options.getCookie,
options.setCookie,
options.setUserSession
);
};

Expand Down
134 changes: 126 additions & 8 deletions packages/auth/src/services/process-session-cookie.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,135 @@
import { randomUUID } from 'crypto';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { createUser } from '@atj/database';
import { createSession, createUser } from '@atj/database';

import { processProviderCallback } from './process-provider-callback';
import { createTestAuthContext } from '../context/test';
import { AuthContext } from '..';
import { processSessionCookie } from './process-session-cookie';

describe('processSessionCookie', () => {
let ctx: AuthContext;
const today = new Date(2020, 1, 1);
const tenYearsAgo = new Date(2010, 1, 1);

it('works', async () => {
const ctx = await createTestAuthContext();
//processSessionCookie()
expect(true).toBe(true);
beforeEach(async () => {
vi.setSystemTime(today);
});

it('sets null user session with unset session cookie', async () => {
const mocks = {
getCookie: vi.fn(() => undefined),
setUserSession: vi.fn(),
};
const ctx = await createTestAuthContext(mocks);

const result = await processSessionCookie(
ctx,
new Request('http://localhost', {
headers: { Origin: 'http://localhost', Host: 'http://www.google.com' },
})
);

expect(result.success).toEqual(true);
expect(mocks.setUserSession).toHaveBeenCalledWith({
session: null,
user: null,
});
});

it('resets session cookie and sets user session with fresh session cookie', async () => {
const { ctx, mocks, sessionId, user } = await setUpTest(today);

const result = await processSessionCookie(
ctx,
new Request('http://localhost', {
headers: { Origin: 'http://localhost', Host: 'http://www.google.com' },
})
);

expect(result.success).toEqual(true);
expect(mocks.setCookie).toHaveBeenCalledWith(
expect.objectContaining({
attributes: {
httpOnly: true,
maxAge: 2592000,
path: '/',
sameSite: 'lax',
secure: false,
},
name: 'auth_session',
value: sessionId,
})
);
expect(mocks.setUserSession).toHaveBeenCalledWith(
expect.objectContaining({
session: {
expiresAt: expect.any(Date),
fresh: true,
id: sessionId,
userId: user.id,
},
user: {
email: '[email protected]',
id: user.id,
},
})
);
});

it('clears cookies with stale session cookie', async () => {
const { ctx, mocks } = await setUpTest(tenYearsAgo);

const result = await processSessionCookie(
ctx,
new Request('http://localhost', {
headers: { Origin: 'http://localhost', Host: 'http://www.google.com' },
})
);

expect(result.success).toEqual(true);
expect(mocks.setCookie).toHaveBeenCalledWith(
expect.objectContaining({
attributes: {
httpOnly: true,
maxAge: 0,
path: '/',
sameSite: 'lax',
secure: false,
},
name: 'auth_session',
value: '',
})
);
expect(mocks.setUserSession).toHaveBeenCalledWith(
expect.objectContaining({
session: null,
user: null,
})
);
});
});

const addOneDay = (date: Date): Date => {
const newDate = new Date(date);
newDate.setDate(newDate.getDate() + 1);
return newDate;
};

const setUpTest = async (sessionExpirationDate: Date) => {
const mocks = {
getCookie: vi.fn(() => sessionId || ''),
setCookie: vi.fn(),
setUserSession: vi.fn(),
};
const ctx = await createTestAuthContext(mocks);
const user = await createUser(ctx.database, '[email protected]');
if (!user) {
expect.fail('error creating test user');
}
const sessionId = await createSession(ctx.database, {
id: randomUUID(),
expiresAt: addOneDay(sessionExpirationDate),
sessionToken: 'my-token',
userId: user.id,
});
return { ctx, mocks, sessionId, user };
};
1 change: 0 additions & 1 deletion packages/auth/src/services/process-session-cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ export const processSessionCookie = async (
};
}
}

const lucia = await ctx.getLucia();

const sessionId = ctx.getCookie(lucia.sessionCookieName);
Expand Down
2 changes: 1 addition & 1 deletion packages/auth/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { defineConfig, defineProject, mergeConfig } from 'vitest/config';
import { defineConfig, mergeConfig } from 'vitest/config';

import sharedTestConfig from '../../vitest.shared';

Expand Down
2 changes: 1 addition & 1 deletion vitest.shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default {
: ['default', 'html'],
*/
coverage: {
enabled: true,
enabled: false,
reporter: ['html', 'text', 'text-summary'],
reportOnFailure: true,
},
Expand Down

0 comments on commit 3f6ee77

Please sign in to comment.