• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3const common = require('../common');
4if (!common.hasCrypto) common.skip('missing crypto');
5
6const tmpdir = require('../common/tmpdir');
7const assert = require('assert');
8const { spawnSync } = require('child_process');
9const crypto = require('crypto');
10const fs = require('fs');
11const path = require('path');
12const { pathToFileURL } = require('url');
13
14tmpdir.refresh();
15
16function hash(algo, body) {
17  const h = crypto.createHash(algo);
18  h.update(body);
19  return h.digest('base64');
20}
21
22const tmpdirPath = path.join(tmpdir.path, 'test-policy-parse-integrity');
23fs.rmdirSync(tmpdirPath, { maxRetries: 3, recursive: true });
24fs.mkdirSync(tmpdirPath, { recursive: true });
25
26const policyFilepath = path.join(tmpdirPath, 'policy');
27
28const parentFilepath = path.join(tmpdirPath, 'parent.js');
29const parentBody = "require('./dep.js')";
30
31const depFilepath = path.join(tmpdirPath, 'dep.js');
32const depURL = pathToFileURL(depFilepath);
33const depBody = '';
34
35fs.writeFileSync(parentFilepath, parentBody);
36fs.writeFileSync(depFilepath, depBody);
37
38const tmpdirURL = pathToFileURL(tmpdirPath);
39if (!tmpdirURL.pathname.endsWith('/')) {
40  tmpdirURL.pathname += '/';
41}
42
43const packageFilepath = path.join(tmpdirPath, 'package.json');
44const packageURL = pathToFileURL(packageFilepath);
45const packageBody = '{"main": "dep.js"}';
46
47function test({ shouldFail, integrity }) {
48  const resources = {
49    [packageURL]: {
50      body: packageBody,
51      integrity: `sha256-${hash('sha256', packageBody)}`
52    },
53    [depURL]: {
54      body: depBody,
55      integrity
56    }
57  };
58  const manifest = {
59    resources: {},
60  };
61  for (const [url, { body, integrity }] of Object.entries(resources)) {
62    manifest.resources[url] = {
63      integrity,
64    };
65    fs.writeFileSync(new URL(url, tmpdirURL.href), body);
66  }
67  fs.writeFileSync(policyFilepath, JSON.stringify(manifest, null, 2));
68  const { status } = spawnSync(process.execPath, [
69    '--experimental-policy',
70    policyFilepath,
71    depFilepath
72  ]);
73  if (shouldFail) {
74    assert.notStrictEqual(status, 0);
75  } else {
76    assert.strictEqual(status, 0);
77  }
78}
79
80test({
81  shouldFail: false,
82  integrity: `sha256-${hash('sha256', depBody)}`,
83});
84test({
85  shouldFail: true,
86  integrity: `1sha256-${hash('sha256', depBody)}`,
87});
88test({
89  shouldFail: true,
90  integrity: 'hoge',
91});
92test({
93  shouldFail: true,
94  integrity: `sha256-${hash('sha256', depBody)}sha256-${hash(
95    'sha256',
96    depBody
97  )}`,
98});
99