diff --git a/.env.example b/.env.example index 472ce46..bdc9fa7 100644 --- a/.env.example +++ b/.env.example @@ -1,6 +1,17 @@ # Copy this file to .env and adjust values before running `docker compose up`. # --- Postgres --- +# IMPORTANT, and easy to get wrong: Postgres only applies this password when +# it FIRST creates its data directory. Change it later and the running +# database keeps the old one — the value here and the value in the database +# drift apart, and the backend starts failing to connect with a password +# authentication error that looks like it came out of nowhere. So set it +# before the first `docker compose up`. Changing it afterwards means either +# ALTER USER inside the running database, or deleting the aurum_pgdata volume +# (which deletes all your data — export a backup from Settings first). +# +# The database is not published to your host machine (no ports mapping for the +# db service), so it's only reachable from inside the container network. AURUM_POSTGRES_USER=aurum AURUM_POSTGRES_PASSWORD=change-me AURUM_POSTGRES_DB=aurum @@ -23,6 +34,13 @@ AURUM_DEFAULT_CURRENCY=USD # you to set this — nothing else in the app is affected. AURUM_COINGECKO_API_KEY= +# Swagger UI / ReDoc / openapi.json at /api/docs. Left on: the REST API is a +# documented feature (see DOCS.md), and when basic auth is configured these +# sit behind it like every other /api/ route. Set it to false on an instance +# that's reachable from the internet without basic auth — an open +# openapi.json is a complete machine-readable map of every endpoint. +AURUM_ENABLE_DOCS=true + # --- Basic auth (STRONGLY recommended if this instance is reachable from # anywhere other than your own machine) --- # Aurum has no login system of its own — it's built for one person @@ -36,3 +54,10 @@ AURUM_BASIC_AUTH_PASSWORD= # --- Ports exposed on your host machine --- AURUM_WEB_PORT=3000 + +# Which host interface Aurum listens on. The default, 127.0.0.1, means "this +# machine only" — nothing else on your network can reach it. Change it to +# 0.0.0.0 to open it up (phone on the same Wi-Fi, another PC, a reverse +# proxy), but set the basic auth variables above first: without them the app +# has no password, and this is the line that decides who can knock. +AURUM_BIND_ADDRESS=127.0.0.1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a96f9cb..0d33e25 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,6 +8,12 @@ on: push: branches: [main] +# Least privilege for GITHUB_TOKEN: these jobs only ever read the checkout. +# Without this the token inherits the repository default, which can include +# write access — handed to every third-party action in the run. +permissions: + contents: read + jobs: backend-tests: runs-on: ubuntu-latest diff --git a/DOCS.md b/DOCS.md index d1c2463..8aa0691 100644 --- a/DOCS.md +++ b/DOCS.md @@ -116,9 +116,13 @@ string. ### `GET /api/health` -No auth required. Returns `{"status": "ok", "version": "1.1.0"}` — `version` is the running app's -version, the same value shown in the UI under Settings. Use this to check the backend is up before -hitting anything else. +No auth required. Returns `{"status": "ok"}`. Use this to check the backend is up before hitting +anything else. + +This response deliberately carries nothing else. It used to include the running app version, but +this is the one endpoint served without authentication — handing the exact release to anyone who +can reach the instance tells them which known issues it still has. The version now comes back as +`app_version` from `GET /settings`, which sits behind auth like everything else. ## Accounts @@ -763,10 +767,13 @@ Single row, created automatically on first run — there's nothing to create, on "net_worth_decline_threshold_months": 2, "risky_allocation_threshold_percent": 20, "idle_cash_threshold_amount": "1000.00", - "idle_cash_threshold_days": 60 + "idle_cash_threshold_days": 60, + "app_version": "1.1.7" } ``` +- `app_version`: read-only, ignored on `PATCH` — the running app's release, shown in the UI under + Settings. It lives here rather than on the unauthenticated `/health`. - `currency`: 3-letter uppercase code — display-only, no conversion. - `negative_cash_flow_threshold_months` / `net_worth_decline_threshold_months`: consecutive months before the corresponding alert fires (`1`–`24`). diff --git a/backend/Dockerfile b/backend/Dockerfile index bfb7872..98a2b13 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -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 \ diff --git a/backend/app/api/routes/settings.py b/backend/app/api/routes/settings.py index 40de89b..2010976 100644 --- a/backend/app/api/routes/settings.py +++ b/backend/app/api/routes/settings.py @@ -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) diff --git a/backend/app/core/config.py b/backend/app/core/config.py index ac0d37c..2ed65b9 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -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 ( diff --git a/backend/app/main.py b/backend/app/main.py index ce2dacd..a75b782 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -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"} diff --git a/backend/app/schemas/asset.py b/backend/app/schemas/asset.py index 74007d5..7698b39 100644 --- a/backend/app/schemas/asset.py +++ b/backend/app/schemas/asset.py @@ -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 diff --git a/backend/app/schemas/recurring.py b/backend/app/schemas/recurring.py index 17e7e7e..5bc6443 100644 --- a/backend/app/schemas/recurring.py +++ b/backend/app/schemas/recurring.py @@ -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 diff --git a/backend/app/schemas/settings.py b/backend/app/schemas/settings.py index 0bdde0b..9d03c43 100644 --- a/backend/app/schemas/settings.py +++ b/backend/app/schemas/settings.py @@ -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): diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.py index 6c11014..3c0d595 100644 --- a/backend/app/schemas/transaction.py +++ b/backend/app/schemas/transaction.py @@ -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 diff --git a/backend/app/services/backup_service.py b/backend/app/services/backup_service.py index 5c939a2..21942d5 100644 --- a/backend/app/services/backup_service.py +++ b/backend/app/services/backup_service.py @@ -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 diff --git a/backend/requirements-dev.txt b/backend/requirements-dev.txt index 8f93b12..cec7943 100644 --- a/backend/requirements-dev.txt +++ b/backend/requirements-dev.txt @@ -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 diff --git a/backend/tests/README.md b/backend/tests/README.md index b67c83a..abb83b8 100644 --- a/backend/tests/README.md +++ b/backend/tests/README.md @@ -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 diff --git a/docker-compose.yml b/docker-compose.yml index 5e278ad..983b316 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -4,7 +4,14 @@ services: restart: unless-stopped environment: POSTGRES_USER: ${AURUM_POSTGRES_USER:-aurum} - POSTGRES_PASSWORD: ${AURUM_POSTGRES_PASSWORD:-aurum} + # "change-me" so this matches .env.example exactly: with no .env at all + # the fallback here used to be "aurum" while the template said + # "change-me", i.e. "the default password" meant two different things + # depending on whether the file existed. Postgres isn't published to the + # host (no ports: below), so reaching it means already being on the + # container network — but see .env.example for the trap that makes this + # worth getting right the first time. + POSTGRES_PASSWORD: ${AURUM_POSTGRES_PASSWORD:-change-me} POSTGRES_DB: ${AURUM_POSTGRES_DB:-aurum} volumes: - aurum_pgdata:/var/lib/postgresql/data @@ -17,9 +24,17 @@ services: backend: build: ./backend restart: unless-stopped + # Nothing here ever needs to gain privileges (no setuid binaries, no sudo), + # so forbid it outright — this is what stops a compromised process from + # escalating back to root inside the container. + security_opt: + - no-new-privileges:true environment: AURUM_POSTGRES_USER: ${AURUM_POSTGRES_USER:-aurum} - AURUM_POSTGRES_PASSWORD: ${AURUM_POSTGRES_PASSWORD:-aurum} + # Must stay identical to the db service's fallback above — if the two + # drift, an install without .env brings up a database with one password + # and a backend dialling it with another. + AURUM_POSTGRES_PASSWORD: ${AURUM_POSTGRES_PASSWORD:-change-me} AURUM_POSTGRES_DB: ${AURUM_POSTGRES_DB:-aurum} AURUM_POSTGRES_HOST: db AURUM_POSTGRES_PORT: 5432 @@ -28,6 +43,7 @@ services: # Free CoinGecko Demo key (coingecko.com/en/api/pricing) — the Crypto # tab's price sync 400s with a clear message until this is set. AURUM_COINGECKO_API_KEY: ${AURUM_COINGECKO_API_KEY:-} + AURUM_ENABLE_DOCS: ${AURUM_ENABLE_DOCS:-true} depends_on: db: condition: service_healthy @@ -35,8 +51,19 @@ services: web: build: ./frontend restart: unless-stopped + # nginx's master still needs root to bind :80 and to write the htpasswd + # file at boot (docker-entrypoint.d/20-basic-auth.sh), so this one can't + # drop to a non-root user without reworking both — but it can still be + # barred from escalating any further. + security_opt: + - no-new-privileges:true ports: - - "${AURUM_WEB_PORT:-3000}:80" + # Bound to loopback by default: published as "3000:80" the app answers + # on every interface, so anyone on the same Wi-Fi reaches it — and by + # default there is no password on it at all (see 20-basic-auth.sh). + # Set AURUM_BIND_ADDRESS=0.0.0.0 to reach it from other devices, but + # set AURUM_BASIC_AUTH_USER/PASSWORD before you do. + - "${AURUM_BIND_ADDRESS:-127.0.0.1}:${AURUM_WEB_PORT:-3000}:80" environment: # Both unset = no login screen at all. See frontend/docker-entrypoint.d/20-basic-auth.sh. AURUM_BASIC_AUTH_USER: ${AURUM_BASIC_AUTH_USER:-} diff --git a/frontend/index.html b/frontend/index.html index b4cf15a..a99cbf4 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -6,24 +6,10 @@ Aurum — Личные финансы - + +
diff --git a/frontend/nginx.conf b/frontend/nginx.conf index eb55a53..6eea216 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -1,9 +1,53 @@ +# Rate limit shared by every /api/ request. This file is included from inside +# nginx's http{} block, which is the only context where a zone can be declared. +# Basic Auth has no lockout, no captcha and no delay of its own, so without +# this the single instance password can be guessed at network speed. The rate +# is deliberately well above what the UI needs (a dashboard load fires a +# dozen or so queries at once, and CSV import pages through history) and still +# cuts a brute-force attempt by orders of magnitude. +limit_req_zone $binary_remote_addr zone=aurum_api:10m rate=20r/s; + server { listen 80; server_name _; root /usr/share/nginx/html; index index.html; + # Don't advertise the exact nginx version — it turns "is this instance + # vulnerable to X" into a lookup instead of a probe. + server_tokens off; + + # Security headers, applied at server level so every location inherits + # them. Note for whoever edits this next: adding an add_header inside a + # location block drops ALL of these for that location — nginx does not + # merge them. + add_header X-Content-Type-Options "nosniff" always; + add_header Referrer-Policy "no-referrer" always; + add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always; + + # Enforced. This started out as Content-Security-Policy-Report-Only, but + # Report-Only without a report-uri/report-to endpoint is inert in Firefox + # — it says so itself in the console: "CSP will not block and cannot + # report violations of this policy". So an empty console proved nothing, + # and the choice was between standing up a report-collecting endpoint for + # a single self-hosted app or enforcing and watching. Enforcing wins: a + # violation then shows up in every browser's console *and* as a visibly + # broken element, and rolling back is renaming this one header. + # + # Why each part is the way it is: + # script-src 'self' — verified: the built bundle contains no eval/ + # new Function, and the theme script was moved + # out of index.html into /theme-init.js. + # style-src 'unsafe-inline' — unavoidable for now: 27 components use + # style={{...}} and Recharts injects inline + # styles of its own. + # img-src ... coingecko — coin icons come straight from CoinGecko's + # CDN (thumb_url on a holding); both the + # current and the older asset host are listed. + # img-src blob: — the chart/download paths build blob URLs. + # connect-src 'self' — the API is same-origin; nothing else is called. + add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https://coin-images.coingecko.com https://assets.coingecko.com; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always; + # Always open, no auth — this is what Docker's own HEALTHCHECK and any # external uptime monitor hit, and it returns nothing but {"status":"ok"}. # docker-entrypoint.d/20-basic-auth.sh writes basic-auth.conf; without an @@ -11,6 +55,11 @@ server { # sets below and healthchecks would start failing with 401. location = /api/health { auth_basic off; + # Rate limited too: this is the one unauthenticated route, so it's the + # one an attacker can hammer for free. Docker's HEALTHCHECK hits it + # once every 10s, nowhere near the limit. + limit_req zone=aurum_api burst=40 nodelay; + limit_req_status 429; proxy_pass http://backend:8000/api/health; proxy_set_header Host $host; } @@ -20,6 +69,21 @@ server { # aren't set, so this is a no-op by default) — see docker-entrypoint.d/. location /api/ { include /etc/nginx/basic-auth.conf; + + limit_req zone=aurum_api burst=40 nodelay; + limit_req_status 429; + + # Backup restore posts the whole snapshot as one JSON body, and a + # real one runs to several MB — nginx's 1m default silently rejected + # those with a 413 before they ever reached the backend, which meant + # backups could be taken but not restored. Bounded on purpose rather + # than disabled (0), so an oversized upload still can't exhaust memory. + client_max_body_size 64m; + client_body_timeout 60s; + # A large restore rewrites every table in one transaction; the default + # 60s read timeout can cut that off midway. + proxy_read_timeout 120s; + proxy_pass http://backend:8000/api/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; diff --git a/frontend/package.json b/frontend/package.json index 8e67e2c..56444eb 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "aurum-frontend", "private": true, - "version": "1.1.6", + "version": "1.1.7", "type": "module", "scripts": { "dev": "vite", diff --git a/frontend/public/theme-init.js b/frontend/public/theme-init.js new file mode 100644 index 0000000..c18f8d5 --- /dev/null +++ b/frontend/public/theme-init.js @@ -0,0 +1,24 @@ +// Applies the saved theme (light/dark/system) to before the first +// paint, so an explicit override never flashes the wrong theme for a frame +// while React/lib/theme.ts loads. "system" needs no attribute at all — +// index.css's prefers-color-scheme media query already handles that case +// with zero JS. +// +// Lives in public/ as its own file rather than inline in index.html so the +// Content-Security-Policy in frontend/nginx.conf can forbid inline scripts +// outright — an inline block would need either 'unsafe-inline' (which gives +// up most of what CSP buys) or a hash that has to be regenerated by hand on +// every edit to these lines. Loaded as a plain synchronous