Add safe attachment reconciliation and scoped maintenance checks

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-02 14:08:12 +03:00
parent 9347fe35ae
commit dc4f5c6c7f
9 changed files with 403 additions and 0 deletions
+1
View File
@@ -7,6 +7,7 @@ RUN pip install --no-cache-dir -r requirements.txt && useradd --system --uid 100
COPY --chown=app:app src/ src/
COPY --chown=app:app migrations/ migrations/
COPY --chown=app:app scripts/migrate.py scripts/migrate.py
COPY --chown=app:app scripts/reconcile-attachments.py scripts/reconcile-attachments.py
USER app
EXPOSE 8080
CMD ["python", "-m", "src.server"]
+20
View File
@@ -102,6 +102,26 @@ services:
cpus: 0.5
mem_limit: 256m
reconcile:
profiles: [maintenance]
build: .
command: ["python", "scripts/reconcile-attachments.py"]
environment:
DATABASE_URL_FILE: /run/secrets/database_url
S3_ENDPOINT: s3:9000
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_maintenance_key_id
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_maintenance_secret_key
secrets: [database_url, s3_maintenance_key_id, s3_maintenance_secret_key]
volumes: ["./tests/fixtures:/fixtures:ro"]
depends_on:
migrate:
condition: service_completed_successfully
s3-bootstrap:
condition: service_completed_successfully
restart: "no"
cpus: 0.5
mem_limit: 256m
lb:
image: haproxy:3.0.11-alpine
volumes:
+19
View File
@@ -0,0 +1,19 @@
Lab 4 U5, local Colima/arm64, 2026-10-02, synthetic data only.
Service setup: Compose API x2 + PostgreSQL + private MinIO. Default reconciliation grace: 3600 s.
The ignored compose.local.yaml only supplied a temporary package-CDN address for local builds.
Checks:
- `docker compose ... exec -T api python - < student-tests/test_upload_failure.py`: 4/4 PASS, including uncertain COMMIT retaining the object.
- `docker compose ... exec -T api python - < student-tests/test_storage_permissions.py`: 1/1 PASS; API identity cannot ListBucket or create a bucket, anonymous GET 403.
- `docker compose ... --profile maintenance run --rm -T reconcile python - < student-tests/test_storage_permissions.py`: 1/1 PASS; separate maintenance identity can list but cannot create a bucket, anonymous GET 403, root/API secrets absent.
- `docker compose ... --profile maintenance run --rm -T reconcile python - < student-tests/test_reconcile.py`: 2/2 PASS. Old orphan originated from S3 PUT followed by PostgreSQL FK rollback; missing originated from deleting an existing S3 object while ready metadata remained. Dry-run did not mutate. With a test-only 5-second grace, apply deleted the old orphan while preserving a fresh orphan and a message-linked attachment. A wrong fixture was rejected before any deletion; missing content returned HTTP 503. The fixture with matching size/SHA-256 restored the original key, after which API content returned the exact original bytes. Repeat restore was `already_present`.
- `docker compose ... ps s3`: healthy S3; only internal `9000-9001/tcp`, no host port published.
CLI evidence (separate runs, production grace 3600 s):
- `reconcile-u5-dry-run.json`: 28 metadata / 28 objects; 1 fresh orphan protected, 1 missing/manual incident, 0 deleted, 5.176 ms.
- `reconcile-u5-restore.json`: verified fixture restored that synthetic missing object; 0 deleted, 9.130 ms.
- `reconcile-u5-repeat.json`: restore `already_present`, no remaining missing ID, 0 deleted, 7.657 ms.
MinIO list timestamps include milliseconds while HEAD timestamps have second precision. Before deletion, the reconciler compares their second-level time, ETag and size, then rechecks the age and PostgreSQL reference. The first integration run exposed this representation difference; after the fix, both tests passed.
Limits: these are single-run local timings, not a throughput estimate. The 5-second grace is used only for synthetic integration data; routine maintenance defaults to one hour. Missing bytes without a verified source remain a manual incident, with metadata retained. A test-created fresh orphan remains in the inventory until it ages beyond grace and a later apply run handles it.
+1
View File
@@ -0,0 +1 @@
{"deleted": [], "duration_ms": 5.176, "fresh_orphans": ["originals/c2046814-1d5e-429b-b537-168d68d43f40"], "grace_seconds": 3600, "inventory": {"metadata": 28, "objects": 28}, "manual_incidents": ["ee0c99ff-772d-4957-91aa-8a599a67578a"], "missing_attachment_ids": ["ee0c99ff-772d-4957-91aa-8a599a67578a"], "mode": "dry_run", "old_orphans": [], "preserved_after_recheck": [], "restore": null, "unknown_keys_preserved": []}
+1
View File
@@ -0,0 +1 @@
{"deleted": [], "duration_ms": 7.657, "fresh_orphans": ["originals/c2046814-1d5e-429b-b537-168d68d43f40"], "grace_seconds": 3600, "inventory": {"metadata": 28, "objects": 29}, "manual_incidents": [], "missing_attachment_ids": [], "mode": "apply", "old_orphans": [], "preserved_after_recheck": [], "restore": "already_present", "unknown_keys_preserved": []}
+1
View File
@@ -0,0 +1 @@
{"deleted": [], "duration_ms": 9.13, "fresh_orphans": ["originals/c2046814-1d5e-429b-b537-168d68d43f40"], "grace_seconds": 3600, "inventory": {"metadata": 28, "objects": 28}, "manual_incidents": [], "missing_attachment_ids": ["ee0c99ff-772d-4957-91aa-8a599a67578a"], "mode": "apply", "old_orphans": [], "preserved_after_recheck": [], "restore": "restored", "unknown_keys_preserved": []}
+173
View File
@@ -0,0 +1,173 @@
"""Compare PostgreSQL attachment metadata with private S3 originals.
Dry-run is the default. Run in the Compose maintenance profile with its separate S3 identity.
"""
import argparse
import hashlib
import json
import os
import re
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from uuid import UUID
import psycopg
from minio import Minio
from minio.error import S3Error
from psycopg.rows import dict_row
from urllib3 import PoolManager, Retry, Timeout
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.db import database_url # noqa: E402
BUCKET = "messenger-attachments"
ORIGINAL = re.compile(r"originals/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\Z")
MAX_SOURCE = 10 * 1024 * 1024
def secret(name: str) -> str:
return Path(os.environ[f"{name}_FILE"]).read_text(encoding="utf-8").strip()
def storage() -> Minio:
return Minio(
os.environ.get("S3_ENDPOINT", "s3:9000"),
access_key=secret("S3_ACCESS_KEY_ID"), secret_key=secret("S3_SECRET_ACCESS_KEY"),
secure=False, region="us-east-1",
http_client=PoolManager(timeout=Timeout(connect=2, read=10), retries=Retry(total=0)),
)
def age_seconds(last_modified: datetime, now: datetime) -> float:
if last_modified is None or last_modified.tzinfo is None:
return 0 # Unknown age is never safe to delete.
return max(0, (now - last_modified).total_seconds())
def absent(client: Minio, key: str) -> bool:
try:
client.stat_object(BUCKET, key)
return False
except S3Error as exc:
if exc.code == "NoSuchKey":
return True
raise
def source_hash(path: Path) -> tuple[int, str]:
size, digest = 0, hashlib.sha256()
with path.open("rb") as stream:
while chunk := stream.read(1024 * 1024):
size += len(chunk)
if size > MAX_SOURCE:
raise ValueError("restore source exceeds 10 MiB")
digest.update(chunk)
return size, digest.hexdigest()
def delete_orphan(client: Minio, conn: psycopg.Connection, item, grace: int) -> bool:
key = item.object_name
if conn.execute("SELECT 1 FROM attachments WHERE object_key=%s", (key,)).fetchone():
return False
try:
current = client.stat_object(BUCKET, key)
except S3Error as exc:
if exc.code == "NoSuchKey":
return False
raise
if (
current.etag != item.etag or current.last_modified.replace(microsecond=0) != item.last_modified.replace(microsecond=0)
or current.size != item.size or age_seconds(current.last_modified, datetime.now(timezone.utc)) < grace
):
return False
# Upload keys are random and S3 PUT + PostgreSQL INSERT is bounded; grace and recheck protect live uploads.
client.remove_object(BUCKET, key)
return True
def restore_missing(client: Minio, conn: psycopg.Connection, attachment_id: UUID, source: Path, apply: bool) -> str:
size, digest = source_hash(source)
row = conn.execute(
"SELECT id,object_key,size_bytes,sha256,content_type,status FROM attachments WHERE id=%s FOR UPDATE",
(attachment_id,),
).fetchone()
if row is None or row["status"] != "ready":
raise ValueError("ready attachment not found")
if not ORIGINAL.fullmatch(row["object_key"]):
raise ValueError("invalid original object key")
if (size, digest) != (row["size_bytes"], row["sha256"]):
raise ValueError("restore source size/SHA-256 mismatch")
if not absent(client, row["object_key"]):
return "already_present"
if not apply:
return "would_restore"
with source.open("rb") as stream:
client.put_object(BUCKET, row["object_key"], stream, size, content_type=row["content_type"])
if client.stat_object(BUCKET, row["object_key"]).size != size:
raise RuntimeError("restored object size mismatch")
return "restored"
def reconcile(client: Minio, conn: psycopg.Connection, apply: bool, grace: int, restore_id: UUID | None, source: Path | None) -> dict:
start = time.monotonic()
metadata = conn.execute(
"SELECT id,object_key,size_bytes,sha256,content_type,status FROM attachments"
).fetchall()
objects = list(client.list_objects(BUCKET, prefix="originals/", recursive=True))
by_key = {row["object_key"]: row for row in metadata}
by_object = {item.object_name: item for item in objects}
now = datetime.now(timezone.utc)
old = [item for item in objects if item.object_name not in by_key and ORIGINAL.fullmatch(item.object_name)
and age_seconds(item.last_modified, now) >= grace]
fresh = [item.object_name for item in objects if item.object_name not in by_key and ORIGINAL.fullmatch(item.object_name)
and age_seconds(item.last_modified, now) < grace]
unknown = [item.object_name for item in objects if item.object_name not in by_key and not ORIGINAL.fullmatch(item.object_name)]
missing = [row for row in metadata if row["status"] == "ready" and row["object_key"] not in by_object
and absent(client, row["object_key"])]
result = {
"mode": "apply" if apply else "dry_run", "grace_seconds": grace,
"inventory": {"objects": len(objects), "metadata": len(metadata)},
"old_orphans": [item.object_name for item in old], "fresh_orphans": fresh,
"unknown_keys_preserved": unknown, "missing_attachment_ids": [str(row["id"]) for row in missing],
"manual_incidents": [str(row["id"]) for row in missing],
"deleted": [], "preserved_after_recheck": [], "restore": None,
}
if restore_id is not None and apply:
# Reject an invalid source before any orphan deletion in this apply run.
restore_missing(client, conn, restore_id, source, False)
if apply:
for item in old:
(result["deleted"] if delete_orphan(client, conn, item, grace) else result["preserved_after_recheck"]).append(item.object_name)
if restore_id is not None:
result["restore"] = restore_missing(client, conn, restore_id, source, apply)
if result["restore"] in {"restored", "already_present"}:
result["manual_incidents"] = [item for item in result["manual_incidents"] if item != str(restore_id)]
result["duration_ms"] = round((time.monotonic() - start) * 1000, 3)
return result
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--apply", action="store_true", help="perform safe deletions and selected verified restore")
parser.add_argument("--grace-seconds", type=int, default=3600, help="minimum age before deleting an orphan (default 3600)")
parser.add_argument("--restore-id", type=UUID, help="one missing attachment to restore")
parser.add_argument("--source", type=Path, help="read-only original fixture with matching size and SHA-256")
args = parser.parse_args()
if args.grace_seconds < 1 or (args.restore_id is None) != (args.source is None):
parser.error("grace must be positive; restore-id and source must be supplied together")
try:
with psycopg.connect(database_url(), row_factory=dict_row, connect_timeout=5, options="-c statement_timeout=30000") as conn:
result = reconcile(storage(), conn, args.apply, args.grace_seconds, args.restore_id, args.source)
print(json.dumps(result, ensure_ascii=False, sort_keys=True))
return 0
except (psycopg.Error, S3Error, OSError, ValueError, RuntimeError) as exc:
print(json.dumps({"error": type(exc).__name__, "message": "reconciliation stopped without further mutation"}))
return 2
if __name__ == "__main__":
raise SystemExit(main())
+142
View File
@@ -0,0 +1,142 @@
"""Run inside the maintenance image: python - < student-tests/test_reconcile.py."""
import hashlib
import importlib.util
import io
import time
import unittest
from datetime import datetime, timedelta, timezone
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import Mock
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from uuid import UUID, uuid4
import psycopg
from psycopg.rows import dict_row
from src.db import database_url
from src.store import store
spec = importlib.util.spec_from_file_location("reconciler", "scripts/reconcile-attachments.py")
reconciler = importlib.util.module_from_spec(spec)
spec.loader.exec_module(reconciler)
class ReconcileTests(unittest.TestCase):
def test_delete_rechecks_database_and_object_version(self):
key = f"originals/{uuid4()}"
item = SimpleNamespace(object_name=key, etag="old", size=10,
last_modified=datetime.now(timezone.utc) - timedelta(hours=2))
conn, client = Mock(), Mock()
conn.execute.return_value.fetchone.return_value = {"id": uuid4()}
self.assertFalse(reconciler.delete_orphan(client, conn, item, 3600))
client.remove_object.assert_not_called()
conn.execute.return_value.fetchone.return_value = None
client.stat_object.return_value = SimpleNamespace(etag="replaced", size=10, last_modified=item.last_modified)
self.assertFalse(reconciler.delete_orphan(client, conn, item, 3600))
client.remove_object.assert_not_called()
def test_orphans_missing_repair_and_live_reference(self):
client = reconciler.storage()
fixture = Path("/fixtures/sample.png")
data = fixture.read_bytes()
digest = hashlib.sha256(data).hexdigest()
username = "reconcile_" + uuid4().hex[:16]
owner = store.register(username, "Reconciler test", "Test-password-123")
session = store.create_session(username, "Test-password-123")
chat = store.create_chat(owner["id"], "Reconciler test", [owner["id"]])
active_id, missing_id = uuid4(), uuid4()
active_key, missing_key = f"originals/{active_id}", f"originals/{missing_id}"
old_key, fresh_key = f"originals/{uuid4()}", f"originals/{uuid4()}"
def put(key):
client.put_object(reconciler.BUCKET, key, io.BytesIO(data), len(data), content_type="image/png")
put(active_key)
put(missing_key)
put(old_key)
with self.assertRaises(psycopg.errors.ForeignKeyViolation):
with psycopg.connect(database_url()) as failed:
failed.execute(
"INSERT INTO attachments (id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
(UUID(old_key.split("/")[1]), uuid4(), UUID(owner["id"]), "orphan.png", old_key,
"image/png", len(data), digest),
)
with psycopg.connect(database_url(), row_factory=dict_row) as conn:
for item_id, key in ((active_id, active_key), (missing_id, missing_key)):
conn.execute(
"INSERT INTO attachments (id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
(item_id, UUID(chat["id"]), UUID(owner["id"]), "sample.png", key, "image/png", len(data), digest),
)
message_id = uuid4()
conn.execute(
"INSERT INTO messages (id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s)",
(message_id, UUID(chat["id"]), UUID(owner["id"]), ""),
)
conn.execute(
"INSERT INTO message_attachments (message_id,chat_id,attachment_id,position) VALUES (%s,%s,%s,0)",
(message_id, UUID(chat["id"]), active_id),
)
client.remove_object(reconciler.BUCKET, missing_key)
time.sleep(6)
put(fresh_key)
with psycopg.connect(database_url(), row_factory=dict_row) as conn:
preview = reconciler.reconcile(client, conn, False, 5, None, None)
self.assertIn(old_key, preview["old_orphans"])
self.assertIn(fresh_key, preview["fresh_orphans"])
self.assertIn(str(missing_id), preview["missing_attachment_ids"])
self.assertNotIn(active_key, preview["old_orphans"])
self.assertFalse(reconciler.absent(client, old_key))
wrong = Path("/tmp/reconcile-wrong-source")
wrong.write_bytes(b"not the original")
with self.assertRaisesRegex(ValueError, "size/SHA-256 mismatch"):
reconciler.reconcile(client, conn, True, 5, missing_id, wrong)
self.assertFalse(reconciler.absent(client, old_key))
applied = reconciler.reconcile(client, conn, True, 5, None, None)
self.assertIn(old_key, applied["deleted"])
self.assertTrue(reconciler.absent(client, old_key))
self.assertFalse(reconciler.absent(client, fresh_key))
self.assertFalse(reconciler.absent(client, active_key))
self.assertTrue(reconciler.absent(client, missing_key))
request = Request(
f"http://api:8080/api/v1/attachments/{missing_id}/content",
headers={"Authorization": "Bearer " + session["token"]},
)
with self.assertRaises(HTTPError) as unavailable:
urlopen(request, timeout=5)
self.assertEqual(unavailable.exception.code, 503)
with self.assertRaisesRegex(ValueError, "size/SHA-256 mismatch"):
reconciler.restore_missing(client, conn, missing_id, wrong, True)
self.assertTrue(reconciler.absent(client, missing_key))
self.assertEqual(reconciler.restore_missing(client, conn, missing_id, fixture, True), "restored")
self.assertEqual(reconciler.restore_missing(client, conn, missing_id, fixture, True), "already_present")
final = reconciler.reconcile(client, conn, False, 5, None, None)
self.assertNotIn(old_key, final["old_orphans"])
self.assertNotIn(str(missing_id), final["missing_attachment_ids"])
self.assertIsNotNone(conn.execute(
"SELECT 1 FROM message_attachments WHERE attachment_id=%s", (active_id,)
).fetchone())
response = client.get_object(reconciler.BUCKET, missing_key)
try:
self.assertEqual(hashlib.sha256(response.read()).hexdigest(), digest)
finally:
response.close()
response.release_conn()
with urlopen(request, timeout=5) as response:
self.assertEqual(response.read(), data)
print("PASS: old orphan dry-run/apply, fresh and linked objects retained, missing restored from verified fixture")
if __name__ == "__main__":
unittest.main()
+45
View File
@@ -0,0 +1,45 @@
"""Run in both API and maintenance containers; tests their distinct S3 identities."""
import io
import os
import unittest
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import urlopen
from uuid import uuid4
from minio.error import S3Error
from src.attachments import BUCKET, storage
class StoragePermissionsTests(unittest.TestCase):
def test_scoped_identity_and_private_bucket(self):
maintenance = os.environ["S3_ACCESS_KEY_ID_FILE"].endswith("/s3_maintenance_key_id")
self.assertFalse(Path("/run/secrets/minio_root_user").exists())
if maintenance:
self.assertFalse(Path("/run/secrets/s3_access_key_id").exists())
else:
self.assertFalse(Path("/run/secrets/s3_maintenance_key_id").exists())
client = storage()
key = "permissions/" + uuid4().hex
client.put_object(BUCKET, key, io.BytesIO(b"private"), 7)
try:
if maintenance:
list(client.list_objects(BUCKET, prefix="originals/", recursive=True))
else:
with self.assertRaises(S3Error) as denied:
list(client.list_objects(BUCKET, prefix="originals/", recursive=True))
self.assertEqual(denied.exception.code, "AccessDenied")
with self.assertRaises(S3Error) as denied:
client.make_bucket("forbidden-" + uuid4().hex)
self.assertEqual(denied.exception.code, "AccessDenied")
with self.assertRaises(HTTPError) as denied:
urlopen(f"http://s3:9000/{BUCKET}/{key}", timeout=3)
self.assertEqual(denied.exception.code, 403)
finally:
client.remove_object(BUCKET, key)
if __name__ == "__main__":
unittest.main()