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:
@@ -6,24 +6,10 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#0b0b0b" />
|
||||
<title>Aurum — Личные финансы</title>
|
||||
<script>
|
||||
// Applies the saved theme (light/dark/system) to <html> 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.
|
||||
(function () {
|
||||
var stored = localStorage.getItem("aurum:theme");
|
||||
if (stored === "light" || stored === "dark") {
|
||||
document.documentElement.setAttribute("data-theme", stored);
|
||||
}
|
||||
var isDark =
|
||||
stored === "dark" || (stored !== "light" && window.matchMedia("(prefers-color-scheme: dark)").matches);
|
||||
var meta = document.querySelector('meta[name="theme-color"]');
|
||||
// Kept in sync by hand with index.css's --surface-0 light/dark values.
|
||||
if (meta) meta.setAttribute("content", isDark ? "#0d0d0d" : "#f9f9f7");
|
||||
})();
|
||||
</script>
|
||||
<!-- Runs before the first paint to avoid a wrong-theme flash. Kept in its
|
||||
own file (public/theme-init.js), not inline, so the CSP in
|
||||
frontend/nginx.conf can forbid inline scripts entirely. -->
|
||||
<script src="/theme-init.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "aurum-frontend",
|
||||
"private": true,
|
||||
"version": "1.1.6",
|
||||
"version": "1.1.7",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
24
frontend/public/theme-init.js
Normal file
24
frontend/public/theme-init.js
Normal file
@@ -0,0 +1,24 @@
|
||||
// Applies the saved theme (light/dark/system) to <html> 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 <script src> in
|
||||
// <head>, which still blocks the first paint, so the no-flash behaviour is
|
||||
// unchanged.
|
||||
(function () {
|
||||
var stored = localStorage.getItem("aurum:theme");
|
||||
if (stored === "light" || stored === "dark") {
|
||||
document.documentElement.setAttribute("data-theme", stored);
|
||||
}
|
||||
var isDark =
|
||||
stored === "dark" || (stored !== "light" && window.matchMedia("(prefers-color-scheme: dark)").matches);
|
||||
var meta = document.querySelector('meta[name="theme-color"]');
|
||||
// Kept in sync by hand with index.css's --surface-0 light/dark values.
|
||||
if (meta) meta.setAttribute("content", isDark ? "#0d0d0d" : "#f9f9f7");
|
||||
})();
|
||||
@@ -1,6 +0,0 @@
|
||||
import { api } from "@/api/client";
|
||||
import type { HealthStatus } from "@/types";
|
||||
|
||||
export function fetchHealth() {
|
||||
return api.get<HealthStatus>("/health");
|
||||
}
|
||||
@@ -208,6 +208,7 @@ export function AssetFormModal({ open, onClose, asset }: AssetFormModalProps) {
|
||||
<Label htmlFor="asset-notes">{t("netWorth.form.notesLabel")}</Label>
|
||||
<Input
|
||||
id="asset-notes"
|
||||
maxLength={2000}
|
||||
value={form.notes}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, notes: event.target.value }))}
|
||||
/>
|
||||
|
||||
@@ -485,8 +485,11 @@ export function TransactionFormModal({ open, onClose, transaction }: Transaction
|
||||
|
||||
<div>
|
||||
<Label htmlFor="notes">{t("transactions.form.notesLabel")}</Label>
|
||||
{/* Matches the server's max_length on notes — without it an overlong
|
||||
note only fails on save, as an untranslated 422. */}
|
||||
<Input
|
||||
id="notes"
|
||||
maxLength={2000}
|
||||
value={form.notes}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, notes: event.target.value }))}
|
||||
/>
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { fetchHealth } from "@/api/health";
|
||||
|
||||
// The running version only changes on a deploy (a full page reload), so
|
||||
// there's no need to ever refetch within a session.
|
||||
export function useHealth() {
|
||||
return useQuery({ queryKey: ["health"], queryFn: fetchHealth, staleTime: Infinity });
|
||||
}
|
||||
@@ -20,7 +20,11 @@ import { useSyncExternalStore } from "react";
|
||||
*/
|
||||
const SESSION_KEY = "aurum:basicAuth";
|
||||
const REMEMBER_KEY = "aurum:basicAuth:remember";
|
||||
const REMEMBER_DAYS = 30;
|
||||
// 7, not 30: what's stored is the Basic Auth header, i.e. the instance
|
||||
// password recoverable in plaintext by anyone who can read localStorage (an
|
||||
// XSS, a browser extension, someone with the machine). It can't be revoked
|
||||
// server-side, so the only lever on that exposure is how long it sits there.
|
||||
const REMEMBER_DAYS = 7;
|
||||
const REMEMBER_MS = REMEMBER_DAYS * 24 * 60 * 60 * 1000;
|
||||
|
||||
interface RememberedEntry {
|
||||
|
||||
@@ -49,7 +49,7 @@ const ru = {
|
||||
"auth.subtitle": "Личные финансы",
|
||||
"auth.usernameLabel": "Логин",
|
||||
"auth.passwordLabel": "Пароль",
|
||||
"auth.rememberMe": "Запомнить меня на 30 дней",
|
||||
"auth.rememberMe": "Запомнить меня на 7 дней",
|
||||
"auth.submitButton": "Войти",
|
||||
"auth.submitting": "Вход…",
|
||||
"auth.errorInvalidCredentials": "Неверный логин или пароль",
|
||||
@@ -567,7 +567,7 @@ const en: Record<keyof typeof ru, string> = {
|
||||
"auth.subtitle": "Personal finance",
|
||||
"auth.usernameLabel": "Username",
|
||||
"auth.passwordLabel": "Password",
|
||||
"auth.rememberMe": "Remember me for 30 days",
|
||||
"auth.rememberMe": "Remember me for 7 days",
|
||||
"auth.submitButton": "Sign in",
|
||||
"auth.submitting": "Signing in…",
|
||||
"auth.errorInvalidCredentials": "Incorrect username or password",
|
||||
|
||||
@@ -2,14 +2,14 @@ import { AlertThresholdsCard } from "@/components/settings/AlertThresholdsCard";
|
||||
import { BackupCard } from "@/components/settings/BackupCard";
|
||||
import { CurrencyCard } from "@/components/settings/CurrencyCard";
|
||||
import { PreferencesCard } from "@/components/settings/PreferencesCard";
|
||||
import { useHealth } from "@/hooks/useHealth";
|
||||
import { useAppSettings } from "@/hooks/useSettings";
|
||||
import { t } from "@/lib/i18n";
|
||||
|
||||
export function SettingsPage() {
|
||||
// Purely informational — if /api/health hasn't answered yet (or is
|
||||
// Purely informational — if the settings request hasn't answered yet (or is
|
||||
// unreachable), just show nothing rather than a loading/error state for
|
||||
// one line of fine print.
|
||||
const { data: health } = useHealth();
|
||||
const { data: appSettings } = useAppSettings();
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
@@ -17,9 +17,9 @@ export function SettingsPage() {
|
||||
<CurrencyCard />
|
||||
<AlertThresholdsCard />
|
||||
<BackupCard />
|
||||
{health?.version && (
|
||||
{appSettings?.app_version && (
|
||||
<p className="text-center text-xs text-text-muted">
|
||||
{t("settings.version", { version: health.version })}
|
||||
{t("settings.version", { version: appSettings.app_version })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -565,10 +565,8 @@ export interface AppSettings {
|
||||
risky_allocation_threshold_percent: number;
|
||||
idle_cash_threshold_amount: string;
|
||||
idle_cash_threshold_days: number;
|
||||
}
|
||||
|
||||
export interface HealthStatus {
|
||||
status: string;
|
||||
version: string;
|
||||
/** Read-only: the running backend release. Comes back here rather than
|
||||
* from /api/health, which is served without auth. */
|
||||
app_version: string;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user