Skip to content

Commit 25abed7

Browse files
committed
src: read env files only from Node.js options
`--env-file` and `--env-file-if-exists` were looked up in every argument up to a literal `--`, including the ones that follow the script name. Those belong to the script, but the files they named were still opened and their `NODE_OPTIONS` applied. Find where the options of Node.js end with a throwaway parse and only look for env file flags before that point. The parse is shared with the config file reader and only runs when an env file flag is present. Assisted-By: OpenAI GPT-5.6 Sol <openai/gpt-5.6-sol> Signed-off-by: Paolo Insogna <paolo@cowtech.it>
1 parent 50ba1ec commit 25abed7

7 files changed

Lines changed: 167 additions & 53 deletions

File tree

‎doc/api/cli.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1367,6 +1367,9 @@ variables which configure Node.js][environment_variables], such as `NODE_OPTIONS
13671367
are parsed and applied. If the same variable is defined in the environment and
13681368
in the file, the value from the environment takes precedence.
13691369

1370+
The flag is only recognized before the script. Arguments after the script name
1371+
or after `--` are passed to the script and are not read as Node.js options.
1372+
13701373
You can pass multiple `--env-file` arguments. Subsequent files override
13711374
pre-existing variables defined in previous files.
13721375

‎doc/node.1‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -815,6 +815,8 @@ making them available to applications on \fBprocess.env\fR. The environment
815815
variables which configure Node.js, such as \fBNODE_OPTIONS\fR,
816816
are parsed and applied. If the same variable is defined in the environment and
817817
in the file, the value from the environment takes precedence.
818+
The flag is only recognized before the script. Arguments after the script name
819+
or after \fB--\fR are passed to the script and are not read as Node.js options.
818820
You can pass multiple \fB--env-file\fR arguments. Subsequent files override
819821
pre-existing variables defined in previous files.
820822
An error is thrown if the file does not exist.

‎src/node_config_file.cc‎

Lines changed: 1 addition & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -8,63 +8,19 @@
88

99
namespace node {
1010

11-
constexpr std::string_view kConfigFileFlag = "--config-file";
12-
// TODO(marco-ippolito): Remove these aliases in a semver-major.
13-
constexpr std::string_view kExperimentalConfigFileFlag =
14-
"--experimental-config-file";
15-
constexpr std::string_view kDefaultConfigFileFlag =
16-
"--experimental-default-config-file";
17-
constexpr std::string_view kDefaultConfigFileName = "node.config.json";
1811
constexpr std::string_view kSchemaField = "$schema";
1912

2013
inline bool HasEqualsPrefix(std::string_view arg, std::string_view flag) {
2114
return arg.size() > flag.size() && arg.starts_with(flag) &&
2215
arg[flag.size()] == '=';
2316
}
2417

25-
inline bool IsBareConfigFileFlag(std::string_view arg) {
26-
return arg == kConfigFileFlag || arg == kExperimentalConfigFileFlag ||
27-
arg == kDefaultConfigFileFlag;
28-
}
29-
3018
inline bool IsConfigFileFlag(std::string_view arg) {
3119
return IsBareConfigFileFlag(arg) || HasEqualsPrefix(arg, kConfigFileFlag) ||
3220
HasEqualsPrefix(arg, kExperimentalConfigFileFlag) ||
3321
HasEqualsPrefix(arg, kDefaultConfigFileFlag);
3422
}
3523

36-
inline std::string DefaultConfigFileArg() {
37-
return std::string(kConfigFileFlag) + "=" +
38-
std::string(kDefaultConfigFileName);
39-
}
40-
41-
// Returns the index of the first entry in `args` that is neither the program
42-
// name nor an option for Node.js itself. Everything from there on is the
43-
// script and its arguments, or follows `--`, so it must not be read as a
44-
// config file flag.
45-
size_t GetNodeOptionsEnd(const std::vector<std::string>& args) {
46-
// The bare flags take no value. Spell them out the way GetDataFromArgs()
47-
// does before the real parse, otherwise the parser would consume the next
48-
// argument as the path.
49-
std::vector<std::string> remaining;
50-
remaining.reserve(args.size());
51-
for (const std::string& arg : args) {
52-
remaining.push_back(IsBareConfigFileFlag(arg) ? DefaultConfigFileArg()
53-
: arg);
54-
}
55-
56-
// Parsing into throwaway options stops exactly where the real parse will.
57-
// Any errors are reported by the real parse later on.
58-
PerProcessOptions options;
59-
std::vector<std::string> v8_args;
60-
std::vector<std::string> errors;
61-
options_parser::Parse(
62-
&remaining, nullptr, &v8_args, &options, kDisallowedInEnvvar, &errors);
63-
64-
// `remaining` is left with the program name and the unparsed arguments.
65-
return args.size() - remaining.size() + 1;
66-
}
67-
6824
std::optional<std::string_view> ConfigReader::GetDataFromArgs(
6925
std::vector<std::string>* args) {
7026
std::optional<std::string_view> result;
@@ -75,7 +31,7 @@ std::optional<std::string_view> ConfigReader::GetDataFromArgs(
7531
return result;
7632
}
7733

78-
const size_t node_options_end = GetNodeOptionsEnd(*args);
34+
const size_t node_options_end = options_parser::GetNodeOptionsEnd(*args);
7935
for (size_t i = 1; i < node_options_end; ++i) {
8036
std::string& arg = (*args)[i];
8137

‎src/node_dotenv.cc‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
#include "node_dotenv.h"
2+
#include <algorithm>
23
#include <unordered_set>
34
#include "env-inl.h"
45
#include "node_file.h"
6+
#include "node_options.h"
57
#include "uv.h"
68

79
namespace node {
@@ -22,17 +24,31 @@ std::vector<Dotenv::env_file_data> Dotenv::GetDataFromArgs(
2224
const std::vector<std::string>& args) {
2325
const std::string_view optional_env_file_flag = "--env-file-if-exists";
2426

25-
const auto find_match = [](const std::string& arg) {
26-
return arg == "--" || arg == "--env-file" ||
27-
arg.starts_with("--env-file=") || arg == "--env-file-if-exists" ||
27+
const auto is_env_file_flag = [](const std::string& arg) {
28+
return arg == "--env-file" || arg.starts_with("--env-file=") ||
29+
arg == "--env-file-if-exists" ||
2830
arg.starts_with("--env-file-if-exists=");
2931
};
32+
const auto find_match = [&](const std::string& arg) {
33+
return arg == "--" || is_env_file_flag(arg);
34+
};
3035

3136
std::vector<Dotenv::env_file_data> env_files;
32-
// This will be an iterator, pointing to args.end() if no matches are found
33-
auto matched_arg = std::ranges::find_if(args, find_match);
37+
// Only pay for the extra parse when an env file flag might be present.
38+
if (args.empty() ||
39+
std::none_of(args.begin(), args.end(), is_env_file_flag)) {
40+
return env_files;
41+
}
42+
43+
// Only the options of Node.js itself are considered. The script and its
44+
// arguments are left alone.
45+
const auto options_begin = args.begin() + 1;
46+
const auto options_end =
47+
args.begin() + options_parser::GetNodeOptionsEnd(args);
48+
// This will be an iterator, pointing to options_end if no matches are found
49+
auto matched_arg = std::find_if(options_begin, options_end, find_match);
3450

35-
while (matched_arg != args.end()) {
51+
while (matched_arg != options_end) {
3652
if (*matched_arg == "--") {
3753
return env_files;
3854
}
@@ -51,7 +67,7 @@ std::vector<Dotenv::env_file_data> Dotenv::GetDataFromArgs(
5167
// `--env-file path`
5268
auto file_path = std::next(matched_arg);
5369

54-
if (file_path == args.end()) {
70+
if (file_path == options_end) {
5571
return env_files;
5672
}
5773

@@ -60,7 +76,7 @@ std::vector<Dotenv::env_file_data> Dotenv::GetDataFromArgs(
6076
env_files.push_back(env_file_data);
6177
}
6278

63-
matched_arg = std::find_if(++matched_arg, args.end(), find_match);
79+
matched_arg = std::find_if(++matched_arg, options_end, find_match);
6480
}
6581

6682
return env_files;

‎src/node_options.cc‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -651,6 +651,27 @@ void Parse(
651651
args, exec_args, v8_args, options, required_env_settings, errors);
652652
}
653653

654+
size_t GetNodeOptionsEnd(const StringVector& args) {
655+
// The bare config file flags take no value. Spell them out the way the
656+
// config file reader does before the real parse, otherwise the parser would
657+
// consume the next argument as the path.
658+
StringVector remaining;
659+
remaining.reserve(args.size());
660+
for (const std::string& arg : args) {
661+
remaining.push_back(IsBareConfigFileFlag(arg) ? DefaultConfigFileArg()
662+
: arg);
663+
}
664+
665+
// Any errors are reported by the real parse later on.
666+
PerProcessOptions options;
667+
StringVector v8_args;
668+
StringVector errors;
669+
Parse(&remaining, nullptr, &v8_args, &options, kDisallowedInEnvvar, &errors);
670+
671+
// `remaining` is left with the program name and the unparsed arguments.
672+
return args.size() - remaining.size() + 1;
673+
}
674+
654675
// XXX: If you add an option here, please also add it to doc/node.1 and
655676
// doc/api/cli.md
656677
// TODO(addaleax): Make that unnecessary.

‎src/node_options.h‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
#include <memory>
77
#include <string>
8+
#include <string_view>
89
#include <unordered_map>
910
#include <vector>
1011
#include "node_constants.h"
@@ -795,8 +796,35 @@ void Parse(StringVector* const args,
795796
OptionEnvvarSettings required_env_settings,
796797
StringVector* const errors);
797798

799+
// Returns the index of the first entry in `args` that is neither the program
800+
// name nor an option for Node.js itself. Everything from there on is the
801+
// script and its arguments, or follows `--`, so it must not be read as an
802+
// option of Node.js. This is determined with a throwaway parse, which stops
803+
// exactly where the real parse will.
804+
size_t GetNodeOptionsEnd(const StringVector& args);
805+
798806
} // namespace options_parser
799807

808+
constexpr std::string_view kConfigFileFlag = "--config-file";
809+
// TODO(marco-ippolito): Remove these aliases in a semver-major.
810+
constexpr std::string_view kExperimentalConfigFileFlag =
811+
"--experimental-config-file";
812+
constexpr std::string_view kDefaultConfigFileFlag =
813+
"--experimental-default-config-file";
814+
constexpr std::string_view kDefaultConfigFileName = "node.config.json";
815+
816+
// The config file flags that take no value. Before the real parse they are
817+
// spelled out as `--config-file=node.config.json`.
818+
inline bool IsBareConfigFileFlag(std::string_view arg) {
819+
return arg == kConfigFileFlag || arg == kExperimentalConfigFileFlag ||
820+
arg == kDefaultConfigFileFlag;
821+
}
822+
823+
inline std::string DefaultConfigFileArg() {
824+
return std::string(kConfigFileFlag) + "=" +
825+
std::string(kDefaultConfigFileName);
826+
}
827+
800828
// Helper macro for passing bit-field members to AddOption(). Expands to a
801829
// getter and setter function pointer pair that can read/write the named
802830
// bit-field without requiring a pointer-to-member (which is illegal for
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
'use strict';
2+
3+
require('../common');
4+
const assert = require('node:assert');
5+
const fs = require('node:fs');
6+
const path = require('node:path');
7+
const { spawnSync } = require('node:child_process');
8+
const tmpdir = require('../common/tmpdir');
9+
10+
// Env file flags are options of Node.js only when they appear before the
11+
// script name. After it they belong to the script, which must receive them
12+
// untouched without the file being read.
13+
14+
tmpdir.refresh();
15+
16+
const envFile = path.join(tmpdir.path, 'test.env');
17+
fs.writeFileSync(envFile, 'FOO=fromfile\nNODE_OPTIONS=--stack-trace-limit=7\n');
18+
19+
const script = path.join(tmpdir.path, 'script.js');
20+
fs.writeFileSync(script, `
21+
console.log(JSON.stringify({
22+
foo: process.env.FOO ?? null,
23+
limit: Error.stackTraceLimit,
24+
args: process.argv.slice(2),
25+
}));
26+
`);
27+
28+
const env = { ...process.env };
29+
delete env.NODE_OPTIONS;
30+
delete env.FOO;
31+
32+
// Builds without support for NODE_OPTIONS ignore the one set in the env file.
33+
const fileLimit = process.config.variables.node_without_node_options ? 10 : 7;
34+
35+
function run(args) {
36+
const child = spawnSync(process.execPath, args, { env, encoding: 'utf8' });
37+
assert.strictEqual(child.status, 0, child.stderr);
38+
return JSON.parse(child.stdout);
39+
}
40+
41+
// Before the script the file is still read.
42+
for (const flagArgs of [
43+
[`--env-file=${envFile}`],
44+
['--env-file', envFile],
45+
[`--env-file-if-exists=${envFile}`],
46+
['--env-file-if-exists', envFile],
47+
]) {
48+
assert.deepStrictEqual(run([...flagArgs, script, 'one']),
49+
{ foo: 'fromfile', limit: fileLimit, args: ['one'] });
50+
}
51+
52+
// After the script the file is not read and the arguments are kept.
53+
for (const flagArgs of [
54+
[`--env-file=${envFile}`],
55+
['--env-file', envFile],
56+
[`--env-file-if-exists=${envFile}`],
57+
['--env-file-if-exists', envFile],
58+
['--env-file=missing.env'],
59+
]) {
60+
assert.deepStrictEqual(run([script, ...flagArgs]),
61+
{ foo: null, limit: 10, args: flagArgs });
62+
assert.deepStrictEqual(run([script, 'one', ...flagArgs]),
63+
{ foo: null, limit: 10, args: ['one', ...flagArgs] });
64+
}
65+
66+
// A file before the script is read while the same flag after it is ignored.
67+
assert.deepStrictEqual(
68+
run([`--env-file=${envFile}`, script, '--env-file=missing.env']),
69+
{ foo: 'fromfile', limit: fileLimit, args: ['--env-file=missing.env'] });
70+
71+
// Nothing is read after the separator either.
72+
assert.deepStrictEqual(
73+
run(['--', script, `--env-file=${envFile}`]),
74+
{ foo: null, limit: 10, args: [`--env-file=${envFile}`] });
75+
76+
// A missing file before the script still stops the startup.
77+
{
78+
const child = spawnSync(process.execPath,
79+
['--env-file=missing.env', script],
80+
{ env, encoding: 'utf8' });
81+
assert.strictEqual(child.status, 9);
82+
assert.match(child.stderr, /missing\.env: not found/);
83+
}
84+
85+
// Options of Node.js between the file and the script do not hide it.
86+
assert.deepStrictEqual(
87+
run([`--env-file=${envFile}`, '--no-warnings', '-r', 'node:path', script]),
88+
{ foo: 'fromfile', limit: fileLimit, args: [] });

0 commit comments

Comments
 (0)