fix(config): la app no arranca sin SECRET_KEY propia
Sin clave por defecto en el repo. Vacía o con un valor de ejemplo, Settings falla con un mensaje claro; solo APP_ENV=test arranca sin ella (genera una al vuelo). APP_ENV: dev | test | prod, por omisión prod.
This commit is contained in:
1 parent
bac8982058
commit
bbc8fd50af
3 files changed
+103
-3
No files matched your search
+23
-3
@@ -2,22 +2,29 @@
|
||||
|
||||
El esquema de CHM vive fuera del repositorio: solo se referencia por ruta en `CHM_SCHEMA_PATH`.
|
||||
`ANONYMIZE_SALT` vacía ⇒ se genera una sal al vuelo por proceso y nunca se persiste.
|
||||
`SECRET_KEY` es obligatoria: sin ella (o con un valor de ejemplo) la app no arranca, salvo con
|
||||
`APP_ENV=test`, donde se genera una al vuelo.
|
||||
"""
|
||||
|
||||
import secrets
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Literal, Self
|
||||
|
||||
from pydantic import Field, PrivateAttr
|
||||
from pydantic import Field, PrivateAttr, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
# Valores que nunca firman sesiones fuera de tests: vacío y los de ejemplo o de versiones previas.
|
||||
CLAVES_DE_EJEMPLO = frozenset({"", "dev-solo-local-cambiar", "cambiar", "changeme"})
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
|
||||
|
||||
secret_key: str = Field(
|
||||
default="dev-solo-local-cambiar", description="Firma de la cookie de sesión."
|
||||
app_env: Literal["dev", "test", "prod"] = Field(
|
||||
default="prod", description="Solo `test` permite arrancar sin SECRET_KEY."
|
||||
)
|
||||
secret_key: str = Field(default="", description="Firma de la cookie de sesión. Obligatoria.")
|
||||
database_url: str = Field(default="sqlite:///./data/pld.db")
|
||||
data_dir: Path = Field(default=Path("./data"))
|
||||
chm_schema_path: Path | None = Field(
|
||||
@@ -30,6 +37,19 @@ class Settings(BaseSettings):
|
||||
|
||||
_sal_sesion: str = PrivateAttr(default_factory=lambda: secrets.token_hex(32))
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _exigir_secret_key(self) -> Self:
|
||||
if self.secret_key.strip() in CLAVES_DE_EJEMPLO:
|
||||
if self.app_env != "test":
|
||||
raise ValueError(
|
||||
"SECRET_KEY no está definida o es un valor de ejemplo: la app no arranca "
|
||||
"sin una clave propia. Genera una con "
|
||||
'`python -c "import secrets; print(secrets.token_urlsafe(48))"` '
|
||||
"(solo APP_ENV=test arranca sin ella)."
|
||||
)
|
||||
self.secret_key = secrets.token_urlsafe(48)
|
||||
return self
|
||||
|
||||
@property
|
||||
def sal_anonimizacion(self) -> str:
|
||||
"""Sal efectiva para el hash de identificadores. Nunca se guarda en base ni en logs."""
|
||||
|
||||
@@ -8,6 +8,7 @@ from fastapi.testclient import TestClient
|
||||
|
||||
# Las settings se leen antes de importar la app; en tests nunca se toca ./data.
|
||||
os.environ.setdefault("DATABASE_URL", "sqlite://")
|
||||
os.environ.setdefault("APP_ENV", "test")
|
||||
os.environ.setdefault("SECRET_KEY", "secreto-de-pruebas")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""`SECRET_KEY` obligatoria: sin ella la app no arranca, salvo con `APP_ENV=test`."""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.config import Settings
|
||||
|
||||
RAIZ = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def entorno_limpio(monkeypatch: pytest.MonkeyPatch) -> pytest.MonkeyPatch:
|
||||
for variable in ("SECRET_KEY", "APP_ENV"):
|
||||
monkeypatch.delenv(variable, raising=False)
|
||||
return monkeypatch
|
||||
|
||||
|
||||
@pytest.mark.parametrize("clave", [None, "", " ", "dev-solo-local-cambiar"])
|
||||
@pytest.mark.parametrize("app_env", [None, "dev", "prod"])
|
||||
def test_sin_secret_key_propia_las_settings_fallan(
|
||||
entorno_limpio: pytest.MonkeyPatch, clave: str | None, app_env: str | None
|
||||
) -> None:
|
||||
if clave is not None:
|
||||
entorno_limpio.setenv("SECRET_KEY", clave)
|
||||
if app_env is not None:
|
||||
entorno_limpio.setenv("APP_ENV", app_env)
|
||||
|
||||
with pytest.raises(ValidationError, match="SECRET_KEY no está definida"):
|
||||
Settings(_env_file=None)
|
||||
|
||||
|
||||
def test_con_app_env_test_arranca_sin_secret_key(entorno_limpio: pytest.MonkeyPatch) -> None:
|
||||
entorno_limpio.setenv("APP_ENV", "test")
|
||||
|
||||
settings = Settings(_env_file=None)
|
||||
|
||||
assert len(settings.secret_key) >= 32
|
||||
assert Settings(_env_file=None).secret_key != settings.secret_key # se genera por proceso
|
||||
|
||||
|
||||
def test_una_secret_key_propia_se_respeta(entorno_limpio: pytest.MonkeyPatch) -> None:
|
||||
entorno_limpio.setenv("SECRET_KEY", "una-clave-propia-y-larga")
|
||||
assert Settings(_env_file=None).secret_key == "una-clave-propia-y-larga"
|
||||
|
||||
|
||||
def _arrancar_app(tmp_path: Path, **extra: str) -> subprocess.CompletedProcess[str]:
|
||||
"""Importa `app.main` en un proceso aparte, sin `.env` y sin las variables del test."""
|
||||
entorno = {
|
||||
clave: valor
|
||||
for clave, valor in os.environ.items()
|
||||
if clave not in ("SECRET_KEY", "APP_ENV")
|
||||
}
|
||||
entorno |= {"PYTHONPATH": str(RAIZ), "DATABASE_URL": "sqlite://", **extra}
|
||||
return subprocess.run(
|
||||
[sys.executable, "-c", "import app.main"],
|
||||
cwd=tmp_path,
|
||||
env=entorno,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=60,
|
||||
)
|
||||
|
||||
|
||||
def test_sin_secret_key_la_app_no_levanta(tmp_path: Path) -> None:
|
||||
proceso = _arrancar_app(tmp_path)
|
||||
|
||||
assert proceso.returncode != 0
|
||||
assert "SECRET_KEY no está definida" in proceso.stderr
|
||||
|
||||
|
||||
def test_con_app_env_test_la_app_levanta(tmp_path: Path) -> None:
|
||||
proceso = _arrancar_app(tmp_path, APP_ENV="test")
|
||||
|
||||
assert proceso.returncode == 0, proceso.stderr
|
||||
Reference in new issue
Block a user