Files
mtusi2026lab4-fork/student-tests/attachments_http.py
T

142 lines
5.8 KiB
Python

from datetime import datetime, timezone
from hashlib import sha256
from io import BytesIO
import logging
import os
import http.client
import socket
from pathlib import Path
import threading
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from uuid import uuid4
import json
import sys
from botocore.response import StreamingBody
from PIL import Image
root = Path(__file__).resolve().parents[1]
os.environ['S3_BUCKET'] = 'test'
sys.path.insert(0, str(root / 'src'))
from messenger.api import Api
from messenger.config import Config
from messenger.security import hash_token
from messenger.server import build_server
from messenger.store import Store
chat, member, outsider = [str(uuid4()) for _ in range(3)]
class Metadata:
rows = {}
def get_session(self, token):
return {hash_token('member'): member, hash_token('outsider'): outsider}.get(token)
def user(self, uid):
return {'id': uid}
def chat(self, cid):
return {'id': cid} if cid == chat else None
def is_member(self, _chat, uid):
return uid == member
def reserve_attachment(self, aid, cid, uid, filename, mime, size, digest, key):
now = datetime.now(timezone.utc)
self.rows[aid] = dict(id=aid, chat_id=cid, owner_id=uid, filename=filename,
content_type=mime, size_bytes=size, sha256=digest,
object_key=key, status='pending', error_code=None,
created_at=now, updated_at=now)
def finish_attachment(self, aid, put_object):
put_object(self.rows[aid]['object_key'])
self.rows[aid]['status'] = 'ready'
return self.rows[aid]
def visible_attachment(self, aid, uid):
row = self.rows.get(aid)
if uid == member and row and row['status'] == 'ready':
return row
return None
public_attachment = staticmethod(Store.public_attachment)
class S3:
def __init__(self):
self.objects = {}
self.fail = False
def put_object(self, **kw):
if self.fail:
from botocore.exceptions import EndpointConnectionError
raise EndpointConnectionError(endpoint_url='http://s3.invalid')
data = kw['Body'].read()
assert len(data) == kw['ContentLength']
self.objects[kw['Key']] = data
def get_object(self, **kw):
data = self.objects[kw['Key']]
return {'ContentLength': len(data), 'Body': StreamingBody(BytesIO(data), len(data))}
config = Config.from_env({'APP_HOST':'127.0.0.1','APP_PORT':'8080'})
config.port = 0
api = Api(config, Metadata(), None)
s3 = S3()
api.attachments.client = s3
server = build_server(config, logging.getLogger('lab4-check'), api, None)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base = 'http://127.0.0.1:' + str(server.server_address[1])
upload = f'/api/v1/chats/{chat}/attachments?filename=x.png'
def call(path, method='GET', data=None, mime='image/png', token='member'):
headers = {'Authorization': 'Bearer ' + token, 'Content-Type': mime}
try:
response = urlopen(Request(base + path, data=data, headers=headers, method=method), timeout=12)
except HTTPError as exc:
response = exc
with response:
return response.code, response.headers, response.read()
try:
for image_format, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]:
buf = BytesIO()
Image.new('RGB', (10, 10), 'green').save(buf, format=image_format)
data = buf.getvalue()
status, _, raw = call(upload, 'POST', data, mime)
assert status == 201, (status, raw)
item = json.loads(raw)
assert item['status'] == 'ready' and item['sha256'] == sha256(data).hexdigest()
assert item['size_bytes'] == len(data) and 'object_key' not in item
path = '/api/v1/attachments/' + item['id']
assert json.loads(call(path)[2]) == item
status, headers, actual = call(path + '/content')
assert (status, headers['Content-Type'], actual) == (200, mime, data)
assert call(path, token='outsider')[0] == 404
assert call(path + '/content', token='outsider')[0] == 404
assert call(path + '/content?variant=thumbnail')[0] == 404
png = (root / 'tests/fixtures/sample.png').read_bytes()
assert call(upload, 'POST', png)[0] == 201
assert call(upload, 'POST', png, 'image/jpeg')[0] == 415
assert call(upload, 'POST', png[:30])[0] == 415
assert call(upload.replace('x.png','a%2Fb.png'), 'POST', png)[0] == 400
before = len(api.store.rows)
for length, partial, expected in [(10 * 1024 * 1024 + 1, b'', 413), (64, b'abc', 400)]:
conn = http.client.HTTPConnection(*server.server_address, timeout=5)
try:
conn.request('POST', upload, body=partial, headers={
'Authorization': 'Bearer member', 'Content-Type': 'image/png',
'Content-Length': str(length)})
if partial:
conn.sock.shutdown(socket.SHUT_WR)
with conn.getresponse() as response:
assert response.status == expected, response.status
response.read()
finally:
conn.close()
assert len(api.store.rows) == before
buf = BytesIO()
Image.new('1', (8001, 5000)).save(buf, 'PNG')
assert call(upload, 'POST', buf.getvalue())[0] == 413
s3.fail = True
assert call(upload, 'POST', png)[0] == 503
assert list(api.store.rows.values())[-1]['status'] == 'pending'
print('PASS: local HTTP PNG/JPEG round trip, checksum, metadata, ACL and missing variant')
print('PASS: malformed image, mismatched MIME, unsafe filename, byte/pixel limits and S3 error mapping')
print('NOTE: metadata and S3 are test substitutes; real Compose integration not exercised')
finally:
server.shutdown()
server.server_close()
thread.join()