Skip to content

Commit 60d0d3d

Browse files
authored
fix(allowScripts): close three enforcement gaps (npm#9652)
Three allowScripts (install-script policy) fixes: - Version-pinned deny fails closed when the lockfile omits `resolved`. - `npm link <pkg>` gates the global install of a missing package. - Regression test: bundled-dep scripts stay blocked under the gate.
1 parent c4e5356 commit 60d0d3d

5 files changed

Lines changed: 165 additions & 7 deletions

File tree

‎lib/commands/link.js‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const pkgJson = require('@npmcli/package-json')
55
const semver = require('semver')
66
const reifyFinish = require('../utils/reify-finish.js')
77
const resolveAllowScripts = require('../utils/resolve-allow-scripts.js')
8+
const strictAllowScriptsPreflight = require('../utils/strict-allow-scripts-preflight.js')
89
const { patchRelaxOpts } = require('../utils/cli-only-flag.js')
910
const ArboristWorkspaceCmd = require('../arborist-cmd.js')
1011

@@ -69,13 +70,17 @@ class Link extends ArboristWorkspaceCmd {
6970
// load current packages from the global space, and then add symlinks installs locally
7071
const globalTop = resolve(this.npm.globalDir, '..')
7172
const Arborist = require('@npmcli/arborist')
73+
// Resolve the policy up front so it also gates the global install of
74+
// missing packages, not just the local link.
75+
const { policy: allowScriptsPolicy } = await resolveAllowScripts(this.npm)
7276
const globalOpts = {
7377
...this.npm.flatOptions,
7478
...patchRelaxOpts(this.npm.config),
7579
Arborist,
7680
path: globalTop,
7781
global: true,
7882
prune: false,
83+
allowScripts: allowScriptsPolicy,
7984
}
8085
const globalArb = new Arborist(globalOpts)
8186

@@ -88,10 +93,17 @@ class Link extends ArboristWorkspaceCmd {
8893
// any extra arg that is missing from the current global space should be reified there first
8994
const missing = this.missingArgsFromTree(globals, args)
9095
if (missing.length) {
91-
await globalArb.reify({
96+
const globalReifyOpts = {
9297
...globalOpts,
9398
add: missing,
99+
}
100+
// Gate the global install with the same preflight as `npm install`.
101+
await strictAllowScriptsPreflight({
102+
arb: globalArb,
103+
npm: this.npm,
104+
idealTreeOpts: globalReifyOpts,
94105
})
106+
await globalArb.reify(globalReifyOpts)
95107
}
96108

97109
// get a list of module names that should be linked in the local prefix
@@ -118,7 +130,6 @@ class Link extends ArboristWorkspaceCmd {
118130
)
119131
// create a new arborist instance for the local prefix and
120132
// reify all the pending names as symlinks there
121-
const { policy: allowScriptsPolicy } = await resolveAllowScripts(this.npm)
122133
const localArb = new Arborist({
123134
...this.npm.flatOptions,
124135
...patchRelaxOpts(this.npm.config),

‎test/lib/commands/link.js‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,3 +592,73 @@ t.test('link threads allowScripts policy through to arborist', async t => {
592592
t.strictSame(localOpts.allowScripts, { canvas: true },
593593
'local arborist opts.allowScripts populated from package.json')
594594
})
595+
596+
t.test('link threads allowScripts policy to the global install', async t => {
597+
const capturedOpts = []
598+
const FakeArborist = function (opts) {
599+
capturedOpts.push(opts)
600+
this.options = opts
601+
this.actualTree = { inventory: new Map() }
602+
}
603+
FakeArborist.prototype.loadActual = async () => ({ isLink: false, children: new Map() })
604+
FakeArborist.prototype.reify = async () => {}
605+
606+
const mock = await mockNpm(t, {
607+
command: 'link',
608+
prefixDir: {
609+
'package.json': JSON.stringify({
610+
name: 'host',
611+
version: '1.0.0',
612+
allowScripts: { canvas: true },
613+
}),
614+
},
615+
mocks: {
616+
'@npmcli/arborist': FakeArborist,
617+
'{LIB}/utils/reify-finish.js': async () => {},
618+
},
619+
})
620+
await mock.npm.exec('link', ['canvas'])
621+
// the global Arborist is constructed first; its missing-package install
622+
// must carry the project policy.
623+
t.strictSame(capturedOpts[0].allowScripts, { canvas: true },
624+
'global arborist opts.allowScripts populated from package.json')
625+
})
626+
627+
t.test('link runs the strict-allow-scripts preflight before the global install', async t => {
628+
// The mocked preflight stands in for strict mode finding an uncovered
629+
// script. It must run and throw before the global reify.
630+
const calls = []
631+
const FakeArborist = function (opts) {
632+
this.options = opts
633+
this.actualTree = { inventory: new Map() }
634+
}
635+
FakeArborist.prototype.loadActual = async () => ({ isLink: false, children: new Map() })
636+
FakeArborist.prototype.reify = async () => {
637+
calls.push('reify')
638+
}
639+
640+
const mock = await mockNpm(t, {
641+
command: 'link',
642+
prefixDir: {
643+
'package.json': JSON.stringify({
644+
name: 'host',
645+
version: '1.0.0',
646+
}),
647+
},
648+
mocks: {
649+
'@npmcli/arborist': FakeArborist,
650+
'{LIB}/utils/reify-finish.js': async () => {},
651+
'{LIB}/utils/strict-allow-scripts-preflight.js': async () => {
652+
calls.push('preflight')
653+
throw Object.assign(new Error('blocked'), { code: 'ESTRICTALLOWSCRIPTS' })
654+
},
655+
},
656+
})
657+
await t.rejects(
658+
mock.npm.exec('link', ['canvas']),
659+
{ code: 'ESTRICTALLOWSCRIPTS' },
660+
'the strict preflight blocks the link'
661+
)
662+
t.strictSame(calls, ['preflight'],
663+
'preflight ran and the global reify never executed')
664+
})

‎workspaces/arborist/lib/script-allowed.js‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,9 @@ const isScriptAllowed = (node, policy) => {
4343
let anyDeny = false
4444

4545
for (const [key, value] of Object.entries(policy)) {
46-
if (!matches(node, key)) {
46+
// Pass deny intent so matchRegistry can fail closed on an unverifiable
47+
// version: a deny still blocks, an allow stays refused.
48+
if (!matches(node, key, value === false)) {
4749
continue
4850
}
4951
if (value === false) {
@@ -66,7 +68,7 @@ const isScriptAllowed = (node, policy) => {
6668
return null
6769
}
6870

69-
const matches = (node, key) => {
71+
const matches = (node, key, failClosed) => {
7072
let parsed
7173
try {
7274
parsed = npa(key)
@@ -78,7 +80,7 @@ const matches = (node, key) => {
7880
case 'tag':
7981
case 'range':
8082
case 'version':
81-
return matchRegistry(node, parsed)
83+
return matchRegistry(node, parsed, failClosed)
8284
case 'git':
8385
return matchGit(node, parsed)
8486
case 'file':
@@ -132,7 +134,7 @@ const resolvedSourceSpecs = (node) => {
132134
return specs
133135
}
134136

135-
const matchRegistry = (node, parsed) => {
137+
const matchRegistry = (node, parsed, failClosed) => {
136138
// If this node is not a registry dep, refuse the match. A registry-style
137139
// key (`pkg`, `pkg@1`, `pkg@1 || 2`) must not match a tarball or git node
138140
// even if their names happen to coincide.
@@ -168,16 +170,25 @@ const matchRegistry = (node, parsed) => {
168170
if (parsed.fetchSpec === '*' || parsed.rawSpec === '' || parsed.rawSpec === '*') {
169171
return true
170172
}
171-
if (!trusted.version || !isExactVersionDisjunction(parsed.fetchSpec)) {
173+
if (!isExactVersionDisjunction(parsed.fetchSpec)) {
172174
return false
173175
}
176+
// Unverifiable version (omit-lockfile-registry-resolved): a deny blocks,
177+
// an allow is refused.
178+
if (!trusted.version) {
179+
return failClosed
180+
}
174181
return semver.satisfies(trusted.version, parsed.fetchSpec, { loose: true })
175182
}
176183

177184
// `version` is an exact pin like `[email protected]`.
178185
/* istanbul ignore else: parsed.type at this point is always 'version';
179186
the istanbul-ignored fallback below handles the impossible case. */
180187
if (parsed.type === 'version') {
188+
// Unverifiable version: a deny blocks, an allow is refused.
189+
if (!trusted.version) {
190+
return failClosed
191+
}
181192
return trusted.version === parsed.fetchSpec
182193
}
183194

‎workspaces/arborist/test/arborist/rebuild.js‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,21 @@ t.test('do not run scripts if ignoreScripts=true', async t => {
118118
t.throws(() => fs.statSync(file), 'bundle build script not run')
119119
})
120120

121+
t.test('bundled deps cannot be allowlisted: gate blocks their scripts', async t => {
122+
// With the gate active, a bundled dep's script must not run even with an
123+
// explicit allow: scripts only run when isScriptAllowed returns true, and
124+
// bundled deps return null.
125+
const path = fixture(t, 'testing-rebuild-bundle-reified')
126+
const file = resolve(path, 'node_modules/@isaacs/testing-rebuild-bundle-a/node_modules/@isaacs/testing-rebuild-bundle-b/cwd')
127+
t.throws(() => fs.statSync(file), 'file not there already (gut check)')
128+
const arb = new Arborist({
129+
path,
130+
allowScripts: { '@isaacs/testing-rebuild-bundle-b': true },
131+
})
132+
await arb.rebuild()
133+
t.throws(() => fs.statSync(file), 'bundled dep postinstall did not run despite explicit allow')
134+
})
135+
121136
t.test('allowScripts deny entry skips the build set entry for that node', async t => {
122137
// Verifies the deny gate in #addToBuildSet: when `allowScripts` resolves
123138
// a node's policy to `false`, that node's scripts are skipped while

‎workspaces/arborist/test/script-allowed.js‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,57 @@ t.test('omitLockfileRegistryResolved: name-only match via edges; version-pinned
229229
t.end()
230230
})
231231

232+
t.test('omitLockfileRegistryResolved: version-pinned deny fails closed', t => {
233+
// No resolved URL means no trusted version. A version-pinned deny must
234+
// still block (fail closed); a matching allow stays refused.
235+
const omitted = () => ({
236+
name: 'evilpkg',
237+
packageName: 'evilpkg',
238+
version: '1.0.0',
239+
resolved: undefined,
240+
location: 'node_modules/evilpkg',
241+
edgesIn: new Set([{ name: 'evilpkg', spec: '^1.0.0' }]),
242+
})
243+
244+
// Exact-version deny: blocked.
245+
t.equal(isScriptAllowed(omitted(), { '[email protected]': false }), false,
246+
'version-pinned deny blocks even without a trusted version')
247+
// Exact-disjunction deny: blocked.
248+
t.equal(isScriptAllowed(omitted(), { '[email protected] || 2.0.0': false }), false,
249+
'exact-disjunction deny blocks even without a trusted version')
250+
// The exploit: name-only allow + version-pinned deny. Deny still wins.
251+
t.equal(isScriptAllowed(omitted(), { evilpkg: true, '[email protected]': false }), false,
252+
'deny wins over a name-only allow when the version is unverifiable')
253+
254+
// Allow stays strict: an unverifiable version is never authorized.
255+
t.equal(isScriptAllowed(omitted(), { '[email protected] || 2.0.0': true }), null,
256+
'exact-disjunction allow is refused without a trusted version')
257+
258+
// Name mismatch: fail-closed must not over-match a different package.
259+
t.equal(isScriptAllowed(omitted(), { '[email protected]': false }), null,
260+
'a version-pinned deny for a different name does not match')
261+
262+
t.end()
263+
})
264+
265+
t.test('omitLockfileRegistryResolved + alias: version-pinned deny fails closed', t => {
266+
// `"trusted": "npm:[email protected]"`, resolved omitted. A deny on the
267+
// underlying name must block; the alias name authorizes nothing.
268+
const aliasOmitted = {
269+
name: 'trusted',
270+
packageName: 'naughty',
271+
version: '1.0.0',
272+
resolved: undefined,
273+
location: 'node_modules/trusted',
274+
edgesIn: new Set([{ name: 'trusted', spec: 'npm:[email protected]' }]),
275+
}
276+
t.equal(isScriptAllowed(aliasOmitted, { '[email protected]': false }), false,
277+
'underlying-name version deny blocks the aliased package')
278+
t.equal(isScriptAllowed(aliasOmitted, { '[email protected]': false }), null,
279+
'alias-name version deny does not match the underlying package')
280+
t.end()
281+
})
282+
232283
t.test('omitLockfileRegistryResolved + alias: location is ignored; underlying name wins', t => {
233284
// Consumer's package.json has `"trusted": "npm:[email protected]"`. With
234285
// omitLockfileRegistryResolved, the resolved URL is absent. The install

0 commit comments

Comments
 (0)