nex_docus/backend/tests/test_security_selfcheck.py

56 lines
1.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""敏感配置启动自检回归用例。
背景:docker-compose 用 `${SECRET_KEY:-your-secret-key-change-me-in-production}` 之类的
占位默认值,运维忘记改 .env 时会带着公开已知的密钥上线;这里锁定告警行为。
"""
import os
import pytest
from app.core.config import Settings
BASE_ENV = {
"DB_HOST": "localhost",
"DB_USER": "u",
"DB_PASSWORD": "p",
"DB_NAME": "d",
"REDIS_HOST": "localhost",
"REDIS_PASSWORD": "r",
"SECRET_KEY": "x" * 48,
}
def make_settings(**overrides):
env = {**BASE_ENV, **{k: str(v) for k, v in overrides.items()}}
saved = {k: os.environ.get(k) for k in env}
os.environ.update(env)
try:
return Settings(_env_file=None)
finally:
for k, v in saved.items():
if v is None:
os.environ.pop(k, None)
else:
os.environ[k] = v
def test_placeholder_secret_key_is_flagged():
s = make_settings(SECRET_KEY="your-secret-key-change-me-in-production")
assert any("SECRET_KEY" in w for w in s.security_warnings())
def test_short_secret_key_is_flagged():
s = make_settings(SECRET_KEY="abc")
assert any("SECRET_KEY" in w for w in s.security_warnings())
@pytest.mark.parametrize("password", ["User@123", "User@123456"])
def test_default_user_password_is_flagged(password):
s = make_settings(DEFAULT_USER_PASSWORD=password)
assert any("DEFAULT_USER_PASSWORD" in w for w in s.security_warnings())
def test_hardened_configuration_produces_no_warnings():
s = make_settings(SECRET_KEY="a" * 48, DEFAULT_USER_PASSWORD="R7#kQ!zs9dLp2Vt4")
assert s.security_warnings() == []