Skip to content

Commit 302c9cf

Browse files
committed
Improves logging of environment variables
Fixes: #3542
1 parent f39abe3 commit 302c9cf

File tree

3 files changed

+26
-19
lines changed

3 files changed

+26
-19
lines changed

docs/changelog/3542.bugfix.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improves logging of environment variables by sorting them by key and redacting
2+
the values for the ones that are likely to contain secrets.

src/tox/tox_env/api.py

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -31,22 +31,15 @@
3131
from tox.tox_env.installer import Installer
3232

3333
LOGGER = logging.getLogger(__name__)
34+
# Based on original gitleaks rule named generic-api-key
35+
# See: https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml#L587
3436
SECRET_ENV_VAR_REGEX = re.compile(
35-
r"""(?ix) # case-insensitive, verbose mode
36-
^\s* # optional leading whitespace
37-
(?P<key> # capture group: key
38-
(?:\w*(_)?)
39-
(?:
40-
(SECRET|TOKEN|KEY|PASSWORD|PWD|CRED|PRIVATE|AUTH|API)
41-
)
42-
(?:\w*) # allow variable prefixes/suffixes
43-
)\s*=\s* # equal sign with optional spaces
44-
(?P<value> # capture group: value
45-
(['"])? # optional opening quote
46-
([A-Za-z0-9\-_]{12,}) # suspicious value (long, alphanumeric)
47-
\1? # optional closing quote matching opening
48-
)
49-
"""
37+
r"""(?ix)[\w.-]{0,50}?
38+
(?:access|auth|(?-i:[Aa]pi|API)|credential|creds|key|passw(?:or)?d|secret|token)
39+
(?:[ \t\w.-]{0,20})[\s'"]{0,3}
40+
(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}
41+
([\w.=-]{10,150}|[a-z0-9][a-z0-9+/]{11,}={0,3})
42+
(?:[\x60'"\s;]|\\[nr]|$)"""
5043
)
5144

5245

tests/tox_env/test_api.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,21 @@ def test_setenv_section_substitution(tox_project: ToxProjectCreator) -> None:
3939

4040

4141
@pytest.mark.parametrize(
42-
("key", "value", "expected"), [pytest.param("FOO", "bar", "bar"), pytest.param("GITHUB_TOKEN", "foo", "***")]
42+
("key", "do_redact"),
43+
[
44+
pytest.param("ACCESS_TOKEN", True),
45+
pytest.param("API_KEY", True),
46+
pytest.param("DB_PASSWORD", True),
47+
pytest.param("FOO", False),
48+
pytest.param("GITHUB_TOKEN", True),
49+
pytest.param("NORMAL_VAR", False),
50+
pytest.param("SECRET", True),
51+
],
4352
)
44-
def test_redact(key: str, value: str, expected: str) -> None:
53+
def test_redact(key: str, do_redact: bool) -> None:
4554
"""Ensures that redact_value works as expected."""
46-
result = redact_value(key, value)
47-
assert result == expected
55+
result = redact_value(key, "foo")
56+
if do_redact:
57+
assert result == "***"
58+
else:
59+
assert result == "foo"

0 commit comments

Comments
 (0)