Шхуна не тонет: 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
@@ -0,0 +1,35 @@
from app.core.security import create_access_token, hash_password
from tests.helpers import register_and_verify
def _admin_headers(client) -> dict[str, str]:
from app.modules.users.repository import get_user_by_email
admin = get_user_by_email("admin@compton.example")
token = create_access_token(admin.id, admin.role, admin.is_superuser)
return {"Authorization": f"Bearer {token}"}
def test_blocked_user_access_token_revoked_after_admin_block(client):
register_and_verify(client, "blocked-jwt@example.com")
login = client.post(
"/api/v1/auth/login",
json={"email": "blocked-jwt@example.com", "password": "Valid123"},
)
assert login.status_code == 200
access_token = login.json()["access_token"]
me = client.get("/api/v1/users/me", headers={"Authorization": f"Bearer {access_token}"})
assert me.status_code == 200
user_id = me.json()["user"]["id"]
blocked = client.patch(
f"/api/v1/admin/users/{user_id}",
headers=_admin_headers(client),
json={"status": "blocked"},
)
assert blocked.status_code == 200
revoked = client.get("/api/v1/users/me", headers={"Authorization": f"Bearer {access_token}"})
assert revoked.status_code == 401
assert revoked.json()["detail"] == "TOKEN_REVOKED"
@@ -0,0 +1,77 @@
from unittest.mock import MagicMock, patch
import pytest
from app.core import jwt_denylist as denylist_module
from app.core.jwt_denylist import (
bump_auth_epoch,
deny_jti,
ensure_jwt_revocation_backend,
get_auth_epoch,
is_jti_denied,
)
def test_ensure_jwt_revocation_backend_requires_redis_in_production(monkeypatch):
monkeypatch.setattr(denylist_module.settings, "app_env", "production")
with patch("app.core.jwt_denylist.get_redis_client", return_value=None):
with pytest.raises(RuntimeError, match="Redis is required"):
ensure_jwt_revocation_backend()
def test_redis_auth_epoch_roundtrip():
mock_client = MagicMock()
mock_client.get.return_value = "3"
mock_client.incr.return_value = 4
with patch("app.core.jwt_denylist.get_redis_client", return_value=mock_client):
assert get_auth_epoch("user-1") == 3
assert bump_auth_epoch("user-1") == 4
mock_client.incr.assert_called_once()
def test_redis_deny_jti_and_check():
mock_client = MagicMock()
with patch("app.core.jwt_denylist.get_redis_client", return_value=mock_client):
with patch("app.core.jwt_denylist.time.time", return_value=1000):
deny_jti("abc-jti", 1060)
mock_client.setex.assert_called_once_with("jwt:deny:abc-jti", 60, "1")
mock_client.exists.return_value = 1
assert is_jti_denied("abc-jti") is True
def test_forgot_password_skips_blocked_user(client):
from app.modules.users.repository import create_user, get_user_by_email, update_user
from app.core.security import hash_password
create_user("blocked-forgot@example.com", hash_password("Valid123"), status="active")
user = get_user_by_email("blocked-forgot@example.com")
user.status = "blocked"
update_user(user)
response = client.post(
"/api/v1/auth/forgot-password",
json={"email": "blocked-forgot@example.com"},
)
assert response.status_code == 200
from app.core.email import memory_mailer
assert not any(msg.to == "blocked-forgot@example.com" for msg in memory_mailer.sent)
def test_logout_revokes_access_token(client):
from tests.helpers import register_and_verify
register_and_verify(client, "logout-jti@example.com")
login = client.post(
"/api/v1/auth/login",
json={"email": "logout-jti@example.com", "password": "Valid123"},
)
token = login.json()["access_token"]
logout = client.post(
"/api/v1/auth/logout",
headers={"Authorization": f"Bearer {token}", "Origin": "http://localhost:5173"},
)
assert logout.status_code == 200
me = client.get("/api/v1/users/me", headers={"Authorization": f"Bearer {token}"})
assert me.status_code == 401
assert me.json()["detail"] == "TOKEN_REVOKED"
@@ -12,6 +12,31 @@ def _admin_headers(client) -> dict[str, str]:
return {"Authorization": f"Bearer {token}"}
def test_refresh_fails_for_pending_user(client):
client.post(
"/api/v1/auth/register",
json={"email": "pending-refresh@example.com", "password": "Valid123"},
)
login = client.post(
"/api/v1/auth/login",
json={"email": "pending-refresh@example.com", "password": "Valid123"},
)
assert login.status_code == 403
assert login.json()["detail"] == "EMAIL_NOT_VERIFIED"
# Simulate stale refresh cookie from an earlier active session edge case via direct token issue.
from app.modules.auth.service import issue_refresh_token
from app.modules.users.repository import get_user_by_email
user = get_user_by_email("pending-refresh@example.com")
refresh_token = issue_refresh_token(user.id)
client.cookies.set("refresh_token", refresh_token, path="/api/v1/auth")
refresh = client.post("/api/v1/auth/refresh", headers={"Origin": "http://localhost:5173"})
assert refresh.status_code == 403
assert refresh.json()["detail"] == "EMAIL_NOT_VERIFIED"
def test_refresh_fails_for_blocked_user(client):
register_and_verify(client, "blocked-refresh@example.com")
login = client.post(
@@ -32,7 +57,8 @@ def test_refresh_fails_for_blocked_user(client):
)
assert blocked.status_code == 200
refresh = client.post("/api/v1/auth/refresh", headers={"Origin": "http://localhost:5173"})
assert refresh.status_code == 401
assert refresh.status_code == 403
assert refresh.json()["detail"] == "ACCOUNT_BLOCKED"
def test_refresh_requires_origin_header_when_cookie_present(client):
@@ -0,0 +1,40 @@
from __future__ import annotations
from unittest.mock import patch
import pytest
from app.core.security import hash_password
from app.modules.auth import repository as auth_repository
from app.modules.auth.service import issue_refresh_token, refresh
from app.modules.users.repository import create_user, get_user_by_id, update_user
def test_refresh_returns_account_blocked_for_blocked_user():
user = create_user("blocked-svc@example.com", hash_password("Valid123"), status="active")
token = issue_refresh_token(user.id)
user.status = "blocked"
update_user(user)
auth_repository.revoke_user_families(user.id)
with pytest.raises(PermissionError, match="ACCOUNT_BLOCKED"):
refresh(token)
def test_refresh_returns_email_not_verified_for_pending_user():
user = create_user("pending-svc@example.com", hash_password("Valid123"), status="pending")
token = issue_refresh_token(user.id)
with pytest.raises(PermissionError, match="EMAIL_NOT_VERIFIED"):
refresh(token)
def test_refresh_rejects_revoked_token_for_active_user():
user = create_user("active-svc@example.com", hash_password("Valid123"), status="active")
token = issue_refresh_token(user.id)
auth_repository.revoke_user_families(user.id)
with patch.object(auth_repository, "revoke_family_tokens") as revoke_family:
with pytest.raises(PermissionError, match="INVALID_REFRESH"):
refresh(token)
revoke_family.assert_called_once()