126 lines
6.1 KiB
Python
Executable File
126 lines
6.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Inject and restore a missing S3 object to prove reconciler safety.
|
|
|
|
Creates an isolated attachment through the public API, removes only its
|
|
server-generated S3 key from inside the private network, verifies detection and
|
|
non-destructive ``--apply``, restores the exact bytes, and verifies a clean scan.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import base64
|
|
import json
|
|
import subprocess
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
|
|
|
|
|
def request(method: str, base_url: str, path: str, *, body: dict[str, Any] | None = None,
|
|
raw: bytes | None = None, headers: dict[str, str] | None = None) -> tuple[int, bytes]:
|
|
data = raw if body is None else json.dumps(body).encode("utf-8")
|
|
request_headers = {"Accept": "application/json"}
|
|
if body is not None:
|
|
request_headers["Content-Type"] = "application/json"
|
|
request_headers.update(headers or {})
|
|
prepared = urllib.request.Request(base_url + path, data=data, headers=request_headers, method=method)
|
|
try:
|
|
response = urllib.request.urlopen(prepared, timeout=30)
|
|
except urllib.error.HTTPError as error:
|
|
response = error
|
|
with response:
|
|
return response.status, response.read()
|
|
|
|
|
|
def require_json(response: tuple[int, bytes], expected: int) -> dict[str, Any]:
|
|
status, data = response
|
|
if status != expected:
|
|
raise RuntimeError("expected HTTP %s, received %s: %s" % (expected, status, data[:300]))
|
|
return json.loads(data)
|
|
|
|
|
|
def reconcile(env_file: str, *args: str) -> dict[str, Any]:
|
|
result = subprocess.run(
|
|
["docker", "compose", "--env-file", env_file, "exec", "-T", "api-1", "python", "-m", "src.reconcile", *args],
|
|
cwd=ROOT, check=True, text=True, capture_output=True,
|
|
)
|
|
return json.loads(result.stdout)
|
|
|
|
|
|
def s3_command(env_file: str, source: str) -> None:
|
|
subprocess.run(
|
|
["docker", "compose", "--env-file", env_file, "exec", "-T", "api-1", "python", "-c", source],
|
|
cwd=ROOT, check=True, text=True, capture_output=True,
|
|
)
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--base-url", default="http://127.0.0.1:8083")
|
|
parser.add_argument("--env-file", default=".env")
|
|
parser.add_argument("--evidence", type=Path)
|
|
args = parser.parse_args()
|
|
base_url = args.base_url.rstrip("/")
|
|
registration = {"username": "missing_" + uuid.uuid4().hex[:16],
|
|
"display_name": "Missing S3 experiment", "password": "Missing-" + uuid.uuid4().hex}
|
|
user = require_json(request("POST", base_url, "/api/v1/users", body=registration), 201)
|
|
basic = base64.b64encode((registration["username"] + ":" + registration["password"]).encode()).decode()
|
|
session = require_json(request("POST", base_url, "/api/v1/auth/sessions",
|
|
headers={"Authorization": "Basic " + basic}), 201)
|
|
token = session["token"]
|
|
chat = require_json(request("POST", base_url, "/api/v1/chats",
|
|
body={"title": "Missing S3 experiment", "member_ids": [user["id"]]},
|
|
headers={"Authorization": "Bearer " + token}), 201)
|
|
attachment = require_json(request("POST", base_url,
|
|
"/api/v1/chats/%s/attachments?filename=missing.png" % chat["id"], raw=PNG,
|
|
headers={"Authorization": "Bearer " + token, "Content-Type": "image/png"}), 201)
|
|
key = "attachments/" + attachment["id"]
|
|
delete_code = "from src.config import load_settings; from src.object_store import ObjectStore; ObjectStore(load_settings()).delete(%r)" % key
|
|
s3_command(args.env_file, delete_code)
|
|
unavailable_status, unavailable_body = request("GET", base_url, "/api/v1/attachments/%s/content" % attachment["id"],
|
|
headers={"Authorization": "Bearer " + token})
|
|
missing_dry_run = reconcile(args.env_file, "--grace-seconds", "60")
|
|
missing_apply = reconcile(args.env_file, "--apply", "--grace-seconds", "60")
|
|
# Do not put image bytes on a Windows command line: it is capped at 32 KiB.
|
|
# docker compose cp crosses the private container boundary without exposing S3.
|
|
subprocess.run(
|
|
["docker", "compose", "--env-file", args.env_file, "cp",
|
|
str(ROOT / "tests" / "fixtures" / "sample.png"), "api-1:/tmp/reconcile-restore.png"],
|
|
cwd=ROOT, check=True, text=True, capture_output=True,
|
|
)
|
|
restore_code = (
|
|
"from src.config import load_settings; from src.object_store import ObjectStore; "
|
|
"source=open('/tmp/reconcile-restore.png','rb'); "
|
|
"ObjectStore(load_settings()).put(%r,source,%s,'image/png'); source.close()"
|
|
% (key, len(PNG))
|
|
)
|
|
s3_command(args.env_file, restore_code)
|
|
final_dry_run = reconcile(args.env_file, "--grace-seconds", "60")
|
|
restored_status, restored_bytes = request("GET", base_url, "/api/v1/attachments/%s/content" % attachment["id"],
|
|
headers={"Authorization": "Bearer " + token})
|
|
summary = {
|
|
"missing_download": {"status": unavailable_status, "error": json.loads(unavailable_body)["error"]["code"]},
|
|
"missing_dry_run": missing_dry_run,
|
|
"missing_apply": missing_apply,
|
|
"final_dry_run": final_dry_run,
|
|
"restored_download": {"status": restored_status, "bytes_match": restored_bytes == PNG},
|
|
"safety": "apply leaves missing PostgreSQL metadata intact; object was restored without metadata recreation",
|
|
}
|
|
text = json.dumps(summary, ensure_ascii=False, sort_keys=True)
|
|
print(text)
|
|
if args.evidence is not None:
|
|
args.evidence.parent.mkdir(parents=True, exist_ok=True)
|
|
args.evidence.write_text(text + "\n", encoding="utf-8")
|
|
if unavailable_status != 503 or missing_dry_run["missing_metadata_objects"] < 1 or missing_apply["deleted_orphans"] != 0 or final_dry_run["missing_metadata_objects"] != 0 or restored_status != 200 or restored_bytes != PNG:
|
|
raise SystemExit(1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|