ЛР2: PostgreSQL + Valkey, сессии Basic/Bearer, миграции, compose, тесты, отчёт

This commit is contained in:
2026-10-15 19:17:22 +03:00
parent 65003b6119
commit 6808ed8c98
44 changed files with 2370 additions and 19 deletions
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""Dependency-failure probe (grade 4).
Proves the documented behaviour of the running compose stand:
* Valkey down -> API keeps authenticating from PostgreSQL (cache bypass),
/health/ready stays 200;
* PostgreSQL down -> /health/ready is 503 and authenticated calls return a
bounded 503 (an anonymous caller is never trusted);
* both recover when the service is started again.
Run from the repository root where ``docker compose`` is available.
"""
from __future__ import annotations
import base64
import json
import os
import subprocess
import time
import urllib.error
import urllib.request
BASE = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
def call(method, path, token=None, body=None):
headers = {"Accept": "application/json"}
data = None
if body is not None:
data = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
if token:
headers["Authorization"] = "Bearer " + token
request = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=15) as response:
return response.status
except urllib.error.HTTPError as error:
return error.code
except (urllib.error.URLError, TimeoutError, OSError):
return 0
def compose(*args):
subprocess.run(["docker", "compose", *args], check=True)
def wait_ready(expected, timeout=120.0):
deadline = time.time() + timeout
while time.time() < deadline:
if call("GET", "/health/ready") == expected:
return
time.sleep(2)
raise SystemExit(f"readiness did not reach {expected}")
def login():
username = "degrade_" + os.urandom(4).hex()
password = "T3st-" + os.urandom(8).hex()
assert call("POST", "/api/v1/users", body={
"username": username, "display_name": "Degrade", "password": password}) == 201
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
request = urllib.request.Request(
BASE + "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + credential, "Accept": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=15) as response:
return json.loads(response.read())["token"]
def main() -> None:
wait_ready(200)
token = login()
assert call("GET", "/api/v1/users/me", token=token) == 200
print("baseline: /users/me = 200")
print("stopping valkey ...")
compose("stop", "valkey")
ready = call("GET", "/health/ready")
me = call("GET", "/api/v1/users/me", token=token)
assert ready == 200, f"readiness must stay 200 without cache, got {ready}"
assert me == 200, f"auth must work from PostgreSQL without cache, got {me}"
print("valkey down: /health/ready = 200, /users/me = 200 (cache bypassed)")
compose("start", "valkey")
wait_ready(200)
assert call("GET", "/api/v1/users/me", token=token) == 200
print("valkey restored: /users/me = 200")
print("stopping postgres ...")
compose("stop", "postgres")
time.sleep(2)
ready = call("GET", "/health/ready")
me = call("GET", "/api/v1/users/me", token=token)
anon = call("GET", "/api/v1/users/me")
assert ready == 503, f"readiness must be 503 without PostgreSQL, got {ready}"
assert me == 503, f"authenticated call must be a bounded 503, got {me}"
assert anon == 503, f"anonymous call must not be trusted, got {anon}"
print("postgres down: /health/ready = 503, /users/me = 503, anonymous = 503")
compose("start", "postgres")
wait_ready(200, timeout=180)
assert call("GET", "/api/v1/users/me", token=token) == 200
print("postgres restored: /users/me = 200 (session survived)")
print("PASS: graceful degradation and recovery without trusting the cache/anonymous user")
if __name__ == "__main__":
main()
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -eu
# Prove session expiry with a SHORT SESSION_TTL_SECONDS on a throwaway stack.
# The main stand can stay up; this uses a second compose project on port 8081.
cd "$(dirname "$0")/.."
export SESSION_TTL_SECONDS=2
export PUBLISH_PORT=8081
PROJECT=mtusi2expiry
cleanup() { docker compose -p "$PROJECT" down -v >/dev/null 2>&1 || true; }
trap cleanup EXIT
docker compose -p "$PROJECT" up -d --build
python3 scripts/expiry_probe.py --base-url http://localhost:8081 --ttl 2
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Wait for a stand, then prove that a short-TTL session expires.
Run against a stand started with SESSION_TTL_SECONDS=2 (see check-expiry.sh).
"""
from __future__ import annotations
import argparse
import base64
import json
import os
import time
import urllib.error
import urllib.request
def _call(base, method, path, token=None, body=None):
headers = {"Accept": "application/json"}
data = None
if body is not None:
data = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
if token:
headers["Authorization"] = "Bearer " + token
request = urllib.request.Request(base + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=10) as response:
return response.status, json.loads(response.read() or b"null")
except urllib.error.HTTPError as error:
return error.code, json.loads(error.read() or b"null")
def wait_ready(base, timeout=180.0):
deadline = time.time() + timeout
while time.time() < deadline:
try:
with urllib.request.urlopen(base + "/health/ready", timeout=3) as response:
if response.status == 200:
return
except (urllib.error.URLError, TimeoutError, OSError):
pass
time.sleep(2)
raise SystemExit("stand did not become ready")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8081")
parser.add_argument("--ttl", type=int, default=2)
args = parser.parse_args()
base = args.base_url.rstrip("/")
wait_ready(base)
username = "expiry_" + os.urandom(4).hex()
password = "T3st-" + os.urandom(8).hex()
status, _ = _call(base, "POST", "/api/v1/users",
body={"username": username, "display_name": "Expiry", "password": password})
assert status == 201, status
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
request = urllib.request.Request(
base + "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + credential, "Accept": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=10) as response:
session = json.loads(response.read())
token = session["token"]
me_before, _ = _call(base, "GET", "/api/v1/users/me", token=token)
assert me_before == 200, me_before
time.sleep(args.ttl + 1)
me_after, _ = _call(base, "GET", "/api/v1/users/me", token=token)
assert me_after == 401, f"expired token still accepted: {me_after}"
print(f"PASS: session expired after ~{args.ttl}s (before=200, after=401)")
if __name__ == "__main__":
main()
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -eu
# Generate local (gitignored) compose secrets with a random database password.
cd "$(dirname "$0")/.."
mkdir -p secrets
PASSWORD=$(head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n')
printf '%s' "$PASSWORD" > secrets/database_password
printf '%s' "postgresql://messenger:${PASSWORD}@postgres:5432/messenger" > secrets/database_url
printf '%s' "redis://valkey:6379/0" > secrets/cache_url
chmod 600 secrets/database_password secrets/database_url secrets/cache_url 2>/dev/null || true
echo "Wrote ./secrets/database_password, ./secrets/database_url, ./secrets/cache_url (not committed)."
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
set -eu
# Restart the API and ALL state stores used by this stack.
# Volumes are preserved; schema and data are never dropped or re-seeded.
# Used by: make test-persistence ACTION_SCRIPT=scripts/restart.sh
cd "$(dirname "$0")/.."
docker compose restart api postgres valkey
exit 0