|
| 1 | +'use strict'; |
| 2 | +const common = require('../../common'); |
| 3 | +if (!common.hasCrypto) |
| 4 | + common.skip('missing crypto'); |
| 5 | + |
| 6 | +const assert = require('assert'); |
| 7 | +const tmpdir = require('../../common/tmpdir'); |
| 8 | +const { spawnSync } = require('child_process'); |
| 9 | +const crypto = require('crypto'); |
| 10 | +const fs = require('fs'); |
| 11 | +const path = require('path'); |
| 12 | +const { pathToFileURL } = require('url'); |
| 13 | + |
| 14 | +tmpdir.refresh(); |
| 15 | + |
| 16 | +function hash(algo, body) { |
| 17 | + const h = crypto.createHash(algo); |
| 18 | + h.update(body); |
| 19 | + return h.digest('base64'); |
| 20 | +} |
| 21 | + |
| 22 | +const policyFilepath = path.join(tmpdir.path, 'policy'); |
| 23 | + |
| 24 | +const depFilepath = require.resolve(`./build/${common.buildType}/binding.node`); |
| 25 | +const depURL = pathToFileURL(depFilepath); |
| 26 | + |
| 27 | +const tmpdirURL = pathToFileURL(tmpdir.path); |
| 28 | +if (!tmpdirURL.pathname.endsWith('/')) { |
| 29 | + tmpdirURL.pathname += '/'; |
| 30 | +} |
| 31 | + |
| 32 | +const depBody = fs.readFileSync(depURL); |
| 33 | +function writePolicy(...resources) { |
| 34 | + const manifest = { resources: {} }; |
| 35 | + for (const { url, integrity } of resources) { |
| 36 | + manifest.resources[url] = { integrity }; |
| 37 | + } |
| 38 | + fs.writeFileSync(policyFilepath, JSON.stringify(manifest, null, 2)); |
| 39 | +} |
| 40 | + |
| 41 | + |
| 42 | +function test(shouldFail, resources) { |
| 43 | + writePolicy(...resources); |
| 44 | + const { status, stdout, stderr } = spawnSync(process.execPath, [ |
| 45 | + '--experimental-policy', |
| 46 | + policyFilepath, |
| 47 | + depFilepath |
| 48 | + ]); |
| 49 | + |
| 50 | + console.log(stdout.toString(), stderr.toString()); |
| 51 | + if (shouldFail) { |
| 52 | + assert.notStrictEqual(status, 0); |
| 53 | + } else { |
| 54 | + assert.strictEqual(status, 0); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +test(false, [{ |
| 59 | + url: depURL, |
| 60 | + integrity: `sha256-${hash('sha256', depBody)}` |
| 61 | +}]); |
| 62 | +test(true, [{ |
| 63 | + url: depURL, |
| 64 | + integrity: `sha256akjsalkjdlaskjdk-${hash('sha256', depBody)}` |
| 65 | +}]); |
0 commit comments