forked from mtusi2026/mtusi2026lab7
ЛР 7: Безопасность, mTLS и OpenBao
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise upload limits, image validation, attachment ACL, and message links."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import uuid
|
||||
import zlib
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import Client, LAB, arguments, check, run
|
||||
|
||||
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
|
||||
|
||||
|
||||
def oversized_png_header(width, height):
|
||||
def chunk(kind, data):
|
||||
checksum = zlib.crc32(kind + data) & 0xFFFFFFFF
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", checksum)
|
||||
|
||||
image_header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", image_header)
|
||||
+ chunk(b"IDAT", zlib.compress(b"\x00"))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Validate attachment upload rules")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
endpoint = "/api/v1/chats/" + chat["id"] + "/attachments?filename="
|
||||
|
||||
content = (Path(__file__).resolve().parent / "fixtures" / "sample.png").read_bytes()
|
||||
uploaded = client.call(
|
||||
"POST",
|
||||
endpoint + quote("sample.png", safe=""),
|
||||
201 if LAB == 4 else 202,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
if LAB == 4:
|
||||
check(uploaded["status"] == "ready", "uploaded attachment is not ready")
|
||||
check(uploaded["variants"] == [] and uploaded["error_code"] is None,
|
||||
"Lab4 attachment must have no processing variants or error")
|
||||
else:
|
||||
check(uploaded["status"] == "queued", "Lab5 upload must initially be queued")
|
||||
uploaded = client.wait_ready(alice, uploaded)
|
||||
check(len(uploaded["variants"]) == 1
|
||||
and uploaded["variants"][0]["name"] == "thumbnail",
|
||||
"Lab5 attachment must have exactly one thumbnail")
|
||||
check(uploaded["sha256"] == hashlib.sha256(content).hexdigest(),
|
||||
"attachment checksum differs from original")
|
||||
|
||||
downloaded = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + uploaded["id"] + "/content",
|
||||
actor=bob,
|
||||
)
|
||||
check(downloaded["bytes"] == content, "download differs from uploaded bytes")
|
||||
for suffix in ("", "/content"):
|
||||
client.call("GET", "/api/v1/attachments/" + uploaded["id"] + suffix,
|
||||
404, actor=eve)
|
||||
|
||||
def rejected(filename, data, content_type, status):
|
||||
client.call(
|
||||
"POST",
|
||||
endpoint + quote(filename, safe=""),
|
||||
status,
|
||||
actor=alice,
|
||||
raw=data,
|
||||
headers={"Content-Type": content_type},
|
||||
)
|
||||
|
||||
rejected("../sample.png", content, "image/png", 400)
|
||||
rejected("mismatch.jpg", content, "image/jpeg", 415)
|
||||
rejected("corrupt.png", b"\x89PNG\r\n\x1a\nnot-an-image", "image/png", 415)
|
||||
rejected("too-large.png", b"x" * (MAX_UPLOAD_BYTES + 1), "image/png", 413)
|
||||
rejected("too-many-pixels.png", oversized_png_header(20001, 2000),
|
||||
"image/png", 413)
|
||||
|
||||
message = client.message(alice, chat, "", attachments=[uploaded["id"]])["json"]
|
||||
check(message["attachment_ids"] == [uploaded["id"]],
|
||||
"message did not retain attachment_ids")
|
||||
history = client.call(
|
||||
"GET",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages?limit=100",
|
||||
actor=bob,
|
||||
schema="MessagePage",
|
||||
)["json"]["items"]
|
||||
check(any(item["id"] == message["id"] and
|
||||
item["attachment_ids"] == [uploaded["id"]] for item in history),
|
||||
"message history did not return attachment_ids")
|
||||
|
||||
key = uuid.uuid4().hex
|
||||
message_path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
first = client.call(
|
||||
"POST", message_path, 201, actor=alice, body={"text": "semantic replay"},
|
||||
headers={"Idempotency-Key": key}, schema="Message",
|
||||
)["json"]
|
||||
replay = client.call(
|
||||
"POST", message_path, 201, actor=alice, body={"text": "semantic replay", "attachment_ids": []},
|
||||
headers={"Idempotency-Key": key}, schema="Message",
|
||||
)["json"]
|
||||
check(replay == first, "missing attachment_ids and [] should be idempotently equivalent")
|
||||
|
||||
other_chat = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "Different attachment scope", "member_ids": [alice["id"], bob["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + other_chat["id"] + "/messages",
|
||||
404,
|
||||
actor=alice,
|
||||
body={"text": "", "attachment_ids": [uploaded["id"]]},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
print("PASS: PNG upload/download, authorization, file limits, and message attachment links")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify concurrent same-key requests are shared across API replicas."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from threading import Barrier
|
||||
import uuid
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--requests', type=int, default=16)
|
||||
|
||||
args = arguments('Concurrent cross-replica idempotency check', configure)
|
||||
check(2 <= args.requests <= 64, '--requests must be between 2 and 64')
|
||||
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
text = 'concurrent idempotency ' + key
|
||||
barrier = Barrier(args.requests)
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
|
||||
def submit():
|
||||
worker = Client(args.base_url, args.ca_file)
|
||||
barrier.wait(timeout=10)
|
||||
return worker.call(
|
||||
'POST',
|
||||
path,
|
||||
201,
|
||||
actor=alice,
|
||||
body={'text': text},
|
||||
headers={'Idempotency-Key': key},
|
||||
schema='Message',
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.requests) as executor:
|
||||
responses = list(executor.map(lambda _: submit(), range(args.requests)))
|
||||
|
||||
messages = [response['json'] for response in responses]
|
||||
check(all(message == messages[0] for message in messages), 'replay response changed')
|
||||
instances = {response['headers']['X-Instance-Id'] for response in responses}
|
||||
check(len(instances) >= 2, 'concurrent requests did not reach two API replicas')
|
||||
|
||||
history = client.call(
|
||||
'GET',
|
||||
'/api/v1/chats/' + chat['id'] + '/messages?limit=100',
|
||||
actor=bob,
|
||||
schema='MessagePage',
|
||||
)['json']['items']
|
||||
created = [message for message in history if message['text'] == text]
|
||||
check(created == [messages[0]], 'concurrent replay created duplicate messages')
|
||||
print(
|
||||
'PASS: %d concurrent requests across %d API replicas created one message'
|
||||
% (args.requests, len(instances))
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the LB-to-API mTLS positive/negative probe inside the API container."""
|
||||
import subprocess
|
||||
|
||||
|
||||
SCRIPT = r"""
|
||||
import ssl, urllib.request, urllib.error
|
||||
ca = "/certs/internal-ca.crt"
|
||||
try:
|
||||
c = ssl.create_default_context(cafile=ca)
|
||||
urllib.request.urlopen("https://api:8443/health/ready", context=c, timeout=5)
|
||||
raise SystemExit("no-certificate accepted")
|
||||
except (urllib.error.URLError, ssl.SSLError):
|
||||
pass
|
||||
print("PASS:no-cert")
|
||||
try:
|
||||
c = ssl.create_default_context(cafile=ca)
|
||||
c.load_cert_chain("/certs/public-server.crt", "/certs/public-server.key")
|
||||
urllib.request.urlopen("https://api:8443/health/ready", context=c, timeout=5)
|
||||
raise SystemExit("wrong-CA accepted")
|
||||
except (urllib.error.URLError, ssl.SSLError):
|
||||
pass
|
||||
print("PASS:wrong-CA")
|
||||
try:
|
||||
c = ssl.create_default_context(cafile=ca)
|
||||
c.load_cert_chain("/certs/rogue.crt", "/certs/rogue.key")
|
||||
urllib.request.urlopen("https://api:8443/health/ready", context=c, timeout=5)
|
||||
raise SystemExit("wrong-identity accepted")
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code != 401:
|
||||
raise
|
||||
print("PASS:wrong-SAN")
|
||||
c = ssl.create_default_context(cafile=ca)
|
||||
c.load_cert_chain("/certs/lb.crt", "/certs/lb.key")
|
||||
response = urllib.request.urlopen("https://api:8443/health/ready", context=c, timeout=5)
|
||||
print("PASS:LB-identity", response.status)
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker", "compose",
|
||||
"--env-file", ".env",
|
||||
"exec", "-T", "api",
|
||||
"python", "-c", SCRIPT,
|
||||
],
|
||||
check=True,
|
||||
cwd=str(__import__("pathlib").Path(__file__).resolve().parents[1]),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
timeout=30,
|
||||
)
|
||||
print(result.stdout.strip())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate the Lab6 observability endpoints and provisioning."""
|
||||
import json
|
||||
import ssl
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def http_json(url, timeout=10):
|
||||
with urllib.request.urlopen(url, timeout=timeout) as response:
|
||||
return response.status, response.headers, response.read()
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Validate OTel backends and Grafana provisioning")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
client.bootstrap()
|
||||
internal_ca = Path(args.ca_file).resolve().parent / "internal-ca.crt"
|
||||
context = ssl.create_default_context(cafile=str(internal_ca))
|
||||
def https_json(url):
|
||||
with urllib.request.urlopen(url, context=context, timeout=10) as response:
|
||||
return response.status, response.headers, response.read()
|
||||
|
||||
status, _, _ = http_json("http://127.0.0.1:3000/api/health")
|
||||
check(status == 200, "Grafana health endpoint is unavailable")
|
||||
status, _, raw = http_json("http://127.0.0.1:3000/api/datasources")
|
||||
check(status == 200, "Grafana datasource API is unavailable")
|
||||
datasources = {item["name"]: item["uid"] for item in json.loads(raw)}
|
||||
check(set(("Prometheus", "Loki", "Tempo")).issubset(datasources),
|
||||
"Grafana is missing required datasources")
|
||||
|
||||
status, _, _ = https_json("https://127.0.0.1:9090/-/ready")
|
||||
check(status == 200, "Prometheus is not ready")
|
||||
status, _, _ = https_json("https://127.0.0.1:3100/loki/api/v1/status/buildinfo")
|
||||
check(status == 200, "Loki API is not ready")
|
||||
status, _, _ = https_json("https://127.0.0.1:3200/status")
|
||||
check(status == 200, "Tempo search API is not ready")
|
||||
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
status, _, raw = https_json(
|
||||
"https://127.0.0.1:9464/metrics"
|
||||
)
|
||||
text = raw.decode("utf-8", "replace")
|
||||
if status == 200 and "messenger_http_requests" in text:
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise AssertionError("collector did not expose messenger HTTP metrics")
|
||||
|
||||
status, _, raw = http_json(
|
||||
"http://127.0.0.1:3000/api/dashboards/uid/messenger-lab6"
|
||||
)
|
||||
check(status == 200, "Lab6 dashboard was not provisioned")
|
||||
dashboard = json.loads(raw)["dashboard"]
|
||||
check(dashboard["title"] == "Messenger Observability",
|
||||
"unexpected Grafana dashboard title")
|
||||
|
||||
print("PASS: Grafana datasources/dashboard and Prometheus/Loki/Tempo backends are ready")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify bounded API errors during an S3 outage, then restore the service."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import Client, arguments, run
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
command = [
|
||||
"docker", "compose", "--project-directory", str(ROOT),
|
||||
"--env-file", str(ROOT / ".env"), *args,
|
||||
]
|
||||
subprocess.run(
|
||||
command,
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Verify API responses when MinIO is unavailable")
|
||||
client = Client(args.base_url, args.ca_file, timeout=15)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
content = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
|
||||
compose("stop", "s3")
|
||||
try:
|
||||
health = client.call("GET", "/health/ready", 503)
|
||||
if health["elapsed"] > 10:
|
||||
raise AssertionError("S3 readiness failure exceeded 10 seconds")
|
||||
upload = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote("sample.png"),
|
||||
503,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
if upload["elapsed"] > 10:
|
||||
raise AssertionError("S3 upload failure exceeded 10 seconds")
|
||||
finally:
|
||||
compose("start", "s3")
|
||||
compose("up", "-d", "--wait", "s3")
|
||||
client.call("GET", "/health/ready", 200)
|
||||
|
||||
print("PASS: MinIO outage returns bounded 503 errors and recovers")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Focused tests for the required thumbnail transformation."""
|
||||
import io
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from queueing import JOB_QUEUE, publish_event
|
||||
from worker import InvalidImage, parse_event, thumbnail_jpeg
|
||||
|
||||
|
||||
def main():
|
||||
event = parse_event(
|
||||
b'{"schema_version":1,"job_id":"11111111-1111-4111-8111-111111111111",'
|
||||
b'"type":"attachment.process.v1","attachment_id":"22222222-2222-4222-8222-222222222222",'
|
||||
b'"pipeline_version":1,"attempt":1,"created_at":"2026-09-01T12:00:00Z"}'
|
||||
)
|
||||
assert event["attempt"] == 1
|
||||
try:
|
||||
parse_event(b'{"schema_version":1}')
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("incomplete job message should be rejected")
|
||||
|
||||
publisher_event = {
|
||||
"schema_version": 1,
|
||||
"job_id": "11111111-1111-4111-8111-111111111111",
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": "22222222-2222-4222-8222-222222222222",
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
"created_at": "2026-09-01T12:00:00Z",
|
||||
}
|
||||
connection = Mock()
|
||||
connection.is_open = True
|
||||
channel = connection.channel.return_value
|
||||
channel.basic_publish.return_value = True
|
||||
with patch("queueing.pika.BlockingConnection", return_value=connection), \
|
||||
patch("queueing.connection_parameters", return_value=Mock()):
|
||||
publish_event(publisher_event)
|
||||
channel.queue_declare.assert_any_call(
|
||||
queue=JOB_QUEUE,
|
||||
durable=True,
|
||||
arguments={
|
||||
"x-dead-letter-exchange": "attachment.jobs.dlx",
|
||||
"x-dead-letter-routing-key": "attachment.jobs.dead",
|
||||
},
|
||||
)
|
||||
channel.confirm_delivery.assert_called_once()
|
||||
published = channel.basic_publish.call_args.kwargs
|
||||
assert published["mandatory"] is True
|
||||
assert published["properties"].delivery_mode == 2
|
||||
assert set(publisher_event) == {
|
||||
"schema_version", "job_id", "type", "attachment_id",
|
||||
"pipeline_version", "attempt", "created_at",
|
||||
}
|
||||
|
||||
sample = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
thumbnail, width, height = thumbnail_jpeg(sample, "image/png")
|
||||
assert (width, height) == (256, 160), (width, height)
|
||||
with Image.open(io.BytesIO(thumbnail)) as image:
|
||||
assert image.format == "JPEG"
|
||||
assert image.size == (256, 160)
|
||||
|
||||
small = Image.new("RGBA", (30, 20), (255, 0, 0, 0))
|
||||
small_bytes = io.BytesIO()
|
||||
small.save(small_bytes, format="PNG")
|
||||
result, width, height = thumbnail_jpeg(small_bytes.getvalue(), "image/png")
|
||||
assert (width, height) == (30, 20), (width, height)
|
||||
with Image.open(io.BytesIO(result)) as image:
|
||||
assert image.getpixel((0, 0)) == (255, 255, 255)
|
||||
|
||||
try:
|
||||
thumbnail_jpeg(b"not an image", "image/png")
|
||||
except InvalidImage:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("corrupt image should be rejected")
|
||||
print("PASS: 256x256 contain, no-upscale, alpha-on-white, invalid image")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise a queued upload across API/broker restarts and duplicate delivery."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
command = [
|
||||
"docker", "compose", "--project-directory", str(ROOT),
|
||||
"--env-file", str(ROOT / ".env"), *args,
|
||||
]
|
||||
subprocess.run(
|
||||
command,
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=120,
|
||||
)
|
||||
|
||||
|
||||
def republish_completed_job(attachment_id):
|
||||
source = r"""
|
||||
import sys
|
||||
from datetime import timezone
|
||||
import psycopg
|
||||
from app import database_conninfo
|
||||
from queueing import publish_event
|
||||
|
||||
with psycopg.connect(database_conninfo()) as conn:
|
||||
job = conn.execute(
|
||||
"SELECT id, attachment_id, pipeline_version, attempt, created_at "
|
||||
"FROM image_jobs WHERE attachment_id = %s",
|
||||
(sys.argv[1],),
|
||||
).fetchone()
|
||||
if job is None:
|
||||
raise SystemExit("job not found")
|
||||
created_at = job[4].astimezone(timezone.utc)
|
||||
publish_event({
|
||||
"schema_version": 1,
|
||||
"job_id": str(job[0]),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(job[1]),
|
||||
"pipeline_version": job[2],
|
||||
"attempt": job[3],
|
||||
"created_at": created_at.isoformat(timespec="microseconds").replace("+00:00", "Z"),
|
||||
})
|
||||
"""
|
||||
command = [
|
||||
"docker", "compose", "--project-directory", str(ROOT),
|
||||
"--env-file", str(ROOT / ".env"), "run", "--rm", "--no-deps",
|
||||
"api", "python", "-c", source, attachment_id,
|
||||
]
|
||||
subprocess.run(
|
||||
command,
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Verify queued job recovery and idempotent redelivery")
|
||||
client = Client(args.base_url, args.ca_file, timeout=10)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
content = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
upload_path = (
|
||||
"/api/v1/chats/" + chat["id"]
|
||||
+ "/attachments?filename=" + quote("sample.png", safe="")
|
||||
)
|
||||
|
||||
compose("stop", "worker")
|
||||
try:
|
||||
uploaded = client.call(
|
||||
"POST",
|
||||
upload_path,
|
||||
202,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
check(uploaded["status"] == "queued", "stopped worker upload was not queued")
|
||||
client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + uploaded["id"] + "/content",
|
||||
409,
|
||||
actor=bob,
|
||||
)
|
||||
linked = client.message(
|
||||
alice, chat, "", attachments=[uploaded["id"]]
|
||||
)["json"]
|
||||
check(linked["attachment_ids"] == [uploaded["id"]],
|
||||
"queued attachment could not be linked to a message")
|
||||
|
||||
compose("restart", "db", "s3", "broker")
|
||||
compose("up", "-d", "--wait", "db", "s3", "broker")
|
||||
compose("run", "--rm", "s3-init")
|
||||
compose("restart", "api")
|
||||
compose("up", "-d", "--wait", "--scale", "api=2", "api", "lb")
|
||||
compose("start", "worker")
|
||||
|
||||
ready = client.wait_ready(alice, uploaded, wait_seconds=60)
|
||||
check(ready["status"] == "ready", "queued work did not recover to ready")
|
||||
original = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + uploaded["id"] + "/content",
|
||||
actor=bob,
|
||||
)
|
||||
check(original["bytes"] == content, "recovered original bytes changed")
|
||||
thumbnail = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + uploaded["id"] + "/content?variant=thumbnail",
|
||||
actor=bob,
|
||||
)
|
||||
variant = ready["variants"][0]
|
||||
check(
|
||||
hashlib.sha256(thumbnail["bytes"]).hexdigest() == variant["sha256"],
|
||||
"thumbnail changed after recovery",
|
||||
)
|
||||
|
||||
republish_completed_job(uploaded["id"])
|
||||
time.sleep(1)
|
||||
after_duplicate = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + uploaded["id"],
|
||||
actor=bob,
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
check(after_duplicate["status"] == "ready",
|
||||
"duplicate delivery changed a completed attachment state")
|
||||
check(len(after_duplicate["variants"]) == 1,
|
||||
"duplicate delivery created duplicate variants")
|
||||
print("PASS: queued upload survived API/DB/S3/broker restart; duplicate was idempotent")
|
||||
finally:
|
||||
compose("up", "-d", "--scale", "api=2", "api", "worker", "lb")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user