add level 4

This commit is contained in:
Матвей
2026-10-22 11:37:09 +03:00
parent e9ef559c34
commit 9017861707
24 changed files with 571 additions and 31 deletions
+138
View File
@@ -0,0 +1,138 @@
#!/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"]
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")
check(orphan in report["fresh_unreferenced"] and not report["deleted"], "grace period ignored")
report = reconcile("--apply", "--grace-seconds", "0")
check(report["deleted"] == [orphan], "aged orphan was not deleted safely")
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)
report = reconcile("--grace-seconds", "0")
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"] + "/content", 503, actor=bob)
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")
print("PASS: dry-run, grace period, orphan deletion and missing-object reporting", 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")
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 = [key for key in report["orphan_candidates"] if key.startswith("originals/")]
check(injected, "injected post-PUT failure did not create a detectable orphan")
report = reconcile("--apply", "--grace-seconds", "0")
check(set(injected).issubset(report["deleted"]), "reconciler did not clean injected orphan")
print("PASS: post-PUT/pre-DB injected failure leaves no permanent orphan", flush=True)
finally:
environment["UPLOAD_FAULT_AFTER_S3_PUT"] = "0"
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "api-a"],
cwd=ROOT, env=environment, check=True, stdout=subprocess.DEVNULL)
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)
+92
View File
@@ -0,0 +1,92 @@
#!/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()
def sampler():
while not stop.is_set():
values = api_memory()
samples.append(values)
for name, value in values.items():
peak[name] = max(peak.get(name, 0), value)
time.sleep(.1)
def upload(index):
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")
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),
"method": "cgroup memory.current sampled through Docker every 0.1 seconds while clients send chunked 512 KiB blocks every 0.5 seconds; peak is not a continuous profiler.",
}
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)