import base64 import uuid from pathlib import Path from client import Client, arguments, check, run def main(): args = arguments("Lab7 grade 4 negative and security checks") c = Client(args.base_url, args.ca_file) alice, bob, eve, chat = c.bootstrap() att, _ = c.attachment(alice, chat) c.call("GET", f"/api/v1/attachments/{att['id']}", 404, actor=eve) c.call("GET", f"/api/v1/attachments/{att['id']}/content", 404, actor=eve) c.call( "POST", f"/api/v1/chats/{chat['id']}/messages", 404, actor=eve, body={"text": "intrusion", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}, ) me = c.call( "GET", "/api/v1/users/me", 200, actor=alice, headers={"X-User-Id": eve["id"]}, schema="User", )["json"] check(me["id"] == alice["id"], "X-User-Id must not override Bearer identity") bad_cred = base64.b64encode( f"{alice['registration']['username']}:definitely-wrong-password-999".encode("utf-8") ).decode("ascii") saw_429 = False for _ in range(12): r = c.call( "POST", "/api/v1/auth/sessions", [401, 429], headers={"Authorization": f"Basic {bad_cred}"}, ) if r["status"] == 429: ra = r["headers"].get("Retry-After") check(ra is not None and int(ra) >= 1, "429 must include positive Retry-After") saw_429 = True break check(saw_429, "expected 429 after brute-force login attempts") print("PASS: grade 4 negative checks (attachment/message ACL, X-User-Id immunity, login 429 + Retry-After)") def _tls_probe(host: str, port: int, ca_file: Path, cert_file: Path | None = None, key_file: Path | None = None) -> bool: """Возвращает True, если TLS-рукопожатие успешно, и False при отказе на TLS/соединении.""" import socket import ssl ctx = ssl.create_default_context(cafile=str(ca_file)) if cert_file and key_file: ctx.load_cert_chain(str(cert_file), str(key_file)) try: with socket.create_connection((host, port), timeout=3) as raw_sock: with ctx.wrap_socket(raw_sock, server_hostname=host) as tls_sock: tls_sock.do_handshake() return True except (ssl.SSLError, OSError): return False def test_mtls_matrix_endpoints() -> None: """Проверяет доступность/отказ по TLS/mTLS для LB->API, Redis и Collector при наличии соответствующих параметров.""" import os from pathlib import Path root = Path(__file__).resolve().parent.parent ca_file = Path(os.getenv("CA_FILE", root / "infra/certs/ca.crt")) edge_crt = Path(os.getenv("EDGE_LB_CRT", root / "infra/certs/edge-lb.crt")) edge_key = Path(os.getenv("EDGE_LB_KEY", root / "infra/certs/edge-lb.key")) unpriv_crt = Path(os.getenv("UNPRIV_CRT", root / "infra/certs/unprivileged-client.crt")) unpriv_key = Path(os.getenv("UNPRIV_KEY", root / "infra/certs/unprivileged-client.key")) assert ca_file.exists(), f"Missing CA file: {ca_file}" api_host = os.getenv("API_MTLS_HOST") api_port = int(os.getenv("API_MTLS_PORT", "8443")) if api_host: assert not _tls_probe(api_host, api_port, ca_file, None, None), "API must reject connection without client cert" if unpriv_crt.exists() and unpriv_key.exists(): assert not _tls_probe(api_host, api_port, ca_file, unpriv_crt, unpriv_key), ( "API must reject unprivileged client cert" ) if edge_crt.exists() and edge_key.exists(): assert _tls_probe(api_host, api_port, ca_file, edge_crt, edge_key), ( "API must accept edge-lb client cert" ) redis_host = os.getenv("REDIS_TLS_HOST") redis_port = int(os.getenv("REDIS_TLS_PORT", "6379")) if redis_host: assert not _tls_probe(redis_host, redis_port, ca_file, None, None), "Redis must reject connection without client cert" if unpriv_crt.exists() and unpriv_key.exists(): assert not _tls_probe(redis_host, redis_port, ca_file, unpriv_crt, unpriv_key), ( "Redis must reject unprivileged client cert" ) collector_host = os.getenv("COLLECTOR_TLS_HOST") collector_port = int(os.getenv("COLLECTOR_TLS_PORT", "4318")) if collector_host: assert not _tls_probe(collector_host, collector_port, ca_file, None, None), ( "Collector must reject connection without client cert" ) if unpriv_crt.exists() and unpriv_key.exists(): assert not _tls_probe(collector_host, collector_port, ca_file, unpriv_crt, unpriv_key), ( "Collector must reject unprivileged client cert" ) def test_openbao_policy_and_secret_id_revocation() -> None: """Проверяет изоляцию пути KV, запрет записи policy и невалидность старого SecretID.""" import json import os import ssl import urllib.error import urllib.request from pathlib import Path bao_addr = os.getenv("BAO_ADDR") role_id = os.getenv("TEST_BAO_ROLE_ID") secret_id = os.getenv("TEST_BAO_SECRET_ID") revoked_secret_id = os.getenv("TEST_REVOKED_BAO_SECRET_ID") if not (bao_addr and role_id and secret_id): return root = Path(__file__).resolve().parent.parent ca_file = Path(os.getenv("BAO_CACERT", root / "infra/certs/ca.crt")) ctx = ssl.create_default_context(cafile=str(ca_file)) def _bao_req(method: str, path: str, body: dict | None = None, token: str | None = None) -> tuple[int, dict | None]: data = json.dumps(body).encode() if body is not None else None headers = {"Content-Type": "application/json"} if token: headers["X-Vault-Token"] = token req = urllib.request.Request(f"{bao_addr.rstrip('/')}{path}", data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, context=ctx, timeout=5) as resp: raw = resp.read().decode("utf-8", "ignore") return resp.status, json.loads(raw) if raw else None except urllib.error.HTTPError as exc: raw = exc.read().decode("utf-8", "ignore") return exc.code, json.loads(raw) if raw else None if revoked_secret_id: rev_status, _ = _bao_req("POST", "/v1/auth/approle/login", {"role_id": role_id, "secret_id": revoked_secret_id}) assert rev_status in (400, 403), f"Expected revoked SecretID to fail, got HTTP {rev_status}" status, payload = _bao_req("POST", "/v1/auth/approle/login", {"role_id": role_id, "secret_id": secret_id}) assert status == 200 and payload and payload.get("auth", {}).get("client_token"), ( f"Expected valid AppRole login, got HTTP {status}: {payload}" ) token = payload["auth"]["client_token"] own_status, _ = _bao_req("GET", "/v1/secret/data/messenger/api/db", token=token) assert own_status == 200, f"Expected 200 on own secret path, got {own_status}" other_status, _ = _bao_req("GET", "/v1/secret/data/messenger/worker/db", token=token) assert other_status == 403, f"Expected 403 on worker secret path, got {other_status}" pol_status, _ = _bao_req("PUT", "/v1/sys/policies/acl/test-denial", {"policy": "path \"*\" { capabilities = [\"read\"] }"}, token=token) assert pol_status == 403, f"Expected 403 on policy write, got {pol_status}" if __name__ == "__main__": run(main)