Implement lab4 S3 attachments and reliability checks
This commit is contained in:
@@ -0,0 +1,225 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import http.client
|
||||
import json
|
||||
import secrets
|
||||
import struct
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from uuid import uuid4
|
||||
import zlib
|
||||
|
||||
|
||||
BASE = "http://127.0.0.1:18082/api/v1"
|
||||
token = None
|
||||
passed = 0
|
||||
|
||||
|
||||
def check(label, status, headers, body, expected):
|
||||
global passed
|
||||
|
||||
if status != expected:
|
||||
raise SystemExit(
|
||||
f"FAIL {label}: expected={expected}, actual={status}\n"
|
||||
+ body[:1000].decode("utf-8", errors="replace")
|
||||
)
|
||||
|
||||
assert headers.get("X-Request-Id"), "Missing X-Request-Id"
|
||||
assert headers.get("X-Instance-Id"), "Missing X-Instance-Id"
|
||||
result = json.loads(body)
|
||||
|
||||
if expected >= 400:
|
||||
codes = {
|
||||
400: "invalid_request",
|
||||
404: "not_found",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
}
|
||||
assert result["error"]["code"] == codes[expected]
|
||||
assert (
|
||||
result["error"]["request_id"]
|
||||
== headers["X-Request-Id"]
|
||||
)
|
||||
|
||||
passed += 1
|
||||
print(f"OK {status}: {label}", flush=True)
|
||||
return result
|
||||
|
||||
|
||||
def call(label, method, path, expected, *,
|
||||
payload=None, data=None, headers=None):
|
||||
headers = dict(headers or {})
|
||||
|
||||
if token and "Authorization" not in headers:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
|
||||
if payload is not None:
|
||||
data = json.dumps(payload).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
|
||||
request = urllib.request.Request(
|
||||
BASE + path, data=data, headers=headers, method=method
|
||||
)
|
||||
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=15)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
|
||||
with response:
|
||||
body = response.read()
|
||||
return check(
|
||||
label, response.code, response.headers, body, expected
|
||||
)
|
||||
|
||||
|
||||
def chunk(kind, content):
|
||||
return (
|
||||
struct.pack(">I", len(content))
|
||||
+ kind + content
|
||||
+ struct.pack(">I", zlib.crc32(kind + content) & 0xffffffff)
|
||||
)
|
||||
|
||||
|
||||
def png(width, height):
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(
|
||||
b"IHDR",
|
||||
struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0),
|
||||
)
|
||||
+ chunk(b"IDAT", zlib.compress(b"\x00\x12\x34\x56"))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
username = "negative_" + secrets.token_hex(6)
|
||||
password = "Lab4-" + secrets.token_hex(16)
|
||||
|
||||
user = call(
|
||||
"create user", "POST", "/users", 201,
|
||||
payload={
|
||||
"username": username,
|
||||
"display_name": "Lab4 negative tests",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
|
||||
basic = base64.b64encode(
|
||||
f"{username}:{password}".encode()
|
||||
).decode()
|
||||
|
||||
session = call(
|
||||
"login", "POST", "/auth/sessions", 201,
|
||||
headers={"Authorization": "Basic " + basic},
|
||||
)
|
||||
token = session["token"]
|
||||
|
||||
chat_ids = []
|
||||
for number in (1, 2):
|
||||
chat = call(
|
||||
f"create chat {number}", "POST", "/chats", 201,
|
||||
payload={
|
||||
"title": f"Negative check {number}",
|
||||
"member_ids": [user["id"]],
|
||||
},
|
||||
)
|
||||
chat_ids.append(chat["id"])
|
||||
|
||||
upload = f"/chats/{chat_ids[0]}/attachments"
|
||||
image = png(1, 1)
|
||||
|
||||
attachment = call(
|
||||
"valid upload", "POST", upload + "?filename=valid.png", 201,
|
||||
data=image,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
for filename in (
|
||||
"../bad.png",
|
||||
"bad\\name.png",
|
||||
"bad\x00.png",
|
||||
"bad\n.png",
|
||||
" ",
|
||||
"a" * 256,
|
||||
):
|
||||
call(
|
||||
"unsafe filename " + repr(filename[:30]),
|
||||
"POST",
|
||||
upload + "?filename=" + urllib.parse.quote(filename, safe=""),
|
||||
400,
|
||||
data=image,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
for label, data, mime in (
|
||||
("PNG declared as JPEG", image, "image/jpeg"),
|
||||
("non-image", b"this is not an image", "image/png"),
|
||||
("truncated PNG", image[:-12], "image/png"),
|
||||
("unsupported MIME", image, "application/octet-stream"),
|
||||
("empty image", b"", "image/png"),
|
||||
):
|
||||
call(
|
||||
label, "POST", upload + "?filename=bad.png", 415,
|
||||
data=data,
|
||||
headers={"Content-Type": mime},
|
||||
)
|
||||
|
||||
call(
|
||||
"over 40 million pixels",
|
||||
"POST", upload + "?filename=huge.png", 413,
|
||||
data=png(8001, 5000),
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
connection = http.client.HTTPConnection(
|
||||
"127.0.0.1", 18082, timeout=15
|
||||
)
|
||||
try:
|
||||
connection.putrequest(
|
||||
"POST", "/api/v1" + upload + "?filename=oversize.png"
|
||||
)
|
||||
connection.putheader("Authorization", "Bearer " + token)
|
||||
connection.putheader("Content-Type", "image/png")
|
||||
connection.putheader("Content-Length", str(10 * 1024 * 1024 + 1))
|
||||
connection.putheader("Connection", "close")
|
||||
connection.endheaders()
|
||||
|
||||
response = connection.getresponse()
|
||||
check(
|
||||
"oversized Content-Length rejected before body",
|
||||
response.status,
|
||||
response.headers,
|
||||
response.read(),
|
||||
413,
|
||||
)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
for label, chat_id, ids, expected in (
|
||||
(
|
||||
"attachment from another chat",
|
||||
chat_ids[1], [attachment["id"]], 404,
|
||||
),
|
||||
(
|
||||
"unknown attachment",
|
||||
chat_ids[0], [str(uuid4())], 404,
|
||||
),
|
||||
(
|
||||
"duplicate attachment",
|
||||
chat_ids[0], [attachment["id"], attachment["id"]], 400,
|
||||
),
|
||||
(
|
||||
"more than 10 attachments",
|
||||
chat_ids[0], [str(uuid4()) for _ in range(11)], 400,
|
||||
),
|
||||
):
|
||||
call(
|
||||
label, "POST", f"/chats/{chat_id}/messages", expected,
|
||||
payload={"text": "", "attachment_ids": ids},
|
||||
headers={"Idempotency-Key": secrets.token_hex(16)},
|
||||
)
|
||||
|
||||
print(f"\nPASS: {passed} checks including setup")
|
||||
Reference in New Issue
Block a user