b5546ea7bd
B.13 Error-Handling-Infrastruktur:
- ErrorCategory Enum (TRANSIENT/PERMANENT/PARTIAL), ApiError erweitert
- Einheitliches Error-Response-Format: {code, detail, field, trace_id, retryable, category}
- 3 FastAPI Exception-Handler (ApiError, HTTPException, unhandled)
- classify_exception() Helper, 6 neue Error-Codes
- 28 Tests in test_error_handling.py
B.14 Observability & trace_id-Korrelation:
- trace_id pro Request (UUID4 short) in structlog contextvars
- X-Trace-Id Response-Header
- Sensitive Fields structlog processor
- llm_complete()/llm_embed() akzeptieren trace_id kwarg
- 12 Tests in test_observability.py
B.15 Graceful Shutdown & Connection Draining:
- _shutdown_event + _inflight_requests Tracking in main.py
- drain_all_connections() in ws_helpers.py
- Worker on_shutdown pausiert WorkflowInstances (status=paused)
- 8 Tests in test_graceful_shutdown.py
B.16 API Versioning Strategie:
- Plugin-Dev-Guide Kapitel 30: URL-basiertes Versioning, Breaking Change Prozess
B.17 Cost Overrun Protection:
- llm_monthly_budget_usd + llm_hard_cutoff Settings
- _check_tenant_budget() vor jedem LLM-Call
- _track_tenant_cost() in Redis (INCRBYFLOAT)
- _check_cost_alerts() bei 50%/80%/100% -> post_system_message()
- 20 Tests in test_cost_protection.py
Total: 68 neue Tests, alle grün. Keine Regressionen.
141 lines
5.0 KiB
Python
141 lines
5.0 KiB
Python
"""Application configuration via Pydantic Settings."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from functools import lru_cache
|
|
from typing import Literal
|
|
|
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
|
|
|
|
class Settings(BaseSettings):
|
|
"""Application settings loaded from environment variables."""
|
|
|
|
model_config = SettingsConfigDict(
|
|
env_file=".env",
|
|
env_file_encoding="utf-8",
|
|
case_sensitive=False,
|
|
extra="ignore",
|
|
)
|
|
|
|
# App version (used for plugin compatibility checks)
|
|
app_version: str = "1.0.0"
|
|
|
|
# Environment
|
|
environment: Literal["development", "production", "testing"] = "development"
|
|
log_level: str = "INFO"
|
|
|
|
# Database — separate connections for auth, API, worker, and migrations
|
|
database_url: str = "postgresql+asyncpg://leocrm:leocrm@localhost:5432/leocrm_test"
|
|
auth_database_url: str = "" # Falls back to database_url if empty
|
|
worker_database_url: str = "" # Falls back to database_url if empty
|
|
migration_database_url: str = "" # Falls back to database_url if empty
|
|
db_pool_size: int = 20
|
|
db_max_overflow: int = 30
|
|
db_echo: bool = False
|
|
|
|
# Redis
|
|
redis_url: str = "redis://localhost:6379/0"
|
|
session_ttl_seconds: int = 28800 # 8 hours
|
|
|
|
# Auth
|
|
bcrypt_rounds: int = 12
|
|
session_cookie_name: str = "leocrm_session"
|
|
session_cookie_secure: bool = True # Secure by default — set to False only for local HTTP development
|
|
session_cookie_samesite: str = "lax" # Lax allows WebSocket cookies while preventing CSRF on top-level navigations
|
|
session_cookie_httponly: bool = True
|
|
password_reset_expiry_hours: int = 1
|
|
|
|
# Storage
|
|
storage_path: str = "/data/storage"
|
|
storage_max_file_size_mb: int = 50
|
|
storage_allowed_mimes: str = "" # comma-separated, empty = all allowed
|
|
|
|
# SMTP
|
|
smtp_host: str = "localhost"
|
|
smtp_port: int = 587
|
|
smtp_username: str | None = None
|
|
smtp_password: str | None = None
|
|
smtp_from_email: str = "noreply@leocrm.local"
|
|
smtp_use_tls: bool = True
|
|
|
|
# Secret Key (for signing, sessions, etc.)
|
|
secret_key: str = "change-me-in-production-use-a-secure-random-string"
|
|
|
|
# CORS
|
|
cors_origins: str = "http://localhost:5173,http://localhost:3000"
|
|
|
|
# Frontend URL for email links (password reset, invitations, etc.)
|
|
frontend_url: str = "http://localhost:5173"
|
|
|
|
# Trusted proxy CIDRs (comma-separated) — only these proxies can set X-Forwarded-For
|
|
trusted_proxy_cidrs: str = ""
|
|
|
|
# Resilience
|
|
circuit_breaker_failure_threshold: int = 5
|
|
circuit_breaker_window_seconds: int = 30
|
|
circuit_breaker_cooldown_seconds: int = 60
|
|
db_retry_max_attempts: int = 3
|
|
db_retry_base_delay: float = 0.1
|
|
|
|
# Marketplace
|
|
marketplace_server_url: str = ""
|
|
|
|
# pgvector / HNSW
|
|
hnsw_ef_construction: int = 128
|
|
hnsw_m: int = 16
|
|
hnsw_ef_search: int = 40
|
|
vector_index_type: Literal["hnsw", "ivfflat"] = "hnsw"
|
|
|
|
# Rate Limiting — legacy per-endpoint settings (kept for backward compat)
|
|
rate_limit_login_max: int = 5
|
|
rate_limit_login_window: int = 900 # 15 min
|
|
rate_limit_reset_max: int = 3
|
|
rate_limit_reset_window: int = 3600 # 1 hour
|
|
rate_limit_reset_confirm_max: int = 5
|
|
rate_limit_reset_confirm_window: int = 3600 # 1 hour
|
|
rate_limit_general_max: int = 300
|
|
rate_limit_general_window: int = 60 # 1 min
|
|
|
|
# Rate Limiting — unified policies for abuse/cost-sensitive endpoints
|
|
rate_limit_auth_max: int = 5 # login, password-reset
|
|
rate_limit_auth_window: int = 300 # 5 minutes
|
|
rate_limit_ai_max: int = 20 # AI/LLM calls
|
|
rate_limit_ai_window: int = 60 # 1 minute
|
|
rate_limit_upload_max: int = 30 # file uploads
|
|
rate_limit_upload_window: int = 60 # 1 minute
|
|
rate_limit_webhook_max: int = 100 # incoming webhooks
|
|
rate_limit_webhook_window: int = 60 # 1 minute
|
|
|
|
# LLM Cost Overrun Protection (B.17)
|
|
llm_monthly_budget_usd: float = 100.0 # per-tenant monthly LLM budget
|
|
llm_hard_cutoff: bool = True # block LLM calls when budget exceeded
|
|
|
|
@property
|
|
def cors_origin_list(self) -> list[str]:
|
|
"""Parse comma-separated CORS origins into a list."""
|
|
return [o.strip() for o in self.cors_origins.split(",") if o.strip()]
|
|
|
|
|
|
@lru_cache
|
|
def get_settings() -> Settings:
|
|
"""Get cached settings instance."""
|
|
s = Settings()
|
|
# Safety checks — always validate critical settings
|
|
_DEFAULT_KEY = "change-me-in-production-use-a-secure-random-string"
|
|
if s.secret_key == _DEFAULT_KEY:
|
|
raise RuntimeError("SECRET_KEY must be changed from default value")
|
|
if len(s.secret_key) < 32:
|
|
raise RuntimeError("SECRET_KEY must be at least 32 characters long")
|
|
# Production-only checks
|
|
if s.environment == "production":
|
|
if not s.session_cookie_secure:
|
|
raise RuntimeError("SESSION_COOKIE_SECURE must be True in production")
|
|
if s.storage_path == "/tmp":
|
|
raise RuntimeError("STORAGE_PATH must not be /tmp in production")
|
|
return s
|
|
|
|
|
|
# Module-level singleton for backward-compatible imports
|
|
settings = get_settings()
|