diff --git a/admin_api.py b/admin_api.py index d2edec5..243cb51 100644 --- a/admin_api.py +++ b/admin_api.py @@ -29,7 +29,14 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from dotenv import load_dotenv -load_dotenv() +if __name__ == "__main__": + # Load the repo .env ONLY when this file is run as the entrypoint + # (`python admin_api.py`). A bare module-level load_dotenv() here used to + # fire on every import too -- including pytest collection -- leaking the + # real repo .env (secrets included) into any process that merely imports + # this module. This runs before the os.environ.get(...) constants below, + # so `python admin_api.py` still behaves identically. + load_dotenv() from runtime.env_overrides import load as _load_overrides # noqa: E402 _load_overrides() from runtime import env_overrides # noqa: E402 diff --git a/tests/unit/test_admin_effective_config.py b/tests/unit/test_admin_effective_config.py index 115547f..f734359 100644 --- a/tests/unit/test_admin_effective_config.py +++ b/tests/unit/test_admin_effective_config.py @@ -1,7 +1,33 @@ """Admin effective-config endpoint: masking, drift, and fail-closed auth (plan 007 step 6).""" +import importlib +import os + import admin_api +# A key defined only in the real repo .env (never set by tests/CI) — used to +# prove import-time isolation without ever reading/asserting its value. +_ENV_ONLY_SENTINEL_KEY = "DATABENTO_API_KEY" + + +def test_importing_admin_api_does_not_load_dotenv(): + """Importing (or reloading) admin_api must be env-neutral: it must not + read the repo .env. A bare module-level load_dotenv() used to run on + every import — including pytest collection — leaking real secrets into + the whole test session. Only running admin_api as __main__ may load it.""" + before = os.environ.pop(_ENV_ONLY_SENTINEL_KEY, None) + try: + importlib.reload(admin_api) + # bool-ify before asserting: keeps a real secret value out of any + # pytest assertion-rewrite diff if this ever fails again. + leaked = _ENV_ONLY_SENTINEL_KEY in os.environ + assert leaked is False, f"{_ENV_ONLY_SENTINEL_KEY} was set by importing admin_api" + finally: + if before is not None: + os.environ[_ENV_ONLY_SENTINEL_KEY] = before + else: + os.environ.pop(_ENV_ONLY_SENTINEL_KEY, None) + def test_effective_config_masks_secret_values(monkeypatch): monkeypatch.setenv("ALPACA_API_KEY", "supersecretvalue")