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:
ZProger
2026-09-10 21:12:31 +03:00
parent eba8add92f
commit f9413aa6e1
27 changed files with 268 additions and 78 deletions

View File

@@ -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;