1
0

asset-server-plugin.e2e-spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /* eslint-disable @typescript-eslint/no-non-null-assertion */
  2. import { ConfigService, mergeConfig } from '@vendure/core';
  3. import { AssetFragment } from '@vendure/core/e2e/graphql/generated-e2e-admin-types';
  4. import { createTestEnvironment } from '@vendure/testing';
  5. import { exec } from 'child_process';
  6. import fs from 'fs-extra';
  7. import gql from 'graphql-tag';
  8. import fetch from 'node-fetch';
  9. import path from 'path';
  10. import { afterAll, beforeAll, describe, expect, it } from 'vitest';
  11. import { initialData } from '../../../e2e-common/e2e-initial-data';
  12. import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config';
  13. import { AssetServerPlugin } from '../src/plugin';
  14. import {
  15. CreateAssetsMutation,
  16. DeleteAssetMutation,
  17. DeleteAssetMutationVariables,
  18. DeletionResult,
  19. } from './graphql/generated-e2e-asset-server-plugin-types';
  20. const TEST_ASSET_DIR = 'test-assets';
  21. const IMAGE_BASENAME = 'derick-david-409858-unsplash';
  22. describe('AssetServerPlugin', () => {
  23. let asset: AssetFragment;
  24. const sourceFilePath = path.join(__dirname, TEST_ASSET_DIR, `source/b6/${IMAGE_BASENAME}.jpg`);
  25. const previewFilePath = path.join(__dirname, TEST_ASSET_DIR, `preview/71/${IMAGE_BASENAME}__preview.jpg`);
  26. const { server, adminClient, shopClient } = createTestEnvironment(
  27. mergeConfig(testConfig(), {
  28. // logger: new DefaultLogger({ level: LogLevel.Info }),
  29. plugins: [
  30. AssetServerPlugin.init({
  31. assetUploadDir: path.join(__dirname, TEST_ASSET_DIR),
  32. route: 'assets',
  33. }),
  34. ],
  35. }),
  36. );
  37. beforeAll(async () => {
  38. await fs.emptyDir(path.join(__dirname, TEST_ASSET_DIR, 'source'));
  39. await fs.emptyDir(path.join(__dirname, TEST_ASSET_DIR, 'preview'));
  40. await fs.emptyDir(path.join(__dirname, TEST_ASSET_DIR, 'cache'));
  41. await server.init({
  42. initialData,
  43. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-empty.csv'),
  44. customerCount: 1,
  45. });
  46. await adminClient.asSuperAdmin();
  47. }, TEST_SETUP_TIMEOUT_MS);
  48. afterAll(async () => {
  49. await server.destroy();
  50. });
  51. it('names the Asset correctly', async () => {
  52. const filesToUpload = [path.join(__dirname, `fixtures/assets/${IMAGE_BASENAME}.jpg`)];
  53. const { createAssets }: CreateAssetsMutation = await adminClient.fileUploadMutation({
  54. mutation: CREATE_ASSETS,
  55. filePaths: filesToUpload,
  56. mapVariables: filePaths => ({
  57. input: filePaths.map(p => ({ file: null })),
  58. }),
  59. });
  60. asset = createAssets[0] as AssetFragment;
  61. expect(asset.name).toBe(`${IMAGE_BASENAME}.jpg`);
  62. });
  63. it('creates the expected asset files', async () => {
  64. expect(fs.existsSync(sourceFilePath)).toBe(true);
  65. expect(fs.existsSync(previewFilePath)).toBe(true);
  66. });
  67. it('serves the source file', async () => {
  68. const res = await fetch(`${asset.source}`);
  69. const responseBuffer = await res.buffer();
  70. const sourceFile = await fs.readFile(sourceFilePath);
  71. expect(Buffer.compare(responseBuffer, sourceFile)).toBe(0);
  72. });
  73. it('serves the untransformed preview file', async () => {
  74. const res = await fetch(`${asset.preview}`);
  75. const responseBuffer = await res.buffer();
  76. const previewFile = await fs.readFile(previewFilePath);
  77. expect(Buffer.compare(responseBuffer, previewFile)).toBe(0);
  78. });
  79. it('can handle non-latin filenames', async () => {
  80. const FILE_NAME_ZH = '白飯';
  81. const filesToUpload = [path.join(__dirname, `fixtures/assets/${FILE_NAME_ZH}.jpg`)];
  82. const { createAssets }: { createAssets: AssetFragment[] } = await adminClient.fileUploadMutation({
  83. mutation: CREATE_ASSETS,
  84. filePaths: filesToUpload,
  85. mapVariables: filePaths => ({
  86. input: filePaths.map(p => ({ file: null })),
  87. }),
  88. });
  89. expect(createAssets[0].name).toBe(`${FILE_NAME_ZH}.jpg`);
  90. expect(createAssets[0].source).toContain(`${FILE_NAME_ZH}.jpg`);
  91. const previewUrl = encodeURI(`${createAssets[0].preview}`);
  92. const res = await fetch(previewUrl);
  93. expect(res.status).toBe(200);
  94. const previewFilePathZH = path.join(
  95. __dirname,
  96. TEST_ASSET_DIR,
  97. `preview/3f/${FILE_NAME_ZH}__preview.jpg`,
  98. );
  99. const responseBuffer = await res.buffer();
  100. const previewFile = await fs.readFile(previewFilePathZH);
  101. expect(Buffer.compare(responseBuffer, previewFile)).toBe(0);
  102. });
  103. describe('caching', () => {
  104. const cacheDir = path.join(__dirname, TEST_ASSET_DIR, 'cache');
  105. const cacheFileDir = path.join(__dirname, TEST_ASSET_DIR, 'cache', 'preview', '71');
  106. it('cache initially empty', async () => {
  107. const files = await fs.readdir(cacheDir);
  108. expect(files.length).toBe(0);
  109. });
  110. it('creates cached image on first request', async () => {
  111. const res = await fetch(`${asset.preview}?preset=thumb`);
  112. const responseBuffer = await res.buffer();
  113. expect(fs.existsSync(cacheFileDir)).toBe(true);
  114. const files = await fs.readdir(cacheFileDir);
  115. expect(files.length).toBe(1);
  116. expect(files[0]).toContain(`${IMAGE_BASENAME}__preview`);
  117. const cachedFile = await fs.readFile(path.join(cacheFileDir, files[0]));
  118. // was the file returned the exact same file as is stored in the cache dir?
  119. expect(Buffer.compare(responseBuffer, cachedFile)).toBe(0);
  120. });
  121. it('does not create a new cached image on a second request', async () => {
  122. const res = await fetch(`${asset.preview}?preset=thumb`);
  123. const files = await fs.readdir(cacheFileDir);
  124. expect(files.length).toBe(1);
  125. });
  126. it('does not create a new cached image for an untransformed image', async () => {
  127. const res = await fetch(`${asset.preview}`);
  128. const files = await fs.readdir(cacheFileDir);
  129. expect(files.length).toBe(1);
  130. });
  131. it('does not create a new cached image for an invalid preset', async () => {
  132. const res = await fetch(`${asset.preview}?preset=invalid`);
  133. const files = await fs.readdir(cacheFileDir);
  134. expect(files.length).toBe(1);
  135. const previewFile = await fs.readFile(previewFilePath);
  136. const responseBuffer = await res.buffer();
  137. expect(Buffer.compare(responseBuffer, previewFile)).toBe(0);
  138. });
  139. it('does not create a new cached image if cache=false', async () => {
  140. const res = await fetch(`${asset.preview}?preset=tiny&cache=false`);
  141. const files = await fs.readdir(cacheFileDir);
  142. expect(files.length).toBe(1);
  143. });
  144. it('creates a new cached image if cache=true', async () => {
  145. const res = await fetch(`${asset.preview}?preset=tiny&cache=true`);
  146. const files = await fs.readdir(cacheFileDir);
  147. expect(files.length).toBe(2);
  148. });
  149. });
  150. describe('unexpected input', () => {
  151. it('does not error on non-integer width', async () => {
  152. return fetch(`${asset.preview}?w=10.5`);
  153. });
  154. it('does not error on non-integer height', async () => {
  155. return fetch(`${asset.preview}?h=10.5`);
  156. });
  157. // https://github.com/vendure-ecommerce/vendure/security/advisories/GHSA-r9mq-3c9r-fmjq
  158. describe('path traversal', () => {
  159. function curlWithPathAsIs(url: string) {
  160. return new Promise<string>((resolve, reject) => {
  161. // We use curl here rather than node-fetch or any other fetch-type function because
  162. // those will automatically perform path normalization which will mask the path traversal
  163. return exec(`curl --path-as-is ${url}`, (err, stdout, stderr) => {
  164. if (err) {
  165. reject(err);
  166. }
  167. resolve(stdout);
  168. });
  169. });
  170. }
  171. function testPathTraversalOnUrl(urlPath: string) {
  172. return async () => {
  173. const port = server.app.get(ConfigService).apiOptions.port;
  174. const result = await curlWithPathAsIs(`http://localhost:${port}/assets${urlPath}`);
  175. expect(result).not.toContain('@vendure/asset-server-plugin');
  176. expect(result.toLowerCase()).toContain('resource not found');
  177. };
  178. }
  179. it('blocks path traversal 1', testPathTraversalOnUrl(`/../../package.json`));
  180. it('blocks path traversal 2', testPathTraversalOnUrl(`/foo/../../../package.json`));
  181. it('blocks path traversal 3', testPathTraversalOnUrl(`/foo/../../../foo/../package.json`));
  182. it('blocks path traversal 4', testPathTraversalOnUrl(`/%2F..%2F..%2Fpackage.json`));
  183. it('blocks path traversal 5', testPathTraversalOnUrl(`/%2E%2E/%2E%2E/package.json`));
  184. it('blocks path traversal 6', testPathTraversalOnUrl(`/..//..//package.json`));
  185. it('blocks path traversal 7', testPathTraversalOnUrl(`/.%2F.%2F.%2Fpackage.json`));
  186. it('blocks path traversal 8', testPathTraversalOnUrl(`/..\\\\..\\\\package.json`));
  187. it('blocks path traversal 9', testPathTraversalOnUrl(`/\\\\\\..\\\\\\..\\\\\\package.json`));
  188. });
  189. });
  190. describe('deletion', () => {
  191. it('deleting Asset deletes binary file', async () => {
  192. const { deleteAsset } = await adminClient.query<
  193. DeleteAssetMutation,
  194. DeleteAssetMutationVariables
  195. >(DELETE_ASSET, {
  196. input: {
  197. assetId: asset.id,
  198. force: true,
  199. },
  200. });
  201. expect(deleteAsset.result).toBe(DeletionResult.DELETED);
  202. expect(fs.existsSync(sourceFilePath)).toBe(false);
  203. expect(fs.existsSync(previewFilePath)).toBe(false);
  204. });
  205. });
  206. describe('MIME type detection', () => {
  207. let testImages: AssetFragment[] = [];
  208. async function testMimeTypeOfAssetWithExt(ext: string, expectedMimeType: string) {
  209. const testImage = testImages.find(i => i.source.endsWith(ext))!;
  210. const result = await fetch(testImage.source);
  211. const contentType = result.headers.get('Content-Type');
  212. expect(contentType).toBe(expectedMimeType);
  213. }
  214. beforeAll(async () => {
  215. const formats = ['gif', 'jpg', 'png', 'svg', 'tiff', 'webp'];
  216. const filesToUpload = formats.map(ext => path.join(__dirname, `fixtures/assets/test.${ext}`));
  217. const { createAssets }: CreateAssetsMutation = await adminClient.fileUploadMutation({
  218. mutation: CREATE_ASSETS,
  219. filePaths: filesToUpload,
  220. mapVariables: filePaths => ({
  221. input: filePaths.map(p => ({ file: null })),
  222. }),
  223. });
  224. testImages = createAssets as AssetFragment[];
  225. });
  226. it('gif', async () => {
  227. await testMimeTypeOfAssetWithExt('gif', 'image/gif');
  228. });
  229. it('jpg', async () => {
  230. await testMimeTypeOfAssetWithExt('jpg', 'image/jpeg');
  231. });
  232. it('png', async () => {
  233. await testMimeTypeOfAssetWithExt('png', 'image/png');
  234. });
  235. it('svg', async () => {
  236. await testMimeTypeOfAssetWithExt('svg', 'image/svg+xml');
  237. });
  238. it('tiff', async () => {
  239. await testMimeTypeOfAssetWithExt('tiff', 'image/tiff');
  240. });
  241. it('webp', async () => {
  242. await testMimeTypeOfAssetWithExt('webp', 'image/webp');
  243. });
  244. });
  245. // https://github.com/vendure-ecommerce/vendure/issues/1563
  246. it('falls back to binary preview if image file cannot be processed', async () => {
  247. const filesToUpload = [path.join(__dirname, 'fixtures/assets/bad-image.jpg')];
  248. const { createAssets }: CreateAssetsMutation = await adminClient.fileUploadMutation({
  249. mutation: CREATE_ASSETS,
  250. filePaths: filesToUpload,
  251. mapVariables: filePaths => ({
  252. input: filePaths.map(p => ({ file: null })),
  253. }),
  254. });
  255. expect(createAssets.length).toBe(1);
  256. expect(createAssets[0].name).toBe('bad-image.jpg');
  257. });
  258. });
  259. export const CREATE_ASSETS = gql`
  260. mutation CreateAssets($input: [CreateAssetInput!]!) {
  261. createAssets(input: $input) {
  262. ... on Asset {
  263. id
  264. name
  265. source
  266. preview
  267. focalPoint {
  268. x
  269. y
  270. }
  271. }
  272. }
  273. }
  274. `;
  275. export const DELETE_ASSET = gql`
  276. mutation DeleteAsset($input: DeleteAssetInput!) {
  277. deleteAsset(input: $input) {
  278. result
  279. }
  280. }
  281. `;