mirror of
https://github.com/Zproger/Aurum.git
synced 2026-10-12 18:46: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:
@@ -14,6 +14,19 @@ RUN pip install --upgrade pip && pip install -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
# Drop root. The app never writes to disk (PYTHONDONTWRITEBYTECODE above, no
|
||||
# uploads, no local cache), so it only needs read access to /app — which is
|
||||
# why the source stays root-owned and is merely readable here. Anything that
|
||||
# manages to execute code in this container now lands as an unprivileged user
|
||||
# instead of root, which is the difference between a bad day and a container
|
||||
# escape.
|
||||
#
|
||||
# Note for running the test suite (see tests/README.md): installing
|
||||
# requirements-dev.txt inside the container now needs `--user`, or run the
|
||||
# exec with `-u root`.
|
||||
RUN useradd --create-home --uid 10001 aurum
|
||||
USER aurum
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=5s --start-period=10s --retries=5 \
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
# backend container (see backend/tests/README.md) rather than baking these
|
||||
# into the Docker image.
|
||||
-r requirements.txt
|
||||
pytest==8.3.4
|
||||
pytest-asyncio==0.25.0
|
||||
pytest==9.0.3
|
||||
pytest-asyncio==1.4.0
|
||||
httpx==0.28.1
|
||||
|
||||
@@ -14,12 +14,22 @@ lifetime, then run pytest inside the running `backend` container — it's the
|
||||
only place with network access to Postgres:
|
||||
|
||||
```bash
|
||||
docker compose exec backend pip install -r requirements-dev.txt
|
||||
docker compose exec backend pytest -v
|
||||
docker compose exec backend pip install --user -r requirements-dev.txt
|
||||
docker compose exec backend python -m pytest -v
|
||||
```
|
||||
|
||||
Re-run just `pytest -v` for subsequent runs; the `pip install` only needs
|
||||
repeating after a container restart/rebuild.
|
||||
Re-run just the `python -m pytest -v` line for subsequent runs; the
|
||||
`pip install` only needs repeating after a container restart/rebuild.
|
||||
|
||||
Two details that both come from the container running as an unprivileged user
|
||||
(`aurum`, uid 10001 — see backend/Dockerfile) rather than root:
|
||||
|
||||
- `--user` on the install: site-packages belongs to root and isn't writable.
|
||||
The packages land in `/home/aurum/.local`, which isn't on `PATH`, hence
|
||||
`python -m pytest` instead of a bare `pytest`.
|
||||
- pytest prints a `PytestCacheWarning` about not being able to write
|
||||
`/app/.pytest_cache`. Expected — the source tree is read-only to the app
|
||||
user by design. Tests still pass; add `-p no:cacheprovider` to silence it.
|
||||
|
||||
## Adding a test
|
||||
|
||||
|
||||
Reference in New Issue
Block a user