sync: migrate secure-online-shop to Gitea (2026-08-10)

This commit is contained in:
konturai-ops
2026-08-10 15:26:59 +00:00
commit 2022c8890d
44 changed files with 3196 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
"""Core application utilities."""
+79
View File
@@ -0,0 +1,79 @@
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]
+82
View File
@@ -0,0 +1,82 @@
from __future__ import annotations
import logging
from fastapi import FastAPI, HTTPException, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from sqlalchemy.exc import SQLAlchemyError
logger = logging.getLogger("app.errors")
class AppError(Exception):
def __init__(self, status_code: int, detail: str) -> None:
self.status_code = status_code
self.detail = detail
super().__init__(detail)
class BadRequestError(AppError):
def __init__(self, detail: str = "Bad request") -> None:
super().__init__(status.HTTP_400_BAD_REQUEST, detail)
class UnauthorizedError(AppError):
def __init__(self, detail: str = "Authentication failed") -> None:
super().__init__(status.HTTP_401_UNAUTHORIZED, detail)
class ForbiddenError(AppError):
def __init__(self, detail: str = "Access denied") -> None:
super().__init__(status.HTTP_403_FORBIDDEN, detail)
class NotFoundError(AppError):
def __init__(self, detail: str = "Resource not found") -> None:
super().__init__(status.HTTP_404_NOT_FOUND, detail)
class ConflictError(AppError):
def __init__(self, detail: str = "Conflict detected") -> None:
super().__init__(status.HTTP_409_CONFLICT, detail)
class TooManyRequestsError(AppError):
def __init__(self, detail: str = "Too many requests") -> None:
super().__init__(status.HTTP_429_TOO_MANY_REQUESTS, detail)
def register_exception_handlers(app: FastAPI) -> None:
@app.exception_handler(AppError)
async def handle_app_error(_: Request, exc: AppError) -> JSONResponse:
return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})
@app.exception_handler(HTTPException)
async def handle_http_exception(_: Request, exc: HTTPException) -> JSONResponse:
return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})
@app.exception_handler(RequestValidationError)
async def handle_validation_error(
_: Request, exc: RequestValidationError
) -> JSONResponse:
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={"detail": "Validation error"},
)
@app.exception_handler(SQLAlchemyError)
async def handle_database_error(_: Request, exc: SQLAlchemyError) -> JSONResponse:
logger.exception("Database operation failed")
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"detail": "Internal server error"},
)
@app.exception_handler(Exception)
async def handle_unexpected_error(_: Request, exc: Exception) -> JSONResponse:
logger.exception("Unhandled application error")
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"detail": "Internal server error"},
)
+86
View File
@@ -0,0 +1,86 @@
from __future__ import annotations
import logging
import logging.config
import re
from collections.abc import Mapping, Sequence
from typing import Any
SENSITIVE_KEYS = {
"password",
"password_hash",
"token",
"access_token",
"refresh_token",
"authorization",
"email",
}
TOKEN_PATTERN = re.compile(r"Bearer\s+[A-Za-z0-9\-._~+/]+=*", re.IGNORECASE)
def _sanitize_value(value: Any) -> Any:
if isinstance(value, str):
redacted = TOKEN_PATTERN.sub("Bearer [REDACTED]", value)
for key in SENSITIVE_KEYS:
redacted = re.sub(
rf"({key}\s*=\s*)([^,\s]+)",
r"\1[REDACTED]",
redacted,
flags=re.IGNORECASE,
)
return redacted
if isinstance(value, Mapping):
return {
key: "[REDACTED]" if str(key).lower() in SENSITIVE_KEYS else _sanitize_value(item)
for key, item in value.items()
}
if isinstance(value, tuple):
return tuple(_sanitize_value(item) for item in value)
if isinstance(value, list):
return [_sanitize_value(item) for item in value]
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
return [_sanitize_value(item) for item in value]
return value
class SensitiveDataFilter(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
record.msg = _sanitize_value(record.msg)
if record.args:
record.args = _sanitize_value(record.args)
return True
def setup_logging(log_level: str) -> None:
logging.config.dictConfig(
{
"version": 1,
"disable_existing_loggers": False,
"filters": {
"sensitive_data_filter": {
"()": "app.core.logging.SensitiveDataFilter",
}
},
"formatters": {
"standard": {
"format": "%(asctime)s %(levelname)s [%(name)s] %(message)s",
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"filters": ["sensitive_data_filter"],
"formatter": "standard",
}
},
"root": {
"level": log_level.upper(),
"handlers": ["console"],
},
}
)
+92
View File
@@ -0,0 +1,92 @@
from __future__ import annotations
import hashlib
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from threading import Lock
from app.core.config import get_settings
from app.core.exceptions import TooManyRequestsError
settings = get_settings()
@dataclass(slots=True)
class _AttemptBucket:
timestamps: deque[datetime] = field(default_factory=deque)
last_seen: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
class LoginRateLimiter:
def __init__(self, attempts: int, window_seconds: int, max_buckets: int) -> None:
self.attempts = attempts
self.window = timedelta(seconds=window_seconds)
self.max_buckets = max_buckets
self._lock = Lock()
self._buckets: dict[str, _AttemptBucket] = {}
def build_key(self, username: str, client_host: str) -> str:
material = f"{username.lower()}:{client_host}".encode("utf-8")
return hashlib.sha256(material).hexdigest()
def is_limited(self, key: str) -> bool:
with self._lock:
now = datetime.now(timezone.utc)
self._cleanup(now=now)
bucket = self._buckets.get(key)
if bucket is None:
return False
self._touch(bucket, now=now)
self._prune(bucket, now=now)
return len(bucket.timestamps) >= self.attempts
def record_failure(self, key: str) -> None:
with self._lock:
now = datetime.now(timezone.utc)
self._cleanup(now=now)
bucket = self._buckets.get(key)
if bucket is None:
if len(self._buckets) >= self.max_buckets:
self._evict_oldest_bucket()
bucket = _AttemptBucket()
self._buckets[key] = bucket
self._touch(bucket, now=now)
self._prune(bucket, now=now)
bucket.timestamps.append(now)
def reset(self, key: str) -> None:
with self._lock:
self._buckets.pop(key, None)
def raise_limit_exceeded(self) -> None:
raise TooManyRequestsError("Too many login attempts. Please try again later.")
def _prune(self, bucket: _AttemptBucket, *, now: datetime) -> None:
cutoff = now - self.window
while bucket.timestamps and bucket.timestamps[0] < cutoff:
bucket.timestamps.popleft()
@staticmethod
def _touch(bucket: _AttemptBucket, *, now: datetime) -> None:
bucket.last_seen = now
def _cleanup(self, *, now: datetime) -> None:
stale_keys: list[str] = []
for key, bucket in self._buckets.items():
self._prune(bucket, now=now)
if not bucket.timestamps and bucket.last_seen < now - self.window:
stale_keys.append(key)
for key in stale_keys:
self._buckets.pop(key, None)
def _evict_oldest_bucket(self) -> None:
oldest_key = min(self._buckets, key=lambda bucket_key: self._buckets[bucket_key].last_seen)
self._buckets.pop(oldest_key, None)
login_rate_limiter = LoginRateLimiter(
attempts=settings.auth_rate_limit_attempts,
window_seconds=settings.auth_rate_limit_window_seconds,
max_buckets=settings.auth_rate_limit_max_buckets,
)
+62
View File
@@ -0,0 +1,62 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from uuid import uuid4
from jose import JWTError, jwt
from passlib.context import CryptContext
from app.core.config import get_settings
from app.core.exceptions import UnauthorizedError
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
settings = get_settings()
ACCESS_TOKEN_TYPE = "access" # nosec B105
@dataclass(slots=True)
class TokenPayload:
user_id: int
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
def create_access_token(subject: str) -> str:
now = datetime.now(timezone.utc)
expire = now + timedelta(minutes=settings.access_token_expire_minutes)
to_encode = {
"sub": subject,
"iat": int(now.timestamp()),
"nbf": int(now.timestamp()),
"exp": int(expire.timestamp()),
"jti": str(uuid4()),
"type": ACCESS_TOKEN_TYPE,
"iss": settings.jwt_issuer,
"aud": settings.jwt_audience,
}
return jwt.encode(to_encode, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
def decode_access_token(token: str) -> TokenPayload:
try:
payload = jwt.decode(
token,
settings.jwt_secret_key,
algorithms=[settings.jwt_algorithm],
issuer=settings.jwt_issuer,
audience=settings.jwt_audience,
)
subject = payload.get("sub")
token_type = payload.get("type")
if subject is None or token_type != ACCESS_TOKEN_TYPE:
raise UnauthorizedError("Could not validate credentials")
return TokenPayload(user_id=int(subject))
except (JWTError, ValueError) as exc:
raise UnauthorizedError("Could not validate credentials") from exc