303 lines
15 KiB
Python
Executable File
303 lines
15 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Lab4 attachment contract checks: limits, MIME, names, ACL, dependency faults.
|
|
|
|
Expectations in this file are derived from contracts/README.md, not from the
|
|
current implementation:
|
|
* 10 MiB body limit and 40 MP pixel limit, checked before unbounded read/decode;
|
|
* Content-Type is validated against the bytes; corrupt/foreign formats are 415;
|
|
* filename is display-only, 1..255 code points, no '/', '\\\\', NUL or controls;
|
|
* foreign/unknown metadata and bytes are 404;
|
|
* files of another chat cannot be linked to a message (404);
|
|
* an unavailable S3 is 503 on upload/download/metadata, while invalid input is
|
|
still rejected as a user error (415), never masked as 500;
|
|
* an interrupted upload leaves neither an attachment row nor an object.
|
|
|
|
Python 3.9+, standard library only. Requires the running stand and Docker.
|
|
"""
|
|
import hashlib
|
|
import os
|
|
import socket
|
|
import sys
|
|
import time
|
|
import urllib.parse
|
|
import uuid
|
|
|
|
ROOT = __import__('pathlib').Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
sys.path.insert(0, str(ROOT / 'scripts'))
|
|
from client import Client, Failure, arguments, check # noqa: E402
|
|
import lab4_metrics as M # noqa: E402
|
|
|
|
CHECKS = 0
|
|
|
|
|
|
def ok(condition, message):
|
|
global CHECKS
|
|
CHECKS += 1
|
|
check(condition, message)
|
|
|
|
|
|
def upload(c, actor, chat_id, data, filename='test.png', content_type='image/png', status=201):
|
|
path = '/api/v1/chats/' + chat_id + '/attachments?filename=' + urllib.parse.quote(filename, safe='')
|
|
headers = {'Content-Type': content_type} if content_type else {}
|
|
return c.call('POST', path, status, actor=actor, raw=data, headers=headers,
|
|
schema='Attachment' if status == 201 else None)
|
|
|
|
|
|
def error_code(response):
|
|
return response['json']['error']['code']
|
|
|
|
|
|
def test_size_limits(c, alice, chat):
|
|
# 10 MiB + 1 byte: the declared Content-Length is enough for the handler to
|
|
# return 413 before it accepts or decodes the content.
|
|
oversized = os.urandom(10485761)
|
|
response = upload(c, alice, chat['id'], oversized, 'too-big.png', status=413)
|
|
ok(error_code(response) == 'payload_too_large', 'declared body over 10 MiB is not 413')
|
|
|
|
# A real, valid PNG just under the 10 MiB boundary is accepted and stored
|
|
# byte-for-byte.
|
|
boundary = M.png_random(1600, 2167)
|
|
ok(10485760 - len(boundary) < 100000, 'boundary fixture is not near 10 MiB: %d' % len(boundary))
|
|
att = upload(c, alice, chat['id'], boundary, 'boundary.png', status=201)['json']
|
|
ok(att['size_bytes'] == len(boundary), 'near-limit size changed')
|
|
ok(att['sha256'] == hashlib.sha256(boundary).hexdigest(), 'near-limit checksum changed')
|
|
download = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=alice)
|
|
ok(download['bytes'] == boundary, 'near-limit download differs')
|
|
|
|
empty = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=empty.png', 415,
|
|
actor=alice, raw=b'', headers={'Content-Type': 'image/png'})
|
|
ok(error_code(empty) == 'unsupported_media_type', 'empty body is not 415')
|
|
|
|
# More than 40 million decoded pixels, but a small compressed file: the
|
|
# limit must come from the decoded header, not from the byte size.
|
|
huge_pixels = M.png_solid(8000, 5001)
|
|
ok(len(huge_pixels) < 10485760, 'pixel-limit fixture unexpectedly large')
|
|
response = upload(c, alice, chat['id'], huge_pixels, 'pixels.png', status=413)
|
|
ok(error_code(response) == 'payload_too_large', '>40 MP is not 413')
|
|
ok(not any(item['size_bytes'] == len(huge_pixels) for item in M.s3_list()),
|
|
'>40 MP upload left an object in S3')
|
|
print('PASS size and pixel limits')
|
|
|
|
|
|
def test_mime_and_damage(c, alice, chat):
|
|
png = M.fixture_bytes('sample.png')
|
|
jpeg = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes()
|
|
|
|
response = upload(c, alice, chat['id'], png, 'wrong.jpg', 'image/jpeg', status=415)
|
|
ok(error_code(response) == 'unsupported_media_type', 'PNG declared as JPEG is not 415')
|
|
response = upload(c, alice, chat['id'], jpeg, 'wrong.png', 'image/png', status=415)
|
|
ok(error_code(response) == 'unsupported_media_type', 'JPEG declared as PNG is not 415')
|
|
response = upload(c, alice, chat['id'], b'not an image at all\n' * 20, 'text.png', 'image/png', status=415)
|
|
ok(error_code(response) == 'unsupported_media_type', 'non-image bytes are not 415')
|
|
response = upload(c, alice, chat['id'], png[:200], 'truncated.png', 'image/png', status=415)
|
|
ok(error_code(response) == 'unsupported_media_type', 'truncated PNG is not 415')
|
|
response = upload(c, alice, chat['id'], M.png_corrupt(), 'corrupt.png', 'image/png', status=415)
|
|
ok(error_code(response) == 'unsupported_media_type', 'corrupt PNG is not 415')
|
|
|
|
response = upload(c, alice, chat['id'], png, 'none.png', '', status=415)
|
|
ok(error_code(response) == 'unsupported_media_type', 'missing Content-Type is not 415')
|
|
response = upload(c, alice, chat['id'], png, 'plain.png', 'text/plain', status=415)
|
|
ok(error_code(response) == 'unsupported_media_type', 'text/plain is not 415')
|
|
response = upload(c, alice, chat['id'], png, 'multi.png', 'multipart/form-data; boundary=x', status=415)
|
|
ok(error_code(response) == 'unsupported_media_type', 'multipart is not 415')
|
|
|
|
att = upload(c, alice, chat['id'], jpeg, 'real.jpg', 'image/jpeg', status=201)['json']
|
|
ok(att['content_type'] == 'image/jpeg' and att['sha256'] == hashlib.sha256(jpeg).hexdigest(),
|
|
'JPEG upload metadata mismatch')
|
|
download = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=alice)
|
|
ok(download['bytes'] == jpeg and download['headers'].get_content_type() == 'image/jpeg',
|
|
'JPEG download mismatch')
|
|
|
|
# The display name is returned verbatim but never used as a key/path, and
|
|
# the public JSON never exposes storage internals.
|
|
unicode_name = 'фото 🚀.png'
|
|
named = upload(c, alice, chat['id'], png, unicode_name, status=201)['json']
|
|
ok(named['filename'] == unicode_name, 'Unicode filename changed')
|
|
ok('object_key' not in named and 'bucket' not in named, 'attachment JSON leaks storage internals')
|
|
print('PASS MIME, damage and filename display')
|
|
|
|
|
|
def test_filenames(c, alice, chat):
|
|
png = M.fixture_bytes('sample.png')
|
|
base = '/api/v1/chats/' + chat['id'] + '/attachments'
|
|
|
|
def expect(query, status):
|
|
c.call('POST', base + query, status, actor=alice, raw=png,
|
|
headers={'Content-Type': 'image/png'})
|
|
|
|
expect('', 400) # required parameter
|
|
expect('?filename=', 400) # empty
|
|
expect('?filename=a.png&filename=b.png', 400) # exactly once
|
|
expect('?filename=' + urllib.parse.quote('../evil.png', safe=''), 400)
|
|
expect('?filename=' + urllib.parse.quote('..\\evil.png', safe=''), 400)
|
|
expect('?filename=' + urllib.parse.quote('bad\x00name.png', safe=''), 400)
|
|
expect('?filename=' + urllib.parse.quote('bad\x01name.png', safe=''), 400)
|
|
expect('?filename=' + 'a' * 256, 400)
|
|
expect('?filename=' + urllib.parse.quote('a' * 255, safe=''), 201)
|
|
expect('?filename=' + urllib.parse.quote('./x.png', safe=''), 400)
|
|
print('PASS filename validation')
|
|
|
|
|
|
def test_acl(c, alice, bob, eve, chat):
|
|
att, content = c.attachment(alice, chat)
|
|
for suffix in ('', '/content'):
|
|
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
|
|
c.call('GET', '/api/v1/attachments/' + att['id'], 200, actor=bob)
|
|
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 200, actor=bob)
|
|
|
|
png = M.fixture_bytes('sample.png')
|
|
response = upload(c, eve, chat['id'], png, 'outsider.png', status=404)
|
|
ok(error_code(response) == 'not_found', 'outsider upload is not hidden as 404')
|
|
c.call('POST', '/api/v1/chats/not-a-uuid/attachments?filename=x.png', 400, actor=alice,
|
|
raw=png, headers={'Content-Type': 'image/png'})
|
|
c.call('POST', '/api/v1/chats/' + str(uuid.uuid4()) + '/attachments?filename=x.png', 404,
|
|
actor=alice, raw=png, headers={'Content-Type': 'image/png'})
|
|
|
|
eve_chat = c.call('POST', '/api/v1/chats', 201, actor=eve,
|
|
body={'title': 'Чужой чат', 'member_ids': [eve['id']]}, schema='Chat')['json']
|
|
foreign, _ = c.attachment(eve, eve_chat)
|
|
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
|
|
body={'text': 'чужое', 'attachment_ids': [foreign['id']]},
|
|
headers={'Idempotency-Key': uuid.uuid4().hex})
|
|
ok(error_code(response) == 'not_found', 'foreign attachment link is not 404')
|
|
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
|
|
body={'text': 'нет', 'attachment_ids': [str(uuid.uuid4())]},
|
|
headers={'Idempotency-Key': uuid.uuid4().hex})
|
|
print('PASS attachment ACL')
|
|
|
|
|
|
def test_interrupted_upload(c, alice, chat):
|
|
before_rows = int(M.psql("SELECT count(*) FROM attachments"))
|
|
before_objects = M.s3_count()
|
|
head = (
|
|
'POST /api/v1/chats/' + chat['id'] + '/attachments?filename=aborted.png HTTP/1.1\r\n'
|
|
'Host: 127.0.0.1\r\n'
|
|
'Authorization: Bearer ' + alice['token'] + '\r\n'
|
|
'Content-Type: image/png\r\n'
|
|
'Content-Length: 4194304\r\n'
|
|
'Connection: close\r\n\r\n'
|
|
).encode('ascii')
|
|
# Send only a prefix of the declared body and close: the server must abort
|
|
# the upload without creating metadata or an object.
|
|
parsed = urllib.parse.urlsplit(c.base)
|
|
connection = socket.create_connection((parsed.hostname, parsed.port or 80), timeout=5)
|
|
try:
|
|
connection.sendall(head)
|
|
connection.sendall(M.fixture_bytes()[:100000])
|
|
finally:
|
|
connection.close()
|
|
time.sleep(1.0)
|
|
after_rows = int(M.psql("SELECT count(*) FROM attachments"))
|
|
after_objects = M.s3_count()
|
|
ok(after_rows == before_rows, 'interrupted upload left an attachment row')
|
|
ok(after_objects == before_objects, 'interrupted upload left an S3 object')
|
|
print('PASS interrupted upload leaves no row/object')
|
|
|
|
|
|
def test_s3_unavailable(c, alice, bob, chat):
|
|
att, content = c.attachment(alice, chat)
|
|
try:
|
|
M.compose('stop', 's3')
|
|
time.sleep(1.0)
|
|
png = M.fixture_bytes('sample.png')
|
|
response = upload(c, alice, chat['id'], png, 'outage.png', status=503)
|
|
ok(error_code(response) == 'unavailable', 'S3 outage upload is not the contract 503')
|
|
response = c.call('GET', '/api/v1/attachments/' + att['id'], 503, actor=bob)
|
|
ok(error_code(response) == 'unavailable', 'S3 outage metadata is not 503')
|
|
response = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 503, actor=bob)
|
|
ok(error_code(response) == 'unavailable', 'S3 outage download is not 503')
|
|
# Invalid input is still a user error, not a fake 500/503: validation
|
|
# runs before any S3 access.
|
|
response = upload(c, alice, chat['id'], b'broken image', 'broken.png', status=415)
|
|
ok(error_code(response) == 'unsupported_media_type', 'bad image masked as dependency error')
|
|
# The message path does not depend on S3 and must keep working.
|
|
c.message(alice, chat, 'сообщение при недоступном S3')
|
|
finally:
|
|
M.compose('start', 's3')
|
|
M.wait_healthy('s3', 60)
|
|
# Docker's embedded DNS needs a moment to publish the restarted alias
|
|
# again; retry the first upload instead of asserting instantaneous recovery.
|
|
deadline = time.monotonic() + 30
|
|
while True:
|
|
try:
|
|
upload(c, alice, chat['id'], M.fixture_bytes('sample.png'), 'recovered.png', status=201)
|
|
break
|
|
except Failure:
|
|
if time.monotonic() >= deadline:
|
|
raise
|
|
time.sleep(0.5)
|
|
ok(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == content,
|
|
'existing attachment changed after S3 restart')
|
|
print('PASS unavailable S3 is 503, not 500, and recovers')
|
|
|
|
|
|
def test_database_unavailable(c, alice, chat):
|
|
try:
|
|
M.compose('stop', 'postgres')
|
|
deadline = time.monotonic() + 30
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
c.call('GET', '/health/ready', 503)
|
|
break
|
|
except Failure:
|
|
time.sleep(0.5)
|
|
else:
|
|
raise Failure('readiness did not become 503 while PostgreSQL was stopped')
|
|
live = c.call('GET', '/health/live', schema='Health')
|
|
ok(live['status'] == 200, 'liveness failed while PostgreSQL was down')
|
|
response = c.call('GET', '/api/v1/users/me', 503, actor=alice)
|
|
ok(error_code(response) == 'unavailable', 'DB outage /users/me is not 503')
|
|
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 503, actor=alice,
|
|
body={'text': 'пока БД лежит'}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
|
ok(error_code(response) == 'unavailable', 'DB outage message is not 503')
|
|
# Authentication shape is checked before the database: a malformed
|
|
# bearer header is still a user-level 401, not a masked 500/503.
|
|
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Bearer short'})
|
|
finally:
|
|
M.compose('start', 'postgres')
|
|
M.wait_ready(120)
|
|
c.message(alice, chat, 'после восстановления БД')
|
|
print('PASS unavailable PostgreSQL is 503, liveness stays up, data recovers')
|
|
|
|
|
|
def test_log_privacy(c, alice, chat):
|
|
sentinel = 'SENTINEL-' + uuid.uuid4().hex
|
|
c.message(alice, chat, sentinel)
|
|
password = alice['registration']['password']
|
|
token = alice['token']
|
|
api = M.compose_ids('api')
|
|
ok(len(api) >= 2, 'need at least two API containers to inspect both logs')
|
|
secret = M.env_value(api[0], 'S3_SECRET_KEY')
|
|
admin = M.env_value(api[0], 'S3_ADMIN_SECRET_KEY')
|
|
logs = M.compose('logs', '--no-color', 'api').stdout
|
|
ok(token not in logs, 'session token leaked into API logs')
|
|
ok(password not in logs, 'password leaked into API logs')
|
|
ok(sentinel not in logs, 'message text leaked into API logs')
|
|
ok(secret and secret not in logs, 'S3 API secret leaked into API logs')
|
|
ok(not admin, 'administrative S3 secret is present in the API container')
|
|
print('PASS no token/password/message/S3 secret in API logs')
|
|
|
|
|
|
def main():
|
|
args = arguments('Lab4 attachment limits, ACL and dependency faults; creates synthetic data')
|
|
c = Client(args.base_url, args.ca_file)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
test_size_limits(c, alice, chat)
|
|
test_mime_and_damage(c, alice, chat)
|
|
test_filenames(c, alice, chat)
|
|
test_acl(c, alice, bob, eve, chat)
|
|
test_interrupted_upload(c, alice, chat)
|
|
test_s3_unavailable(c, alice, bob, chat)
|
|
test_database_unavailable(c, alice, chat)
|
|
test_log_privacy(c, alice, chat)
|
|
print('PASS: lab4 attachment checks, %d assertions' % CHECKS)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except (Failure, ValueError, OSError) as exc:
|
|
print('FAIL:', str(exc))
|
|
raise SystemExit(1)
|