forked from mtusi2026/mtusi2026lab7
grade4
This commit is contained in:
+162
-127
@@ -1,139 +1,174 @@
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import json
|
||||
import unittest
|
||||
from client import Client
|
||||
import base64
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
class TestMessengerLevel4Complete(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client()
|
||||
self.alice = self.client.user("alice")
|
||||
self.bob = self.client.user("bob")
|
||||
self.eve = self.client.user("eve")
|
||||
|
||||
res_chat1 = self.client.call(
|
||||
'POST', '/api/v1/chats', 201,
|
||||
actor=self.alice,
|
||||
body={"title": "Team Chat", "member_ids": [self.alice["id"], self.bob["id"]]},
|
||||
schema='Chat'
|
||||
)
|
||||
self.chat1 = res_chat1['json']
|
||||
|
||||
res_chat2 = self.client.call(
|
||||
'POST', '/api/v1/chats', 201,
|
||||
actor=self.eve,
|
||||
body={"title": "Private Chat", "member_ids": [self.eve["id"], self.bob["id"]]},
|
||||
schema='Chat'
|
||||
)
|
||||
self.chat2 = res_chat2['json']
|
||||
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()
|
||||
|
||||
def test_unsupported_media_type(self):
|
||||
"""Проверка 415: передача текстового файла под видом картинки."""
|
||||
fake_bytes = b"Just a simple plain text file content."
|
||||
url = self.client.base + f"/api/v1/chats/{self.chat1['id']}/attachments?filename=notes.txt"
|
||||
req = urllib.request.Request(
|
||||
url, data=fake_bytes,
|
||||
headers={"Authorization": f"Bearer {self.alice['token']}", "Content-Type": "image/png"},
|
||||
method="POST"
|
||||
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) as resp:
|
||||
self.fail("Expected HTTP 415")
|
||||
except urllib.error.HTTPError as e:
|
||||
self.assertEqual(e.code, 415)
|
||||
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
|
||||
|
||||
def test_payload_too_large(self):
|
||||
"""Проверка 413: файл размером больше 10 MiB."""
|
||||
large_data = b'\x89PNG\r\n\x1a\n' + b'\x00' * (10 * 1024 * 1024 + 100)
|
||||
url = self.client.base + f"/api/v1/chats/{self.chat1['id']}/attachments?filename=huge.png"
|
||||
req = urllib.request.Request(
|
||||
url, data=large_data,
|
||||
headers={"Authorization": f"Bearer {self.alice['token']}", "Content-Type": "image/png"},
|
||||
method="POST"
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
self.fail("Expected HTTP 413")
|
||||
except urllib.error.HTTPError as e:
|
||||
self.assertEqual(e.code, 413)
|
||||
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}"
|
||||
|
||||
def test_corrupted_image_signature(self):
|
||||
"""Проверка 415: битая структура / неверные размеры PNG."""
|
||||
corrupted_png = b'\x89PNG\r\n\x1a\n' + b'\xFF' * 50
|
||||
url = self.client.base + f"/api/v1/chats/{self.chat1['id']}/attachments?filename=corrupt.png"
|
||||
req = urllib.request.Request(
|
||||
url, data=corrupted_png,
|
||||
headers={"Authorization": f"Bearer {self.alice['token']}", "Content-Type": "image/png"},
|
||||
method="POST"
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
self.fail("Expected HTTP 415")
|
||||
except urllib.error.HTTPError as e:
|
||||
self.assertEqual(e.code, 415)
|
||||
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"]
|
||||
|
||||
def test_invalid_filename_characters(self):
|
||||
"""Проверка 400: недопустимые символы (path traversal) в имени файла."""
|
||||
valid_png = (
|
||||
b'\x89PNG\r\n\x1a\n'
|
||||
b'\x00\x00\x00\rIHDR'
|
||||
b'\x00\x00\x00\n\x00\x00\x00\n'
|
||||
b'\x08\x02\x00\x00\x00'
|
||||
b'\x02p\xdd\xb5'
|
||||
b'\x00\x00\x00\x0fcIDATx\x9cc`\x00\x00\x00\x02\x00\x01H\xaf\xa4q'
|
||||
b'\x00\x00\x00\x00IEND\xaeB`\x82'
|
||||
)
|
||||
url = self.client.base + f"/api/v1/chats/{self.chat1['id']}/attachments?filename=../../etc/passwd"
|
||||
req = urllib.request.Request(
|
||||
url, data=valid_png,
|
||||
headers={"Authorization": f"Bearer {self.alice['token']}", "Content-Type": "image/png"},
|
||||
method="POST"
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
self.fail("Expected HTTP 400")
|
||||
except urllib.error.HTTPError as e:
|
||||
self.assertEqual(e.code, 400)
|
||||
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}"
|
||||
|
||||
def test_nonexistent_attachment_id(self):
|
||||
"""Проверка 404: передача несуществующего ID вложения при отправке сообщения."""
|
||||
fake_uuid = "12345678-1234-4123-8123-123456789abc"
|
||||
res = self.client.call(
|
||||
'POST', f"/api/v1/chats/{self.chat1['id']}/messages", 404,
|
||||
actor=self.alice,
|
||||
body={"text": "Check this out", "attachment_ids": [fake_uuid]},
|
||||
headers={"Idempotency-Key": "test-key-lvl4-1"}
|
||||
)
|
||||
self.assertEqual(res['status'], 404)
|
||||
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}"
|
||||
|
||||
def test_cross_chat_attachment_isolation(self):
|
||||
"""Проверка 404: попытка прикрепить вложение из чужого чата."""
|
||||
valid_png = (
|
||||
b'\x89PNG\r\n\x1a\n'
|
||||
b'\x00\x00\x00\rIHDR'
|
||||
b'\x00\x00\x00\n\x00\x00\x00\n'
|
||||
b'\x08\x02\x00\x00\x00'
|
||||
b'\x02p\xdd\xb5'
|
||||
b'\x00\x00\x00\x0fcID1Tx\x9cc`\x00\x00\x00\x02\x00\x01H\xaf\xa4q'
|
||||
b'\x00\x00\x00\x00IEND\xaeB`\x82'
|
||||
)
|
||||
url = self.client.base + f"/api/v1/chats/{self.chat2['id']}/attachments?filename=secret.png"
|
||||
req = urllib.request.Request(
|
||||
url, data=valid_png,
|
||||
headers={"Authorization": f"Bearer {self.eve['token']}", "Content-Type": "image/png"},
|
||||
method="POST"
|
||||
)
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
data = json.loads(resp.read().decode())
|
||||
eve_att_id = data["id"]
|
||||
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}"
|
||||
|
||||
res = self.client.call(
|
||||
'POST', f"/api/v1/chats/{self.chat1['id']}/messages", 404,
|
||||
actor=self.alice,
|
||||
body={"text": "Stealing file", "attachment_ids": [eve_att_id]},
|
||||
headers={"Idempotency-Key": "test-key-lvl4-2"}
|
||||
)
|
||||
self.assertEqual(res['status'], 404)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user