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

Add testing utility for generating session cookies [SDK-3569] #816

Merged
merged 5 commits into from
Sep 12, 2022
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
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
},
"files": [
"dist",
"src"
"src",
"testing.js",
"testing.d.ts"
],
"engines": {
"node": "^10.13.0 || >=12.0.0"
Expand Down
2 changes: 1 addition & 1 deletion src/auth0-session/cookie-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export default class CookieStore {
return this.keys;
}

private async encrypt(payload: jose.JWTPayload, { iat, uat, exp }: Header): Promise<string> {
public async encrypt(payload: jose.JWTPayload, { iat, uat, exp }: Header): Promise<string> {
const [key] = await this.getKeys();
return await new jose.EncryptJWT({ ...payload }).setProtectedHeader({ alg, enc, uat, iat, exp }).encrypt(key);
}
Expand Down
15 changes: 15 additions & 0 deletions src/helpers/testing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Config as BaseConfig, CookieStore } from '../auth0-session';
import { Session } from '../session';
import { GenerateSessionCookieConfig } from '../../testing';

export const generateSessionCookie = async (
session: Partial<Session>,
config: GenerateSessionCookieConfig
): Promise<string> => {
const weekInSeconds = 7 * 24 * 60 * 60;
const { secret, duration: absoluteDuration = weekInSeconds, ...cookie } = config;
const cookieStoreConfig = { secret, session: { absoluteDuration, cookie } };
const cookieStore = new CookieStore(cookieStoreConfig as BaseConfig);
const epoch = (Date.now() / 1000) | 0;
return cookieStore.encrypt(session, { iat: epoch, uat: epoch, exp: epoch + absoluteDuration });
};
39 changes: 39 additions & 0 deletions testing.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import type { CookieConfig } from './dist/config';
import type { Session } from './dist/session';

/**
* Configuration parameters used by ({@link generateSessionCookie}.
*/
export type GenerateSessionCookieConfig = {
/**
* The secret used to derive an encryption key for the session cookie.
*
* **IMPORTANT**: you must use the same value as in the SDK configuration.
* See {@link ConfigParameters.secret}.
*/
secret: string;

/**
* Integer value, in seconds, used as the duration of the session cookie.
* Defaults to `604800` seconds (7 days).
*/
duration?: number;
} & Partial<CookieConfig>;

/**
* Generates an encrypted session cookie that can be used to mock the Auth0
* authentication flow in e2e tests.
*
* **IMPORTANT**: this utility can only run on Node.js, **not on the browser**.
* For example, if you're using [Cypress](https://www.cypress.io/), you can
* wrap it in a [task](https://docs.cypress.io/api/commands/task) and then
* invoke the task from a test or a custom command.
*
* @param {Session} session The user's session.
* @param {GenerateSessionCookieConfig} config Configuration parameters for the session cookie.
* @return {String}
*/
export declare function generateSessionCookie(
session: Partial<Session>,
config: GenerateSessionCookieConfig
): Promise<string>;
1 change: 1 addition & 0 deletions testing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('./dist/helpers/testing');
79 changes: 79 additions & 0 deletions tests/helpers/testing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import CookieStore from '../../src/auth0-session/cookie-store';
import { generateSessionCookie } from '../../src/helpers/testing';

jest.mock('../../src/auth0-session/cookie-store');

const encryptMock = jest.spyOn(CookieStore.prototype, 'encrypt');
const weekInSeconds = 7 * 24 * 60 * 60;

describe('generate-session-cookie', () => {
test('use the provided secret', async () => {
await generateSessionCookie({}, { secret: '__test_secret__' });
expect(CookieStore).toHaveBeenCalledWith(expect.objectContaining({ secret: '__test_secret__' }));
});

test('use the default session configuration values', async () => {
await generateSessionCookie({}, { secret: '' });
expect(CookieStore).toHaveBeenCalledWith(
expect.objectContaining({
session: { absoluteDuration: weekInSeconds, cookie: {} }
})
);
});

test('use the provided session configuration values', async () => {
await generateSessionCookie(
{},
{
secret: '',
duration: 1000,
domain: '__test_domain__',
path: '__test_path__',
transient: true,
httpOnly: false,
secure: false,
sameSite: 'none'
}
);
expect(CookieStore).toHaveBeenCalledWith(
expect.objectContaining({
session: {
absoluteDuration: 1000,
cookie: {
domain: '__test_domain__',
path: '__test_path__',
transient: true,
httpOnly: false,
secure: false,
sameSite: 'none'
}
}
})
);
});

test('use the provided session', async () => {
await generateSessionCookie({ user: { foo: 'bar' } }, { secret: '' });
expect(encryptMock).toHaveBeenCalledWith({ user: { foo: 'bar' } }, expect.anything());
});

test('use the current time for the header values', async () => {
const now = Date.now();
const current = (now / 1000) | 0;
const clock = jest.useFakeTimers('modern');
clock.setSystemTime(now);
await generateSessionCookie({}, { secret: '' });
expect(encryptMock).toHaveBeenCalledWith(expect.anything(), {
iat: current,
uat: current,
exp: current + weekInSeconds
});
clock.restoreAllMocks();
jest.useRealTimers();
});

test('return the encrypted cookie', async () => {
encryptMock.mockResolvedValueOnce('foo');
expect(generateSessionCookie({}, { secret: '' })).resolves.toBe('foo');
});
});