Skip to content

Commit 3455e0c

Browse files
committed
Enforce SECRET_KEY requirement in production
1 parent 8b27647 commit 3455e0c

File tree

3 files changed

+58
-3
lines changed

3 files changed

+58
-3
lines changed

AIPscan/__init__.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@ def create_app(config_name=None):
3535
app = Flask(__name__)
3636
app.config.from_object(config)
3737

38+
# Set up the secret key.
39+
secret = os.getenv("SECRET_KEY") or app.config.get("SECRET_KEY")
40+
if app.debug or app.testing:
41+
app.config["SECRET_KEY"] = secret or "dev"
42+
else:
43+
if not secret or not str(secret).strip():
44+
raise RuntimeError(
45+
"SECRET_KEY must be set to a non-empty value when running in production."
46+
)
47+
app.config["SECRET_KEY"] = secret
48+
3849
migrations_dir = os.path.abspath(
3950
os.path.join(os.path.dirname(__file__), "migrations")
4051
)

AIPscan/config.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,7 @@
2020

2121

2222
class Config:
23-
# Be sure to set a secure secret key for production.
24-
SECRET_KEY = os.getenv("SECRET_KEY", "you-will-never-guess")
25-
23+
SECRET_KEY = None
2624
DEBUG = False
2725
TESTING = False
2826

AIPscan/tests/test_app.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""Tests for Flask application factory configuration.
2+
3+
Ensures that SECRET_KEY is properly validated in production and that
4+
development/test environments have appropriate fallback behavior.
5+
"""
6+
7+
import pytest
8+
9+
from AIPscan import create_app
10+
11+
12+
@pytest.mark.parametrize(
13+
"config_name,secret_value,should_raise,expected_secret",
14+
[
15+
# Production requires valid SECRET_KEY.
16+
("default", None, True, None),
17+
("default", "", True, None),
18+
("default", " ", True, None),
19+
("default", "super-secret", False, "super-secret"),
20+
# Dev and test use fallback.
21+
("dev", None, False, "dev"),
22+
("test", None, False, "dev"),
23+
],
24+
ids=[
25+
"prod-rejects-missing-key",
26+
"prod-rejects-empty-key",
27+
"prod-rejects-whitespace-key",
28+
"prod-accepts-valid-key",
29+
"dev-provides-fallback-key",
30+
"test-provides-fallback-key",
31+
],
32+
)
33+
def test_create_app_secret_key_handling(
34+
monkeypatch, config_name, secret_value, should_raise, expected_secret
35+
):
36+
"""Test SECRET_KEY validation across all config environments."""
37+
monkeypatch.delenv("SECRET_KEY", raising=False)
38+
if secret_value is not None:
39+
monkeypatch.setenv("SECRET_KEY", secret_value)
40+
41+
if should_raise:
42+
with pytest.raises(RuntimeError, match="SECRET_KEY must be set"):
43+
create_app(config_name)
44+
else:
45+
app = create_app(config_name)
46+
assert app.config["SECRET_KEY"] == expected_secret

0 commit comments

Comments
 (0)