45 lines
1.9 KiB
Python
45 lines
1.9 KiB
Python
import importlib
|
|||
|
|
import sys
|
||
|
|
|
||
|
|
import pytest
|
||
|
|
|
||
|
|
from utils.secret_key import resolve_secret_key, SecretKeyError
|
||
|
|
|
||
|
|
GOOD = "0123456789abcdef" * 4 # 64 hex characters
|
||
|
|
|
||
|
|
|
||
|
|
def test_weak_or_missing_key_is_refused():
|
||
|
|
for bad in (None, "", " ", "ovpmon-secret-change-me", "Change-Me-Please", "k" * 31):
|
||
|
|
with pytest.raises(SecretKeyError) as exc:
|
||
|
|
resolve_secret_key(bad, None)
|
||
|
|
assert "openssl rand -hex 32" in str(exc.value)
|
||
|
|
if bad and bad.strip():
|
||
|
|
assert bad not in str(exc.value) # the key value is never part of the message
|
||
|
|
# the same checks apply to the config.ini value
|
||
|
|
with pytest.raises(SecretKeyError):
|
||
|
|
resolve_secret_key(None, "ovpmon-secret-change-me")
|
||
|
|
# legacy variable name is called out explicitly
|
||
|
|
with pytest.raises(SecretKeyError) as exc:
|
||
|
|
resolve_secret_key(None, "", legacy_env=GOOD)
|
||
|
|
assert "OVPMON_SECRET_KEY" in str(exc.value) and "OVPMON_API_SECRET_KEY" in str(exc.value)
|
||
|
|
assert GOOD not in str(exc.value)
|
||
|
|
|
||
|
|
|
||
|
|
def test_good_key_and_priority():
|
||
|
|
assert resolve_secret_key(GOOD, None) == (GOOD, "environment")
|
||
|
|
assert resolve_secret_key(None, GOOD) == (GOOD, "config.ini")
|
||
|
|
# environment wins over config.ini, even when the config.ini value is the old default
|
||
|
|
assert resolve_secret_key(GOOD, "ovpmon-secret-change-me") == (GOOD, "environment")
|
||
|
|
|
||
|
|
|
||
|
|
def test_auth_import_fails_closed(monkeypatch):
|
||
|
|
# Fresh import each time; the original module is restored in sys.modules after the test
|
||
|
|
monkeypatch.delitem(sys.modules, "utils.auth", raising=False)
|
||
|
|
monkeypatch.setenv("OVPMON_API_SECRET_KEY", "ovpmon-secret-change-me")
|
||
|
|
with pytest.raises(SystemExit) as exc:
|
||
|
|
importlib.import_module("utils.auth")
|
||
|
|
assert exc.value.code == 1
|
||
|
|
|
||
|
|
monkeypatch.delitem(sys.modules, "utils.auth", raising=False)
|
||
|
|
monkeypatch.setenv("OVPMON_API_SECRET_KEY", GOOD)
|
||
|
|
assert importlib.import_module("utils.auth").SECRET_KEY == GOOD
|