@guardian/pan-domain-node 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ # Changesets
2
+
3
+ Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
4
+ with multi-package repos, or single-package repos to help you version and publish your code. You can
5
+ find the full documentation for it [in our repository](https://github.com/changesets/changesets)
6
+
7
+ We have a quick list of common questions to get you started engaging with this project in
8
+ [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
@@ -0,0 +1,11 @@
1
+ {
2
+ "$schema": "https://unpkg.com/@changesets/config@3.0.4/schema.json",
3
+ "changelog": "@changesets/cli/changelog",
4
+ "commit": false,
5
+ "fixed": [],
6
+ "linked": [],
7
+ "access": "public",
8
+ "baseBranch": "main",
9
+ "updateInternalDependencies": "patch",
10
+ "ignore": []
11
+ }
package/.nvmrc CHANGED
@@ -1 +1 @@
1
- 8
1
+ v20.18.1
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @guardian/pan-domain-node
2
+
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 01ddac5: Fix bug preventing cookie expiry from being correctly validated
package/dist/src/api.js CHANGED
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.guardianValidation = exports.AuthenticationStatus = void 0;
3
4
  var panda_1 = require("./panda");
4
- exports.PanDomainAuthentication = panda_1.PanDomainAuthentication;
5
+ Object.defineProperty(exports, "PanDomainAuthentication", { enumerable: true, get: function () { return panda_1.PanDomainAuthentication; } });
5
6
  var AuthenticationStatus;
6
7
  (function (AuthenticationStatus) {
7
8
  AuthenticationStatus["INVALID_COOKIE"] = "Invalid Cookie";
@@ -0,0 +1,5 @@
1
+ export interface PublicKeyHolder {
2
+ key: string;
3
+ lastUpdated: Date;
4
+ }
5
+ export declare function fetchPublicKey(region: string, bucket: String, keyFile: String): Promise<PublicKeyHolder>;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.fetchPublicKey = void 0;
23
+ const iniparser = __importStar(require("iniparser"));
24
+ const utils_1 = require("./utils");
25
+ function fetchPublicKey(region, bucket, keyFile) {
26
+ const path = `https://s3.${region}.amazonaws.com/${bucket}/${keyFile}`;
27
+ return utils_1.httpGet(path).then(response => {
28
+ const config = iniparser.parseString(response);
29
+ if (config.publicKey) {
30
+ return {
31
+ key: utils_1.base64ToPEM(config.publicKey, "PUBLIC"),
32
+ lastUpdated: new Date()
33
+ };
34
+ }
35
+ else {
36
+ throw new Error("Missing publicKey setting from config");
37
+ }
38
+ });
39
+ }
40
+ exports.fetchPublicKey = fetchPublicKey;
@@ -1,11 +1,8 @@
1
1
  /// <reference types="node" />
2
2
  import { User, AuthenticationResult, ValidateUserFn } from './api';
3
- interface PublicKeyHolder {
4
- key: string;
5
- lastUpdated: Date;
6
- }
3
+ import { PublicKeyHolder } from './fetch-public-key';
7
4
  export declare function createCookie(user: User, privateKey: string): string;
8
- export declare function verifyUser(pandaCookie: string | undefined, publicKey: string, currentTimestamp: number, validateUser: ValidateUserFn): AuthenticationResult;
5
+ export declare function verifyUser(pandaCookie: string | undefined, publicKey: string, currentTime: Date, validateUser: ValidateUserFn): AuthenticationResult;
9
6
  export declare class PanDomainAuthentication {
10
7
  cookieName: string;
11
8
  region: string;
@@ -20,4 +17,3 @@ export declare class PanDomainAuthentication {
20
17
  getPublicKey(): Promise<string>;
21
18
  verify(requestCookies: string): Promise<AuthenticationResult>;
22
19
  }
23
- export {};
package/dist/src/panda.js CHANGED
@@ -1,31 +1,29 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
2
14
  var __importStar = (this && this.__importStar) || function (mod) {
3
15
  if (mod && mod.__esModule) return mod;
4
16
  var result = {};
5
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
6
- result["default"] = mod;
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
7
19
  return result;
8
20
  };
9
21
  Object.defineProperty(exports, "__esModule", { value: true });
10
- const iniparser = __importStar(require("iniparser"));
22
+ exports.PanDomainAuthentication = exports.verifyUser = exports.createCookie = void 0;
11
23
  const cookie = __importStar(require("cookie"));
12
24
  const utils_1 = require("./utils");
13
25
  const api_1 = require("./api");
14
- function fetchPublicKey(region, bucket, keyFile) {
15
- const path = `https://s3.${region}.amazonaws.com/${bucket}/${keyFile}`;
16
- return utils_1.httpGet(path).then(response => {
17
- const config = iniparser.parseString(response);
18
- if (config.publicKey) {
19
- return {
20
- key: utils_1.base64ToPEM(config.publicKey, "PUBLIC"),
21
- lastUpdated: new Date()
22
- };
23
- }
24
- else {
25
- throw new Error("Missing publicKey setting from config");
26
- }
27
- });
28
- }
26
+ const fetch_public_key_1 = require("./fetch-public-key");
29
27
  function createCookie(user, privateKey) {
30
28
  let queryParams = [];
31
29
  queryParams.push("firstName=" + user.firstName);
@@ -42,7 +40,7 @@ function createCookie(user, privateKey) {
42
40
  return queryParamsString + "." + signature;
43
41
  }
44
42
  exports.createCookie = createCookie;
45
- function verifyUser(pandaCookie, publicKey, currentTimestamp, validateUser) {
43
+ function verifyUser(pandaCookie, publicKey, currentTime, validateUser) {
46
44
  if (!pandaCookie) {
47
45
  return { status: api_1.AuthenticationStatus.INVALID_COOKIE };
48
46
  }
@@ -50,9 +48,10 @@ function verifyUser(pandaCookie, publicKey, currentTimestamp, validateUser) {
50
48
  if (!utils_1.verifySignature(data, signature, publicKey)) {
51
49
  return { status: api_1.AuthenticationStatus.INVALID_COOKIE };
52
50
  }
51
+ const currentTimestampInMilliseconds = currentTime.getTime();
53
52
  try {
54
53
  const user = utils_1.parseUser(data);
55
- const isExpired = user.expires < currentTimestamp;
54
+ const isExpired = user.expires < currentTimestampInMilliseconds;
56
55
  if (isExpired) {
57
56
  return { status: api_1.AuthenticationStatus.EXPIRED, user };
58
57
  }
@@ -75,20 +74,21 @@ class PanDomainAuthentication {
75
74
  this.bucket = bucket;
76
75
  this.keyFile = keyFile;
77
76
  this.validateUser = validateUser;
78
- this.publicKey = fetchPublicKey(region, bucket, keyFile);
77
+ this.publicKey = fetch_public_key_1.fetchPublicKey(region, bucket, keyFile);
79
78
  this.keyUpdateTimer = setInterval(() => this.getPublicKey(), this.keyCacheTime);
80
79
  }
81
80
  stop() {
82
81
  if (this.keyUpdateTimer) {
83
82
  clearInterval(this.keyUpdateTimer);
83
+ this.keyUpdateTimer = undefined;
84
84
  }
85
85
  }
86
86
  getPublicKey() {
87
87
  return this.publicKey.then(({ key, lastUpdated }) => {
88
88
  const now = new Date();
89
- const diff = now.getMilliseconds() - lastUpdated.getMilliseconds();
89
+ const diff = now.getTime() - lastUpdated.getTime();
90
90
  if (diff > this.keyCacheTime) {
91
- this.publicKey = fetchPublicKey(this.region, this.bucket, this.keyFile);
91
+ this.publicKey = fetch_public_key_1.fetchPublicKey(this.region, this.bucket, this.keyFile);
92
92
  return this.publicKey.then(({ key }) => key);
93
93
  }
94
94
  else {
@@ -100,8 +100,7 @@ class PanDomainAuthentication {
100
100
  return this.getPublicKey().then(publicKey => {
101
101
  const cookies = cookie.parse(requestCookies);
102
102
  const pandaCookie = cookies[this.cookieName];
103
- const now = new Date().getMilliseconds();
104
- return verifyUser(pandaCookie, publicKey, now, this.validateUser);
103
+ return verifyUser(pandaCookie, publicKey, new Date(), this.validateUser);
105
104
  });
106
105
  }
107
106
  }
package/dist/src/utils.js CHANGED
@@ -1,12 +1,25 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
2
14
  var __importStar = (this && this.__importStar) || function (mod) {
3
15
  if (mod && mod.__esModule) return mod;
4
16
  var result = {};
5
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
6
- result["default"] = mod;
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
7
19
  return result;
8
20
  };
9
21
  Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.parseUser = exports.httpGet = exports.base64ToPEM = exports.sign = exports.verifySignature = exports.parseCookie = exports.decodeBase64 = void 0;
10
23
  const crypto = __importStar(require("crypto"));
11
24
  const https = __importStar(require("https"));
12
25
  const url_1 = require("url");
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sampleNonGuardianCookie = exports.sampleCookieWithoutMultifactor = exports.sampleCookie = exports.publicKey = exports.encodedPublicKey = exports.privateKey = exports.encodedPrivateKey = void 0;
3
4
  const utils_1 = require("../src/utils");
4
5
  exports.encodedPrivateKey = "MIIJKAIBAAKCAgEAur0hOjhB2QWjwOopCR+Qo27AYv97BJkVaKWPXpj9RfvY1wtpIratDN6tkXN9WCRPzVX8+5qaW034Kvf9WwBZD1ntS8iHYwY1YUaU8Mrp2sRT3K0RqyBlTswIH3HIqpASqv7ZtwDHdhk7Cbd13P5aomJSOjYFhCDUi3sRbjJP1kb6uQLdkZj8fIU518HzSR7Kw7p2mbDqSrGbnaeHWd0Tr3BvDHp9Pi0KpSAVm2qWAXix+BcjMA4ar7kLU1Pre0lt4K4DlSvq5XoHdX9/yvS6KGf+8pXDR9bY6dgRPSG4mzKpiKfkv1eXE8WKs0q3217QZItaSjocw4d0o47vSN+/MAh9V5Zewyb6ogs8JicX3Y3FPG29I1g8iLf3kBZ7V4mUimGuOq/L+1YVvyOTb2zWWMjNmECO2lrxXJc5LWRs5FmSJyCdilRktDE0WTGUo89O+DcF2752qtpUmlV2fllU1LXIAn0TJKiAZspKakamifrgYFIzZK4oZ8wDeFesQB/a/U7wtyv85vknzCtMLI28dnpGQ/ZFHNqWYVaHoHsnEmWion7lgMctnpY5pwKFfUSfZecl2Xqwjk1HZj71A9TFNQj+/x4z957cNtx+utAkGinK3eZF+H1o5YnSgjg4hN41kbXttk8nADerPdF7hDS6np7xzUl6qOicJhEOJ5x0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WWrlV6YKDUwl+gWDHmJOcvKqKKAeUnrhIMmJGaO6C++5DxPE/n7g5M86GA0bu/+B+32wL/65B8HoJrkHnSMJp9GcCsVZA3+2xcJfo+xAiXeiRobRIxCQMYCDDM7Hr7X5jGa7l9bQr4GuWRKRYTroE9LCDnH/LLUN+0ny3UXrSjtTUVL4mVAJT0Ws2H1zUzVDbu7ZQgA0u3GjtdFvAnS/E+ln8DS3Q1DeD6Zsf0hrrJbtwU4zZIU445SZ+IUaTjueB9v/skukoIQi/0Mj+gpZ1c=";
5
6
  exports.privateKey = utils_1.base64ToPEM(exports.encodedPrivateKey, "RSA PRIVATE");
@@ -1,28 +1,41 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  const api_1 = require("../src/api");
4
13
  const panda_1 = require("../src/panda");
14
+ const fetch_public_key_1 = require("../src/fetch-public-key");
5
15
  const fixtures_1 = require("./fixtures");
6
16
  const utils_1 = require("../src/utils");
17
+ jest.mock('../src/fetch-public-key');
18
+ jest.useFakeTimers('modern');
7
19
  describe('verifyUser', function () {
8
20
  test("return invalid cookie if missing", () => {
9
- expect(panda_1.verifyUser(undefined, "", 0, api_1.guardianValidation).status).toBe(api_1.AuthenticationStatus.INVALID_COOKIE);
21
+ expect(panda_1.verifyUser(undefined, "", new Date(0), api_1.guardianValidation).status).toBe(api_1.AuthenticationStatus.INVALID_COOKIE);
10
22
  });
11
23
  test("return invalid cookie for a malformed signature", () => {
12
24
  const [data, signature] = fixtures_1.sampleCookie.split(".");
13
25
  const testCookie = data + ".1234";
14
- expect(panda_1.verifyUser(testCookie, fixtures_1.publicKey, 0, api_1.guardianValidation).status).toBe(api_1.AuthenticationStatus.INVALID_COOKIE);
26
+ expect(panda_1.verifyUser(testCookie, fixtures_1.publicKey, new Date(0), api_1.guardianValidation).status).toBe(api_1.AuthenticationStatus.INVALID_COOKIE);
15
27
  });
16
28
  test("return expired", () => {
17
- const someTimeInTheFuture = 5678;
29
+ const someTimeInTheFuture = new Date(5678);
30
+ expect(someTimeInTheFuture.getTime()).toBe(5678);
18
31
  expect(panda_1.verifyUser(fixtures_1.sampleCookie, fixtures_1.publicKey, someTimeInTheFuture, api_1.guardianValidation).status).toBe(api_1.AuthenticationStatus.EXPIRED);
19
32
  });
20
33
  test("return not authenticated if user fails validation function", () => {
21
- expect(panda_1.verifyUser(fixtures_1.sampleCookieWithoutMultifactor, fixtures_1.publicKey, 0, api_1.guardianValidation).status).toBe(api_1.AuthenticationStatus.NOT_AUTHORISED);
22
- expect(panda_1.verifyUser(fixtures_1.sampleNonGuardianCookie, fixtures_1.publicKey, 0, api_1.guardianValidation).status).toBe(api_1.AuthenticationStatus.NOT_AUTHORISED);
34
+ expect(panda_1.verifyUser(fixtures_1.sampleCookieWithoutMultifactor, fixtures_1.publicKey, new Date(0), api_1.guardianValidation).status).toBe(api_1.AuthenticationStatus.NOT_AUTHORISED);
35
+ expect(panda_1.verifyUser(fixtures_1.sampleNonGuardianCookie, fixtures_1.publicKey, new Date(0), api_1.guardianValidation).status).toBe(api_1.AuthenticationStatus.NOT_AUTHORISED);
23
36
  });
24
37
  test("return authenticated", () => {
25
- expect(panda_1.verifyUser(fixtures_1.sampleCookie, fixtures_1.publicKey, 0, api_1.guardianValidation).status).toBe(api_1.AuthenticationStatus.AUTHORISED);
38
+ expect(panda_1.verifyUser(fixtures_1.sampleCookie, fixtures_1.publicKey, new Date(0), api_1.guardianValidation).status).toBe(api_1.AuthenticationStatus.AUTHORISED);
26
39
  });
27
40
  });
28
41
  describe('createCookie', function () {
@@ -41,3 +54,61 @@ describe('createCookie', function () {
41
54
  expect(cookie).toEqual(fixtures_1.sampleCookie);
42
55
  });
43
56
  });
57
+ describe('panda class', function () {
58
+ beforeEach(() => {
59
+ fetch_public_key_1.fetchPublicKey.mockResolvedValue({ key: 'PUBLIC KEY', lastUpdated: new Date() });
60
+ });
61
+ describe('stop', () => {
62
+ it('stops auto refresh', () => {
63
+ const panda = new panda_1.PanDomainAuthentication('cookiename', 'region', 'bucket', 'keyfile', (u) => true);
64
+ expect(panda.keyUpdateTimer).not.toBeUndefined();
65
+ panda.stop();
66
+ expect(panda.keyUpdateTimer).toBeUndefined();
67
+ });
68
+ });
69
+ describe('getPublicKey', () => {
70
+ it('getsPublicKey immediately when last fetch is within the cache time', () => __awaiter(this, void 0, void 0, function* () {
71
+ const panda = new panda_1.PanDomainAuthentication('cookiename', 'region', 'bucket', 'keyfile', (u) => true);
72
+ const fetchesBeforeGet = fetch_public_key_1.fetchPublicKey.mock.calls.length;
73
+ yield expect(panda.getPublicKey()).resolves.toEqual('PUBLIC KEY');
74
+ const fetchesAfterGet = fetch_public_key_1.fetchPublicKey.mock.calls.length;
75
+ expect(fetchesAfterGet).toEqual(fetchesBeforeGet);
76
+ }));
77
+ it('getsPublicKey after refetching when last fetch is outside the cache time', () => __awaiter(this, void 0, void 0, function* () {
78
+ // cache time is 1 min
79
+ const fiveMinsAgo = new Date();
80
+ fiveMinsAgo.setMinutes(fiveMinsAgo.getMinutes() - 5);
81
+ fetch_public_key_1.fetchPublicKey.mockResolvedValue({ key: 'PUBLIC KEY', lastUpdated: fiveMinsAgo });
82
+ const panda = new panda_1.PanDomainAuthentication('cookiename', 'region', 'bucket', 'keyfile', (u) => true);
83
+ const fetchesBefore = fetch_public_key_1.fetchPublicKey.mock.calls.length;
84
+ yield expect(panda.getPublicKey()).resolves.toEqual('PUBLIC KEY');
85
+ fetch_public_key_1.fetchPublicKey.mockResolvedValue({ key: 'PUBLIC KEY 2', lastUpdated: fiveMinsAgo });
86
+ const fetchesAfter = fetch_public_key_1.fetchPublicKey.mock.calls.length;
87
+ yield expect(panda.getPublicKey()).resolves.toEqual('PUBLIC KEY 2');
88
+ expect(fetchesAfter).toEqual(fetchesBefore + 1);
89
+ }));
90
+ });
91
+ describe('verify', () => {
92
+ beforeEach(() => {
93
+ fetch_public_key_1.fetchPublicKey.mockResolvedValue({ key: fixtures_1.publicKey, lastUpdated: new Date() });
94
+ });
95
+ it('should return authenticated if valid', () => __awaiter(this, void 0, void 0, function* () {
96
+ jest.setSystemTime(100);
97
+ const panda = new panda_1.PanDomainAuthentication('cookiename', 'region', 'bucket', 'keyfile', (u) => true);
98
+ const { status } = yield panda.verify(`cookiename=${fixtures_1.sampleCookie}`);
99
+ expect(status).toBe(api_1.AuthenticationStatus.AUTHORISED);
100
+ }));
101
+ it('should return expired if expired', () => __awaiter(this, void 0, void 0, function* () {
102
+ jest.setSystemTime(10000);
103
+ const panda = new panda_1.PanDomainAuthentication('cookiename', 'region', 'bucket', 'keyfile', (u) => true);
104
+ const { status } = yield panda.verify(`cookiename=${fixtures_1.sampleCookie}`);
105
+ expect(status).toBe(api_1.AuthenticationStatus.EXPIRED);
106
+ }));
107
+ it('should return not authenticated if validation fails', () => __awaiter(this, void 0, void 0, function* () {
108
+ jest.setSystemTime(100);
109
+ const panda = new panda_1.PanDomainAuthentication('cookiename', 'region', 'bucket', 'keyfile', api_1.guardianValidation);
110
+ const { status } = yield panda.verify(`cookiename=${fixtures_1.sampleNonGuardianCookie}`);
111
+ expect(status).toBe(api_1.AuthenticationStatus.NOT_AUTHORISED);
112
+ }));
113
+ });
114
+ });
package/jest.config.js CHANGED
@@ -3,6 +3,7 @@ module.exports = {
3
3
  "<rootDir>/src",
4
4
  "<rootDir>/test"
5
5
  ],
6
+ "clearMocks": true,
6
7
  "transform": {
7
8
  "^.+\\.tsx?$": "ts-jest"
8
9
  },
@@ -15,4 +16,4 @@ module.exports = {
15
16
  "json",
16
17
  "node"
17
18
  ],
18
- }
19
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guardian/pan-domain-node",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "description": "NodeJs implementation of Guardian pan-domain auth verification",
5
5
  "main": "dist/src/api.js",
6
6
  "types": "dist/src/api.d.ts",
@@ -22,16 +22,17 @@
22
22
  },
23
23
  "homepage": "https://github.com/guardian/pan-domain-authentication",
24
24
  "devDependencies": {
25
- "@types/cookie": "^0.3.2",
25
+ "@changesets/cli": "^2.27.10",
26
+ "@types/cookie": "^0.4.0",
26
27
  "@types/iniparser": "0.0.29",
27
- "@types/jest": "^24.0.9",
28
- "@types/node": "^11.10.5",
29
- "jest": "^24.3.1",
30
- "ts-jest": "^24.0.0",
31
- "typescript": "^3.3.3333"
28
+ "@types/jest": "^26.0.9",
29
+ "@types/node": "^14.0.27",
30
+ "jest": "^26.2.2",
31
+ "ts-jest": "^26.1.4",
32
+ "typescript": "^3.9.7"
32
33
  },
33
34
  "dependencies": {
34
- "cookie": "^0.3.1",
35
+ "cookie": "^0.4.1",
35
36
  "iniparser": "^1.0.5"
36
37
  },
37
38
  "scripts": {
@@ -0,0 +1,27 @@
1
+ import * as iniparser from 'iniparser';
2
+ import {base64ToPEM, httpGet} from './utils';
3
+
4
+ export interface PublicKeyHolder {
5
+ key: string,
6
+ lastUpdated: Date
7
+ }
8
+
9
+
10
+ export function fetchPublicKey(region: string, bucket: String, keyFile: String): Promise<PublicKeyHolder> {
11
+ const path = `https://s3.${region}.amazonaws.com/${bucket}/${keyFile}`;
12
+
13
+ return httpGet(path).then(response => {
14
+ const config: { publicKey?: string} = iniparser.parseString(response);
15
+
16
+ if(config.publicKey) {
17
+ return {
18
+ key: base64ToPEM(config.publicKey, "PUBLIC"),
19
+ lastUpdated: new Date()
20
+ };
21
+ } else {
22
+ throw new Error("Missing publicKey setting from config");
23
+ }
24
+ });
25
+ }
26
+
27
+
package/src/panda.ts CHANGED
@@ -1,30 +1,8 @@
1
- import * as iniparser from 'iniparser';
2
1
  import * as cookie from 'cookie';
3
2
 
4
- import {base64ToPEM, httpGet, parseCookie, parseUser, sign, verifySignature} from './utils';
3
+ import {parseCookie, parseUser, sign, verifySignature} from './utils';
5
4
  import {AuthenticationStatus, User, AuthenticationResult, ValidateUserFn} from './api';
6
-
7
- interface PublicKeyHolder {
8
- key: string,
9
- lastUpdated: Date
10
- }
11
-
12
- function fetchPublicKey(region: string, bucket: String, keyFile: String): Promise<PublicKeyHolder> {
13
- const path = `https://s3.${region}.amazonaws.com/${bucket}/${keyFile}`;
14
-
15
- return httpGet(path).then(response => {
16
- const config: { publicKey?: string} = iniparser.parseString(response);
17
-
18
- if(config.publicKey) {
19
- return {
20
- key: base64ToPEM(config.publicKey, "PUBLIC"),
21
- lastUpdated: new Date()
22
- };
23
- } else {
24
- throw new Error("Missing publicKey setting from config");
25
- }
26
- });
27
- }
5
+ import { fetchPublicKey, PublicKeyHolder } from './fetch-public-key';
28
6
 
29
7
  export function createCookie(user: User, privateKey: string): string {
30
8
  let queryParams: string[] = [];
@@ -46,7 +24,7 @@ export function createCookie(user: User, privateKey: string): string {
46
24
  return queryParamsString + "." + signature
47
25
  }
48
26
 
49
- export function verifyUser(pandaCookie: string | undefined, publicKey: string, currentTimestamp: number, validateUser: ValidateUserFn): AuthenticationResult {
27
+ export function verifyUser(pandaCookie: string | undefined, publicKey: string, currentTime: Date, validateUser: ValidateUserFn): AuthenticationResult {
50
28
  if(!pandaCookie) {
51
29
  return { status: AuthenticationStatus.INVALID_COOKIE };
52
30
  }
@@ -57,9 +35,11 @@ export function verifyUser(pandaCookie: string | undefined, publicKey: string, c
57
35
  return { status: AuthenticationStatus.INVALID_COOKIE };
58
36
  }
59
37
 
38
+ const currentTimestampInMilliseconds = currentTime.getTime();
39
+
60
40
  try {
61
41
  const user: User = parseUser(data);
62
- const isExpired = user.expires < currentTimestamp;
42
+ const isExpired = user.expires < currentTimestampInMilliseconds;
63
43
 
64
44
  if(isExpired) {
65
45
  return { status: AuthenticationStatus.EXPIRED, user };
@@ -102,13 +82,14 @@ export class PanDomainAuthentication {
102
82
  stop(): void {
103
83
  if(this.keyUpdateTimer) {
104
84
  clearInterval(this.keyUpdateTimer);
85
+ this.keyUpdateTimer = undefined;
105
86
  }
106
87
  }
107
88
 
108
89
  getPublicKey(): Promise<string> {
109
90
  return this.publicKey.then(({ key, lastUpdated }) => {
110
91
  const now = new Date();
111
- const diff = now.getMilliseconds() - lastUpdated.getMilliseconds();
92
+ const diff = now.getTime() - lastUpdated.getTime();
112
93
 
113
94
  if(diff > this.keyCacheTime) {
114
95
  this.publicKey = fetchPublicKey(this.region, this.bucket, this.keyFile);
@@ -124,8 +105,7 @@ export class PanDomainAuthentication {
124
105
  const cookies = cookie.parse(requestCookies);
125
106
  const pandaCookie = cookies[this.cookieName];
126
107
 
127
- const now = new Date().getMilliseconds();
128
- return verifyUser(pandaCookie, publicKey, now, this.validateUser);
108
+ return verifyUser(pandaCookie, publicKey, new Date(), this.validateUser);
129
109
  });
130
110
  }
131
111
  }
@@ -1,5 +1,6 @@
1
1
  import {guardianValidation, AuthenticationStatus, User} from '../src/api';
2
- import { verifyUser, createCookie } from '../src/panda';
2
+ import { verifyUser, createCookie, PanDomainAuthentication } from '../src/panda';
3
+ import { fetchPublicKey } from '../src/fetch-public-key';
3
4
 
4
5
  import {
5
6
  sampleCookie,
@@ -10,31 +11,35 @@ import {
10
11
  } from './fixtures';
11
12
  import {decodeBase64} from "../src/utils";
12
13
 
14
+ jest.mock('../src/fetch-public-key');
15
+ jest.useFakeTimers('modern');
16
+
13
17
  describe('verifyUser', function () {
14
18
 
15
19
  test("return invalid cookie if missing", () => {
16
- expect(verifyUser(undefined, "", 0, guardianValidation).status).toBe(AuthenticationStatus.INVALID_COOKIE);
20
+ expect(verifyUser(undefined, "", new Date(0), guardianValidation).status).toBe(AuthenticationStatus.INVALID_COOKIE);
17
21
  });
18
22
 
19
23
  test("return invalid cookie for a malformed signature", () => {
20
24
  const [data, signature] = sampleCookie.split(".");
21
25
  const testCookie = data + ".1234";
22
26
 
23
- expect(verifyUser(testCookie, publicKey, 0, guardianValidation).status).toBe(AuthenticationStatus.INVALID_COOKIE);
27
+ expect(verifyUser(testCookie, publicKey, new Date(0), guardianValidation).status).toBe(AuthenticationStatus.INVALID_COOKIE);
24
28
  });
25
29
 
26
30
  test("return expired", () => {
27
- const someTimeInTheFuture = 5678;
31
+ const someTimeInTheFuture = new Date(5678);
32
+ expect(someTimeInTheFuture.getTime()).toBe(5678);
28
33
  expect(verifyUser(sampleCookie, publicKey, someTimeInTheFuture, guardianValidation).status).toBe(AuthenticationStatus.EXPIRED);
29
34
  });
30
35
 
31
36
  test("return not authenticated if user fails validation function", () => {
32
- expect(verifyUser(sampleCookieWithoutMultifactor, publicKey, 0, guardianValidation).status).toBe(AuthenticationStatus.NOT_AUTHORISED);
33
- expect(verifyUser(sampleNonGuardianCookie, publicKey, 0, guardianValidation).status).toBe(AuthenticationStatus.NOT_AUTHORISED);
37
+ expect(verifyUser(sampleCookieWithoutMultifactor, publicKey, new Date(0), guardianValidation).status).toBe(AuthenticationStatus.NOT_AUTHORISED);
38
+ expect(verifyUser(sampleNonGuardianCookie, publicKey, new Date(0), guardianValidation).status).toBe(AuthenticationStatus.NOT_AUTHORISED);
34
39
  });
35
40
 
36
41
  test("return authenticated", () => {
37
- expect(verifyUser(sampleCookie, publicKey, 0, guardianValidation).status).toBe(AuthenticationStatus.AUTHORISED);
42
+ expect(verifyUser(sampleCookie, publicKey, new Date(0), guardianValidation).status).toBe(AuthenticationStatus.AUTHORISED);
38
43
  });
39
44
  });
40
45
 
@@ -56,3 +61,93 @@ describe('createCookie', function () {
56
61
  expect(cookie).toEqual(sampleCookie)
57
62
  });
58
63
  });
64
+
65
+ describe('panda class', function () {
66
+ beforeEach(() => {
67
+ (fetchPublicKey as jest.MockedFunction<typeof fetchPublicKey>).mockResolvedValue({ key: 'PUBLIC KEY', lastUpdated: new Date() });
68
+ });
69
+
70
+ describe('stop', () => {
71
+
72
+ it('stops auto refresh', () => {
73
+ const panda = new PanDomainAuthentication('cookiename', 'region', 'bucket', 'keyfile', (u)=> true);
74
+ expect(panda.keyUpdateTimer).not.toBeUndefined();
75
+ panda.stop();
76
+ expect(panda.keyUpdateTimer).toBeUndefined();
77
+ });
78
+
79
+ });
80
+
81
+ describe('getPublicKey', () => {
82
+
83
+ it('getsPublicKey immediately when last fetch is within the cache time', async () => {
84
+
85
+ const panda = new PanDomainAuthentication('cookiename', 'region', 'bucket', 'keyfile', (u)=> true);
86
+ const fetchesBeforeGet = (fetchPublicKey as jest.MockedFunction<typeof fetchPublicKey>).mock.calls.length;
87
+
88
+ await expect(panda.getPublicKey()).resolves.toEqual('PUBLIC KEY');
89
+ const fetchesAfterGet = (fetchPublicKey as jest.MockedFunction<typeof fetchPublicKey>).mock.calls.length;
90
+
91
+ expect(fetchesAfterGet).toEqual(fetchesBeforeGet);
92
+
93
+ });
94
+
95
+ it('getsPublicKey after refetching when last fetch is outside the cache time', async () => {
96
+ // cache time is 1 min
97
+ const fiveMinsAgo = new Date();
98
+ fiveMinsAgo.setMinutes(fiveMinsAgo.getMinutes() - 5);
99
+
100
+ (fetchPublicKey as jest.MockedFunction<typeof fetchPublicKey>).mockResolvedValue({ key: 'PUBLIC KEY', lastUpdated: fiveMinsAgo });
101
+
102
+ const panda = new PanDomainAuthentication('cookiename', 'region', 'bucket', 'keyfile', (u)=> true);
103
+
104
+ const fetchesBefore = (fetchPublicKey as jest.MockedFunction<typeof fetchPublicKey>).mock.calls.length;
105
+
106
+ await expect(panda.getPublicKey()).resolves.toEqual('PUBLIC KEY');
107
+
108
+ (fetchPublicKey as jest.MockedFunction<typeof fetchPublicKey>).mockResolvedValue({ key: 'PUBLIC KEY 2', lastUpdated: fiveMinsAgo });
109
+
110
+ const fetchesAfter = (fetchPublicKey as jest.MockedFunction<typeof fetchPublicKey>).mock.calls.length;
111
+
112
+ await expect(panda.getPublicKey()).resolves.toEqual('PUBLIC KEY 2');
113
+
114
+ expect(fetchesAfter).toEqual(fetchesBefore + 1);
115
+ });
116
+
117
+ });
118
+
119
+ describe('verify', () => {
120
+
121
+ beforeEach(() => {
122
+ (fetchPublicKey as jest.MockedFunction<typeof fetchPublicKey>).mockResolvedValue({ key: publicKey, lastUpdated: new Date() });
123
+ });
124
+
125
+ it('should return authenticated if valid', async () => {
126
+ jest.setSystemTime(100);
127
+ const panda = new PanDomainAuthentication('cookiename', 'region', 'bucket', 'keyfile', (u)=> true);
128
+ const { status } = await panda.verify(`cookiename=${sampleCookie}`);
129
+
130
+ expect(status).toBe(AuthenticationStatus.AUTHORISED);
131
+ });
132
+
133
+ it('should return expired if expired', async () => {
134
+ jest.setSystemTime(10_000);
135
+
136
+ const panda = new PanDomainAuthentication('cookiename', 'region', 'bucket', 'keyfile', (u)=> true);
137
+ const { status } = await panda.verify(`cookiename=${sampleCookie}`);
138
+
139
+ expect(status).toBe(AuthenticationStatus.EXPIRED);
140
+ });
141
+
142
+ it('should return not authenticated if validation fails', async () => {
143
+ jest.setSystemTime(100);
144
+
145
+ const panda = new PanDomainAuthentication('cookiename', 'region', 'bucket', 'keyfile', guardianValidation);
146
+ const { status } = await panda.verify(`cookiename=${sampleNonGuardianCookie}`);
147
+
148
+ expect(status).toBe(AuthenticationStatus.NOT_AUTHORISED);
149
+ });
150
+
151
+ });
152
+
153
+ });