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
+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()