summaryrefslogtreecommitdiff
path: root/test/parallel/test-policy-parse-integrity.js
blob: 6fa954163906939a35ee98848de318037cc1b0ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';

const common = require('../common');
if (!common.hasCrypto) common.skip('missing crypto');

const tmpdir = require('../common/tmpdir');
const assert = require('assert');
const { spawnSync } = require('child_process');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const { pathToFileURL } = require('url');

tmpdir.refresh();

function hash(algo, body) {
  const h = crypto.createHash(algo);
  h.update(body);
  return h.digest('base64');
}

const policyFilepath = path.join(tmpdir.path, 'policy');

const parentFilepath = path.join(tmpdir.path, 'parent.js');
const parentBody = "require('./dep.js')";

const depFilepath = path.join(tmpdir.path, 'dep.js');
const depURL = pathToFileURL(depFilepath);
const depBody = '';

fs.writeFileSync(parentFilepath, parentBody);
fs.writeFileSync(depFilepath, depBody);

const tmpdirURL = pathToFileURL(tmpdir.path);
if (!tmpdirURL.pathname.endsWith('/')) {
  tmpdirURL.pathname += '/';
}

const packageFilepath = path.join(tmpdir.path, 'package.json');
const packageURL = pathToFileURL(packageFilepath);
const packageBody = '{"main": "dep.js"}';

function test({ shouldFail, integrity }) {
  const resources = {
    [packageURL]: {
      body: packageBody,
      integrity: `sha256-${hash('sha256', packageBody)}`
    },
    [depURL]: {
      body: depBody,
      integrity
    }
  };
  const manifest = {
    resources: {},
  };
  for (const [url, { body, integrity }] of Object.entries(resources)) {
    manifest.resources[url] = {
      integrity,
    };
    fs.writeFileSync(new URL(url, tmpdirURL.href), body);
  }
  fs.writeFileSync(policyFilepath, JSON.stringify(manifest, null, 2));
  const { status } = spawnSync(process.execPath, [
    '--experimental-policy',
    policyFilepath,
    depFilepath
  ]);
  if (shouldFail) {
    assert.notStrictEqual(status, 0);
  } else {
    assert.strictEqual(status, 0);
  }
}

test({
  shouldFail: false,
  integrity: `sha256-${hash('sha256', depBody)}`,
});
test({
  shouldFail: true,
  integrity: `1sha256-${hash('sha256', depBody)}`,
});
test({
  shouldFail: true,
  integrity: 'hoge',
});
test({
  shouldFail: true,
  integrity: `sha256-${hash('sha256', depBody)}sha256-${hash(
    'sha256',
    depBody
  )}`,
});