Add bounded private image upload with safe S3 persistence

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-02 13:24:51 +03:00
parent 22f7bcddf5
commit 412b465b85
13 changed files with 430 additions and 8 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 633 B

+63
View File
@@ -0,0 +1,63 @@
"""Black-box upload and validation checks; BASE_URL defaults to localhost:8080."""
import hashlib
import struct
import sys
import unittest
import zlib
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client # noqa: E402
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
JPEG = (ROOT / "student-tests/fixtures/sample.jpg").read_bytes()
class UploadTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.client = Client()
cls.alice, _, cls.eve, cls.chat = cls.client.bootstrap()
cls.path = f"/api/v1/chats/{cls.chat['id']}/attachments"
def upload(self, content=PNG, media_type="image/png", filename="sample.png", expected=201, actor=None):
return self.client.call(
"POST", self.path + "?filename=" + quote(filename, safe=""), expected,
actor=actor or self.alice, raw=content, headers={"Content-Type": media_type},
schema="Attachment" if expected == 201 else None,
)
def test_png_and_jpeg(self):
for content, media_type, filename in ((PNG, "image/png", "sample.png"), (JPEG, "image/jpeg", "sample.jpg")):
attachment = self.upload(content, media_type, filename)["json"]
self.assertEqual(attachment["status"], "ready")
self.assertEqual(attachment["owner_id"], self.alice["id"])
self.assertEqual(attachment["chat_id"], self.chat["id"])
self.assertEqual(attachment["content_type"], media_type)
self.assertEqual(attachment["size_bytes"], len(content))
self.assertEqual(attachment["sha256"], hashlib.sha256(content).hexdigest())
def test_rejects_oversized_and_oversized_pixels(self):
self.upload(b"x" * (10 * 1024 * 1024 + 1), expected=413)
changed = bytearray(PNG)
changed[16:24] = struct.pack(">II", 6325, 6325)
changed[29:33] = struct.pack(">I", zlib.crc32(changed[12:29]))
self.upload(bytes(changed), expected=413)
def test_rejects_invalid_image_and_mime_spoofing(self):
self.upload(PNG[:-10], expected=415)
self.upload(PNG, "image/jpeg", expected=415)
self.upload(b"not an image", expected=415)
def test_rejects_unsafe_names_and_outsider(self):
for name in ("../bad.png", "folder\\bad.png", "bad\x00name.png", "bad\nname.png", ""):
self.upload(filename=name, expected=400)
self.upload(expected=404, actor=self.eve)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -31,7 +31,7 @@ class DatabaseTests(unittest.TestCase):
def test_migration_and_unique_username_race(self):
with psycopg.connect(URL) as conn:
versions = conn.execute("SELECT version FROM schema_migrations").fetchall()
self.assertEqual(versions, [(1,), (2,), (3,), (4,)])
self.assertEqual(versions, [(1,), (2,), (3,), (4,), (5,)])
name = "u_" + uuid4().hex[:16]
def register(_):
+46
View File
@@ -0,0 +1,46 @@
"""Run inside an API container while S3 is stopped; no secrets are printed."""
import io
import unittest
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from uuid import uuid4
from PIL import Image
from src.db import pool
from src.store import store
def status(path: str, data: bytes | None = None, headers: dict | None = None) -> int:
request = Request("http://127.0.0.1:8080" + path, data=data, headers=headers or {}, method="POST" if data is not None else "GET")
try:
with urlopen(request, timeout=15) as response:
return response.status
except HTTPError as error:
return error.code
class S3OutageTests(unittest.TestCase):
def test_unavailable_without_false_ready_or_metadata(self):
username = "s3_outage_" + uuid4().hex[:16]
user = store.register(username, "S3 outage", "Test-password-123")
session = store.create_session(username, "Test-password-123")
chat = store.create_chat(user["id"], "S3 outage", [user["id"]])
with pool().connection() as conn:
before = conn.execute("SELECT count(*) AS n FROM attachments WHERE chat_id=%s", (chat["id"],)).fetchone()["n"]
data = io.BytesIO()
Image.new("RGB", (4, 3), (20, 60, 120)).save(data, format="PNG")
self.assertEqual(status("/health/ready"), 503)
self.assertEqual(
status(f"/api/v1/chats/{chat['id']}/attachments?filename=outage.png", data.getvalue(),
{"Content-Type": "image/png", "Authorization": "Bearer " + session["token"]}),
503,
)
with pool().connection() as conn:
after = conn.execute("SELECT count(*) AS n FROM attachments WHERE chat_id=%s", (chat["id"],)).fetchone()["n"]
self.assertEqual(after, before)
if __name__ == "__main__":
unittest.main()
+68
View File
@@ -0,0 +1,68 @@
"""Run inside an API image: python - < student-tests/test_upload_failure.py."""
import asyncio
import io
import unittest
from contextlib import contextmanager
from unittest.mock import Mock, patch
from uuid import uuid4
from fastapi import HTTPException
from src import attachments
class UploadFailureTests(unittest.TestCase):
def test_post_put_database_failure_compensates(self):
client = Mock()
with patch.object(attachments, "storage", return_value=client), patch.object(
attachments, "connection", side_effect=HTTPException(503)
):
with self.assertRaises(HTTPException) as failure:
attachments.persist_attachment(str(uuid4()), str(uuid4()), "test.png", "image/png", 3, "0" * 64, io.BytesIO(b"png"))
self.assertEqual(failure.exception.status_code, 503)
key = client.put_object.call_args.args[1]
client.remove_object.assert_called_once_with(attachments.BUCKET, key)
def test_s3_failure_does_not_touch_database(self):
client = Mock()
client.put_object.side_effect = OSError("simulated outage")
with patch.object(attachments, "storage", return_value=client), patch.object(attachments, "connection") as db:
with self.assertRaises(HTTPException) as failure:
attachments.persist_attachment(str(uuid4()), str(uuid4()), "test.png", "image/png", 3, "0" * 64, io.BytesIO(b"png"))
self.assertEqual(failure.exception.status_code, 503)
db.assert_not_called()
def test_ambiguous_commit_keeps_object_for_reconciliation(self):
@contextmanager
def ambiguous_commit():
connection = Mock()
connection.execute.return_value.fetchone.return_value = {}
yield connection
raise HTTPException(503)
client = Mock()
with patch.object(attachments, "storage", return_value=client), patch.object(
attachments, "connection", side_effect=ambiguous_commit
):
with self.assertRaises(HTTPException) as failure:
attachments.persist_attachment(str(uuid4()), str(uuid4()), "test.png", "image/png", 3, "0" * 64, io.BytesIO(b"png"))
self.assertEqual(failure.exception.status_code, 503)
client.remove_object.assert_not_called()
def test_interrupted_request_never_starts_s3_put(self):
class Interrupted:
headers = {"content-type": "image/png"}
async def stream(self):
yield b"partial"
raise OSError("client disconnected")
with patch.object(attachments.store, "chat"), patch.object(attachments, "storage") as client:
with self.assertRaises(OSError):
asyncio.run(attachments.upload(Interrupted(), str(uuid4()), str(uuid4()), "test.png"))
client.assert_not_called()
if __name__ == "__main__":
unittest.main()