diff --git a/REPORT.md b/REPORT.md index 764a8f9..6d20dad 100644 --- a/REPORT.md +++ b/REPORT.md @@ -46,6 +46,7 @@ make test-persistence ACTION_SCRIPT=scripts/restart.sh # выполня make test-failover ACTION_SCRIPT=scripts/stop-one.sh # одна реплика остаётся остановленной sh scripts/restore-api.sh # вернуть остановленную реплику sh scripts/rolling-update.sh # поочерёдная замена под нагрузкой +python scripts/check-revocation.py # отзыв сессии при недоступном Valkey # Безопасная остановка (данные сохраняются): docker compose stop @@ -63,7 +64,7 @@ docker compose down -v - **Динамический backend-list.** `upstream api_backend { zone …; server api:8080 resolve max_fails=1 fail_timeout=5s; }` + `resolver 127.0.0.11 valid=5s`. nginx перечитывает A-записи Docker DNS: добавление/остановка реплики подхватывается без reload; `proxy_next_upstream error timeout http_502/503/504` повторяет запрос на живой реплике. Максимальное время обнаружения отказа: пассивный `fail_timeout` 5 s + `valid` 5 s, замеренная первая успешная запись после старта хука — **< 1 с**. - **X-Instance-Id.** `src/instance.py`: `INSTANCE_ID = $INSTANCE_ID` или hostname контейнера (= короткий container id). Ставится middleware на **каждый** ответ, включая ошибки и health; стабилен на время жизни процесса. Проверка в `evidence/lab3-instances.txt`: 12 запросов дают ровно два чередующихся id. - **Общая идемпотентность.** Таблица `idempotency_keys` (PK `user_id, scope, key`, `scope = "POST /api/v1/chats/{id}/messages"`), `request_hash`, `status_code`, `response_body jsonb`, `expires_at`. `POST …/messages` требует `Idempotency-Key` `[A-Za-z0-9._:-]{1,128}` (нет/неверный — 400). Вставка сообщения и запись журнала — одна транзакция; `pg_advisory_xact_lock(hashtext(user|scope), hashtext(key))` сериализует одинаковые ключи между всеми репликами. Повтор возвращает тот же `201` и тот же Message; другой body — `409`. TTL — `IDEMPOTENCY_TTL_SECONDS` (default 86400). -- **Сессии общие.** Источник истины — PostgreSQL (`sessions.expires_at > now()`); Valkey — read-through кэш с TTL и обходом при отказе. Sticky session не используются: пользователь свободно попадает на любую реплику без повторного входа. +- **Сессии общие, отзыв немедленный.** Источник истины — PostgreSQL: каждый запрос проверяет строку сессии (`sessions.expires_at > now()`), поэтому отозванный токен даёт `401` на любой реплике немедленно. Valkey — read-through кэш **неизменяемого профиля пользователя** (`user:{id}`, TTL 300 c), он никогда не используется для решения о доступе. Поэтому сбой инвалидации при лежащем Valkey не может «воскресить» отозванную сессию (регрессионная проверка — `scripts/check-revocation.py`). Sticky session не используются: пользователь свободно попадает на любую реплику без повторного входа. - **Одноразовые миграции.** Отдельный сервис `migrate` (`python -m src.migrate`) под `pg_advisory_xact_lock`; реплики стартуют только после `service_completed_successfully`, гонки за схему нет. - **Graceful shutdown.** `src/main.py` переопределяет `Server.handle_exit`: по SIGTERM/SIGINT выставляет флаг (`src/state.py`), `/health/ready` отвечает `503` (LB выводит реплику из ротации), затем Uvicorn доигрывает запросы (`timeout_graceful_shutdown=10`). - **Ресурсы и секреты.** У всех сервисов заданы CPU/RAM-лимиты (`deploy.resources.limits`); секреты — файловые compose secrets/`*_FILE`, в образ и Git не попадают. `container_name` не задаётся, масштабирование одной Compose-service работает. @@ -90,8 +91,10 @@ docker compose down -v | Публичный smoke | `python tests/smoke.py --base-url http://localhost:8080` | `PASS: lab3 public API scenario` | `evidence/lab3-smoke.txt` | | Стенд: ≥2 реплики, LB, общая БД/сессии | `docker compose up -d --build`, `docker compose ps` | 2× `api` healthy, `lb` 127.0.0.1:8080, `postgres`, `valkey`; у `api` порты не публикуются | `evidence/lab3-compose-ps.txt` | | Разные запросы одной сессии обслуживают разные реплики | 12× `GET /users/me` через LB | чередование `4141f552b001`/`5ac0582fa5e1` (2 реплики), один токен | `evidence/lab3-instances.txt` | -| Уровень 3: остановка одной реплики, запись/чтение продолжаются ≤10 с | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | 138 успешных записей, 0 ошибок, восстановление **0.898 с**; `api-6 Exited` при живом `api-5` | `evidence/lab3-failover.txt` | +| Уровень 3: остановка одной реплики, запись/чтение продолжаются ≤10 с | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | 122 успешных записи, 0 ошибок, восстановление **1.083 с**; `api-6 Exited` при живом `api-5` | `evidence/lab3-failover.txt` | | Общая идемпотентность, в т.ч. конкурентная и через разные реплики | `test_idempotency.py` | повтор = тот же Message; другой body → 409; 8 параллельных запросов с одним ключом → ровно одно сообщение | `evidence/lab3-student-tests.txt` | +| Отзыв сессии не обходится при сбое Valkey | `python scripts/check-revocation.py` (pause Valkey → logout 204 → unpause → 6 c) | старый токен даёт `401` через 2 реплики и не может отправить сообщение | `evidence/lab3-revocation-fix.txt` | +| Деградация кэша без остановки API | pause Valkey, валидный `/users/me` | 5×`200`, `/health/ready` = `200` (кэш обойдён) | `evidence/lab3-valkey-degradation.txt` | | Persistence: данные и сессия переживают рестарт API и хранилищ | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | `PASS: persistence preserved confirmed data and existing session` | `evidence/lab3-persistence.txt` | | Миграции применяются однократно и повторно идемпотентно | `docker compose exec -T api python -m src.migrate` | `migrations up to date`; в `schema_migrations` 2 строки | `evidence/lab3-migrations.txt` | | Уровень 4: health/readiness, SIGTERM, LB исключает backend | `scripts/stop-one.sh` + `/health/ready` | остановленная реплика исчезает из ответов; readiness→503 при SIGTERM; пассивные проверки nginx | `evidence/lab3-failover.txt` | @@ -109,10 +112,11 @@ docker compose down -v | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| Остановка одной API-реплики (`stop-one.sh`, TARGET = обслужившая реплика) | записи/чтения продолжаются, без дублей, токен жив | 138 записей за 15 с, 0 ошибок, цель не в последних ответах; `api-6 Exited` | **0.898 с**; потерь нет | -| То же для второй реплики (после восстановления первой) | то же | 138 записей, 0 ошибок, `api-2 Exited` | **1.02 с** | +| Остановка одной API-реплики (`stop-one.sh`, TARGET = обслужившая реплика) | записи/чтения продолжаются, без дублей, токен жив | 122 записи за 15 с, 0 ошибок, цель не в последних ответах; `api-6 Exited` | **1.083 с**; потерь нет | +| То же для второй реплики (после восстановления первой) | то же | ≈120–140 записей, 0 ошибок; `api-2 Exited` | **≈1 с**; потерь нет | | `docker compose restart api lb postgres valkey` | данные и сессия сохранены | `PASS: persistence preserved……` | рестарт ≈ секунды; потерь нет | | Rolling update (`rolling-update.sh`) под непрерывным опросом | замена реплик без недоступности | 400/400 `200` при поочерёдной замене | простоя нет | +| Valkey недоступен во время logout (`check-revocation.py`) | отзыв сессии не обходится, старый токен → 401 | pause → logout 204 → unpause → 6 c → 401 через обе реплики, POST отклонён | потерь нет; сессия отозвана в PostgreSQL | | Нагрузка 133 RPS на 2 реплики | стабильная пропускная способность | 0 ошибок, p99 203 мс | n/a | Ограничения измерения: closed-loop генератор страдает coordinated omission и ограничен клиентом; числа — throughput HTTP-подтверждений, не точный счётчик COMMIT; единичный Docker-host не проверяет отказ узла. `docker stats` показывает ~74 MB RSS на реплику при лимите 256 MB. diff --git a/evidence/lab3-compose-ps.txt b/evidence/lab3-compose-ps.txt index 74b954f..9dc0b6e 100644 Binary files a/evidence/lab3-compose-ps.txt and b/evidence/lab3-compose-ps.txt differ diff --git a/evidence/lab3-explain.txt b/evidence/lab3-explain.txt index 47fe1c7..e8f438b 100644 Binary files a/evidence/lab3-explain.txt and b/evidence/lab3-explain.txt differ diff --git a/evidence/lab3-failover.txt b/evidence/lab3-failover.txt index 997b543..b986759 100644 Binary files a/evidence/lab3-failover.txt and b/evidence/lab3-failover.txt differ diff --git a/evidence/lab3-instances.txt b/evidence/lab3-instances.txt index 597a7b4..b8504ad 100644 Binary files a/evidence/lab3-instances.txt and b/evidence/lab3-instances.txt differ diff --git a/evidence/lab3-load.txt b/evidence/lab3-load.txt index a68bd5d..ebdbd77 100644 Binary files a/evidence/lab3-load.txt and b/evidence/lab3-load.txt differ diff --git a/evidence/lab3-migrations.txt b/evidence/lab3-migrations.txt index b14ab1f..f92faf5 100644 Binary files a/evidence/lab3-migrations.txt and b/evidence/lab3-migrations.txt differ diff --git a/evidence/lab3-persistence.txt b/evidence/lab3-persistence.txt index 8351ad7..9799975 100644 Binary files a/evidence/lab3-persistence.txt and b/evidence/lab3-persistence.txt differ diff --git a/evidence/lab3-revocation-fix.txt b/evidence/lab3-revocation-fix.txt new file mode 100644 index 0000000..18175cb --- /dev/null +++ b/evidence/lab3-revocation-fix.txt @@ -0,0 +1,4 @@ +Pausing Valkey (messenger-lab3-valkey-1) ... +Logout returned 204 while the cache was unavailable. +Valkey resumed; waiting 6.0s for the cache circuit breaker ... +PASS: revoked session stays 401 through 2 replica(s) and cannot post after a failed cache invalidation. diff --git a/evidence/lab3-rolling.txt b/evidence/lab3-rolling.txt index 89d2a53..2d4e2d3 100644 Binary files a/evidence/lab3-rolling.txt and b/evidence/lab3-rolling.txt differ diff --git a/evidence/lab3-smoke.txt b/evidence/lab3-smoke.txt index 9155c94..fc20f9d 100644 Binary files a/evidence/lab3-smoke.txt and b/evidence/lab3-smoke.txt differ diff --git a/evidence/lab3-stats.txt b/evidence/lab3-stats.txt index 660836b..44b1a4e 100644 Binary files a/evidence/lab3-stats.txt and b/evidence/lab3-stats.txt differ diff --git a/evidence/lab3-student-tests.txt b/evidence/lab3-student-tests.txt index d5d2a72..6f94e80 100644 Binary files a/evidence/lab3-student-tests.txt and b/evidence/lab3-student-tests.txt differ diff --git a/evidence/lab3-valkey-degradation.txt b/evidence/lab3-valkey-degradation.txt new file mode 100644 index 0000000..c06b4db --- /dev/null +++ b/evidence/lab3-valkey-degradation.txt @@ -0,0 +1,6 @@ +messenger-lab3-valkey-1 +messenger-lab3-valkey-1 +Pausing Valkey; valid traffic must keep working (cache bypassed). +statuses during pause: [200, 200, 200, 200, 200] +ready: 200 +PASS: valid traffic served from PostgreSQL with Valkey unavailable. diff --git a/scripts/check-revocation.py b/scripts/check-revocation.py new file mode 100644 index 0000000..f0f157a --- /dev/null +++ b/scripts/check-revocation.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Regression check: logout must not be bypassed while Valkey is unavailable. + +Scenario (the one that used to fail): + 1. login and warm any session cache; + 2. pause Valkey; + 3. logout -> 204 (session row removed from PostgreSQL); + 4. resume Valkey; + 5. after the cache circuit breaker window, the old token must still be 401 on + every replica, and it must not be able to send a message. + +Requires the docker CLI and a running lab3 stack. +""" +import argparse +import os +import subprocess +import sys +import time +import uuid + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tests")) +from client import Client # noqa: E402 + + +def _docker(*args: str) -> None: + subprocess.run(["docker", *args], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080")) + parser.add_argument("--valkey-container", default=os.environ.get("VALKEY_CONTAINER", "messenger-lab3-valkey-1")) + parser.add_argument("--wait", type=float, default=6.0, help="seconds to wait after resuming Valkey") + args = parser.parse_args() + + c = Client(args.base_url) + alice, bob, eve, chat = c.bootstrap() + + # Warm the cache on both replicas. + for _ in range(6): + c.call("GET", "/api/v1/users/me", actor=alice, schema="User") + c.message(alice, chat, "warm-up before revocation") + + print("Pausing Valkey (%s) ..." % args.valkey_container) + _docker("pause", args.valkey_container) + try: + logout = c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice) + assert logout["status"] == 204, logout["status"] + print("Logout returned 204 while the cache was unavailable.") + finally: + _docker("unpause", args.valkey_container) + print("Valkey resumed; waiting %.1fs for the cache circuit breaker ..." % args.wait) + time.sleep(args.wait) + + seen = set() + for _ in range(12): + response = c.call("GET", "/api/v1/users/me", 401, actor=alice, schema="Error") + seen.add(response["headers"].get("X-Instance-Id")) + assert len(seen) >= 1, "no replica observed" + + blocked = c.call( + "POST", + "/api/v1/chats/" + chat["id"] + "/messages", + 401, + actor=alice, + body={"text": "must not be written"}, + headers={"Idempotency-Key": uuid.uuid4().hex}, + schema="Error", + ) + assert blocked["status"] == 401, blocked["status"] + + print( + "PASS: revoked session stays 401 through %d replica(s) and cannot post after a " + "failed cache invalidation." % len(seen) + ) + + +if __name__ == "__main__": + main() diff --git a/src/app.py b/src/app.py index a8da8af..45f3a45 100644 --- a/src/app.py +++ b/src/app.py @@ -213,14 +213,16 @@ def _idempotency_key(request: Request) -> str: def current_user(request: Request, conn=Depends(get_conn)) -> Dict: + # Session validity is always checked against PostgreSQL; the cache may only + # serve the immutable user profile, never an access decision. token = _bearer_token(request) user_id = sessions.resolve(conn, token) if user_id is None: raise ApiError(401, "unauthorized", "Сессия недействительна", challenge=BEARER_CHALLENGE) - row = repo.get_user_by_id(conn, user_id) - if row is None: + user = sessions.cached_user(conn, user_id) + if user is None: raise ApiError(401, "unauthorized", "Сессия недействительна", challenge=BEARER_CHALLENGE) - return row + return user def _require_chat(conn, chat_id: str, user_id: str) -> str: @@ -287,7 +289,7 @@ def revoke_session( @app.get("/api/v1/users/me") def current_user_endpoint(user: Dict = Depends(current_user)) -> dict: - return repo.user_json(user) + return user # --------------------------------------------------------------------------- # diff --git a/src/sessions.py b/src/sessions.py index f1eee15..a810d62 100644 --- a/src/sessions.py +++ b/src/sessions.py @@ -1,11 +1,17 @@ -"""Sessions: PostgreSQL is the source of truth, Valkey is a read-through cache. +"""Sessions and profile cache. -Design: - * ``sessions`` rows in PostgreSQL decide validity (``expires_at > now()``). - * Valkey caches ``session:{token_hash} -> user_id`` with a TTL equal to the - remaining session lifetime. - * If Valkey is unreachable the cache is bypassed transparently and the API - keeps authenticating from PostgreSQL (Valkey is never trusted as authority). +PostgreSQL is the source of truth for **session validity**. Every authenticated +request resolves its bearer token against the ``sessions`` table, so an +expired, revoked or unknown token is rejected immediately - even if Valkey was +unreachable at logout time and the invalidation could not be performed. The +cache is therefore never consulted to decide whether a session is valid, and a +stale or not-invalidated entry cannot resurrect a revoked session. + +Valkey is a best-effort read-through cache for **immutable user profiles** +(``user:{id}``). Profiles do not carry authorization state, so a failed cache +operation only costs one extra SQL query; it can never change an access +decision. This keeps Redis/Valkey genuinely useful without weakening the +contract. Every cache operation is bounded by a hard timeout and guarded by a tiny circuit breaker. A stopped Valkey container can make Docker DNS itself block @@ -16,9 +22,10 @@ from __future__ import annotations import concurrent.futures import datetime as dt +import json import logging import time -from typing import Optional, Tuple +from typing import Dict, Optional, Tuple import redis from redis.backoff import NoBackoff @@ -38,6 +45,10 @@ _OP_TIMEOUT = 0.5 _BREAKER_SECONDS = 5.0 _breaker_until = 0.0 +# User profiles are immutable in the mandatory API, so a short TTL is enough +# and bounds staleness to a value that cannot affect authorization. +_USER_CACHE_TTL = 300 + def _cache() -> Optional[redis.Redis]: global _client, _client_disabled @@ -73,32 +84,36 @@ def _guard(fn, *args): return None -def _key(token_hash: str) -> str: - return f"session:{token_hash}" - - -def _cache_get(token_hash: str) -> Optional[str]: +def _cache_get(key: str) -> Optional[str]: client = _cache() if client is None: return None - value = _guard(lambda: client.get(_key(token_hash))) + value = _guard(lambda: client.get(key)) if value is None: return None return value.decode("utf-8") if isinstance(value, bytes) else str(value) -def _cache_set(token_hash: str, user_id: str, ttl_seconds: float) -> None: +def _cache_set(key: str, value: str, ttl_seconds: float) -> None: client = _cache() if client is None: return - _guard(lambda: client.set(_key(token_hash), user_id, ex=max(1, int(ttl_seconds)))) + _guard(lambda: client.set(key, value, ex=max(1, int(ttl_seconds)))) -def _cache_delete(token_hash: str) -> None: +def _cache_delete(key: str) -> None: client = _cache() if client is None: return - _guard(lambda: client.delete(_key(token_hash))) + _guard(lambda: client.delete(key)) + + +def _session_key(token_hash: str) -> str: + return f"session:{token_hash}" + + +def _user_key(user_id: str) -> str: + return f"user:{user_id}" def create(conn, user_id: str) -> Tuple[str, dt.datetime]: @@ -106,26 +121,44 @@ def create(conn, user_id: str) -> Tuple[str, dt.datetime]: hashed = security.token_hash(token) expires_at = repo.utcnow() + dt.timedelta(seconds=settings.session_ttl_seconds) repo.insert_session(conn, hashed, user_id, expires_at) - _cache_set(hashed, user_id, settings.session_ttl_seconds) return token, expires_at def resolve(conn, token: str) -> Optional[str]: + """Return the session's user id, or None if the token is not valid. + + Validity is always decided by PostgreSQL. The cache is *not* consulted here, + so revoking a session (DELETE row) takes effect immediately on every + replica regardless of the state of Valkey. + """ hashed = security.token_hash(token) - cached = _cache_get(hashed) - if cached is not None: - return cached row = repo.get_valid_session(conn, hashed) if row is None: + # Best-effort cleanup of any legacy session entry from older versions; + # never used for a decision. + _cache_delete(_session_key(hashed)) return None - user_id = str(row["user_id"]) - remaining = (row["expires_at"] - repo.utcnow()).total_seconds() - if remaining > 0: - _cache_set(hashed, user_id, remaining) - return user_id + return str(row["user_id"]) def revoke(conn, token: str) -> None: hashed = security.token_hash(token) repo.delete_session(conn, hashed) - _cache_delete(hashed) + _cache_delete(_session_key(hashed)) + + +def cached_user(conn, user_id: str) -> Optional[Dict]: + """Read-through cache of an immutable user profile (never authorization).""" + key = _user_key(user_id) + raw = _cache_get(key) + if raw is not None: + try: + return json.loads(raw) + except ValueError: + pass + row = repo.get_user_by_id(conn, user_id) + if row is None: + return None + data = repo.user_json(row) + _cache_set(key, json.dumps(data, ensure_ascii=False), _USER_CACHE_TTL) + return data diff --git a/student-tests/test_session_revocation.py b/student-tests/test_session_revocation.py new file mode 100644 index 0000000..e5c5654 --- /dev/null +++ b/student-tests/test_session_revocation.py @@ -0,0 +1,34 @@ +"""Lab3 revocation: logout takes effect immediately on every replica. + +Session validity is decided only by PostgreSQL, so a revoked token must be +rejected regardless of which replica answers and regardless of the cache state. +The heavier Valkey-outage reproduction lives in scripts/check-revocation.py. +""" +from __future__ import annotations + +import os + + +def _actor(client, label="revoke"): + suffix = os.urandom(4).hex() + username = f"s_{label}_{suffix}" + password = "T3st-" + os.urandom(8).hex() + assert client.register(username, password).status == 201 + token = client.login(username, password).json["token"] + return {"id": client.me(token).json["id"], "token": token} + + +def test_logout_invalidates_across_replicas(client): + actor = _actor(client) + seen = set() + for _ in range(20): + response = client.me(actor["token"]) + assert response.status == 200, response.body + seen.add(response.instance_id) + assert len(seen) >= 2, f"expected the LB to spread requests, saw {sorted(seen)}" + + logout = client.logout(actor["token"]) + assert logout.status == 204, logout.body + + for _ in range(20): + assert client.me(actor["token"]).status == 401