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
32 changes: 32 additions & 0 deletions tests/misc/test_secret_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import os
import subprocess
import sys
import unittest


class SecretKeyGuardTestCase(unittest.TestCase):
"""
Zou refuses to serve HTTP with the public default SECRET_KEY (JWT
forgery), but CLI commands must keep working with it. The guard fires
at config import, so it is observed from fresh interpreters where
neither pytest nor a caller has set the variable.
"""

def _run(self, code):
env = dict(os.environ)
env.pop("SECRET_KEY", None)
env.pop("DEBUG", None)
return subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
env=env,
)

def test_server_context_rejects_default_secret_key(self):
result = self._run("import zou.app.config")
self.assertNotEqual(result.returncode, 0)
self.assertIn(b"insecure default", result.stderr)

def test_cli_context_allows_default_secret_key(self):
result = self._run("import zou.cli; import zou.app.config")
self.assertEqual(result.returncode, 0, result.stderr)
12 changes: 9 additions & 3 deletions zou/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,15 @@
SECRET_KEY = os.getenv("SECRET_KEY", "mysecretkey")
# The default key is public: since JWT signing falls back to SECRET_KEY, an
# unconfigured production deployment lets anyone forge admin tokens. Refuse to
# boot with the default outside DEBUG. Test runs (pytest) are exempt so the
# suite keeps working without setting the variable.
if SECRET_KEY == "mysecretkey" and not DEBUG and "pytest" not in sys.modules:
# boot the HTTP server with the default outside DEBUG. CLI commands (which load
# zou.cli) and test runs (pytest) never serve tokens, so they stay exempt and
# keep working without the variable set.
if (
SECRET_KEY == "mysecretkey"
and not DEBUG
and "pytest" not in sys.modules
and "zou.cli" not in sys.modules
):
raise RuntimeError(
"SECRET_KEY is set to the insecure default 'mysecretkey'. Set the "
"SECRET_KEY environment variable to a strong, unique value before "
Expand Down
Loading