auth.e2e-spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. import { DocumentNode } from 'graphql';
  2. import gql from 'graphql-tag';
  3. import path from 'path';
  4. import {
  5. CREATE_ADMINISTRATOR,
  6. CREATE_ROLE,
  7. } from '../../admin-ui/src/app/data/definitions/administrator-definitions';
  8. import { ATTEMPT_LOGIN } from '../../admin-ui/src/app/data/definitions/auth-definitions';
  9. import {
  10. CREATE_PRODUCT,
  11. GET_PRODUCT_LIST,
  12. UPDATE_PRODUCT,
  13. } from '../../admin-ui/src/app/data/definitions/product-definitions';
  14. import {
  15. CreateAdministrator,
  16. CreateProductMutationArgs,
  17. CreateRole,
  18. LoginMutationArgs,
  19. Permission,
  20. RegisterCustomerInput,
  21. UpdateProductMutationArgs,
  22. } from '../../shared/generated-types';
  23. import { SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD } from '../../shared/shared-constants';
  24. import { NoopEmailGenerator } from '../src/config/email/noop-email-generator';
  25. import { defaultEmailTypes } from '../src/email/default-email-types';
  26. import { TEST_SETUP_TIMEOUT_MS } from './config/test-config';
  27. import { TestClient } from './test-client';
  28. import { TestServer } from './test-server';
  29. import { assertThrowsWithMessage } from './test-utils';
  30. let sendEmailFn: jest.Mock;
  31. const emailOptions = {
  32. emailTemplatePath: 'src/email/templates',
  33. emailTypes: defaultEmailTypes,
  34. generator: new NoopEmailGenerator(),
  35. transport: {
  36. type: 'testing' as 'testing',
  37. onSend: ctx => sendEmailFn(ctx),
  38. },
  39. };
  40. describe('Authorization & permissions', () => {
  41. const client = new TestClient();
  42. const server = new TestServer();
  43. beforeAll(async () => {
  44. const token = await server.init(
  45. {
  46. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
  47. customerCount: 1,
  48. },
  49. {
  50. emailOptions,
  51. },
  52. );
  53. await client.init();
  54. }, TEST_SETUP_TIMEOUT_MS);
  55. afterAll(async () => {
  56. await server.destroy();
  57. });
  58. describe('admin permissions', () => {
  59. describe('Anonymous user', () => {
  60. beforeAll(async () => {
  61. await client.asAnonymousUser();
  62. });
  63. it('can attempt login', async () => {
  64. await assertRequestAllowed<LoginMutationArgs>(ATTEMPT_LOGIN, {
  65. username: SUPER_ADMIN_USER_IDENTIFIER,
  66. password: SUPER_ADMIN_USER_PASSWORD,
  67. rememberMe: false,
  68. });
  69. });
  70. });
  71. describe('ReadCatalog', () => {
  72. beforeAll(async () => {
  73. await client.asSuperAdmin();
  74. const { identifier, password } = await createAdministratorWithPermissions('ReadCatalog', [
  75. Permission.ReadCatalog,
  76. ]);
  77. await client.asUserWithCredentials(identifier, password);
  78. });
  79. it('can read', async () => {
  80. await assertRequestAllowed(GET_PRODUCT_LIST);
  81. });
  82. it('cannot uppdate', async () => {
  83. await assertRequestForbidden<UpdateProductMutationArgs>(UPDATE_PRODUCT, {
  84. input: {
  85. id: '1',
  86. translations: [],
  87. },
  88. });
  89. });
  90. it('cannot create', async () => {
  91. await assertRequestForbidden<CreateProductMutationArgs>(CREATE_PRODUCT, {
  92. input: {
  93. translations: [],
  94. },
  95. });
  96. });
  97. });
  98. describe('CRUD on Customers', () => {
  99. beforeAll(async () => {
  100. await client.asSuperAdmin();
  101. const { identifier, password } = await createAdministratorWithPermissions('CRUDCustomer', [
  102. Permission.CreateCustomer,
  103. Permission.ReadCustomer,
  104. Permission.UpdateCustomer,
  105. Permission.DeleteCustomer,
  106. ]);
  107. await client.asUserWithCredentials(identifier, password);
  108. });
  109. it('can create', async () => {
  110. await assertRequestAllowed(
  111. gql`
  112. mutation CreateCustomer($input: CreateCustomerInput!) {
  113. createCustomer(input: $input) {
  114. id
  115. }
  116. }
  117. `,
  118. { input: { emailAddress: '', firstName: '', lastName: '' } },
  119. );
  120. });
  121. it('can read', async () => {
  122. await assertRequestAllowed(gql`
  123. query {
  124. customers {
  125. totalItems
  126. }
  127. }
  128. `);
  129. });
  130. });
  131. });
  132. describe('customer account creation', () => {
  133. const password = 'password';
  134. const emailAddress = 'test1@test.com';
  135. let verificationToken: string;
  136. beforeEach(() => {
  137. sendEmailFn = jest.fn();
  138. });
  139. it(
  140. 'errors if a password is provided',
  141. assertThrowsWithMessage(async () => {
  142. const input: RegisterCustomerInput = {
  143. firstName: 'Sofia',
  144. lastName: 'Green',
  145. emailAddress: 'sofia.green@test.com',
  146. password: 'test',
  147. };
  148. const result = await client.query(REGISTER_ACCOUNT, { input });
  149. }, 'Do not provide a password when `authOptions.requireVerification` is set to "true"'),
  150. );
  151. it('register a new account', async () => {
  152. const verificationTokenPromise = getVerificationTokenPromise();
  153. const input: RegisterCustomerInput = {
  154. firstName: 'Sean',
  155. lastName: 'Tester',
  156. emailAddress,
  157. };
  158. const result = await client.query(REGISTER_ACCOUNT, { input });
  159. verificationToken = await verificationTokenPromise;
  160. expect(result.registerCustomerAccount).toBe(true);
  161. expect(sendEmailFn).toHaveBeenCalled();
  162. expect(verificationToken).toBeDefined();
  163. });
  164. it('issues a new token if attempting to register a second time', async () => {
  165. const sendEmail = new Promise<string>(resolve => {
  166. sendEmailFn.mockImplementation(ctx => {
  167. resolve(ctx.event.user.verificationToken);
  168. });
  169. });
  170. const input: RegisterCustomerInput = {
  171. firstName: 'Sean',
  172. lastName: 'Tester',
  173. emailAddress,
  174. };
  175. const result = await client.query(REGISTER_ACCOUNT, { input });
  176. const newVerificationToken = await sendEmail;
  177. expect(result.registerCustomerAccount).toBe(true);
  178. expect(sendEmailFn).toHaveBeenCalled();
  179. expect(newVerificationToken).not.toBe(verificationToken);
  180. verificationToken = newVerificationToken;
  181. });
  182. it('refreshCustomerVerification issues a new token', async () => {
  183. const sendEmail = new Promise<string>(resolve => {
  184. sendEmailFn.mockImplementation(ctx => {
  185. resolve(ctx.event.user.verificationToken);
  186. });
  187. });
  188. const result = await client.query(REFRESH_TOKEN, { emailAddress });
  189. const newVerificationToken = await sendEmail;
  190. expect(result.refreshCustomerVerification).toBe(true);
  191. expect(sendEmailFn).toHaveBeenCalled();
  192. expect(newVerificationToken).not.toBe(verificationToken);
  193. verificationToken = newVerificationToken;
  194. });
  195. it('refreshCustomerVerification does nothing with an unrecognized emailAddress', async () => {
  196. const result = await client.query(REFRESH_TOKEN, {
  197. emailAddress: 'never-been-registered@test.com',
  198. });
  199. await waitForSendEmailFn();
  200. expect(result.refreshCustomerVerification).toBe(true);
  201. expect(sendEmailFn).not.toHaveBeenCalled();
  202. });
  203. it('login fails before verification', async () => {
  204. try {
  205. await client.asUserWithCredentials(emailAddress, '');
  206. fail('should have thrown');
  207. } catch (err) {
  208. expect(getErrorCode(err)).toBe('UNAUTHORIZED');
  209. }
  210. });
  211. it(
  212. 'verification fails with wrong token',
  213. assertThrowsWithMessage(
  214. () =>
  215. client.query(VERIFY_EMAIL, {
  216. password,
  217. token: 'bad-token',
  218. }),
  219. `Verification token not recognized`,
  220. ),
  221. );
  222. it('verification succeeds with correct token', async () => {
  223. const result = await client.query(VERIFY_EMAIL, {
  224. password,
  225. token: verificationToken,
  226. });
  227. expect(result.verifyCustomerAccount.user.identifier).toBe('test1@test.com');
  228. });
  229. it('registration silently fails if attempting to register an email already verified', async () => {
  230. const input: RegisterCustomerInput = {
  231. firstName: 'Dodgy',
  232. lastName: 'Hacker',
  233. emailAddress,
  234. };
  235. const result = await client.query(REGISTER_ACCOUNT, { input });
  236. await waitForSendEmailFn();
  237. expect(result.registerCustomerAccount).toBe(true);
  238. expect(sendEmailFn).not.toHaveBeenCalled();
  239. });
  240. it(
  241. 'verification fails if attempted a second time',
  242. assertThrowsWithMessage(
  243. () =>
  244. client.query(VERIFY_EMAIL, {
  245. password,
  246. token: verificationToken,
  247. }),
  248. `Verification token not recognized`,
  249. ),
  250. );
  251. });
  252. async function assertRequestAllowed<V>(operation: DocumentNode, variables?: V) {
  253. try {
  254. const status = await client.queryStatus(operation, variables);
  255. expect(status).toBe(200);
  256. } catch (e) {
  257. const errorCode = getErrorCode(e);
  258. if (!errorCode) {
  259. fail(`Unexpected failure: ${e}`);
  260. } else {
  261. fail(`Operation should be allowed, got status ${getErrorCode(e)}`);
  262. }
  263. }
  264. }
  265. async function assertRequestForbidden<V>(operation: DocumentNode, variables: V) {
  266. try {
  267. const status = await client.query(operation, variables);
  268. fail(`Should have thrown`);
  269. } catch (e) {
  270. expect(getErrorCode(e)).toBe('FORBIDDEN');
  271. }
  272. }
  273. function getErrorCode(err: any): string {
  274. return err.response.errors[0].extensions.code;
  275. }
  276. async function createAdministratorWithPermissions(
  277. code: string,
  278. permissions: Permission[],
  279. ): Promise<{ identifier: string; password: string }> {
  280. const roleResult = await client.query<CreateRole.Mutation, CreateRole.Variables>(CREATE_ROLE, {
  281. input: {
  282. code,
  283. description: '',
  284. permissions,
  285. },
  286. });
  287. const role = roleResult.createRole;
  288. const identifier = `${code}@${Math.random()
  289. .toString(16)
  290. .substr(2, 8)}`;
  291. const password = `test`;
  292. const adminResult = await client.query<CreateAdministrator.Mutation, CreateAdministrator.Variables>(
  293. CREATE_ADMINISTRATOR,
  294. {
  295. input: {
  296. emailAddress: identifier,
  297. firstName: code,
  298. lastName: 'Admin',
  299. password,
  300. roleIds: [role.id],
  301. },
  302. },
  303. );
  304. const admin = adminResult.createAdministrator;
  305. return {
  306. identifier,
  307. password,
  308. };
  309. }
  310. /**
  311. * A "sleep" function which allows the sendEmailFn time to get called.
  312. */
  313. function waitForSendEmailFn() {
  314. return new Promise(resolve => setTimeout(resolve, 10));
  315. }
  316. });
  317. describe('Expiring registration token', () => {
  318. const client = new TestClient();
  319. const server = new TestServer();
  320. beforeAll(async () => {
  321. const token = await server.init(
  322. {
  323. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
  324. customerCount: 1,
  325. },
  326. {
  327. emailOptions,
  328. authOptions: {
  329. verificationTokenDuration: '1ms',
  330. },
  331. },
  332. );
  333. await client.init();
  334. }, TEST_SETUP_TIMEOUT_MS);
  335. beforeEach(() => {
  336. sendEmailFn = jest.fn();
  337. });
  338. afterAll(async () => {
  339. await server.destroy();
  340. });
  341. it(
  342. 'attempting to verify after token has expired throws',
  343. assertThrowsWithMessage(async () => {
  344. const verificationTokenPromise = getVerificationTokenPromise();
  345. const input: RegisterCustomerInput = {
  346. firstName: 'Barry',
  347. lastName: 'Wallace',
  348. emailAddress: 'barry.wallace@test.com',
  349. };
  350. const result = await client.query(REGISTER_ACCOUNT, { input });
  351. const verificationToken = await verificationTokenPromise;
  352. expect(result.registerCustomerAccount).toBe(true);
  353. expect(sendEmailFn).toHaveBeenCalledTimes(1);
  354. expect(verificationToken).toBeDefined();
  355. await new Promise(resolve => setTimeout(resolve, 3));
  356. return client.query(VERIFY_EMAIL, {
  357. password: 'test',
  358. token: verificationToken,
  359. });
  360. }, `Verification token has expired. Use refreshCustomerVerification to send a new token.`),
  361. );
  362. });
  363. describe('Registration without email verification', () => {
  364. const client = new TestClient();
  365. const server = new TestServer();
  366. const userEmailAddress = 'glen.beardsley@test.com';
  367. beforeAll(async () => {
  368. const token = await server.init(
  369. {
  370. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
  371. customerCount: 1,
  372. },
  373. {
  374. emailOptions,
  375. authOptions: {
  376. requireVerification: false,
  377. },
  378. },
  379. );
  380. await client.init();
  381. }, TEST_SETUP_TIMEOUT_MS);
  382. beforeEach(() => {
  383. sendEmailFn = jest.fn();
  384. });
  385. afterAll(async () => {
  386. await server.destroy();
  387. });
  388. it(
  389. 'errors if no password is provided',
  390. assertThrowsWithMessage(async () => {
  391. const input: RegisterCustomerInput = {
  392. firstName: 'Glen',
  393. lastName: 'Beardsley',
  394. emailAddress: userEmailAddress,
  395. };
  396. const result = await client.query(REGISTER_ACCOUNT, { input });
  397. }, 'A password must be provided when `authOptions.requireVerification` is set to "false"'),
  398. );
  399. it('register a new account with password', async () => {
  400. const input: RegisterCustomerInput = {
  401. firstName: 'Glen',
  402. lastName: 'Beardsley',
  403. emailAddress: userEmailAddress,
  404. password: 'test',
  405. };
  406. const result = await client.query(REGISTER_ACCOUNT, { input });
  407. expect(result.registerCustomerAccount).toBe(true);
  408. expect(sendEmailFn).not.toHaveBeenCalled();
  409. });
  410. it('can login after registering', async () => {
  411. await client.asUserWithCredentials(userEmailAddress, 'test');
  412. const result = await client.query(
  413. gql`
  414. query {
  415. me {
  416. identifier
  417. }
  418. }
  419. `,
  420. );
  421. expect(result.me.identifier).toBe(userEmailAddress);
  422. });
  423. });
  424. function getVerificationTokenPromise(): Promise<string> {
  425. return new Promise<string>(resolve => {
  426. sendEmailFn.mockImplementation(ctx => {
  427. resolve(ctx.event.user.verificationToken);
  428. });
  429. });
  430. }
  431. const REGISTER_ACCOUNT = gql`
  432. mutation Register($input: RegisterCustomerInput!) {
  433. registerCustomerAccount(input: $input)
  434. }
  435. `;
  436. const VERIFY_EMAIL = gql`
  437. mutation Verify($password: String!, $token: String!) {
  438. verifyCustomerAccount(password: $password, token: $token) {
  439. user {
  440. id
  441. identifier
  442. }
  443. }
  444. }
  445. `;
  446. const REFRESH_TOKEN = gql`
  447. mutation RefreshToken($emailAddress: String!) {
  448. refreshCustomerVerification(emailAddress: $emailAddress)
  449. }
  450. `;