#!/usr/bin/env python3 """Проверяет ACL, logout, expiry, SAN и общий rate limit через HTTPS.""" import base64 import concurrent.futures import os import socket import ssl import sys import time import uuid from pathlib import Path from urllib.parse import urlsplit ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, arguments, check, run def configure(parser): parser.add_argument("--expiry-url", default=os.environ.get("EXPIRY_BASE_URL")) def check_hostname(base_url, ca_file): url = urlsplit(base_url) context = ssl.create_default_context(cafile=ca_file) try: with socket.create_connection((url.hostname, url.port or 443), timeout=3) as connection: context.wrap_socket(connection, server_hostname="unexpected.invalid").close() except ssl.SSLCertVerificationError as error: check(error.verify_code == 62 or "hostname" in error.verify_message.lower(), "TLS отклонён по другой причине") else: raise RuntimeError("TLS принял неверный hostname") def permissions(client): alice, _, eve, chat = client.bootstrap() attachment, _ = client.attachment(alice, chat) attachment = client.wait_ready(alice, attachment) path = "/api/v1/attachments/" + attachment["id"] spoofed = {"X-User-Id": alice["id"]} for suffix in ("", "/content"): client.call("GET", path + suffix, 404, actor=eve, headers=spoofed) other_chat = client.call("POST", "/api/v1/chats", 201, actor=eve, body={"title": "ACL audit", "member_ids": [eve["id"]]}, schema="Chat")["json"] client.call("POST", "/api/v1/chats/" + other_chat["id"] + "/messages", 404, actor=eve, headers={"Idempotency-Key": uuid.uuid4().hex}, body={"text": "ACL audit", "attachment_ids": [attachment["id"]]}) client.call("GET", "/api/v1/users/me", actor=alice, schema="User") client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice) for _ in range(8): client.call("GET", "/api/v1/users/me", 401, actor=alice) print("PASS ACL: чужие metadata/content/attachment, подмена X-User-Id и отозванная сессия") def rate_limit(client): invalid = base64.b64encode(b"audit_unknown:invalid-password").decode() headers = {"Authorization": "Basic " + invalid} def invalid_login(_): return client.call("POST", "/api/v1/auth/sessions", [401, 429], headers=headers) time.sleep(4) with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor: responses = list(executor.map(invalid_login, range(40))) backend = {r["headers"]["X-Instance-Id"] for r in responses if r["status"] == 401} limited = [r for r in responses if r["status"] == 429] check(len(backend) >= 2 and limited, "Лимит не доказан одновременно для обеих реплик") for result in limited: check(result["json"]["error"]["code"] == "rate_limited", "Машинный код 429") check(int(result["headers"]["Retry-After"]) > 0, "Пустой Retry-After") print(f"PASS rate limit: {len(backend)} API-реплики, 429={len(limited)}/40, Retry-After") def main(): args = arguments("Отрицательные проверки lab7", configure) ca = args.ca_file or str(ROOT / "certs/ca.crt") client = Client(args.base_url, ca) check_hostname(client.base, ca) print("PASS TLS: сертификат ingress отвергнут при неверном hostname") permissions(client) if args.expiry_url: expiry = Client(args.expiry_url, ca) actor = expiry.user("expiry") expiry.call("GET", "/api/v1/users/me", actor=actor, schema="User") time.sleep(2.5) expiry.call("GET", "/api/v1/users/me", 401, actor=actor) print("PASS expiry: сессия профиля с TTL=2 с истекла") rate_limit(client) if __name__ == "__main__": run(main)