auth.e2e-spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. /* tslint:disable:no-non-null-assertion */
  2. import { SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD } from '@vendure/common/lib/shared-constants';
  3. import { createTestEnvironment } from '@vendure/testing';
  4. import { DocumentNode } from 'graphql';
  5. import gql from 'graphql-tag';
  6. import path from 'path';
  7. import { initialData } from '../../../e2e-common/e2e-initial-data';
  8. import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config';
  9. import { ProtectedFieldsPlugin, transactions } from './fixtures/test-plugins/with-protected-field-resolver';
  10. import {
  11. CreateAdministrator,
  12. CreateCustomerGroup,
  13. CreateRole,
  14. ErrorCode,
  15. GetCustomerList,
  16. GetTaxRates,
  17. Me,
  18. MutationCreateProductArgs,
  19. MutationLoginArgs,
  20. MutationUpdateProductArgs,
  21. Permission,
  22. UpdateTaxRate,
  23. } from './graphql/generated-e2e-admin-types';
  24. import {
  25. ATTEMPT_LOGIN,
  26. CREATE_ADMINISTRATOR,
  27. CREATE_CUSTOMER_GROUP,
  28. CREATE_PRODUCT,
  29. CREATE_ROLE,
  30. GET_CUSTOMER_LIST,
  31. GET_PRODUCT_LIST,
  32. GET_TAX_RATES_LIST,
  33. ME,
  34. UPDATE_PRODUCT,
  35. UPDATE_TAX_RATE,
  36. } from './graphql/shared-definitions';
  37. import { assertThrowsWithMessage } from './utils/assert-throws-with-message';
  38. describe('Authorization & permissions', () => {
  39. const { server, adminClient, shopClient } = createTestEnvironment({
  40. ...testConfig,
  41. plugins: [ProtectedFieldsPlugin],
  42. });
  43. beforeAll(async () => {
  44. await server.init({
  45. initialData,
  46. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
  47. customerCount: 5,
  48. });
  49. await adminClient.asSuperAdmin();
  50. }, TEST_SETUP_TIMEOUT_MS);
  51. afterAll(async () => {
  52. await server.destroy();
  53. });
  54. describe('admin permissions', () => {
  55. describe('Anonymous user', () => {
  56. beforeAll(async () => {
  57. await adminClient.asAnonymousUser();
  58. });
  59. it(
  60. 'me is not permitted',
  61. assertThrowsWithMessage(async () => {
  62. await adminClient.query<Me.Query>(ME);
  63. }, 'You are not currently authorized to perform this action'),
  64. );
  65. it('can attempt login', async () => {
  66. await assertRequestAllowed<MutationLoginArgs>(ATTEMPT_LOGIN, {
  67. username: SUPER_ADMIN_USER_IDENTIFIER,
  68. password: SUPER_ADMIN_USER_PASSWORD,
  69. rememberMe: false,
  70. });
  71. });
  72. });
  73. describe('Customer user', () => {
  74. let customerEmailAddress: string;
  75. beforeAll(async () => {
  76. await adminClient.asSuperAdmin();
  77. const { customers } = await adminClient.query<GetCustomerList.Query>(GET_CUSTOMER_LIST);
  78. customerEmailAddress = customers.items[0].emailAddress;
  79. });
  80. it('cannot login', async () => {
  81. const result = await adminClient.asUserWithCredentials(customerEmailAddress, 'test');
  82. expect(result.errorCode).toBe(ErrorCode.INVALID_CREDENTIALS_ERROR);
  83. });
  84. });
  85. describe('ReadCatalog permission', () => {
  86. beforeAll(async () => {
  87. await adminClient.asSuperAdmin();
  88. const { identifier, password } = await createAdministratorWithPermissions('ReadCatalog', [
  89. Permission.ReadCatalog,
  90. ]);
  91. await adminClient.asUserWithCredentials(identifier, password);
  92. });
  93. it('me returns correct permissions', async () => {
  94. const { me } = await adminClient.query<Me.Query>(ME);
  95. expect(me!.channels[0].permissions).toEqual([
  96. Permission.Authenticated,
  97. Permission.ReadCatalog,
  98. ]);
  99. });
  100. it('can read', async () => {
  101. await assertRequestAllowed(GET_PRODUCT_LIST);
  102. });
  103. it('cannot update', async () => {
  104. await assertRequestForbidden<MutationUpdateProductArgs>(UPDATE_PRODUCT, {
  105. input: {
  106. id: '1',
  107. translations: [],
  108. },
  109. });
  110. });
  111. it('cannot create', async () => {
  112. await assertRequestForbidden<MutationCreateProductArgs>(CREATE_PRODUCT, {
  113. input: {
  114. translations: [],
  115. },
  116. });
  117. });
  118. });
  119. describe('CRUD on Customers permissions', () => {
  120. beforeAll(async () => {
  121. await adminClient.asSuperAdmin();
  122. const { identifier, password } = await createAdministratorWithPermissions('CRUDCustomer', [
  123. Permission.CreateCustomer,
  124. Permission.ReadCustomer,
  125. Permission.UpdateCustomer,
  126. Permission.DeleteCustomer,
  127. ]);
  128. await adminClient.asUserWithCredentials(identifier, password);
  129. });
  130. it('me returns correct permissions', async () => {
  131. const { me } = await adminClient.query<Me.Query>(ME);
  132. expect(me!.channels[0].permissions).toEqual([
  133. Permission.Authenticated,
  134. Permission.CreateCustomer,
  135. Permission.ReadCustomer,
  136. Permission.UpdateCustomer,
  137. Permission.DeleteCustomer,
  138. ]);
  139. });
  140. it('can create', async () => {
  141. await assertRequestAllowed(
  142. gql(`mutation CanCreateCustomer($input: CreateCustomerInput!) {
  143. createCustomer(input: $input) {
  144. ... on Customer {
  145. id
  146. }
  147. }
  148. }
  149. `),
  150. { input: { emailAddress: '', firstName: '', lastName: '' } },
  151. );
  152. });
  153. it('can read', async () => {
  154. await assertRequestAllowed(gql`
  155. query GetCustomerCount {
  156. customers {
  157. totalItems
  158. }
  159. }
  160. `);
  161. });
  162. });
  163. });
  164. describe('protected field resolvers', () => {
  165. let readCatalogAdmin: { identifier: string; password: string };
  166. let transactionsAdmin: { identifier: string; password: string };
  167. const GET_PRODUCT_WITH_TRANSACTIONS = `
  168. query GetProductWithTransactions($id: ID!) {
  169. product(id: $id) {
  170. id
  171. transactions {
  172. id
  173. amount
  174. description
  175. }
  176. }
  177. }
  178. `;
  179. beforeAll(async () => {
  180. await adminClient.asSuperAdmin();
  181. transactionsAdmin = await createAdministratorWithPermissions('Transactions', [
  182. Permission.ReadCatalog,
  183. transactions.Permission,
  184. ]);
  185. readCatalogAdmin = await createAdministratorWithPermissions('ReadCatalog', [
  186. Permission.ReadCatalog,
  187. ]);
  188. });
  189. it('protected field not resolved without permissions', async () => {
  190. await adminClient.asUserWithCredentials(readCatalogAdmin.identifier, readCatalogAdmin.password);
  191. try {
  192. const status = await adminClient.query(gql(GET_PRODUCT_WITH_TRANSACTIONS), { id: 'T_1' });
  193. fail(`Should have thrown`);
  194. } catch (e) {
  195. expect(getErrorCode(e)).toBe('FORBIDDEN');
  196. }
  197. });
  198. it('protected field is resolved with permissions', async () => {
  199. await adminClient.asUserWithCredentials(transactionsAdmin.identifier, transactionsAdmin.password);
  200. const { product } = await adminClient.query(gql(GET_PRODUCT_WITH_TRANSACTIONS), { id: 'T_1' });
  201. expect(product.id).toBe('T_1');
  202. expect(product.transactions).toEqual([
  203. { id: 'T_1', amount: 100, description: 'credit' },
  204. { id: 'T_2', amount: -50, description: 'debit' },
  205. ]);
  206. });
  207. // https://github.com/vendure-ecommerce/vendure/issues/730
  208. it('protects against deep query data leakage', async () => {
  209. await adminClient.asSuperAdmin();
  210. const { createCustomerGroup } = await adminClient.query<
  211. CreateCustomerGroup.Mutation,
  212. CreateCustomerGroup.Variables
  213. >(CREATE_CUSTOMER_GROUP, {
  214. input: {
  215. name: 'Test group',
  216. customerIds: ['T_1', 'T_2', 'T_3', 'T_4'],
  217. },
  218. });
  219. const taxRateName = `Standard Tax ${initialData.defaultZone}`;
  220. const { taxRates } = await adminClient.query<GetTaxRates.Query, GetTaxRates.Variables>(
  221. GET_TAX_RATES_LIST,
  222. {
  223. options: {
  224. filter: {
  225. name: { eq: taxRateName },
  226. },
  227. },
  228. },
  229. );
  230. const standardTax = taxRates.items[0];
  231. expect(standardTax.name).toBe(taxRateName);
  232. await adminClient.query<UpdateTaxRate.Mutation, UpdateTaxRate.Variables>(UPDATE_TAX_RATE, {
  233. input: {
  234. id: standardTax.id,
  235. customerGroupId: createCustomerGroup.id,
  236. },
  237. });
  238. try {
  239. const status = await shopClient.query(
  240. gql(`
  241. query DeepFieldResolutionTestQuery{
  242. product(id: "T_1") {
  243. variants {
  244. taxRateApplied {
  245. customerGroup {
  246. customers {
  247. items {
  248. id
  249. emailAddress
  250. }
  251. }
  252. }
  253. }
  254. }
  255. }
  256. }`),
  257. { id: 'T_1' },
  258. );
  259. fail(`Should have thrown`);
  260. } catch (e) {
  261. expect(getErrorCode(e)).toBe('FORBIDDEN');
  262. }
  263. });
  264. });
  265. async function assertRequestAllowed<V>(operation: DocumentNode, variables?: V) {
  266. try {
  267. const status = await adminClient.queryStatus(operation, variables);
  268. expect(status).toBe(200);
  269. } catch (e) {
  270. const errorCode = getErrorCode(e);
  271. if (!errorCode) {
  272. fail(`Unexpected failure: ${e}`);
  273. } else {
  274. fail(`Operation should be allowed, got status ${getErrorCode(e)}`);
  275. }
  276. }
  277. }
  278. async function assertRequestForbidden<V>(operation: DocumentNode, variables: V) {
  279. try {
  280. const status = await adminClient.query(operation, variables);
  281. fail(`Should have thrown`);
  282. } catch (e) {
  283. expect(getErrorCode(e)).toBe('FORBIDDEN');
  284. }
  285. }
  286. function getErrorCode(err: any): string {
  287. return err.response.errors[0].extensions.code;
  288. }
  289. async function createAdministratorWithPermissions(
  290. code: string,
  291. permissions: Permission[],
  292. ): Promise<{ identifier: string; password: string }> {
  293. const roleResult = await adminClient.query<CreateRole.Mutation, CreateRole.Variables>(CREATE_ROLE, {
  294. input: {
  295. code,
  296. description: '',
  297. permissions,
  298. },
  299. });
  300. const role = roleResult.createRole;
  301. const identifier = `${code}@${Math.random().toString(16).substr(2, 8)}`;
  302. const password = `test`;
  303. const adminResult = await adminClient.query<
  304. CreateAdministrator.Mutation,
  305. CreateAdministrator.Variables
  306. >(CREATE_ADMINISTRATOR, {
  307. input: {
  308. emailAddress: identifier,
  309. firstName: code,
  310. lastName: 'Admin',
  311. password,
  312. roleIds: [role.id],
  313. },
  314. });
  315. const admin = adminResult.createAdministrator;
  316. return {
  317. identifier,
  318. password,
  319. };
  320. }
  321. });