level 4
This commit is contained in:
@@ -0,0 +1,173 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Student negative suite for lab4 attachments. Public smoke.py is not modified."""
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import uuid
|
||||
import zlib
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from client import Client, Failure, arguments, check, run, shape
|
||||
|
||||
MAX_UPLOAD_BYTES = 10_485_760
|
||||
ROOT = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def png_header(width, height):
|
||||
ihdr = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)
|
||||
data = ihdr
|
||||
crc = zlib.crc32(b'IHDR' + data) & 0xffffffff
|
||||
chunk = struct.pack('>I', len(data)) + b'IHDR' + data + struct.pack('>I', crc)
|
||||
return b'\x89PNG\r\n\x1a\n' + chunk
|
||||
|
||||
|
||||
def error_payload(status, headers, body, where):
|
||||
check(status != 500, where + ' returned 500 for a client error')
|
||||
check(bool(headers.get('X-Request-Id')), where + ': missing X-Request-Id')
|
||||
content_type = headers.get_content_type() if hasattr(headers, 'get_content_type') else (headers.get('Content-Type') or '').split(';', 1)[0].strip().lower()
|
||||
check(content_type == 'application/json', where + ': expected JSON error')
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
except (ValueError, UnicodeError):
|
||||
raise Failure(where + ': invalid error JSON') from None
|
||||
shape(payload, 'Error')
|
||||
check(payload['error']['request_id'] == headers.get('X-Request-Id'), where + ': request_id mismatch')
|
||||
return payload
|
||||
|
||||
|
||||
def raw_post(base, path, headers, body, extra_headers=None, chunked=False):
|
||||
parsed = urlparse(base)
|
||||
conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=60)
|
||||
try:
|
||||
hdrs = dict(headers)
|
||||
if extra_headers:
|
||||
hdrs.update(extra_headers)
|
||||
conn.putrequest('POST', path)
|
||||
if chunked:
|
||||
hdrs.pop('Content-Length', None)
|
||||
for name, value in hdrs.items():
|
||||
conn.putheader(name, value)
|
||||
conn.putheader('Transfer-Encoding', 'chunked')
|
||||
conn.endheaders()
|
||||
if isinstance(body, (bytes, bytearray)):
|
||||
pieces = [bytes(body)]
|
||||
else:
|
||||
pieces = body
|
||||
for piece in pieces:
|
||||
conn.send(('%x\r\n' % len(piece)).encode('ascii') + piece + b'\r\n')
|
||||
conn.send(b'0\r\n\r\n')
|
||||
else:
|
||||
payload = body if isinstance(body, (bytes, bytearray)) else b''
|
||||
if not any(name.lower() == 'content-length' for name in hdrs):
|
||||
hdrs['Content-Length'] = str(len(payload))
|
||||
for name, value in hdrs.items():
|
||||
conn.putheader(name, value)
|
||||
conn.endheaders()
|
||||
if payload:
|
||||
conn.send(payload)
|
||||
response = conn.getresponse()
|
||||
data = response.read(1024 * 1024)
|
||||
hdr = response.headers
|
||||
return response.status, hdr, data
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def expect_error(c, actor, chat, *, filename='photo.png', content_type='image/png', body=b'', status=None, extra_headers=None, chunked=False, pieces=None, where='upload'):
|
||||
path = '/api/v1/chats/%s/attachments?filename=%s' % (chat['id'], filename)
|
||||
headers = {
|
||||
'Authorization': 'Bearer ' + actor['token'],
|
||||
'Content-Type': content_type,
|
||||
'Accept': 'application/json',
|
||||
}
|
||||
payload_body = pieces if chunked and pieces is not None else body
|
||||
code, hdr, data = raw_post(c.base, path, headers, payload_body, extra_headers=extra_headers, chunked=chunked)
|
||||
payload = error_payload(code, hdr, data, where)
|
||||
if status is not None:
|
||||
check(code == status, '%s: expected %s, received %s (%s)' % (where, status, code, payload['error']['code']))
|
||||
return code, payload
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab4 attachment negative cases')
|
||||
c = Client(args.base_url, args.ca_file, timeout=60)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
sample = open(os.path.join(ROOT, 'fixtures', 'sample.png'), 'rb').read()
|
||||
|
||||
code, payload = expect_error(
|
||||
c, alice, chat,
|
||||
extra_headers={'Content-Length': str(MAX_UPLOAD_BYTES + 1)},
|
||||
body=b'x',
|
||||
status=413,
|
||||
where='oversized Content-Length',
|
||||
)
|
||||
check(payload['error']['code'] == 'payload_too_large', 'oversized Content-Length: wrong code')
|
||||
|
||||
header = png_header(32, 32)
|
||||
remain = MAX_UPLOAD_BYTES + 1 - len(header)
|
||||
chunk = b'\x00' * 65536
|
||||
pieces = [header]
|
||||
sent = len(header)
|
||||
while sent < len(header) + remain:
|
||||
take = min(len(chunk), len(header) + remain - sent)
|
||||
pieces.append(chunk[:take])
|
||||
sent += take
|
||||
code, payload = expect_error(
|
||||
c, alice, chat,
|
||||
chunked=True,
|
||||
pieces=pieces,
|
||||
status=413,
|
||||
where='oversized chunked body',
|
||||
)
|
||||
check(payload['error']['code'] == 'payload_too_large', 'oversized chunked body: wrong code')
|
||||
|
||||
expect_error(c, alice, chat, body=b'\x89PNG\r\n\x1a\n\x00\x00\x00\x0dnotH', status=415, where='corrupt PNG')
|
||||
expect_error(c, alice, chat, body=b'\xff\xd8\xff\xe0\x00', status=415, where='truncated JPEG')
|
||||
expect_error(c, alice, chat, body=b'GIF89a-not-an-image', status=415, where='foreign format')
|
||||
|
||||
code, payload = expect_error(
|
||||
c, alice, chat,
|
||||
content_type='image/jpeg',
|
||||
body=sample,
|
||||
status=415,
|
||||
where='MIME spoof',
|
||||
)
|
||||
check(payload['error']['code'] == 'unsupported_media_type', 'MIME spoof: wrong code')
|
||||
|
||||
bomb = png_header(10000, 5000)
|
||||
code, payload = expect_error(c, alice, chat, body=bomb, status=413, where='pixel bomb')
|
||||
check(payload['error']['code'] == 'payload_too_large', 'pixel bomb: wrong code')
|
||||
|
||||
att, _content = c.attachment(alice, chat)
|
||||
for suffix in ('', '/content'):
|
||||
unknown = c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=alice)
|
||||
check(unknown['json']['error']['code'] == 'not_found', 'random id: wrong code')
|
||||
check(unknown['status'] != 500, 'random id returned 500')
|
||||
foreign = c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
|
||||
check(foreign['json']['error']['code'] == 'not_found', 'outsider: wrong code')
|
||||
|
||||
other = c.call(
|
||||
'POST',
|
||||
'/api/v1/chats',
|
||||
201,
|
||||
actor=alice,
|
||||
body={'title': 'Чужой чат', 'member_ids': [alice['id']]},
|
||||
schema='Chat',
|
||||
)['json']
|
||||
linked = c.call(
|
||||
'POST',
|
||||
'/api/v1/chats/' + other['id'] + '/messages',
|
||||
404,
|
||||
actor=alice,
|
||||
body={'text': '', 'attachment_ids': [att['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex},
|
||||
)
|
||||
check(linked['json']['error']['code'] == 'not_found', 'cross-chat attach: wrong code')
|
||||
check(linked['status'] != 500, 'cross-chat attach returned 500')
|
||||
|
||||
print('PASS: lab4 attachment negative cases (413/415/404, never 500)')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user