ЛР 4: S3-вложения и исследование согласованности — Майорова БВТ2301
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
"""Actual replica stop after upload, interrupted request, and dependency outages."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure
|
||||
|
||||
|
||||
def docker(*args, code=None):
|
||||
result = subprocess.run(['docker', *args], input=code, text=True, capture_output=True, check=True)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def instance(container):
|
||||
return docker('exec', container, 'python', '-c', "import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8080/health/live').headers['X-Instance-Id'])")
|
||||
|
||||
|
||||
def wait(c):
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Failure:
|
||||
if time.monotonic() > deadline:
|
||||
raise
|
||||
time.sleep(.2)
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
containers = docker('compose', 'ps', '-q', 'api').splitlines()
|
||||
assert len(containers) == 2
|
||||
report = {'replicas': []}
|
||||
for container in containers:
|
||||
alias = instance(container)
|
||||
for attempt in range(20):
|
||||
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=failover.png', 201, actor=alice, raw=content, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
if response['headers']['X-Instance-Id'] == alias:
|
||||
break
|
||||
else:
|
||||
raise AssertionError('Target uploader never observed')
|
||||
att = response['json']
|
||||
message = c.message(alice, chat, 'file before stop', attachments=[att['id']])['json']
|
||||
started = time.monotonic()
|
||||
try:
|
||||
docker('stop', '--time', '8', container)
|
||||
state = json.loads(docker('inspect', '--format', '{{json .State}}', container))
|
||||
assert not state['Running']
|
||||
while True:
|
||||
try:
|
||||
data = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
|
||||
assert data['headers']['X-Instance-Id'] != alias and data['bytes'] == content
|
||||
break
|
||||
except Failure:
|
||||
assert time.monotonic() - started < 10
|
||||
time.sleep(.1)
|
||||
c.message(alice, chat, 'write survives stop')
|
||||
report['replicas'].append({'container': container, 'uploader': alias, 'downloader': data['headers']['X-Instance-Id'], 'confirmed_stopped': True, 'recovery_seconds': round(time.monotonic() - started, 3), 'sha256': hashlib.sha256(data['bytes']).hexdigest(), 'exit_code': state['ExitCode'], 'oom_killed': state['OOMKilled']})
|
||||
finally:
|
||||
docker('compose', 'up', '-d', '--wait', '--no-deps', 'api')
|
||||
wait(c)
|
||||
# Send only part of a declared upload and terminate the TCP connection.
|
||||
name = 'interrupted_' + uuid.uuid4().hex + '.png'
|
||||
target = urlsplit(c.base)
|
||||
connection = socket.create_connection((target.hostname, target.port), timeout=3)
|
||||
headers = 'POST /api/v1/chats/' + chat['id'] + '/attachments?filename=' + name + ' HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer ' + alice['token'] + '\r\nContent-Type: image/png\r\nContent-Length: 10485760\r\nConnection: close\r\n\r\n'
|
||||
connection.sendall(headers.encode() + content[:30])
|
||||
connection.shutdown(socket.SHUT_WR)
|
||||
connection.close()
|
||||
time.sleep(.5)
|
||||
rows = docker('compose', 'exec', '-T', 'api', 'python', '-c', "import sys; sys.path.insert(0,'src'); from postgres import setting; import psycopg; c=psycopg.connect(setting('DATABASE_URL')); print(c.execute('SELECT count(*) FROM attachments WHERE 1=1 AND filename = %s', ('" + name + "',)).fetchone()[0])")
|
||||
assert rows == '0'
|
||||
report['interrupted_before_validation_leaves_no_intent'] = True
|
||||
# Observe API directly inside its container after the LB removes unready backends.
|
||||
probe_code = """import sys, json, urllib.request, urllib.error
|
||||
sys.path.insert(0,'src')
|
||||
from postgres import Store
|
||||
from common import APIError
|
||||
s=Store()
|
||||
try:
|
||||
s.ready(); ready=200
|
||||
except APIError as e: ready=e.status
|
||||
try:
|
||||
s.objects.get(%r); content_status=200
|
||||
except APIError as e: content_status=e.status
|
||||
live=urllib.request.urlopen('http://127.0.0.1:8080/health/live').status
|
||||
print(json.dumps({'ready':ready,'content':content_status,'live':live}))
|
||||
s.close()
|
||||
""" % ('originals/' + att['id'])
|
||||
try:
|
||||
docker('compose', 'stop', 's3')
|
||||
result = json.loads(docker('compose', 'exec', '-T', 'api', 'python', '-c', probe_code))
|
||||
assert result == {'ready': 503, 'content': 503, 'live': 200}
|
||||
report['s3_outage'] = result
|
||||
finally:
|
||||
docker('compose', 'up', '-d', '--wait', '--no-deps', 's3')
|
||||
wait(c)
|
||||
assert c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == content
|
||||
try:
|
||||
docker('compose', 'stop', 'redis')
|
||||
assert c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['json'] == alice['user']
|
||||
c.message(alice, chat, 'Redis fallback')
|
||||
report['redis_outage_fallback'] = True
|
||||
finally:
|
||||
docker('compose', 'up', '-d', '--wait', '--no-deps', 'redis')
|
||||
wait(c)
|
||||
print(json.dumps(report, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Small deterministic PNG helpers; generation happens outside measurement."""
|
||||
import random
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
|
||||
def chunk(name, data):
|
||||
return struct.pack('!I', len(data)) + name + data + struct.pack('!I', zlib.crc32(name + data) & 0xffffffff)
|
||||
|
||||
|
||||
def png(width, height, noise=False, rgb=True):
|
||||
channels = 3 if rgb else 1
|
||||
rand = random.Random(2301)
|
||||
encoded = zlib.compressobj(1)
|
||||
parts = []
|
||||
for _ in range(height):
|
||||
line = bytes(rand.getrandbits(8) for _ in range(width * channels)) if noise else b'\x7f' * (width * channels)
|
||||
parts.append(encoded.compress(b'\0' + line))
|
||||
parts.append(encoded.flush())
|
||||
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!IIBBBBB', width, height, 8, 2 if rgb else 0, 0, 0, 0)) + chunk(b'IDAT', b''.join(parts)) + chunk(b'IEND', b'')
|
||||
|
||||
|
||||
def bomb():
|
||||
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!IIBBBBB', 10000, 4001, 8, 2, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(b'x')) + chunk(b'IEND', b'')
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Render only measured local evidence; optional matplotlib dependency."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
|
||||
import matplotlib
|
||||
matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
evidence = ROOT / 'evidence'
|
||||
plt.rcParams.update({'font.family': 'DejaVu Sans', 'font.size': 10})
|
||||
research = json.loads((evidence / 'reconciliation.json').read_text())
|
||||
groups = {}
|
||||
for sample in research['scan_cost']:
|
||||
groups.setdefault(sample['counts']['metadata'], []).append(sample['elapsed_seconds'])
|
||||
fig, axes = plt.subplots(1, 2, figsize=(11, 4.2), layout='constrained')
|
||||
for size, samples in groups.items():
|
||||
axes[0].scatter([size] * len(samples), [x * 1000 for x in samples], color='#4e79a7', alpha=.65)
|
||||
axes[0].plot(sorted(groups), [statistics.median(groups[n]) * 1000 for n in sorted(groups)], color='#4e79a7', label='Медиана 3 прогонов')
|
||||
axes[0].set(xlabel='Число строк метаданных', ylabel='Полный обход, мс', title='Сверка PostgreSQL + S3')
|
||||
axes[0].legend()
|
||||
uploads = json.loads((evidence / 'uploads.json').read_text())['experiments']
|
||||
labels = ['0,51 MiB\n0,18 Мп', '7,21 MiB\n2,52 Мп', '0,51 MiB\n40 Мп']
|
||||
for i in range(2):
|
||||
values = [int(list(e['after'].values())[i]['memory.peak']) / 1048576 for e in uploads]
|
||||
axes[1].bar([n + (i - .5) * .34 for n in range(3)], values, width=.34, label='API ' + str(i + 1))
|
||||
axes[1].axhline(512, color='#e15759', linestyle='--', label='Лимит на реплику')
|
||||
axes[1].set(xticks=range(3), xticklabels=labels, ylabel='cgroup memory.peak, MiB', title='10 одновременных upload + download')
|
||||
axes[1].legend(fontsize=8)
|
||||
for ax in axes:
|
||||
ax.grid(axis='y', alpha=.2)
|
||||
ax.set_axisbelow(True)
|
||||
fig.suptitle('ЛР 4 · измерения локального стенда · 27 октября 2026')
|
||||
fig.savefig(evidence / 'research.png', dpi=160)
|
||||
fig.savefig(evidence / 'research.svg')
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Track 2 fault injection and measured traversal; use only synthetic lab4 data."""
|
||||
import concurrent.futures
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
sys.path[:0] = [str(Path.cwd() / 'tests'), '/app/src']
|
||||
from client import Client
|
||||
from objects import Objects
|
||||
from postgres import setting, Store
|
||||
from reconcile import reconcile
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
good, content = c.attachment(alice, chat)
|
||||
message = c.message(alice, chat, '', attachments=[good['id']])['json']
|
||||
sha = hashlib.sha256(content).hexdigest()
|
||||
objects = Objects(setting)
|
||||
report = {'method': 'real S3 and PostgreSQL, per-run fixed cutoff, synthetic data, 2s test grace; production >=3600s', 'checks': {}, 'passes': []}
|
||||
with psycopg.connect(setting('DATABASE_URL'), autocommit=True, row_factory=dict_row) as conn:
|
||||
def row(attachment_id):
|
||||
return conn.execute('SELECT * FROM attachments WHERE 1=1 AND id = %s', (attachment_id,)).fetchone()
|
||||
def aged(attachment_id):
|
||||
conn.execute("UPDATE attachments SET updated_at = clock_timestamp() - INTERVAL '2 hours' WHERE 1=1 AND id = %s", (attachment_id,))
|
||||
def intent(state='uploading'):
|
||||
aid = uuid.uuid4()
|
||||
conn.execute('''
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256, state, updated_at)
|
||||
VALUES (%s, %s, %s, 'research.png', %s, 'image/png', %s, %s, %s, clock_timestamp() - INTERVAL '2 hours')
|
||||
''', (aid, chat['id'], alice['id'], 'originals/' + str(aid), len(content), sha, state))
|
||||
return str(aid)
|
||||
# Fail precisely after successful S3 PUT, before the ready UPDATE/COMMIT.
|
||||
broken_name = 'fault_' + uuid.uuid4().hex + '.png'
|
||||
trigger = 'research_' + uuid.uuid4().hex
|
||||
try:
|
||||
from psycopg import sql
|
||||
conn.execute(sql.SQL('''CREATE FUNCTION {}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.state = 'ready' AND NEW.filename = '{}' THEN
|
||||
RAISE EXCEPTION 'synthetic research failure';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$''').format(sql.Identifier(trigger), sql.SQL(broken_name)))
|
||||
conn.execute(sql.SQL('CREATE TRIGGER {} BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION {}()').format(sql.Identifier(trigger), sql.Identifier(trigger)))
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + broken_name, 503, actor=alice, raw=content, headers={'Content-Type': 'image/png'})
|
||||
failed = conn.execute('SELECT id, state, object_key FROM attachments WHERE 1=1 AND filename = %s', (broken_name,)).fetchone()
|
||||
assert failed['state'] == 'uploading' and objects.head(failed['object_key']) is not None
|
||||
aged(failed['id'])
|
||||
finally:
|
||||
conn.execute(sql.SQL('DROP TRIGGER IF EXISTS {} ON attachments').format(sql.Identifier(trigger)))
|
||||
conn.execute(sql.SQL('DROP FUNCTION IF EXISTS {}()').format(sql.Identifier(trigger)))
|
||||
absent = intent() # DB intent exists, S3 PUT never happened (process died first).
|
||||
missing, _ = c.attachment(alice, chat)
|
||||
c.message(alice, chat, 'keep missing reference', attachments=[missing['id']])
|
||||
missing_key = 'originals/' + missing['id']
|
||||
objects.delete(missing_key) # S3-side loss; referenced metadata must never be erased.
|
||||
aged(missing['id'])
|
||||
orphan_key = 'originals/' + str(uuid.uuid4())
|
||||
objects.put(orphan_key, io.BytesIO(content), len(content), 'image/png', sha) # no DB row
|
||||
aged(good['id'])
|
||||
# Wait real object age; don't forge LastModified or replace the S3 clock.
|
||||
time.sleep(3)
|
||||
fresh_key = 'originals/' + str(uuid.uuid4())
|
||||
objects.put(fresh_key, io.BytesIO(content), len(content), 'image/png', sha)
|
||||
fresh_intent = intent()
|
||||
conn.execute('UPDATE attachments SET updated_at = clock_timestamp() WHERE 1=1 AND id = %s', (fresh_intent,))
|
||||
locked = intent()
|
||||
# Hold the same lock as a live uploader while reconciliation runs.
|
||||
with psycopg.connect(setting('DATABASE_URL')) as uploading:
|
||||
uploading.execute('SELECT id FROM attachments WHERE 1=1 AND id = %s FOR UPDATE', (locked,))
|
||||
dry = reconcile(False, 2)
|
||||
assert row(failed['id']) and row(absent) and row(missing['id'])['state'] == 'ready'
|
||||
assert objects.head(orphan_key) is not None
|
||||
report['checks']['dry_run_mutates_nothing'] = True
|
||||
fixed = reconcile(True, 2)
|
||||
assert row(failed['id']) is None and row(absent) is None
|
||||
assert objects.head(failed['object_key']) is None and objects.head(orphan_key) is None
|
||||
assert row(missing['id'])['state'] == 'storage_missing'
|
||||
assert row(locked) is not None and fixed['counts']['skipped_locked'] >= 1
|
||||
assert row(fresh_intent) is not None and objects.head(fresh_key) is not None
|
||||
assert row(good['id'])['state'] == 'ready' and objects.head('originals/' + good['id']) is not None
|
||||
report['checks'].update(stale_intents_and_orphans_cleaned=True, fresh_and_locked_retained=True, used_ready_retained=True, missing_reference_retained=True)
|
||||
repeat = reconcile(True, 2)
|
||||
assert repeat['counts']['deleted_objects'] == 0 and repeat['counts']['marked_missing'] == 0
|
||||
report['checks']['apply_repeat_idempotent'] = True
|
||||
c.call('GET', '/api/v1/attachments/' + missing['id'] + '/content', 503, actor=bob)
|
||||
# Restore exact original from the test's external copy; reconciler can't invent lost bytes.
|
||||
objects.put(missing_key, io.BytesIO(content), len(content), 'image/png', sha)
|
||||
aged(missing['id'])
|
||||
recovered = reconcile(True, 2)
|
||||
assert row(missing['id'])['state'] == 'ready'
|
||||
assert c.call('GET', '/api/v1/attachments/' + missing['id'] + '/content', actor=bob)['bytes'] == content
|
||||
report['checks']['restore_after_sha256_verification'] = True
|
||||
# Verify metadata FK and existing message survive every repair.
|
||||
assert conn.execute('SELECT 1 FROM message_attachments WHERE 1=1 AND message_id = %s AND attachment_id = %s', (message['id'], good['id'])).fetchone()
|
||||
report['passes'] = [dict(name=n, **v) for n, v in [('dry_run', dry), ('apply', fixed), ('repeat', repeat), ('recover', recovered)]]
|
||||
# Clean up only new unattached diagnostic keys/intents; confirmed files remain.
|
||||
objects.delete(fresh_key)
|
||||
for aid in [fresh_intent, locked]:
|
||||
conn.execute("DELETE FROM attachments WHERE 1=1 AND id = %s AND state = 'uploading'", (aid,))
|
||||
# Measure bounded scans at three populations; 3 repeats, no writes during scan.
|
||||
report['scan_cost'] = []
|
||||
for extra in [0, 100, 400]:
|
||||
for _ in range(extra):
|
||||
aid = intent('ready')
|
||||
objects.put('originals/' + aid, io.BytesIO(content), len(content), 'image/png', sha)
|
||||
for repetition in range(3):
|
||||
scan = reconcile(False, 2)
|
||||
report['scan_cost'].append({'repetition': repetition + 1, **scan})
|
||||
print(json.dumps(report, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""A continuously trickling client still reaches the absolute upload deadline."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import select
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import urlsplit
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client
|
||||
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
target = urlsplit(c.base)
|
||||
connection = socket.create_connection((target.hostname, target.port), timeout=3)
|
||||
header = 'POST /api/v1/chats/' + chat['id'] + '/attachments?filename=slow_' + uuid.uuid4().hex + '.png HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer ' + alice['token'] + '\r\nContent-Type: image/png\r\nContent-Length: 10485760\r\nConnection: close\r\n\r\n'
|
||||
started = time.monotonic()
|
||||
connection.sendall(header.encode())
|
||||
response = b''
|
||||
while time.monotonic() - started < 20:
|
||||
if select.select([connection], [], [], .15)[0]:
|
||||
response += connection.recv(4096)
|
||||
if b'\r\n\r\n' in response:
|
||||
break
|
||||
connection.sendall(b'x')
|
||||
connection.close()
|
||||
elapsed = time.monotonic() - started
|
||||
assert response.startswith(b'HTTP/1.1 400') or response.startswith(b'HTTP/1.0 400'), response[:100]
|
||||
assert 14 <= elapsed < 19
|
||||
assert b'x-instance-id:' in response.lower() and b'x-request-id:' in response.lower()
|
||||
print(json.dumps({'trickle_seconds': round(elapsed, 3), 'http_status': 400, 'absolute_deadline_enforced': True}))
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Execute with the isolated tools profile; inject faults only into new test IDs."""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
sys.path[:0] = [str(Path.cwd() / 'tests'), '/app/src']
|
||||
from botocore.exceptions import ClientError
|
||||
from PIL import Image
|
||||
from client import Client
|
||||
from objects import Objects
|
||||
from postgres import setting
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
att, content = c.attachment(alice, chat)
|
||||
api = Objects(setting)
|
||||
admin = Objects(lambda key: Path('/run/secrets/s3_admin_' + ('key' if key.endswith('_ID') else 'secret')).read_text().strip())
|
||||
key = 'originals/' + att['id']
|
||||
assert admin.head(key)['ContentLength'] == len(content)
|
||||
denied = []
|
||||
for path in ('/' + api.bucket + '/' + key, '/' + api.bucket + '?list-type=2'):
|
||||
try:
|
||||
urllib.request.urlopen('http://s3:8333' + path, timeout=3)
|
||||
raise AssertionError('Anonymous S3 access allowed')
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 403
|
||||
denied.append(error.code)
|
||||
# API credentials cannot create a bucket, read another bucket or change policy.
|
||||
other = 'test-' + uuid.uuid4().hex
|
||||
admin.client.create_bucket(Bucket=other)
|
||||
rejected = []
|
||||
try:
|
||||
actions = [lambda: api.client.create_bucket(Bucket='forbidden-' + uuid.uuid4().hex), lambda: api.client.list_objects_v2(Bucket=other), lambda: api.client.put_bucket_policy(Bucket=api.bucket, Policy=json.dumps({'Version': '2012-10-17', 'Statement': []}))]
|
||||
for action in actions:
|
||||
try:
|
||||
action()
|
||||
raise AssertionError('API credentials have excessive permissions')
|
||||
except ClientError as error:
|
||||
assert error.response['ResponseMetadata']['HTTPStatusCode'] == 403
|
||||
rejected.append(403)
|
||||
finally:
|
||||
admin.client.delete_bucket(Bucket=other)
|
||||
for host, port in [('s3-store', 8888), ('s3', 12535)]:
|
||||
try:
|
||||
connection = socket.create_connection((host, port), timeout=1)
|
||||
connection.close()
|
||||
raise AssertionError('Administrative/internal endpoint is exposed')
|
||||
except OSError:
|
||||
pass
|
||||
image = io.BytesIO()
|
||||
Image.new('RGB', (320, 200), (20, 150, 210)).save(image, format='JPEG')
|
||||
jpg = image.getvalue()
|
||||
uploaded = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=photo.jpg', 201, actor=alice, raw=jpg, headers={'Content-Type': 'image/jpeg'}, schema='Attachment')['json']
|
||||
downloaded = c.call('GET', '/api/v1/attachments/' + uploaded['id'] + '/content', actor=bob)
|
||||
assert downloaded['bytes'] == jpg and uploaded['sha256'] == hashlib.sha256(jpg).hexdigest()
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=bad.jpg', 415, actor=alice, raw=jpg[:200], headers={'Content-Type': 'image/jpeg'})
|
||||
print(json.dumps({'anonymous_statuses': denied, 'api_credentials_denied': rejected, 'internal_filer_and_admin_inaccessible': True, 'jpeg_byte_roundtrip': True, 'damaged_jpeg_415': True}, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Extra black-box tests, without changing the course's public tests."""
|
||||
import concurrent.futures
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from urllib.parse import quote
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client as PublicClient, LAB
|
||||
|
||||
|
||||
class Client(PublicClient):
|
||||
def call(self, method, path, *args, headers=None, **kwargs):
|
||||
headers = dict(headers or {})
|
||||
if method == 'POST' and path.endswith('/messages'):
|
||||
headers.setdefault('Idempotency-Key', uuid.uuid4().hex)
|
||||
return super().call(method, path, *args, headers=headers, **kwargs)
|
||||
|
||||
|
||||
class APIContract(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client()
|
||||
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
|
||||
self.path = '/api/v1/chats/' + self.chat['id']
|
||||
|
||||
def test_malformed_json_and_extra_fields(self):
|
||||
for raw in (b'{', b'[]', b'{"text":"x","text":"y"}', b'{"text":NaN}', b'{"text":"\\ud800"}'):
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=raw, headers={'Content-Type': 'application/json'})
|
||||
for body in ({'text': 'ok', 'sender_id': self.eve['id']}, {'text': True}, {'text': ' '}, {'text': ''}, {'text': None}):
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body=body)
|
||||
deep = b'{"text":' + b'[' * 1200 + b'0' + b']' * 1200 + b'}'
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=deep, headers={'Content-Type': 'application/json'})
|
||||
|
||||
def test_unicode_limits(self):
|
||||
result = self.client.message(self.alice, self.chat, '👩' * 4000)['json']
|
||||
self.assertEqual(result['text'], '👩' * 4000)
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': '👩' * 4001})
|
||||
|
||||
def test_unicode_nul_round_trip(self):
|
||||
import base64
|
||||
value = 'A\x00B\\u0000👩'
|
||||
registration = dict(self.alice['registration'], username='nul_' + uuid.uuid4().hex[:20], display_name=value)
|
||||
user = self.client.call('POST', '/api/v1/users', 201, body=registration, schema='User')['json']
|
||||
self.assertEqual(user['display_name'], value)
|
||||
credential = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
|
||||
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
|
||||
self.assertEqual(session['user'], user)
|
||||
actor = {'id': user['id'], 'token': session['token']}
|
||||
# Exercise the database path and then the Redis profile cache.
|
||||
for _ in range(2):
|
||||
self.assertEqual(self.client.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json'], user)
|
||||
chat = self.client.call('POST', '/api/v1/chats', 201, actor=actor, body={'title': value, 'member_ids': [actor['id']]}, schema='Chat')['json']
|
||||
self.assertEqual(chat['title'], value)
|
||||
self.assertEqual(self.client.call('GET', '/api/v1/chats/' + chat['id'], actor=actor, schema='Chat')['json'], chat)
|
||||
contents = [value, '\x00' * 4000, '👩' * 3999 + '\x00']
|
||||
for content in contents:
|
||||
self.assertEqual(self.client.message(actor, chat, content)['json']['text'], content)
|
||||
history = self.client.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=actor, schema='MessagePage')['json']
|
||||
self.assertEqual([message['text'] for message in history['items']], contents)
|
||||
|
||||
def test_foreign_chat(self):
|
||||
for suffix in ('', '/messages'):
|
||||
self.client.call('GET', self.path + suffix, 404, actor=self.eve)
|
||||
self.client.call('POST', self.path + '/messages', 404, actor=self.eve, body={'text': 'hidden'})
|
||||
self.client.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=self.alice)
|
||||
|
||||
def test_registration_race(self):
|
||||
body = dict(self.alice['registration'], username='race_' + uuid.uuid4().hex[:20])
|
||||
def register(_):
|
||||
return Client().call('POST', '/api/v1/users', [201, 409], body=body)['status']
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
||||
statuses = list(executor.map(register, range(10)))
|
||||
self.assertEqual(statuses.count(201), 1)
|
||||
self.assertEqual(statuses.count(409), 9)
|
||||
|
||||
def test_invalid_chat_creation(self):
|
||||
members = ([self.alice['id'], self.alice['id']], [self.bob['id']], [self.alice['id'], str(uuid.uuid4())], [], [True])
|
||||
for member_ids in members:
|
||||
self.client.call('POST', '/api/v1/chats', 400, actor=self.alice, body={'title': 'rollback', 'member_ids': member_ids})
|
||||
|
||||
def test_cursor_scope_and_validation(self):
|
||||
for i in range(3):
|
||||
self.client.message(self.alice, self.chat, str(i))
|
||||
cursor = self.client.call('GET', self.path + '/messages?limit=1', actor=self.alice, schema='MessagePage')['json']['next_cursor']
|
||||
other = self.client.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'other', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
|
||||
self.client.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(cursor), 400, actor=self.alice)
|
||||
for query in ('limit=0', 'limit=101', 'limit=' + '9' * 5000, 'limit=true', 'limit=1&limit=2', 'cursor=', 'cursor=bad', 'cursor=e30=', 'offset=1'):
|
||||
self.client.call('GET', self.path + '/messages?' + query, 400, actor=self.alice)
|
||||
|
||||
def test_concurrent_messages_and_pagination(self):
|
||||
def send(i):
|
||||
return Client().message(self.alice if i % 2 else self.bob, self.chat, 'parallel-' + str(i))['json']
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
||||
sent = list(executor.map(send, range(100)))
|
||||
found = []
|
||||
cursor = None
|
||||
while True:
|
||||
url = self.path + '/messages?limit=7' + ('&cursor=' + quote(cursor) if cursor else '')
|
||||
page = self.client.call('GET', url, actor=self.alice, schema='MessagePage')['json']
|
||||
found.extend(page['items'])
|
||||
cursor = page['next_cursor']
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual(len(found), 100)
|
||||
self.assertEqual(len({v['id'] for v in found}), 100)
|
||||
self.assertEqual({v['id'] for v in found}, {v['id'] for v in sent})
|
||||
self.assertEqual(found, sorted(found, key=lambda v: (v['created_at'], v['id'])))
|
||||
|
||||
def test_idempotency_concurrent_replicas(self):
|
||||
key = uuid.uuid4().hex
|
||||
def send(_):
|
||||
return Client().message(self.alice, self.chat, 'Один раз\x00👩', key=key)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
|
||||
replies = list(executor.map(send, range(32)))
|
||||
self.assertGreaterEqual(len({v['headers']['X-Instance-Id'] for v in replies}), 2)
|
||||
self.assertTrue(all(v['json'] == replies[0]['json'] for v in replies))
|
||||
page = self.client.call('GET', self.path + '/messages', actor=self.bob, schema='MessagePage')['json']
|
||||
self.assertEqual(page['items'], [replies[0]['json']])
|
||||
self.client.call('POST', self.path + '/messages', 409, actor=self.alice, body={'text': 'different'}, headers={'Idempotency-Key': key})
|
||||
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=self.alice)
|
||||
self.client.call('POST', self.path + '/messages', 401, actor=self.alice, body={'text': 'Один раз\x00👩'}, headers={'Idempotency-Key': key})
|
||||
|
||||
def test_protocol_error_headers(self):
|
||||
self.client.call('TRACE', '/api/v1/users/me', 400, actor=self.alice)
|
||||
|
||||
def test_idempotency_scope(self):
|
||||
key = uuid.uuid4().hex
|
||||
one = self.client.message(self.alice, self.chat, 'same', key=key)['json']
|
||||
two = self.client.message(self.bob, self.chat, 'same', key=key)['json']
|
||||
other = self.client.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'scope', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
|
||||
three = self.client.message(self.alice, other, 'same', key=key)['json']
|
||||
self.assertEqual(len({one['id'], two['id'], three['id']}), 3)
|
||||
|
||||
def test_idempotency_semantic_body(self):
|
||||
key = uuid.uuid4().hex
|
||||
one = self.client.message(self.alice, self.chat, 'semantic', key=key)['json']
|
||||
two = self.client.call('POST', self.path + '/messages', 201, actor=self.alice, body={'attachment_ids': [], 'text': 'semantic'}, headers={'Idempotency-Key': key}, schema='Message')['json']
|
||||
self.assertEqual(one, two)
|
||||
|
||||
def test_idempotency_invalid_keys(self):
|
||||
for key in (None, '', 'x' * 129, 'space key', 'bad,key', 'slash/key'):
|
||||
headers = {} if key is None else {'Idempotency-Key': key}
|
||||
PublicClient().call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': 'valid'}, headers=headers)
|
||||
for raw in (b'{"text":true}', b'{"text":"ok","extra":1}', b'{"text":"ok","attachment_ids":false}'):
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=raw, headers={'Content-Type': 'application/json'})
|
||||
|
||||
def test_idempotency_conflicting_race(self):
|
||||
key = uuid.uuid4().hex
|
||||
def send(i):
|
||||
return Client().call('POST', self.path + '/messages', [201, 409], actor=self.alice, body={'text': str(i % 2)}, headers={'Idempotency-Key': key}, schema=None)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
|
||||
replies = list(executor.map(send, range(32)))
|
||||
self.assertEqual(sum(v['status'] == 201 for v in replies), 16)
|
||||
self.assertEqual(sum(v['status'] == 409 for v in replies), 16)
|
||||
page = self.client.call('GET', self.path + '/messages', actor=self.alice, schema='MessagePage')['json']
|
||||
self.assertEqual(len(page['items']), 1)
|
||||
|
||||
@unittest.skipUnless(LAB >= 2, 'sessions start in lab2')
|
||||
def test_unicode_password_basic_and_logout(self):
|
||||
import base64
|
||||
registration = {'username': 'unicode_' + uuid.uuid4().hex[:16], 'display_name': 'Софья', 'password': '🔐' * 127 + ':'}
|
||||
self.client.call('POST', '/api/v1/users', 201, body=registration)
|
||||
encoded = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
|
||||
headers = {'Authorization': 'Basic ' + encoded}
|
||||
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers=headers, schema='Session')['json']
|
||||
actor = {'id': session['user']['id'], 'token': session['token']}
|
||||
self.client.call('GET', '/api/v1/users/me', actor=actor)
|
||||
self.client.call('GET', '/api/v1/users/me', 401, headers=headers)
|
||||
for authorization in ('Basic !!!', 'Bearer wrong', '', 'Basic Zm9v'):
|
||||
self.client.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': authorization})
|
||||
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
|
||||
self.client.call('GET', '/api/v1/users/me', 401, actor=actor)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,83 @@
|
||||
import concurrent.futures
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from urllib.parse import quote
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client
|
||||
from images import bomb, png
|
||||
|
||||
|
||||
class Attachments(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.c = Client()
|
||||
self.alice, self.bob, self.eve, self.chat = self.c.bootstrap()
|
||||
self.path = '/api/v1/chats/' + self.chat['id']
|
||||
self.image = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
def upload(self, content=None, name='photo.png', mime='image/png', status=201, actor=None):
|
||||
return self.c.call('POST', self.path + '/attachments?filename=' + quote(name, safe=''), status, actor=actor or self.alice, raw=self.image if content is None else content, headers={'Content-Type': mime}, schema='Attachment' if status == 201 else None)
|
||||
|
||||
def test_binary_roundtrip_and_metadata(self):
|
||||
att = self.upload(name='Софья 👩💻.png')['json']
|
||||
self.assertEqual(att['filename'], 'Софья 👩💻.png')
|
||||
self.assertEqual(att['variants'], [])
|
||||
self.assertIsNone(att['error_code'])
|
||||
for _ in range(4):
|
||||
metadata = self.c.call('GET', '/api/v1/attachments/' + att['id'], actor=self.bob, schema='Attachment')['json']
|
||||
self.assertEqual(metadata, att)
|
||||
response = self.c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=original', actor=self.bob)
|
||||
self.assertEqual(response['bytes'], self.image)
|
||||
self.c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', 404, actor=self.bob)
|
||||
|
||||
def test_bad_images_and_mime(self):
|
||||
for raw in (b'not image', b'<svg/>', self.image[:40], self.image[:-30]):
|
||||
self.upload(raw, status=415)
|
||||
self.upload(mime='image/jpeg', status=415)
|
||||
self.upload(mime='application/octet-stream', status=415)
|
||||
self.upload(bomb(), status=413)
|
||||
self.upload(b'x' * (10 * 1024 * 1024 + 1), status=413)
|
||||
|
||||
def test_dangerous_names_and_query(self):
|
||||
for name in ('', ' ', '../a.png', 'a/b.png', 'a\\b.png', '\0.png', 'a\n.png', 'a\x7f.png', 'a' * 256):
|
||||
self.upload(name=name, status=400)
|
||||
for query in ('', '?filename=a&filename=b', '?filename=a&extra=x'):
|
||||
self.c.call('POST', self.path + '/attachments' + query, 400, actor=self.alice, raw=self.image, headers={'Content-Type': 'image/png'})
|
||||
|
||||
def test_access_and_cross_chat(self):
|
||||
att = self.upload()['json']
|
||||
for suffix in ('', '/content'):
|
||||
self.c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=self.eve)
|
||||
self.c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 401)
|
||||
self.upload(actor=self.eve, status=404)
|
||||
other = self.c.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'other', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
|
||||
self.c.call('POST', '/api/v1/chats/' + other['id'] + '/messages', 404, actor=self.alice, body={'text': '', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
self.c.call('POST', self.path + '/messages', 404, actor=self.alice, body={'text': '', 'attachment_ids': [str(uuid.uuid4())]}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
|
||||
def test_attachment_message_replay(self):
|
||||
one, two = self.upload()['json'], self.upload()['json']
|
||||
key = uuid.uuid4().hex
|
||||
def send(_):
|
||||
return Client().message(self.bob, self.chat, '', key=key, attachments=[one['id'], two['id']])['json']
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
||||
replies = list(executor.map(send, range(20)))
|
||||
self.assertTrue(all(r == replies[0] for r in replies))
|
||||
self.assertEqual(replies[0]['attachment_ids'], [one['id'], two['id']])
|
||||
self.c.call('POST', self.path + '/messages', 409, actor=self.bob, body={'text': '', 'attachment_ids': [two['id'], one['id']]}, headers={'Idempotency-Key': key})
|
||||
history = self.c.call('GET', self.path + '/messages', actor=self.alice, schema='MessagePage')['json']
|
||||
self.assertEqual(history['items'], [replies[0]])
|
||||
for ids in ([one['id']] * 2, [True], 'bad', [str(uuid.uuid4()) for _ in range(11)]):
|
||||
self.c.call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
|
||||
def test_valid_pixel_boundary(self):
|
||||
# Exactly 40M decoded grayscale pixels, small compressed upload.
|
||||
content = png(10000, 4000, rgb=False)
|
||||
att = self.upload(content)['json']
|
||||
response = self.c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=self.bob)
|
||||
self.assertEqual(response['bytes'], content)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,75 @@
|
||||
""">=10 simultaneous uploads with sampled cgroup memory and true cgroup peak."""
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client
|
||||
from images import png
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.check_output(['docker', *args], text=True).strip()
|
||||
|
||||
|
||||
def memory(container):
|
||||
code = "import json; from pathlib import Path; p=Path('/sys/fs/cgroup'); print(json.dumps({k:(p/k).read_text().strip() for k in ['memory.current','memory.peak','memory.events','cpu.stat']}))"
|
||||
return json.loads(docker('exec', container, 'python', '-c', code))
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
records = []
|
||||
for width, height, noise, rgb in [(420, 420, True, True), (1800, 1400, True, True), (10000, 4000, False, True)]:
|
||||
content = png(width, height, noise=noise, rgb=rgb)
|
||||
assert len(content) <= 10 * 1024 * 1024
|
||||
digest = hashlib.sha256(content).hexdigest()
|
||||
# Fresh API processes make memory.peak attributable to this one experiment.
|
||||
docker('compose', 'restart', 'api')
|
||||
docker('compose', 'up', '-d', '--wait', '--no-deps', 'api')
|
||||
time.sleep(2)
|
||||
containers = docker('compose', 'ps', '-q', 'api').splitlines()
|
||||
before = {v: memory(v) for v in containers}
|
||||
samples = []
|
||||
done = threading.Event()
|
||||
started = time.monotonic()
|
||||
def sample():
|
||||
while not done.is_set():
|
||||
samples.append({'seconds': round(time.monotonic() - started, 4), 'memory': {v: memory(v) for v in containers}})
|
||||
done.wait(.05)
|
||||
thread = threading.Thread(target=sample)
|
||||
thread.start()
|
||||
barrier = threading.Barrier(10)
|
||||
def upload(i):
|
||||
barrier.wait()
|
||||
begin = time.monotonic()
|
||||
response = Client(timeout=30).call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=concurrent.png', [201, 503], actor=alice, raw=content, headers={'Content-Type': 'image/png'})
|
||||
if response['status'] == 201:
|
||||
# Parse because schema omitted to allow a documented admission rejection.
|
||||
attachment = json.loads(response['bytes'])
|
||||
assert attachment['sha256'] == digest
|
||||
downloaded = Client(timeout=30).call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)
|
||||
assert hashlib.sha256(downloaded['bytes']).hexdigest() == digest
|
||||
return {'index': i, 'status': response['status'], 'instance': response['headers']['X-Instance-Id'], 'elapsed_seconds': round(time.monotonic() - begin, 6)}
|
||||
try:
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
||||
results = list(executor.map(upload, range(10)))
|
||||
finally:
|
||||
done.set()
|
||||
thread.join()
|
||||
after = {v: memory(v) for v in containers}
|
||||
for m in after.values():
|
||||
assert 'oom_kill 0' in m['memory.events']
|
||||
records.append({'width': width, 'height': height, 'bytes': len(content), 'pixels': width * height, 'clients': 10, 'before': before, 'after': after, 'samples': samples, 'results': results, 'seconds': round(time.monotonic() - started, 6)})
|
||||
print(json.dumps({'memory_source': 'Linux cgroup v2: memory.current, memory.peak (lifetime peak; API restarted before each case), memory.events; samples include tmpfs and kernel charges, not Python heap alone', 'experiments': records}, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user