Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions gateway/app/services/api_key_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,14 +122,16 @@ class APIKeyHashingUnavailable(RuntimeError):
def _configured_pepper() -> bytes | None:
"""The server pepper: process env first, then Settings (``.env``).

An explicitly empty environment value also masks dotenv in Settings;
production then fails closed instead of reviving a stale dotenv pepper.
An explicitly empty environment value masks dotenv and cached Settings;
production then fails closed instead of reviving a stale pepper.
Settings holds it as a SecretStr so it is masked in any settings dump.
It is never logged.
"""
value = os.environ.get(API_KEY_HASH_PEPPER_ENV, "").strip()
if not value:
value = get_settings().API_KEY_HASH_PEPPER.get_secret_value().strip()
value = (
os.environ[API_KEY_HASH_PEPPER_ENV]
if API_KEY_HASH_PEPPER_ENV in os.environ
else get_settings().API_KEY_HASH_PEPPER.get_secret_value()
).strip()
return value.encode("utf-8") if value else None


Expand Down
17 changes: 17 additions & 0 deletions gateway/tests/test_api_key_scrypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,23 @@ def test_empty_env_pepper_does_not_revive_dotenv_secret(monkeypatch, tmp_path) -
svc.validate_api_key_hashing_config()


@pytest.mark.parametrize("empty_value", ["", " "])
def test_empty_env_pepper_does_not_revive_cached_settings(
monkeypatch, empty_value
) -> None:
monkeypatch.setenv("ENVIRONMENT", "production")
monkeypatch.setenv(svc.API_KEY_HASH_PEPPER_ENV, secrets.token_urlsafe(32))
get_settings.cache_clear()
try:
get_settings()
svc.validate_api_key_hashing_config()
monkeypatch.setenv(svc.API_KEY_HASH_PEPPER_ENV, empty_value)
with pytest.raises(svc.APIKeyHashingUnavailable):
svc.validate_api_key_hashing_config()
finally:
get_settings.cache_clear()


@pytest.mark.anyio
async def test_row_authenticates(clean_database, pepper: str) -> None:
stored = svc.hash_api_key(KEY)
Expand Down
Loading