Files

80 lines
2.7 KiB
Python

from __future__ import annotations
from functools import lru_cache
from pathlib import Path
from pydantic import Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
PROJECT_ROOT = Path(__file__).resolve().parents[2]
class Settings(BaseSettings):
app_name: str = "Secure E-commerce API"
api_v1_prefix: str = "/api/v1"
database_url: str = "sqlite:///./ecommerce.db"
jwt_secret_key: str = Field(min_length=32)
jwt_algorithm: str = "HS256"
jwt_issuer: str = "secure-ecommerce-api"
jwt_audience: str = "secure-ecommerce-clients"
access_token_expire_minutes: int = Field(default=30, ge=5, le=120)
auth_rate_limit_attempts: int = Field(default=5, ge=3, le=20)
auth_rate_limit_window_seconds: int = Field(default=300, ge=60, le=3600)
auth_rate_limit_max_buckets: int = Field(default=5000, ge=100, le=100_000)
log_level: str = "INFO"
demo_seed_products: bool = False
demo_product_count: int = Field(default=220, ge=0, le=1000)
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=False,
extra="ignore",
)
@field_validator("jwt_secret_key")
@classmethod
def validate_jwt_secret_key(cls, value: str) -> str:
insecure_values = {
"change-this-secret-in-production",
"replace-with-a-long-random-secret",
}
if value in insecure_values:
raise ValueError("JWT_SECRET_KEY must be replaced with a strong random secret")
return value
@field_validator("database_url")
@classmethod
def validate_database_url(cls, value: str) -> str:
sqlite_prefix = "sqlite:///"
if not value.startswith(sqlite_prefix):
return value
raw_path = value[len(sqlite_prefix):]
if raw_path == ":memory:":
return value
if (
len(raw_path) >= 3
and raw_path[1] == ":"
and raw_path[0].isalpha()
and raw_path[2] in {"/", "\\"}
):
raise ValueError(
"SQLite database file must stay inside the project directory"
)
candidate = Path(raw_path)
resolved = candidate.resolve() if candidate.is_absolute() else (PROJECT_ROOT / candidate).resolve()
try:
resolved.relative_to(PROJECT_ROOT)
except ValueError as exc:
raise ValueError("SQLite database file must stay inside the project directory") from exc
normalized_relative_path = resolved.relative_to(PROJECT_ROOT).as_posix()
return f"{sqlite_prefix}./{normalized_relative_path}"
@lru_cache
def get_settings() -> Settings:
return Settings() # type: ignore[call-arg]