auth.e2e-spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. productCount: 1,
  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('register a new account', async () => {
  140. const verificationTokenPromise = getVerificationTokenPromise();
  141. const input: RegisterCustomerInput = {
  142. firstName: 'Sean',
  143. lastName: 'Tester',
  144. emailAddress,
  145. };
  146. const result = await client.query(REGISTER_ACCOUNT, { input });
  147. verificationToken = await verificationTokenPromise;
  148. expect(result.registerCustomerAccount).toBe(true);
  149. expect(sendEmailFn).toHaveBeenCalled();
  150. expect(verificationToken).toBeDefined();
  151. });
  152. it('issues a new token if attempting to register a second time', async () => {
  153. const sendEmail = new Promise<string>(resolve => {
  154. sendEmailFn.mockImplementation(ctx => {
  155. resolve(ctx.event.user.verificationToken);
  156. });
  157. });
  158. const input: RegisterCustomerInput = {
  159. firstName: 'Sean',
  160. lastName: 'Tester',
  161. emailAddress,
  162. };
  163. const result = await client.query(REGISTER_ACCOUNT, { input });
  164. const newVerificationToken = await sendEmail;
  165. expect(result.registerCustomerAccount).toBe(true);
  166. expect(sendEmailFn).toHaveBeenCalled();
  167. expect(newVerificationToken).not.toBe(verificationToken);
  168. verificationToken = newVerificationToken;
  169. });
  170. it('refreshCustomerVerification issues a new token', async () => {
  171. const sendEmail = new Promise<string>(resolve => {
  172. sendEmailFn.mockImplementation(ctx => {
  173. resolve(ctx.event.user.verificationToken);
  174. });
  175. });
  176. const result = await client.query(REFRESH_TOKEN, { emailAddress });
  177. const newVerificationToken = await sendEmail;
  178. expect(result.refreshCustomerVerification).toBe(true);
  179. expect(sendEmailFn).toHaveBeenCalled();
  180. expect(newVerificationToken).not.toBe(verificationToken);
  181. verificationToken = newVerificationToken;
  182. });
  183. it('refreshCustomerVerification does nothing with an unrecognized emailAddress', async () => {
  184. const result = await client.query(REFRESH_TOKEN, {
  185. emailAddress: 'never-been-registered@test.com',
  186. });
  187. await waitForSendEmailFn();
  188. expect(result.refreshCustomerVerification).toBe(true);
  189. expect(sendEmailFn).not.toHaveBeenCalled();
  190. });
  191. it('login fails before verification', async () => {
  192. try {
  193. await client.asUserWithCredentials(emailAddress, '');
  194. fail('should have thrown');
  195. } catch (err) {
  196. expect(getErrorCode(err)).toBe('UNAUTHORIZED');
  197. }
  198. });
  199. it(
  200. 'verification fails with wrong token',
  201. assertThrowsWithMessage(
  202. () =>
  203. client.query(VERIFY_EMAIL, {
  204. password,
  205. token: 'bad-token',
  206. }),
  207. `Verification token not recognized`,
  208. ),
  209. );
  210. it('verification succeeds with correct token', async () => {
  211. const result = await client.query(VERIFY_EMAIL, {
  212. password,
  213. token: verificationToken,
  214. });
  215. expect(result.verifyCustomerAccount.user.identifier).toBe('test1@test.com');
  216. });
  217. it('registration silently fails if attempting to register an email already verified', async () => {
  218. const input: RegisterCustomerInput = {
  219. firstName: 'Dodgy',
  220. lastName: 'Hacker',
  221. emailAddress,
  222. };
  223. const result = await client.query(REGISTER_ACCOUNT, { input });
  224. await waitForSendEmailFn();
  225. expect(result.registerCustomerAccount).toBe(true);
  226. expect(sendEmailFn).not.toHaveBeenCalled();
  227. });
  228. it(
  229. 'verification fails if attempted a second time',
  230. assertThrowsWithMessage(
  231. () =>
  232. client.query(VERIFY_EMAIL, {
  233. password,
  234. token: verificationToken,
  235. }),
  236. `Verification token not recognized`,
  237. ),
  238. );
  239. });
  240. async function assertRequestAllowed<V>(operation: DocumentNode, variables?: V) {
  241. try {
  242. const status = await client.queryStatus(operation, variables);
  243. expect(status).toBe(200);
  244. } catch (e) {
  245. const errorCode = getErrorCode(e);
  246. if (!errorCode) {
  247. fail(`Unexpected failure: ${e}`);
  248. } else {
  249. fail(`Operation should be allowed, got status ${getErrorCode(e)}`);
  250. }
  251. }
  252. }
  253. async function assertRequestForbidden<V>(operation: DocumentNode, variables: V) {
  254. try {
  255. const status = await client.query(operation, variables);
  256. fail(`Should have thrown`);
  257. } catch (e) {
  258. expect(getErrorCode(e)).toBe('FORBIDDEN');
  259. }
  260. }
  261. function getErrorCode(err: any): string {
  262. return err.response.errors[0].extensions.code;
  263. }
  264. async function createAdministratorWithPermissions(
  265. code: string,
  266. permissions: Permission[],
  267. ): Promise<{ identifier: string; password: string }> {
  268. const roleResult = await client.query<CreateRole.Mutation, CreateRole.Variables>(CREATE_ROLE, {
  269. input: {
  270. code,
  271. description: '',
  272. permissions,
  273. },
  274. });
  275. const role = roleResult.createRole;
  276. const identifier = `${code}@${Math.random()
  277. .toString(16)
  278. .substr(2, 8)}`;
  279. const password = `test`;
  280. const adminResult = await client.query<CreateAdministrator.Mutation, CreateAdministrator.Variables>(
  281. CREATE_ADMINISTRATOR,
  282. {
  283. input: {
  284. emailAddress: identifier,
  285. firstName: code,
  286. lastName: 'Admin',
  287. password,
  288. roleIds: [role.id],
  289. },
  290. },
  291. );
  292. const admin = adminResult.createAdministrator;
  293. return {
  294. identifier,
  295. password,
  296. };
  297. }
  298. /**
  299. * A "sleep" function which allows the sendEmailFn time to get called.
  300. */
  301. function waitForSendEmailFn() {
  302. return new Promise(resolve => setTimeout(resolve, 10));
  303. }
  304. });
  305. describe('Expiring registration token', () => {
  306. const client = new TestClient();
  307. const server = new TestServer();
  308. beforeAll(async () => {
  309. const token = await server.init(
  310. {
  311. productCount: 1,
  312. customerCount: 1,
  313. },
  314. {
  315. emailOptions,
  316. authOptions: {
  317. verificationTokenDuration: '1ms',
  318. },
  319. },
  320. );
  321. await client.init();
  322. }, TEST_SETUP_TIMEOUT_MS);
  323. beforeEach(() => {
  324. sendEmailFn = jest.fn();
  325. });
  326. afterAll(async () => {
  327. await server.destroy();
  328. });
  329. it(
  330. 'attempting to verify after token has expired throws',
  331. assertThrowsWithMessage(async () => {
  332. const verificationTokenPromise = getVerificationTokenPromise();
  333. const input: RegisterCustomerInput = {
  334. firstName: 'Barry',
  335. lastName: 'Wallace',
  336. emailAddress: 'barry.wallace@test.com',
  337. };
  338. const result1 = await client.query(REGISTER_ACCOUNT, { input });
  339. const verificationToken = await verificationTokenPromise;
  340. expect(result1.registerCustomerAccount).toBe(true);
  341. expect(sendEmailFn).toHaveBeenCalledTimes(1);
  342. expect(verificationToken).toBeDefined();
  343. await new Promise(resolve => setTimeout(resolve, 3));
  344. return client.query(VERIFY_EMAIL, {
  345. password: 'test',
  346. token: verificationToken,
  347. });
  348. }, `Verification token has expired. Use refreshCustomerVerification to send a new token.`),
  349. );
  350. });
  351. function getVerificationTokenPromise(): Promise<string> {
  352. return new Promise<string>(resolve => {
  353. sendEmailFn.mockImplementation(ctx => {
  354. resolve(ctx.event.user.verificationToken);
  355. });
  356. });
  357. }
  358. const REGISTER_ACCOUNT = gql`
  359. mutation Register($input: RegisterCustomerInput!) {
  360. registerCustomerAccount(input: $input)
  361. }
  362. `;
  363. const VERIFY_EMAIL = gql`
  364. mutation Verify($password: String!, $token: String!) {
  365. verifyCustomerAccount(password: $password, token: $token) {
  366. user {
  367. id
  368. identifier
  369. }
  370. }
  371. }
  372. `;
  373. const REFRESH_TOKEN = gql`
  374. mutation RefreshToken($emailAddress: String!) {
  375. refreshCustomerVerification(emailAddress: $emailAddress)
  376. }
  377. `;