Шхуна не тонет: security, infra и доки на русском.

Безопасность довёл до ума — Cursor-генерацию переписал руками.
IDOR закрыл, CSRF задушил, refresh rotation теперь как надо.
HSTS на staging, ENABLE_DOCS=false, install.env recovery протестил.

Backend:
- jwt_denylist + auth_epoch: мгновенный revoke access JWT (logout/block/reset)
- auth/admin/users: bump epoch, logout с Bearer, forgot_password skip для blocked
- install_secrets: путь всегда apps/api/data/secrets/ (bootstrap из корня не ломает Docker)
- seed: SEED_DEMO_USERS=false на prod/staging
- тесты: jwt revoke, integration, coverage gate 90%

Frontend:
- logout шлёт Bearer, обработка TOKEN_REVOKED
- guards TypeScript fix
- E2E: blocked user → 401 сразу после block

Infra:
- staging/prod compose, TLS nginx, deploy-скрипты
- k6 §17.2, backup/health/smoke scripts

Docs:
- docs/ на русском: project, security, deploy, release (старые md слили)
- README короткий + план ТЗ + стандартные логины dev

Код готов к плаванию. Капитан может идти писать фронт.
This commit is contained in:
влад
2026-07-15 00:06:13 +03:00
parent 86cc3fa541
commit 12c983c0fc
66 changed files with 2377 additions and 520 deletions
+13
View File
@@ -0,0 +1,13 @@
# Copy to infra/docker/.env.production and fill in production values.
FRONTEND_URL=https://compton.example.com
PUBLIC_BASE_URL=https://compton.example.com
CORS_ORIGINS=["https://compton.example.com"]
TRUSTED_PROXY_IPS=172.16.0.0/12,10.0.0.0/8
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=
SMTP_PASSWORD=
SMTP_FROM=noreply@compton.example.com
TLS_CERT_DIR=./certs
ADMIN_INITIAL_PASSWORD=ChangeMeProductionAdmin1234
SEED_DEMO_USERS=false
+12
View File
@@ -0,0 +1,12 @@
# Copy to infra/docker/.env.staging and fill in domain/SMTP values.
FRONTEND_URL=https://staging.example.com
PUBLIC_BASE_URL=https://staging.example.com
CORS_ORIGINS=["https://staging.example.com"]
TRUSTED_PROXY_IPS=172.16.0.0/12,10.0.0.0/8
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=
SMTP_PASSWORD=
SMTP_FROM=noreply@example.com
TLS_CERT_DIR=./certs
ADMIN_INITIAL_PASSWORD=ChangeMeStagingAdmin1234
+30 -3
View File
@@ -1,4 +1,31 @@
# Docker notes
# Docker deployment
`docker-compose.yml` is for local development.
`docker-compose.test.yml` is for CI-like integration and e2e testing.
Краткая справка. Подробный runbook: [docs/deploy.md](../../docs/deploy.md).
| Файл | Среда |
|------|-------|
| [`../../docker-compose.yml`](../../docker-compose.yml) | Локальная разработка |
| [`../../docker-compose.test.yml`](../../docker-compose.test.yml) | CI / E2E |
| [`docker-compose.staging.yml`](docker-compose.staging.yml) | Staging VPS |
| [`docker-compose.prod.yml`](docker-compose.prod.yml) | Production VPS |
## Staging
```bash
cp infra/docker/.env.staging.example infra/docker/.env.staging
# TLS: infra/docker/certs/fullchain.pem, privkey.pem
python3 apps/api/scripts/bootstrap_install.py
./infra/docker/deploy-staging.sh
```
## Production
```bash
cp infra/docker/.env.production.example infra/docker/.env.production
python3 apps/api/scripts/bootstrap_install.py
./infra/docker/deploy-prod.sh infra/docker/.env.production
```
## QA на staging
См. [docs/release.md](../../docs/release.md): E2E, k6, ZAP, Lighthouse.
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$ROOT"
ENV_FILE="${1:-infra/docker/.env.production}"
if [[ ! -f "$ENV_FILE" ]]; then
echo "Missing $ENV_FILE — copy infra/docker/.env.production.example first."
exit 1
fi
if [[ ! -f apps/api/data/secrets/install.env ]]; then
python3 apps/api/scripts/bootstrap_install.py
fi
docker compose \
-f infra/docker/docker-compose.prod.yml \
--env-file "$ENV_FILE" \
up -d --build
echo "Production deploy complete."
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$ROOT"
ENV_FILE="${1:-infra/docker/.env.staging}"
if [[ ! -f "$ENV_FILE" ]]; then
echo "Missing $ENV_FILE — copy infra/docker/.env.staging.example first."
exit 1
fi
if [[ ! -f apps/api/data/secrets/install.env ]]; then
python3 apps/api/scripts/bootstrap_install.py
fi
docker compose \
-f infra/docker/docker-compose.staging.yml \
--env-file "$ENV_FILE" \
up -d --build
echo "Staging deploy complete. Verify: curl -k https://\$(grep FRONTEND_URL $ENV_FILE | cut -d= -f2)/api/v1/health"
+99
View File
@@ -0,0 +1,99 @@
# Production stack — VPS deploy.
# Usage:
# python apps/api/scripts/bootstrap_install.py
# cp infra/docker/.env.production.example infra/docker/.env.production
# docker compose -f infra/docker/docker-compose.prod.yml --env-file infra/docker/.env.production up -d --build
services:
postgres:
image: postgres:16
restart: unless-stopped
env_file:
- ../../apps/api/data/secrets/install.env
volumes:
- prod_postgres_data:/var/lib/postgresql/data
networks:
- internal
redis:
image: redis:7-alpine
restart: unless-stopped
networks:
- internal
minio:
image: minio/minio
restart: unless-stopped
command: server /data --console-address ":9001"
env_file:
- ../../apps/api/data/secrets/install.env
volumes:
- prod_minio_data:/data
networks:
- internal
api:
build:
context: ../../apps/api
dockerfile: Dockerfile
restart: unless-stopped
environment:
APP_ENV: production
ENABLE_DOCS: "false"
ENABLE_TEST_ROUTES: "false"
COOKIE_SECURE: "true"
ENABLE_RATE_LIMIT: "true"
EMAIL_DELIVERY_MODE: smtp
STORAGE_MODE: s3
S3_ENDPOINT: http://minio:9000
REDIS_URL: redis://redis:6379/0
SEED_DEMO_USERS: "false"
env_file:
- ../../apps/api/data/secrets/install.env
- .env.production
volumes:
- ../../apps/api/data/secrets:/app/data/secrets
- prod_api_logs:/app/data/logs
depends_on:
- postgres
- redis
- minio
networks:
- internal
web:
build:
context: ../..
dockerfile: apps/web/Dockerfile
restart: unless-stopped
environment:
VITE_USE_API_PROXY: "true"
VITE_API_URL: http://api:8000
depends_on:
- api
networks:
- internal
nginx:
image: nginx:stable-alpine
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- ../nginx/default.tls.conf:/etc/nginx/conf.d/default.conf:ro
- ${TLS_CERT_DIR:-./certs}:/etc/nginx/certs:ro
depends_on:
- web
- api
networks:
- internal
networks:
internal:
driver: bridge
volumes:
prod_postgres_data:
prod_minio_data:
prod_api_logs:
+78 -4
View File
@@ -1,9 +1,83 @@
# Staging stack — VPS deploy (no bind mounts, production-like settings).
# Usage:
# cp infra/docker/.env.staging.example infra/docker/.env.staging
# docker compose -f infra/docker/docker-compose.staging.yml --env-file infra/docker/.env.staging up -d --build
services:
web:
image: compton/web:staging
postgres:
image: postgres:16
restart: unless-stopped
env_file:
- ../../apps/api/data/secrets/install.env
volumes:
- staging_postgres_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
restart: unless-stopped
minio:
image: minio/minio
restart: unless-stopped
command: server /data --console-address ":9001"
env_file:
- ../../apps/api/data/secrets/install.env
volumes:
- staging_minio_data:/data
api:
image: compton/api:staging
build:
context: ../../apps/api
dockerfile: Dockerfile
restart: unless-stopped
environment:
APP_ENV: staging
ENABLE_DOCS: "false"
ENABLE_TEST_ROUTES: "false"
COOKIE_SECURE: "true"
ENABLE_RATE_LIMIT: "true"
EMAIL_DELIVERY_MODE: smtp
STORAGE_MODE: s3
S3_ENDPOINT: http://minio:9000
REDIS_URL: redis://redis:6379/0
SEED_DEMO_USERS: "false"
env_file:
- ../../apps/api/.env.example
- ../../apps/api/data/secrets/install.env
- .env.staging
volumes:
- ../../apps/api/data/secrets:/app/data/secrets
- staging_api_logs:/app/data/logs
depends_on:
- postgres
- redis
- minio
web:
build:
context: ../..
dockerfile: apps/web/Dockerfile
restart: unless-stopped
environment:
VITE_USE_API_PROXY: "true"
VITE_API_URL: http://api:8000
depends_on:
- api
nginx:
image: nginx:stable-alpine
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- ../nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
- ../nginx/default.tls.conf:/etc/nginx/conf.d/default.conf:ro
- ${TLS_CERT_DIR:-./certs}:/etc/nginx/certs:ro
depends_on:
- web
- api
volumes:
staging_postgres_data:
staging_minio_data:
staging_api_logs:
+40 -2
View File
@@ -1,6 +1,10 @@
import http from "k6/http";
import { check, sleep } from "k6";
const BASE_URL = __ENV.BASE_URL || "http://localhost:8000";
const ADMIN_EMAIL = __ENV.ADMIN_EMAIL || "admin@compton.example";
const ADMIN_PASSWORD = __ENV.ADMIN_PASSWORD || "Admin1234";
export const options = {
stages: [
{ duration: "1m", target: 10 },
@@ -14,7 +18,41 @@ export const options = {
};
export default function () {
const contentList = http.get("http://localhost:8000/api/v1/content/pages");
check(contentList, { "content list is 200": (r) => r.status === 200 });
const roll = Math.random();
if (roll < 0.35) {
const res = http.get(`${BASE_URL}/api/v1/content/pages`);
check(res, { "content list 200": (r) => r.status === 200 });
} else if (roll < 0.6) {
const res = http.post(
`${BASE_URL}/api/v1/auth/login`,
JSON.stringify({ email: ADMIN_EMAIL, password: ADMIN_PASSWORD }),
{ headers: { "Content-Type": "application/json" } }
);
check(res, { "login 200": (r) => r.status === 200 });
if (res.status === 200) {
const token = res.json("access_token");
const me = http.get(`${BASE_URL}/api/v1/users/me`, {
headers: { Authorization: `Bearer ${token}` }
});
check(me, { "users me 200": (r) => r.status === 200 });
}
} else if (roll < 0.7) {
const login = http.post(
`${BASE_URL}/api/v1/auth/login`,
JSON.stringify({ email: ADMIN_EMAIL, password: ADMIN_PASSWORD }),
{ headers: { "Content-Type": "application/json" } }
);
if (login.status === 200) {
const refresh = http.post(`${BASE_URL}/api/v1/auth/refresh`, null, {
headers: { Cookie: login.headers["Set-Cookie"] || "" }
});
check(refresh, { "refresh ok": (r) => r.status === 200 || r.status === 401 });
}
} else {
const res = http.get(`${BASE_URL}/api/v1/content/pages/about`);
check(res, { "content slug": (r) => r.status === 200 || r.status === 404 });
}
sleep(1);
}
+39
View File
@@ -0,0 +1,39 @@
server {
listen 80;
server_name _;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name _;
ssl_certificate /etc/nginx/certs/fullchain.pem;
ssl_certificate_key /etc/nginx/certs/privkey.pem;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self';" always;
location /api/ {
proxy_pass http://api:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
proxy_pass http://web:5173;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
BACKUP_DIR="$ROOT/backups"
mkdir -p "$BACKUP_DIR"
STAMP="$(date +%F-%H%M)"
FILE="$BACKUP_DIR/postgres-$STAMP.sql.gz"
docker compose -f "$ROOT/infra/docker/docker-compose.prod.yml" exec -T postgres \
pg_dump -U "${POSTGRES_USER:-compton_app}" "${POSTGRES_DB:-compton}" | gzip > "$FILE"
echo "Backup written: $FILE"
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -euo pipefail
BASE="${1:-http://localhost:8000}"
BASE="${BASE%/}"
fail() {
echo "FAIL: $1"
exit 1
}
code="$(curl -fsS -o /dev/null -w "%{http_code}" "$BASE/api/v1/health" || echo 000)"
[[ "$code" == "200" ]] || fail "health returned $code"
root_code="$(curl -fsS -o /dev/null -w "%{http_code}" "${BASE%/api/v1/health}/" 2>/dev/null || curl -fsS -o /dev/null -w "%{http_code}" "$(echo "$BASE" | sed 's|:8000||')/" || echo 000)"
echo "Landing/root HTTP: $root_code"
echo "OK: health check passed"
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env bash
set -euo pipefail
BASE="${1:-http://127.0.0.1:8000}"
BASE="${BASE%/}"
echo "== Smoke: health =="
curl -fsS "$BASE/api/v1/health" | grep -q '"status":"ok"'
echo "== Smoke: docs disabled =="
docs_code="$(curl -s -o /dev/null -w "%{http_code}" "$BASE/api/v1/docs")"
[[ "$docs_code" == "404" || "$docs_code" == "307" ]] || { echo "Expected docs 404, got $docs_code"; exit 1; }
echo "== Smoke: public content =="
curl -fsS "$BASE/api/v1/content/pages" | grep -q '"data"'
echo "All smoke checks passed."