Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: add test of policy about parse error #26873

Closed
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions test/parallel/test-policy-parse-integrity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
'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 += '/';
}

function test({ shouldFail = false, entry, resources = {} }) {
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,
entry,
]);
if (shouldFail) {
assert.notStrictEqual(status, 0);
} else {
assert.strictEqual(status, 0);
}
}

test({
shouldFail: false,
entry: depFilepath,
resources: {
[depURL]: {
body: depBody,
integrity: `sha256-${hash('sha256', depBody)}`,
},
},
});
test({
shouldFail: true,
entry: depFilepath,
resources: {
[depURL]: {
body: depBody,
integrity: `1sha256-${hash('sha256', depBody)}`,
},
},
});
test({
shouldFail: true,
entry: depFilepath,
resources: {
[depURL]: {
body: depBody,
integrity: 'hoge',
},
},
});
test({
shouldFail: true,
entry: depFilepath,
resources: {
[depURL]: {
body: depBody,
integrity: `sha256-${hash('sha256', depBody)}sha256-${hash(
'sha256',
depBody
)}`,
},
},
});