This commit is contained in:
2026-10-29 15:00:36 +03:00
parent ec540a1a72
commit 1706ddca25
56 changed files with 5935 additions and 19 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

+34
View File
@@ -0,0 +1,34 @@
"""Synthetic PNG builders for negative/limit tests (stdlib only, nothing stored in Git)."""
import os
import struct
import zlib
def chunk(kind, data):
body = kind + data
return struct.pack('>I', len(data)) + body + struct.pack('>I', zlib.crc32(body) & 0xffffffff)
def png(width, height, raw=None, level=6, color_type=2):
"""RGB (color_type=2) PNG; raw is the filtered scanline stream (default: random noise)."""
if raw is None:
row = 1 + 3 * width
raw = b''.join(b'\x00' + os.urandom(row - 1) for _ in range(height))
ihdr = struct.pack('>IIBBBBB', width, height, 8, color_type, 0, 0, 0)
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', ihdr) +
chunk(b'IDAT', zlib.compress(raw, level)) + chunk(b'IEND', b''))
def near_limit_png(limit=10 * 1024 * 1024):
"""Valid noise PNG a little below the byte limit (stored deflate blocks)."""
width = 1000
height = (limit - 64 * 1024) // (1 + 3 * width)
data = png(width, height, level=0)
assert len(data) <= limit, len(data)
return data
def bomb_png(width=20000, height=20000):
"""Header declares 400M pixels, the compressed payload is tiny."""
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' * 4096, 9)) + chunk(b'IEND', b''))
+175
View File
@@ -0,0 +1,175 @@
#!/usr/bin/env python3
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import sys
import threading
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, Failure, check
sys.path.insert(0, str(Path(__file__).resolve().parent))
import test_attachments
RESULTS = []
def case(name):
def wrap(fn):
def run(*a):
try:
detail = fn(*a)
RESULTS.append({'test': name, 'result': 'PASS', 'detail': detail})
print('PASS', name, '-', detail or '')
except Failure as exc:
RESULTS.append({'test': name, 'result': 'FAIL', 'detail': str(exc)})
print('FAIL', name, '-', exc)
return run
return wrap
def msg_path(chat):
return '/api/v1/chats/' + chat['id'] + '/messages'
def history(c, actor, chat):
out, cursor = [], None
while True:
q = '?limit=100' + ('&cursor=' + cursor if cursor else '')
page = c.call('GET', msg_path(chat) + q, actor=actor, schema='MessagePage')['json']
out += page['items']
cursor = page['next_cursor']
if not cursor:
return out
@case('one session served by >=2 replicas without re-login (no stickiness)')
def t_no_sticky(c, alice, bob, chat):
seen = {}
for _ in range(30):
iid = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id']
seen[iid] = seen.get(iid, 0) + 1
check(len(seen) >= 2, 'only one replica observed: %s' % seen)
return 'distribution %s' % sorted(seen.values())
@case('X-Instance-Id is present on errors and health too')
def t_instance_on_errors(c, alice, bob, chat):
r = c.call('GET', '/api/v1/chats/not-a-uuid', 400, actor=alice)
check(bool(r['headers'].get('X-Instance-Id')), 'missing on 400')
r = c.call('GET', '/api/v1/users/me', 401)
check(bool(r['headers'].get('X-Instance-Id')), 'missing on 401')
r = c.call('GET', '/health/ready', schema='Health')
check(bool(r['headers'].get('X-Instance-Id')), 'missing on health')
@case('Idempotency-Key missing or malformed -> 400, nothing stored')
def t_key_validation(c, alice, bob, chat):
before = len(history(c, alice, chat))
c.call('POST', msg_path(chat), 400, actor=alice, body={'text': 'без ключа'})
for bad in ('', 'a b', 'clé', 'x' * 129, 'a/b'):
c.call('POST', msg_path(chat), 400, actor=alice, body={'text': 'плохой ключ'},
headers={'Idempotency-Key': bad})
c.call('POST', msg_path(chat), 201, actor=alice, body={'text': 'граница ключа'},
headers={'Idempotency-Key': 'A-z0_9.:' + 'k' * 120})
check(len(history(c, alice, chat)) == before + 1, 'rejected requests created messages')
@case('concurrent replay of one key through different replicas -> exactly one message')
def t_concurrent_same_key(c, alice, bob, chat):
key = 'conc-' + uuid.uuid4().hex
text = 'Конкурентный повтор ' + key
n = 24
barrier = threading.Barrier(n)
raw = json.dumps({'text': text}, ensure_ascii=False).encode()
def send(_):
local = Client(c.base, timeout=10)
barrier.wait()
r = local.call('POST', msg_path(chat), 201, actor=alice, raw=raw,
headers={'Idempotency-Key': key, 'Content-Type': 'application/json'}, schema='Message')
return r['json'], r['headers']['X-Instance-Id']
with ThreadPoolExecutor(max_workers=n) as pool:
results = list(pool.map(send, range(n)))
bodies = {json.dumps(m, sort_keys=True) for m, _ in results}
instances = {i for _, i in results}
check(len(bodies) == 1, 'replays returned different messages: %d' % len(bodies))
check(len(instances) >= 2, 'all requests hit one replica; test does not prove cross-replica')
same = [m for m in history(c, bob, chat) if m['text'] == text]
check(len(same) == 1, 'expected exactly 1 stored message, found %d' % len(same))
return '%d parallel requests via %d replicas -> 1 message' % (n, len(instances))
@case('replay is semantic: JSON key order/whitespace does not matter; other body -> 409')
def t_semantic_replay(c, alice, bob, chat):
key = uuid.uuid4().hex
first = c.call('POST', msg_path(chat), 201, actor=alice, raw=b'{"text":"abc"}',
headers={'Idempotency-Key': key, 'Content-Type': 'application/json'}, schema='Message')
again = c.call('POST', msg_path(chat), 201, actor=alice, raw=b'{ "text" : "abc" }\n',
headers={'Idempotency-Key': key, 'Content-Type': 'application/json'}, schema='Message')
check(first['json'] == again['json'], 'replay returned another message')
c.call('POST', msg_path(chat), 409, actor=alice, body={'text': 'abd'}, headers={'Idempotency-Key': key})
third = c.call('POST', msg_path(chat), 201, actor=alice, body={'text': 'abc'},
headers={'Idempotency-Key': key}, schema='Message')
check(third['json'] == first['json'], 'stored result changed after 409')
@case('key scope = user + chat: same key is independent for other user / other chat')
def t_key_scope(c, alice, bob, chat):
key = 'shared-' + uuid.uuid4().hex
a = c.message(alice, chat, 'scope', key=key)['json']
b = c.message(bob, chat, 'scope', key=key)['json']
chat2 = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Второй', 'member_ids': [alice['id'], bob['id']]}, schema='Chat')['json']
a2 = c.message(alice, chat2, 'scope', key=key)['json']
check(len({a['id'], b['id'], a2['id']}) == 3, 'scopes collided')
check(b['sender_id'] == bob['id'], 'sender mixed up')
@case('replay re-checks the session and chat access')
def t_replay_rechecks_access(c, alice, bob, chat, eve):
key = uuid.uuid4().hex
c.message(alice, chat, 'access', key=key)
c.call('POST', msg_path(chat), 404, actor=eve, body={'text': 'access'}, headers={'Idempotency-Key': key})
c.call('POST', msg_path(chat), 401, body={'text': 'access'}, headers={'Idempotency-Key': key})
c.call('POST', msg_path(chat), 404, actor=eve, body={'text': ' '}, headers={'Idempotency-Key': key})
c.call('POST', msg_path(chat), 404, actor=eve, body={'text': 'x'})
@case('logout is visible on every replica immediately (shared sessions)')
def t_logout_shared(c, alice, bob, chat):
tmp = c.user('tmp')
c.call('GET', '/api/v1/users/me', actor=tmp, schema='User')
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=tmp)
seen = set()
for _ in range(10):
seen.add(c.call('GET', '/api/v1/users/me', 401, actor=tmp)['headers']['X-Instance-Id'])
check(len(seen) >= 2, 'revocation checked on one replica only')
return 'revoked token rejected by %d replicas' % len(seen)
def main():
import argparse
p = argparse.ArgumentParser()
p.add_argument('--base-url', default='http://localhost:8080')
p.add_argument('--json', default=None)
a = p.parse_args()
c = Client(a.base_url, timeout=60)
alice, bob, eve, chat = c.bootstrap()
for t in (t_no_sticky, t_instance_on_errors, t_key_validation, t_concurrent_same_key,
t_semantic_replay, t_key_scope, t_logout_shared):
t(c, alice, bob, chat)
t_replay_rechecks_access(c, alice, bob, chat, eve)
for needs_eve, t in test_attachments.register(case, history, msg_path):
t(c, alice, bob, chat, *([eve] if needs_eve else []))
failed = [r for r in RESULTS if r['result'] != 'PASS']
print('%d/%d passed' % (len(RESULTS) - len(failed), len(RESULTS)))
if a.json:
Path(a.json).write_text(json.dumps(RESULTS, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
sys.exit(1 if failed else 0)
if __name__ == '__main__':
main()
+181
View File
@@ -0,0 +1,181 @@
"""Lab4 attachment cases; registered by run_tests.py (same case() harness)."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import os
from pathlib import Path
import threading
import uuid
from urllib.parse import quote
from client import Client, check
import imagegen
FIXTURES = Path(__file__).resolve().parent / 'fixtures'
PNG = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
JPG = (FIXTURES / 'sample.jpg').read_bytes()
def register(case, history, msg_path):
"""Return the list of (needs_eve, fn) cases bound to the runner's helpers."""
def upload(c, actor, chat, data, ctype='image/png', name='sample.png', expected=201):
r = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + quote(name, safe=''),
expected, actor=actor, raw=data, headers={'Content-Type': ctype},
schema='Attachment' if expected == 201 else None)
return r['json']
@case('PNG and JPEG upload/download byte-exact with true Content-Type')
def t_upload_formats(c, alice, bob, chat):
for data, ctype, name in ((PNG, 'image/png', 'a.png'), (JPG, 'image/jpeg', 'b.jpg')):
att = upload(c, alice, chat, data, ctype, name)
check(att['content_type'] == ctype and att['size_bytes'] == len(data), 'metadata mismatch')
check(att['sha256'] == hashlib.sha256(data).hexdigest(), 'sha256 mismatch')
check(att['status'] == 'ready' and att['variants'] == [] and att['error_code'] is None, 'lab4 state')
meta = c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')['json']
check(meta == att, 'GET metadata differs from POST')
got = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
check(got['bytes'] == data and got['headers'].get_content_type() == ctype, 'download differs')
check(got['headers'].get('X-Content-Type-Options') == 'nosniff', 'nosniff missing')
return 'png %d B, jpeg %d B' % (len(PNG), len(JPG))
@case('size limit: valid ~10 MiB image accepted, 10 MiB + 1 byte -> 413')
def t_size_limit(c, alice, bob, chat):
near = imagegen.near_limit_png()
att = upload(c, alice, chat, near, name='near-limit.png')
got = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=alice)
check(hashlib.sha256(got['bytes']).hexdigest() == att['sha256'] == hashlib.sha256(near).hexdigest(),
'big file changed')
over = PNG + b'\0' * (10 * 1024 * 1024 + 1 - len(PNG))
upload(c, alice, chat, over, name='over.png', expected=413)
return 'accepted %d B, rejected %d B' % (len(near), len(over))
@case('decompression bomb (400M px header, tiny body) -> 413 before decoding')
def t_bomb(c, alice, bob, chat):
data = imagegen.bomb_png()
r = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=bomb.png', 413,
actor=alice, raw=data, headers={'Content-Type': 'image/png'})
check(r['elapsed'] < 2, 'bomb took %.2fs: was it decoded?' % r['elapsed'])
return '%d B rejected in %.0f ms' % (len(data), r['elapsed'] * 1000)
@case('corrupted images and MIME spoofing -> 415, never 500')
def t_corrupt_and_spoof(c, alice, bob, chat):
cases = {
'truncated png': (PNG[:len(PNG) // 2], 'image/png'),
'garbage after png header': (PNG[:40] + os.urandom(2000), 'image/png'),
'truncated jpeg': (JPG[:len(JPG) // 2], 'image/jpeg'),
'png declared as jpeg': (PNG, 'image/jpeg'),
'jpeg declared as png': (JPG, 'image/png'),
'gif bytes as png': (b'GIF89a' + os.urandom(100), 'image/png'),
'html as png': (b'<html><script>alert(1)</script></html>', 'image/png'),
'text/plain content type': (PNG, 'text/plain'),
'multipart content type': (PNG, 'multipart/form-data; boundary=x'),
}
for name, (data, ctype) in cases.items():
r = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=x.png', 415,
actor=alice, raw=data, headers={'Content-Type': ctype})
check(r['json']['error']['code'] == 'unsupported_media_type', name)
upload(c, alice, chat, b'', name='empty.png', expected=400)
return '%d spoof/corrupt variants -> 415' % len(cases)
@case('dangerous filenames -> 400; Unicode display name kept as-is')
def t_filenames(c, alice, bob, chat):
bad = ['../etc/passwd', 'a/b.png', 'a\\b.png', 'nul\x00.png', 'bell\x07.png', 'line\nbreak.png',
'', ' ', '.', '..', 'x' * 256, 'evil‮gnp.exe']
for name in bad:
upload(c, alice, chat, PNG, name=name, expected=400)
base = '/api/v1/chats/' + chat['id'] + '/attachments'
c.call('POST', base, 400, actor=alice, raw=PNG, headers={'Content-Type': 'image/png'})
c.call('POST', base + '?filename=a.png&filename=b.png', 400, actor=alice, raw=PNG,
headers={'Content-Type': 'image/png'})
nice = 'Фото кота 🐱 (1).png'
att = upload(c, alice, chat, PNG, name=nice)
check(att['filename'] == nice, 'filename changed')
long_ok = upload(c, alice, chat, PNG, name='я' * 255)
check(len(long_ok['filename']) == 255, '255 code points must pass')
return '%d bad names rejected' % len(bad)
@case('ACL: outsider gets 404 on upload, metadata, content; no token -> 401')
def t_attachment_acl(c, alice, bob, chat, eve):
att = upload(c, alice, chat, PNG)
upload(c, eve, chat, PNG, expected=404)
for suffix in ('', '/content', '/content?variant=original'):
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 401)
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()), 404, actor=alice)
c.call('GET', '/api/v1/attachments/not-a-uuid', 400, actor=alice)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', 404, actor=alice)
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=huge', 400, actor=alice)
@case('message attachment_ids: other chat / foreign / unknown -> 404, nothing stored')
def t_message_links(c, alice, bob, chat, eve):
# alice is a member of both chats: the file still must not cross the chat boundary
chat2 = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]}, schema='Chat')['json']
other = upload(c, alice, chat2, PNG)
eve_chat = c.call('POST', '/api/v1/chats', 201, actor=eve,
body={'title': 'Чат Евы', 'member_ids': [eve['id']]}, schema='Chat')['json']
foreign = upload(c, eve, eve_chat, PNG)
own = upload(c, alice, chat, PNG)
before = len(history(c, alice, chat))
for ids in ([other['id']], [foreign['id']], [str(uuid.uuid4())], [own['id'], other['id']]):
r = c.call('POST', msg_path(chat), 404, actor=alice, body={'text': 'x', 'attachment_ids': ids},
headers={'Idempotency-Key': uuid.uuid4().hex})
check(r['json']['error']['code'] == 'not_found', 'expected not_found')
check(len(history(c, alice, chat)) == before, 'rejected message was stored')
m = c.message(bob, chat, '', attachments=[own['id']])['json']
check(m['attachment_ids'] == [own['id']] and m['text'] == '', 'bob could not reference chat file')
listed = [x for x in history(c, alice, chat) if x['id'] == m['id']]
check(listed == [m], 'history lost attachment_ids')
@case('attachment_ids validation: duplicates, >10, bad UUID, empty text without files -> 400')
def t_message_validation(c, alice, bob, chat):
att = upload(c, alice, chat, PNG)
for body in ({'text': 'x', 'attachment_ids': [att['id'], att['id']]},
{'text': 'x', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]},
{'text': 'x', 'attachment_ids': ['nope']},
{'text': 'x', 'attachment_ids': 'nope'},
{'text': '', 'attachment_ids': []},
{'text': ' '}):
c.call('POST', msg_path(chat), 400, actor=alice, body=body,
headers={'Idempotency-Key': uuid.uuid4().hex})
ten = [upload(c, alice, chat, PNG)['id'] for _ in range(10)]
m = c.message(alice, chat, 'десять файлов', attachments=ten)['json']
check(m['attachment_ids'] == ten, 'order of attachment_ids changed')
@case('idempotency: missing attachment_ids == []; other attachment list -> 409')
def t_attachment_idempotency(c, alice, bob, chat):
key = uuid.uuid4().hex
first = c.message(alice, chat, 'idem', key=key)['json']
again = c.message(alice, chat, 'idem', key=key, attachments=[])['json']
check(first == again and first['attachment_ids'] == [], 'missing vs [] not equal')
att = upload(c, alice, chat, PNG)
c.call('POST', msg_path(chat), 409, actor=alice, body={'text': 'idem', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': key})
key2 = uuid.uuid4().hex
a = c.message(alice, chat, '', key=key2, attachments=[att['id']])['json']
b = c.message(alice, chat, '', key=key2, attachments=[att['id']])['json']
check(a == b, 'replay with attachments differs')
@case('10 concurrent uploads through both replicas: all 201, distinct ids, same bytes back')
def t_concurrent_uploads(c, alice, bob, chat):
n = 10
barrier = threading.Barrier(n)
def one(i):
local = Client(c.base, timeout=60)
barrier.wait()
r = local.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=p%d.png' % i, 201,
actor=alice, raw=PNG, headers={'Content-Type': 'image/png'}, schema='Attachment')
return r['json'], r['headers']['X-Instance-Id']
with ThreadPoolExecutor(max_workers=n) as pool:
res = list(pool.map(one, range(n)))
check(len({a['id'] for a, _ in res}) == n, 'ids collided')
for a, _ in res:
got = c.call('GET', '/api/v1/attachments/' + a['id'] + '/content', actor=bob)
check(got['bytes'] == PNG, 'content mixed up')
return '%d uploads via %d replicas' % (n, len({i for _, i in res}))
return [(False, t_upload_formats), (False, t_size_limit), (False, t_bomb), (False, t_corrupt_and_spoof),
(False, t_filenames), (False, t_message_validation), (False, t_attachment_idempotency),
(False, t_concurrent_uploads), (True, t_attachment_acl), (True, t_message_links)]