Добавил вложения и очистку

This commit is contained in:
Югай Артур Рустамович
2026-11-16 20:14:31 +03:00
parent ec540a1a72
commit 74e0750d18
48 changed files with 4559 additions and 41 deletions
+232
View File
@@ -0,0 +1,232 @@
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
import json
import subprocess
from urllib.parse import urlencode
from uuid import uuid4
from helpers import Client, ROOT, arguments, cleanup_once, image_bytes, lab, object_exists, s3, sql, wait
@contextmanager
def fault(chat_id, action):
name = "fault_" + uuid4().hex
sql("CREATE FUNCTION " + name + "() RETURNS trigger LANGUAGE plpgsql AS $body$ BEGIN "
"IF NEW.chat_id='" + chat_id + "'::uuid THEN " + action + "; END IF; RETURN NEW; END; $body$; "
"CREATE TRIGGER " + name + " BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION " + name + "()")
try:
yield
finally:
sql("DROP TRIGGER IF EXISTS " + name + " ON attachments; DROP FUNCTION IF EXISTS " + name + "()")
def intent(chat, actor, key=None):
identity = str(uuid4())
key = key or "originals/" + uuid4().hex
sql("INSERT INTO upload_intents(id,chat_id,owner_id,object_key) VALUES ('"
+ identity + "','" + chat["id"] + "','" + actor["id"] + "','" + key + "')")
return identity, key
def age(identity):
sql("UPDATE upload_intents SET created_at=clock_timestamp()-INTERVAL '11 minutes' WHERE id='" + identity + "'")
def present(identity):
return sql("SELECT count(*) FROM upload_intents WHERE id='" + identity + "'") == "1"
def put(key):
s3("c.put_object(Bucket=b,Key=" + repr(key) + ",Body=b'cleanup-test'); print('true')")
def privacy(client, actor, chat):
args = arguments()
current = lab.states(args)
networks = {}
for name in ("api1", "s3", "s3-storage"):
networks[name] = set(json.loads(lab.run(args, ["docker", "inspect", "--format",
"{{json .NetworkSettings.Networks}}", current[name]["id"]], quiet=True)))
assert not networks["api1"] & networks["s3-storage"], "Storage interfaces share the application network"
assert networks["api1"] & networks["s3"] and networks["s3-storage"] & networks["s3"]
for name in ("api1", "api2", "db", "s3", "s3-storage"):
ports = json.loads(lab.run(args, ["docker", "inspect", "--format",
"{{json .HostConfig.PortBindings}}", current[name]["id"]], quiet=True))
assert not ports, "Internal service has public ports"
att, raw = client.attachment(actor, chat)
key = sql("SELECT object_key FROM attachments WHERE id='" + att["id"] + "'")
anonymous = s3(
"import boto3, os; from botocore import UNSIGNED; from botocore.config import Config; "
"from botocore.exceptions import ClientError\n"
"u=boto3.client('s3',endpoint_url=os.environ['S3_ENDPOINT'],config=Config(signature_version=UNSIGNED,proxies={}))\n"
"try:\n u.get_object(Bucket=b,Key=" + repr(key) + "); status=200\n"
"except ClientError as e:\n status=e.response['ResponseMetadata']['HTTPStatusCode']\n"
"print(json.dumps(status))"
)
assert anonymous == 403, "Anonymous S3 access is allowed"
other = "other-" + uuid4().hex
forbidden = "forbidden-" + uuid4().hex
s3("c.create_bucket(Bucket=" + repr(other) + "); "
"c.put_object(Bucket=" + repr(other) + ",Key='private',Body=b'x'); print('true')")
try:
denied = s3(
"from botocore.exceptions import ClientError\n"
"checks=[('get_object',dict(Bucket=" + repr(other) + ",Key='private')),"
"('create_bucket',dict(Bucket=" + repr(forbidden) + ")),"
"('put_bucket_acl',dict(Bucket=b,ACL='public-read'))]\n"
"result=[]\n"
"for operation,values in checks:\n"
" try:\n getattr(c,operation)(**values); result.append(200)\n"
" except ClientError as e:\n result.append(e.response['ResponseMetadata']['HTTPStatusCode'])\n"
"print(json.dumps(result))", admin=False,
)
assert denied == [403, 403, 403], "Application credentials are too broad"
finally:
s3("c.delete_object(Bucket=" + repr(other) + ",Key='private'); "
"c.delete_bucket(Bucket=" + repr(other) + "); print('true')")
lab.compose(arguments(), "run", "--rm", "--no-deps", "bootstrap")
downloaded = client.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=actor)["bytes"]
assert downloaded == raw
return {"anonymous_get": anonymous, "other_bucket_get": denied[0],
"create_bucket": denied[1], "change_acl": denied[2], "bootstrap_replay": "PASS",
"storage_network_isolated": True, "internal_ports_not_published": True}, att, key
def main():
args = arguments()
client = lab.client(args)
alice, bob, eve, chat = client.bootstrap()
result = {}
lab.compose(args, "stop", "--timeout", "3", "cleanup")
try:
result["privacy"], good, good_key = privacy(client, alice, chat)
fresh_id, fresh_key = intent(chat, alice)
put(fresh_key)
cleanup_once()
assert present(fresh_id) and object_exists(fresh_key)
result["fresh_intent_protected"] = "PASS"
age(fresh_id)
lock_name = "lab4_lock_" + uuid4().hex
command = ["docker", "compose", "--project-name", args.project, "--env-file", ".env",
"exec", "-T", "db", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c",
"SET application_name='" + lock_name + "'; BEGIN; SELECT id FROM upload_intents WHERE id='"
+ fresh_id + "' FOR UPDATE; SELECT pg_sleep(60); COMMIT"]
with subprocess.Popen(command, cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) as process:
try:
wait(lambda: sql("SELECT count(*) FROM pg_stat_activity WHERE application_name='"
+ lock_name + "' AND wait_event='PgSleep'") == "1", 10)
cleanup_once()
assert present(fresh_id) and object_exists(fresh_key)
result["locked_intent_skipped"] = "PASS"
finally:
sql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name='" + lock_name + "'")
process.wait(timeout=10)
cleanup_once()
assert not present(fresh_id) and not object_exists(fresh_key)
cleanup_once()
result["orphan_removed_and_repeat_safe"] = "PASS"
protected_id, _ = intent(chat, alice, good_key)
age(protected_id)
cleaned = cleanup_once()
assert cleaned["protected"] >= 1 and not present(protected_id) and object_exists(good_key)
import hashlib
protected = client.call("GET", "/api/v1/attachments/" + good["id"] + "/content", actor=bob)["bytes"]
assert hashlib.sha256(protected).hexdigest() == good["sha256"]
result["ready_unlinked_attachment_protected"] = "PASS"
path = "/api/v1/chats/" + chat["id"] + "/attachments?" + urlencode({"filename": "fault.png"})
with fault(chat["id"], "RAISE EXCEPTION 'test failure after S3 write'"):
client.call("POST", path, 500, actor=alice, raw=image_bytes(), headers={"Content-Type": "image/png"})
row = json.loads(sql("SELECT row_to_json(x) FROM (SELECT id,object_key FROM upload_intents WHERE chat_id='"
+ chat["id"] + "' ORDER BY created_at DESC LIMIT 1) x"))
assert object_exists(row["object_key"])
age(row["id"])
cleanup_once()
assert not present(row["id"]) and not object_exists(row["object_key"])
result["sql_failure_after_put_compensated"] = "PASS"
mapping = lab.instance_map(args)
addresses = {}
for service, item in mapping.items():
networks = json.loads(lab.run(args, ["docker", "inspect", "--format",
"{{json .NetworkSettings.Networks}}", item["container_id"]], quiet=True))
for network in networks.values():
addresses[network["IPAddress"]] = service
def interrupted_upload():
try:
Client(lab.base_url(args), timeout=20).call(
"POST", path, 201, actor=alice, raw=image_bytes(), headers={"Content-Type": "image/png"},
)
except (AssertionError, OSError):
return
with fault(chat["id"], "PERFORM pg_sleep(30)"):
with ThreadPoolExecutor(max_workers=1) as pool:
pending = pool.submit(interrupted_upload)
def session():
return sql("SELECT json_build_object('address',host(client_addr)) FROM pg_stat_activity "
"WHERE wait_event='PgSleep' AND query LIKE 'INSERT INTO attachments%' LIMIT 1")
wait(lambda: bool(session()), 10)
service = addresses[json.loads(session())["address"]]
row = json.loads(sql("SELECT row_to_json(x) FROM (SELECT id,object_key FROM upload_intents WHERE chat_id='"
+ chat["id"] + "' ORDER BY created_at DESC LIMIT 1) x"))
lab.run(args, ["docker", "kill", mapping[service]["container_id"]])
pending.result(timeout=25)
assert object_exists(row["object_key"]), "Fault was not injected after S3 PUT"
lab.restore(args)
assert present(row["id"])
assert sql("SELECT count(*) FROM attachments WHERE id='" + row["id"] + "'") == "0"
age(row["id"])
cleanup_once()
assert not present(row["id"]) and not object_exists(row["object_key"])
result["api_killed_after_put_compensated"] = {"status": "PASS", "service": service}
retry_id, retry_key = intent(chat, alice)
put(retry_key)
age(retry_id)
try:
lab.compose(args, "stop", "--timeout", "3", "s3")
cleanup_once(expected=False)
assert present(retry_id)
client.call("GET", "/health/live", schema="Health")
lab.outage_response(args, "/health/ready")
finally:
lab.compose(args, "start", "s3")
lab.wait_ready(args)
cleanup_once()
assert not present(retry_id) and not object_exists(retry_key)
result["s3_outage_keeps_intent_then_recovers"] = "PASS"
import socket
from urllib.parse import urlsplit
endpoint = urlsplit(client.base)
before = sql("SELECT count(*) FROM attachments WHERE chat_id='" + chat["id"] + "'")
with socket.create_connection((endpoint.hostname, endpoint.port), timeout=5) as connection:
request = ("POST " + path + " HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer "
+ alice["token"] + "\r\nContent-Type: image/png\r\nContent-Length: 1000000\r\n\r\n")
connection.sendall(request.encode("ascii") + image_bytes())
import time
time.sleep(0.5)
assert sql("SELECT count(*) FROM attachments WHERE chat_id='" + chat["id"] + "'") == before
assert sql("SELECT count(*) FROM upload_intents WHERE chat_id='" + chat["id"] + "'") == "0"
result["client_disconnect_has_no_publication"] = "PASS"
worker_id, worker_key = intent(chat, alice)
put(worker_key)
age(worker_id)
lab.compose(args, "start", "cleanup")
wait(lambda: not present(worker_id), 45)
assert not object_exists(worker_key)
result["periodic_cleanup_worker"] = "PASS"
lab.evidence("cleanup.json", result)
print("PASS: private S3, restricted credentials, real faults and safe cleanup")
finally:
lab.compose(args, "start", "s3", "cleanup")
lab.restore(args)
if __name__ == "__main__":
main()
+129
View File
@@ -0,0 +1,129 @@
from concurrent.futures import ThreadPoolExecutor
import argparse
import hashlib
import json
from pathlib import Path
import subprocess
import threading
import time
from urllib.parse import urlencode
from uuid import uuid4
from helpers import Client, ROOT, image_bytes, lab, padded_png
RUNTIME = ("lb", "api1", "api2", "cleanup", "s3", "s3-storage", "db")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--project", required=True)
parser.add_argument("--port", required=True, type=int)
args = parser.parse_args()
args.ttl, args.test_port = 3600, args.port
samplers, records, readers = {}, {"api1": [], "api2": []}, []
result = {"clients": 10, "upload_slots_per_replica": 2, "sampling_seconds": 0.05, "profiles": []}
flag = "/tmp/memory-stop-" + uuid4().hex
code = (
"import json,time; from pathlib import Path\n"
"root=Path('/sys/fs/cgroup')\n"
"while not Path(" + repr(flag) + ").exists():\n"
" status=dict(line.split(':',1) for line in Path('/proc/1/status').read_text().splitlines())\n"
" events=dict(line.split() for line in (root/'memory.events').read_text().splitlines())\n"
" print(json.dumps({'current':int((root/'memory.current').read_text()),"
"'peak':int((root/'memory.peak').read_text()),'limit':int((root/'memory.max').read_text()),"
"'rss':int(status['VmRSS'].split()[0])*1024,'hwm':int(status['VmHWM'].split()[0])*1024,"
"'oom_kill':int(events['oom_kill'])}),flush=True)\n"
" time.sleep(0.05)"
)
try:
# свежие API дают отдельный cgroup peak для этого опыта
lab.compose(args, "stop", "--timeout", "3", *RUNTIME)
lab.compose(args, "rm", "-f", "api1", "api2")
lab.start(args)
client = Client(lab.base_url(args), timeout=60)
actor, bob, eve, chat = client.bootstrap()
initial = lab.states(args)
for service in records:
command = ["docker", "exec", initial[service]["id"], "python", "-u", "-c", code]
process = subprocess.Popen(command, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
text=True, encoding="utf-8")
samplers[service] = process
def collect(name=service, running=process):
for line in running.stdout:
item = json.loads(line)
item["received_at"] = time.monotonic()
records[name].append(item)
reader = threading.Thread(target=collect)
reader.start()
readers.append(reader)
deadline = time.monotonic() + 10
while not all(records.values()):
if time.monotonic() > deadline:
raise AssertionError("Memory sampler did not start")
time.sleep(0.05)
result["baseline"] = {name: values[-1] for name, values in records.items()}
profiles = [
("near_byte_limit", padded_png(10 * 1024 * 1024 - 1024), [32, 24]),
("near_pixel_limit", image_bytes(size=(8000, 5000), mode="RGBA"), [8000, 5000]),
]
for name, raw, dimensions in profiles:
started = time.monotonic()
barrier = threading.Barrier(10)
def upload(_):
c = Client(client.base, timeout=60)
barrier.wait(timeout=15)
response = c.call(
"POST", "/api/v1/chats/" + chat["id"] + "/attachments?"
+ urlencode({"filename": name + ".png"}), 201, actor=actor, raw=raw,
headers={"Content-Type": "image/png"}, schema="Attachment",
)
return response["json"], response["headers"]["X-Instance-Id"], response["elapsed"]
with ThreadPoolExecutor(max_workers=10) as pool:
uploads = list(pool.map(upload, range(10)))
for att, instance, elapsed in uploads:
downloaded = client.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob)["bytes"]
assert hashlib.sha256(downloaded).hexdigest() == att["sha256"] == hashlib.sha256(raw).hexdigest()
assert downloaded == raw
peaks = {}
for service, values in records.items():
window = [item for item in values if item["received_at"] >= started]
assert window, "No memory samples during upload"
peaks[service] = {
"sampled_cgroup_peak_bytes": max(x["current"] for x in window),
"sampled_rss_peak_bytes": max(x["rss"] for x in window),
"cgroup_lifetime_peak_bytes": window[-1]["peak"],
"process_lifetime_hwm_bytes": window[-1]["hwm"],
"memory_limit_bytes": window[-1]["limit"],
"oom_kills": window[-1]["oom_kill"],
}
assert peaks[service]["oom_kills"] == 0
assert peaks[service]["cgroup_lifetime_peak_bytes"] < peaks[service]["memory_limit_bytes"]
assert len({item[0]["id"] for item in uploads}) == 10
assert len({item[1] for item in uploads}) == 2
result["profiles"].append({
"name": name, "file_bytes": len(raw), "dimensions": dimensions, "successes": len(uploads),
"errors": 0, "seconds": round(time.monotonic() - started, 3),
"slowest_upload_seconds": round(max(item[2] for item in uploads), 3),
"replicas_used": 2, "originals_verified": 10, "memory": peaks,
})
for service in records:
data = json.loads(lab.run(args, ["docker", "inspect", "--format",
'{"oom":{{json .State.OOMKilled}},"restarts":{{.RestartCount}}}',
initial[service]["id"]], quiet=True))
assert not data["oom"] and data["restarts"] == 0
result["status"] = "PASS"
lab.evidence("memory.json", result)
print("PASS: 10 concurrent uploads in both profiles; originals intact, no OOM or restarts")
finally:
for service, process in samplers.items():
lab.compose(args, "exec", "-T", service, "python", "-c", "from pathlib import Path; Path(" + repr(flag) + ").touch()",
quiet=True)
process.wait(timeout=10)
for reader in readers:
reader.join(timeout=5)
lab.compose(args, "stop", "--timeout", "10", *RUNTIME)
if __name__ == "__main__":
main()
+90
View File
@@ -0,0 +1,90 @@
import argparse
import io
import json
import os
from pathlib import Path
import struct
import subprocess
import sys
import time
import zlib
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "tests"))
from client import Client
from scripts import lab
def arguments():
return argparse.Namespace(
project=os.environ.get("LAB4_PROJECT", "mtusi-lab4"),
port=int(os.environ.get("LAB4_PORT", "8080")),
ttl=int(os.environ.get("LAB4_TTL", "3600")), test_port=18082,
)
def sql(statement):
args = arguments()
return lab.compose(args, "exec", "-T", "db", "psql", "-U", "messenger", "-d", "messenger",
"-v", "ON_ERROR_STOP=1", "-At", "-c", statement, quiet=True).strip()
def s3(code, admin=True):
args = arguments()
prelude = "import json; from src.objects import Objects; o=Objects(admin=" + str(admin) + "); c=o.client; b=o.bucket; "
if admin:
output = lab.compose(args, "run", "--rm", "--no-deps", "-T", "bootstrap",
"python", "-c", prelude + code, quiet=True)
else:
output = lab.compose(args, "exec", "-T", "api1", "python", "-c", prelude + code, quiet=True)
return json.loads(output.strip().splitlines()[-1])
def object_exists(key):
return s3("print(json.dumps(any(x['Key']==" + repr(key)
+ " for x in c.list_objects_v2(Bucket=b,Prefix=" + repr(key) + ").get('Contents',[]))))")
def wait(predicate, seconds=30):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
if predicate():
return
time.sleep(0.1)
raise AssertionError("Test condition timed out")
def image_bytes(kind="PNG", size=(32, 24), mode="RGB"):
with Image.new(mode, size, (35, 120, 200, 255) if mode == "RGBA" else (35, 120, 200)) as image:
output = io.BytesIO()
image.save(output, format=kind)
return output.getvalue()
def chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xffffffff)
def padded_png(size):
base = image_bytes()
padding = b"p" * (size - len(base) - 12)
return base[:-12] + chunk(b"raNd", padding) + base[-12:]
def oversized_pixels():
header = struct.pack(">IIBBBBB", 8000, 5001, 8, 2, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IEND", b"")
def cleanup_once(expected=True):
args = arguments()
command = ["docker", "compose", "--project-name", args.project, "--env-file", ".env",
"run", "--rm", "--no-deps", "-T", "cleanup", "python", "-m", "src.cleanup", "--once"]
result = subprocess.run(command, cwd=ROOT, env=lab.environment(args), capture_output=True, text=True, encoding="utf-8")
if (result.returncode == 0) != expected:
raise AssertionError("Unexpected cleanup exit status")
return json.loads(result.stdout.strip().splitlines()[-1]) if expected else None
+181
View File
@@ -0,0 +1,181 @@
from concurrent.futures import ThreadPoolExecutor
import os
from pathlib import Path
import sys
import unittest
from urllib.parse import urlencode
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, timestamp
class ApiTests(unittest.TestCase):
def setUp(self):
self.client = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
self.path = "/api/v1/chats/" + self.chat["id"]
def error(self, method, path, status=400, **kwargs):
if method == "POST" and path.endswith("/messages"):
kwargs.setdefault("headers", {}).setdefault("Idempotency-Key", uuid4().hex)
response = self.client.call(method, path, status, **kwargs)
code = {400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict", 415: "unsupported_media_type"}[status]
self.assertEqual(response["json"]["error"]["code"], code)
def get_page(self, path, actor=None, **query):
schema = "MessagePage" if path.endswith("/messages") else "ChatPage"
return self.client.call("GET", path + "?" + urlencode(query), actor=actor or self.alice, schema=schema)["json"]
def new_chat(self):
return self.client.call("POST", "/api/v1/chats", 201, actor=self.alice,
body={"title": "Ещё чат", "member_ids": [self.alice["id"], self.bob["id"]]}, schema="Chat")["json"]
def test_user_fields(self):
name = "u_" + uuid4().hex[:20]
bodies = [
{"username": "ab", "display_name": "Имя"},
{"username": "ABC", "display_name": "Имя"},
{"username": "valid\n", "display_name": "Имя"},
{"username": 123, "display_name": "Имя"},
{"username": name, "display_name": " \t\n"},
{"username": name, "display_name": 123},
{"username": name, "display_name": None},
{"username": name, "display_name": "я" * 101},
{"username": name, "display_name": "Имя", "password": "extra"},
{"username": name},
]
for body in bodies:
body.setdefault("password", "T3st-password-123")
with self.subTest(fields=sorted(body)):
self.error("POST", "/api/v1/users", body=body)
user = self.client.call("POST", "/api/v1/users", 201,
body={"username": name, "display_name": "👋" * 100, "password": "T3st-password-123"}, schema="User")["json"]
self.assertEqual(user["display_name"], "👋" * 100)
self.error("POST", "/api/v1/users", 409, body={"username": name, "display_name": "Повтор", "password": "T3st-password-123"})
def test_invalid_json_and_content_type(self):
for raw in (b'{"username":', b"null", b"[]", b"true", b"\xff", '{}'.encode('utf-16')):
with self.subTest(raw=raw):
self.error("POST", "/api/v1/users", raw=raw, headers={"Content-Type": "application/json"})
self.error("POST", "/api/v1/users", 415, raw=b"text", headers={"Content-Type": "text/plain"})
self.error("POST", "/api/v1/users", 415, raw=b"{}")
def test_auth_and_access(self):
self.error("GET", "/api/v1/users/me", 401)
for value in (str(uuid4()), "bad-id"):
self.error("GET", "/api/v1/users/me", 401, headers={"X-User-Id": value})
self.error("GET", "/api/v1/chats/bad-id", 401)
self.error("GET", "/api/v1/chats/bad-id", actor=self.alice)
self.error("GET", "/api/v1/chats/" + str(uuid4()), 404, actor=self.alice)
self.error("GET", self.path, 404, actor=self.eve)
self.error("GET", self.path + "/messages", 404, actor=self.eve)
self.error("POST", self.path + "/messages", 404, actor=self.eve, body={"text": "Чужое"})
self.assertEqual(self.get_page("/api/v1/chats", self.eve)["items"], [])
def test_chat_validation_is_atomic(self):
before = self.get_page("/api/v1/chats")["items"]
valid = [self.alice["id"], self.bob["id"]]
for members in ([], [self.bob["id"]], [self.alice["id"], str(uuid4())],
[self.alice["id"], self.alice["id"].upper()], ["bad-id"], valid * 51):
self.error("POST", "/api/v1/chats", actor=self.alice, body={"title": "Чат", "member_ids": members})
for title in ("", " \t", "я" * 101, 123):
self.error("POST", "/api/v1/chats", actor=self.alice, body={"title": title, "member_ids": valid})
self.error("POST", "/api/v1/chats", actor=self.alice, body={"title": "Чат", "member_ids": valid, "extra": 1})
self.assertEqual(before, self.get_page("/api/v1/chats")["items"])
def test_message_fields_and_unicode(self):
bodies = [{"text": value} for value in ("", " \t\n", "я" * 4001, None, 123, True, [])]
bodies += [{}, {"text": "Hi", "sender_id": self.bob["id"]}, {"text": "Hi", "unexpected": []}]
for body in bodies:
self.error("POST", self.path + "/messages", actor=self.alice, body=body)
for text in (" Привет, мир 👋\n", "👋" * 4000):
message = self.client.message(self.alice, self.chat, text)["json"]
self.assertEqual(message["text"], text)
self.assertEqual(message["sender_id"], self.alice["id"])
def test_message_pagination(self):
self.assertEqual(self.get_page(self.path + "/messages"), {"items": [], "next_cursor": None})
self.assertEqual(self.get_page(self.path + "/messages", limit="0000000001")["items"], [])
sent = [self.client.message(self.alice if i % 2 else self.bob, self.chat, str(i))["json"] for i in range(6)]
received, cursor = [], None
for limit in (2, 3, 1):
query = {"limit": limit}
if cursor:
query["cursor"] = cursor
page = self.get_page(self.path + "/messages", self.bob, **query)
received.extend(page["items"])
cursor = page["next_cursor"]
self.assertIsNone(cursor)
self.assertEqual(received, sorted(sent, key=lambda item: (timestamp(item["created_at"]), item["id"])))
def test_chat_pagination(self):
chats = [self.chat] + [self.new_chat() for _ in range(4)]
received, cursor = [], None
while True:
query = {"limit": 2}
if cursor:
query["cursor"] = cursor
page = self.get_page("/api/v1/chats", **query)
received += page["items"]
cursor = page["next_cursor"]
if cursor is None:
break
self.assertEqual(received, sorted(chats, key=lambda item: (timestamp(item["created_at"]), item["id"])))
cursor = self.get_page("/api/v1/chats", limit=1)["next_cursor"]
self.error("GET", "/api/v1/chats?" + urlencode({"cursor": cursor}), actor=self.bob)
def test_bad_cursors_and_limits(self):
for i in range(2):
self.client.message(self.alice, self.chat, str(i))
cursor = self.get_page(self.path + "/messages", limit=1)["next_cursor"]
for value in ("", "bad", cursor[:-1] + ("0" if cursor[-1] != "0" else "1")):
self.error("GET", self.path + "/messages?" + urlencode({"cursor": value}), actor=self.alice)
other = self.new_chat()
self.error("GET", "/api/v1/chats/" + other["id"] + "/messages?" + urlencode({"cursor": cursor}), actor=self.alice)
self.error("GET", "/api/v1/chats?" + urlencode({"cursor": cursor}), actor=self.alice)
for path in ("/api/v1/chats", self.path + "/messages"):
for value in ("", "0", "-1", "101", "1.5", "true", "9" * 500):
self.error("GET", path + "?" + urlencode({"limit": value}), actor=self.alice)
def test_read_after_write(self):
first = self.client.message(self.alice, self.chat, "Первое")["json"]
second = self.client.message(self.bob, self.chat, "Второе")["json"]
page = self.get_page(self.path + "/messages", limit=1)
third = self.client.message(self.bob, self.chat, "Новое")["json"]
rest = self.get_page(self.path + "/messages", self.bob, cursor=page["next_cursor"])
self.assertEqual(page["items"] + rest["items"], [first, second, third])
self.assertIsNone(rest["next_cursor"])
def test_parallel_messages(self):
def send(worker):
client = Client(self.client.base)
return [client.message(self.alice, self.chat, f"{worker}:{i}")["json"]["id"] for i in range(10)]
with ThreadPoolExecutor(max_workers=10) as pool:
sent = [item for group in pool.map(send, range(10)) for item in group]
received, cursor = [], None
while True:
query = {"limit": 17}
if cursor:
query["cursor"] = cursor
page = self.get_page(self.path + "/messages", self.bob, **query)
received += page["items"]
cursor = page["next_cursor"]
if cursor is None:
break
self.assertEqual(len(received), 100)
self.assertEqual(len({item["text"] for item in received}), 100)
self.assertEqual({item["id"] for item in received}, set(sent))
def test_parallel_username(self):
body = {"username": "u_" + uuid4().hex[:20], "display_name": "Один", "password": "T3st-password-123"}
def create(_):
return Client(self.client.base).call("POST", "/api/v1/users", [201, 409], body=body, schema="User")["status"]
with ThreadPoolExecutor(max_workers=10) as pool:
statuses = list(pool.map(create, range(10)))
self.assertEqual(statuses.count(201), 1)
self.assertEqual(statuses.count(409), 9)
if __name__ == "__main__":
unittest.main(verbosity=2)
+117
View File
@@ -0,0 +1,117 @@
from concurrent.futures import ThreadPoolExecutor
import hashlib
from urllib.parse import urlencode
from uuid import uuid4
import unittest
from helpers import Client, ROOT, image_bytes, oversized_pixels, padded_png
class AttachmentTests(unittest.TestCase):
def setUp(self):
self.client = Client(timeout=60)
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
self.path = "/api/v1/chats/" + self.chat["id"]
def upload(self, content=None, media="image/png", name="photo.png", expected=201, actor=None):
return self.client.call(
"POST", self.path + "/attachments?" + urlencode({"filename": name}), expected,
actor=actor or self.alice, raw=image_bytes() if content is None else content,
headers={"Content-Type": media}, schema="Attachment" if expected == 201 else None,
)
def test_original_png_jpeg_and_unicode_filename(self):
for kind, media in (("PNG", "image/png"), ("JPEG", "image/jpeg")):
raw = image_bytes(kind)
att = self.upload(raw, media, "фото 👋." + kind.lower())["json"]
self.assertEqual(att["owner_id"], self.alice["id"])
self.assertEqual(att["sha256"], hashlib.sha256(raw).hexdigest())
self.assertEqual(att["size_bytes"], len(raw))
self.assertEqual((att["status"], att["variants"], att["error_code"]), ("ready", [], None))
path = "/api/v1/attachments/" + att["id"]
metadata = self.client.call("GET", path, actor=self.bob, schema="Attachment")["json"]
self.assertEqual(metadata, att)
downloaded = self.client.call("GET", path + "/content", actor=self.bob)
self.assertEqual(downloaded["bytes"], raw)
self.assertEqual(downloaded["headers"].get_content_type(), media)
self.assertNotIn("object_key", metadata)
self.assertNotIn("Location", downloaded["headers"])
def test_filename_validation(self):
for name in ("", " \t", "../a.png", "a/b.png", "a\\b.png", "a\x00.png", "a\n.png", "a\x7f.png", "я" * 256):
self.upload(name=name, expected=400)
self.assertEqual(self.upload(name="я" * 255)["json"]["filename"], "я" * 255)
def test_corrupt_images_mime_and_multipart(self):
png, jpeg = image_bytes(), image_bytes("JPEG")
for content, media in ((b"", "image/png"), (b"not an image", "image/png"),
(png[:-8], "image/png"), (jpeg[:-8], "image/jpeg"),
(png, "image/jpeg"), (jpeg, "image/png"),
(image_bytes("GIF"), "image/png"), (png, "multipart/form-data")):
self.upload(content, media, expected=415)
def test_byte_limit_and_original_at_exact_boundary(self):
raw = padded_png(10485760)
att = self.upload(raw)["json"]
downloaded = self.client.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=self.bob)
self.assertEqual(downloaded["bytes"], raw)
self.upload(raw + b"x", expected=413)
def test_chunked_body_cannot_bypass_size_limit(self):
def blocks():
for _ in range(161):
yield b"x" * 65536
self.upload(blocks(), expected=413)
def test_pixel_boundary_and_decompression_bomb(self):
self.upload(oversized_pixels(), expected=413)
self.assertEqual(self.upload(image_bytes(size=(8000, 5000)))["json"]["status"], "ready")
def test_attachment_access_and_unknown_ids(self):
att = self.upload()["json"]
for suffix in ("", "/content"):
self.client.call("GET", "/api/v1/attachments/" + att["id"] + suffix, 404, actor=self.eve)
self.client.call("GET", "/api/v1/attachments/" + str(uuid4()) + suffix, 404, actor=self.alice)
self.client.call("GET", "/api/v1/attachments/" + att["id"] + suffix, 401)
self.upload(actor=self.eve, expected=404)
def test_messages_keep_attachment_order_and_allow_empty_text(self):
ids = [self.upload()["json"]["id"] for _ in range(2)]
for text in ("", " \t\n", "с картинками"):
message = self.client.message(self.bob, self.chat, text, attachments=ids[::-1])["json"]
self.assertEqual(message["attachment_ids"], ids[::-1])
self.assertEqual(message["text"], text)
page = self.client.call("GET", self.path + "/messages", actor=self.alice, schema="MessagePage")["json"]
self.assertEqual([m["attachment_ids"] for m in page["items"]], [ids[::-1]] * 3)
def test_bad_attachment_list_and_other_chat_do_not_create_messages(self):
att = self.upload()["json"]["id"]
other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice,
body={"title": "other", "member_ids": [self.alice["id"]]}, schema="Chat")["json"]
foreign = self.client.attachment(self.alice, other)[0]["id"]
for ids, status in (([att, att], 400), ([str(uuid4()) for _ in range(11)], 400),
(["bad"], 400), ([str(uuid4())], 404), ([foreign], 404)):
self.client.call("POST", self.path + "/messages", status, actor=self.alice,
body={"text": "test", "attachment_ids": ids}, headers={"Idempotency-Key": uuid4().hex})
page = self.client.call("GET", self.path + "/messages", actor=self.alice, schema="MessagePage")["json"]
self.assertEqual(page["items"], [])
def test_idempotency_defaults_and_attachment_replay(self):
key = uuid4().hex
original = self.client.message(self.alice, self.chat, "text", key=key)["json"]
explicit = self.client.message(self.alice, self.chat, "text", key=key, attachments=[])["json"]
self.assertEqual(original, explicit)
att = self.upload()["json"]["id"]
key = uuid4().hex
def send(_):
return Client(timeout=30).message(self.alice, self.chat, "", key=key, attachments=[att])
with ThreadPoolExecutor(max_workers=10) as pool:
responses = list(pool.map(send, range(10)))
self.assertEqual(len({r["json"]["id"] for r in responses}), 1)
self.assertEqual(len({r["headers"]["X-Instance-Id"] for r in responses}), 2)
self.client.call("POST", self.path + "/messages", 409, actor=self.alice,
body={"text": "different", "attachment_ids": [att]}, headers={"Idempotency-Key": key})
if __name__ == "__main__":
unittest.main(verbosity=2)
+140
View File
@@ -0,0 +1,140 @@
from concurrent.futures import ThreadPoolExecutor
import base64
import json
import os
from pathlib import Path
import subprocess
import sys
import unittest
from uuid import uuid4
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client
class IdempotencyTests(unittest.TestCase):
def setUp(self):
self.client = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
self.path = "/api/v1/chats/" + self.chat["id"] + "/messages"
def history(self):
return self.client.call("GET", self.path + "?limit=100", actor=self.alice, schema="MessagePage")["json"]["items"]
def sql(self, statement):
project = os.environ.get("LAB4_PROJECT", "mtusi-lab4")
command = ["docker", "compose", "--project-name", project, "--env-file", ".env",
"exec", "-T", "db", "psql", "-U", "messenger", "-d", "messenger",
"-v", "ON_ERROR_STOP=1", "-At", "-c", statement]
result = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, encoding="utf-8")
if result.returncode:
raise AssertionError("Database test command failed")
return result.stdout.strip()
def test_key_required_and_format(self):
for key in (None, "", "two words", "a/b", "é", "a" * 129):
headers = {} if key is None else {"Idempotency-Key": key}
self.client.call("POST", self.path, 400, actor=self.alice, body={"text": "test"}, headers=headers)
for key in ("a", ".:_-", "a" * 128):
self.client.message(self.alice, self.chat, key, key=key)
self.assertEqual(len(self.history()), 3)
def test_replay_normalizes_json(self):
key = uuid4().hex
text = "Привет 👋"
first = self.client.message(self.alice, self.chat, text, key=key)
raw = json.dumps({"text": text}, ensure_ascii=True, indent=4).encode("ascii")
second = self.client.call("POST", self.path, 201, actor=self.alice, raw=raw,
headers={"Idempotency-Key": key, "Content-Type": "application/json"}, schema="Message")
self.assertEqual(first["json"], second["json"])
self.assertNotEqual(first["headers"]["X-Request-Id"], second["headers"]["X-Request-Id"])
self.assertEqual(len(self.history()), 1)
def test_different_body_conflicts(self):
key = uuid4().hex
original = self.client.message(self.alice, self.chat, "first", key=key)["json"]
self.client.call("POST", self.path, 409, actor=self.alice,
body={"text": "second"}, headers={"Idempotency-Key": key})
self.assertEqual(self.client.message(self.alice, self.chat, "first", key=key)["json"], original)
self.assertEqual(self.history(), [original])
def test_twenty_concurrent_requests_use_both_replicas(self):
key = uuid4().hex
def send(_):
return Client(self.client.base).message(self.alice, self.chat, "one message", key=key)
with ThreadPoolExecutor(max_workers=20) as pool:
responses = list(pool.map(send, range(20)))
self.assertEqual(len({item["json"]["id"] for item in responses}), 1)
self.assertEqual(len({item["headers"]["X-Instance-Id"] for item in responses}), 2)
self.assertTrue(all(item["json"] == responses[0]["json"] for item in responses))
self.assertEqual(self.history(), [responses[0]["json"]])
def test_scope_is_user_and_chat_not_session(self):
key = uuid4().hex
first = self.client.message(self.alice, self.chat, "shared", key=key)["json"]
second = self.client.message(self.bob, self.chat, "shared", key=key)["json"]
other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice,
body={"title": "other", "member_ids": [self.alice["id"]]}, schema="Chat")["json"]
third = self.client.message(self.alice, other, "shared", key=key)["json"]
self.assertEqual(len({first["id"], second["id"], third["id"]}), 3)
source = self.alice["registration"]
value = base64.b64encode((source["username"] + ":" + source["password"]).encode()).decode()
session = self.client.call("POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": "Basic " + value}, schema="Session")["json"]
actor = {"id": self.alice["id"], "token": session["token"]}
self.assertEqual(self.client.message(actor, self.chat, "shared", key=key)["json"], first)
def test_replay_still_checks_access_and_session(self):
key = uuid4().hex
self.client.message(self.alice, self.chat, "private", key=key)
self.client.call("POST", self.path, 404, actor=self.eve,
body={"text": "private"}, headers={"Idempotency-Key": key})
self.client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.alice)
self.client.call("POST", self.path, 401, actor=self.alice,
body={"text": "private"}, headers={"Idempotency-Key": key})
def test_failure_rolls_back_message_and_key(self):
key = "fault-" + uuid4().hex
constraint = "test_reject_" + uuid4().hex[:12]
self.sql("ALTER TABLE idempotency_keys ADD CONSTRAINT " + constraint
+ " CHECK(request_key <> '" + key + "') NOT VALID")
try:
self.client.call("POST", self.path, 500, actor=self.alice,
body={"text": "rollback"}, headers={"Idempotency-Key": key})
self.assertEqual(self.history(), [])
self.assertEqual(self.sql("SELECT count(*) FROM idempotency_keys WHERE request_key='" + key + "'"), "0")
finally:
self.sql("ALTER TABLE idempotency_keys DROP CONSTRAINT " + constraint)
result = self.client.message(self.alice, self.chat, "rollback", key=key)["json"]
self.assertEqual(self.client.message(self.alice, self.chat, "rollback", key=key)["json"], result)
self.assertEqual(self.history(), [result])
def test_retention_and_expired_key_reuse(self):
key = uuid4().hex
first = self.client.message(self.alice, self.chat, "old", key=key)["json"]
retained = self.sql("SELECT expires_at-created_at > INTERVAL '23 hours 59 minutes 59 seconds'"
+ " FROM idempotency_keys WHERE request_key='" + key + "'")
self.assertEqual(retained, "t")
self.sql("UPDATE idempotency_keys SET expires_at=created_at + INTERVAL '1 microsecond'"
+ " WHERE request_key='" + key + "'")
second = self.client.message(self.alice, self.chat, "new", key=key)["json"]
self.assertNotEqual(first["id"], second["id"])
self.assertEqual(self.history(), [first, second])
def test_same_session_on_both_instances(self):
responses = [self.client.call("GET", "/api/v1/users/me", actor=self.alice, schema="User")
for _ in range(12)]
self.assertEqual(len({item["headers"]["X-Instance-Id"] for item in responses}), 2)
self.assertTrue(all(item["json"] == self.alice["user"] for item in responses))
def test_invalid_body_does_not_reserve_key(self):
key = uuid4().hex
self.client.call("POST", self.path, 400, actor=self.alice,
body={"text": ""}, headers={"Idempotency-Key": key})
result = self.client.message(self.alice, self.chat, "fixed", key=key)["json"]
self.assertEqual(self.history(), [result])
if __name__ == "__main__":
unittest.main(verbosity=2)
+96
View File
@@ -0,0 +1,96 @@
import base64
import json
import os
from pathlib import Path
import re
import sys
import unittest
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client
def basic(username, password):
value = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
return {"Authorization": "Basic " + value}
class SessionTests(unittest.TestCase):
def setUp(self):
self.client = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
self.actor = self.client.user("auth")
def register(self, password):
body = {"username": "p_" + uuid4().hex[:20], "display_name": "Пароль", "password": password}
user = self.client.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
session = self.client.call("POST", "/api/v1/auth/sessions", 201,
headers=basic(body["username"], password), schema="Session")["json"]
self.assertEqual(session["user"], user)
self.assertEqual(set(session), {"token", "token_type", "expires_at", "user"})
self.assertTrue(re.fullmatch(r"[A-Za-z0-9_-]{43}", session["token"]), "Invalid token format")
return body, session
def test_password_required_and_limits(self):
source = self.actor["registration"]
for password in ("x" * 11, "x" * 129, " " * 12, None, 123, True, "a" * 12 + "\x00"):
body = {**source, "username": "p_" + uuid4().hex[:20], "password": password}
self.client.call("POST", "/api/v1/users", 400, body=body)
missing = {key: value for key, value in source.items() if key != "password"}
self.client.call("POST", "/api/v1/users", 400, body=missing)
raw = json.dumps({**source, "username": "p_" + uuid4().hex[:20], "password": "\ud800" * 12}).encode()
self.client.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": "application/json"})
def test_password_boundaries_unicode_colon_spaces(self):
for password in ("x" * 12, "🙂" * 127 + ":", " Привет:пароль🙂 "):
body, session = self.register(password)
actor = {"id": session["user"]["id"], "token": session["token"]}
self.client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
changed = password.strip() if password != password.strip() else password + "!"
self.client.call("POST", "/api/v1/auth/sessions", 401,
headers=basic(body["username"], changed))
def test_wrong_and_unknown_credentials(self):
source = self.actor["registration"]
wrong = self.client.call("POST", "/api/v1/auth/sessions", 401,
headers=basic(source["username"], "wrong-password-123"))
unknown = self.client.call("POST", "/api/v1/auth/sessions", 401,
headers=basic("unknown_" + uuid4().hex[:12], source["password"]))
self.assertEqual(wrong["json"]["error"]["message"], unknown["json"]["error"]["message"])
self.assertEqual(wrong["headers"]["WWW-Authenticate"], 'Basic realm="messenger", charset="UTF-8"')
def test_malformed_basic_and_body(self):
for value in ("", "Basic", "Basic !!!", "Bearer " + self.actor["token"],
"Basic " + base64.b64encode(b"missing-colon").decode(),
"Basic " + base64.b64encode(b"\xff:some-password").decode()):
self.client.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": value})
source = self.actor["registration"]
self.client.call("POST", "/api/v1/auth/sessions", 400, body={},
headers=basic(source["username"], source["password"]))
def test_only_bearer_identifies_user(self):
source = self.actor["registration"]
for value in ("", "Bearer", "Bearer bad", "Bearer " + "x" * 43,
basic(source["username"], source["password"])["Authorization"]):
self.client.call("GET", "/api/v1/users/me", 401, headers={"Authorization": value})
self.client.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": self.actor["id"]})
other = self.client.user("other")
result = self.client.call("GET", "/api/v1/users/me", actor=self.actor,
headers={"X-User-Id": other["id"]}, schema="User")
self.assertEqual(result["json"]["id"], self.actor["id"])
self.client.call("GET", "/api/v1/users/me", schema="User",
headers={"Authorization": "bEaReR " + self.actor["token"]})
def test_logout_only_revokes_current_session(self):
source = self.actor["registration"]
second = self.client.call("POST", "/api/v1/auth/sessions", 201,
headers=basic(source["username"], source["password"]), schema="Session")["json"]
other_session = {"id": self.actor["id"], "token": second["token"]}
self.client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.actor)
for method, path in (("GET", "/api/v1/users/me"), ("DELETE", "/api/v1/auth/sessions/current")):
self.client.call(method, path, 401, actor=self.actor)
self.client.call("GET", "/api/v1/users/me", actor=other_session, schema="User")
if __name__ == "__main__":
unittest.main(verbosity=2)