100 lines
3.7 KiB
Python
Executable File
100 lines
3.7 KiB
Python
Executable File
"""Проверка отказа Valkey и корректности logout при недоступном кэше."""
|
|
from __future__ import annotations
|
|
import base64, json, subprocess, sys, time, urllib.error, urllib.request, uuid
|
|
|
|
BASE = "http://localhost:8080"
|
|
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
|
|
|
def call(method, path, headers=None, body=None):
|
|
data = None
|
|
h = dict(headers or {})
|
|
if body is not None:
|
|
data = json.dumps(body).encode()
|
|
h["Content-Type"] = "application/json"
|
|
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
|
try:
|
|
r = urllib.request.urlopen(req, timeout=10)
|
|
raw = r.read()
|
|
return r.code, json.loads(raw) if raw else None
|
|
except urllib.error.HTTPError as e:
|
|
raw = e.read()
|
|
try:
|
|
return e.code, json.loads(raw) if raw else None
|
|
except Exception:
|
|
return e.code, None
|
|
|
|
def stop_cache():
|
|
subprocess.run(COMPOSE + ["stop", "cache"], check=True)
|
|
|
|
def start_cache():
|
|
subprocess.run(COMPOSE + ["start", "cache"], check=True)
|
|
|
|
def restart_api():
|
|
subprocess.run(COMPOSE + ["restart", "api"], check=True)
|
|
|
|
def wait_ready(deadline=60):
|
|
end = time.monotonic() + deadline
|
|
while time.monotonic() < end:
|
|
try:
|
|
code, _ = call("GET", "/health/ready")
|
|
if code == 200:
|
|
return
|
|
except Exception:
|
|
pass
|
|
time.sleep(1)
|
|
raise SystemExit("API did not become ready")
|
|
|
|
def main():
|
|
username = "cf_" + uuid.uuid4().hex[:10]
|
|
password = "cache-fail-pass-1234567890"
|
|
code, _ = call("POST", "/api/v1/users", body={
|
|
"username": username, "display_name": "Cache Fail", "password": password,
|
|
})
|
|
assert code == 201, code
|
|
|
|
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
|
code, session = call("POST", "/api/v1/auth/sessions",
|
|
headers={"Authorization": "Basic " + cred})
|
|
assert code == 201, code
|
|
token = session["token"]
|
|
|
|
# Токен работает
|
|
code, _ = call("GET", "/api/v1/users/me",
|
|
headers={"Authorization": "Bearer " + token})
|
|
assert code == 200, code
|
|
|
|
# Останавливаем Valkey
|
|
stop_cache()
|
|
time.sleep(2)
|
|
|
|
# API должно работать в degraded mode
|
|
code, _ = call("GET", "/api/v1/users/me",
|
|
headers={"Authorization": "Bearer " + token})
|
|
assert code == 200, f"degraded mode failed: {code}"
|
|
print("PASS: API works with Valkey down (degraded mode)")
|
|
|
|
# Logout при недоступном Valkey должен вернуть 204
|
|
code, _ = call("DELETE", "/api/v1/auth/sessions/current",
|
|
headers={"Authorization": "Bearer " + token})
|
|
assert code == 204, f"logout with cache down returned {code}"
|
|
print("PASS: logout with cache down returned 204")
|
|
|
|
# Токен немедленно недействителен (проверка через БД)
|
|
code, _ = call("GET", "/api/v1/users/me",
|
|
headers={"Authorization": "Bearer " + token})
|
|
assert code == 401, f"revoked token still works with cache down: {code}"
|
|
print("PASS: revoked token rejected while cache down")
|
|
|
|
# Поднимаем Valkey, рестартуем API — критический регресс-тест
|
|
start_cache()
|
|
time.sleep(2)
|
|
restart_api()
|
|
wait_ready()
|
|
|
|
code, _ = call("GET", "/api/v1/users/me",
|
|
headers={"Authorization": "Bearer " + token})
|
|
assert code == 401, f"REGRESSION: revoked token resurrected after cache restart: {code}"
|
|
print("PASS: revoked token still 401 after cache restart (regression fixed)")
|
|
|
|
if __name__ == "__main__":
|
|
main() |