certauth/tests/test_config.py
Jarian Cottingham 279a28515f fix: generate JWT secret on first boot instead of hardcoded default (#19)
Generate random 256-bit secret stored in /var/lib/certauth/.jwt_secret (mode 0600)
ENV JWT_SECRET takes precedence. Remove CHANGE_ME_JWT_SECRET default.
Add tests for secret generation and env override
2026-07-04 04:48:30 +00:00

67 lines
2.4 KiB
Python

import os
import sys
import tempfile
import unittest
class TestConfigSecurity(unittest.TestCase):
def test_jwt_secret_generates_new(self):
with tempfile.NamedTemporaryFile(suffix=".jwt_secret", delete=False) as f:
secret_path = f.name
os.unlink(secret_path)
try:
os.environ.pop("JWT_SECRET", None)
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import importlib
if "config" in sys.modules:
del sys.modules["config"]
os.environ["_JWT_SECRET_FILE"] = secret_path
cfg = __import__("config")
self.assertIsNotNone(cfg.SECRET_KEY)
self.assertEqual(len(cfg.SECRET_KEY), 64)
with open(secret_path) as sf:
self.assertEqual(sf.read().strip(), cfg.SECRET_KEY)
finally:
os.environ.pop("JWT_SECRET", None)
os.environ.pop("_JWT_SECRET_FILE", None)
if os.path.exists(secret_path):
os.unlink(secret_path)
if "config" in sys.modules:
del sys.modules["config"]
def test_jwt_secret_env_override(self):
os.environ["JWT_SECRET"] = "test-secret-from-env"
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
if "config" in sys.modules:
del sys.modules["config"]
cfg = __import__("config")
self.assertEqual(cfg.SECRET_KEY, "test-secret-from-env")
os.environ.pop("JWT_SECRET", None)
if "config" in sys.modules:
del sys.modules["config"]
def test_yk_pin_requires_env(self):
os.environ.pop("YK_ROOT_PIN", None)
os.environ.pop("YK_INT_PIN", None)
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
if "config" in sys.modules:
del sys.modules["config"]
with self.assertRaises(RuntimeError):
__import__("config")
os.environ["YK_ROOT_PIN"] = "test1234"
os.environ["YK_INT_PIN"] = "test5678"
if "config" in sys.modules:
del sys.modules["config"]
cfg = __import__("config")
self.assertEqual(cfg.YK_ROOT_PIN, "test1234")
self.assertEqual(cfg.YK_INT_PIN, "test5678")
os.environ.pop("YK_ROOT_PIN", None)
os.environ.pop("YK_INT_PIN", None)
if "config" in sys.modules:
del sys.modules["config"]
if __name__ == "__main__":
unittest.main()