fix(config): rifiuta i segreti di default fuori da dev/test (#33, parte A2)

Nuova impostazione app_env (env APP_ENV, default "dev"). All'istanza di
Settings, se app_env non è "dev"/"test" e SERVER_SECRET_KEY o
DB_PASSWORD sono ancora il valore committato, RuntimeError che nomina
la variabile. Dev e test continuano a partire senza .env: il default
"dev" non fa mai scattare la guardia.

Le parti frontend (flask_app/config.py) e deploy (docker-compose.yml)
di questa issue sono degli altri lotti (B2, C2).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-21 22:41:28 +02:00
parent 0ec5988581
commit a2f357b3d3
2 changed files with 89 additions and 2 deletions
+39 -2
View File
@@ -1,22 +1,37 @@
"""TieMeasureFlow Server Configuration."""
from pathlib import Path
from pydantic import model_validator
from pydantic_settings import BaseSettings
# Committed defaults. Fine for dev/test (SQLite in-memory, nothing exposed); a
# real deployment that still has these is running on secrets anyone can read
# in this file's git history.
_DEFAULT_SECRET_KEY = "change-this-to-a-random-secret-key"
_DEFAULT_DB_PASSWORD = "change_me_in_production"
class Settings(BaseSettings):
"""Application settings loaded from environment variables."""
# Deployment environment. "dev" and "test" skip the production-only guard
# below; anything else (e.g. "production") is treated as a real
# deployment. Local dev and the test suite must keep starting with no
# .env at all, which is why this defaults to "dev" rather than requiring
# the variable.
app_env: str = "dev"
# Database
db_host: str = "localhost"
db_port: int = 3306
db_name: str = "tiemeasureflow"
db_user: str = "tmflow"
db_password: str = "change_me_in_production"
db_password: str = _DEFAULT_DB_PASSWORD
# Server
server_host: str = "0.0.0.0"
server_port: int = 8000
server_secret_key: str = "change-this-to-a-random-secret-key"
server_secret_key: str = _DEFAULT_SECRET_KEY
server_cors_origins: str = "http://localhost:5000"
# Worker processes (e.g. `uvicorn --workers N`). Each rate-limit bucket lives
# in process memory, so this is how RateLimitMiddleware divides the
@@ -86,5 +101,27 @@ class Settings(BaseSettings):
"extra": "ignore",
}
@model_validator(mode="after")
def _refuse_default_secrets_outside_dev(self) -> "Settings":
"""Refuse to boot with a committed default secret in a real deployment.
Only fires when APP_ENV names an actual deployment (not "dev"/"test"),
so local development and the test suite keep starting with no .env at
all.
"""
if self.app_env in ("dev", "test"):
return self
if self.server_secret_key == _DEFAULT_SECRET_KEY:
raise RuntimeError(
"SERVER_SECRET_KEY is still the committed default value; "
"set it before running with APP_ENV=" + self.app_env
)
if self.db_password == _DEFAULT_DB_PASSWORD:
raise RuntimeError(
"DB_PASSWORD is still the committed default value; "
"set it before running with APP_ENV=" + self.app_env
)
return self
settings = Settings()