mirror of
https://github.com/Zproger/Aurum.git
synced 2026-10-13 11:06:40 +07:00
security: устранить находки аудита, версия 1.1.7
Конфигурация и эксплуатационный слой: - nginx: client_max_body_size 64m — восстановление из бэкапа не работало вовсе, дефолтный лимит в 1 МБ резал дампы (реальный экспорт ~3.4 МБ) с 413 ещё до backend; - nginx: заголовки безопасности (nosniff, Referrer-Policy, Permissions-Policy) и полный Content-Security-Policy. Ради него inline-скрипт темы вынесен в public/theme-init.js; - nginx: limit_req на /api/ — перебор пароля Basic Auth шёл со скоростью сети, ни блокировки, ни задержки не было; - nginx: server_tokens off; - порт web привязан к 127.0.0.1, адрес настраивается через AURUM_BIND_ADDRESS (раньше слушался на всех интерфейсах); - backend работает от непривилегированного пользователя, no-new-privileges для backend и web; - дефолты пароля Postgres сведены к одному значению в обоих сервисах, в .env.example описана ловушка с инициализацией тома. Приложение: - версия убрана из неавторизованного /api/health и отдаётся как app_version в GET /api/settings; - /api/docs, /api/redoc и /api/openapi.json отключаются через AURUM_ENABLE_DOCS; - текст исключения при неудачном восстановлении уходит в лог, а не клиенту; - max_length для notes в схемах транзакций, активов и регулярных платежей (и в соответствующих полях UI); - срок «запомнить меня» сокращён с 30 дней до 7; - pytest обновлён до 9.0.3 (PYSEC-2026-1845), pytest-asyncio до 1.4.0; - CI: permissions contents:read для GITHUB_TOKEN.
This commit is contained in:
@@ -9,6 +9,9 @@ from app.services.settings_service import get_or_create_app_settings
|
||||
router = APIRouter(prefix="/settings", tags=["settings"])
|
||||
|
||||
|
||||
# Both routes still return the ORM row as-is: AppSettingsRead.app_version
|
||||
# isn't a stored column, it defaults to APP_VERSION when FastAPI validates
|
||||
# the response (see schemas/settings.py).
|
||||
@router.get("", response_model=AppSettingsRead)
|
||||
async def read_settings(session: AsyncSession = Depends(get_session)) -> AppSettings:
|
||||
return await get_or_create_app_settings(session)
|
||||
|
||||
@@ -4,10 +4,11 @@ from functools import lru_cache
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
# Single source of truth for the running app's version — surfaced in the API
|
||||
# title, /api/health (which the frontend reads to show it in Settings), and
|
||||
# embedded in exported backups so an old file can be told apart from a
|
||||
# current one.
|
||||
APP_VERSION = "1.1.6"
|
||||
# title, in GET /api/settings as app_version (which the frontend reads to show
|
||||
# it in Settings; it deliberately does NOT ride on the unauthenticated
|
||||
# /api/health), and embedded in exported backups so an old file can be told
|
||||
# apart from a current one.
|
||||
APP_VERSION = "1.1.7"
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
@@ -35,6 +36,14 @@ class Settings(BaseSettings):
|
||||
# rather than silently hitting CoinGecko's much stingier keyless tier.
|
||||
coingecko_api_key: str = ""
|
||||
|
||||
# Swagger/ReDoc/openapi.json at /api/docs. On by default because the API
|
||||
# is a documented feature of this app (see DOCS.md), and because when
|
||||
# basic auth is configured these sit behind it like everything else under
|
||||
# /api/. Turn it off on an instance that's reachable from the internet
|
||||
# *without* basic auth: an open /api/openapi.json is a complete,
|
||||
# machine-readable map of every endpoint and payload shape.
|
||||
enable_docs: bool = True
|
||||
|
||||
@property
|
||||
def database_url(self) -> str:
|
||||
return (
|
||||
|
||||
@@ -46,9 +46,12 @@ app = FastAPI(
|
||||
# backend (see frontend/nginx.conf) — everything else falls through to
|
||||
# the SPA's index.html, which is why the defaults (/docs, /openapi.json)
|
||||
# would silently 404 through the reverse proxy.
|
||||
docs_url="/api/docs",
|
||||
redoc_url="/api/redoc",
|
||||
openapi_url="/api/openapi.json",
|
||||
# All three go away together when AURUM_ENABLE_DOCS=false — leaving
|
||||
# openapi.json reachable would keep handing out the full API map even
|
||||
# with the Swagger UI itself switched off.
|
||||
docs_url="/api/docs" if settings.enable_docs else None,
|
||||
redoc_url="/api/redoc" if settings.enable_docs else None,
|
||||
openapi_url="/api/openapi.json" if settings.enable_docs else None,
|
||||
)
|
||||
|
||||
# CORS stays off unless someone deliberately opens it, and credentials are
|
||||
@@ -88,7 +91,10 @@ app.include_router(crypto.router, prefix="/api")
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health() -> dict[str, str]:
|
||||
# version rides along so the frontend's Settings page can show which
|
||||
# release is actually running without a separate authenticated endpoint —
|
||||
# this route is already auth_basic-exempt for Docker's HEALTHCHECK.
|
||||
return {"status": "ok", "version": APP_VERSION}
|
||||
# Status only. This is the one route nginx serves without auth (Docker's
|
||||
# HEALTHCHECK and uptime monitors need it — see frontend/nginx.conf), so
|
||||
# anything returned here is world-readable. The running version used to
|
||||
# ride along, which told an unauthenticated caller exactly which release
|
||||
# they were looking at, and therefore which known issues it still has;
|
||||
# it now comes back from GET /api/settings, which is behind auth.
|
||||
return {"status": "ok"}
|
||||
|
||||
@@ -23,7 +23,7 @@ class AssetBase(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=150)
|
||||
asset_class: AssetClass
|
||||
currency: str = Field(default="USD", min_length=3, max_length=3)
|
||||
notes: str | None = None
|
||||
notes: str | None = Field(default=None, max_length=2000)
|
||||
capital_role: CapitalRole = CapitalRole.NEUTRAL
|
||||
# Rough self-reported monthly net cash flow — informational, not tracked
|
||||
# transactions (see Asset.monthly_cash_flow).
|
||||
@@ -40,7 +40,7 @@ class AssetUpdate(BaseModel):
|
||||
name: str | None = Field(default=None, min_length=1, max_length=150)
|
||||
asset_class: AssetClass | None = None
|
||||
currency: str | None = Field(default=None, min_length=3, max_length=3)
|
||||
notes: str | None = None
|
||||
notes: str | None = Field(default=None, max_length=2000)
|
||||
capital_role: CapitalRole | None = None
|
||||
monthly_cash_flow: Decimal | None = Field(default=None, max_digits=14, decimal_places=2)
|
||||
risk_level: RiskLevel | None = None
|
||||
|
||||
@@ -15,7 +15,7 @@ class RecurringTransactionCreate(BaseModel):
|
||||
amount: Decimal = Field(gt=0)
|
||||
description: str = Field(min_length=1, max_length=255)
|
||||
merchant: str | None = None
|
||||
notes: str | None = None
|
||||
notes: str | None = Field(default=None, max_length=2000)
|
||||
frequency: RecurringFrequency
|
||||
anchor_date: date_
|
||||
|
||||
@@ -35,7 +35,7 @@ class RecurringTransactionUpdate(BaseModel):
|
||||
amount: Decimal | None = Field(default=None, gt=0)
|
||||
description: str | None = Field(default=None, min_length=1, max_length=255)
|
||||
merchant: str | None = None
|
||||
notes: str | None = None
|
||||
notes: str | None = Field(default=None, max_length=2000)
|
||||
frequency: RecurringFrequency | None = None
|
||||
anchor_date: date_ | None = None
|
||||
is_active: bool | None = None
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.core.config import APP_VERSION
|
||||
|
||||
|
||||
class AppSettingsRead(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
currency: str
|
||||
negative_cash_flow_threshold_months: int
|
||||
net_worth_decline_threshold_months: int
|
||||
risky_allocation_threshold_percent: int
|
||||
idle_cash_threshold_amount: Decimal
|
||||
idle_cash_threshold_days: int
|
||||
# Not a stored column: the default fills itself in when FastAPI validates
|
||||
# the ORM row against this model, so neither route has to assemble it.
|
||||
# It lives on this (authenticated) response rather than on /api/health,
|
||||
# which is deliberately unauthenticated and so would hand the running
|
||||
# version to anyone who can reach the instance.
|
||||
app_version: str = APP_VERSION
|
||||
|
||||
|
||||
class AppSettingsUpdate(BaseModel):
|
||||
|
||||
@@ -86,7 +86,7 @@ class TransactionFields(BaseModel):
|
||||
amount: Decimal = Field(gt=0, max_digits=14, decimal_places=2)
|
||||
description: str = Field(min_length=1, max_length=255)
|
||||
merchant: str | None = Field(default=None, max_length=150)
|
||||
notes: str | None = None
|
||||
notes: str | None = Field(default=None, max_length=2000)
|
||||
date: date_
|
||||
|
||||
# Auto-capitalizes "траты на продукты" -> "Траты на продукты" so mixed
|
||||
@@ -152,7 +152,7 @@ class TransactionUpdate(BaseModel):
|
||||
amount: Decimal | None = Field(default=None, gt=0, max_digits=14, decimal_places=2)
|
||||
description: str | None = Field(default=None, min_length=1, max_length=255)
|
||||
merchant: str | None = Field(default=None, max_length=150)
|
||||
notes: str | None = None
|
||||
notes: str | None = Field(default=None, max_length=2000)
|
||||
date: date_ | None = None
|
||||
# Omitted -> tags untouched; sent (even as []) -> replaces the full tag set.
|
||||
tag_ids: list[int] | None = None
|
||||
|
||||
@@ -9,6 +9,7 @@ run first, before any row is touched), and any failure during the swap rolls
|
||||
the database back to exactly where it was, so a bad file never leaves the
|
||||
app half-restored.
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import HTTPException
|
||||
@@ -46,6 +47,8 @@ from app.schemas.backup import (
|
||||
TransactionSplitBackup,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BACKUP_FORMAT_VERSION = 1
|
||||
|
||||
|
||||
@@ -304,4 +307,9 @@ async def restore_backup(session: AsyncSession, payload: BackupPayload) -> None:
|
||||
raise
|
||||
except Exception as exc:
|
||||
await session.rollback()
|
||||
raise HTTPException(400, f"Restore failed, no changes were made: {exc}") from exc
|
||||
# The exception text is SQLAlchemy's, naming tables, columns and
|
||||
# constraints — a free map of the schema for anyone probing the API.
|
||||
# It goes to the container log, where the operator can actually read
|
||||
# it; the client gets told only that nothing changed.
|
||||
logger.exception("Backup restore failed")
|
||||
raise HTTPException(400, "Restore failed, no changes were made") from exc
|
||||
|
||||
Reference in New Issue
Block a user