feat: Authorize attachment reads and message links (U4)
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
"""Black-box attachment ACL, message links and idempotency on a running lab4 stack."""
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client
|
||||
|
||||
|
||||
class AttachmentAccessTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.client = Client()
|
||||
cls.alice, cls.bob, cls.eve, cls.chat = cls.client.bootstrap()
|
||||
cls.other_chat = cls.client.call(
|
||||
"POST", "/api/v1/chats", 201, actor=cls.alice,
|
||||
body={"title": "Other", "member_ids": [cls.alice["id"], cls.bob["id"]]}, schema="Chat",
|
||||
)["json"]
|
||||
cls.attachment, cls.content = cls.client.attachment(cls.alice, cls.chat)
|
||||
cls.other_attachment, _ = cls.client.attachment(cls.alice, cls.other_chat)
|
||||
|
||||
def test_message_links_and_replay(self):
|
||||
key = uuid4().hex
|
||||
path = f"/api/v1/chats/{self.chat['id']}/messages"
|
||||
body = {"text": "", "attachment_ids": [self.attachment["id"]]}
|
||||
first = self.client.call("POST", path, 201, body=body, actor=self.bob,
|
||||
headers={"Idempotency-Key": key}, schema="Message")["json"]
|
||||
same = self.client.call("POST", path, 201, body={"attachment_ids": body["attachment_ids"], "text": ""},
|
||||
actor=self.bob, headers={"Idempotency-Key": key}, schema="Message")["json"]
|
||||
self.assertEqual(first, same)
|
||||
self.assertEqual(first["attachment_ids"], [self.attachment["id"]])
|
||||
items = self.client.call("GET", path, actor=self.alice, schema="MessagePage")["json"]["items"]
|
||||
self.assertEqual([item["id"] for item in items].count(first["id"]), 1)
|
||||
self.client.call("POST", path, 409, body={"text": "changed", "attachment_ids": body["attachment_ids"]},
|
||||
actor=self.bob, headers={"Idempotency-Key": key})
|
||||
|
||||
def test_access_and_invalid_links(self):
|
||||
attachment_path = f"/api/v1/attachments/{self.attachment['id']}"
|
||||
metadata = self.client.call("GET", attachment_path, actor=self.bob, schema="Attachment")["json"]
|
||||
self.assertEqual(metadata["id"], self.attachment["id"])
|
||||
self.assertNotIn("object_key", metadata)
|
||||
self.assertNotIn("s3", str(metadata).lower())
|
||||
self.assertEqual(self.client.call("GET", attachment_path + "/content", actor=self.bob)["bytes"], self.content)
|
||||
self.client.call("GET", attachment_path + "/content?variant=thumbnail", 404, actor=self.bob)
|
||||
for suffix in ("", "/content"):
|
||||
self.client.call("GET", attachment_path + suffix, 401)
|
||||
for suffix in ("", "/content"):
|
||||
self.client.call("GET", attachment_path + suffix, 404, actor=self.eve)
|
||||
path = f"/api/v1/chats/{self.chat['id']}/messages"
|
||||
for attachment_id in (str(uuid4()), self.other_attachment["id"]):
|
||||
self.client.call("POST", path, 404, actor=self.alice,
|
||||
body={"text": "", "attachment_ids": [attachment_id]},
|
||||
headers={"Idempotency-Key": uuid4().hex})
|
||||
self.client.call("POST", path, 400, actor=self.alice, body={"text": ""},
|
||||
headers={"Idempotency-Key": uuid4().hex})
|
||||
self.client.call("POST", path, 400, actor=self.alice,
|
||||
body={"text": "", "attachment_ids": [self.attachment["id"]] * 2},
|
||||
headers={"Idempotency-Key": uuid4().hex})
|
||||
|
||||
def test_other_replica_reads_same_bytes(self):
|
||||
path = f"/api/v1/attachments/{self.attachment['id']}/content"
|
||||
seen = set()
|
||||
for _ in range(20):
|
||||
result = self.client.call("GET", path, actor=self.bob)
|
||||
self.assertEqual(result["bytes"], self.content)
|
||||
seen.add(result["headers"]["X-Instance-Id"])
|
||||
if len(seen) >= 2:
|
||||
break
|
||||
self.assertGreaterEqual(len(seen), 2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stop the replica that accepted an upload, then read its bytes elsewhere."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
client = Client(timeout=2)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
original = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
observed = {client.call("GET", "/api/v1/users/me", actor=bob)["headers"]["X-Instance-Id"] for _ in range(30)}
|
||||
if len(observed) != 2:
|
||||
raise Failure("two API replicas were not observed before stop")
|
||||
for target in sorted(observed):
|
||||
for _ in range(10):
|
||||
result = client.call(
|
||||
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", 201,
|
||||
actor=alice, raw=original, headers={"Content-Type": "image/png"}, schema="Attachment",
|
||||
)
|
||||
if result["headers"]["X-Instance-Id"] == target:
|
||||
break
|
||||
else:
|
||||
raise Failure("upload did not reach the selected replica")
|
||||
attachment_id = result["json"]["id"]
|
||||
env = {**os.environ, "TARGET_INSTANCE_ID": target}
|
||||
try:
|
||||
subprocess.run([str(ROOT / "scripts/stop-one.sh")], cwd=ROOT, env=env, check=True)
|
||||
deadline = time.monotonic() + 10
|
||||
while True:
|
||||
try:
|
||||
read = client.call("GET", f"/api/v1/attachments/{attachment_id}/content", actor=bob)
|
||||
if read["headers"]["X-Instance-Id"] == target:
|
||||
raise Failure("stopped replica still answered")
|
||||
if read["bytes"] != original:
|
||||
raise Failure("attachment bytes changed after replica stop")
|
||||
break
|
||||
except Failure:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.2)
|
||||
finally:
|
||||
subprocess.run(["docker", "compose", "--env-file", ".env", "up", "-d", "--wait", "--scale", "api=2"],
|
||||
cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
print(json.dumps({"stopped_upload_replicas": len(observed), "download_on_other_replica": True,
|
||||
"bytes_equal": True}, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user