This commit is contained in:
@@ -0,0 +1,147 @@
|
||||
"""Негативные проверки ACL, logout/expiry, лимита входа и размера запроса."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
CA = str(ROOT / "certs" / "ca.crt")
|
||||
client = Client("https://localhost:8443", CA)
|
||||
results = []
|
||||
|
||||
|
||||
def record(name: str, ok: bool, detail: str) -> None:
|
||||
results.append({"name": name, "ok": ok, "detail": detail})
|
||||
print(("PASS " if ok else "FAIL ") + name + ": " + detail)
|
||||
|
||||
|
||||
def psql(sql: str) -> None:
|
||||
subprocess.run(
|
||||
["docker", "exec", "lab7-postgres-1", "psql", "-U", "messenger", "-d", "messenger", "-v", "ON_ERROR_STOP=1", "-c", sql],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
att, _ = client.attachment(alice, chat)
|
||||
att = client.wait_ready(alice, att)
|
||||
|
||||
# Чужой не видит ни чат, ни вложение, ни историю.
|
||||
for name, method, path in (
|
||||
("acl_foreign_history", "GET", f"/api/v1/chats/{chat['id']}/messages"),
|
||||
("acl_foreign_attachment", "GET", f"/api/v1/attachments/{att['id']}"),
|
||||
("acl_foreign_attachment_content", "GET", f"/api/v1/attachments/{att['id']}/content"),
|
||||
):
|
||||
response = client.call(method, path, 404, actor=eve, schema="Error")
|
||||
record(name, response["status"] == 404, f"HTTP {response['status']}")
|
||||
|
||||
# Поддельный X-User-Id не меняет владельца Bearer-сессии.
|
||||
sent = client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"text": "identity check"},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex, "X-User-Id": eve["id"]},
|
||||
schema="Message",
|
||||
)["json"]
|
||||
record("acl_fake_x_user_id_ignored", sent["sender_id"] == alice["id"], "sender is Bearer owner")
|
||||
|
||||
# Logout и повторное использование отозванного токена.
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
response = client.call("GET", "/api/v1/users/me", 401, actor=alice, schema="Error")
|
||||
record("session_logout_revoked", response["status"] == 401, "revoked token -> 401")
|
||||
|
||||
# Expiry: TTL абсолютный, поэтому проверяем его переводом expires_at в прошлое.
|
||||
login = client.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
201,
|
||||
headers={"Authorization": "Basic " + base64.b64encode(
|
||||
(alice["registration"]["username"] + ":" + alice["registration"]["password"]).encode()
|
||||
).decode()},
|
||||
schema="Session",
|
||||
)["json"]
|
||||
token_hash = hashlib.sha256(login["token"].encode()).hexdigest()
|
||||
psql(f"UPDATE sessions SET expires_at = now() - interval '1 second' WHERE token_hash = '{token_hash}'")
|
||||
expired = client.call("GET", "/api/v1/users/me", 401, actor={"id": alice["id"], "token": login["token"]}, schema="Error")
|
||||
record("session_expiry_enforced", expired["status"] == 401, "expired token -> 401")
|
||||
|
||||
# Лимит входа: неизвестный username, одинаковый 401, затем 429 + Retry-After.
|
||||
username = "ghost_" + uuid.uuid4().hex[:10]
|
||||
credential = base64.b64encode((username + ":wrong-password-value").encode()).decode()
|
||||
limited = None
|
||||
instances = set()
|
||||
for index in range(12):
|
||||
response = client.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
401 if index < 10 else 429,
|
||||
headers={"Authorization": "Basic " + credential},
|
||||
schema="Error",
|
||||
)
|
||||
instances.add(response["headers"].get("X-Instance-Id"))
|
||||
if response["status"] == 429:
|
||||
limited = response
|
||||
break
|
||||
ok = limited is not None and bool(limited["headers"].get("Retry-After"))
|
||||
record(
|
||||
"login_rate_limit_429",
|
||||
ok,
|
||||
f"attempts={index + 1}, retry_after={limited['headers'].get('Retry-After') if limited else None}, instances={len(instances)}",
|
||||
)
|
||||
# Проверяем, что блокировка видна другой реплике: повтор сразу после 429.
|
||||
if limited is not None:
|
||||
second = client.call(
|
||||
"POST", "/api/v1/auth/sessions", 429,
|
||||
headers={"Authorization": "Basic " + credential}, schema="Error",
|
||||
)
|
||||
record("login_rate_limit_shared", second["status"] == 429, "second replica also 429")
|
||||
|
||||
# Размер запроса: 10 MiB + 1 байт должен дать 413 до декодирования.
|
||||
oversized = b"\x89PNG\r\n\x1a\n" + b"0" * (10_485_760 + 1 - 8)
|
||||
try:
|
||||
client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=big.png",
|
||||
413,
|
||||
actor=bob,
|
||||
raw=oversized,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Error",
|
||||
)
|
||||
record("upload_size_limit_413", True, "10 MiB + 1 rejected")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
record("upload_size_limit_413", False, type(exc).__name__)
|
||||
|
||||
# Неверный MIME по содержимому -> 415.
|
||||
response = client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=fake.png",
|
||||
415,
|
||||
actor=bob,
|
||||
raw=b"not-an-image",
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Error",
|
||||
)
|
||||
record("upload_mime_by_content_415", response["status"] == 415, "fake PNG rejected")
|
||||
|
||||
failed = [item for item in results if not item["ok"]]
|
||||
print(json.dumps({"checks": results, "passed": len(results) - len(failed), "failed": len(failed)}, ensure_ascii=False, sort_keys=True))
|
||||
return 0 if not failed else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user