auth.e2e-spec.ts 14 KB

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