forked from mtusi2026/mtusi2026lab5
lab5
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
"""Контракт файлов: реальные изображения, лимиты, ACL и ключи сообщений."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import http.client
|
||||
import io
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
from urllib.parse import quote, urlsplit
|
||||
import uuid
|
||||
import zlib
|
||||
|
||||
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('Attachment negative and concurrent checks')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
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()
|
||||
headers = {'Content-Type': 'image/png'}
|
||||
att = c.call('POST', path+'sample.png', 202, actor=alice, raw=png, headers=headers, schema='Attachment')['json']
|
||||
check('object_key' not in att and 'url' not in att, 'private storage details leaked')
|
||||
for filename in ['../a.png', 'a\\b.png', 'x\x00.png', 'x\n.png', '..', ' ']:
|
||||
c.call('POST', path+quote(filename, safe=''), 400, actor=alice, raw=png, headers=headers)
|
||||
for data, mime in [(b'not an image', 'image/png'), (png[:30], 'image/png'),
|
||||
(png[:-12], 'image/png'), (png, 'image/jpeg'), (png, 'application/octet-stream')]:
|
||||
c.call('POST', path+'invalid.png', 415, actor=alice, raw=data, headers={'Content-Type': mime})
|
||||
jpeg = io.BytesIO()
|
||||
Image.new('RGB', (64, 64), 'red').save(jpeg, format='JPEG')
|
||||
data = jpeg.getvalue()
|
||||
j = c.call('POST', path+'real.jpg', 202, actor=alice, raw=data,
|
||||
headers={'Content-Type': 'image/jpeg'}, schema='Attachment')['json']
|
||||
j = c.wait_ready(alice,j)
|
||||
downloaded = c.call('GET', '/api/v1/attachments/'+j['id']+'/content', actor=bob)
|
||||
check(downloaded['bytes'] == data, 'JPEG bytes changed')
|
||||
c.call('POST', path+'broken.jpg', 415, actor=alice, raw=data[:-20], headers={'Content-Type': 'image/jpeg'})
|
||||
# Валидный IHDR заявляет >40M пикселей. Отклонение происходит до декодирования.
|
||||
ihdr = struct.pack('>IIBBBBB', 9000, 5000, 8, 2, 0, 0, 0)
|
||||
header = b'\x89PNG\r\n\x1a\n' + struct.pack('>I', len(ihdr)) + b'IHDR' + ihdr
|
||||
header += struct.pack('>I', zlib.crc32(b'IHDR'+ihdr))
|
||||
header += png[33:]
|
||||
c.call('POST', path+'huge-pixels.png', 413, actor=alice, raw=header, headers=headers)
|
||||
# Отправляем только headers заведомо большого файла: доказываем ранний byte limit.
|
||||
base = urlsplit(c.base)
|
||||
connection = http.client.HTTPConnection(base.hostname, base.port or 80, timeout=10)
|
||||
connection.putrequest('POST', path+'too-big.png')
|
||||
connection.putheader('Authorization', 'Bearer '+alice['token'])
|
||||
connection.putheader('Content-Type', 'image/png')
|
||||
connection.putheader('Content-Length', str(10485761))
|
||||
connection.endheaders()
|
||||
response = connection.getresponse()
|
||||
check(response.status == 413, 'oversized body was not rejected before reading')
|
||||
response.read(); connection.close()
|
||||
c.call('POST', path+'outsider.png', 404, actor=eve, raw=png, headers=headers)
|
||||
for suffix in ['', '/content']:
|
||||
c.call('GET', '/api/v1/attachments/'+att['id']+suffix, 404, actor=eve)
|
||||
ready = c.wait_ready(alice,att)
|
||||
c.call('GET', '/api/v1/attachments/'+att['id']+'/content?variant=unknown', 404, actor=bob)
|
||||
other_chat = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Другой чат', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
message_path = '/api/v1/chats/'+other_chat['id']+'/messages'
|
||||
c.call('POST', message_path, 404, actor=alice, body={'text': '', 'attachment_ids': [att['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
message_path = '/api/v1/chats/'+chat['id']+'/messages'
|
||||
for ids, code in [([str(uuid.uuid4())], 404), ([att['id'], att['id']], 400), ([att['id']]*11, 400)]:
|
||||
c.call('POST', message_path, code, actor=alice, body={'text': '', 'attachment_ids': ids},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
key = uuid.uuid4().hex
|
||||
def send(_):
|
||||
return Client(args.base_url).message(bob, chat, '', key=key, attachments=[att['id']])
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
replies = list(pool.map(send, range(16)))
|
||||
check(all(r['json'] == replies[0]['json'] for r in replies), 'attachment replay created different messages')
|
||||
check(len({r['headers']['X-Instance-Id'] for r in replies}) >= 2, 'attachment race did not cross replicas')
|
||||
# Отсутствие attachment_ids и [] одинаковы и для хеша повтора.
|
||||
text_key = uuid.uuid4().hex
|
||||
text_message = c.message(alice, chat, 'Только текст', key=text_key)['json']
|
||||
check(c.message(alice, chat, 'Только текст', key=text_key, attachments=[])['json'] == text_message,
|
||||
'default [] changes key semantics')
|
||||
check(att['sha256'] == hashlib.sha256(png).hexdigest(), 'wrong original checksum')
|
||||
print('PASS: PNG/JPEG, bytes/pixels limits, filename/MIME, ACL, attachment message replay')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Дополнения к публичному smoke. Не печатает и не сохраняет tokens."""
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def check_cursor_types(c, actor, path, cursor, schema):
|
||||
check(bool(cursor), 'test requires a real pagination cursor')
|
||||
payload = json.loads(base64.urlsafe_b64decode(cursor + '=' * (-len(cursor) % 4)))
|
||||
c.call('GET', path + '?cursor=' + quote(cursor, safe=''), actor=actor, schema=schema)
|
||||
invalid = []
|
||||
for field in ['created_at', 'id']:
|
||||
for value in [1, 1.5, None, True, [], {}, '', 'invalid']:
|
||||
invalid.append({**payload, field: value})
|
||||
invalid.extend([None, 1, True, [], 'cursor'])
|
||||
for value in invalid:
|
||||
encoded = base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip('=')
|
||||
instances = set()
|
||||
# Проверяем один и тот же cursor на обеих API за round-robin LB.
|
||||
for _ in range(8):
|
||||
response = c.call('GET', path + '?cursor=' + quote(encoded, safe=''), 400, actor=actor)
|
||||
check(response['json']['error']['code'] == 'invalid_request', 'incorrect cursor error code')
|
||||
instances.add(response['headers']['X-Instance-Id'])
|
||||
if len(instances) >= 2:
|
||||
break
|
||||
check(len(instances) >= 2, 'invalid cursor was not checked on two API instances')
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--expiry', action='store_true', help='API must run with TTL=2')
|
||||
args = arguments('Student API checks', configure)
|
||||
c = Client(args.base_url)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
if args.expiry:
|
||||
time.sleep(2.2)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
print('PASS: short TTL expiry')
|
||||
return
|
||||
registration = {'username': 'race_' + uuid4().hex[:12], 'display_name': 'Гонка',
|
||||
'password': 'Synthetic-password-42'}
|
||||
# Для гонки регистрируем оба допустимых исхода через urllib.
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
def register(_):
|
||||
req = urllib.request.Request(c.base + '/api/v1/users',
|
||||
data=json.dumps(registration).encode(),
|
||||
headers={'Content-Type': 'application/json'})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
return response.status
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
|
||||
codes = list(executor.map(register, range(8)))
|
||||
check(codes.count(201) == 1 and codes.count(409) == 7, 'username race failed')
|
||||
path = '/api/v1/chats/' + chat['id']
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice,
|
||||
body={'title': 'unknown member', 'member_ids': [alice['id'], str(uuid4())]})
|
||||
for body in [{'text': 'x', 'sender_id': eve['id']}, {'text': 4}, {'text': ' '}]:
|
||||
c.call('POST', path + '/messages', 400, actor=alice, body=body)
|
||||
c.call('GET', path + '/messages?limit=true', 400, actor=alice)
|
||||
c.call('GET', path + '/messages?cursor=not-a-cursor', 400, actor=alice)
|
||||
for n in range(3):
|
||||
c.message(alice, chat, 'read-after-write ' + str(n))
|
||||
page = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json']
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' +
|
||||
quote(page['next_cursor'], safe=''), 400, actor=alice)
|
||||
check_cursor_types(c, alice, path + '/messages', page['next_cursor'], 'MessagePage')
|
||||
chats = c.call('GET', '/api/v1/chats?limit=1', actor=alice, schema='ChatPage')['json']
|
||||
check_cursor_types(c, alice, '/api/v1/chats', chats['next_cursor'], 'ChatPage')
|
||||
history = c.call('GET', path + '/messages', actor=bob, schema='MessagePage')['json']['items']
|
||||
check(len(history) == 3 and history[-1]['text'] == 'read-after-write 2', 'read-after-write failed')
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
print('PASS: registration race, invalid input, cursor scope/types on two API, read-after-write, logout')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Проверка реального rollback после вставки чата и первого участника."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from uuid import uuid4
|
||||
import psycopg
|
||||
import os
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client
|
||||
from src.config import DATABASE_URL
|
||||
from src.migrate import migrate
|
||||
|
||||
migrate()
|
||||
migrate() # Повтор миграции не создаёт дубликаты.
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
user = db.execute('SELECT id FROM users LIMIT 1').fetchone()
|
||||
assert user, 'Сначала выполните smoke, чтобы создать синтетического пользователя'
|
||||
chat = uuid4()
|
||||
try:
|
||||
with db.transaction():
|
||||
db.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (chat, 'rollback test'))
|
||||
db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat, user[0]))
|
||||
# FK прерывает составную операцию ПОСЛЕ двух успешных INSERT.
|
||||
db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat, uuid4()))
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Expected foreign-key failure')
|
||||
assert db.execute('SELECT count(*) FROM chats WHERE id=%s', (chat,)).fetchone()[0] == 0
|
||||
assert db.execute('SELECT count(*) FROM chat_members WHERE chat_id=%s', (chat,)).fetchone()[0] == 0
|
||||
assert db.execute('SELECT count(*) FROM schema_migrations').fetchone()[0] == 4
|
||||
print('PASS: rollback of chat + members; migration reapplied twice')
|
||||
|
||||
c = Client(os.getenv('BASE_URL', 'http://localhost:8080'))
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
key = uuid4().hex
|
||||
original = c.message(alice, chat, 'До истечения ключа', key=key)['json']
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
# Без ожидания суток: сдвигаем именно persisted expiry, а не clock приложения.
|
||||
db.execute("UPDATE message_requests SET expires_at=now()-interval '1 second' "
|
||||
"WHERE chat_id=%s AND request_key=%s", (chat['id'], key))
|
||||
renewed = c.message(alice, chat, 'После истечения ключа', key=key)['json']
|
||||
assert renewed['id'] != original['id']
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
assert db.execute('SELECT count(*) FROM message_requests WHERE chat_id=%s AND request_key=%s',
|
||||
(chat['id'], key)).fetchone()[0] == 1
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
message = uuid4()
|
||||
try:
|
||||
with db.transaction():
|
||||
db.execute('INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s)',
|
||||
(message, chat['id'], bob['id'], 'atomic rollback'))
|
||||
# Ошибка сохранения результата должна откатить и сообщение.
|
||||
db.execute("INSERT INTO message_requests VALUES (%s,%s,%s,%s,%s,now())",
|
||||
(uuid4(), chat['id'], 'rollback', '0'*64, psycopg.types.json.Jsonb({})))
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Expected result-store failure')
|
||||
assert db.execute('SELECT count(*) FROM messages WHERE id=%s', (message,)).fetchone()[0] == 0
|
||||
print('PASS: persisted key expiry, atomic message/result rollback')
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Отказы Redis и PostgreSQL; старые токены и подтверждения после восстановления."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client
|
||||
from scripts.stack import command,wait,save
|
||||
|
||||
base=os.getenv('BASE_URL','http://localhost:8080');c=Client(base,timeout=15)
|
||||
alice,bob,_,chat=c.bootstrap();message=c.message(alice,chat,'До отказов')['json']
|
||||
att,data=c.attachment(alice,chat);att=c.wait_ready(alice,att)
|
||||
results={}
|
||||
try:
|
||||
command(['docker','compose','stop','cache'])
|
||||
for _ in range(6):c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
c.message(alice,chat,'Без кеша');results['redis']='PASS'
|
||||
finally:command(['docker','compose','up','-d','--wait','cache'])
|
||||
try:
|
||||
command(['docker','compose','stop','db']);time.sleep(4)
|
||||
codes=[]
|
||||
for path in ['/health/ready','/api/v1/users/me']:
|
||||
request=urllib.request.Request(base+path,headers={'Authorization':'Bearer '+alice['token']})
|
||||
try:
|
||||
with urllib.request.urlopen(request,timeout=10) as response:codes.append(response.status)
|
||||
except urllib.error.HTTPError as exc:codes.append(exc.code)
|
||||
assert codes==[503,503];results['postgres']=codes
|
||||
finally:
|
||||
command(['docker','compose','up','-d','--wait','db']);wait(2,base)
|
||||
page=c.call('GET','/api/v1/chats/'+chat['id']+'/messages',actor=bob,schema='MessagePage')['json']
|
||||
assert message in page['items']
|
||||
assert c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==data
|
||||
results['old_token_message_original_preserved']=True
|
||||
save('dependencies.json',results)
|
||||
print('PASS: Redis fallback, PostgreSQL 503 and recovery, old token/message/original preserved')
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Останавливаем именно API, принявшую upload, и скачиваем оригинал другой репликой."""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, Failure
|
||||
from scripts.stack import stop, wait, save, command
|
||||
|
||||
base = os.getenv('BASE_URL', 'http://localhost:8080')
|
||||
c = Client(base, timeout=3)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
data = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
response = c.call('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename=failover.png',
|
||||
202, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
target = response['headers']['X-Instance-Id']
|
||||
att = c.wait_ready(alice,response['json'])
|
||||
c.message(alice, chat, '', attachments=[att['id']])
|
||||
started = time.monotonic()
|
||||
errors = 0
|
||||
try:
|
||||
stopped = stop(target)
|
||||
while True:
|
||||
try:
|
||||
downloaded = c.call('GET', '/api/v1/attachments/'+att['id']+'/content', actor=bob)
|
||||
alias = downloaded['headers']['X-Instance-Id']
|
||||
assert alias != target and downloaded['bytes'] == data
|
||||
assert hashlib.sha256(downloaded['bytes']).hexdigest() == att['sha256']
|
||||
break
|
||||
except Failure:
|
||||
errors += 1
|
||||
if time.monotonic()-started > 10:
|
||||
raise
|
||||
time.sleep(.2)
|
||||
save('attachment_failover.json', dict(status='PASS', uploader=target, downloader=alias,
|
||||
recovery_seconds=time.monotonic()-started, failed_attempts=errors,
|
||||
original_size=len(data), checksum_verified=True, stop=stopped))
|
||||
print('PASS: upload API stopped, original downloaded by other API with existing token')
|
||||
finally:
|
||||
command(['docker', 'compose', 'start', 'api'])
|
||||
wait(2, base)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Проверки общего результата повтора через LB и несколько API."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Shared idempotency through LB')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Один результат для конкурентных повторов'
|
||||
|
||||
def send(_):
|
||||
return Client(args.base_url, args.ca_file).message(alice, chat, text, key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
responses = list(pool.map(send, range(32)))
|
||||
first = responses[0]['json']
|
||||
check(all(r['json'] == first and r['status'] == 201 for r in responses), 'replay differs')
|
||||
instances = {r['headers']['X-Instance-Id'] for r in responses}
|
||||
check(len(instances) >= 2, 'race did not cross API replicas')
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
history = c.call('GET', path, actor=bob, schema='MessagePage')['json']['items']
|
||||
check(len(history) == 1 and history[0] == first, 'concurrent replay created duplicates')
|
||||
c.call('POST', path, 409, body={'text': 'Другой текст'}, actor=alice,
|
||||
headers={'Idempotency-Key': key})
|
||||
for invalid in ['', 'bad key', 'a' * 129]:
|
||||
c.call('POST', path, 400, body={'text': text}, actor=alice,
|
||||
headers={'Idempotency-Key': invalid})
|
||||
c.call('POST', path, 400, body={'text': text}, actor=alice)
|
||||
# Тот же ключ независим для другого пользователя и другого чата.
|
||||
other = c.message(bob, chat, text, key=key)['json']
|
||||
check(other['id'] != first['id'], 'key scope must include user')
|
||||
chat2 = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Second', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
check(c.message(alice, chat2, text, key=key)['json']['id'] != first['id'], 'key scope must include chat')
|
||||
# Пробелы JSON не изменяют смысл текста и не должны менять результат.
|
||||
replay = c.call('POST', path, 201, actor=alice, raw=json.dumps({'text': text}, indent=2).encode(),
|
||||
headers={'Content-Type': 'application/json', 'Idempotency-Key': key}, schema='Message')
|
||||
check(replay['json'] == first, 'JSON formatting changed idempotency')
|
||||
c.call('POST', path, 404, actor=eve, body={'text': text}, headers={'Idempotency-Key': key})
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('POST', path, 401, actor=alice, body={'text': text}, headers={'Idempotency-Key': key})
|
||||
result = dict(status='PASS', concurrent_requests=32, observed_instances=len(instances),
|
||||
messages_after_race=len(history), conflict=409, invalid_key=400, logout=401)
|
||||
Path('evidence').mkdir(exist_ok=True)
|
||||
Path('evidence/idempotency.json').write_text(json.dumps(result, indent=2))
|
||||
print('PASS: shared idempotency, scope, conflict and auth on replay')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,183 @@
|
||||
"""Сценарии pipeline внутри сети стенда. Приватный контекст только в stdin/stdout оператора."""
|
||||
import argparse
|
||||
import base64
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client,check
|
||||
from src.jobs import connection,inspect,payload,event,replay,new_version
|
||||
from src.broker import connect,publish,STREAM,GROUP
|
||||
from src.storage import ObjectStore
|
||||
from src.cleanup import run as cleanup
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser();p.add_argument('mode',choices=['config','create','queued','wait','snapshot','duplicate','arm',
|
||||
'fault-fired','unready','published','drained','audit','missing-stage','restore-stage','replay','version','failed','cleanup','privacy','invalid-job'])
|
||||
p.add_argument('--phase');p.add_argument('--state',default='ready');p.add_argument('--timeout',type=int,default=100)
|
||||
args=p.parse_args();ctx=json.load(sys.stdin)
|
||||
if args.mode=='config':
|
||||
from src.config import JOB_MAX_ATTEMPTS,JOB_TIMEOUT,JOB_LEASE,STAGING_RETENTION,MAX_PENDING_JOBS,WORKER_CONCURRENCY
|
||||
return dict(job_max_attempts=JOB_MAX_ATTEMPTS,job_timeout_seconds=JOB_TIMEOUT,job_lease_seconds=JOB_LEASE,
|
||||
staging_retention_seconds=STAGING_RETENTION,max_pending_jobs=MAX_PENDING_JOBS,
|
||||
worker_concurrency=WORKER_CONCURRENCY,prefetch_per_consumer=1)
|
||||
c=Client(os.getenv('BASE_URL','http://localhost:8080'),timeout=15)
|
||||
fixture=(Path(__file__).resolve().parents[1]/'tests/fixtures/sample.png').read_bytes()
|
||||
storage=ObjectStore()
|
||||
if args.mode=='create':
|
||||
alice,bob,_,chat=c.bootstrap()
|
||||
response=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=pipeline.png',202,actor=alice,
|
||||
raw=fixture,headers={'Content-Type':'image/png'},schema='Attachment')
|
||||
att=response['json'];assert att['status']=='queued'
|
||||
with connection() as db:
|
||||
job=db.execute('SELECT * FROM jobs WHERE attachment_id=%s',(att['id'],)).fetchone()
|
||||
assert storage.head(job['staging_key']) and job['status']=='queued'
|
||||
return dict(actor=alice,reader=bob,chat=chat,attachment=att,job_id=str(job['id']),uploader=response['headers']['X-Instance-Id'])
|
||||
info=inspect(ctx['job_id']);job=info['job'];att=info['attachment']
|
||||
path='/api/v1/attachments/'+str(job['attachment_id'])
|
||||
if args.mode=='queued':
|
||||
result=c.call('GET',path,actor=ctx['actor'],schema='Attachment')['json'];assert result['status']=='queued'
|
||||
c.call('GET',path+'/content',409,actor=ctx['reader'])
|
||||
c.message(ctx['actor'],ctx['chat'],'',attachments=[str(job['attachment_id'])])
|
||||
c.message(ctx['actor'],ctx['chat'],'Worker выключен, сообщения работают')
|
||||
return dict(status='PASS',attachment_id=str(job['attachment_id']),job_id=ctx['job_id'],accepted_status=202,content_status=409)
|
||||
if args.mode in {'wait','fault-fired'}:
|
||||
deadline=time.monotonic()+args.timeout
|
||||
while time.monotonic()<deadline:
|
||||
info=inspect(ctx['job_id'])
|
||||
if args.mode=='fault-fired':
|
||||
if any(r['phase']==args.phase and r['fired_at'] is not None for r in info['faults']):return dict(status='PASS',phase=args.phase)
|
||||
elif info['job']['status']==args.state:return dict(status='PASS',state=args.state,attempts=info['job']['attempts'])
|
||||
time.sleep(.2)
|
||||
raise AssertionError('Pipeline deadline exceeded: '+args.mode)
|
||||
if args.mode=='unready':
|
||||
import urllib.request,urllib.error
|
||||
codes=[]
|
||||
for suffix in ['/health/ready',path+'/content']:
|
||||
request=urllib.request.Request(c.base+suffix,headers={'Authorization':'Bearer '+ctx['actor']['token']})
|
||||
try:
|
||||
with urllib.request.urlopen(request,timeout=10) as response:codes.append(response.status)
|
||||
except urllib.error.HTTPError as exc:codes.append(exc.code)
|
||||
assert codes==[503,503],codes
|
||||
return dict(status='PASS',readiness_and_content=codes)
|
||||
if args.mode=='audit':return info
|
||||
if args.mode in {'published','drained'}:
|
||||
client=connect();deadline=time.monotonic()+args.timeout
|
||||
try:
|
||||
while time.monotonic()<deadline:
|
||||
if args.mode=='published':
|
||||
current=inspect(ctx['job_id']);ids=[r['stream_id'] for r in current['outbox'] if r['published_at']]
|
||||
if ids and all(client.xrange(STREAM,identifier,identifier) for identifier in ids):
|
||||
return dict(status='PASS',stream_ids=ids)
|
||||
else:
|
||||
ids=ctx['stream_ids'];last=max(tuple(map(int,x.split('-'))) for x in ids)
|
||||
groups=client.xinfo_groups(STREAM);group=next(r for r in groups if r['name']==GROUP)
|
||||
delivered=tuple(map(int,group['last-delivered-id'].split('-')))
|
||||
pending={r['message_id'] for r in client.xpending_range(STREAM,GROUP,'-','+',10000)}
|
||||
if delivered>=last and not pending.intersection(ids):return dict(status='PASS',acked=len(ids))
|
||||
time.sleep(.2)
|
||||
finally:client.close()
|
||||
raise AssertionError('Broker state deadline exceeded')
|
||||
if args.mode=='arm':
|
||||
with connection() as db:
|
||||
db.execute('INSERT INTO pipeline_faults(job_id,phase) VALUES (%s,%s) ON CONFLICT (job_id,phase) DO UPDATE SET fired_at=NULL',
|
||||
(ctx['job_id'],args.phase))
|
||||
return dict(armed=True,phase=args.phase)
|
||||
if args.mode=='snapshot':
|
||||
current=c.call('GET',path,actor=ctx['reader'],schema='Attachment')['json']
|
||||
assert current['status']=='ready' and current['error_code'] is None
|
||||
content=c.call('GET',path+'/content',actor=ctx['reader'])['bytes']
|
||||
assert content==fixture
|
||||
variants={v['name']:v for v in current['variants']};assert set(variants)=={'thumbnail','crop','optimized'}
|
||||
digests={}
|
||||
for name,meta in variants.items():
|
||||
data=c.call('GET',path+'/content?variant='+name,actor=ctx['reader'])['bytes']
|
||||
assert len(data)==meta['size_bytes'] and hashlib.sha256(data).hexdigest()==meta['sha256']
|
||||
digests[name]=meta['sha256']
|
||||
keys=[]
|
||||
for prefix in ['originals/','variants/']:
|
||||
keys.extend(r['Key'] for r in storage.objects(prefix+str(job['attachment_id'])+'/'))
|
||||
expected=1+3
|
||||
# После новой версии прежние объекты остаются для аудита; текущий набор ровно 4.
|
||||
current_keys=[k for k in keys if '/v'+str(att['pipeline_version'])+'/' in k]
|
||||
assert len(current_keys)==expected and len(set(current_keys))==expected
|
||||
info=inspect(ctx['job_id'])
|
||||
assert info['job']['status']=='ready' and info['attachment']['current_job_id']==job['id']
|
||||
assert len([r for r in info['events'] if r['event']=='ready'])==1
|
||||
deadline=time.monotonic()+5
|
||||
while storage.head(info['job']['staging_key']) is not None and time.monotonic()<deadline:time.sleep(.1)
|
||||
assert storage.head(info['job']['staging_key']) is None,'Staging not cleaned after ready'
|
||||
return dict(status='PASS',attachment=current,job_id=ctx['job_id'],pipeline_version=att['pipeline_version'],
|
||||
attempts=info['job']['attempts'],current_keys=sorted(current_keys),all_final_keys=sorted(keys),
|
||||
variants_sha256=digests,original_sha256=hashlib.sha256(content).hexdigest(),
|
||||
ready_commits=1,staging_deleted=True,queued_to_ready_seconds=round((datetime.fromisoformat(current['updated_at'].replace('Z','+00:00'))-job['created_at']).total_seconds(),6),
|
||||
events=info['events'],outbox=info['outbox'])
|
||||
if args.mode=='duplicate':
|
||||
client=connect()
|
||||
try:
|
||||
result=[]
|
||||
for _ in range(ctx.get('copies',1)):
|
||||
result.append(publish(client,payload(job,ctx.get('attempt',max(1,job['attempts'])))))
|
||||
finally:client.close()
|
||||
return dict(stream_ids=result)
|
||||
if args.mode=='invalid-job':
|
||||
client=connect();bad=payload(job,max(1,job['attempts']));bad['url']='http://not-allowed.invalid/'
|
||||
try:identifier=publish(client,bad)
|
||||
finally:client.close()
|
||||
deadline=time.monotonic()+10
|
||||
while time.monotonic()<deadline:
|
||||
with connection() as db:
|
||||
row=db.execute('SELECT error_code FROM broker_rejections WHERE stream_id=%s',(identifier,)).fetchone()
|
||||
if row:return dict(status='PASS',error_code=row['error_code'])
|
||||
time.sleep(.2)
|
||||
raise AssertionError('Invalid broker message not rejected')
|
||||
if args.mode=='missing-stage':
|
||||
storage.delete(job['staging_key']);return dict(deleted=True)
|
||||
if args.mode=='restore-stage':
|
||||
storage.put(io.BytesIO(fixture),job['staging_key'],len(fixture),'image/png',hashlib.sha256(fixture).hexdigest(),
|
||||
base64.b64encode(hashlib.md5(fixture).digest()).decode())
|
||||
return dict(restored=True)
|
||||
if args.mode=='replay':return replay(job['id'])
|
||||
if args.mode=='version':
|
||||
result=new_version(job['attachment_id'],ctx.get('version',2))
|
||||
return dict(ctx,job_id=result['job_id'])
|
||||
if args.mode=='failed':
|
||||
failed=c.call('GET',path,actor=ctx['reader'],schema='Attachment')['json']
|
||||
assert failed['status']=='failed' and failed['error_code']
|
||||
c.call('GET',path+'/content',409,actor=ctx['reader'])
|
||||
c.call('POST','/api/v1/chats/'+ctx['chat']['id']+'/messages',409,actor=ctx['actor'],
|
||||
body={'text':'','attachment_ids':[str(job['attachment_id'])]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
return dict(status='PASS',error_code=failed['error_code'],attempts=job['attempts'],events=info['events'])
|
||||
if args.mode=='cleanup':
|
||||
# Вызывается при остановленном worker: текущий queued не должен быть удалён.
|
||||
old_key='staging/'+str(uuid.uuid4())+'/'+str(uuid.uuid4())
|
||||
def put(key):storage.put(io.BytesIO(fixture),key,len(fixture),'image/png',hashlib.sha256(fixture).hexdigest(),
|
||||
base64.b64encode(hashlib.md5(fixture).digest()).decode())
|
||||
put(old_key);time.sleep(3.2)
|
||||
fresh_key='staging/'+str(uuid.uuid4())+'/'+str(uuid.uuid4());put(fresh_key)
|
||||
dry=cleanup(2,False);assert storage.head(old_key)
|
||||
applied=cleanup(2,True)
|
||||
assert storage.head(old_key) is None and storage.head(fresh_key) and storage.head(job['staging_key'])
|
||||
storage.delete(fresh_key)
|
||||
return dict(status='PASS',orphan_removed=True,fresh_and_queued_preserved=True,dry_run=dry,apply=applied)
|
||||
if args.mode=='privacy':
|
||||
import urllib.request,urllib.error
|
||||
from src.config import S3_ENDPOINT,S3_BUCKET
|
||||
try:urllib.request.urlopen(S3_ENDPOINT+'/'+S3_BUCKET+'/'+att['object_key'],timeout=5)
|
||||
except urllib.error.HTTPError as exc:assert exc.code==403
|
||||
else:raise AssertionError('Public bucket')
|
||||
return dict(status='PASS',anonymous_get=403)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
result=main()
|
||||
print(json.dumps(result,ensure_ascii=False,default=str))
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Black-box grading evidence beyond the public smoke test."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def collect_messages(client, actor, chat, page_size=17):
|
||||
items = []
|
||||
cursor = None
|
||||
while True:
|
||||
path = f"/api/v1/chats/{chat['id']}/messages?limit={page_size}"
|
||||
if cursor:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
items.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Student negative, pagination and concurrency tests")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, outsider, chat = client.bootstrap()
|
||||
|
||||
client.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
400,
|
||||
raw=b'{"username":',
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
client.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
415,
|
||||
raw=b'{"username":"wrong_media","display_name":"Wrong"}',
|
||||
headers={"Content-Type": "text/plain"},
|
||||
)
|
||||
client.call("POST", "/api/v1/users", 409, body=alice["registration"])
|
||||
client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
400,
|
||||
actor=alice,
|
||||
body={"text": " \t"},
|
||||
)
|
||||
client.call("GET", f"/api/v1/chats/{chat['id']}", 404, actor=outsider)
|
||||
|
||||
prefix = "race-" + uuid.uuid4().hex + "-"
|
||||
|
||||
def send(worker_id):
|
||||
local = Client(args.base_url, args.ca_file)
|
||||
return [
|
||||
local.message(alice, chat, f"{prefix}{worker_id}-{index}")["json"]
|
||||
for index in range(10)
|
||||
]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
created = [message for batch in pool.map(send, range(10)) for message in batch]
|
||||
|
||||
check(len(created) == 100, "not all concurrent requests succeeded")
|
||||
check(len({message["id"] for message in created}) == 100, "duplicate message ids returned")
|
||||
|
||||
history = collect_messages(client, bob, chat)
|
||||
concurrent_history = [message for message in history if message["text"].startswith(prefix)]
|
||||
check(len(concurrent_history) == 100, "history does not contain exactly 100 concurrent messages")
|
||||
check(len({message["id"] for message in concurrent_history}) == 100, "history contains duplicates")
|
||||
check(
|
||||
history == sorted(history, key=lambda message: (message["created_at"], uuid.UUID(message["id"]).int)),
|
||||
"multi-page history is out of order",
|
||||
)
|
||||
|
||||
print("PASS: malformed JSON/media type, duplicate username, blank message, outsider access, pagination")
|
||||
print("PASS: 10 clients created exactly 100 unique messages")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Проверяем реальные форматы, EXIF orientation, alpha/white, размеры и метаданные."""
|
||||
import hashlib
|
||||
import io
|
||||
from pathlib import Path
|
||||
import sys
|
||||
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('Image pipeline variants');c=Client(args.base_url,args.ca_file,timeout=30)
|
||||
alice,bob,eve,chat=c.bootstrap()
|
||||
cases=[]
|
||||
image=Image.new('RGBA',(320,200),(255,0,0,0));out=io.BytesIO();image.save(out,format='PNG');image.close()
|
||||
cases.append(('alpha.png',out.getvalue(),'image/png',(256,160),(320,200)))
|
||||
image=Image.new('RGB',(32,20),'green');out=io.BytesIO();image.save(out,format='PNG');image.close()
|
||||
cases.append(('small.png',out.getvalue(),'image/png',(32,20),(32,20)))
|
||||
image=Image.new('RGB',(320,200),'blue');exif=Image.Exif();exif[274]=6;out=io.BytesIO()
|
||||
image.save(out,format='JPEG',exif=exif);image.close()
|
||||
cases.append(('orientation.jpg',out.getvalue(),'image/jpeg',(160,256),(200,320)))
|
||||
for filename,data,mime,thumb_size,optimized_size in cases:
|
||||
att=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename='+filename,202,actor=alice,
|
||||
raw=data,headers={'Content-Type':mime},schema='Attachment')['json']
|
||||
check(att['status']=='queued','202 must carry queued snapshot')
|
||||
c.message(alice,chat,'',attachments=[att['id']])
|
||||
att=c.wait_ready(alice,att)
|
||||
check(att['error_code'] is None,'ready has error')
|
||||
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==data,'original changed')
|
||||
variants={v['name']:v for v in att['variants']}
|
||||
check(set(variants)=={'thumbnail','crop','optimized'},'missing variants')
|
||||
for name,size,fmt,mime in [('thumbnail',thumb_size,'JPEG','image/jpeg'),('crop',(128,128),'JPEG','image/jpeg'),
|
||||
('optimized',optimized_size,'WEBP','image/webp')]:
|
||||
response=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+name,actor=bob)
|
||||
content=response['bytes'];meta=variants[name]
|
||||
check(response['headers'].get_content_type()==mime,'incorrect variant Content-Type')
|
||||
check(len(content)==meta['size_bytes'] and hashlib.sha256(content).hexdigest()==meta['sha256'],'variant checksum')
|
||||
with Image.open(io.BytesIO(content)) as result:
|
||||
result.load();check(result.format==fmt and result.size==size,'variant format/size')
|
||||
check((meta['width'],meta['height'])==size,'metadata dimensions')
|
||||
check(not result.getexif(),'EXIF leaked into variant')
|
||||
if filename=='alpha.png':check(all(v>=245 for v in result.convert('RGB').getpixel((0,0))),'alpha not composited on white')
|
||||
c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+name,404,actor=eve)
|
||||
print('PASS: thumbnail/crop/WebP bytes, sizes, EXIF orientation, white alpha, no upscaling, ACL')
|
||||
|
||||
|
||||
if __name__=='__main__':run(main)
|
||||
Reference in New Issue
Block a user