lab4 for lab5

This commit is contained in:
Матвей
2026-10-26 10:05:24 +03:00
parent 276dbdad8a
commit 3b67201e5e
40 changed files with 3522 additions and 0 deletions
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""Explicit local Docker tests: private bucket, uploader failover, S3 outage."""
import json
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, arguments, check, run
def compose(*args, input=None):
return subprocess.check_output(['docker', 'compose', *args], cwd=ROOT, input=input,
text=True, stderr=subprocess.DEVNULL)
def wait_ready(c):
deadline = time.monotonic() + 90
while True:
try:
c.call('GET', '/health/ready', schema='Health')
return
except Failure:
check(time.monotonic() < deadline, 'stack did not recover')
time.sleep(1)
def main():
def configure(parser):
parser.add_argument('--mode', required=True, choices=['private', 'failover', 's3-outage'])
args = arguments(__doc__, configure)
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
uploaded = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png',
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
att = uploaded['json']
content_path = '/api/v1/attachments/' + att['id'] + '/content'
if args.mode == 'private':
script = '''import sys, urllib.request, urllib.error
url = "http://s3:8333/messenger-attachments/originals/" + sys.stdin.read().strip()
try:
urllib.request.urlopen(url, timeout=5)
except urllib.error.HTTPError as error:
assert error.code == 403, error.code
print("PASS: anonymous S3 GET returns 403 for an existing object")
else:
raise AssertionError("private object leaked")
'''
print(compose('exec', '-T', 'api-a', '/app/.venv/bin/python', '-c', script, input=att['id']).strip())
elif args.mode == 'failover':
target = uploaded['headers']['X-Instance-Id']
service = None
for candidate in ('api-a', 'api-b'):
container = compose('ps', '-q', candidate).strip()
hostname = subprocess.check_output(['docker', 'inspect', '--format', '{{.Config.Hostname}}', container], text=True).strip()
if hostname == target:
service = candidate
check(service is not None, 'uploading replica not found')
try:
compose('stop', service)
deadline = time.monotonic() + 15
while True:
try:
download = c.call('GET', content_path, actor=bob)
break
except Failure:
check(time.monotonic() < deadline, 'download did not recover')
time.sleep(0.5)
check(download['headers']['X-Instance-Id'] != target, 'download used stopped uploader')
check(download['bytes'] == data, 'original changed after stopping uploader')
print('PASS: uploaded via ' + service + '; stopped that container; original downloaded through another replica')
finally:
compose('start', service)
wait_ready(c)
else:
try:
compose('stop', 's3')
# Direct API request inside the network: LB excludes unready backends.
script = '''import json, sys, urllib.request, urllib.error
payload = json.load(sys.stdin)
for method, path, body, headers in [
("GET", "/health/ready", None, {}),
("GET", payload["path"], None, {"Authorization": "Bearer " + payload["token"]}),
("POST", payload["upload_path"], bytes.fromhex(payload["bytes"]),
{"Authorization": "Bearer " + payload["token"], "Content-Type": "image/png"}),
]:
req = urllib.request.Request("http://localhost:8080" + path, data=body, headers=headers, method=method)
try:
urllib.request.urlopen(req, timeout=15)
except urllib.error.HTTPError as error:
assert error.code == 503, error.code
document = json.load(error)
assert document["error"]["code"] == "unavailable"
assert document["error"]["request_id"] == error.headers["X-Request-Id"]
else:
raise AssertionError("S3 outage was not reported")
assert urllib.request.urlopen("http://localhost:8080/health/live").status == 200
print("PASS: S3 outage gives 503 for readiness, download and upload; liveness stays 200")
'''
payload = {'path': content_path, 'token': bob['token'], 'bytes': data.hex(),
'upload_path': '/api/v1/chats/' + chat['id'] + '/attachments?filename=outage.png'}
print(compose('exec', '-T', 'api-a', '/app/.venv/bin/python', '-c', script,
input=json.dumps(payload)).strip())
finally:
compose('start', 's3')
# HeadBucket/read recovery alone does not prove the write path is ready.
# Use the same write-probing bootstrap as the documented restart hook.
compose('run', '--rm', '--no-deps', 's3-init')
wait_ready(c)
check(c.call('GET', content_path, actor=bob)['bytes'] == data, 'original lost after S3 outage')
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=after-recovery.png',
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
print('PASS: original available and new upload accepted after S3 restart/bootstrap')
if __name__ == '__main__':
run(main)
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""Attachment contract checks against the running lab4 stack."""
import hashlib
import http.client
from io import BytesIO
from pathlib import Path
import struct
import sys
import uuid
import zlib
from urllib.parse import quote, urlsplit
from PIL import Image
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, arguments, check, run
def main():
args = arguments(__doc__)
c = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
png = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
def upload(data, mime='image/png', filename='photo.png', status=201, actor=alice):
return c.call('POST', path + quote(filename, safe=''), status, actor=actor, raw=data,
headers={'Content-Type': mime}, schema='Attachment' if status == 201 else None)
for fmt, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]:
buf = BytesIO()
Image.new('RGB', (32, 20), 'blue').save(buf, fmt)
data = buf.getvalue()
att = upload(data, mime)['json']
check(att['variants'] == [] and att['status'] == 'ready', 'wrong attachment state')
check(att['sha256'] == hashlib.sha256(data).hexdigest(), 'wrong checksum')
content_path = '/api/v1/attachments/' + att['id']
check(c.call('GET', content_path, actor=bob, schema='Attachment')['json'] == att,
'metadata changed')
check(c.call('GET', content_path + '/content', actor=bob)['bytes'] == data, 'bytes changed')
c.call('GET', content_path, 404, actor=eve)
c.call('GET', content_path + '/content', 404, actor=eve)
c.call('GET', content_path + '/content', 401)
c.call('GET', content_path + '/content?variant=thumbnail', 404, actor=bob)
message = c.message(bob, chat, '', attachments=[att['id']])['json']
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages',
actor=alice, schema='MessagePage')['json']['items']
check(message in history, 'attachment message missing in history')
print('PASS: PNG/JPEG originals, metadata, attachment-only messages and ACL')
for name in ('../x.png', 'x/y.png', 'x\\y.png', 'x\x00.png', 'x\n.png', 'x\x7f.png', ' ', 'x' * 256):
upload(png, filename=name, status=400)
upload(png, mime='image/jpeg', status=415)
upload(b'not an image', status=415)
upload(png[:30], status=415)
upload(png, mime='application/octet-stream', status=415)
upload(png, status=404, actor=eve)
upload(b'x' * (10485760 + 1), status=413)
# Valid PNG header with an oversized canvas: reject before attempting pixel decoding.
def chunk(kind, data):
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
huge = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 8001, 5000, 8, 2, 0, 0, 0))
huge += chunk(b'IDAT', zlib.compress(b'')) + chunk(b'IEND', b'')
upload(huge, status=413)
# No Content-Length: limits must also work for chunked requests.
url = urlsplit(c.base)
connection = http.client.HTTPConnection(url.hostname, url.port, timeout=30)
connection.request('POST', path + 'chunked.png', body=iter([b'x' * 65536] * 161),
headers={'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'},
encode_chunked=True)
response = connection.getresponse()
check(response.status == 413, 'chunked upload bypassed byte limit')
response.read()
connection.close()
print('PASS: filename, MIME, malformed image, byte/pixel and chunked limits')
att = upload(png)['json']
other_chat = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json']
for target, ids, code in ((chat, [str(uuid.uuid4())], 404),
(other_chat, [att['id']], 404),
(chat, [att['id'], att['id']], 400)):
c.call('POST', '/api/v1/chats/' + target['id'] + '/messages', code, actor=alice,
body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
key = uuid.uuid4().hex
first = c.message(alice, chat, 'same', key=key)['json']
check(c.message(alice, chat, 'same', key=key, attachments=[])['json'] == first,
'omitted and empty attachment_ids differ')
key = uuid.uuid4().hex
first = c.message(alice, chat, '', key=key, attachments=[att['id']])['json']
check(c.message(alice, chat, '', key=key, attachments=[att['id']])['json'] == first, 'replay differs')
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
body={'text': 'changed', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': key})
print('PASS: attachment scope, duplicates and idempotency normalization')
# Exact limits are accepted; original bytes (including PNG trailing data) survive.
exact = png + b'\0' * (10485760 - len(png))
att = upload(exact)['json']
check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == exact,
'10 MiB original changed')
buf = BytesIO()
Image.new('RGB', (8000, 5000)).save(buf, 'PNG')
att = upload(buf.getvalue())['json']
check(att['size_bytes'] == len(buf.getvalue()), '40M pixel upload failed')
print('PASS: inclusive 10 MiB and 40 million pixel boundaries')
if __name__ == '__main__':
run(main)
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Один ключ одновременно через LB создаёт ровно одно сообщение."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import sys
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, check, run # noqa: E402
def main() -> None:
client = Client()
alice, _bob, _eve, chat = client.bootstrap()
key = uuid.uuid4().hex
text = "concurrent idempotency " + key
def send(_number: int):
return Client().message(alice, chat, text, key=key)["json"]
with ThreadPoolExecutor(max_workers=16) as pool:
replies = list(pool.map(send, range(16)))
check(all(reply == replies[0] for reply in replies), "replays returned different messages")
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
history = client.call("GET", path, actor=alice, schema="MessagePage")["json"]["items"]
check(sum(message["id"] == replies[0]["id"] for message in history) == 1, "concurrent retries created duplicates")
print("PASS: concurrent idempotency through load balancer")
if __name__ == "__main__":
run(main)
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""Запрет БД только для api-a через pg_hba; восстановление в finally."""
import ipaddress
import json
from pathlib import Path
import subprocess
import sys
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check, run
def compose(*args):
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True).strip()
def sql(statement):
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d",
"messenger", "-v", "ON_ERROR_STOP=1", "-Atc", statement)
def ready(service):
code = """import urllib.request, urllib.error
try:
print(urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=7).status)
except urllib.error.HTTPError as error:
print(error.code)
"""
return compose("exec", "-T", service, "/app/.venv/bin/python", "-c", code)
def main():
client = Client()
container = json.loads(subprocess.check_output(
["docker", "inspect", compose("ps", "-q", "api-a")], text=True))[0]
addresses = list(container["NetworkSettings"]["Networks"].values())
check(len(addresses) == 1, "test expects one API network")
address = str(ipaddress.IPv4Address(addresses[0]["IPAddress"]))
bad_id = container["Config"]["Hostname"]
before = {client.call("GET", "/health/live")["headers"]["X-Instance-Id"] for _ in range(40)}
check(len(before) == 2 and bad_id in before, "both API replicas must be reachable")
check(ready("api-a") == ready("api-b") == "200", "both APIs must be ready")
# Сохраняем исходный pg_hba; чужую оставшуюся резервную копию не перезаписываем.
compose("exec", "-T", "postgres", "sh", "-ec",
'test ! -e "$PGDATA/pg_hba.conf.readiness-backup"; '
'cp -p "$PGDATA/pg_hba.conf" "$PGDATA/pg_hba.conf.readiness-backup"')
try:
compose("exec", "-T", "postgres", "sh", "-ec",
'{ printf "host all all %s/32 reject\\n" "$1"; '
'cat "$PGDATA/pg_hba.conf.readiness-backup"; } > "$PGDATA/pg_hba.conf"',
"sh", address)
sql("SELECT pg_reload_conf()")
time.sleep(0.5)
sql(f"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE client_addr = '{address}'::inet")
check(ready("api-a") == "503", "api-a must be unready")
check(ready("api-b") == "200", "api-b must remain ready")
# 2s interval + 2s check timeout, с запасом на планировщик Docker Desktop.
time.sleep(6)
for _ in range(40):
result = client.call("GET", "/health/live", 200)
check(result["headers"]["X-Instance-Id"] != bad_id, "LB selected unready api-a")
for _ in range(20):
result = client.call("POST", "/api/v1/users", 201, body={
"username": "r_" + uuid.uuid4().hex[:16],
"display_name": "Readiness regression",
"password": "Test-password-" + uuid.uuid4().hex,
}, schema="User")
check(result["headers"]["X-Instance-Id"] != bad_id, "registration reached api-a")
print("PASS: api-a ready=503, api-b ready=200; 40/40 live and 20/20 registrations use api-b")
finally:
compose("exec", "-T", "postgres", "sh", "-ec",
'mv "$PGDATA/pg_hba.conf.readiness-backup" "$PGDATA/pg_hba.conf"')
sql("SELECT pg_reload_conf()")
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
observed = {client.call("GET", "/health/live")["headers"]["X-Instance-Id"] for _ in range(10)}
if observed == before:
check(ready("api-a") == "200", "restored api-a must be ready")
print("PASS: database access restored; both API replicas returned to LB")
return
time.sleep(0.5)
raise AssertionError("api-a did not return to LB")
if __name__ == "__main__":
run(main)
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Проверка 503 readiness при остановленном PostgreSQL."""
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, run # noqa: E402
def main() -> None:
Client().call("GET", "/health/ready", 503)
print("PASS: readiness rejects unavailable PostgreSQL")
if __name__ == "__main__":
run(main)
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Inject S3/DB disagreement and prove dry-run, grace period and safe repair."""
import json
import base64
from pathlib import Path
import subprocess
import sys
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, arguments, check, run
def compose(*args, input=None, env=None) -> str:
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True,
input=input, env=env)
def reconcile(*args) -> dict:
output = compose("--profile", "maintenance", "run", "--rm", "--no-deps", "reconcile", *args)
return json.loads(next(line for line in reversed(output.splitlines()) if line.startswith("{")))
def s3_code(action: str, key: str, data: bytes | None = None) -> None:
code = """from src.storage.s3 import S3Settings, S3Store
import base64, json, sys
s3 = S3Store(S3Settings.load())
payload = json.load(sys.stdin)
key = payload['key']
try:
if sys.argv[1] == 'put':
s3.client.put_object(Bucket=s3.settings.bucket, Key=key,
Body=base64.b64decode(payload.get('data', 'b3JwaGFu')))
else:
s3.client.delete_object(Bucket=s3.settings.bucket, Key=key)
finally:
s3.client.close()
"""
payload = {"key": key}
if data is not None:
payload["data"] = base64.b64encode(data).decode()
compose("run", "--rm", "--no-deps", "s3-init", "/app/.venv/bin/python", "-c", code, action,
input=json.dumps(payload))
def wait_ready(client: Client, env=None) -> None:
subprocess.run(["docker", "compose", "up", "-d", "--wait", "--no-deps", "api-a"],
cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL)
deadline = time.monotonic() + 15
while True:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
check(time.monotonic() < deadline, "stack did not recover")
time.sleep(.5)
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, _eve, chat = client.bootstrap()
image = (ROOT / "tests/fixtures/sample.png").read_bytes()
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename="
def upload(name, expected=201):
return client.call("POST", path + name, expected, actor=alice, raw=image,
headers={"Content-Type": "image/png"},
schema="Attachment" if expected == 201 else None)
# A reference object must survive an apply sweep, even with zero grace.
protected = upload("protected.png")["json"]
message = client.message(alice, chat, "protected", attachments=[protected["id"]])["json"]
orphan = "originals/test-orphan-" + uuid.uuid4().hex
s3_code("put", orphan)
report = reconcile("--grace-seconds", "3600")
check(orphan in report["fresh_unreferenced"], "fresh orphan missing from dry-run")
check(not report["deleted"], "dry-run deleted an object")
report = reconcile("--apply", "--grace-seconds", "3600", "--object-key", orphan)
check(orphan in report["fresh_unreferenced"] and not report["deleted"], "grace period ignored")
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", orphan)
check(report["deleted"] == [orphan], "aged orphan was not deleted safely")
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", orphan)
check(orphan not in report["deleted"] and orphan not in report["orphan_candidates"],
"second repair run was not idempotent")
check(client.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=bob)["bytes"] == image,
"reconciler deleted a referenced object")
# This models loss after metadata has committed: report it, do not delete metadata.
missing = upload("missing.png")["json"]
missing_key = "originals/" + missing["id"]
s3_code("delete", missing_key)
try:
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", missing_key)
expected = {"attachment_id": missing["id"], "object_key": missing_key}
check(expected in report["missing_objects"], "missing metadata/object pair not reported")
client.call("GET", "/api/v1/attachments/" + missing["id"], actor=bob, schema="Attachment")
client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", 503, actor=bob)
finally:
s3_code("put", missing_key, image)
check(client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", actor=bob)["bytes"] == image,
"test object was not restored")
report = reconcile("--grace-seconds", "0")
check(expected not in report["missing_objects"], "restored object remained missing on second scan")
print("PASS: S3-side missing object, dry-run, grace period and idempotent orphan repair", flush=True)
# Inject a process-equivalent failure after PUT directly into the configured
# replica. The public load balancer may correctly select the healthy peer,
# which would not exercise this boundary.
environment = dict(__import__("os").environ, UPLOAD_FAULT_AFTER_S3_PUT="1")
before_fault = set(reconcile("--grace-seconds", "0")["orphan_candidates"])
try:
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "api-a"],
cwd=ROOT, env=environment, check=True, stdout=subprocess.DEVNULL)
wait_ready(client, environment)
fault = """import base64, json, sys, urllib.error, urllib.request
payload = json.load(sys.stdin)
request = urllib.request.Request('http://127.0.0.1:8080/api/v1/chats/' + payload['chat_id'] +
'/attachments?filename=fault-after-put.png', data=base64.b64decode(payload['image']),
method='POST', headers={'Authorization': 'Bearer ' + payload['token'], 'Content-Type': 'image/png'})
try:
urllib.request.urlopen(request, timeout=30)
except urllib.error.HTTPError as error:
assert error.code == 503, error.code
assert json.load(error)['error']['code'] == 'unavailable'
else:
raise AssertionError('fault injection unexpectedly returned success')
"""
compose("exec", "-T", "api-a", "/app/.venv/bin/python", "-c", fault,
input=json.dumps({"chat_id": chat["id"], "token": alice["token"],
"image": base64.b64encode(image).decode()}))
report = reconcile("--grace-seconds", "0")
injected = sorted(set(report["orphan_candidates"]) - before_fault)
check(len(injected) == 1, "fault must create exactly one new orphan; run without other writers")
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", injected[0])
check(set(injected).issubset(report["deleted"]), "reconciler did not clean injected orphan")
history = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, schema="MessagePage")["json"]
check(message in history["items"], "message reference was lost")
check(client.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=bob)["bytes"] == image,
"used original was lost")
print("PASS: injected pre-INSERT failure repaired; message and used original survive", flush=True)
finally:
environment["UPLOAD_FAULT_AFTER_S3_PUT"] = "0"
subprocess.run(["docker", "compose", "up", "-d", "--wait", "--force-recreate", "--no-deps", "api-a"],
cwd=ROOT, env=environment, check=True, stdout=subprocess.DEVNULL)
if __name__ == "__main__":
run(main)
+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env python3
"""Real database rejection, concurrent commit, interrupted upload and pagination."""
import base64
import json
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, run
PROBE = r'''
import asyncio, base64, hashlib, http.client, json, sys, urllib.request, urllib.error
from types import SimpleNamespace
from uuid import UUID, uuid4
from src.config import load_settings
from src.storage.postgres import PostgresStore
from src.storage.s3 import S3Store, S3Settings
from src.reconcile import run as reconcile, scan
payload = json.load(sys.stdin)
image = base64.b64decode(payload['image'])
chat_id, user_id = UUID(payload['chat_id']), UUID(payload['user_id'])
def upload(filename):
req = urllib.request.Request('http://api-a:8080/api/v1/chats/' + str(chat_id) +
'/attachments?filename=' + filename, data=image, method='POST',
headers={'Authorization': 'Bearer ' + payload['token'], 'Content-Type': 'image/png'})
try:
with urllib.request.urlopen(req, timeout=30) as response:
return response.status, json.load(response)
except urllib.error.HTTPError as error:
return error.code, json.load(error)
async def main():
db = PostgresStore(load_settings().database_url)
s3 = S3Store(S3Settings.load())
await db.connect()
def args(key):
return SimpleNamespace(apply=True, grace_seconds=0, object_key=[key])
try:
# A failed metadata inventory must not authorize any S3 deletion.
key = 'originals/audit-inventory-' + uuid4().hex
await s3.call('put_object', Bucket=s3.settings.bucket, Key=key, Body=image)
class BrokenInventory:
async def attachment_keys(self):
# Real SQL failure, not an empty inventory on error.
return await db.pool.fetch('SELECT * FROM audit_missing_table_' + uuid4().hex)
try:
async with db.attachment_transaction(maintenance=True):
try:
await scan(args(key), BrokenInventory(), s3)
except Exception:
pass
else:
raise AssertionError('failed inventory did not abort')
assert key in await s3.list('originals/')
finally:
await s3.delete(key)
print('PASS: failed PostgreSQL inventory aborts apply without deleting the orphan', flush=True)
# An actual PostgreSQL trigger rejects only this test chat's INSERT.
suffix = uuid4().hex
name = 'audit_reject_' + suffix
before = await s3.list('originals/')
await db.pool.execute(f"""CREATE FUNCTION {name}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN IF NEW.chat_id = '{chat_id}'::uuid THEN
RAISE EXCEPTION 'synthetic audit rejection' USING ERRCODE = '23514';
END IF; RETURN NEW; END $$""")
try:
await db.pool.execute(f'CREATE TRIGGER {name} BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION {name}()')
status, body = await asyncio.to_thread(upload, 'db-failure.png')
assert status == 503 and body['error']['code'] == 'unavailable', (status, body)
assert await db.pool.fetchval('SELECT count(*) FROM attachments WHERE chat_id=$1', chat_id) == 0
finally:
await db.pool.execute(f'DROP TRIGGER IF EXISTS {name} ON attachments')
await db.pool.execute(f'DROP FUNCTION {name}()')
created = set(await s3.list('originals/')) - set(before)
assert len(created) == 1, created
key = created.pop()
report = await reconcile(SimpleNamespace(apply=False, grace_seconds=0, object_key=[key]))
assert key in report['orphan_candidates'] and not report['deleted']
assert (await reconcile(args(key)))['deleted'] == [key]
assert not (await reconcile(args(key)))['deleted']
print('PASS: actual PostgreSQL INSERT rejection -> 503, dry-run detection, scoped repair, repeat no-op', flush=True)
# Writer holds a shared lock after PUT; cleanup must wait for COMMIT.
identifier = uuid4()
key = 'originals/' + str(identifier)
async with db.attachment_transaction() as connection:
await s3.call('put_object', Bucket=s3.settings.bucket, Key=key, Body=image)
sweep = asyncio.create_task(reconcile(args(key)))
for _ in range(40):
waiting = await db.pool.fetchval("SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND classid=41004 AND objid=1 AND NOT granted")
if waiting:
break
await asyncio.sleep(.05)
assert waiting and not sweep.done(), 'maintenance failed to wait for active writer'
await db.create_attachment(identifier, chat_id, user_id, 'concurrent.png', 'image/png',
len(image), hashlib.sha256(image).hexdigest(), key, connection=connection)
report = await sweep
assert key not in report['deleted'] and key not in report['orphan_candidates']
row = await db.attachment_for_member(identifier, user_id)
assert await s3.download(row) == image
print('PASS: apply with zero grace waits for in-flight PUT/COMMIT; committed original survives', flush=True)
# Abrupt client close before all bytes arrive must not persist a file.
before = await s3.list('originals/')
rows = await db.attachment_keys()
def interrupt():
conn = http.client.HTTPConnection('api-a', 8080, timeout=10)
conn.putrequest('POST', '/api/v1/chats/' + str(chat_id) + '/attachments?filename=interrupted.png')
conn.putheader('Authorization', 'Bearer ' + payload['token'])
conn.putheader('Content-Type', 'image/png')
conn.putheader('Content-Length', str(len(image) + 100000))
conn.endheaders()
conn.send(image[:32])
conn.close()
await asyncio.to_thread(interrupt)
await asyncio.sleep(1)
assert await db.attachment_keys() == rows
assert await s3.list('originals/') == before
status, body = await asyncio.to_thread(upload, 'after-disconnect.png')
assert status == 201, (status, body)
print('PASS: interrupted upload leaves no metadata/object and next upload succeeds', flush=True)
# Exercise pagination on real S3 without adding thousands of fixtures.
original_call = s3.call
async def small_pages(method, **kwargs):
if method == 'list_objects_v2':
kwargs['MaxKeys'] = 7
return await original_call(method, **kwargs)
expected = await s3.list('originals/')
s3.call = small_pages
actual, pages = await s3.list_with_pages('originals/')
assert actual == expected and pages > 1
print(f'PASS: S3 pagination: {len(actual)} keys across {pages} pages, no missing/duplicate keys', flush=True)
finally:
s3.client.close()
await db.close()
asyncio.run(main())
'''
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file, timeout=30)
alice, _, _, chat = client.bootstrap()
payload = {"chat_id": chat["id"], "user_id": alice["id"], "token": alice["token"],
"image": base64.b64encode((ROOT / "tests/fixtures/sample.png").read_bytes()).decode()}
subprocess.run(["docker", "compose", "--profile", "maintenance", "run", "--rm", "--no-deps",
"--entrypoint", "/app/.venv/bin/python", "reconcile", "-c", PROBE],
cwd=ROOT, input=json.dumps(payload), text=True, check=True)
if __name__ == "__main__":
run(main)
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
"""Measure repeatable reconciler inventory cost for two controlled S3 sizes."""
import json
from pathlib import Path
import statistics
import subprocess
import sys
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import arguments, check, run
def compose(*args, input=None) -> str:
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True, input=input)
def reconcile() -> dict:
output = compose("--profile", "maintenance", "run", "--rm", "--no-deps", "reconcile",
"--grace-seconds", "3600")
return json.loads(next(line for line in reversed(output.splitlines()) if line.startswith("{")))
def mutate(action: str, keys: list[str]) -> None:
code = """from src.storage.s3 import S3Settings, S3Store
import json, sys
s3 = S3Store(S3Settings.load())
try:
for key in json.load(sys.stdin):
if sys.argv[1] == 'put':
s3.client.put_object(Bucket=s3.settings.bucket, Key=key, Body=b'track-2-benchmark')
else:
s3.client.delete_object(Bucket=s3.settings.bucket, Key=key)
finally:
s3.client.close()
"""
compose("run", "--rm", "--no-deps", "s3-init", "/app/.venv/bin/python", "-c", code, action,
input=json.dumps(keys))
def main() -> None:
arguments(__doc__) # Keeps the common --base-url/--ca-file command interface.
results = []
for requested in (32, 128):
prefix = f"originals/track2-benchmark-{uuid.uuid4().hex}-"
keys = [prefix + str(index) for index in range(requested)]
try:
mutate("put", keys)
reports = [reconcile() for _ in range(3)]
for report in reports:
check(set(keys).issubset(report["fresh_unreferenced"]),
"benchmark objects were not included in the inventory")
check(not set(keys) & set(report["orphan_candidates"]),
"grace period classified fresh benchmark objects as deletable")
seconds = [report["scan_metrics"]["total_seconds"] for report in reports]
results.append({
"added_unreferenced_objects": requested,
"runs": 3,
"s3_objects_scanned": reports[-1]["s3_objects"],
"metadata_rows_scanned": reports[-1]["metadata_rows"],
"s3_list_pages": reports[-1]["scan_metrics"]["s3_list_pages"],
"seconds": seconds,
"median_seconds": round(statistics.median(seconds), 6),
})
finally:
mutate("delete", keys)
print(json.dumps({"method": "three dry-run inventories per controlled size", "results": results},
sort_keys=True))
print("PASS: reconciler cost measured for 32 and 128 added S3 objects; fixtures removed")
if __name__ == "__main__":
run(main)
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Регрессии ревью: не-ASCII Bearer и невалидная кодировка JSON через LB."""
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, arguments, check, run
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file)
for path in ("/api/v1/users/me", "/api/v1/auth/sessions/current"):
method = "DELETE" if path.endswith("/current") else "GET"
result = client.call(method, path, 401,
headers={"Authorization": "Bearer é"}, schema="Error")
check(result["headers"].get("WWW-Authenticate", "").startswith("Bearer"),
"missing Bearer challenge")
check(result["json"]["error"]["code"] == "unauthorized", "wrong error code")
check(result["json"]["error"]["request_id"] == result["headers"]["X-Request-Id"],
"request IDs differ")
for raw in (b"\xff", b"{", b'{"username":'):
result = client.call("POST", "/api/v1/users", 400, raw=raw,
headers={"Content-Type": "application/json"}, schema="Error")
check(result["json"]["error"]["code"] == "invalid_request", "wrong JSON error code")
check(result["json"]["error"]["request_id"] == result["headers"]["X-Request-Id"],
"request IDs differ")
print("PASS: non-ASCII Bearer returns 401/challenge; malformed JSON returns contract Error/400")
if __name__ == "__main__":
run(main)
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env python3
"""Prove that the API identity is bucket-scoped and lacks admin operations."""
import subprocess
from pathlib import Path
import sys
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run
def compose(*args, input=None):
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True,
input=input, stderr=subprocess.DEVNULL)
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file)
alice, _bob, _eve, chat = client.bootstrap()
data = (ROOT / "tests/fixtures/sample.png").read_bytes()
client.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=permission.png", 201,
actor=alice, raw=data, headers={"Content-Type": "image/png"}, schema="Attachment")
bucket = "permission-probe-" + uuid.uuid4().hex
code = """from botocore.exceptions import ClientError
from src.storage.s3 import S3Settings, S3Store
import sys
s3 = S3Store(S3Settings.load())
try:
try:
s3.client.create_bucket(Bucket=sys.stdin.read().strip())
except ClientError as error:
assert error.response['Error']['Code'] in {'AccessDenied', 'Unauthorized'}, error.response
else:
raise AssertionError('API S3 identity unexpectedly has admin bucket creation')
finally:
s3.client.close()
"""
compose("exec", "-T", "api-a", "/app/.venv/bin/python", "-c", code, input=bucket)
admin = """from src.storage.s3 import S3Settings, S3Store
import sys
s3 = S3Store(S3Settings.load())
try:
s3.client.list_buckets()
finally:
s3.client.close()
"""
compose("run", "--rm", "--no-deps", "s3-init", "/app/.venv/bin/python", "-c", admin)
print("PASS: API identity cannot create buckets; maintenance identity has separate admin access")
if __name__ == "__main__":
run(main)
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
"""Проверка expiry; запускается при SESSION_TTL_SECONDS=2."""
from pathlib import Path
import sys
import time
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, check, run # noqa: E402
def main() -> None:
client = Client()
actor = client.user("expiry")
time.sleep(3)
client.call("GET", "/api/v1/users/me", 401, actor=actor)
print("PASS: expired Bearer session was rejected")
if __name__ == "__main__":
run(main)
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
"""Ten concurrent bounded uploads, with API-container peak memory sampling."""
from concurrent.futures import ThreadPoolExecutor
import json
import http.client
from pathlib import Path
import subprocess
import sys
import threading
import time
from urllib.parse import quote
from urllib.parse import urlsplit
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run
def api_memory() -> dict[str, int]:
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api-a", "api-b"], cwd=ROOT, text=True).split()
return {container[:12]: int(subprocess.check_output(
["docker", "exec", container, "cat", "/sys/fs/cgroup/memory.current"], text=True))
for container in ids}
def main():
def configure(parser):
parser.add_argument("--output", default="evidence/upload-memory.json")
parser.add_argument("--size-mib", type=int, default=5)
args = arguments(__doc__, configure)
check(1 <= args.size_mib <= 10, "--size-mib must be 1..10")
client = Client(args.base_url, args.ca_file, timeout=60)
alice, _bob, _eve, chat = client.bootstrap()
seed = (ROOT / "tests/fixtures/sample.png").read_bytes()
payload = seed + b"\0" * (args.size_mib * 1024 * 1024 - len(seed))
baseline, peak, samples, stop = api_memory(), {}, [], threading.Event()
check(len(baseline) == 2, "memory experiment requires two running APIs")
sampling_errors = []
timestamps = []
barrier = threading.Barrier(10)
def sampler():
while not stop.is_set():
try:
values = api_memory()
check(set(values) == set(baseline), "API containers changed during measurement")
except Exception as error:
sampling_errors.append(type(error).__name__)
return
timestamps.append(time.monotonic())
samples.append(values)
for name, value in values.items():
peak[name] = max(peak.get(name, 0), value)
time.sleep(.1)
def upload(index):
barrier.wait(timeout=15)
parsed = urlsplit(client.base)
connection = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=60)
def chunks():
for offset in range(0, len(payload), 512 * 1024):
yield payload[offset:offset + 512 * 1024]
# Keep all ten client streams open long enough for multiple memory samples.
time.sleep(.5)
connection.request("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote(f"load-{index}.png"),
body=chunks(), encode_chunked=True,
headers={"Authorization": "Bearer " + alice["token"], "Content-Type": "image/png"})
response = connection.getresponse()
body = response.read()
connection.close()
check(response.status == 201, "upload %s returned %s: %s" % (index, response.status, body[:200]))
return json.loads(body)
started = time.monotonic()
thread = threading.Thread(target=sampler, daemon=True)
thread.start()
try:
with ThreadPoolExecutor(max_workers=10) as pool:
attachments = list(pool.map(upload, range(10)))
finally:
stop.set()
thread.join(timeout=5)
elapsed = time.monotonic() - started
check(len({item["id"] for item in attachments}) == 10, "uploads were not distinct")
check(not sampling_errors and len(samples) >= 2 and not thread.is_alive(),
"memory sampler failed or did not collect enough samples: " + repr(sampling_errors))
report = {
"uploads": 10, "file_bytes": len(payload), "concurrency": 10,
"api_upload_concurrency_limit": 1, "elapsed_seconds": round(elapsed, 3),
"baseline_memory_bytes": baseline, "peak_memory_bytes": peak,
"peak_growth_bytes": {name: peak.get(name, 0) - baseline.get(name, 0) for name in baseline},
"samples": len(samples),
"sample_intervals_seconds": [round(b-a, 3) for a, b in zip(timestamps, timestamps[1:])],
"method": "cgroup memory.current via Docker; 0.1s pause AFTER each poll, actual intervals include Docker latency; ten clients start at a barrier and send chunked 512 KiB blocks every 0.5s. Peak is sampled, not continuous.",
}
destination = ROOT / args.output
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
print(json.dumps(report, ensure_ascii=False))
check(all(value <= 512 * 1024 * 1024 for value in peak.values()), "API exceeded configured memory limit")
if __name__ == "__main__":
run(main)