Skip to content

Commit 8a50cef

Browse files
committed
cli: implement --trace-env and --trace-env-[js|native]-stack
This implements --trace-env, --trace-env-js-stack and --trace-env-native-stack CLI options which can be used to find out what environment variables are accessed and where they are accessed.
1 parent 1d01ad6 commit 8a50cef

19 files changed

Lines changed: 372 additions & 26 deletions

‎doc/api/cli.md‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2588,6 +2588,44 @@ added: v0.8.0
25882588

25892589
Print stack traces for deprecations.
25902590

2591+
### `--trace-env`
2592+
2593+
<!-- YAML
2594+
added: REPLACEME
2595+
-->
2596+
2597+
Print reads and writes to environment variables.
2598+
2599+
The following accesses will be printed:
2600+
2601+
* The environment variable reads that Node.js does internally.
2602+
* Writes in the form of `process.env.KEY = "SOME VALUE"`.
2603+
* Reads in the form of `process.env.KEY`.
2604+
* Definitions in the form of `Object.defineProperty(process.env, 'KEY', {...})`.
2605+
* Queries in the form of `Object.hasOwn(process.env, 'KEY')`,
2606+
`process.env.hasOwnProperty('KEY')` or `'KEY' in process.env`.
2607+
* Deletions in the form of `delete process.env.KEY`.
2608+
* Enumerations inf the form of `...process.env` or `Object.keys(process.env)`.
2609+
2610+
To print the stack trace of the access, use `--trace-env-js-stack` and/or
2611+
`--trace-env-native-stack`.
2612+
2613+
### `--trace-env-js-stack`
2614+
2615+
<!-- YAML
2616+
added: REPLACEME
2617+
-->
2618+
2619+
In addition to what `--trace-env` does, this prints the JavaScript stack trace of the access.
2620+
2621+
### `--trace-env-native-stack`
2622+
2623+
<!-- YAML
2624+
added: REPLACEME
2625+
-->
2626+
2627+
In addition to what `--trace-env` does, this prints the native stack trace of the access.
2628+
25912629
### `--trace-event-categories`
25922630

25932631
<!-- YAML
@@ -3134,6 +3172,9 @@ one is included in the list below.
31343172
* `--tls-min-v1.2`
31353173
* `--tls-min-v1.3`
31363174
* `--trace-deprecation`
3175+
* `--trace-env-js-stack`
3176+
* `--trace-env-native-stack`
3177+
* `--trace-env`
31373178
* `--trace-event-categories`
31383179
* `--trace-event-file-pattern`
31393180
* `--trace-events-enabled`

‎src/debug_utils.cc‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,9 @@ EnabledDebugList enabled_debug_list;
6262
using v8::Local;
6363
using v8::StackTrace;
6464

65-
void EnabledDebugList::Parse(std::shared_ptr<KVStore> env_vars) {
65+
void EnabledDebugList::Parse(Environment* env) {
6666
std::string cats;
67-
credentials::SafeGetenv("NODE_DEBUG_NATIVE", &cats, env_vars);
67+
credentials::SafeGetenv("NODE_DEBUG_NATIVE", &cats, env);
6868
Parse(cats);
6969
}
7070

‎src/debug_utils.h‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,10 @@ class NODE_EXTERN_PRIVATE EnabledDebugList {
7474
return enabled_[static_cast<unsigned int>(category)];
7575
}
7676

77-
// Uses NODE_DEBUG_NATIVE to initialize the categories. The env_vars variable
77+
// Uses NODE_DEBUG_NATIVE to initialize the categories. env->env_vars()
7878
// is parsed if it is not a nullptr, otherwise the system environment
7979
// variables are parsed.
80-
void Parse(std::shared_ptr<KVStore> env_vars);
80+
void Parse(Environment* env);
8181

8282
private:
8383
// Enable all categories matching cats.

‎src/env.cc‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -864,9 +864,6 @@ Environment::Environment(IsolateData* isolate_data,
864864
EnvironmentFlags::kOwnsInspector;
865865
}
866866

867-
set_env_vars(per_process::system_environment);
868-
enabled_debug_list_.Parse(env_vars());
869-
870867
// We create new copies of the per-Environment option sets, so that it is
871868
// easier to modify them after Environment creation. The defaults are
872869
// part of the per-Isolate option set, for which in turn the defaults are
@@ -876,6 +873,13 @@ Environment::Environment(IsolateData* isolate_data,
876873
inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
877874
options_->debug_options().host_port);
878875

876+
set_env_vars(per_process::system_environment);
877+
// This should be done after options is created, so that --trace-env can be
878+
// checked when parsing NODE_DEBUG_NATIVE. It should also be done after
879+
// env_vars() is set so that the parser uses values from env->env_vars()
880+
// which may or may not be the system environment variable store.
881+
enabled_debug_list_.Parse(this);
882+
879883
heap_snapshot_near_heap_limit_ =
880884
static_cast<uint32_t>(options_->heap_snapshot_near_heap_limit);
881885

@@ -1104,8 +1108,7 @@ void Environment::InitializeLibuv() {
11041108

11051109
void Environment::InitializeCompileCache() {
11061110
std::string dir_from_env;
1107-
if (!credentials::SafeGetenv(
1108-
"NODE_COMPILE_CACHE", &dir_from_env, env_vars()) ||
1111+
if (!credentials::SafeGetenv("NODE_COMPILE_CACHE", &dir_from_env, this) ||
11091112
dir_from_env.empty()) {
11101113
return;
11111114
}
@@ -1117,7 +1120,7 @@ CompileCacheEnableResult Environment::EnableCompileCache(
11171120
CompileCacheEnableResult result;
11181121
std::string disable_env;
11191122
if (credentials::SafeGetenv(
1120-
"NODE_DISABLE_COMPILE_CACHE", &disable_env, env_vars())) {
1123+
"NODE_DISABLE_COMPILE_CACHE", &disable_env, this)) {
11211124
result.status = CompileCacheEnableStatus::DISABLED;
11221125
result.message = "Disabled by NODE_DISABLE_COMPILE_CACHE";
11231126
Debug(this,

‎src/node.cc‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -993,7 +993,7 @@ InitializeOncePerProcessInternal(const std::vector<std::string>& args,
993993
if (!(flags & ProcessInitializationFlags::kNoParseGlobalDebugVariables)) {
994994
// Initialized the enabled list for Debug() calls with system
995995
// environment variables.
996-
per_process::enabled_debug_list.Parse(per_process::system_environment);
996+
per_process::enabled_debug_list.Parse(nullptr);
997997
}
998998

999999
PlatformInit(flags);

‎src/node_credentials.cc‎

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,7 @@ static bool HasOnly(int capability) {
7272
// process only has the capability CAP_NET_BIND_SERVICE set. If the current
7373
// process does not have any capabilities set and the process is running as
7474
// setuid root then lookup will not be allowed.
75-
bool SafeGetenv(const char* key,
76-
std::string* text,
77-
std::shared_ptr<KVStore> env_vars) {
75+
bool SafeGetenv(const char* key, std::string* text, Environment* env) {
7876
#if !defined(__CloudABI__) && !defined(_WIN32)
7977
#if defined(__linux__)
8078
if ((!HasOnly(CAP_NET_BIND_SERVICE) && linux_at_secure()) ||
@@ -87,14 +85,36 @@ bool SafeGetenv(const char* key,
8785

8886
// Fallback to system environment which reads the real environment variable
8987
// through uv_os_getenv.
90-
if (env_vars == nullptr) {
88+
std::shared_ptr<KVStore> env_vars;
89+
if (env == nullptr) {
9190
env_vars = per_process::system_environment;
91+
} else {
92+
env_vars = env->env_vars();
9293
}
9394

9495
std::optional<std::string> value = env_vars->Get(key);
95-
if (!value.has_value()) return false;
96-
*text = value.value();
97-
return true;
96+
97+
bool has_env = value.has_value();
98+
if (has_env) {
99+
*text = value.value();
100+
}
101+
102+
auto options =
103+
(env != nullptr ? env->options()
104+
: per_process::cli_options->per_isolate->per_env);
105+
106+
if (options->trace_env) {
107+
fprintf(stderr, "[--trace-env] get environment variable \"%s\": ", key);
108+
if (has_env) {
109+
fprintf(stderr, "\"%s\"\n", text->c_str());
110+
} else {
111+
fprintf(stderr, "undefined\n");
112+
}
113+
114+
PrintTraceEnvStack(options);
115+
}
116+
117+
return has_env;
98118
}
99119

100120
static void SafeGetenv(const FunctionCallbackInfo<Value>& args) {
@@ -103,7 +123,7 @@ static void SafeGetenv(const FunctionCallbackInfo<Value>& args) {
103123
Isolate* isolate = env->isolate();
104124
Utf8Value strenvtag(isolate, args[0]);
105125
std::string text;
106-
if (!SafeGetenv(*strenvtag, &text, env->env_vars())) return;
126+
if (!SafeGetenv(*strenvtag, &text, env)) return;
107127
Local<Value> result =
108128
ToV8Value(isolate->GetCurrentContext(), text).ToLocalChecked();
109129
args.GetReturnValue().Set(result);
@@ -117,7 +137,7 @@ static void GetTempDir(const FunctionCallbackInfo<Value>& args) {
117137

118138
// Let's wrap SafeGetEnv since it returns true for empty string.
119139
auto get_env = [&dir, &env](std::string_view key) {
120-
USE(SafeGetenv(key.data(), &dir, env->env_vars()));
140+
USE(SafeGetenv(key.data(), &dir, env));
121141
return !dir.empty();
122142
};
123143

‎src/node_env_var.cc‎

Lines changed: 72 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,19 @@ Maybe<void> KVStore::AssignToObject(v8::Isolate* isolate,
337337
return JustVoid();
338338
}
339339

340+
void PrintTraceEnvStack(Environment* env) {
341+
PrintTraceEnvStack(env->options());
342+
}
343+
344+
void PrintTraceEnvStack(std::shared_ptr<EnvironmentOptions> options) {
345+
if (options->trace_env_native_stack) {
346+
DumpNativeBacktrace(stderr);
347+
}
348+
if (options->trace_env_js_stack) {
349+
DumpJavaScriptBacktrace(stderr);
350+
}
351+
}
352+
340353
static Intercepted EnvGetter(Local<Name> property,
341354
const PropertyCallbackInfo<Value>& info) {
342355
Environment* env = Environment::GetCurrent(info);
@@ -348,7 +361,27 @@ static Intercepted EnvGetter(Local<Name> property,
348361
CHECK(property->IsString());
349362
MaybeLocal<String> value_string =
350363
env->env_vars()->Get(env->isolate(), property.As<String>());
351-
if (!value_string.IsEmpty()) {
364+
365+
bool has_env = !value_string.IsEmpty();
366+
if (env->options()->trace_env) {
367+
Utf8Value key(env->isolate(), property.As<String>());
368+
fprintf(stderr,
369+
"[--trace-env] get environment variable \"%.*s\": ",
370+
static_cast<int>(key.length()),
371+
key.out());
372+
if (has_env) {
373+
Utf8Value value_utf8(env->isolate(), value_string.ToLocalChecked());
374+
fprintf(stderr,
375+
"\"%.*s\"\n",
376+
static_cast<int>(value_utf8.length()),
377+
value_utf8.out());
378+
} else {
379+
fprintf(stderr, "undefined\n");
380+
}
381+
PrintTraceEnvStack(env);
382+
}
383+
384+
if (has_env) {
352385
info.GetReturnValue().Set(value_string.ToLocalChecked());
353386
return Intercepted::kYes;
354387
}
@@ -386,6 +419,17 @@ static Intercepted EnvSetter(Local<Name> property,
386419
}
387420

388421
env->env_vars()->Set(env->isolate(), key, value_string);
422+
if (env->options()->trace_env) {
423+
Utf8Value key_utf8(env->isolate(), key);
424+
Utf8Value value_utf8(env->isolate(), value_string);
425+
fprintf(stderr,
426+
"[--trace-env] set environment variable \"%.*s\" = \"%.*s\"\n",
427+
static_cast<int>(key_utf8.length()),
428+
key_utf8.out(),
429+
static_cast<int>(value_utf8.length()),
430+
value_utf8.out());
431+
PrintTraceEnvStack(env);
432+
}
389433

390434
return Intercepted::kYes;
391435
}
@@ -396,7 +440,18 @@ static Intercepted EnvQuery(Local<Name> property,
396440
CHECK(env->has_run_bootstrapping_code());
397441
if (property->IsString()) {
398442
int32_t rc = env->env_vars()->Query(env->isolate(), property.As<String>());
399-
if (rc != -1) {
443+
bool has_env = (rc != -1);
444+
445+
if (env->options()->trace_env) {
446+
Utf8Value key_utf8(env->isolate(), property.As<String>());
447+
fprintf(stderr,
448+
"[--trace-env] query environment variable \"%.*s\": %s\n",
449+
static_cast<int>(key_utf8.length()),
450+
key_utf8.out(),
451+
has_env ? "is set" : "is not set");
452+
PrintTraceEnvStack(env);
453+
}
454+
if (has_env) {
400455
// Return attributes for the property.
401456
info.GetReturnValue().Set(v8::None);
402457
return Intercepted::kYes;
@@ -411,6 +466,15 @@ static Intercepted EnvDeleter(Local<Name> property,
411466
CHECK(env->has_run_bootstrapping_code());
412467
if (property->IsString()) {
413468
env->env_vars()->Delete(env->isolate(), property.As<String>());
469+
470+
if (env->options()->trace_env) {
471+
Utf8Value key_utf8(env->isolate(), property.As<String>());
472+
fprintf(stderr,
473+
"[--trace-env] delete environment variable \"%.*s\"\n",
474+
static_cast<int>(key_utf8.length()),
475+
key_utf8.out());
476+
PrintTraceEnvStack(env);
477+
}
414478
}
415479

416480
// process.env never has non-configurable properties, so always
@@ -423,6 +487,12 @@ static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
423487
Environment* env = Environment::GetCurrent(info);
424488
CHECK(env->has_run_bootstrapping_code());
425489

490+
if (env->options()->trace_env) {
491+
fprintf(stderr, "[--trace-env] enumerate environment variables\n");
492+
493+
PrintTraceEnvStack(env);
494+
}
495+
426496
info.GetReturnValue().Set(
427497
env->env_vars()->Enumerate(env->isolate()));
428498
}

‎src/node_internals.h‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -321,11 +321,12 @@ class ThreadPoolWork {
321321
#endif // defined(__POSIX__) && !defined(__ANDROID__) && !defined(__CloudABI__)
322322

323323
namespace credentials {
324-
bool SafeGetenv(const char* key,
325-
std::string* text,
326-
std::shared_ptr<KVStore> env_vars = nullptr);
324+
bool SafeGetenv(const char* key, std::string* text, Environment* env = nullptr);
327325
} // namespace credentials
328326

327+
void PrintTraceEnvStack(Environment* env);
328+
void PrintTraceEnvStack(std::shared_ptr<EnvironmentOptions> options);
329+
329330
void DefineZlibConstants(v8::Local<v8::Object> target);
330331
v8::Isolate* NewIsolate(v8::Isolate::CreateParams* params,
331332
uv_loop_t* event_loop,

‎src/node_options.cc‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -762,6 +762,24 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() {
762762
"show stack traces on promise initialization and resolution",
763763
&EnvironmentOptions::trace_promises,
764764
kAllowedInEnvvar);
765+
766+
AddOption("--trace-env",
767+
"Print accesses to the environment variables",
768+
&EnvironmentOptions::trace_env,
769+
kAllowedInEnvvar);
770+
Implies("--trace-env-js-stack", "--trace-env");
771+
Implies("--trace-env-native-stack", "--trace-env");
772+
AddOption("--trace-env-js-stack",
773+
"Print accesses to the environment variables and the JavaScript "
774+
"stack trace",
775+
&EnvironmentOptions::trace_env_js_stack,
776+
kAllowedInEnvvar);
777+
AddOption(
778+
"--trace-env-native-stack",
779+
"Print accesses to the environment variables and the native stack trace",
780+
&EnvironmentOptions::trace_env_native_stack,
781+
kAllowedInEnvvar);
782+
765783
AddOption("--experimental-default-type",
766784
"set module system to use by default",
767785
&EnvironmentOptions::type,

‎src/node_options.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,9 @@ class EnvironmentOptions : public Options {
209209
bool trace_uncaught = false;
210210
bool trace_warnings = false;
211211
bool trace_promises = false;
212+
bool trace_env = false;
213+
bool trace_env_js_stack = false;
214+
bool trace_env_native_stack = false;
212215
bool extra_info_on_fatal_exception = true;
213216
std::string unhandled_rejections;
214217
std::vector<std::string> userland_loaders;

0 commit comments

Comments
 (0)