Files
writer-work-flow/tests/test_env_example_no_secret.py

39 lines
1.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""回归守卫:`.env.example` 不得携带可用的真实密钥CR-H8
`.env.example` 是入库模板;若其中的 `CREDENTIAL_ENC_KEY` 是一把真实可用的
Fernet key任何照抄 `.env.example` 的环境都会共用同一把泄露过的密钥。此测试
确保模板里只放**不可用占位符**——照抄到 `.env` 会在启动校验main._lifespan
处快速失败,逼迫运维生成真实 key。
"""
from __future__ import annotations
import re
from pathlib import Path
import pytest
from cryptography.fernet import Fernet
_ENV_EXAMPLE = Path(__file__).resolve().parent.parent / ".env.example"
_PLACEHOLDER = "replace-me-with-generated-fernet-key"
def _credential_enc_key() -> str:
text = _ENV_EXAMPLE.read_text(encoding="utf-8")
match = re.search(r"^CREDENTIAL_ENC_KEY=(.*)$", text, flags=re.MULTILINE)
assert match is not None, ".env.example 缺少 CREDENTIAL_ENC_KEY 行"
return match.group(1).strip()
def test_env_example_credential_key_is_non_functional_placeholder() -> None:
value = _credential_enc_key()
assert value, "CREDENTIAL_ENC_KEY 不能为空"
# 真实可用的 Fernet key 会构造成功——那正是要杜绝的泄露面。
with pytest.raises(ValueError):
Fernet(value.encode())
def test_env_example_credential_key_is_the_expected_placeholder() -> None:
# 更紧的锁:值必须恰是约定占位符,防止未来又塞进别的真实 key。
assert _credential_enc_key() == _PLACEHOLDER