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

Encode illegal characters inside cookies and change cookies parsing logic #46

Merged
merged 2 commits into from
Dec 5, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
59 changes: 33 additions & 26 deletions __tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import axios from 'axios';
jest.mock('axios');

import { Authenticator } from '../src/';
import { Cookies } from '../src/util/cookie';

const DATE = new Date('2017');
// @ts-ignore
Expand Down Expand Up @@ -61,11 +62,11 @@ describe('private functions', () => {
},
});
expect(response.headers['set-cookie']).toEqual(expect.arrayContaining([
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.accessToken=${tokenData.access_token}; Domain=${domain}; Expires=${DATE}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.refreshToken=${tokenData.refresh_token}; Domain=${domain}; Expires=${DATE}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.tokenScopesString=phone email profile openid aws.cognito.signin.user.admin; Domain=${domain}; Expires=${DATE}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.idToken=${tokenData.id_token}; Domain=${domain}; Expires=${DATE}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.LastAuthUser=${username}; Domain=${domain}; Expires=${DATE}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.accessToken=${tokenData.access_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.refreshToken=${tokenData.refresh_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.tokenScopesString=phone%20email%20profile%20openid%20aws.cognito.signin.user.admin; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.idToken=${tokenData.id_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.LastAuthUser=${username}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure`},
]));
expect(authenticator._jwtVerifier.verify).toHaveBeenCalled();
});
Expand All @@ -81,13 +82,13 @@ describe('private functions', () => {
logLevel: 'error',
});
authenticatorWithNoCookieDomain._jwtVerifier.cacheJwks(jwksData);

const username = 'toto';
const domain = 'example.com';
const path = '/test';
jest.spyOn(authenticatorWithNoCookieDomain._jwtVerifier, 'verify');
authenticatorWithNoCookieDomain._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({ token_use: 'id', 'cognito:username': username }));

const response = await authenticatorWithNoCookieDomain._getRedirectResponse(tokenData, domain, path);
expect(response).toMatchObject({
status: '302',
Expand All @@ -99,11 +100,11 @@ describe('private functions', () => {
},
});
expect(response.headers['set-cookie']).toEqual(expect.arrayContaining([
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.accessToken=${tokenData.access_token}; Expires=${DATE}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.refreshToken=${tokenData.refresh_token}; Expires=${DATE}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.tokenScopesString=phone email profile openid aws.cognito.signin.user.admin; Expires=${DATE}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.idToken=${tokenData.id_token}; Expires=${DATE}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.LastAuthUser=${username}; Expires=${DATE}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.accessToken=${tokenData.access_token}; Expires=${DATE.toUTCString()}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.refreshToken=${tokenData.refresh_token}; Expires=${DATE.toUTCString()}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.tokenScopesString=phone%20email%20profile%20openid%20aws.cognito.signin.user.admin; Expires=${DATE.toUTCString()}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.idToken=${tokenData.id_token}; Expires=${DATE.toUTCString()}; Secure`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.LastAuthUser=${username}; Expires=${DATE.toUTCString()}; Secure`},
]));
expect(authenticatorWithNoCookieDomain._jwtVerifier.verify).toHaveBeenCalled();
});
Expand All @@ -120,13 +121,13 @@ describe('private functions', () => {
logLevel: 'error',
});
authenticatorWithHttpOnly._jwtVerifier.cacheJwks(jwksData);

const username = 'toto';
const domain = 'example.com';
const path = '/test';
jest.spyOn(authenticatorWithHttpOnly._jwtVerifier, 'verify');
authenticatorWithHttpOnly._jwtVerifier.verify.mockReturnValueOnce(Promise.resolve({ token_use: 'id', 'cognito:username': username }));

const response = await authenticatorWithHttpOnly._getRedirectResponse(tokenData, domain, path);
expect(response).toMatchObject({
status: '302',
Expand All @@ -138,11 +139,11 @@ describe('private functions', () => {
},
});
expect(response.headers['set-cookie']).toEqual(expect.arrayContaining([
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.accessToken=${tokenData.access_token}; Domain=${domain}; Expires=${DATE}; Secure; HttpOnly`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.refreshToken=${tokenData.refresh_token}; Domain=${domain}; Expires=${DATE}; Secure; HttpOnly`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.tokenScopesString=phone email profile openid aws.cognito.signin.user.admin; Domain=${domain}; Expires=${DATE}; Secure; HttpOnly`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.idToken=${tokenData.id_token}; Domain=${domain}; Expires=${DATE}; Secure; HttpOnly`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.LastAuthUser=${username}; Domain=${domain}; Expires=${DATE}; Secure; HttpOnly`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.accessToken=${tokenData.access_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.refreshToken=${tokenData.refresh_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.tokenScopesString=phone%20email%20profile%20openid%20aws.cognito.signin.user.admin; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${username}.idToken=${tokenData.id_token}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`},
{key: 'Set-Cookie', value: `CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.LastAuthUser=${username}; Domain=${domain}; Expires=${DATE.toUTCString()}; Secure; HttpOnly`},
]));
expect(authenticatorWithHttpOnly._jwtVerifier.verify).toHaveBeenCalled();
});
Expand All @@ -152,21 +153,27 @@ describe('private functions', () => {
expect(
authenticator._getIdTokenFromCookie([{
key: 'Cookie',
value: `CognitoIdentityServiceProvider.5uka3k8840tap1g1i1617jh8pi.${appClientName}.idToken=wrong; CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${appClientName}.idToken=${tokenData.id_token}; CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${appClientName}.idToken=${tokenData.id_token}; CognitoIdentityServiceProvider.5ukasw8840tap1g1i1617jh8pi.${appClientName}.idToken=wrong;`,
value: [
Cookies.serialize(`CognitoIdentityServiceProvider.5uka3k8840tap1g1i1617jh8pi.${appClientName}.idToken`, 'wrong'),
Cookies.serialize(`CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${appClientName}.idToken`, tokenData.id_token),
Cookies.serialize(`CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${appClientName}.idToken`, tokenData.id_token),
Cookies.serialize(`CognitoIdentityServiceProvider.5ukasw8840tap1g1i1617jh8pi.${appClientName}.idToken`, 'wrong'),
].join('; '),
}]),
).toBe(tokenData.id_token);

expect(
authenticator._getIdTokenFromCookie([{
key: 'Cookie',
value: `CognitoIdentityServiceProvider.5uka3k8840tap1g1i1617jh8pi.${appClientName}.accessToken=someValue; CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${appClientName}.idToken=${tokenData.id_token}`,
value: [
Cookies.serialize(`CognitoIdentityServiceProvider.5uka3k8840tap1g1i1617jh8pi.${appClientName}.accessToken`, 'someValue'),
Cookies.serialize(`CognitoIdentityServiceProvider.123456789qwertyuiop987abcd.${appClientName}.idToken`, tokenData.id_token),
].join('; '),
}]),
).toBe(tokenData.id_token);
});

test('should getIdTokenFromCookie throw on cookies', () => {
expect(() => authenticator._getIdTokenFromCookie()).toThrow('Id token');
expect(() => authenticator._getIdTokenFromCookie('')).toThrow('Id token');
expect(() => authenticator._getIdTokenFromCookie([])).toThrow('Id token');
});
});
Expand Down Expand Up @@ -199,16 +206,16 @@ describe('createAuthenticator', () => {
delete params.disableCookieDomain;
expect(typeof new Authenticator(params)).toBe('object');
});

test('should create authenticator without httpOnly', () => {
delete params.httpOnly;
expect(typeof new Authenticator(params)).toBe('object');
});

test('should fail when creating authenticator without params', () => {
// @ts-ignore
// @ts-ignore
// ts-ignore is used here to override typescript's type check in the constructor
// this test is still useful when the library is imported to a js file
// this test is still useful when the library is imported to a js file
expect(() => new Authenticator()).toThrow('Expected params');
});

Expand Down
99 changes: 99 additions & 0 deletions __tests__/util/cookie.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { CookieAttributes, Cookies } from '../../src/util/cookie';

describe('parse tests', () => {
test('should parse valid cookie string', () => {
const cookieString = [
'test.cookie.one=test.value.one',
'test.cookie.two=test.value.two',
].join(';');

expect(Cookies.parse(cookieString))
.toStrictEqual([
{ name: 'test.cookie.one', value: 'test.value.one' },
{ name: 'test.cookie.two', value: 'test.value.two' },
]);
});

test('should parse valid cookie string with URI encoded characters', () => {
const cookieString = '%F0%9F%91%BB%28%29%3C%3E%40%2C%3B%3A%5C%22%2F%5B%5D%3F%3D%7B%7D%20=%20%22%2C%3B=%5C%F0%9F%91%BB';

expect(Cookies.parse(cookieString))
.toStrictEqual([
{ name: '👻()<>@,;:\\"/[]?={} ', value: ' ",;=\\👻' },
]);
});

test('should try to parse cookie even with not-encoded illegal characters', () => {
const cookieString = '(🤪)<>@,:\\"/[%1Y]?{}%=,\\%"; :=,\\%\\';

expect(Cookies.parse(cookieString))
.toStrictEqual([
{ name: '(🤪)<>@,:\\"/[%1Y]?{}%', value: ',\\%"' },
{ name: ':', value: ',\\%\\' },
]);
});

test('should skip cookies without separator', () => {
const cookieString = [
'1.name=value',
'somestring',
'2.name=value',
].join(';');

expect(Cookies.parse(cookieString))
.toStrictEqual([
{ name: '1.name', value: 'value' },
{ name: '2.name', value: 'value' },
]);
});

test('should return empty array when input parameter is null', () => {
expect(Cookies.parse(null)).toStrictEqual([]);
});
});

describe('serialize tests', () => {
test('should correctly serialize cookie without attributes', () => {
expect(Cookies.serialize('name', 'value'))
.toStrictEqual('name=value');
});

test('should correctly serialize cookie with defined attributes', () => {
const attributes: CookieAttributes = {
domain: 'example.com',
path: '/path/path',
expires: new Date(0),
maxAge: 1,
secure: true,
httpOnly: true,
};

expect(Cookies.serialize('name', 'value', attributes))
.toStrictEqual('name=value; Domain=example.com; Path=/path/path; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=1; Secure; HttpOnly');
});

test('should skip undefined attributes on serialization', () => {
const attributes: CookieAttributes = {
domain: undefined,
maxAge: 1,
secure: true,
httpOnly: true,
};

expect(Cookies.serialize('name', 'value', attributes))
.toStrictEqual('name=value; Max-Age=1; Secure; HttpOnly');
});

test('should encode characters not compliant with RFC 6265 and correctly decode it on parse', () => {
const name = '\t(%)<>@,;🤪:\\"/[]?={ключ} ';
const value = ' ,<;>\t😉%=\\значение';

const serialized = Cookies.serialize(name, value);

expect(serialized)
.toStrictEqual('%09%28%25%29%3C%3E%40%2C%3B%F0%9F%A4%AA%3A%5C%22%2F%5B%5D%3F%3D%7B%D0%BA%D0%BB%D1%8E%D1%87%7D%20=%20%2C<%3B>%09%F0%9F%98%89%25=%5C%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5');

expect(Cookies.parse(serialized))
.toStrictEqual([{ name, value }]);
});
});
80 changes: 34 additions & 46 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { parse, stringify } from 'querystring';
import pino from 'pino';
import { CognitoJwtVerifier } from 'aws-jwt-verify';
import { CloudFrontRequestEvent, CloudFrontRequestResult } from 'aws-lambda';
import { CookieAttributes, Cookies } from './util/cookie';

interface AuthenticatorParams {
region: string;
Expand Down Expand Up @@ -37,8 +38,8 @@ export class Authenticator {
this._userPoolAppSecret = params.userPoolAppSecret;
this._userPoolDomain = params.userPoolDomain;
this._cookieExpirationDays = params.cookieExpirationDays || 365;
this._disableCookieDomain = ('disableCookieDomain' in params && params.disableCookieDomain === true) ? true : false;
this._httpOnly = ('httpOnly' in params && params.httpOnly === true) ? true : false;
this._disableCookieDomain = ('disableCookieDomain' in params && params.disableCookieDomain === true);
this._httpOnly = ('httpOnly' in params && params.httpOnly === true);
this._cookieBase = `CognitoIdentityServiceProvider.${params.userPoolAppId}`;
this._logger = pino({
level: params.logLevel || 'silent', // Default to silent
Expand Down Expand Up @@ -121,17 +122,24 @@ export class Authenticator {
const decoded = await this._jwtVerifier.verify(tokens.id_token);
const username = decoded['cognito:username'];
const usernameBase = `${this._cookieBase}.${username}`;
const directives = [
...((this._disableCookieDomain) ? [] : [`Domain=${domain}`]),
`Expires=${new Date(Date.now() + this._cookieExpirationDays * 864e+5)}`,
'Secure',
...((this._httpOnly) ? ['HttpOnly'] : []),
].join('; ');
const cookieAttributes: CookieAttributes = {
domain: this._disableCookieDomain ? undefined : domain,
expires: new Date(Date.now() + this._cookieExpirationDays * 864e+5),
secure: true,
httpOnly: this._httpOnly,
};
const cookies = [
Cookies.serialize(`${usernameBase}.accessToken`, tokens.access_token, cookieAttributes),
Cookies.serialize(`${usernameBase}.idToken`, tokens.id_token, cookieAttributes),
Cookies.serialize(`${usernameBase}.refreshToken`, tokens.refresh_token, cookieAttributes),
Cookies.serialize(`${usernameBase}.tokenScopesString`, 'phone email profile openid aws.cognito.signin.user.admin', cookieAttributes),
Cookies.serialize(`${this._cookieBase}.LastAuthUser`, username, cookieAttributes),
];

const response = {
status: '302' ,
headers: {
'location': [{
'location': [{
key: 'Location',
value: location,
}],
Expand All @@ -143,28 +151,7 @@ export class Authenticator {
key: 'Pragma',
value: 'no-cache',
}],
'set-cookie': [
{
key: 'Set-Cookie',
value: `${usernameBase}.accessToken=${tokens.access_token}; ${directives}`,
},
{
key: 'Set-Cookie',
value: `${usernameBase}.idToken=${tokens.id_token}; ${directives}`,
},
{
key: 'Set-Cookie',
value: `${usernameBase}.refreshToken=${tokens.refresh_token}; ${directives}`,
},
{
key: 'Set-Cookie',
value: `${usernameBase}.tokenScopesString=phone email profile openid aws.cognito.signin.user.admin; ${directives}`,
},
{
key: 'Set-Cookie',
value: `${this._cookieBase}.LastAuthUser=${username}; ${directives}`,
},
],
'set-cookie': cookies.map(c => ({ key: 'Set-Cookie', value: c })),
},
};

Expand All @@ -175,24 +162,25 @@ export class Authenticator {

/**
* Extract value of the authentication token from the request cookies.
* @param {Array} cookies Request cookies.
* @param {Array} cookieHeaders 'Cookie' request headers.
* @return {String} Extracted access token. Throw if not found.
*/
_getIdTokenFromCookie(cookies) {
this._logger.debug({ msg: 'Extracting authentication token from request cookie', cookies });
// eslint-disable-next-line no-useless-escape
const regex = new RegExp(`${this._userPoolAppId}\..+?\.idToken=(.*?)(?:;|$)`);
if (cookies) {
for (let i = 0; i < cookies.length; i++) {
const matches = cookies[i].value.match(regex);
if (matches && matches.length > 1) {
this._logger.debug({ msg: ' Found token in cookie', token: matches[1] });
return matches[1];
}
}
_getIdTokenFromCookie(cookieHeaders: Array<{ key?: string | undefined, value: string }>) {
this._logger.debug({ msg: 'Extracting authentication token from request cookie', cookieHeaders });

const tokenCookieNamePrefix = `${this._cookieBase}.`;
const tokenCookieNamePostfix = '.idToken';

const cookies = cookieHeaders.flatMap(h => Cookies.parse(h.value));
const token = cookies.find(c => c.name.startsWith(tokenCookieNamePrefix) && c.name.endsWith(tokenCookieNamePostfix))?.value;

if (!token) {
this._logger.debug(" idToken wasn't present in request cookies");
borisfba marked this conversation as resolved.
Show resolved Hide resolved
throw new Error("Id token isn't present in the request cookies");
borisfba marked this conversation as resolved.
Show resolved Hide resolved
}
this._logger.debug(" idToken wasn't present in request cookies");
throw new Error("Id token isn't present in the request cookies");

this._logger.debug({ msg: ' Found token in cookie', token });
borisfba marked this conversation as resolved.
Show resolved Hide resolved
return token;
}

/**
Expand Down
Loading