From 892dd800cc4b319616bf68d2a3792a9b07d42a7f Mon Sep 17 00:00:00 2001 From: Kevin Michel Date: Fri, 5 Jul 2024 07:47:15 +0200 Subject: [PATCH] fix(integrations): don't send full env to subprocess During the arguments modification to `subprocess.Popen.__init__`, an explicitly empty environment of `{}` is incorrectly confused with a `None` environment. This causes sentry to pass the entire environment of the parent process instead of sending just the injected environment variables. Fix it by only replacing the environment with `os.environ` if the variable is None, and not just falsy. --- sentry_sdk/integrations/stdlib.py | 6 +++++- tests/integrations/stdlib/test_subprocess.py | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/sentry_sdk/integrations/stdlib.py b/sentry_sdk/integrations/stdlib.py index 0a17834a40..4e4b411868 100644 --- a/sentry_sdk/integrations/stdlib.py +++ b/sentry_sdk/integrations/stdlib.py @@ -207,7 +207,11 @@ def sentry_patched_popen_init(self, *a, **kw): for k, v in hub.iter_trace_propagation_headers(span): if env is None: env = _init_argument( - a, kw, "env", 10, lambda x: dict(x or os.environ) + a, + kw, + "env", + 10, + lambda x: dict(x if x is not None else os.environ), ) env["SUBPROCESS_" + k.upper().replace("-", "_")] = v diff --git a/tests/integrations/stdlib/test_subprocess.py b/tests/integrations/stdlib/test_subprocess.py index d61be35fd2..d1684c356d 100644 --- a/tests/integrations/stdlib/test_subprocess.py +++ b/tests/integrations/stdlib/test_subprocess.py @@ -180,6 +180,19 @@ def test_subprocess_basic( assert sys.executable + " -c" in subprocess_init_span["description"] +def test_subprocess_empty_env(sentry_init, monkeypatch): + monkeypatch.setenv("TEST_MARKER", "should_not_be_seen") + sentry_init(integrations=[StdlibIntegration()], traces_sample_rate=1.0) + with start_transaction(name="foo"): + args = [ + sys.executable, + "-c", + "import os; print(os.environ.get('TEST_MARKER', None))", + ] + output = subprocess.check_output(args, env={}, text=True) + assert "should_not_be_seen" not in output + + def test_subprocess_invalid_args(sentry_init): sentry_init(integrations=[StdlibIntegration()])