forked from mtusi2026/mtusi2026lab4
ЛР4: S3-вложения, приватный bucket и согласованность хранилищ (трек 2)
This commit is contained in:
Executable
+302
@@ -0,0 +1,302 @@
|
||||
#!/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)
|
||||
Executable
+650
@@ -0,0 +1,650 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Own black-box tests for lab4. They complement, and never weaken, tests/smoke.py.
|
||||
|
||||
The suite assumes a running stack (make up) and creates only synthetic data.
|
||||
It keeps the lab3 regression surface — exact JSON keys, strict input
|
||||
validation, Bearer-only business API, membership hiding as 404, keyset
|
||||
pagination, concurrent registration/messages/idempotency — and adds the lab4
|
||||
attachment regression: message attachment_ids, attachment-only messages and
|
||||
idempotency over the attachment payload. Deep upload limits and ACL negatives
|
||||
live in student-tests/attachment-checks.py.
|
||||
|
||||
Python 3.9+, standard library only.
|
||||
"""
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import datetime as dt
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, arguments, check, timestamp # noqa: E402
|
||||
|
||||
CHECKS = 0
|
||||
|
||||
|
||||
def ok(condition, message):
|
||||
global CHECKS
|
||||
CHECKS += 1
|
||||
check(condition, message)
|
||||
|
||||
|
||||
def expect_keys(payload, expected, where):
|
||||
ok(set(payload) == set(expected), where + ': JSON keys differ: ' + repr(sorted(payload)))
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
return 'Basic ' + base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii')
|
||||
|
||||
|
||||
def register(c, username=None, display_name=None, password=None):
|
||||
username = username or 'bb_' + uuid.uuid4().hex[:12]
|
||||
password = password or 'B3st-' + uuid.uuid4().hex
|
||||
display_name = display_name or 'Тестовый пользователь'
|
||||
body = {'username': username, 'display_name': display_name, 'password': password}
|
||||
user = c.call('POST', '/api/v1/users', 201, body=body, schema='User')['json']
|
||||
expect_keys(user, {'id', 'username', 'display_name', 'created_at'}, 'User')
|
||||
return {'id': user['id'], 'user': user, 'registration': body, 'password': password}
|
||||
|
||||
|
||||
def login(c, actor):
|
||||
response = c.call('POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': basic(actor['registration']['username'], actor['password'])},
|
||||
schema='Session')['json']
|
||||
expect_keys(response, {'token', 'token_type', 'expires_at', 'user'}, 'Session')
|
||||
actor['token'] = response['token']
|
||||
actor['session'] = response
|
||||
return actor
|
||||
|
||||
|
||||
def new_chat(c, actor, title, member_ids):
|
||||
return c.call('POST', '/api/v1/chats', 201, actor=actor,
|
||||
body={'title': title, 'member_ids': member_ids}, schema='Chat')['json']
|
||||
|
||||
|
||||
def key():
|
||||
return uuid.uuid4().hex
|
||||
|
||||
|
||||
def send_with_key(c, actor, chat, text, idem, headers=None):
|
||||
merged = {'Idempotency-Key': idem}
|
||||
merged.update(headers or {})
|
||||
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
|
||||
body={'text': text}, headers=merged, schema='Message')['json']
|
||||
|
||||
|
||||
def send(c, actor, chat, text, headers=None):
|
||||
return send_with_key(c, actor, chat, text, key(), headers)
|
||||
|
||||
|
||||
def all_messages(c, actor, chat, limit=100):
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limit)
|
||||
items, seen = [], set()
|
||||
for _ in range(1000):
|
||||
page = c.call('GET', path, actor=actor, schema='MessagePage')['json']
|
||||
items.extend(page['items'])
|
||||
if page['next_cursor'] is None:
|
||||
return items
|
||||
ok(page['next_cursor'] not in seen, 'message cursor cycle')
|
||||
seen.add(page['next_cursor'])
|
||||
from urllib.parse import quote
|
||||
path = ('/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limit) +
|
||||
'&cursor=' + quote(page['next_cursor'], safe=''))
|
||||
raise AssertionError('message pagination exceeded safety bound')
|
||||
|
||||
|
||||
def sorted_messages(items):
|
||||
return sorted(items, key=lambda x: (timestamp(x['created_at']), uuid.UUID(x['id']).int))
|
||||
|
||||
|
||||
def test_health(c):
|
||||
live = c.call('GET', '/health/live', schema='Health')
|
||||
ok(live['json'] == {'status': 'ok'}, 'liveness body')
|
||||
ok(bool(live['headers'].get('X-Request-Id')), 'liveness X-Request-Id')
|
||||
ok(bool(live['headers'].get('X-Instance-Id')), 'liveness X-Instance-Id')
|
||||
ready = c.call('GET', '/health/ready', schema='Health')
|
||||
ok(ready['json'] == {'status': 'ok'}, 'readiness body')
|
||||
print('PASS health')
|
||||
|
||||
|
||||
def test_registration_and_login(c):
|
||||
alice = register(c)
|
||||
bob = register(c)
|
||||
login(c, alice)
|
||||
login(c, bob)
|
||||
|
||||
ok(len(alice['session']['token']) >= 32, 'session token shorter than contract minimum')
|
||||
ok(alice['session']['token_type'] == 'Bearer', 'token_type')
|
||||
ok(timestamp(alice['session']['expires_at']) > dt.datetime.now(dt.timezone.utc), 'expiry in the past')
|
||||
ok(alice['session']['user'] == alice['user'], 'session user differs from created user')
|
||||
|
||||
# Duplicate username, including a different display name/password.
|
||||
c.call('POST', '/api/v1/users', 409, body={
|
||||
'username': alice['registration']['username'],
|
||||
'display_name': 'Другой',
|
||||
'password': 'Another-password-123',
|
||||
})
|
||||
|
||||
# Wrong / unknown / malformed credentials all give the same Basic 401.
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': basic(alice['registration']['username'], 'wrong-password-123')})
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': basic('definitely_unknown', 'wrong-password-123')})
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic !!!!'})
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + base64.b64encode(b'no-colon').decode()})
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Bearer abcdefghijklmnopqrstuvwxyz'})
|
||||
|
||||
# Basic is not accepted on business endpoints; X-User-Id grants nothing.
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': basic(alice['registration']['username'], alice['password'])})
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Bearer ' + 'a' * 43})
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'X-User-Id ' + alice['id']})
|
||||
|
||||
me = c.call('GET', '/api/v1/users/me', actor=alice, headers={'X-User-Id': bob['id']}, schema='User')['json']
|
||||
ok(me['id'] == alice['id'], 'X-User-Id overrode the bearer identity')
|
||||
|
||||
# A UTF-8 password containing colons is valid and is not truncated at the
|
||||
# first colon by Basic parsing.
|
||||
unicode_password = 'pässwörd:with:12'
|
||||
unicode_user = register(c, password=unicode_password)
|
||||
login(c, unicode_user)
|
||||
ok(unicode_user['session']['user']['username'] == unicode_user['registration']['username'], 'unicode password login')
|
||||
|
||||
# Session JSON must never contain the password or its hash.
|
||||
serialized = json.dumps(alice['session'], ensure_ascii=False)
|
||||
for forbidden in ('password', 'argon2', 'salt'):
|
||||
ok(forbidden not in serialized, 'session leaks ' + forbidden)
|
||||
print('PASS registration/auth')
|
||||
|
||||
|
||||
def test_registration_validation(c):
|
||||
username = 'bb_' + uuid.uuid4().hex[:10]
|
||||
password = 'B3st-' + uuid.uuid4().hex
|
||||
valid = {'username': username, 'display_name': 'Имя', 'password': password}
|
||||
|
||||
def bad(body, status=400, raw=None, headers=None):
|
||||
c.call('POST', '/api/v1/users', status, body=body if raw is None else None, raw=raw,
|
||||
headers=headers)
|
||||
|
||||
bad({'username': username, 'display_name': 'Имя'})
|
||||
bad({'username': username, 'display_name': 'Имя', 'password': 'short'})
|
||||
bad({'username': username, 'display_name': 'Имя', 'password': 'p' * 129})
|
||||
bad({'username': username, 'display_name': 'Имя', 'password': ' ' * 12})
|
||||
bad({'username': 'ab', 'display_name': 'Имя', 'password': password})
|
||||
bad({'username': 'a' * 33, 'display_name': 'Имя', 'password': password})
|
||||
bad({'username': 'UPPER', 'display_name': 'Имя', 'password': password})
|
||||
bad({'username': 'bad-name', 'display_name': 'Имя', 'password': password})
|
||||
bad({'username': 'бвт', 'display_name': 'Имя', 'password': password})
|
||||
bad({'username': username, 'display_name': '', 'password': password})
|
||||
bad({'username': username, 'display_name': ' ', 'password': password})
|
||||
bad({'username': username, 'display_name': 'Имя', 'password': password, 'extra': 1})
|
||||
bad({'username': username, 'display_name': 'Имя', 'password': password, 'Password': 'x'})
|
||||
bad({'Username': username, 'display_name': 'Имя', 'password': password})
|
||||
bad({'username': username, 'display_name': 'Имя', 'password': 123456789012})
|
||||
bad({'username': None, 'display_name': 'Имя', 'password': password})
|
||||
bad({}, raw=b'{', headers={'Content-Type': 'application/json'})
|
||||
bad({}, raw=b'[]', headers={'Content-Type': 'application/json'})
|
||||
bad({}, status=415, raw=json.dumps(valid).encode(), headers={'Content-Type': 'text/plain'})
|
||||
bad({}, raw=(json.dumps(valid)[:-1] + ', "username": "x"}').encode(), headers={'Content-Type': 'application/json'})
|
||||
|
||||
# Exact code-point boundaries.
|
||||
long_name = register(c, display_name='😀' * 100)
|
||||
ok(long_name['user']['display_name'] == '😀' * 100, '100 code points display_name changed')
|
||||
c.call('POST', '/api/v1/users', 400, body={
|
||||
'username': 'bb_' + uuid.uuid4().hex[:10],
|
||||
'display_name': '😀' * 101,
|
||||
'password': password,
|
||||
})
|
||||
c.call('POST', '/api/v1/users', 400, body={
|
||||
'username': 'a' * 32 + 'b',
|
||||
'display_name': 'Имя', 'password': password,
|
||||
})
|
||||
register(c, username='a' * 24 + uuid.uuid4().hex[:8])
|
||||
print('PASS registration validation')
|
||||
|
||||
|
||||
def test_chats(c, alice, bob, eve):
|
||||
chat = new_chat(c, alice, 'Комната с Unicode 🚀', [alice['id'], bob['id']])
|
||||
ok(set(chat['member_ids']) == {alice['id'], bob['id']}, 'chat member set')
|
||||
expect_keys(chat, {'id', 'title', 'member_ids', 'created_at'}, 'Chat')
|
||||
|
||||
def bad(body, status=400):
|
||||
c.call('POST', '/api/v1/chats', status, actor=alice, body=body)
|
||||
|
||||
bad({'title': 'Без автора', 'member_ids': [bob['id']]})
|
||||
bad({'title': 'Дубликат', 'member_ids': [alice['id'], alice['id']]})
|
||||
bad({'title': 'Неизвестный', 'member_ids': [alice['id'], str(uuid.uuid4())]})
|
||||
bad({'title': 'Не UUID', 'member_ids': [alice['id'], 'not-a-uuid']})
|
||||
bad({'title': 'Слишком много', 'member_ids': [alice['id']] + [str(uuid.uuid4()) for _ in range(100)]})
|
||||
bad({'title': '', 'member_ids': [alice['id']]})
|
||||
bad({'title': ' ', 'member_ids': [alice['id']]})
|
||||
bad({'title': 'я' * 101, 'member_ids': [alice['id']]})
|
||||
bad({'title': 'Лишнее', 'member_ids': [alice['id']], 'extra': True})
|
||||
bad({'title': 'Нет списка'})
|
||||
|
||||
own = c.call('GET', '/api/v1/chats/' + chat['id'], actor=bob, schema='Chat')['json']
|
||||
ok(own['id'] == chat['id'], 'member cannot read chat')
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'], 404, actor=eve)
|
||||
c.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/not-a-uuid', 400, actor=alice)
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
|
||||
body={'text': 'чужое'}, headers={'Idempotency-Key': key()})
|
||||
|
||||
hidden = c.call('GET', '/api/v1/chats?limit=100', actor=eve, schema='ChatPage')['json']
|
||||
ok(all(item['id'] != chat['id'] for item in hidden['items']), 'foreign chat leaked into list')
|
||||
listed = c.call('GET', '/api/v1/chats?limit=100', actor=bob, schema='ChatPage')['json']
|
||||
ok(any(item['id'] == chat['id'] for item in listed['items']), 'member chat missing from list')
|
||||
print('PASS chats/membership')
|
||||
|
||||
|
||||
def test_messages(c, alice, bob, eve, chat):
|
||||
text = 'Привет 👋 e\u0301 中文'
|
||||
message = send(c, alice, chat, text)
|
||||
expect_keys(message, {'id', 'chat_id', 'sender_id', 'text', 'created_at', 'attachment_ids'}, 'Message')
|
||||
ok(message['attachment_ids'] == [], 'attachment_ids must default to an empty array')
|
||||
ok(message['text'] == text, 'message text changed')
|
||||
ok(message['sender_id'] == alice['id'] and message['chat_id'] == chat['id'], 'message identity')
|
||||
|
||||
# X-User-Id cannot substitute for the Bearer owner.
|
||||
spoofed = send(c, alice, chat, 'не от Боба', headers={'X-User-Id': bob['id']})
|
||||
ok(spoofed['sender_id'] == alice['id'], 'X-User-Id changed the message sender')
|
||||
|
||||
def bad(actor, body, status=400, raw=None, headers=None):
|
||||
merged = {'Idempotency-Key': key()}
|
||||
merged.update(headers or {})
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', status, actor=actor,
|
||||
body=body, raw=raw, headers=merged)
|
||||
|
||||
bad(alice, {'text': ''})
|
||||
bad(alice, {'text': ' '})
|
||||
bad(alice, {'text': None})
|
||||
bad(alice, {})
|
||||
bad(alice, {'text': 'x' * 4001})
|
||||
bad(alice, {'text': 'ok', 'sender_id': alice['id']})
|
||||
bad(alice, {'text': 'ok', 'attachment_ids': None})
|
||||
bad(alice, {'text': 'ok', 'attachment_ids': 'not-an-array'})
|
||||
bad(alice, {'text': 'ok', 'attachment_ids': ['not-a-uuid']})
|
||||
bad(alice, {'text': 'ok', 'attachment_ids': [str(uuid.uuid4()), str(uuid.uuid4())] * 6})
|
||||
bad(alice, {'Text': 'ok'})
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
|
||||
raw=b'{', headers={'Content-Type': 'application/json', 'Idempotency-Key': key()})
|
||||
# Resource access is checked before body parsing: a foreign chat with a
|
||||
# malformed body still looks like a missing chat.
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
|
||||
raw=b'{', headers={'Content-Type': 'application/json', 'Idempotency-Key': key()})
|
||||
|
||||
boundary = send(c, alice, chat, 'я' * 4000)
|
||||
ok(len(boundary['text']) == 4000, '4000 code point message changed')
|
||||
|
||||
history = all_messages(c, bob, chat)
|
||||
ok(any(item == boundary for item in history), 'member cannot read message history')
|
||||
print('PASS messages')
|
||||
|
||||
|
||||
def test_pagination(c, alice, bob):
|
||||
chat = new_chat(c, alice, 'Пагинация', [alice['id'], bob['id']])
|
||||
for index in range(23):
|
||||
send(c, alice if index % 2 == 0 else bob, chat, 'строка %02d' % index)
|
||||
|
||||
expected = sorted_messages(all_messages(c, alice, chat, limit=100))
|
||||
collected = []
|
||||
cursor = None
|
||||
limits = [7, 5, 100, 1, 3, 9]
|
||||
step = 0
|
||||
while True:
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=' + str(limits[step % len(limits)])
|
||||
if cursor:
|
||||
from urllib.parse import quote
|
||||
path += '&cursor=' + quote(cursor, safe='')
|
||||
page = c.call('GET', path, actor=bob, schema='MessagePage')['json']
|
||||
collected.extend(page['items'])
|
||||
step += 1
|
||||
if page['next_cursor'] is None:
|
||||
break
|
||||
cursor = page['next_cursor']
|
||||
ok(step < 100, 'pagination did not finish')
|
||||
ok(collected == expected, 'pagination lost, duplicated or reordered messages')
|
||||
ids = [item['id'] for item in collected]
|
||||
ok(len(ids) == len(set(ids)), 'pagination repeated an id')
|
||||
|
||||
first = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=3', actor=alice, schema='MessagePage')['json']
|
||||
ok(first['next_cursor'] is not None, 'first page cursor missing')
|
||||
other = new_chat(c, alice, 'Другой чат', [alice['id']])
|
||||
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + first['next_cursor'], 400, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=not-base64!!', 400, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=0', 400, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=101', 400, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=abc', 400, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=1&limit=2', 400, actor=alice)
|
||||
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=', 400, actor=alice)
|
||||
|
||||
# A message cursor is scoped to a chat and cannot continue the chat list.
|
||||
c.call('GET', '/api/v1/chats?cursor=' + first['next_cursor'], 400, actor=alice)
|
||||
listed = c.call('GET', '/api/v1/chats?limit=100', actor=alice, schema='ChatPage')['json']
|
||||
ok(any(item['id'] == chat['id'] for item in listed['items']), 'paginated chat missing from list')
|
||||
ok(any(item['id'] == other['id'] for item in listed['items']), 'other chat missing from list')
|
||||
print('PASS pagination')
|
||||
|
||||
|
||||
def test_concurrent_registration(c):
|
||||
username = 'race_' + uuid.uuid4().hex[:10]
|
||||
body = {'username': username, 'display_name': 'Гонка', 'password': 'Race-password-123'}
|
||||
|
||||
def attempt(_):
|
||||
local = Client(c.base)
|
||||
try:
|
||||
return local.call('POST', '/api/v1/users', (201, 409), body=body)['status']
|
||||
except Exception as exc: # failures are assertions for this test
|
||||
return 'error:' + type(exc).__name__
|
||||
|
||||
barrier = threading.Barrier(8)
|
||||
|
||||
def synchronized_attempt(index):
|
||||
barrier.wait()
|
||||
return attempt(index)
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
statuses = list(pool.map(synchronized_attempt, range(8)))
|
||||
ok(statuses.count(201) == 1, 'concurrent registration: expected exactly one 201, got ' + repr(statuses))
|
||||
ok(statuses.count(409) == 7, 'concurrent registration: expected seven 409, got ' + repr(statuses))
|
||||
c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': basic(username, 'Race-password-123')}, schema='Session')
|
||||
print('PASS concurrent registration')
|
||||
|
||||
|
||||
def test_concurrent_messages(c, alice, bob):
|
||||
chat = new_chat(c, alice, 'Конкурентная запись', [alice['id'], bob['id']])
|
||||
|
||||
def worker(index):
|
||||
local = Client(c.base)
|
||||
actor = alice if index % 2 == 0 else bob
|
||||
return local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
|
||||
body={'text': 'concurrent %02d' % index},
|
||||
headers={'Idempotency-Key': key()}, schema='Message')['json']
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
|
||||
messages = list(pool.map(worker, range(24)))
|
||||
ids = [message['id'] for message in messages]
|
||||
ok(len(ids) == 24 and len(set(ids)) == 24, 'concurrent messages produced duplicate ids')
|
||||
for index, message in enumerate(messages):
|
||||
ok(message['sender_id'] == (alice['id'] if index % 2 == 0 else bob['id']), 'concurrent sender mismatch')
|
||||
history = all_messages(c, alice, chat)
|
||||
ok(len(history) == 24, 'concurrent history has %d rows, want 24' % len(history))
|
||||
ok(sorted_messages(history) == history, 'concurrent history is not ordered by (created_at, id)')
|
||||
ok([item['text'] for item in history].count('concurrent 00') == 1, 'concurrent duplicate text')
|
||||
print('PASS concurrent messages')
|
||||
|
||||
|
||||
def test_logout(c, alice):
|
||||
second = login(c, {'id': alice['id'], 'user': alice['user'],
|
||||
'registration': alice['registration'], 'password': alice['password']})
|
||||
first_token = alice['token']
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor={'token': first_token})
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor={'token': first_token})
|
||||
me = c.call('GET', '/api/v1/users/me', actor=second, schema='User')['json']
|
||||
ok(me['id'] == alice['id'], 'logout revoked another session of the same user')
|
||||
alice['token'] = second['token']
|
||||
print('PASS logout')
|
||||
|
||||
|
||||
def test_instances(c, alice):
|
||||
"""One session served by at least two real processes through the LB."""
|
||||
seen = set()
|
||||
for _ in range(40):
|
||||
response = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
instance = response['headers']['X-Instance-Id']
|
||||
seen.add(instance)
|
||||
ok(not response['headers'].get('Set-Cookie'), 'LB introduced a sticky cookie')
|
||||
ok(len(seen) >= 2, 'only one X-Instance-Id observed; run the default >=2 replicas')
|
||||
ok(all(instance for instance in seen), 'empty X-Instance-Id')
|
||||
# The same token keeps working while the LB moves it between processes.
|
||||
ready = c.call('GET', '/health/ready', schema='Health')
|
||||
ok(ready['headers']['X-Instance-Id'] in seen, 'health and business endpoints disagree on replicas')
|
||||
missing = c.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=alice)
|
||||
ok(bool(missing['headers']['X-Instance-Id']), 'error response missing X-Instance-Id')
|
||||
ok(missing['json']['error']['request_id'] == missing['headers']['X-Request-Id'],
|
||||
'error request_id differs from X-Request-Id')
|
||||
print('PASS instances (%d observed) ' % len(seen))
|
||||
|
||||
|
||||
def test_idempotency(c, alice, bob, eve, chat):
|
||||
text = 'Идемпотентность ✅ e\u0301'
|
||||
idem = key()
|
||||
first = send_with_key(c, alice, chat, text, idem)
|
||||
expect_keys(first, {'id', 'chat_id', 'sender_id', 'text', 'created_at', 'attachment_ids'}, 'Message')
|
||||
replay = send_with_key(c, alice, chat, text, idem)
|
||||
ok(replay == first, 'sequential replay returned a different Message')
|
||||
|
||||
# JSON whitespace and escapes are not part of the semantic body.
|
||||
raw = json.dumps({'text': text}, ensure_ascii=True, indent=2).encode('utf-8')
|
||||
escaped = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
|
||||
actor=alice, raw=raw,
|
||||
headers={'Content-Type': 'application/json', 'Idempotency-Key': idem},
|
||||
schema='Message')['json']
|
||||
ok(escaped == first, 'semantically equal JSON did not replay the message')
|
||||
|
||||
# A different body with the same key is a conflict and must not append.
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': 'другой body'}, headers={'Idempotency-Key': idem})
|
||||
# The original body is still the recorded result after a conflict.
|
||||
ok(send_with_key(c, alice, chat, text, idem) == first, 'conflict replaced the stored result')
|
||||
|
||||
# Scope includes the user and the chat path, so the same key is independent.
|
||||
other = new_chat(c, alice, 'Другой чат идемпотентности', [alice['id'], bob['id']])
|
||||
other_message = send_with_key(c, alice, other, text, idem)
|
||||
ok(other_message['id'] != first['id'] and other_message['chat_id'] == other['id'],
|
||||
'same key leaked across chats')
|
||||
bob_message = send_with_key(c, bob, chat, text, idem)
|
||||
ok(bob_message['id'] != first['id'] and bob_message['sender_id'] == bob['id'],
|
||||
'same key leaked across users')
|
||||
# The outsider cannot replay or inspect alice's record: scope + access = 404.
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
|
||||
body={'text': text}, headers={'Idempotency-Key': idem})
|
||||
|
||||
# Header validation is exact ASCII [A-Za-z0-9._:-]{1,128}.
|
||||
def bad_key(value, status=400):
|
||||
headers = {} if value is None else {'Idempotency-Key': value}
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', status, actor=alice,
|
||||
body={'text': 'ключ'}, headers=headers)
|
||||
|
||||
bad_key(None)
|
||||
bad_key('')
|
||||
bad_key('bad key')
|
||||
bad_key('ключ'.encode('utf-8').decode('latin-1')) # raw non-ASCII header bytes
|
||||
bad_key('a' * 129)
|
||||
accepted = 'A.-_:z9' + 'x' * 121
|
||||
ok(len(accepted) == 128, 'test key length')
|
||||
boundary = send_with_key(c, alice, chat, 'максимальный ключ', accepted)
|
||||
ok(boundary['text'] == 'максимальный ключ', '128-character key rejected')
|
||||
|
||||
# Revoked/unknown session is checked before the idempotency record.
|
||||
temp = login(c, register(c))
|
||||
temp_chat = new_chat(c, temp, 'Сессия и ключ', [temp['id'], alice['id']])
|
||||
temp_key = key()
|
||||
keep = send_with_key(c, temp, temp_chat, 'до logout', temp_key)
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=temp)
|
||||
c.call('POST', '/api/v1/chats/' + temp_chat['id'] + '/messages', 401,
|
||||
actor={'token': temp['token']}, body={'text': 'до logout'},
|
||||
headers={'Idempotency-Key': temp_key})
|
||||
# A different user's valid session cannot inherit the record.
|
||||
c.call('POST', '/api/v1/chats/' + temp_chat['id'] + '/messages', 404, actor=bob,
|
||||
body={'text': 'до logout'}, headers={'Idempotency-Key': temp_key})
|
||||
ok(keep['sender_id'] == temp['id'], 'temporary message identity')
|
||||
print('PASS idempotency replay/conflict/scope/validation')
|
||||
|
||||
|
||||
def test_idempotency_concurrency(c, alice, bob, chat):
|
||||
"""Concurrent same-key POSTs through several replicas must be exactly-once."""
|
||||
text = 'конкурентная идемпотентность ' + uuid.uuid4().hex
|
||||
idem = key()
|
||||
barrier = threading.Barrier(16)
|
||||
|
||||
def worker(index):
|
||||
local = Client(c.base)
|
||||
barrier.wait()
|
||||
response = local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
|
||||
actor=alice, body={'text': text},
|
||||
headers={'Idempotency-Key': idem}, schema='Message')
|
||||
return response['json'], response['headers']['X-Instance-Id']
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
|
||||
results = list(pool.map(worker, range(16)))
|
||||
ids = {item['id'] for item, _ in results}
|
||||
instances = {instance for _, instance in results}
|
||||
ok(len(ids) == 1, 'concurrent replay returned %d distinct messages' % len(ids))
|
||||
ok(len(instances) >= 2, 'concurrent replay did not cross replicas: ' + repr(instances))
|
||||
history = [m for m in all_messages(c, bob, chat) if m['text'] == text]
|
||||
ok(len(history) == 1, 'concurrent replay appended %d rows' % len(history))
|
||||
|
||||
# Different bodies racing for one key: one winner, one row, the rest 409.
|
||||
mixed_key = key()
|
||||
barrier = threading.Barrier(12)
|
||||
|
||||
def mixed(index):
|
||||
local = Client(c.base)
|
||||
payload = 'вариант A' if index % 2 == 0 else 'вариант B'
|
||||
barrier.wait()
|
||||
try:
|
||||
response = local.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', (201, 409),
|
||||
actor=bob, body={'text': payload},
|
||||
headers={'Idempotency-Key': mixed_key}, schema='Message')
|
||||
return response['status'], response['json']
|
||||
except Exception as exc: # noqa: BLE001 - a status other than 201/409 is a failure below
|
||||
return 'error:' + type(exc).__name__, None
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
|
||||
outcomes = list(pool.map(mixed, range(12)))
|
||||
statuses = [status for status, _ in outcomes]
|
||||
ok(set(statuses) <= {201, 409}, 'mixed race produced unexpected results: ' + repr(statuses))
|
||||
winners = [payload for status, payload in outcomes if status == 201]
|
||||
ok(len({item['id'] for item in winners}) == 1, 'mixed race produced more than one message')
|
||||
ok(any(status == 409 for status in statuses), 'mixed race did not produce a conflict')
|
||||
stored = [m for m in all_messages(c, alice, chat)
|
||||
if m['text'] in ('вариант A', 'вариант B') and m['id'] == winners[0]['id']]
|
||||
ok(len(stored) == 1, 'mixed race stored a different or duplicate message')
|
||||
print('PASS concurrent idempotency across %d replicas' % len(instances))
|
||||
|
||||
|
||||
def upload(c, actor, chat, raw=None, filename='sample.png', content_type='image/png', status=201):
|
||||
if raw is None:
|
||||
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
return c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename,
|
||||
status, actor=actor, raw=raw, headers={'Content-Type': content_type},
|
||||
schema='Attachment' if status == 201 else None)
|
||||
|
||||
|
||||
def test_attachments(c, alice, bob, eve, chat):
|
||||
att, content = c.attachment(alice, chat)
|
||||
expect_keys(att, {'id', 'chat_id', 'owner_id', 'filename', 'content_type', 'size_bytes',
|
||||
'sha256', 'status', 'variants', 'error_code', 'created_at', 'updated_at'}, 'Attachment')
|
||||
ok(att['status'] == 'ready' and att['variants'] == [] and att['error_code'] is None,
|
||||
'lab4 upload must return ready with no variants and no error')
|
||||
|
||||
# A message may be attachment-only: text="" is legal with at least one
|
||||
# attachment of this chat, and the order of ids is preserved.
|
||||
second, _ = c.attachment(alice, chat)
|
||||
message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [second['id'], att['id']]},
|
||||
headers={'Idempotency-Key': key()}, schema='Message')['json']
|
||||
ok(message['text'] == '' and message['attachment_ids'] == [second['id'], att['id']],
|
||||
'attachment-only message lost text or order')
|
||||
history = all_messages(c, bob, chat)
|
||||
ok(any(item == message for item in history), 'member cannot read a message with attachments')
|
||||
|
||||
# Both endpoints enforce chat membership; a foreign id is indistinguishable
|
||||
# from an absent one.
|
||||
for suffix in ('', '/content'):
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
|
||||
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=alice)
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 200, actor=bob)
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=original', 200, actor=bob)
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', 404, actor=bob)
|
||||
|
||||
# An attachment from another chat cannot be linked, even by its owner.
|
||||
eve_chat = new_chat(c, eve, 'Чужой чат', [eve['id']])
|
||||
foreign, _ = c.attachment(eve, eve_chat)
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
|
||||
body={'text': 'чужая картинка', 'attachment_ids': [foreign['id']]},
|
||||
headers={'Idempotency-Key': key()})
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
|
||||
body={'text': 'нет такой', 'attachment_ids': [str(uuid.uuid4())]},
|
||||
headers={'Idempotency-Key': key()})
|
||||
# The owner of the foreign attachment still cannot link it here.
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=eve,
|
||||
body={'text': 'чужое', 'attachment_ids': [foreign['id']]},
|
||||
headers={'Idempotency-Key': key()})
|
||||
# And the same attachment works in its own chat.
|
||||
own = c.call('POST', '/api/v1/chats/' + eve_chat['id'] + '/messages', 201, actor=eve,
|
||||
body={'text': '', 'attachment_ids': [foreign['id']]},
|
||||
headers={'Idempotency-Key': key()}, schema='Message')['json']
|
||||
ok(own['attachment_ids'] == [foreign['id']], 'attachment cannot be used in its own chat')
|
||||
|
||||
# Attachment ids are unique, limited to ten and syntactically valid UUIDs.
|
||||
for ids in ([att['id']] * 2,
|
||||
[str(uuid.uuid4()) for _ in range(11)],
|
||||
['not-a-uuid']):
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
|
||||
body={'text': 'x', 'attachment_ids': ids},
|
||||
headers={'Idempotency-Key': key()})
|
||||
|
||||
# Idempotency covers the attachment payload: [] is the same as an absent
|
||||
# field, while a different set of ids with the same key is a conflict.
|
||||
plain_key = key()
|
||||
plain = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
|
||||
body={'text': 'без вложений'}, headers={'Idempotency-Key': plain_key},
|
||||
schema='Message')['json']
|
||||
explicit = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
|
||||
body={'text': 'без вложений', 'attachment_ids': []},
|
||||
headers={'Idempotency-Key': plain_key}, schema='Message')['json']
|
||||
ok(explicit == plain, 'absent attachment_ids and [] are not semantically equal')
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': 'без вложений', 'attachment_ids': [att['id']]},
|
||||
headers={'Idempotency-Key': plain_key})
|
||||
with_key = key()
|
||||
first = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [att['id']]},
|
||||
headers={'Idempotency-Key': with_key}, schema='Message')['json']
|
||||
replay = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [att['id']]},
|
||||
headers={'Idempotency-Key': with_key}, schema='Message')['json']
|
||||
ok(replay == first, 'attachment message replay differs')
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [second['id']]},
|
||||
headers={'Idempotency-Key': with_key})
|
||||
print('PASS attachments and message links')
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab4 own black-box suite; creates synthetic data')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
test_health(c)
|
||||
alice = register(c)
|
||||
bob = register(c)
|
||||
eve = register(c)
|
||||
login(c, alice)
|
||||
login(c, bob)
|
||||
login(c, eve)
|
||||
test_registration_and_login(c)
|
||||
test_registration_validation(c)
|
||||
test_chats(c, alice, bob, eve)
|
||||
chat = new_chat(c, alice, 'Основной чат blackbox', [alice['id'], bob['id']])
|
||||
test_messages(c, alice, bob, eve, chat)
|
||||
test_attachments(c, alice, bob, eve, chat)
|
||||
test_instances(c, alice)
|
||||
test_idempotency(c, alice, bob, eve, chat)
|
||||
test_idempotency_concurrency(c, alice, bob, chat)
|
||||
test_pagination(c, alice, bob)
|
||||
test_concurrent_registration(c)
|
||||
test_concurrent_messages(c, alice, bob)
|
||||
test_logout(c, alice)
|
||||
print('PASS: lab4 student black-box suite, %d checks' % CHECKS)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print('FAIL:', exc)
|
||||
raise SystemExit(1)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 8.6 KiB |
Reference in New Issue
Block a user