Skip to content

Commit b050c65

Browse files
d3lmrichardlau
authored andcommitted
src: add option to disable loading native addons
Backport-PR-URL: #40094 PR-URL: #39977 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Bradley Farias <bradley.meck@gmail.com> Reviewed-By: Guy Bedford <guybedford@gmail.com> Reviewed-By: Michael Dawson <midawson@redhat.com>
1 parent 2755d39 commit b050c65

23 files changed

+274
-9
lines changed

doc/api/cli.md

+10
Original file line numberDiff line numberDiff line change
@@ -587,6 +587,15 @@ added: v7.10.0
587587

588588
This option is a no-op. It is kept for compatibility.
589589

590+
### `--no-addons`
591+
<!-- YAML
592+
added: REPLACEME
593+
-->
594+
595+
Disable the `node-addons` exports condition as well as disable loading
596+
native addons. When `--no-addons` is specified, calling `process.dlopen` or
597+
requiring a native C++ addon will fail and throw an exception.
598+
590599
### `--no-deprecation`
591600
<!-- YAML
592601
added: v0.8.0
@@ -1357,6 +1366,7 @@ Node.js options that are allowed are:
13571366
* `--inspect`
13581367
* `--max-http-header-size`
13591368
* `--napi-modules`
1369+
* `--no-addons`
13601370
* `--no-deprecation`
13611371
* `--no-force-async-hooks-checks`
13621372
* `--no-warnings`

doc/api/errors.md

+9
Original file line numberDiff line numberDiff line change
@@ -876,6 +876,14 @@ An unknown cipher was specified.
876876
An unknown Diffie-Hellman group name was given. See
877877
[`crypto.getDiffieHellman()`][] for a list of valid group names.
878878

879+
<a id="ERR_DLOPEN_DISABLED"></a>
880+
### `ERR_DLOPEN_DISABLED`
881+
<!-- YAML
882+
added: REPLACEME
883+
-->
884+
885+
Loading native addons has been disabled using [`--no-addons`][].
886+
879887
<a id="ERR_DLOPEN_FAILED"></a>
880888
### `ERR_DLOPEN_FAILED`
881889
<!-- YAML
@@ -2599,6 +2607,7 @@ closed.
25992607
[`'uncaughtException'`]: process.md#process_event_uncaughtexception
26002608
[`--disable-proto=throw`]: cli.md#cli_disable_proto_mode
26012609
[`--force-fips`]: cli.md#cli_force_fips
2610+
[`--no-addons`]: cli.md#cli_no_addons
26022611
[`Class: assert.AssertionError`]: assert.md#assert_class_assert_assertionerror
26032612
[`ERR_INVALID_ARG_TYPE`]: #ERR_INVALID_ARG_TYPE
26042613
[`EventEmitter`]: events.md#events_class_eventemitter

doc/api/packages.md

+16-4
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,11 @@ Node.js implements the following conditions:
477477
* `"node"` - matches for any Node.js environment. Can be a CommonJS or ES
478478
module file. _This condition should always come after `"import"` or
479479
`"require"`._
480+
* `"node-addons"` - similar to `"node"` and matches for any Node.js environment.
481+
This condition can be used to provide an entry point which uses native C++
482+
addons as opposed to an entry point which is more universal and doesn't rely
483+
on native addons. This condition can be disabled via the
484+
[`--no-addons` flag][].
480485
* `"default"` - the generic fallback that always matches. Can be a CommonJS
481486
or ES module file. _This condition should always come last._
482487

@@ -555,17 +560,23 @@ node --conditions=development main.js
555560
```
556561

557562
which would then resolve the `"development"` condition in package imports and
558-
exports, while resolving the existing `"node"`, `"default"`, `"import"`, and
559-
`"require"` conditions as appropriate.
563+
exports, while resolving the existing `"node"`, `"node-addons"`, `"default"`,
564+
`"import"`, and `"require"` conditions as appropriate.
560565

561566
Any number of custom conditions can be set with repeat flags.
562567

563568
### Conditions Definitions
564569

565-
The `"import"`, `"require"`, `"node"` and `"default"` conditions are defined
566-
and implemented in Node.js core,
570+
The `"import"`, `"require"`, `"node"`, `"node-addons"` and `"default"`
571+
conditions are defined and implemented in Node.js core,
567572
[as specified above](#packages_conditional_exports).
568573

574+
The `"node-addons"` condition can be used to provide an entry point which
575+
uses native C++ addons. However, this condition can be disabled via the
576+
[`--no-addons` flag][]. When using `"node-addons"`, it's recommended to treat
577+
`"default"` as an enhancement that provides a more universal entry point, e.g.
578+
using WebAssembly instead of a native addon.
579+
569580
Other condition strings are unknown to Node.js and thus ignored by default.
570581
Runtimes or tools other than Node.js can use them at their discretion.
571582

@@ -1161,6 +1172,7 @@ This field defines [subpath imports][] for the current package.
11611172
[`"main"`]: #packages_main
11621173
[`"name"`]: #packages_name
11631174
[`"type"`]: #packages_type
1175+
[`--no-addons` flag]: cli.md#cli_no_addons
11641176
[`ERR_PACKAGE_PATH_NOT_EXPORTED`]: errors.md#errors_err_package_path_not_exported
11651177
[`esm`]: https://github.com/standard-things/esm#readme
11661178
[`package.json`]: #packages_node_js_package_json_field_definitions

doc/node.1

+5
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,11 @@ Silence deprecation warnings.
282282
Disable runtime checks for `async_hooks`.
283283
These will still be enabled dynamically when `async_hooks` is enabled.
284284
.
285+
.It Fl -no-addons
286+
Disable the `node-addons` exports condition as well as disable loading native
287+
addons. When `--no-addons` is specified, calling `process.dlopen` or requiring
288+
a native C++ addon will fail and throw an exception.
289+
.
285290
.It Fl -no-warnings
286291
Silence all process warnings (including deprecations).
287292
.

lib/internal/modules/cjs/helpers.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,16 @@ let debug = require('internal/util/debuglog').debuglog('module', (fn) => {
2929
debug = fn;
3030
});
3131

32+
const noAddons = getOptionValue('--no-addons');
33+
const addonConditions = noAddons ? [] : ['node-addons'];
34+
3235
// TODO: Use this set when resolving pkg#exports conditions in loader.js.
33-
const cjsConditions = new SafeSet(['require', 'node', ...userConditions]);
36+
const cjsConditions = new SafeSet([
37+
'require',
38+
'node',
39+
...addonConditions,
40+
...userConditions,
41+
]);
3442

3543
function loadNativeModule(filename, request) {
3644
const mod = NativeModule.map.get(filename);

lib/internal/modules/esm/resolve.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,16 @@ const { Module: CJSModule } = require('internal/modules/cjs/loader');
5757

5858
const packageJsonReader = require('internal/modules/package_json_reader');
5959
const userConditions = getOptionValue('--conditions');
60-
const DEFAULT_CONDITIONS = ObjectFreeze(['node', 'import', ...userConditions]);
60+
const noAddons = getOptionValue('--no-addons');
61+
const addonConditions = noAddons ? [] : ['node-addons'];
62+
63+
const DEFAULT_CONDITIONS = ObjectFreeze([
64+
'node',
65+
'import',
66+
...addonConditions,
67+
...userConditions,
68+
]);
69+
6170
const DEFAULT_CONDITIONS_SET = new SafeSet(DEFAULT_CONDITIONS);
6271

6372
const pendingDeprecation = getOptionValue('--pending-deprecation');

src/env-inl.h

+5
Original file line numberDiff line numberDiff line change
@@ -890,6 +890,11 @@ inline bool Environment::is_main_thread() const {
890890
return worker_context() == nullptr;
891891
}
892892

893+
inline bool Environment::no_native_addons() const {
894+
return (flags_ & EnvironmentFlags::kNoNativeAddons) ||
895+
!options_->allow_native_addons;
896+
}
897+
893898
inline bool Environment::should_not_register_esm_loader() const {
894899
return flags_ & EnvironmentFlags::kNoRegisterESMLoader;
895900
}

src/env.h

+1
Original file line numberDiff line numberDiff line change
@@ -1054,6 +1054,7 @@ class Environment : public MemoryRetainer {
10541054
inline void set_has_serialized_options(bool has_serialized_options);
10551055

10561056
inline bool is_main_thread() const;
1057+
inline bool no_native_addons() const;
10571058
inline bool should_not_register_esm_loader() const;
10581059
inline bool owns_process_state() const;
10591060
inline bool owns_inspector() const;

src/node.h

+7-1
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,13 @@ enum Flags : uint64_t {
428428
// Set this flag to force hiding console windows when spawning child
429429
// processes. This is usually used when embedding Node.js in GUI programs on
430430
// Windows.
431-
kHideConsoleWindows = 1 << 5
431+
kHideConsoleWindows = 1 << 5,
432+
// Set this flag to disable loading native addons via `process.dlopen`.
433+
// This environment flag is especially important for worker threads
434+
// so that a worker thread can't load a native addon even if `execArgv`
435+
// is overwritten and `--no-addons` is not specified but was specified
436+
// for this Environment instance.
437+
kNoNativeAddons = 1 << 6
432438
};
433439
} // namespace EnvironmentFlags
434440

src/node_binding.cc

+6
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,12 @@ inline napi_addon_register_func GetNapiInitializerCallback(DLib* dlib) {
413413
// cache that's a plain C list or hash table that's shared across contexts?
414414
void DLOpen(const FunctionCallbackInfo<Value>& args) {
415415
Environment* env = Environment::GetCurrent(args);
416+
417+
if (env->no_native_addons()) {
418+
return THROW_ERR_DLOPEN_DISABLED(
419+
env, "Cannot load native addon because loading addons is disabled.");
420+
}
421+
416422
auto context = env->context();
417423

418424
CHECK_NULL(thread_local_modpending);

src/node_errors.h

+1
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ void OnFatalError(const char* location, const char* message);
3838
V(ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH, RangeError) \
3939
V(ERR_CRYPTO_UNKNOWN_CIPHER, Error) \
4040
V(ERR_CRYPTO_UNKNOWN_DH_GROUP, Error) \
41+
V(ERR_DLOPEN_DISABLED, Error) \
4142
V(ERR_DLOPEN_FAILED, Error) \
4243
V(ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE, Error) \
4344
V(ERR_INVALID_ADDRESS, Error) \

src/node_options.cc

+5
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,11 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() {
387387
&EnvironmentOptions::force_async_hooks_checks,
388388
kAllowedInEnvironment,
389389
true);
390+
AddOption("--addons",
391+
"disable loading native addons",
392+
&EnvironmentOptions::allow_native_addons,
393+
kAllowedInEnvironment,
394+
true);
390395
AddOption("--warnings",
391396
"silence all process warnings",
392397
&EnvironmentOptions::warnings,

src/node_options.h

+1
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ class EnvironmentOptions : public Options {
122122
uint64_t max_http_header_size = 16 * 1024;
123123
bool deprecation = true;
124124
bool force_async_hooks_checks = true;
125+
bool allow_native_addons = true;
125126
bool warnings = true;
126127
bool force_context_aware = false;
127128
bool pending_deprecation = false;

src/node_worker.cc

+2
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,8 @@ void Worker::New(const FunctionCallbackInfo<Value>& args) {
607607
worker->environment_flags_ |= EnvironmentFlags::kTrackUnmanagedFds;
608608
if (env->hide_console_windows())
609609
worker->environment_flags_ |= EnvironmentFlags::kHideConsoleWindows;
610+
if (env->no_native_addons())
611+
worker->environment_flags_ |= EnvironmentFlags::kNoNativeAddons;
610612
}
611613

612614
void Worker::StartThread(const FunctionCallbackInfo<Value>& args) {

test/addons/no-addons/binding.gyp

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
'targets': [
3+
{
4+
'target_name': 'binding',
5+
'sources': [ '../hello-world/binding.cc' ],
6+
'includes': ['../common.gypi'],
7+
}
8+
]
9+
}

test/addons/no-addons/test-worker.js

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// Flags: --no-addons
2+
3+
'use strict';
4+
5+
const common = require('../../common');
6+
const assert = require('assert');
7+
const path = require('path');
8+
const { Worker } = require('worker_threads');
9+
10+
const binding = path.resolve(__dirname, `./build/${common.buildType}/binding`);
11+
12+
const assertError = (error) => {
13+
assert.strictEqual(error.code, 'ERR_DLOPEN_DISABLED');
14+
assert.strictEqual(
15+
error.message,
16+
'Cannot load native addon because loading addons is disabled.'
17+
);
18+
};
19+
20+
{
21+
// Flags should be inherited
22+
const worker = new Worker(`require(${JSON.stringify(binding)})`, {
23+
eval: true,
24+
});
25+
26+
worker.on('error', common.mustCall(assertError));
27+
}
28+
29+
{
30+
// Should throw when using `process.dlopen` directly
31+
const worker = new Worker(
32+
`process.dlopen({ exports: {} }, ${JSON.stringify(binding)});`,
33+
{
34+
eval: true,
35+
}
36+
);
37+
38+
worker.on('error', common.mustCall(assertError));
39+
}
40+
41+
{
42+
// Explicitly pass `--no-addons`
43+
const worker = new Worker(`require(${JSON.stringify(binding)})`, {
44+
eval: true,
45+
execArgv: ['--no-addons'],
46+
});
47+
48+
worker.on('error', common.mustCall(assertError));
49+
}
50+
51+
{
52+
// If `execArgv` is overwritten it should still fail to load addons
53+
const worker = new Worker(`require(${JSON.stringify(binding)})`, {
54+
eval: true,
55+
execArgv: [],
56+
});
57+
58+
worker.on('error', common.mustCall(assertError));
59+
}

test/addons/no-addons/test.js

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Flags: --no-addons
2+
3+
'use strict';
4+
5+
const common = require('../../common');
6+
const assert = require('assert');
7+
8+
const bindingPath = require.resolve(`./build/${common.buildType}/binding`);
9+
10+
const assertError = (error) => {
11+
assert(error instanceof Error);
12+
assert.strictEqual(error.code, 'ERR_DLOPEN_DISABLED');
13+
assert.strictEqual(
14+
error.message,
15+
'Cannot load native addon because loading addons is disabled.'
16+
);
17+
};
18+
19+
{
20+
let threw = false;
21+
22+
try {
23+
require(bindingPath);
24+
} catch (error) {
25+
assertError(error);
26+
threw = true;
27+
}
28+
29+
assert(threw);
30+
}
31+
32+
{
33+
let threw = false;
34+
35+
try {
36+
process.dlopen({ exports: {} }, bindingPath);
37+
} catch (error) {
38+
assertError(error);
39+
threw = true;
40+
}
41+
42+
assert(threw);
43+
}

test/es-module/test-esm-no-addons.mjs

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { mustCall } from '../common/index.mjs';
2+
import { Worker, isMainThread } from 'worker_threads';
3+
import assert from 'assert';
4+
import { fileURLToPath } from 'url';
5+
import { requireFixture, importFixture } from '../fixtures/pkgexports.mjs';
6+
7+
if (isMainThread) {
8+
const tests = [[], ['--no-addons']];
9+
10+
for (const execArgv of tests) {
11+
new Worker(fileURLToPath(import.meta.url), { execArgv });
12+
}
13+
} else {
14+
[requireFixture, importFixture].forEach((loadFixture) => {
15+
loadFixture('pkgexports/no-addons').then(
16+
mustCall((module) => {
17+
const message = module.default;
18+
19+
if (process.execArgv.length === 0) {
20+
assert.strictEqual(message, 'using native addons');
21+
} else {
22+
assert.strictEqual(message, 'not using native addons');
23+
}
24+
})
25+
);
26+
});
27+
}

test/fixtures/es-module-loaders/loader-with-custom-condition.mjs

+8-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
1-
import {ok, deepStrictEqual} from 'assert';
1+
import { ok, deepStrictEqual } from 'assert';
22

33
export async function resolve(specifier, context, defaultResolve) {
44
ok(Array.isArray(context.conditions), 'loader receives conditions array');
5-
deepStrictEqual([...context.conditions].sort(), ['import', 'node']);
5+
6+
deepStrictEqual([...context.conditions].sort(), [
7+
'import',
8+
'node',
9+
'node-addons',
10+
]);
11+
612
return defaultResolve(specifier, {
713
...context,
814
conditions: ['custom-condition', ...context.conditions],

test/fixtures/node_modules/pkgexports/addons-entry.js

+3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

test/fixtures/node_modules/pkgexports/no-addons-entry.js

+3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)