64 lines
2.5 KiB
Python
64 lines
2.5 KiB
Python
"""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()
|