add level 3
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit local Docker tests: private bucket, uploader failover, S3 outage."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def compose(*args, input=None):
|
||||
return subprocess.check_output(['docker', 'compose', *args], cwd=ROOT, input=input,
|
||||
text=True, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(c):
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'stack did not recover')
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--mode', required=True, choices=['private', 'failover', 's3-outage'])
|
||||
args = arguments(__doc__, configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
uploaded = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png',
|
||||
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
att = uploaded['json']
|
||||
content_path = '/api/v1/attachments/' + att['id'] + '/content'
|
||||
if args.mode == 'private':
|
||||
script = '''import sys, urllib.request, urllib.error
|
||||
url = "http://s3:8333/messenger-attachments/originals/" + sys.stdin.read().strip()
|
||||
try:
|
||||
urllib.request.urlopen(url, timeout=5)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 403, error.code
|
||||
print("PASS: anonymous S3 GET returns 403 for an existing object")
|
||||
else:
|
||||
raise AssertionError("private object leaked")
|
||||
'''
|
||||
print(compose('exec', '-T', 'api-a', '/app/.venv/bin/python', '-c', script, input=att['id']).strip())
|
||||
elif args.mode == 'failover':
|
||||
target = uploaded['headers']['X-Instance-Id']
|
||||
service = None
|
||||
for candidate in ('api-a', 'api-b'):
|
||||
container = compose('ps', '-q', candidate).strip()
|
||||
hostname = subprocess.check_output(['docker', 'inspect', '--format', '{{.Config.Hostname}}', container], text=True).strip()
|
||||
if hostname == target:
|
||||
service = candidate
|
||||
check(service is not None, 'uploading replica not found')
|
||||
try:
|
||||
compose('stop', service)
|
||||
deadline = time.monotonic() + 15
|
||||
while True:
|
||||
try:
|
||||
download = c.call('GET', content_path, actor=bob)
|
||||
break
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'download did not recover')
|
||||
time.sleep(0.5)
|
||||
check(download['headers']['X-Instance-Id'] != target, 'download used stopped uploader')
|
||||
check(download['bytes'] == data, 'original changed after stopping uploader')
|
||||
print('PASS: uploaded via ' + service + '; stopped that container; original downloaded through another replica')
|
||||
finally:
|
||||
compose('start', service)
|
||||
wait_ready(c)
|
||||
else:
|
||||
try:
|
||||
compose('stop', 's3')
|
||||
# Direct API request inside the network: LB excludes unready backends.
|
||||
script = '''import json, sys, urllib.request, urllib.error
|
||||
payload = json.load(sys.stdin)
|
||||
for method, path, body, headers in [
|
||||
("GET", "/health/ready", None, {}),
|
||||
("GET", payload["path"], None, {"Authorization": "Bearer " + payload["token"]}),
|
||||
("POST", payload["upload_path"], bytes.fromhex(payload["bytes"]),
|
||||
{"Authorization": "Bearer " + payload["token"], "Content-Type": "image/png"}),
|
||||
]:
|
||||
req = urllib.request.Request("http://localhost:8080" + path, data=body, headers=headers, method=method)
|
||||
try:
|
||||
urllib.request.urlopen(req, timeout=15)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 503, error.code
|
||||
document = json.load(error)
|
||||
assert document["error"]["code"] == "unavailable"
|
||||
assert document["error"]["request_id"] == error.headers["X-Request-Id"]
|
||||
else:
|
||||
raise AssertionError("S3 outage was not reported")
|
||||
assert urllib.request.urlopen("http://localhost:8080/health/live").status == 200
|
||||
print("PASS: S3 outage gives 503 for readiness, download and upload; liveness stays 200")
|
||||
'''
|
||||
payload = {'path': content_path, 'token': bob['token'], 'bytes': data.hex(),
|
||||
'upload_path': '/api/v1/chats/' + chat['id'] + '/attachments?filename=outage.png'}
|
||||
print(compose('exec', '-T', 'api-a', '/app/.venv/bin/python', '-c', script,
|
||||
input=json.dumps(payload)).strip())
|
||||
finally:
|
||||
compose('start', 's3')
|
||||
wait_ready(c)
|
||||
check(c.call('GET', content_path, actor=bob)['bytes'] == data, 'original lost after S3 outage')
|
||||
print('PASS: original available again after S3 restart')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Attachment contract checks against the running lab4 stack."""
|
||||
import hashlib
|
||||
import http.client
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import uuid
|
||||
import zlib
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
from PIL import Image
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
c = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
|
||||
png = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
def upload(data, mime='image/png', filename='photo.png', status=201, actor=alice):
|
||||
return c.call('POST', path + quote(filename, safe=''), status, actor=actor, raw=data,
|
||||
headers={'Content-Type': mime}, schema='Attachment' if status == 201 else None)
|
||||
|
||||
for fmt, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]:
|
||||
buf = BytesIO()
|
||||
Image.new('RGB', (32, 20), 'blue').save(buf, fmt)
|
||||
data = buf.getvalue()
|
||||
att = upload(data, mime)['json']
|
||||
check(att['variants'] == [] and att['status'] == 'ready', 'wrong attachment state')
|
||||
check(att['sha256'] == hashlib.sha256(data).hexdigest(), 'wrong checksum')
|
||||
content_path = '/api/v1/attachments/' + att['id']
|
||||
check(c.call('GET', content_path, actor=bob, schema='Attachment')['json'] == att,
|
||||
'metadata changed')
|
||||
check(c.call('GET', content_path + '/content', actor=bob)['bytes'] == data, 'bytes changed')
|
||||
c.call('GET', content_path, 404, actor=eve)
|
||||
c.call('GET', content_path + '/content', 404, actor=eve)
|
||||
c.call('GET', content_path + '/content', 401)
|
||||
c.call('GET', content_path + '/content?variant=thumbnail', 404, actor=bob)
|
||||
message = c.message(bob, chat, '', attachments=[att['id']])['json']
|
||||
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages',
|
||||
actor=alice, schema='MessagePage')['json']['items']
|
||||
check(message in history, 'attachment message missing in history')
|
||||
print('PASS: PNG/JPEG originals, metadata, attachment-only messages and ACL')
|
||||
|
||||
for name in ('../x.png', 'x/y.png', 'x\\y.png', 'x\x00.png', 'x\n.png', 'x\x7f.png', ' ', 'x' * 256):
|
||||
upload(png, filename=name, status=400)
|
||||
upload(png, mime='image/jpeg', status=415)
|
||||
upload(b'not an image', status=415)
|
||||
upload(png[:30], status=415)
|
||||
upload(png, mime='application/octet-stream', status=415)
|
||||
upload(png, status=404, actor=eve)
|
||||
upload(b'x' * (10485760 + 1), status=413)
|
||||
|
||||
# Valid PNG header with an oversized canvas: reject before attempting pixel decoding.
|
||||
def chunk(kind, data):
|
||||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
|
||||
huge = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 8001, 5000, 8, 2, 0, 0, 0))
|
||||
huge += chunk(b'IDAT', zlib.compress(b'')) + chunk(b'IEND', b'')
|
||||
upload(huge, status=413)
|
||||
|
||||
# No Content-Length: limits must also work for chunked requests.
|
||||
url = urlsplit(c.base)
|
||||
connection = http.client.HTTPConnection(url.hostname, url.port, timeout=30)
|
||||
connection.request('POST', path + 'chunked.png', body=iter([b'x' * 65536] * 161),
|
||||
headers={'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'},
|
||||
encode_chunked=True)
|
||||
response = connection.getresponse()
|
||||
check(response.status == 413, 'chunked upload bypassed byte limit')
|
||||
response.read()
|
||||
connection.close()
|
||||
print('PASS: filename, MIME, malformed image, byte/pixel and chunked limits')
|
||||
|
||||
att = upload(png)['json']
|
||||
other_chat = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
for target, ids, code in ((chat, [str(uuid.uuid4())], 404),
|
||||
(other_chat, [att['id']], 404),
|
||||
(chat, [att['id'], att['id']], 400)):
|
||||
c.call('POST', '/api/v1/chats/' + target['id'] + '/messages', code, actor=alice,
|
||||
body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
key = uuid.uuid4().hex
|
||||
first = c.message(alice, chat, 'same', key=key)['json']
|
||||
check(c.message(alice, chat, 'same', key=key, attachments=[])['json'] == first,
|
||||
'omitted and empty attachment_ids differ')
|
||||
key = uuid.uuid4().hex
|
||||
first = c.message(alice, chat, '', key=key, attachments=[att['id']])['json']
|
||||
check(c.message(alice, chat, '', key=key, attachments=[att['id']])['json'] == first, 'replay differs')
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': 'changed', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': key})
|
||||
print('PASS: attachment scope, duplicates and idempotency normalization')
|
||||
|
||||
# Exact limits are accepted; original bytes (including PNG trailing data) survive.
|
||||
exact = png + b'\0' * (10485760 - len(png))
|
||||
att = upload(exact)['json']
|
||||
check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == exact,
|
||||
'10 MiB original changed')
|
||||
buf = BytesIO()
|
||||
Image.new('RGB', (8000, 5000)).save(buf, 'PNG')
|
||||
att = upload(buf.getvalue())['json']
|
||||
check(att['size_bytes'] == len(buf.getvalue()), '40M pixel upload failed')
|
||||
print('PASS: inclusive 10 MiB and 40 million pixel boundaries')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user