lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
Executable
+83
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Upload through one API replica, stop it, download through another.
|
||||
|
||||
Run against a live stand:
|
||||
python3 student-tests/attachment_failover.py --base-url https://localhost:8443
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
from tests_helpers import ROOT, compose # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Attachment failover across API replicas (lab4)')
|
||||
client = Client(args.base_url or BASE_URL, args.ca_file or CA_FILE)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
content = FIXTURE.read_bytes()
|
||||
|
||||
response = client.call(
|
||||
'POST',
|
||||
'/api/v1/chats/' + chat['id'] + '/attachments?filename=' + quote('failover.png'),
|
||||
202,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={'Content-Type': 'image/png'},
|
||||
schema='Attachment',
|
||||
)
|
||||
attachment = response['json']
|
||||
instance = response['headers'].get('X-Instance-Id')
|
||||
check(bool(instance), 'upload response has no X-Instance-Id')
|
||||
check(attachment['sha256'] == hashlib.sha256(content).hexdigest(), 'upload checksum mismatch')
|
||||
attachment = client.wait_ready(alice, attachment)
|
||||
|
||||
stop = subprocess.run(
|
||||
[str(ROOT / 'scripts/stop-one.sh')],
|
||||
cwd=ROOT,
|
||||
env={**os.environ, 'TARGET_INSTANCE_ID': instance},
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
check(stop.returncode == 0, 'stop-one.sh failed: ' + stop.stderr.strip())
|
||||
|
||||
deadline = time.monotonic() + 30
|
||||
last_error = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
download = client.call(
|
||||
'GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob,
|
||||
)
|
||||
if download['bytes'] == content:
|
||||
metadata = client.call(
|
||||
'GET', '/api/v1/attachments/' + attachment['id'], actor=bob, schema='Attachment',
|
||||
)['json']
|
||||
check(metadata['sha256'] == attachment['sha256'], 'metadata changed after failover')
|
||||
print('PASS: lab4 attachment failover; served by', instance)
|
||||
return
|
||||
last_error = 'downloaded bytes differ from the original'
|
||||
except Failure as error:
|
||||
last_error = str(error)
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
raise Failure('download did not recover within 30s: ' + str(last_error))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
run(main)
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', 'api', check=False)
|
||||
Executable
+230
@@ -0,0 +1,230 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Negative attachment scenarios required by lab4 level 4.
|
||||
|
||||
Run against a live stand:
|
||||
python3 student-tests/attachments_negative.py --base-url https://localhost:8443
|
||||
"""
|
||||
import hashlib
|
||||
import struct
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE, open_url # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def upload(client, actor, chat, content, filename='sample.png', content_type='image/png', expected=202):
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + quote(filename, safe='')
|
||||
return client.call('POST', path, expected, actor=actor, raw=content, headers={'Content-Type': content_type})
|
||||
|
||||
|
||||
def png_chunk(ctype, payload):
|
||||
crc = zlib.crc32(ctype + payload) & 0xffffffff
|
||||
return struct.pack('>I', len(payload)) + ctype + payload + struct.pack('>I', crc)
|
||||
|
||||
|
||||
def crafted_png(width, height, interlace, raster, bit_depth=8, color_type=6):
|
||||
"""PNG with correct chunk lengths and CRCs around arbitrary IDAT bytes."""
|
||||
return crafted_png_extra(
|
||||
width, height, raster, bit_depth=bit_depth, color_type=color_type,
|
||||
interlace=interlace,
|
||||
)
|
||||
|
||||
|
||||
def crafted_png_extra(width, height, raster, pre_idat=(), bit_depth=8, color_type=6, interlace=0):
|
||||
"""PNG whose IDAT is preceded by caller-supplied chunks (PLTE/tRNS/...)."""
|
||||
ihdr = struct.pack('>IIBBBBB', width, height, bit_depth, color_type, 0, 0, interlace)
|
||||
return (
|
||||
b'\x89PNG\r\n\x1a\n'
|
||||
+ png_chunk(b'IHDR', ihdr)
|
||||
+ b''.join(pre_idat)
|
||||
+ png_chunk(b'IDAT', zlib.compress(raster))
|
||||
+ png_chunk(b'IEND', b'')
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Attachment negative scenarios (lab4)')
|
||||
client = Client(args.base_url or BASE_URL, args.ca_file or CA_FILE)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
fixture = FIXTURE.read_bytes()
|
||||
|
||||
# Oversized body: rejected before any image parsing.
|
||||
upload(client, alice, chat, b'\x00' * (10 * 1024 * 1024 + 1), expected=413)
|
||||
print('10 MiB + 1 body: 413')
|
||||
|
||||
# Empty body is not a valid image.
|
||||
upload(client, alice, chat, b'', expected=415)
|
||||
print('empty body: 415')
|
||||
|
||||
# Corrupt PNG: flip one IDAT payload byte, CRC no longer matches.
|
||||
corrupt = bytearray(fixture)
|
||||
index = corrupt.index(b'IDAT') + 8
|
||||
corrupt[index] ^= 0xFF
|
||||
upload(client, alice, chat, bytes(corrupt), expected=415)
|
||||
print('corrupt PNG (IDAT CRC): 415')
|
||||
|
||||
# Declared JPEG but the bytes are PNG.
|
||||
upload(client, alice, chat, fixture, filename='photo.jpg', content_type='image/jpeg', expected=415)
|
||||
print('MIME spoof (PNG declared as JPEG): 415')
|
||||
|
||||
# Structurally valid PNG (chunk layout, lengths, CRCs all correct) whose
|
||||
# IDAT payload is not a zlib stream at all. Structure-checking alone must
|
||||
# not accept it: the stream has to inflate. Regression for a review
|
||||
# finding that used to produce 202 queued and then failed/invalid_image
|
||||
# in the worker.
|
||||
upload(
|
||||
client, alice, chat,
|
||||
crafted_png(64, 32, 0, b'this is not a zlib stream'),
|
||||
expected=415,
|
||||
)
|
||||
print('structurally valid PNG with non-zlib IDAT: 415')
|
||||
|
||||
# Correct zlib stream that is not a valid PNG raster: an empty payload
|
||||
# and a scanline with an undefined filter byte must both be 415, not 202.
|
||||
upload(client, alice, chat, crafted_png(2, 2, 0, b''), expected=415)
|
||||
print('valid zlib, empty PNG raster: 415')
|
||||
invalid_filter = b'\x05' + b'\x00' * 8 + b'\x00' + b'\x00' * 8
|
||||
upload(client, alice, chat, crafted_png(2, 2, 0, invalid_filter), expected=415)
|
||||
print('valid zlib, invalid PNG scanline filter: 415')
|
||||
|
||||
# RGBA forbids bit depth 1; every chunk CRC is correct.
|
||||
upload(client, alice, chat, crafted_png(1, 1, 0, b'\x00', bit_depth=1), expected=415)
|
||||
print('invalid PNG color type/bit depth pair: 415')
|
||||
|
||||
# Duplicate IHDR is forbidden even with correct CRCs.
|
||||
ihdr = png_chunk(b'IHDR', struct.pack('>IIBBBBB', 1, 1, 8, 6, 0, 0, 0))
|
||||
duplicate_header = (
|
||||
b'\x89PNG\r\n\x1a\n'
|
||||
+ ihdr + ihdr
|
||||
+ png_chunk(b'IDAT', zlib.compress(b'\x00' + b'\x00' * 4))
|
||||
+ png_chunk(b'IEND', b'')
|
||||
)
|
||||
upload(client, alice, chat, duplicate_header, expected=415)
|
||||
print('duplicate PNG IHDR: 415')
|
||||
|
||||
# Bytes after the zlib stream inside IDAT are not part of a valid raster.
|
||||
trailing = (
|
||||
b'\x89PNG\r\n\x1a\n'
|
||||
+ png_chunk(b'IHDR', struct.pack('>IIBBBBB', 1, 1, 8, 6, 0, 0, 0))
|
||||
+ png_chunk(b'IDAT', zlib.compress(b'\x00' + b'\x00' * 4) + b'junk')
|
||||
+ png_chunk(b'IEND', b'')
|
||||
)
|
||||
upload(client, alice, chat, trailing, expected=415)
|
||||
print('trailing bytes after PNG zlib stream: 415')
|
||||
|
||||
# tRNS is forbidden for alpha color types and has fixed lengths otherwise.
|
||||
rgba_trns = crafted_png_extra(
|
||||
1, 1, b'\x00' + b'\x00' * 4,
|
||||
pre_idat=(png_chunk(b'tRNS', b'\x00'),), color_type=6,
|
||||
)
|
||||
upload(client, alice, chat, rgba_trns, expected=415)
|
||||
print('tRNS on RGBA PNG: 415')
|
||||
|
||||
rgb_trns = crafted_png_extra(
|
||||
1, 1, b'\x00' + b'\x00' * 3,
|
||||
pre_idat=(png_chunk(b'tRNS', b'\x00'),), color_type=2,
|
||||
)
|
||||
upload(client, alice, chat, rgb_trns, expected=415)
|
||||
print('short tRNS on RGB PNG: 415')
|
||||
|
||||
# A 1-bit palette cannot address three entries.
|
||||
palette_overflow = crafted_png_extra(
|
||||
1, 1, b'\x00\x00',
|
||||
pre_idat=(png_chunk(b'PLTE', bytes((255, 0, 0, 0, 255, 0, 0, 0, 255))),),
|
||||
bit_depth=1, color_type=3,
|
||||
)
|
||||
upload(client, alice, chat, palette_overflow, expected=415)
|
||||
print('PLTE entries exceed palette bit depth: 415')
|
||||
|
||||
# Palette transparency cannot describe more entries than PLTE provides.
|
||||
palette_trns = crafted_png_extra(
|
||||
1, 1, b'\x00\x00',
|
||||
pre_idat=(
|
||||
png_chunk(b'PLTE', bytes((255, 0, 0))),
|
||||
png_chunk(b'tRNS', b'\x00\x00'),
|
||||
),
|
||||
bit_depth=8, color_type=3,
|
||||
)
|
||||
upload(client, alice, chat, palette_trns, expected=415)
|
||||
print('palette tRNS exceeds PLTE entries: 415')
|
||||
|
||||
# Dangerous display names.
|
||||
for name in ('../x.png', 'a/b.png', 'a\\b.png', 'a\x00.png', 'a\n.png'):
|
||||
upload(client, alice, chat, fixture, filename=name, expected=400)
|
||||
print('dangerous filenames: 400')
|
||||
|
||||
# A member of one chat cannot read an attachment of another chat.
|
||||
other = client.call(
|
||||
'POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Другой чат', 'member_ids': [alice['id'], eve['id']]}, schema='Chat',
|
||||
)['json']
|
||||
foreign, foreign_content = client.attachment(eve, other)
|
||||
client.call('GET', '/api/v1/attachments/' + foreign['id'], 404, actor=bob)
|
||||
client.call('GET', '/api/v1/attachments/' + foreign['id'] + '/content', 404, actor=bob)
|
||||
print('foreign attachment metadata/content: 404')
|
||||
|
||||
# Message rules: empty text without attachments, attachment from another chat.
|
||||
client.call(
|
||||
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
|
||||
body={'text': ''}, headers={'Idempotency-Key': uuid.uuid4().hex},
|
||||
)
|
||||
print('empty text without attachments: 400')
|
||||
client.call(
|
||||
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
|
||||
body={'text': 'чужое', 'attachment_ids': [foreign['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex},
|
||||
)
|
||||
print('attachment from another chat: 404')
|
||||
|
||||
# Contract limits: 11 unique IDs and duplicate IDs are rejected by the schema.
|
||||
client.call(
|
||||
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
|
||||
body={'text': 'много', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex},
|
||||
)
|
||||
print('11 attachment ids: 400')
|
||||
duplicate = str(uuid.uuid4())
|
||||
client.call(
|
||||
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
|
||||
body={'text': 'дубликат', 'attachment_ids': [duplicate, duplicate]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex},
|
||||
)
|
||||
print('duplicate attachment ids: 400')
|
||||
|
||||
# Lab5 exposes the derived variants after ready; queued content is a conflict.
|
||||
own, content = client.attachment(alice, chat)
|
||||
client.call('GET', '/api/v1/attachments/' + own['id'] + '/content', 409, actor=alice)
|
||||
own = client.wait_ready(alice, own)
|
||||
client.call('GET', '/api/v1/attachments/' + own['id'] + '/content?variant=thumbnail', 200, actor=alice)
|
||||
|
||||
# Attachment-only message is valid.
|
||||
client.message(alice, chat, '', attachments=[own['id']])
|
||||
print('attachment-only message: 201')
|
||||
|
||||
# Object keys are server-generated; anonymous direct access must be denied.
|
||||
key = 'attachments/' + chat['id'] + '/' + own['id'] + '/original'
|
||||
request = urllib.request.Request('https://localhost:8333/messenger-attachments/' + key, method='GET')
|
||||
try:
|
||||
with open_url(request, timeout=5, ca_file=args.ca_file or CA_FILE):
|
||||
raise Failure('anonymous S3 GET unexpectedly succeeded')
|
||||
except urllib.error.HTTPError as error:
|
||||
check(error.code == 403, 'anonymous S3 GET must be 403, got ' + str(error.code))
|
||||
|
||||
print('anonymous direct S3 GET: 403')
|
||||
check(hashlib.sha256(content).hexdigest() == own['sha256'], 'fixture checksum mismatch')
|
||||
print('PASS: lab4 attachment negative scenarios')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from statistics import median
|
||||
import time
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Собственный тест живёт в student-tests/ (CONTRIBUTING), публичный клиент — в tests/.
|
||||
sys.path.insert(0, os.path.join(ROOT, 'tests'))
|
||||
sys.path.insert(0, os.path.join(ROOT, 'scripts'))
|
||||
|
||||
from client import Client, check # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE, open_url # noqa: E402
|
||||
from tests_helpers import compose # noqa: E402
|
||||
USERS = 4
|
||||
CHATS_PER_USER = 15
|
||||
REQUESTS_PER_USER = 250
|
||||
WORKERS = 8
|
||||
|
||||
for proxy_name in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(proxy_name, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = os.environ['NO_PROXY']
|
||||
|
||||
|
||||
def restart_api(cache_enabled):
|
||||
env = dict(os.environ)
|
||||
env['REDIS_ENABLED'] = 'true'
|
||||
env['CACHE_ENABLED'] = 'true' if cache_enabled else 'false'
|
||||
compose('up', '-d', '--force-recreate', '--no-deps', 'api', env=env)
|
||||
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
Client(BASE_URL, CA_FILE, timeout=2).call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError('API did not become ready after restart')
|
||||
|
||||
|
||||
def percentile(values, percent):
|
||||
values = sorted(values)
|
||||
index = max(0, (len(values) * percent + 99) // 100 - 1)
|
||||
return values[index]
|
||||
|
||||
|
||||
def benchmark(actors):
|
||||
requests = [(actor, i) for i in range(REQUESTS_PER_USER) for actor in actors]
|
||||
latencies = []
|
||||
failures = []
|
||||
started = time.monotonic()
|
||||
|
||||
def request(item):
|
||||
actor, _ = item
|
||||
request_started = time.monotonic()
|
||||
request = urllib.request.Request(
|
||||
BASE_URL + '/api/v1/chats?limit=50',
|
||||
headers={
|
||||
'Accept': 'application/json',
|
||||
'Authorization': 'Bearer ' + actor['token'],
|
||||
},
|
||||
)
|
||||
try:
|
||||
with open_url(request, timeout=10, ca_file=CA_FILE) as response:
|
||||
data = response.read()
|
||||
status = response.status
|
||||
check(status == 200,
|
||||
'unexpected HTTP status: ' + str(status) + ' body=' + data.decode())
|
||||
result = json.loads(data)
|
||||
check(len(result['items']) == 30, 'unexpected chat count')
|
||||
check(all(actor['id'] in chat['member_ids'] for chat in result['items']),
|
||||
'response contains another user chat')
|
||||
return time.monotonic() - request_started, None
|
||||
except Exception as exc:
|
||||
return 0, type(exc).__name__ + ': ' + str(exc)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
|
||||
for latency, error in pool.map(request, requests):
|
||||
if error is None:
|
||||
latencies.append(latency)
|
||||
else:
|
||||
failures.append(error)
|
||||
|
||||
duration = time.monotonic() - started
|
||||
if failures:
|
||||
raise RuntimeError(
|
||||
'API benchmark failed: %d/%d requests; first error: %s'
|
||||
% (len(failures), len(requests), failures[0])
|
||||
)
|
||||
return {
|
||||
'requests': len(latencies),
|
||||
'workers': WORKERS,
|
||||
'duration_seconds': duration,
|
||||
'rps': len(latencies) / duration,
|
||||
'p50_ms': median(latencies) * 1000,
|
||||
'p95_ms': percentile(latencies, 95) * 1000,
|
||||
'p99_ms': percentile(latencies, 99) * 1000,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
client = Client(BASE_URL, CA_FILE, timeout=10)
|
||||
actors = [client.user('perf_api_' + str(i)) for i in range(USERS)]
|
||||
|
||||
for index, owner in enumerate(actors):
|
||||
member = actors[(index + 1) % len(actors)]
|
||||
for chat_index in range(CHATS_PER_USER):
|
||||
client.call(
|
||||
'POST',
|
||||
'/api/v1/chats',
|
||||
expected=201,
|
||||
actor=owner,
|
||||
body={
|
||||
'title': 'API performance chat ' + str(index) + '-' + str(chat_index),
|
||||
'member_ids': [owner['id'], member['id']],
|
||||
},
|
||||
schema='Chat',
|
||||
)
|
||||
|
||||
results = []
|
||||
try:
|
||||
for trial in range(2):
|
||||
for enabled in (False, True):
|
||||
restart_api(enabled)
|
||||
for actor in actors:
|
||||
for _ in range(5):
|
||||
client.call('GET', '/api/v1/chats?limit=50', actor=actor, schema='ChatPage')
|
||||
print(
|
||||
'running trial %d, cache=%s, requests=%d' %
|
||||
(trial + 1, enabled, len(actors) * REQUESTS_PER_USER),
|
||||
flush=True,
|
||||
)
|
||||
result = benchmark(actors)
|
||||
result.update(trial=trial + 1, cache_enabled=enabled)
|
||||
results.append(result)
|
||||
print(json.dumps(result), flush=True)
|
||||
finally:
|
||||
restart_api(True)
|
||||
print(json.dumps({'results': results, 'users': USERS, 'chats': USERS * CHATS_PER_USER,
|
||||
'sessions_cached_in_both_modes': True}), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+146
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Параллельная проверка общей идемпотентности отправки сообщения (lab3+).
|
||||
|
||||
Публичный smoke проверяет только последовательный повтор. Здесь один и тот же
|
||||
Idempotency-Key отправляется одновременно несколькими потоками через LB, то есть
|
||||
запросы попадают на разные API-реплики: ровно одно сообщение должно быть создано,
|
||||
а повтор с другим payload обязан получить 409.
|
||||
|
||||
Запуск (стенд уже поднят, HTTPS LB на 8443):
|
||||
python3 student-tests/idempotency_parallel.py --base-url https://localhost:8443
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
|
||||
from client import Client, LAB, Failure, arguments, check, run # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
|
||||
WORKERS = 12
|
||||
|
||||
|
||||
def messages_path(chat):
|
||||
return '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
|
||||
|
||||
def history(client, actor, chat):
|
||||
page = client.call('GET', messages_path(chat) + '?limit=100', actor=actor, schema='MessagePage')['json']
|
||||
return page['items']
|
||||
|
||||
|
||||
def replay_confirmed(client, actor, chat, workers=WORKERS):
|
||||
"""Один payload, один ключ, одновременные запросы через LB."""
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Параллельный повтор ' + key
|
||||
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
responses = list(pool.map(lambda _: client.message(actor, chat, text, key=key), range(workers)))
|
||||
|
||||
ids = {response['json']['id'] for response in responses}
|
||||
check(len(ids) == 1, 'параллельные повторы вернули разные сообщения: ' + str(len(ids)))
|
||||
instances = {response['headers']['X-Instance-Id'] for response in responses}
|
||||
check(len(instances) >= 2, 'запросы не разошлись по репликам: ' + str(sorted(instances)))
|
||||
|
||||
stored = [message for message in history(client, actor, chat) if message['text'] == text]
|
||||
check(len(stored) == 1, 'параллельный повтор создал ' + str(len(stored)) + ' сообщений')
|
||||
check(stored[0]['id'] == next(iter(ids)), 'в истории не то сообщение, что вернул POST')
|
||||
|
||||
return {'workers': workers, 'instances': sorted(instances), 'message_id': stored[0]['id']}
|
||||
|
||||
|
||||
def conflicting_payloads(client, actor, chat, workers=WORKERS):
|
||||
"""Один ключ, разные payload одновременно: один 201, остальные 409."""
|
||||
key = uuid.uuid4().hex
|
||||
texts = ['Конфликт ' + key + ' #' + str(index) for index in range(workers)]
|
||||
|
||||
def post(text):
|
||||
return client.call(
|
||||
'POST',
|
||||
messages_path(chat),
|
||||
(201, 409),
|
||||
actor=actor,
|
||||
body={'text': text},
|
||||
headers={'Idempotency-Key': key},
|
||||
schema='Message',
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
responses = list(pool.map(post, texts))
|
||||
|
||||
accepted = [response for response in responses if response['status'] == 201]
|
||||
conflicts = [response for response in responses if response['status'] == 409]
|
||||
check(len(accepted) == 1, 'принято запросов с одним ключом: ' + str(len(accepted)))
|
||||
check(len(conflicts) == workers - 1, 'конфликтов: ' + str(len(conflicts)))
|
||||
|
||||
stored = [message for message in history(client, actor, chat) if message['id'] == accepted[0]['json']['id']]
|
||||
check(len(stored) == 1, 'конфликтующий ключ создал не одно сообщение')
|
||||
|
||||
return {'workers': workers, 'accepted': len(accepted), 'conflicts': len(conflicts)}
|
||||
|
||||
|
||||
def replayed_body_is_stable(client, actor, chat):
|
||||
"""Повтор того же смысла, но другого JSON, возвращает исходное сообщение."""
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Форматирование ' + key
|
||||
first = client.message(actor, chat, text, key=key)
|
||||
|
||||
# Тот же payload, другой порядок пробелов в JSON: контракт требует тот же 201
|
||||
# и то же сообщение.
|
||||
spaced = json.dumps({'text': text}, ensure_ascii=False).replace('":', '" :')
|
||||
replay = client.call(
|
||||
'POST',
|
||||
messages_path(chat),
|
||||
201,
|
||||
actor=actor,
|
||||
raw=spaced.encode('utf-8'),
|
||||
headers={'Idempotency-Key': key, 'Content-Type': 'application/json'},
|
||||
schema='Message',
|
||||
)
|
||||
check(replay['json'] == first['json'], 'повтор вернул другое сообщение')
|
||||
|
||||
return {'message_id': first['json']['id']}
|
||||
|
||||
|
||||
def key_is_required(client, actor, chat):
|
||||
client.call('POST', messages_path(chat), 400, actor=actor, body={'text': 'без ключа'}, schema='Error')
|
||||
|
||||
result = client.call(
|
||||
'POST',
|
||||
messages_path(chat),
|
||||
400,
|
||||
actor=actor,
|
||||
body={'text': 'кривой ключ'},
|
||||
headers={'Idempotency-Key': 'bad key!'},
|
||||
schema='Error',
|
||||
)
|
||||
check(result['status'] == 400, 'некорректный ключ обязан быть 400')
|
||||
|
||||
return {'status': result['status']}
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Параллельная идемпотентность сообщений (lab3+); создаёт синтетические данные')
|
||||
check(LAB >= 3, 'параллельная идемпотентность требует lab3+')
|
||||
|
||||
client = Client(args.base_url or BASE_URL, args.ca_file or CA_FILE)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
|
||||
summary = {
|
||||
'replay': replay_confirmed(client, alice, chat),
|
||||
'conflict': conflicting_payloads(client, alice, chat),
|
||||
'stable_body': replayed_body_is_stable(client, alice, chat),
|
||||
'key_required': key_is_required(client, alice, chat),
|
||||
}
|
||||
|
||||
print(json.dumps(summary, ensure_ascii=False))
|
||||
print('PASS: параллельный повтор с одним Idempotency-Key создаёт ровно одно сообщение')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+155
@@ -0,0 +1,155 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab5: accepted work survives a stopped worker and a broker restart.
|
||||
|
||||
Run against a live stand:
|
||||
python3 student-tests/lab5_async.py --base-url https://localhost:8443
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
from tests_helpers import ROOT, compose, jobctl, psql # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def wait_api_ready(client, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
client.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(0.2)
|
||||
raise Failure('API did not become ready after restart')
|
||||
|
||||
|
||||
def wait_state(client, actor, attachment, expected, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
current = client.call('GET', '/api/v1/attachments/' + attachment['id'], actor=actor, schema='Attachment')['json']
|
||||
check(current['status'] != 'failed', 'attachment failed: ' + str(current.get('error_code')))
|
||||
if current['status'] == expected:
|
||||
return current
|
||||
time.sleep(0.2)
|
||||
raise Failure('attachment did not reach ' + expected)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab5 async worker/broker durability')
|
||||
client = Client(args.base_url or BASE_URL, args.ca_file or CA_FILE)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
content = FIXTURE.read_bytes()
|
||||
|
||||
# 1. Worker down: API still accepts 202, content is 409, the message links.
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
check(attached['status'] == 'queued', '202 snapshot must be queued')
|
||||
queued = client.call('GET', '/api/v1/attachments/' + attached['id'], actor=alice, schema='Attachment')['json']
|
||||
check(queued['status'] == 'queued', 'worker stopped but attachment is not queued')
|
||||
client.call('GET', '/api/v1/attachments/' + attached['id'] + '/content', 409, actor=alice)
|
||||
client.message(alice, chat, '', attachments=[attached['id']])
|
||||
time.sleep(2)
|
||||
still = client.call('GET', '/api/v1/attachments/' + attached['id'], actor=alice, schema='Attachment')['json']
|
||||
check(still['status'] == 'queued', 'worker stopped but job was processed synchronously')
|
||||
# The README demo restarts the API after the 202 and before the worker.
|
||||
compose('restart', 'api')
|
||||
wait_api_ready(client)
|
||||
print('worker down: 202 queued, content 409, queued attachment linked, API restarted')
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', 'worker', check=False)
|
||||
|
||||
ready = client.wait_ready(alice, attached)
|
||||
thumb = client.call('GET', '/api/v1/attachments/' + ready['id'] + '/content?variant=thumbnail', actor=bob)
|
||||
check(thumb['headers'].get_content_type() == 'image/jpeg', 'thumbnail content type mismatch')
|
||||
download = client.call('GET', '/api/v1/attachments/' + ready['id'] + '/content', actor=bob)
|
||||
check(download['bytes'] == content, 'original bytes changed')
|
||||
check(psql("select coalesce(staging_key, '') from attachments where id='%s'" % ready['id']) == '',
|
||||
'staging key was not cleared after ready')
|
||||
print('worker restarted: ready, thumbnail and original downloadable, staging cleared')
|
||||
|
||||
# 2. Broker restart with its volume: an intent accepted while the broker is
|
||||
# down is published by the relay after recovery.
|
||||
compose('stop', 'relay')
|
||||
compose('stop', 'broker')
|
||||
try:
|
||||
during, _ = client.attachment(alice, chat)
|
||||
check(during['status'] == 'queued', 'upload during broker outage must be queued')
|
||||
print('broker down: upload accepted into outbox')
|
||||
finally:
|
||||
compose('up', '-d', '--wait', '--no-deps', 'broker', check=False)
|
||||
compose('up', '-d', '--no-deps', 'relay', check=False)
|
||||
|
||||
ready = client.wait_ready(alice, during, wait_seconds=90)
|
||||
print('broker + relay recovered: queued job reached ready')
|
||||
|
||||
# 3. A full stack restart with volumes keeps ready data and the worker path.
|
||||
compose('restart', 'api', 'worker', 'relay')
|
||||
wait_api_ready(client)
|
||||
recovered = client.call('GET', '/api/v1/attachments/' + ready['id'], actor=bob, schema='Attachment')['json']
|
||||
check(recovered['status'] == 'ready', 'ready attachment lost across restart')
|
||||
body = client.call('GET', '/api/v1/attachments/' + ready['id'] + '/content', actor=bob)
|
||||
check(body['bytes'] == content, 'original lost across restart')
|
||||
print('stack restart: ready attachment and original preserved')
|
||||
|
||||
# 4. Reprocess of a queued upload while the worker is down. The final
|
||||
# original has never been written, so pipeline 2 must source from staging;
|
||||
# pointing at the not-yet-existing final original superseded v1 and left
|
||||
# the attachment queued forever with v2 failed (source_missing).
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
pinned, _ = client.attachment(alice, chat)
|
||||
check(pinned['status'] == 'queued', 'reprocess fixture must be queued')
|
||||
result = jobctl('reprocess', '-attachment', pinned['id'], '-pipeline', '2')
|
||||
check('SourceKey' in result.stdout, 'reprocess did not return the created job')
|
||||
queued2 = client.call('GET', '/api/v1/attachments/' + pinned['id'], actor=alice, schema='Attachment')['json']
|
||||
check(queued2['status'] == 'queued', 'reprocessed upload is not queued')
|
||||
check(psql("select count(*) from attachment_job_events e join attachment_jobs j on j.job_id=e.job_id where j.attachment_id='%s' and j.pipeline_version=1 and e.event='superseded'" % pinned['id']) == '1',
|
||||
'reprocess did not record the v1 superseded event')
|
||||
print('worker down: reprocess pipeline 2 accepted, v1 audit event recorded, upload still queued')
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', 'worker', check=False)
|
||||
|
||||
ready2 = client.wait_ready(alice, pinned, wait_seconds=90)
|
||||
check(psql("select pipeline_version from attachments where id='%s'" % pinned['id']) == '2',
|
||||
'serving pipeline version is not 2 after reprocess')
|
||||
check(psql("select status from attachment_jobs where attachment_id='%s' order by pipeline_version" % pinned['id']) == 'superseded\nready',
|
||||
'old job not superseded or new job not ready')
|
||||
print('worker up: reprocessed upload reached ready at pipeline 2, v1 superseded')
|
||||
|
||||
# 5. A pipeline version the worker cannot execute must be refused by the
|
||||
# operator CLI before any state change; the accepted v1 upload keeps its
|
||||
# job and finishes normally instead of being superseded into queued.
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
preserved, _ = client.attachment(alice, chat)
|
||||
check(preserved['status'] == 'queued', 'unsupported-pipeline fixture must be queued')
|
||||
refused = jobctl('reprocess', '-attachment', preserved['id'], '-pipeline', '3', check=False)
|
||||
check(refused.returncode != 0 and 'unsupported pipeline version 3' in refused.stderr,
|
||||
'unsupported pipeline version was not rejected')
|
||||
check(psql("select status from attachment_jobs where attachment_id='%s' and pipeline_version=1" % preserved['id']) == 'queued',
|
||||
'v1 job changed by rejected reprocess')
|
||||
print('worker down: reprocess pipeline 3 refused, v1 job untouched')
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', 'worker', check=False)
|
||||
|
||||
client.wait_ready(alice, preserved, wait_seconds=90)
|
||||
check(psql("select pipeline_version from attachments where id='%s'" % preserved['id']) == '1',
|
||||
'rejected reprocess changed serving version')
|
||||
print('worker up: preserved upload reached ready at pipeline 1')
|
||||
|
||||
print('PASS: lab5 async worker/broker durability')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
run(main)
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', 'worker', 'relay', check=False)
|
||||
Executable
+321
@@ -0,0 +1,321 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab5 level 4: retry, DLQ/replay, crash windows, lease takeover.
|
||||
|
||||
The stand must be running. The script temporarily recreates worker/relay with
|
||||
FAULTS_ENABLED=1 and targeted failpoints, then restores the normal services.
|
||||
|
||||
python3 student-tests/lab5_faults.py --base-url https://localhost:8443
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
from tests_helpers import compose, jobctl, psql # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def worker_with(**env):
|
||||
compose('up', '-d', '--force-recreate', '--no-deps', 'worker', env=env)
|
||||
|
||||
|
||||
def relay_with(**env):
|
||||
compose('up', '-d', '--force-recreate', '--no-deps', 'relay', env=env)
|
||||
|
||||
|
||||
def reset_worker():
|
||||
worker_with()
|
||||
|
||||
|
||||
def reset_relay():
|
||||
relay_with()
|
||||
|
||||
|
||||
def job_id(attachment_id):
|
||||
value = psql("select job_id from attachment_jobs where attachment_id = '%s'" % attachment_id)
|
||||
check(bool(value), 'job row is missing for ' + attachment_id)
|
||||
|
||||
return value.splitlines()[0]
|
||||
|
||||
|
||||
def wait_db(attachment_id, predicate, timeout=120, description=''):
|
||||
deadline = time.monotonic() + timeout
|
||||
last = ''
|
||||
while time.monotonic() < deadline:
|
||||
rows = psql("select a.status || '|' || coalesce(a.error_code,'') || '|' || j.attempt from attachments a join attachment_jobs j on j.attachment_id=a.id where a.id='%s'" % attachment_id)
|
||||
if rows:
|
||||
last = rows.splitlines()[0]
|
||||
status, error, attempt = last.split('|')
|
||||
if predicate(status, error, int(attempt)):
|
||||
return status, error, int(attempt)
|
||||
time.sleep(0.2)
|
||||
raise Failure('timeout waiting for ' + description + ' (last=' + last + ')')
|
||||
|
||||
|
||||
def queue_messages(name):
|
||||
result = compose('exec', '-T', 'broker', 'rabbitmqctl', '-p', 'messenger',
|
||||
'list_queues', 'name', 'messages')
|
||||
for line in result.stdout.splitlines():
|
||||
if line.startswith(name):
|
||||
return int(line.split()[1])
|
||||
return 0
|
||||
|
||||
|
||||
def scenario_permanent_failure_and_replay(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
|
||||
worker_with(FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_FAIL='permanent')
|
||||
status, code, attempts = wait_db(attached['id'], lambda s, e, a: s == 'failed', 40, 'permanent failure')
|
||||
check(code == 'injected_failure', 'unexpected permanent error_code: ' + code)
|
||||
check(attempts == 1, 'a permanent error must not consume retries')
|
||||
meta = client.call('GET', '/api/v1/attachments/' + attached['id'], actor=alice, schema='Attachment')['json']
|
||||
check(meta['status'] == 'failed' and meta['error_code'] == code, 'API did not expose failed/error_code')
|
||||
client.call('GET', '/api/v1/attachments/' + attached['id'] + '/content', 409, actor=alice)
|
||||
client.call(
|
||||
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [attached['id']]},
|
||||
headers={'Idempotency-Key': 'failed-link-' + attached['id']},
|
||||
)
|
||||
failed_view = jobctl('failed', '-limit', '20').stdout
|
||||
check(jid in failed_view, 'failed job is missing from the operator registry')
|
||||
print('permanent failure: failed/' + code + ', content 409, failed attachment not linkable, registry visible')
|
||||
|
||||
reset_worker()
|
||||
replay = jobctl('replay', '-job', jid)
|
||||
check(replay.returncode == 0, 'jobctl replay failed: ' + replay.stderr)
|
||||
ready = client.wait_ready(alice, attached, wait_seconds=60)
|
||||
check(len([v for v in ready['variants'] if v['name'] == 'thumbnail']) == 1, 'replay created a duplicate thumbnail')
|
||||
print('replay: failed -> queued -> ready, one thumbnail')
|
||||
|
||||
# Replay of a ready job must be refused and must not create another effect.
|
||||
again = jobctl('replay', '-job', jid, check=False)
|
||||
check(again.returncode != 0, 'replay of a ready job must be refused')
|
||||
print('replay ready job: refused')
|
||||
|
||||
|
||||
def scenario_transient_exhaustion(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
|
||||
dlq_before = queue_messages('attachment.process.dead')
|
||||
|
||||
worker_with(
|
||||
FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_FAIL='transient',
|
||||
PROCESSING_RETRY_BASE='100ms', PROCESSING_RETRY_CAP='500ms',
|
||||
)
|
||||
status, code, attempts = wait_db(attached['id'], lambda s, e, a: s == 'failed', 120, 'retry exhaustion')
|
||||
check(attempts == 5, 'retry cap must be exactly 5, got ' + str(attempts))
|
||||
check(code == 'retry_exhausted', 'unexpected exhaustion code: ' + code)
|
||||
events = psql("select event || ':' || coalesce(attempt,0) from attachment_job_events where job_id='%s' order by id" % jid)
|
||||
check(events.count('retried:') == 4, 'expected four managed retries: ' + events)
|
||||
check(events.count('failed:') == 1, 'expected one terminal failure: ' + events)
|
||||
deadline = time.monotonic() + 15
|
||||
while time.monotonic() < deadline:
|
||||
if queue_messages('attachment.process.dead') >= dlq_before + 1:
|
||||
break
|
||||
time.sleep(0.2)
|
||||
|
||||
check(queue_messages('attachment.process.dead') >= dlq_before + 1,
|
||||
'terminal failure did not add a DLQ message')
|
||||
print('transient exhaustion: attempts=5, retry_exhausted, four retries, DLQ message present')
|
||||
|
||||
reset_worker()
|
||||
|
||||
|
||||
def scenario_crash_after_first_variant(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
|
||||
relay_with(OUTBOX_REAPER_INTERVAL='2s')
|
||||
worker_with(
|
||||
FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_AFTER_FIRST_VARIANT='exit',
|
||||
PROCESSING_LEASE_TTL='15s', PROCESSING_HEARTBEAT='3s', PROCESSING_JOB_TIMEOUT='10s',
|
||||
)
|
||||
|
||||
ready = client.wait_ready(alice, attached, wait_seconds=90)
|
||||
status, _, attempts = wait_db(attached['id'], lambda s, e, a: s == 'ready', 10, 'crash recovery')
|
||||
check(attempts >= 2, 'crash recovery must use a new managed attempt, got ' + str(attempts))
|
||||
names = sorted(v['name'] for v in ready['variants'])
|
||||
check(names == ['crop', 'optimized', 'thumbnail'], 'duplicate/partial variant set: ' + str(names))
|
||||
print('crash after first variant: redelivered, same three variants, attempts=' + str(attempts))
|
||||
|
||||
reset_worker()
|
||||
reset_relay()
|
||||
|
||||
|
||||
def scenario_crash_after_commit(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
|
||||
worker_with(FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_AFTER_COMMIT='exit')
|
||||
ready = client.wait_ready(alice, attached, wait_seconds=60)
|
||||
check(ready['status'] == 'ready', 'job did not stay ready after commit/ack crash')
|
||||
check(psql("select attempt from attachment_jobs where job_id='%s'" % jid) == '1',
|
||||
'redelivery after ready must be a no-op, not a new attempt')
|
||||
print('crash after commit before ack: ready remains, redelivery is a no-op')
|
||||
|
||||
reset_worker()
|
||||
|
||||
|
||||
def scenario_crash_before_side_effect(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
|
||||
relay_with(OUTBOX_REAPER_INTERVAL='2s')
|
||||
worker_with(
|
||||
FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_AFTER_CLAIM='exit',
|
||||
PROCESSING_LEASE_TTL='15s', PROCESSING_HEARTBEAT='3s', PROCESSING_JOB_TIMEOUT='12s',
|
||||
)
|
||||
|
||||
ready = client.wait_ready(alice, attached, wait_seconds=90)
|
||||
status, _, attempts = wait_db(attached['id'], lambda s, e, a: s == 'ready', 10, 'pre-effect crash recovery')
|
||||
check(attempts >= 2, 'pre-effect crash must use a new managed attempt, got ' + str(attempts))
|
||||
check(sorted(v['name'] for v in ready['variants']) == ['crop', 'optimized', 'thumbnail'],
|
||||
'pre-effect crash produced an incomplete variant set')
|
||||
print('crash after claim before side effect: requeued, attempts=' + str(attempts) + ', ready')
|
||||
|
||||
reset_worker()
|
||||
reset_relay()
|
||||
|
||||
|
||||
def scenario_outbox_gap(client, alice, chat):
|
||||
compose('stop', 'relay')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
unpublished = psql("select count(*) from outbox_messages where job_id='%s' and published_at is null" % jid)
|
||||
check(unpublished == '1', 'upload did not leave a durable outbox intent')
|
||||
|
||||
relay_with(FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_OUTBOX_AFTER_COMMIT='exit')
|
||||
ready = client.wait_ready(alice, attached, wait_seconds=90)
|
||||
check(psql("select count(*) from outbox_messages where job_id='%s' and published_at is null" % jid) == '0',
|
||||
'outbox row stayed unpublished after recovery')
|
||||
print('outbox gap: crash before publish recovered through the relay, outbox published, ready')
|
||||
reset_relay()
|
||||
|
||||
|
||||
def scenario_lease_takeover(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
|
||||
relay_with(OUTBOX_REAPER_INTERVAL='1s')
|
||||
worker_with(
|
||||
FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_SLEEP_AFTER_CLAIM='8s',
|
||||
PROCESSING_LEASE_TTL='15s', PROCESSING_HEARTBEAT='3s', PROCESSING_JOB_TIMEOUT='12s',
|
||||
)
|
||||
|
||||
wait_db(attached['id'], lambda s, e, a: s == 'processing', 20, 'processing claim')
|
||||
compose('pause', 'worker')
|
||||
wait_db(attached['id'], lambda s, e, a: s == 'queued' and a >= 2, 30, 'lease expiry requeue')
|
||||
compose('unpause', 'worker')
|
||||
ready = client.wait_ready(alice, attached, wait_seconds=60)
|
||||
check(len(ready['variants']) == 3, 'lease takeover produced an incomplete variant set')
|
||||
print('lease expiry: paused worker, reaper requeued, stale attempt fenced, ready')
|
||||
|
||||
reset_worker()
|
||||
reset_relay()
|
||||
|
||||
|
||||
def scenario_replay_reprocessed_version(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
reprocessed = json.loads(jobctl('reprocess', '-attachment', attached['id'], '-pipeline', '2').stdout)
|
||||
jid = reprocessed['ID']
|
||||
|
||||
worker_with(FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_FAIL='permanent')
|
||||
|
||||
deadline = time.monotonic() + 40
|
||||
last = ''
|
||||
while time.monotonic() < deadline:
|
||||
job_status = psql("select status from attachment_jobs where job_id='%s'" % jid)
|
||||
last = psql("select status || '|' || coalesce(error_code,'') from attachments where id='%s'" % attached['id'])
|
||||
if job_status == 'failed' and last.startswith('failed|'):
|
||||
break
|
||||
time.sleep(0.2)
|
||||
|
||||
check(job_status == 'failed' and last == 'failed|injected_failure',
|
||||
'reprocessed failure did not settle: ' + last)
|
||||
|
||||
compose('stop', 'worker')
|
||||
jobctl('replay', '-job', jid)
|
||||
projection = client.call(
|
||||
'GET', '/api/v1/attachments/' + attached['id'], actor=alice, schema='Attachment',
|
||||
)['json']
|
||||
check(projection['status'] == 'queued' and projection['error_code'] is None,
|
||||
'replay left stale terminal projection: ' + str(projection['status']))
|
||||
|
||||
reset_worker()
|
||||
client.wait_ready(alice, attached, wait_seconds=90)
|
||||
check(psql("select pipeline_version from attachments where id='%s'" % attached['id']) == '2',
|
||||
'replayed reprocess did not publish pipeline 2')
|
||||
print('replay of failed reprocess: queued projection restored, then ready at pipeline 2')
|
||||
|
||||
|
||||
def scenario_replay_older_version_refused(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid_v1 = job_id(attached['id'])
|
||||
|
||||
worker_with(FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid_v1, FAULT_WORKER_FAIL='permanent')
|
||||
status, code, _ = wait_db(attached['id'], lambda s, e, a: s == 'failed', 40, 'failed v1')
|
||||
check(code == 'injected_failure', 'unexpected v1 failure: ' + code)
|
||||
|
||||
compose('stop', 'worker')
|
||||
reprocessed = json.loads(jobctl('reprocess', '-attachment', attached['id'], '-pipeline', '2').stdout)
|
||||
refused = jobctl('replay', '-job', jid_v1, check=False)
|
||||
check(refused.returncode != 0, 'older failed version was replayed while v2 exists')
|
||||
jobs = psql("select pipeline_version || ':' || status from attachment_jobs where attachment_id='%s' order by pipeline_version" % attached['id'])
|
||||
check(jobs == '1:failed\n2:queued', 'older replay changed job state: ' + jobs.replace('\n', ', '))
|
||||
print('replay older failed version while v2 queued: refused, state intact')
|
||||
|
||||
reset_worker()
|
||||
client.wait_ready(alice, attached, wait_seconds=90)
|
||||
check(psql("select pipeline_version from attachments where id='%s'" % attached['id']) == '2',
|
||||
'v2 did not publish after older replay was refused')
|
||||
check(psql("select job_id from attachment_jobs where attachment_id='%s' and pipeline_version=2" % attached['id']) == reprocessed['ID'],
|
||||
'v2 job identity changed')
|
||||
print('v2 published after older replay refusal')
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab5 level 4 fault injection')
|
||||
client = Client(args.base_url or BASE_URL, args.ca_file or CA_FILE)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
|
||||
scenarios = [
|
||||
scenario_permanent_failure_and_replay,
|
||||
scenario_replay_older_version_refused,
|
||||
scenario_replay_reprocessed_version,
|
||||
scenario_transient_exhaustion,
|
||||
scenario_crash_after_first_variant,
|
||||
scenario_crash_after_commit,
|
||||
scenario_crash_before_side_effect,
|
||||
scenario_outbox_gap,
|
||||
scenario_lease_takeover,
|
||||
]
|
||||
|
||||
try:
|
||||
for scenario in scenarios:
|
||||
scenario(client, alice, chat)
|
||||
finally:
|
||||
reset_worker()
|
||||
reset_relay()
|
||||
|
||||
print('PASS: lab5 level 4 fault injection')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+91
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab5: metadata, bytes and dimensions of all contract variants.
|
||||
|
||||
Run against a live stand:
|
||||
python3 student-tests/lab5_variants.py --base-url https://localhost:8443
|
||||
"""
|
||||
import hashlib
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
from image_probe import jpeg_size # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def webp_size(data):
|
||||
check(data[:4] == b'RIFF' and data[8:12] == b'WEBP', 'not a WebP container')
|
||||
|
||||
chunk = data[12:16]
|
||||
if chunk == b'VP8X':
|
||||
width = 1 + int.from_bytes(data[24:27], 'little')
|
||||
height = 1 + int.from_bytes(data[27:30], 'little')
|
||||
return width, height
|
||||
if chunk == b'VP8 ':
|
||||
start = data.index(b'\x9d\x01\x2a', 12) + 3
|
||||
width = int.from_bytes(data[start:start + 2], 'little') & 0x3fff
|
||||
height = int.from_bytes(data[start + 2:start + 4], 'little') & 0x3fff
|
||||
return width, height
|
||||
if chunk == b'VP8L':
|
||||
bits = int.from_bytes(data[21:25], 'little')
|
||||
width = (bits & 0x3fff) + 1
|
||||
height = ((bits >> 14) & 0x3fff) + 1
|
||||
return width, height
|
||||
raise Failure('unsupported WebP chunk ' + repr(chunk))
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab5 variant contract')
|
||||
client = Client(args.base_url or BASE_URL, args.ca_file or CA_FILE)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
|
||||
attached, content = client.attachment(alice, chat)
|
||||
ready = client.wait_ready(alice, attached)
|
||||
|
||||
by_name = {variant['name']: variant for variant in ready['variants']}
|
||||
check(set(by_name) == {'thumbnail', 'crop', 'optimized'}, 'unexpected variant set: ' + str(sorted(by_name)))
|
||||
|
||||
expected = {
|
||||
'thumbnail': ('image/jpeg', (256, 160)),
|
||||
'crop': ('image/jpeg', (128, 128)),
|
||||
'optimized': ('image/webp', (320, 200)),
|
||||
}
|
||||
|
||||
for name, (content_type, dims) in expected.items():
|
||||
variant = by_name[name]
|
||||
response = client.call(
|
||||
'GET', '/api/v1/attachments/' + ready['id'] + '/content?variant=' + name, actor=bob,
|
||||
)
|
||||
data = response['bytes']
|
||||
check(response['headers'].get_content_type() == content_type, name + ' content type mismatch')
|
||||
check(variant['content_type'] == content_type, name + ' metadata content type mismatch')
|
||||
check(len(data) == variant['size_bytes'], name + ' size_bytes mismatch')
|
||||
check(hashlib.sha256(data).hexdigest() == variant['sha256'], name + ' sha256 mismatch')
|
||||
|
||||
if name == 'optimized':
|
||||
actual = webp_size(data)
|
||||
check(actual == dims, name + ' dimensions ' + str(actual))
|
||||
check(b'EXIF' not in data[:64], 'optimized WebP must not carry EXIF')
|
||||
else:
|
||||
actual = jpeg_size(data)
|
||||
check(actual == dims, name + ' dimensions ' + str(actual))
|
||||
check('Exif' not in data[:64].decode('latin-1', 'ignore'), name + ' must not carry EXIF')
|
||||
check((variant['width'], variant['height']) == dims, name + ' metadata dimensions mismatch')
|
||||
|
||||
original = client.call('GET', '/api/v1/attachments/' + ready['id'] + '/content', actor=bob)
|
||||
check(original['bytes'] == content, 'original bytes changed')
|
||||
check(original['headers'].get_content_type() == 'image/png', 'original content type changed')
|
||||
|
||||
print('variants: thumbnail 256x160, crop 128x128, optimized WebP 320x200; metadata == bytes')
|
||||
print('PASS: lab5 variant contract')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+720
@@ -0,0 +1,720 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded, secret-redacting local lab7 protocol and operator helpers.
|
||||
|
||||
Internal probes run this module on stdin in python:3.14-slim, on the selected
|
||||
Compose default network, with only explicitly selected read-only identities.
|
||||
No probe treats a timeout, EOF, or connection refusal as certificate denial.
|
||||
"""
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import hmac
|
||||
from http.client import HTTPSConnection, HTTPException
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import socket
|
||||
import ssl
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] if __file__ != '<stdin>' else Path('/work')
|
||||
TIMEOUT = 5
|
||||
|
||||
|
||||
class ProbeFailure(Exception):
|
||||
def __init__(self, classification, detail=''):
|
||||
self.classification = classification
|
||||
self.detail = detail
|
||||
super().__init__(classification + (': ' + detail if detail else ''))
|
||||
|
||||
|
||||
def require(condition, classification, detail=''):
|
||||
if not condition:
|
||||
raise ProbeFailure(classification, detail)
|
||||
|
||||
|
||||
def command(argv, *, env=None, input=None, timeout=60, check=True):
|
||||
try:
|
||||
result = subprocess.run(argv, cwd=ROOT, env={**os.environ, **(env or {})},
|
||||
input=input, capture_output=True, text=True, timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise ProbeFailure('command_timeout') from None
|
||||
except OSError:
|
||||
raise ProbeFailure('command_unavailable') from None
|
||||
if check and result.returncode:
|
||||
# Tool output can contain credentials; it never enters evidence.
|
||||
raise ProbeFailure('command_failed', Path(argv[0]).name)
|
||||
return result
|
||||
|
||||
|
||||
def sanitized(value):
|
||||
if isinstance(value, dict):
|
||||
private = {'password', 'secret_key', 'access_key', 'client_token', 'root_token', 'token',
|
||||
'unseal_keys', 'unseal_keys_b64', 'private_key', 'tls_key', 'tls.pem', 'tls.key'}
|
||||
return {key: sanitized(item) for key, item in value.items() if key.lower() not in private}
|
||||
if isinstance(value, list):
|
||||
return [sanitized(item) for item in value]
|
||||
return value
|
||||
|
||||
def temporary_directory(prefix):
|
||||
# macOS /var/folders is not shared with Docker Desktop. Use an operator-only
|
||||
# directory outside the checkout, on the shared user filesystem.
|
||||
parent = Path.home() / '.local/share/mtusi-lab7/probes'
|
||||
parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
parent.chmod(0o700)
|
||||
return tempfile.TemporaryDirectory(prefix=prefix, dir=parent)
|
||||
|
||||
|
||||
class Stand:
|
||||
def __init__(self, project=None, secrets=None, base_url='https://localhost:8443', env=None):
|
||||
self.project = project or os.environ.get('COMPOSE_PROJECT_NAME', 'mtusi-messenger-lab6')
|
||||
require(self.project.startswith('mtusi-'), 'unsafe_project')
|
||||
self.secrets = Path(secrets or os.environ.get('LAB7_SECRETS_DIR', 'secrets/lab7')).resolve()
|
||||
self.base_url = base_url
|
||||
parsed = urllib.parse.urlsplit(base_url)
|
||||
require(parsed.scheme == 'https' and parsed.hostname in ('localhost', '127.0.0.1'), 'nonlocal_target')
|
||||
endpoint = os.environ.get('DOCKER_HOST')
|
||||
selected_context = os.environ.get('DOCKER_CONTEXT')
|
||||
if not endpoint or selected_context:
|
||||
metadata = command(['docker', 'context', 'inspect', *([selected_context] if selected_context else [])])
|
||||
try:
|
||||
endpoint = json.loads(metadata.stdout)[0]['Endpoints']['docker']['Host']
|
||||
except (ValueError, KeyError, IndexError):
|
||||
raise ProbeFailure('docker_endpoint_unknown') from None
|
||||
require(endpoint.startswith('unix://'), 'nonlocal_docker_endpoint')
|
||||
for key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(key, None)
|
||||
os.environ['NO_PROXY'] = '*'
|
||||
os.environ['no_proxy'] = '*'
|
||||
self.env = {**(env or {}), 'COMPOSE_PROJECT_NAME': self.project, 'LAB7_SECRETS_DIR': str(self.secrets)}
|
||||
self.overrides = []
|
||||
|
||||
def compose(self, *args, timeout=120, check=True):
|
||||
argv = ['docker', 'compose', '--project-name', self.project, '--env-file', '.env', '-f', 'compose.yaml']
|
||||
for path in self.overrides:
|
||||
argv += ['-f', str(path)]
|
||||
return command([*argv, *args], env=self.env, timeout=timeout, check=check)
|
||||
|
||||
def security(self, *args, timeout=180):
|
||||
result = command([sys.executable, 'scripts/securityctl.py', *args], env=self.env, timeout=timeout)
|
||||
try:
|
||||
payload = json.loads(result.stdout)
|
||||
except ValueError:
|
||||
raise ProbeFailure('securityctl_invalid_json') from None
|
||||
require(isinstance(payload, dict), 'securityctl_invalid_json')
|
||||
return sanitized(payload)
|
||||
|
||||
def containers(self, service=None):
|
||||
argv = ['docker', 'ps', '-aq', '--filter', 'label=com.docker.compose.project=' + self.project]
|
||||
if service:
|
||||
argv += ['--filter', 'label=com.docker.compose.service=' + service]
|
||||
ids = command(argv).stdout.split()
|
||||
return json.loads(command(['docker', 'inspect', *ids]).stdout) if ids else []
|
||||
|
||||
def network(self, selector='default'):
|
||||
require(selector in ('default', 'observability', 'edge'), 'unsafe_probe_network')
|
||||
names = command(['docker', 'network', 'ls', '-q', '--filter',
|
||||
'label=com.docker.compose.project=' + self.project, '--filter',
|
||||
'label=com.docker.compose.network=' + selector]).stdout.split()
|
||||
require(len(names) == 1, 'compose_probe_network_missing', selector)
|
||||
info = json.loads(command(['docker', 'network', 'inspect', names[0]]).stdout)[0]
|
||||
require(info['Driver'] == 'bridge', 'unsafe_network_driver')
|
||||
return info['Name']
|
||||
|
||||
def probe(self, kind, roles=(), credentials=False, config=None, extra_mounts=(), control_dir=None, timeout=90, network='default'):
|
||||
name = self.project + '-probe-' + uuid.uuid4().hex[:10]
|
||||
argv = ['docker', 'run', '--rm', '-i', '--name', name, '--network', self.network(network),
|
||||
'--read-only', '--cap-drop=ALL', '--security-opt=no-new-privileges',
|
||||
'--pids-limit=64', '--memory=128m', '--cpus=0.5', '--user=' + str(os.getuid()) + ':10001']
|
||||
for role in roles:
|
||||
require(role.replace('-', '').isalnum(), 'invalid_identity_role')
|
||||
argv += ['--mount', 'type=bind,src=' + str(self.secrets / 'pki' / role) + ',dst=/pki/' + role + ',readonly']
|
||||
if credentials:
|
||||
argv += ['--mount', 'type=bind,src=' + str(self.secrets / 'backends/credentials.json') + ',dst=/credentials.json,readonly']
|
||||
for source, target in extra_mounts:
|
||||
argv += ['--mount', 'type=bind,src=' + str(Path(source).resolve()) + ',dst=' + target + ',readonly']
|
||||
if control_dir:
|
||||
argv += ['--mount', 'type=bind,src=' + str(Path(control_dir).resolve()) + ',dst=/control']
|
||||
cfg = config or {}
|
||||
operation = ':'.join(str(value) for value in (kind, cfg.get('host', ''), cfg.get('port', ''), cfg.get('role', ''), cfg.get('operation', '')))
|
||||
argv += ['python:3.14-slim', 'python', '-', '--internal', kind, json.dumps(cfg, separators=(',', ':'))]
|
||||
try:
|
||||
result = command(argv, input=Path(__file__).read_text(), env=self.env, timeout=timeout, check=False)
|
||||
try:
|
||||
payload = json.loads(result.stdout)
|
||||
except ValueError:
|
||||
stderr_class = 'unclassified'
|
||||
for marker, classification in (('mounts denied', 'mount_denied'), ('bind source path', 'bind_source_missing'),
|
||||
('permission denied', 'permission_denied'), ('network', 'network_launch_error')):
|
||||
if marker in result.stderr.lower():
|
||||
stderr_class = classification
|
||||
break
|
||||
detail = operation + ';exit=' + str(result.returncode) + ';stderr_class=' + stderr_class
|
||||
detail += ';stdout_bytes=' + str(len(result.stdout)) + ';stderr_bytes=' + str(len(result.stderr))
|
||||
raise ProbeFailure('probe_container_failed', detail) from None
|
||||
if result.returncode:
|
||||
detail = operation + ';' + str(payload.get('detail', ''))
|
||||
if payload.get('type'):
|
||||
detail += ';type=' + str(payload['type'])
|
||||
if payload.get('errno') is not None:
|
||||
detail += ';errno=' + str(payload['errno'])
|
||||
raise ProbeFailure(payload.get('classification', 'probe_failed'), detail)
|
||||
return payload
|
||||
finally:
|
||||
command(['docker', 'rm', '-f', name], check=False, timeout=15)
|
||||
|
||||
def psql(self, sql, role=None, check=True):
|
||||
postgres = self.containers('postgres')
|
||||
require(len(postgres) == 1, 'postgres_container_missing')
|
||||
creds = json.loads((self.secrets / 'backends/credentials.json').read_text())
|
||||
admin = creds['postgres']['operator']['username']
|
||||
require(admin.replace('_', '').isalnum(), 'unsafe_database_username')
|
||||
if role:
|
||||
require(role in ('api', 'worker', 'relay', 'operator'), 'unsafe_database_role')
|
||||
username = creds['postgres'][role]['username']
|
||||
require(username.replace('_', '').isalnum(), 'unsafe_database_username')
|
||||
sql = 'SET ROLE "' + username + '"; ' + sql
|
||||
# Local Unix-socket administrator, never a credential on argv. SET ROLE
|
||||
# tests actual privileges; errors must specifically carry SQLSTATE 42501.
|
||||
return command(['docker', 'exec', '-i', postgres[0]['Id'], 'psql', '-X', '-U', admin,
|
||||
'-d', 'messenger', '-v', 'ON_ERROR_STOP=1', '-v', 'VERBOSITY=verbose', '-At'],
|
||||
input='SET statement_timeout=5000; ' + sql, check=check, timeout=15)
|
||||
|
||||
|
||||
def context(role=None, ca=None):
|
||||
ca = ca or '/pki/' + (role or 'operator') + '/current/ca.crt'
|
||||
ctx = ssl.create_default_context(cafile=ca)
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
if role:
|
||||
ctx.load_cert_chain('/pki/' + role + '/current/tls.crt', '/pki/' + role + '/current/tls.key')
|
||||
return ctx
|
||||
|
||||
|
||||
def transport_detail(exc):
|
||||
if isinstance(exc, ssl.SSLCertVerificationError):
|
||||
return 'verify_code=' + str(exc.verify_code)
|
||||
if isinstance(exc, ssl.SSLError):
|
||||
return str(exc.reason or '')[:200]
|
||||
return ''
|
||||
|
||||
|
||||
def transport_error(exc):
|
||||
if isinstance(exc, ssl.SSLCertVerificationError):
|
||||
return 'hostname_rejected' if exc.verify_code in (62, 64) else 'ca_rejected'
|
||||
if isinstance(exc, ssl.SSLError):
|
||||
reason = str(exc.reason or '').upper()
|
||||
if any(x in reason for x in ('CERTIFICATE_REQUIRED', 'BAD_CERTIFICATE', 'UNKNOWN_CA', 'CERTIFICATE_EXPIRED', 'CERTIFICATE_REVOKED', 'CERTIFICATE_UNKNOWN', 'ACCESS_DENIED')):
|
||||
return 'tls_certificate_rejected'
|
||||
return 'tls_protocol_error'
|
||||
if isinstance(exc, (TimeoutError, socket.timeout)):
|
||||
return 'network_timeout'
|
||||
if isinstance(exc, ConnectionRefusedError):
|
||||
return 'connection_refused'
|
||||
return 'connection_error'
|
||||
|
||||
|
||||
def http(host, port, method, path, *, role=None, ca=None, body=b'', headers=None, ctx=None, connect_host=None):
|
||||
conn = HTTPSConnection(host, port, timeout=TIMEOUT, context=ctx or context(role, ca))
|
||||
try:
|
||||
if connect_host:
|
||||
raw = socket.create_connection((connect_host, port), TIMEOUT)
|
||||
conn.sock = (ctx or context(role, ca)).wrap_socket(raw, server_hostname=host)
|
||||
conn.request(method, path, body=body, headers=headers or {})
|
||||
serial = conn.sock.getpeercert().get('serialNumber') if conn.sock else None
|
||||
response = conn.getresponse()
|
||||
data = response.read(2 * 1024 * 1024 + 1)
|
||||
require(len(data) <= 2 * 1024 * 1024, 'response_too_large')
|
||||
return {'status': response.status, 'headers': dict(response.headers), 'body': data,
|
||||
'serial': serial}
|
||||
except (OSError, HTTPException) as exc:
|
||||
raise ProbeFailure(transport_error(exc), transport_detail(exc)) from None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def tls_probe(cfg):
|
||||
try:
|
||||
response = http(cfg['host'], cfg['port'], cfg.get('method', 'GET'), cfg.get('path', '/health/ready'),
|
||||
role=cfg.get('role'), ca=cfg.get('ca'), connect_host=cfg.get('connect_host'),
|
||||
body=cfg.get('body', '').encode(), headers=cfg.get('headers'))
|
||||
return {'classification': 'http_response', 'status': response['status'], 'serial': response['serial']}
|
||||
except ProbeFailure as exc:
|
||||
return {'classification': exc.classification, 'detail': exc.detail}
|
||||
|
||||
|
||||
def bao_probe(cfg):
|
||||
role = cfg.get('role', 'api')
|
||||
login = http('openbao', 8200, 'POST', '/v1/auth/cert/login', role=role,
|
||||
body=json.dumps({'name': role}).encode(), headers={'Content-Type': 'application/json'})
|
||||
require(login['status'] == 200, 'bao_cert_auth_failed')
|
||||
token = json.loads(login['body'])['auth']['client_token']
|
||||
headers = {'X-Vault-Token': token, 'Content-Type': 'application/json'}
|
||||
outcomes = {}
|
||||
requests = [('own_kv', 'GET', '/v1/secret/data/' + role, None, 200),
|
||||
('foreign_kv', 'GET', '/v1/secret/data/worker' if role != 'worker' else '/v1/secret/data/api', None, 403),
|
||||
('policy_admin', 'GET', '/v1/sys/policies/acl/api', None, 403),
|
||||
('foreign_issue', 'POST', '/v1/pki/issue/worker' if role != 'worker' else '/v1/pki/issue/api',
|
||||
{'common_name': 'worker', 'uri_sans': 'spiffe://mtusi/worker', 'ttl': '20s'}, 403)]
|
||||
try:
|
||||
for name, method, path, payload, expected in requests:
|
||||
response = http('openbao', 8200, method, path, role=role, headers=headers,
|
||||
body=json.dumps(payload).encode() if payload else b'')
|
||||
require(response['status'] == expected, 'bao_policy_mismatch', name)
|
||||
outcomes[name] = response['status']
|
||||
finally:
|
||||
# Never leave the probe's token active after an allow/deny failure.
|
||||
revoked = http('openbao', 8200, 'POST', '/v1/auth/token/revoke-self', role=role, headers=headers)
|
||||
require(revoked['status'] in (200, 204), 'bao_probe_token_cleanup_failed')
|
||||
return {'classification': 'passed', 'checks': outcomes}
|
||||
|
||||
|
||||
def short(value):
|
||||
data = value.encode()
|
||||
require(len(data) < 256, 'amqp_field_too_long')
|
||||
return bytes([len(data)]) + data
|
||||
|
||||
|
||||
def long(data):
|
||||
return struct.pack('>I', len(data)) + data
|
||||
|
||||
|
||||
class AMQP:
|
||||
def __init__(self, role, mechanism='EXTERNAL', ca=None, response=b''):
|
||||
self.sock = context(role, ca).wrap_socket(socket.create_connection(('broker', 5671), TIMEOUT), server_hostname='broker')
|
||||
self.sock.settimeout(TIMEOUT)
|
||||
self.sock.sendall(b'AMQP\x00\x00\x09\x01')
|
||||
cls, meth, fields = self.method()
|
||||
require((cls, meth) == (10, 10), 'amqp_start_missing')
|
||||
pos = 2 + 4 + struct.unpack('>I', fields[2:6])[0]
|
||||
size = struct.unpack('>I', fields[pos:pos+4])[0]
|
||||
mechanisms = fields[pos+4:pos+4+size].decode().split()
|
||||
self.mechanisms = mechanisms
|
||||
if mechanism is None:
|
||||
return
|
||||
if mechanism == 'EXTERNAL':
|
||||
require(mechanisms == ['EXTERNAL'], 'amqp_plain_enabled')
|
||||
capabilities = short('authentication_failure_close') + b't\x01'
|
||||
properties = short('capabilities') + b'F' + long(capabilities)
|
||||
self.send(0, 10, 11, long(properties) + short(mechanism) + long(response) + short('en_US'))
|
||||
cls, meth, fields = self.method()
|
||||
self.closed(cls, meth, fields)
|
||||
require((cls, meth) == (10, 30), 'amqp_auth_not_accepted')
|
||||
channel_max, frame_max, _ = struct.unpack('>HIH', fields)
|
||||
self.send(0, 10, 31, struct.pack('>HIH', channel_max, frame_max, 0))
|
||||
self.send(0, 10, 40, short('messenger') + short('') + b'\x00')
|
||||
cls, meth, fields = self.method()
|
||||
self.closed(cls, meth, fields)
|
||||
require((cls, meth) == (10, 41), 'amqp_vhost_denied')
|
||||
self.send(1, 20, 10, short(''))
|
||||
cls, meth, fields = self.method()
|
||||
self.closed(cls, meth, fields)
|
||||
require((cls, meth) == (20, 11), 'amqp_channel_open_failed')
|
||||
|
||||
def receive(self, count):
|
||||
data = b''
|
||||
while len(data) < count:
|
||||
chunk = self.sock.recv(count - len(data))
|
||||
require(bool(chunk), 'amqp_unexpected_eof')
|
||||
data += chunk
|
||||
return data
|
||||
|
||||
def frame(self, kind, channel, payload):
|
||||
self.sock.sendall(struct.pack('>BHI', kind, channel, len(payload)) + payload + b'\xce')
|
||||
|
||||
def send(self, channel, cls, meth, fields=b''):
|
||||
self.frame(1, channel, struct.pack('>HH', cls, meth) + fields)
|
||||
|
||||
def method(self):
|
||||
while True:
|
||||
kind, channel, length = struct.unpack('>BHI', self.receive(7))
|
||||
require(length <= 1048576, 'amqp_frame_too_large')
|
||||
payload = self.receive(length)
|
||||
require(self.receive(1) == b'\xce', 'amqp_invalid_frame')
|
||||
if kind == 8:
|
||||
continue
|
||||
require(kind == 1 and len(payload) >= 4, 'amqp_unexpected_frame')
|
||||
return (*struct.unpack('>HH', payload[:4]), payload[4:])
|
||||
|
||||
def closed(self, cls, meth, fields):
|
||||
if (cls, meth) in ((10, 50), (20, 40)):
|
||||
code = struct.unpack('>H', fields[:2])[0]
|
||||
raise ProbeFailure('amqp_rejected', str(code))
|
||||
|
||||
def operation(self, operation):
|
||||
if operation == 'topology':
|
||||
self.send(1, 50, 10, b'\x00\x00' + short('lab7-denied-' + uuid.uuid4().hex) + b'\x00' + struct.pack('>I', 0))
|
||||
elif operation == 'consume':
|
||||
# basic.consume never removes a job: no acknowledgements are sent,
|
||||
# connection immediately closes on consume-ok; deliveries requeue.
|
||||
self.send(1, 60, 20, b'\x00\x00' + short('attachment.process.v1') + short('lab7-probe') + b'\x00' + struct.pack('>I', 0))
|
||||
elif operation == 'publish':
|
||||
self.send(1, 85, 10, b'\x00')
|
||||
cls, meth, fields = self.method()
|
||||
self.closed(cls, meth, fields)
|
||||
require((cls, meth) == (85, 11), 'amqp_confirm_not_accepted')
|
||||
# Unrouted synthetic body cannot become a real processing job.
|
||||
self.send(1, 60, 40, b'\x00\x00' + short('attachments.jobs') + short('lab7.unrouted') + b'\x00')
|
||||
self.frame(2, 1, struct.pack('>HHQH', 60, 0, 2, 0))
|
||||
self.frame(3, 1, b'{}')
|
||||
else:
|
||||
raise ProbeFailure('unknown_amqp_operation')
|
||||
cls, meth, fields = self.method()
|
||||
self.closed(cls, meth, fields)
|
||||
expected = {'topology': (50, 11), 'consume': (60, 21), 'publish': (60, 80)}[operation]
|
||||
require((cls, meth) == expected, 'amqp_unexpected_method')
|
||||
return {'classification': 'amqp_allowed', 'mechanisms': self.mechanisms}
|
||||
|
||||
def close(self):
|
||||
self.sock.close()
|
||||
|
||||
|
||||
def amqp_probe(cfg):
|
||||
conn = None
|
||||
try:
|
||||
operation = cfg.get('operation', 'consume')
|
||||
mechanism = None if operation == 'mechanisms' else cfg.get('mechanism', 'EXTERNAL')
|
||||
conn = AMQP(cfg.get('role'), mechanism, cfg.get('ca'), cfg.get('response', '').encode())
|
||||
if operation == 'mechanisms':
|
||||
return {'classification': 'amqp_mechanisms', 'mechanisms': conn.mechanisms}
|
||||
return conn.operation(operation)
|
||||
except ProbeFailure as exc:
|
||||
return {'classification': exc.classification, 'code': int(exc.detail) if exc.classification == 'amqp_rejected' else None}
|
||||
except OSError as exc:
|
||||
return {'classification': transport_error(exc)}
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
|
||||
|
||||
def s3_request(credential, method, bucket, key='', *, query=None, body=b'', copy_source=None):
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
stamp, day = now.strftime('%Y%m%dT%H%M%SZ'), now.strftime('%Y%m%d')
|
||||
uri = '/' + urllib.parse.quote(bucket, safe='') + ('/' + urllib.parse.quote(key, safe='/~') if key else '')
|
||||
query_string = '&'.join(urllib.parse.quote(str(k), safe='~') + '=' + urllib.parse.quote(str(v), safe='~') for k, v in sorted((query or {}).items()))
|
||||
payload_hash = hashlib.sha256(body).hexdigest()
|
||||
headers = {'host': 'seaweedfs:8333', 'x-amz-content-sha256': payload_hash, 'x-amz-date': stamp}
|
||||
if copy_source:
|
||||
headers['x-amz-copy-source'] = '/' + urllib.parse.quote(copy_source, safe='/~')
|
||||
canonical_headers = ''.join(k + ':' + headers[k].strip() + '\n' for k in sorted(headers))
|
||||
signed = ';'.join(sorted(headers))
|
||||
canonical = '\n'.join((method, uri, query_string, canonical_headers, signed, payload_hash))
|
||||
scope = day + '/us-east-1/s3/aws4_request'
|
||||
to_sign = 'AWS4-HMAC-SHA256\n' + stamp + '\n' + scope + '\n' + hashlib.sha256(canonical.encode()).hexdigest()
|
||||
key_bytes = ('AWS4' + credential['secret_key']).encode()
|
||||
for part in (day, 'us-east-1', 's3', 'aws4_request'):
|
||||
key_bytes = hmac.new(key_bytes, part.encode(), hashlib.sha256).digest()
|
||||
signature = hmac.new(key_bytes, to_sign.encode(), hashlib.sha256).hexdigest()
|
||||
headers['Authorization'] = 'AWS4-HMAC-SHA256 Credential=' + credential['access_key'] + '/' + scope + ', SignedHeaders=' + signed + ', Signature=' + signature
|
||||
return http('seaweedfs', 8333, method, uri + ('?' + query_string if query_string else ''),
|
||||
ca='/pki/operator/current/ca.crt', headers=headers, body=body)
|
||||
|
||||
|
||||
def s3_probe(cfg):
|
||||
creds = json.loads(Path(cfg.get('credentials', '/credentials.json')).read_text())['s3']
|
||||
bucket = cfg.get('bucket', 'messenger-attachments')
|
||||
role = cfg.get('role', 'api')
|
||||
if cfg.get('single'):
|
||||
result = s3_request(creds[role], cfg.get('method', 'GET'), bucket, cfg['key'])
|
||||
return {'classification': 'http_response', 'status': result['status']}
|
||||
tag = 'lab7-' + uuid.uuid4().hex
|
||||
staging, final, foreign = 'staging/uploads/' + tag, 'attachments/' + tag + '/original', 'foreign/' + tag
|
||||
foreign_bucket = 'lab7-foreign-' + uuid.uuid4().hex[:12]
|
||||
data = b'local synthetic ACL fixture'
|
||||
checks = {}
|
||||
def request(name, who, method, target_bucket, key='', expected=(200,), **kw):
|
||||
result = s3_request(creds[who], method, target_bucket, key, **kw)
|
||||
require(result['status'] in expected, 's3_acl_mismatch', name)
|
||||
checks[name] = result['status']
|
||||
return result
|
||||
try:
|
||||
request('foreign_bucket_create', 'operator', 'PUT', foreign_bucket, expected=(200, 204))
|
||||
request('seed_foreign_bucket', 'operator', 'PUT', foreign_bucket, tag, body=data)
|
||||
request('seed_staging', 'operator', 'PUT', bucket, staging, body=data)
|
||||
request('seed_final', 'operator', 'PUT', bucket, final, body=data)
|
||||
request('seed_foreign', 'operator', 'PUT', bucket, foreign, body=data)
|
||||
for who in ('api', 'worker'):
|
||||
for prefix, key in (('staging', staging), ('final', final)):
|
||||
got = request(who + '_' + prefix + '_get', who, 'GET', bucket, key)
|
||||
require(got['body'] == data, 's3_data_changed')
|
||||
for method in ('GET', 'PUT', 'DELETE'):
|
||||
request(who + '_foreign_' + method, who, method, bucket, foreign, expected=(403,), body=data if method == 'PUT' else b'')
|
||||
request(who + '_foreign_bucket_' + method, who, method, foreign_bucket, tag, expected=(403,))
|
||||
listing = request(who + '_foreign_list', who, 'GET', bucket, query={'list-type': '2', 'prefix': 'foreign/'}, expected=(403,) if who == 'api' else (200,))
|
||||
if who == 'worker':
|
||||
keys = [node.text for node in ET.fromstring(listing['body']).iter() if node.tag.rsplit('}', 1)[-1] == 'Key']
|
||||
checks['worker_foreign_metadata_observed'] = foreign in keys
|
||||
request(who + '_foreign_bucket_list', who, 'GET', foreign_bucket, query={'list-type': '2'}, expected=(403,))
|
||||
copy_target = staging + '-copy' if who == 'api' else final + '-copy'
|
||||
own_source = staging if who == 'api' else final
|
||||
request(who + '_copy_owned', who, 'PUT', bucket, copy_target, copy_source=bucket + '/' + own_source)
|
||||
copied = request(who + '_copy_owned_readback', who, 'GET', bucket, copy_target)
|
||||
require(copied['body'] == data, 's3_copy_content_changed')
|
||||
request(who + '_copy_foreign_source', who, 'PUT', bucket, copy_target, copy_source=bucket + '/' + foreign, expected=(403,))
|
||||
request(who + '_copy_foreign_dest', who, 'PUT', bucket, foreign + '-copy', copy_source=bucket + '/' + own_source, expected=(403,))
|
||||
request(who + '_copy_foreign_bucket_source', who, 'PUT', bucket, copy_target, copy_source=foreign_bucket + '/' + tag, expected=(403,))
|
||||
request(who + '_copy_foreign_bucket_dest', who, 'PUT', foreign_bucket, tag, copy_source=bucket + '/' + own_source, expected=(403,))
|
||||
request('api_staging_put', 'api', 'PUT', bucket, staging, body=b'API changed content')
|
||||
api_readback = request('api_staging_put_readback', 'api', 'GET', bucket, staging)
|
||||
require(api_readback['body'] == b'API changed content', 's3_api_put_not_persisted')
|
||||
request('api_staging_list_denied', 'api', 'GET', bucket, query={'list-type': '2', 'prefix': 'staging/'}, expected=(403,))
|
||||
request('api_staging_delete', 'api', 'DELETE', bucket, staging, expected=(200, 204))
|
||||
request('api_staging_delete_readback', 'api', 'GET', bucket, staging, expected=(404,))
|
||||
request('api_final_put_denied', 'api', 'PUT', bucket, final, expected=(403,), body=data)
|
||||
request('api_final_delete_denied', 'api', 'DELETE', bucket, final, expected=(403,))
|
||||
request('api_final_copy_denied', 'api', 'PUT', bucket, final + '-copy', copy_source=bucket + '/' + final, expected=(403,))
|
||||
request('worker_final_put', 'worker', 'PUT', bucket, final, body=b'worker changed content')
|
||||
worker_readback = request('worker_final_put_readback', 'worker', 'GET', bucket, final)
|
||||
require(worker_readback['body'] == b'worker changed content', 's3_worker_put_not_persisted')
|
||||
managed = request('worker_managed_list', 'worker', 'GET', bucket,
|
||||
query={'list-type': '2', 'prefix': final.rsplit('/', 1)[0] + '/'})
|
||||
managed_keys = [node.text for node in ET.fromstring(managed['body']).iter() if node.tag.rsplit('}', 1)[-1] == 'Key']
|
||||
require(final in managed_keys, 's3_worker_list_did_not_return_managed_object')
|
||||
request('worker_orphan_delete', 'worker', 'DELETE', bucket, final, expected=(200, 204))
|
||||
request('worker_orphan_delete_readback', 'worker', 'GET', bucket, final, expected=(404,))
|
||||
request('seed_worker_staging_orphan', 'operator', 'PUT', bucket, staging, body=data)
|
||||
request('worker_staging_cleanup', 'worker', 'DELETE', bucket, staging, expected=(200, 204))
|
||||
request('worker_staging_cleanup_readback', 'worker', 'GET', bucket, staging, expected=(404,))
|
||||
return {'classification': 'passed', 'checks': checks, 'limitations': ['Seaweed Write grants PUT together with DELETE; cleanup is not delete-only.', 'Worker bucket-level LIST can disclose foreign-prefix metadata within the managed bucket.']}
|
||||
finally:
|
||||
for key in (staging, staging + '-copy', final, final + '-copy', foreign, foreign + '-copy'):
|
||||
s3_request(creds['operator'], 'DELETE', bucket, key)
|
||||
s3_request(creds['operator'], 'DELETE', foreign_bucket, tag)
|
||||
s3_request(creds['operator'], 'DELETE', foreign_bucket)
|
||||
|
||||
|
||||
def tcp_probe(cfg):
|
||||
outcomes = {}
|
||||
for host, port in cfg['targets']:
|
||||
try:
|
||||
with socket.create_connection((host, port), TIMEOUT):
|
||||
outcomes[host + ':' + str(port)] = 'open'
|
||||
except OSError as exc:
|
||||
outcomes[host + ':' + str(port)] = transport_error(exc)
|
||||
return {'classification': 'observed', 'targets': outcomes}
|
||||
|
||||
|
||||
def tls_channel_probe(cfg):
|
||||
try:
|
||||
ctx = context(cfg.get('role'), '/pki/operator/current/ca.crt')
|
||||
ctx.set_alpn_protocols(['h2'])
|
||||
raw = socket.create_connection((cfg['host'], cfg['port']), TIMEOUT)
|
||||
with ctx.wrap_socket(raw, server_hostname=cfg['host']) as conn:
|
||||
conn.sendall(b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n' + b'\x00\x00\x00\x04\x00\x00\x00\x00\x00')
|
||||
data = conn.recv(24)
|
||||
require(bool(data), 'tls_channel_unexpected_eof')
|
||||
return {'classification': 'tls_channel_established', 'alpn': conn.selected_alpn_protocol()}
|
||||
except OSError as exc:
|
||||
return {'classification': transport_error(exc)}
|
||||
|
||||
|
||||
def session_probe(cfg):
|
||||
ctx = context(cfg['role'], '/pki/operator/current/ca.crt')
|
||||
session = None
|
||||
observations = []
|
||||
def exchange(resume=False):
|
||||
nonlocal session
|
||||
raw = socket.create_connection((cfg['host'], cfg['port']), TIMEOUT)
|
||||
try:
|
||||
with ctx.wrap_socket(raw, server_hostname=cfg['host'], session=session if resume else None) as conn:
|
||||
conn.sendall(b'GET /health/ready HTTP/1.1\r\nHost: api-replica\r\nConnection: close\r\n\r\n')
|
||||
body = b''
|
||||
while len(body) < 65536:
|
||||
part = conn.recv(4096)
|
||||
if not part:
|
||||
break
|
||||
body += part
|
||||
session = conn.session
|
||||
return {'classification': 'http_response', 'status': int(body.split(b' ', 2)[1]),
|
||||
'session_reused': conn.session_reused, 'has_ticket': session.has_ticket}
|
||||
except OSError as exc:
|
||||
raw.close()
|
||||
return {'classification': transport_error(exc), 'detail': transport_detail(exc)}
|
||||
initial = exchange()
|
||||
require(initial.get('status') == 200, 'old_identity_control_failed')
|
||||
Path('/control/armed').write_text('ready')
|
||||
deadline = time.monotonic() + cfg.get('wait_seconds', 180)
|
||||
while not Path('/control/proceed').exists():
|
||||
require(time.monotonic() < deadline, 'resumption_control_timeout')
|
||||
time.sleep(0.1)
|
||||
for resume in (True, False):
|
||||
observations.append(exchange(resume))
|
||||
return {'classification': 'observed', 'initial': initial, 'after': observations}
|
||||
|
||||
|
||||
def redis_probe(cfg):
|
||||
creds = json.loads(Path('/credentials.json').read_text())['redis']
|
||||
role = cfg.get('role', 'api')
|
||||
user = cfg.get('user', 'cache')
|
||||
conn = context(role).wrap_socket(socket.create_connection(('redis', 6379), TIMEOUT), server_hostname='redis')
|
||||
conn.settimeout(TIMEOUT)
|
||||
def request(*parts):
|
||||
values = [part.encode() for part in parts]
|
||||
data = b'*' + str(len(values)).encode() + b'\r\n'
|
||||
for value in values:
|
||||
data += b'$' + str(len(value)).encode() + b'\r\n' + value + b'\r\n'
|
||||
conn.sendall(data)
|
||||
response = b''
|
||||
while not response.endswith(b'\r\n'):
|
||||
part = conn.recv(1)
|
||||
require(bool(part), 'redis_unexpected_eof')
|
||||
response += part
|
||||
require(len(response) <= 1024, 'redis_response_too_large')
|
||||
return response
|
||||
try:
|
||||
require(request('AUTH', user, creds[user]['password']) == b'+OK\r\n', 'redis_cache_auth_failed')
|
||||
require(request('PING') == b'+PONG\r\n', 'redis_tls_ping_failed')
|
||||
if cfg.get('check_port'):
|
||||
conn.sendall(b'*3\r\n$6\r\nCONFIG\r\n$3\r\nGET\r\n$4\r\nport\r\n')
|
||||
response = b''
|
||||
while len(response) < 1024:
|
||||
chunk = conn.recv(1024)
|
||||
if not chunk:
|
||||
break
|
||||
response += chunk
|
||||
if response.endswith((b'\r\n0\r\n', b'\r\n6379\r\n')):
|
||||
break
|
||||
require(response.endswith(b'\r\n0\r\n'), 'redis_plaintext_port_open', response.decode(errors='replace')[:80])
|
||||
return {'classification': 'passed', 'port': '0'}
|
||||
foreign = request('GET', 'lab7-forbidden:' + uuid.uuid4().hex)
|
||||
require(foreign.startswith(b'-NOPERM'), 'redis_foreign_key_not_denied')
|
||||
return {'classification': 'passed', 'tls_cache_auth': 'allowed', 'ping': 'PONG', 'foreign_key': 'NOPERM'}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def postgres_plaintext_probe(cfg):
|
||||
host, port = cfg.get('host', 'postgres'), cfg.get('port', 5432)
|
||||
answer = b''
|
||||
try:
|
||||
probe = socket.create_connection((host, port), TIMEOUT)
|
||||
probe.settimeout(TIMEOUT)
|
||||
try:
|
||||
probe.sendall(struct.pack('!ii', 8, 80877103)) # SSLRequest
|
||||
answer = probe.recv(1)
|
||||
finally:
|
||||
probe.close()
|
||||
except (ConnectionResetError, BrokenPipeError, ssl.SSLEOFError):
|
||||
answer = b''
|
||||
except (TimeoutError, socket.timeout):
|
||||
raise ProbeFailure('network_timeout') from None
|
||||
except ConnectionRefusedError:
|
||||
raise ProbeFailure('connection_refused') from None
|
||||
try:
|
||||
plain = socket.create_connection((host, port), TIMEOUT)
|
||||
plain.settimeout(TIMEOUT)
|
||||
try:
|
||||
params = b'user\x00messenger_worker\x00database\x00messenger\x00application_name\x00lab7-probe\x00\x00'
|
||||
body = struct.pack('!i', 196608) + params
|
||||
plain.sendall(struct.pack('!i', len(body) + 4) + body)
|
||||
data = plain.recv(4096)
|
||||
finally:
|
||||
plain.close()
|
||||
except (ConnectionResetError, BrokenPipeError, ssl.SSLEOFError):
|
||||
return {'classification': 'rejected', 'detail': 'plaintext_reset', 'ssl_answer': answer.decode(errors='replace')}
|
||||
except (TimeoutError, socket.timeout):
|
||||
raise ProbeFailure('network_timeout') from None
|
||||
except ConnectionRefusedError:
|
||||
raise ProbeFailure('connection_refused') from None
|
||||
if data[:1] == b'E' and b'28000' in data and b'no encryption' in data:
|
||||
return {'classification': 'rejected', 'detail': 'hostssl_required', 'ssl_answer': answer.decode(errors='replace')}
|
||||
if data[:1] == b'R':
|
||||
return {'classification': 'accepted', 'detail': 'plaintext_auth_requested'}
|
||||
return {'classification': 'unexpected', 'detail': 'first=' + repr(data[:1])}
|
||||
|
||||
|
||||
def redis_plaintext_probe(cfg):
|
||||
host, port = cfg.get('host', 'redis'), cfg.get('port', 6379)
|
||||
try:
|
||||
probe = socket.create_connection((host, port), TIMEOUT)
|
||||
probe.settimeout(TIMEOUT)
|
||||
try:
|
||||
probe.sendall(b'PING\r\n')
|
||||
data = probe.recv(256)
|
||||
finally:
|
||||
probe.close()
|
||||
except (ConnectionResetError, BrokenPipeError, ssl.SSLEOFError):
|
||||
return {'classification': 'rejected', 'detail': 'plaintext_reset'}
|
||||
except (TimeoutError, socket.timeout):
|
||||
raise ProbeFailure('network_timeout') from None
|
||||
except ConnectionRefusedError:
|
||||
raise ProbeFailure('connection_refused') from None
|
||||
if data.startswith((b'+PONG', b'-NOAUTH', b'-ERR')):
|
||||
return {'classification': 'accepted', 'detail': 'plaintext_reply'}
|
||||
return {'classification': 'rejected', 'detail': 'no_redis_reply'}
|
||||
|
||||
|
||||
def s3_plaintext_probe(cfg):
|
||||
host, port = cfg.get('host', 'seaweedfs'), cfg.get('port', 8333)
|
||||
try:
|
||||
probe = socket.create_connection((host, port), TIMEOUT)
|
||||
probe.settimeout(TIMEOUT)
|
||||
try:
|
||||
probe.sendall(b'GET / HTTP/1.1\r\nHost: seaweedfs\r\nConnection: close\r\n\r\n')
|
||||
data = probe.recv(1024)
|
||||
finally:
|
||||
probe.close()
|
||||
except (ConnectionResetError, BrokenPipeError, ssl.SSLEOFError):
|
||||
return {'classification': 'rejected', 'detail': 'plaintext_reset'}
|
||||
except (TimeoutError, socket.timeout):
|
||||
raise ProbeFailure('network_timeout') from None
|
||||
except ConnectionRefusedError:
|
||||
raise ProbeFailure('connection_refused') from None
|
||||
if data.startswith(b'HTTP/'):
|
||||
if b'Client sent an HTTP request to an HTTPS server' in data:
|
||||
return {'classification': 'rejected', 'detail': 'https_listener_rejected_http'}
|
||||
return {'classification': 'accepted', 'detail': 'plaintext_http_response'}
|
||||
return {'classification': 'rejected', 'detail': 'no_http_response'}
|
||||
|
||||
|
||||
def loki_scan_probe(cfg):
|
||||
# Never put credentials into LogQL: Loki logs the query text. Fetch broad
|
||||
# streams and compare their lines with the mounted secret list locally.
|
||||
sensitive = json.loads(Path('/secret-scan.json').read_text())
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
start = (now - dt.timedelta(hours=24)).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
end = now.strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
selectors = cfg.get('selectors') or ['{service_name=~".+"}', '{job=~".+"}']
|
||||
lines = 0
|
||||
leaked = False
|
||||
for selector in selectors:
|
||||
path = ('/loki/api/v1/query_range?query=' + urllib.parse.quote(selector) +
|
||||
'&start=' + start + '&end=' + end + '&limit=2000&direction=backward')
|
||||
result = http('loki', 3100, 'GET', path, role='grafana')
|
||||
require(result['status'] == 200, 'loki_query_failed', str(result['status']))
|
||||
payload = json.loads(result['body'])
|
||||
require(payload.get('status') == 'success', 'loki_query_failed', str(payload.get('status')))
|
||||
for stream in payload.get('data', {}).get('result', []):
|
||||
for _, value in stream.get('values', []):
|
||||
lines += 1
|
||||
if any(secret in value for secret in sensitive):
|
||||
leaked = True
|
||||
require(lines > 0, 'loki_scan_empty')
|
||||
return {'classification': 'leak' if leaked else 'passed', 'lines': lines,
|
||||
'sensitive_values': len(sensitive), 'window_hours': 24, 'selectors': len(selectors)}
|
||||
|
||||
|
||||
def internal_main():
|
||||
try:
|
||||
kind, cfg = sys.argv[2], json.loads(sys.argv[3])
|
||||
result = {'tls': tls_probe, 'bao': bao_probe, 'amqp': amqp_probe, 's3': s3_probe, 'tcp': tcp_probe,
|
||||
'session': session_probe, 'tls-channel': tls_channel_probe, 'redis': redis_probe,
|
||||
'postgres-plaintext': postgres_plaintext_probe, 'redis-plaintext': redis_plaintext_probe,
|
||||
's3-plaintext': s3_plaintext_probe, 'loki-scan': loki_scan_probe}[kind](cfg)
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
except ProbeFailure as exc:
|
||||
print(json.dumps({'classification': exc.classification, 'detail': exc.detail}))
|
||||
raise SystemExit(1)
|
||||
except Exception as exc:
|
||||
print(json.dumps({'classification': 'probe_exception', 'type': type(exc).__name__}))
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__' and len(sys.argv) > 1 and sys.argv[1] == '--internal':
|
||||
internal_main()
|
||||
Executable
+403
@@ -0,0 +1,403 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real local HTTPS, protocol ACL, identity and container lab7 acceptance.
|
||||
|
||||
Usage: python3 student-tests/lab7_security.py --ca-file secrets/lab7/pki/operator/current/ca.crt
|
||||
Requires a bootstrapped running stand and python:3.14-slim available to Docker.
|
||||
Operator-only credentials are mounted exclusively in one-shot probes. Evidence
|
||||
contains classifications/status codes, never credentials or response bodies.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure
|
||||
from lab7_helpers import Stand, ProbeFailure, command, require, http, temporary_directory
|
||||
|
||||
|
||||
class Suite:
|
||||
def __init__(self):
|
||||
self.results = []
|
||||
|
||||
def run(self, name, fn):
|
||||
started = time.monotonic()
|
||||
try:
|
||||
details = fn() or {}
|
||||
result = {'name': name, 'passed': True, 'classification': 'passed', 'details': details}
|
||||
except ProbeFailure as exc:
|
||||
result = {'name': name, 'passed': False, 'classification': exc.classification, 'detail': exc.detail}
|
||||
except Failure:
|
||||
result = {'name': name, 'passed': False, 'classification': 'public_api_contract_failure'}
|
||||
except Exception as exc:
|
||||
result = {'name': name, 'passed': False, 'classification': 'probe_exception', 'type': type(exc).__name__}
|
||||
result['seconds'] = round(time.monotonic() - started, 3)
|
||||
self.results.append(result)
|
||||
|
||||
|
||||
def public_tls(stand, client, ca):
|
||||
client.call('GET', '/health/ready', schema='Health')
|
||||
with temporary_directory(prefix='lab7-untrusted-') as temp:
|
||||
key, cert = Path(temp) / 'key.pem', Path(temp) / 'cert.pem'
|
||||
command(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', str(key),
|
||||
'-out', str(cert), '-days', '1', '-subj', '/CN=local-untrusted'], timeout=30)
|
||||
observations = {}
|
||||
for name, host, trust, expected in [('wrong_ca', 'localhost', cert, 'ca_rejected'),
|
||||
('wrong_hostname', '127.0.0.1', ca, 'hostname_rejected')]:
|
||||
try:
|
||||
http(host, int(urllib.parse.urlsplit(stand.base_url).port or 8443),
|
||||
'GET', '/health/ready', ca=str(trust))
|
||||
raise ProbeFailure('unexpected_tls_acceptance', name)
|
||||
except ProbeFailure as exc:
|
||||
require(exc.classification == expected, 'incorrect_tls_failure_class', name + ':' + exc.classification)
|
||||
observations[name] = exc.classification
|
||||
return observations
|
||||
|
||||
|
||||
def identity_acl(stand):
|
||||
results = {}
|
||||
for name, role, expected in [('lb', 'lb', 'http_response'), ('absent', None, 'tls_certificate_rejected'),
|
||||
('wrong_uri', 'worker', 'tls_certificate_rejected')]:
|
||||
result = stand.probe('tls', roles=('lb', 'worker', 'operator'),
|
||||
config={'host': 'api-replica', 'port': 8080, 'role': role})
|
||||
require(result['classification'] == expected, 'api_identity_mismatch', name + ':' + result['classification'])
|
||||
if role == 'lb':
|
||||
require(result['status'] == 200, 'api_lb_health_failed')
|
||||
results[name] = result
|
||||
with temporary_directory(prefix='lab7-untrusted-client-') as temp:
|
||||
key, cert = Path(temp) / 'tls.key', Path(temp) / 'tls.crt'
|
||||
command(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', str(key),
|
||||
'-out', str(cert), '-days', '1', '-subj', '/CN=lb'], timeout=30)
|
||||
current = Path(temp) / 'current'
|
||||
current.mkdir()
|
||||
key.rename(current / 'tls.key')
|
||||
cert.rename(current / 'tls.crt')
|
||||
(current / 'ca.crt').write_bytes((stand.secrets / 'pki/operator/current/ca.crt').read_bytes())
|
||||
for name, host, port, probe in (
|
||||
('api', 'api-replica', 8080, 'tls'),
|
||||
('collector', 'otel-collector', 4318, 'tls'),
|
||||
('broker', 'broker', 5671, 'tls-channel')):
|
||||
result = stand.probe(probe, roles=('operator',), extra_mounts=((temp, '/pki/untrusted'),),
|
||||
config={'host': host, 'port': port, 'role': 'untrusted'})
|
||||
require(result['classification'] == 'tls_certificate_rejected', name + '_wrong_ca_not_rejected')
|
||||
results[name + '_wrong_ca_client'] = result
|
||||
for role, expected in [('api', 200), ('lb', 403)]:
|
||||
response = stand.probe('tls', roles=('api', 'lb'), config={'host': 'otel-collector', 'port': 4318,
|
||||
'role': role, 'method': 'POST', 'path': '/v1/traces', 'body': '{}',
|
||||
'headers': {'Content-Type': 'application/json'}})
|
||||
require(response.get('status') == expected, 'collector_identity_acl_mismatch', role)
|
||||
results['collector_' + role] = response
|
||||
absent = stand.probe('tls', roles=('operator',), config={'host': 'otel-collector', 'port': 4318})
|
||||
require(absent['classification'] == 'tls_certificate_rejected', 'collector_missing_cert_not_rejected')
|
||||
results['collector_absent'] = absent
|
||||
for host, port, role, method, path in [('otel-collector', 4318, 'api', 'GET', '/v1/traces'),
|
||||
('prometheus', 9090, 'grafana', 'POST', '/-/reload'),
|
||||
('loki', 3100, 'grafana', 'POST', '/loki/api/v1/push'),
|
||||
('loki', 3100, 'collector', 'GET', '/loki/api/v1/query'),
|
||||
('tempo', 3200, 'prometheus', 'GET', '/api/search')]:
|
||||
result = stand.probe('tls', roles=(role,), config={'host': host, 'port': port, 'role': role, 'method': method, 'path': path}, network='observability')
|
||||
require(result.get('status') == 403, 'telemetry_route_acl_mismatch', host + ':' + role)
|
||||
results[host + '_' + role + '_route'] = result
|
||||
return results
|
||||
|
||||
|
||||
def broker_acl(stand):
|
||||
results = {}
|
||||
for role, operation, allowed in [('worker', 'consume', True), ('relay', 'publish', True),
|
||||
('worker', 'publish', False), ('worker', 'topology', False),
|
||||
('relay', 'consume', False), ('relay', 'topology', False)]:
|
||||
result = stand.probe('amqp', roles=('worker', 'relay'), config={'role': role, 'operation': operation})
|
||||
require(result['classification'] == ('amqp_allowed' if allowed else 'amqp_rejected'),
|
||||
'broker_acl_mismatch', role + ':' + operation + ':' + result['classification'])
|
||||
if not allowed:
|
||||
require(result.get('code') == 403, 'broker_denial_not_access_refused')
|
||||
results[role + '_' + operation] = result
|
||||
absent = stand.probe('amqp', roles=('operator',), config={'role': None})
|
||||
require(absent['classification'] == 'tls_certificate_rejected', 'broker_missing_cert_not_rejected')
|
||||
wrong = stand.probe('amqp', roles=('api',), config={'role': 'api'})
|
||||
require(wrong['classification'] == 'amqp_rejected' and wrong.get('code') == 403, 'broker_wrong_dns_principal_not_403')
|
||||
offered = stand.probe('amqp', roles=('worker',), config={'role': 'worker', 'operation': 'mechanisms'})
|
||||
require(offered['classification'] == 'amqp_mechanisms' and offered.get('mechanisms') == ['EXTERNAL'],
|
||||
'broker_password_mechanism_negotiable')
|
||||
results.update(absent=absent, wrong_dns=wrong, offered_mechanisms=offered)
|
||||
return results
|
||||
|
||||
|
||||
def seaweed_auxiliary_acl(stand):
|
||||
results = {}
|
||||
for role in (None, 'worker', 'api', 'operator', 's3'):
|
||||
result = stand.probe('tls-channel', roles=('operator', 'worker', 'api', 's3'),
|
||||
config={'host': 'seaweedfs', 'port': 18333, 'role': role})
|
||||
expected = 'tls_channel_established' if role == 's3' else 'tls_certificate_rejected'
|
||||
require(result['classification'] == expected, 'seaweed_auxiliary_mtls_mismatch', role or 'absent')
|
||||
results[role or 'absent'] = result
|
||||
return {'grpc_18333': results, 'limitations': ['Checks mutual-TLS HTTP/2 channel admission, not a Seaweed administrative gRPC method.']}
|
||||
|
||||
|
||||
def database_acl(stand):
|
||||
results = {}
|
||||
for role, allowed in [('api', ('users', 'sessions', 'messages', 'attachments')),
|
||||
('worker', ('attachments', 'attachment_jobs', 'outbox_messages')),
|
||||
('relay', ('attachment_jobs', 'outbox_messages'))]:
|
||||
for table in allowed:
|
||||
stand.psql('BEGIN; SELECT 1 FROM ' + table + ' LIMIT 0; ROLLBACK;', role=role)
|
||||
results[role + '_read_' + table] = 'allowed'
|
||||
denied = ('users', 'sessions', 'messages') if role != 'api' else ()
|
||||
for table in denied:
|
||||
column = 'token_hash' if table == 'sessions' else 'id'
|
||||
statements = {'select': 'SELECT * FROM ' + table + ' LIMIT 0',
|
||||
'insert': 'INSERT INTO ' + table + ' DEFAULT VALUES',
|
||||
'update': 'UPDATE ' + table + ' SET ' + column + '=' + column + ' WHERE false',
|
||||
'delete': 'DELETE FROM ' + table + ' WHERE false'}
|
||||
for method, sql in statements.items():
|
||||
result = stand.psql('BEGIN; ' + sql + '; ROLLBACK;', role=role, check=False)
|
||||
require(result.returncode != 0 and '42501' in result.stderr, 'database_denial_not_42501', role + ':' + table + ':' + method)
|
||||
results[role + '_denied_' + table + '_' + method] = '42501'
|
||||
result = stand.psql('BEGIN; CREATE TABLE public.lab7_denied_' + uuid.uuid4().hex + '(n int); ROLLBACK;', role=role, check=False)
|
||||
require(result.returncode != 0 and '42501' in result.stderr, 'database_ddl_not_42501', role)
|
||||
results[role + '_ddl'] = '42501'
|
||||
return results
|
||||
|
||||
|
||||
def http_security(stand, client, actors):
|
||||
alice, bob, eve, chat = actors
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
client.call('GET', path, 401, headers={'X-User-Id': alice['id']})
|
||||
client.call('GET', path, 404, actor=eve, headers={'X-User-Id': alice['id']})
|
||||
client.call('POST', path, 404, actor=eve, body={'text': 'denied'},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex, 'X-User-Id': alice['id']})
|
||||
disposable = client.user('logout')
|
||||
client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=disposable)
|
||||
client.call('GET', path, 401, actor=disposable)
|
||||
expired = client.user('expiry')
|
||||
# Actual persisted session expiration, not a forged token or a schema check.
|
||||
raw_token = base64.urlsafe_b64decode(expired['token'] + '=' * (-len(expired['token']) % 4))
|
||||
digest = hashlib.sha256(raw_token).hexdigest()
|
||||
stand.psql("UPDATE sessions SET expires_at=now()-interval '1 second' WHERE token_hash=decode('" + digest + "','hex');")
|
||||
client.call('GET', '/api/v1/chats', 401, actor=expired)
|
||||
upload = '/api/v1/chats/' + chat['id'] + '/attachments?filename=security.png'
|
||||
client.call('POST', upload, 413, actor=alice, raw=b'x' * (10 * 1024 * 1024 + 1), headers={'Content-Type': 'image/png'})
|
||||
client.call('POST', upload, 415, actor=alice, raw=b'not an image', headers={'Content-Type': 'image/png'})
|
||||
def chunk(kind, content):
|
||||
return struct.pack('>I', len(content)) + kind + content + struct.pack('>I', zlib.crc32(kind + content) & 0xffffffff)
|
||||
huge = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 100000, 100000, 8, 6, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(b'\x00')) + chunk(b'IEND', b'')
|
||||
client.call('POST', upload, (413, 415), actor=alice, raw=huge, headers={'Content-Type': 'image/png'})
|
||||
return {'x_user_id': 'no_impersonation', 'foreign_chat': 404, 'logout': 401, 'persisted_expiration': 401,
|
||||
'oversize_body': 413, 'invalid_image': 415, 'image_pixel_bound': 'rejected'}
|
||||
|
||||
|
||||
def rate_limit(client, actor):
|
||||
credential = base64.b64encode((actor['user']['username'] + ':wrong-local-test-password').encode()).decode()
|
||||
instances, statuses, retries = set(), [], []
|
||||
for _ in range(12):
|
||||
result = client.call('POST', '/api/v1/auth/sessions', (401, 429), headers={'Authorization': 'Basic ' + credential})
|
||||
instances.add(result['headers'].get('X-Instance-Id'))
|
||||
statuses.append(result['status'])
|
||||
if result['status'] == 429:
|
||||
value = result['headers'].get('Retry-After', '')
|
||||
require(value.isdigit() and int(value) > 0, 'rate_limit_retry_after_missing')
|
||||
retries.append(int(value))
|
||||
require(429 in statuses, 'shared_rate_limit_not_enforced')
|
||||
require(len(instances) >= 2, 'shared_rate_limit_not_observed_across_replicas')
|
||||
return {'instances': sorted(instances), 'statuses': statuses, 'retry_after': retries}
|
||||
|
||||
|
||||
def workflow(client, actors):
|
||||
alice, bob, _, chat = actors
|
||||
attachment, content = client.attachment(alice, chat)
|
||||
ready = client.wait_ready(alice, attachment, wait_seconds=90)
|
||||
message = client.message(alice, chat, 'lab7-pipeline-sentinel', attachments=[ready['id']])['json']
|
||||
downloaded = client.call('GET', '/api/v1/attachments/' + ready['id'] + '/content', actor=bob)['bytes']
|
||||
require(downloaded == content, 'workflow_attachment_data_changed')
|
||||
return {'attachment_id': ready['id'], 'message_id': message['id'], 'status': ready['status']}
|
||||
|
||||
|
||||
def isolation(stand):
|
||||
containers = stand.containers()
|
||||
require(bool(containers), 'stand_containers_missing')
|
||||
services = {}
|
||||
pairs = {'collector-tls': 'otel-collector', 'prometheus-tls': 'prometheus', 'loki-tls': 'loki',
|
||||
'tempo-tls': 'tempo', 'grafana-tls': 'grafana', 'broker-admin-tls': 'broker', 's3': 'seaweedfs'}
|
||||
by_service = {}
|
||||
for item in containers:
|
||||
name = item['Config']['Labels'].get('com.docker.compose.service')
|
||||
by_service.setdefault(name, []).append(item)
|
||||
host = item['HostConfig']
|
||||
require(not host['Privileged'] and host['NetworkMode'] != 'host', 'privileged_or_host_network', name)
|
||||
require(not any('docker.sock' in m['Source'] for m in item['Mounts']), 'docker_socket_mounted', name)
|
||||
for bindings in (host.get('PortBindings') or {}).values():
|
||||
for binding in bindings or []:
|
||||
require(binding['HostIp'] in ('127.0.0.1', '::1'), 'nonloopback_publish', name)
|
||||
if name in ('api', 'worker', 'relay'):
|
||||
require(item['State']['Running'], 'application_not_running', name)
|
||||
require(host['ReadonlyRootfs'], 'application_writable_root', name)
|
||||
require('ALL' in [x.upper() for x in host.get('CapDrop') or []] and not host.get('CapAdd'), 'application_capability_not_dropped', name)
|
||||
require(any(x.startswith('no-new-privileges') for x in host.get('SecurityOpt') or []), 'application_new_privileges', name)
|
||||
require(host.get('Memory', 0) > 0 and (host.get('NanoCpus', 0) > 0 or host.get('CpuQuota', 0) > 0), 'application_resource_limits_missing', name)
|
||||
require(not host.get('PortBindings'), 'application_published_ports', name)
|
||||
require('/tmp' in (host.get('Tmpfs') or {}), 'application_tmpfs_missing', name)
|
||||
top = command(['docker', 'top', item['Id'], '-eo', 'uid,pid,comm']).stdout.splitlines()[1:]
|
||||
require(bool(top) and all(row.split()[0] != '0' for row in top if row.split()), 'application_root_process', name)
|
||||
identity = [m for m in item['Mounts'] if m['Destination'] == '/run/identity']
|
||||
require(len(identity) == 1 and not identity[0]['RW'] and Path(identity[0]['Source']).name == name,
|
||||
'application_identity_mount_not_isolated', name)
|
||||
require(not any('credentials.json' in m['Source'] or Path(m['Source']).name in ('pki', 'backends', 'lab7') for m in item['Mounts']), 'application_operator_secrets_mounted', name)
|
||||
services.setdefault(name, []).append({'id': item['Id'][:12], 'running_uid_nonzero': True, 'readonly': True})
|
||||
require(len(by_service.get('api', [])) == 2, 'acceptance_requires_two_api_replicas')
|
||||
for child, owner in pairs.items():
|
||||
children = by_service.get(child, [])
|
||||
require(len(children) == 1 and len(by_service.get(owner, [])) == 1, 'namespace_pair_missing', child)
|
||||
require(children[0]['HostConfig']['NetworkMode'] == 'container:' + by_service[owner][0]['Id'], 'namespace_pair_not_current_owner', child)
|
||||
# IDs alone cannot prove kernel namespace pairing after an owner restart.
|
||||
namespace_ids = []
|
||||
for container in (children[0], by_service[owner][0]):
|
||||
observed_ns = command(['docker', 'run', '--rm', '--network', 'container:' + container['Id'],
|
||||
'--user', '10001:10001', '--cap-drop=ALL',
|
||||
'--security-opt=no-new-privileges', 'alpine:3.22',
|
||||
'readlink', '/proc/self/ns/net'])
|
||||
namespace_ids.append(observed_ns.stdout.strip())
|
||||
require(namespace_ids[0] == namespace_ids[1] and namespace_ids[0].startswith('net:['),
|
||||
'namespace_pair_kernel_mismatch', child)
|
||||
target_groups = {
|
||||
'default': [('otel-collector', 14318), ('otel-collector', 18888), ('otel-collector', 18889),
|
||||
('otel-collector', 13133), ('otel-collector', 4317),
|
||||
('broker', 5672), ('broker', 15672), ('broker', 15692),
|
||||
('seaweedfs', 9333), ('seaweedfs', 19333), ('seaweedfs', 8888), ('seaweedfs', 18888),
|
||||
('seaweedfs', 8080), ('seaweedfs', 18080), ('seaweedfs', 8181), ('seaweedfs', 9101),
|
||||
('api-replica', 8084), ('worker', 8081), ('relay', 8082)],
|
||||
'observability': [('loki', 13100), ('loki', 9096), ('loki', 7946),
|
||||
('tempo', 13200), ('tempo', 14317), ('tempo', 9095), ('tempo', 7946),
|
||||
('prometheus', 19090), ('grafana', 13000)],
|
||||
}
|
||||
private_ports = {}
|
||||
for selector, targets in target_groups.items():
|
||||
observed = stand.probe('tcp', config={'targets': targets}, network=selector)
|
||||
require(all(v == 'connection_refused' for v in observed['targets'].values()),
|
||||
'private_listener_network_reachable_or_timeout')
|
||||
private_ports.update(observed['targets'])
|
||||
return {'applications': services, 'namespace_pairs': pairs, 'private_ports': private_ports}
|
||||
|
||||
|
||||
def plaintext_audit(stand):
|
||||
checks = {}
|
||||
for name, kind, config in (
|
||||
('postgres', 'postgres-plaintext', {'host': 'postgres', 'port': 5432}),
|
||||
('redis', 'redis-plaintext', {'host': 'redis', 'port': 6379}),
|
||||
('s3', 's3-plaintext', {'host': 'seaweedfs', 'port': 8333})):
|
||||
result = stand.probe(kind, config=config)
|
||||
require(result.get('classification') == 'rejected', 'plaintext_channel_accepted', name)
|
||||
checks[name] = result
|
||||
redis_port = stand.probe('redis', roles=('operator',), credentials=True,
|
||||
config={'role': 'operator', 'user': 'operator', 'check_port': True})
|
||||
checks['redis_tls_port'] = redis_port
|
||||
foreign = Path.home() / '.local/share/mtusi-lab7' / stand.project / 'root-foreign' / 'ca.crt'
|
||||
require(foreign.is_file(), 'foreign_ca_missing')
|
||||
result = stand.probe('tls', roles=('operator',),
|
||||
extra_mounts=((foreign, '/pki/foreign-ca.crt'),),
|
||||
config={'host': 'seaweedfs', 'port': 8333, 'role': 'operator',
|
||||
'ca': '/pki/foreign-ca.crt'})
|
||||
require(result.get('classification') == 'ca_rejected', 's3_foreign_ca_accepted')
|
||||
checks['s3_foreign_ca'] = result
|
||||
return checks
|
||||
|
||||
|
||||
def leakage(stand, actors):
|
||||
sensitive = []
|
||||
for actor in actors[:3]:
|
||||
sensitive += [actor['token'], actor['registration']['password'],
|
||||
base64.b64encode((actor['registration']['username'] + ':' + actor['registration']['password']).encode()).decode()]
|
||||
def collect(value):
|
||||
if isinstance(value, dict):
|
||||
for key, item in value.items():
|
||||
if key in ('password', 'secret_key', 'access_key') and isinstance(item, str) and len(item) >= 8:
|
||||
sensitive.append(item)
|
||||
else:
|
||||
collect(item)
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
collect(item)
|
||||
collect(json.loads((stand.secrets / 'backends/credentials.json').read_text()))
|
||||
checked = []
|
||||
for item in stand.containers():
|
||||
output = command(['docker', 'logs', '--since', '30m', item['Id']], check=False, timeout=30)
|
||||
text = output.stdout + output.stderr
|
||||
require(not any(value in text for value in sensitive), 'credential_leak_in_container_logs', item['Config']['Labels'].get('com.docker.compose.service'))
|
||||
checked.append(item['Id'][:12])
|
||||
with temporary_directory(prefix='lab7-secret-scan-') as directory:
|
||||
secret_file = Path(directory) / 'secrets.json'
|
||||
secret_file.write_text(json.dumps(list(dict.fromkeys(sensitive))))
|
||||
secret_file.chmod(0o600)
|
||||
result = stand.probe('loki-scan', roles=('grafana',),
|
||||
extra_mounts=((secret_file, '/secret-scan.json'),),
|
||||
config={'selector': '{service_name=~".+"}'}, network='observability')
|
||||
require(result.get('classification') == 'passed', 'credential_leak_in_loki')
|
||||
loki = [result]
|
||||
return {'containers_scanned': checked, 'sensitive_values_scanned': len(sensitive),
|
||||
'loki_scans': len(loki),
|
||||
'limitations': ['Scans retained container logs and Loki streams with service_name; Tempo attributes and historic deleted logs are not text-scanned.']}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--base-url', default='https://localhost:8443')
|
||||
parser.add_argument('--ca-file', required=True)
|
||||
parser.add_argument('--project', default=os.environ.get('COMPOSE_PROJECT_NAME', 'mtusi-messenger-lab6'))
|
||||
parser.add_argument('--secrets-dir', default=os.environ.get('LAB7_SECRETS_DIR', 'secrets/lab7'))
|
||||
parser.add_argument('--output', type=Path)
|
||||
args = parser.parse_args()
|
||||
stand = Stand(args.project, args.secrets_dir, args.base_url)
|
||||
client = Client(args.base_url, args.ca_file, timeout=5)
|
||||
suite = Suite()
|
||||
actors = None
|
||||
suite.run('public_ca_hostname', lambda: public_tls(stand, client, Path(args.ca_file)))
|
||||
suite.run('mtls_and_telemetry_acl', lambda: identity_acl(stand))
|
||||
suite.run('broker_external_acl', lambda: broker_acl(stand))
|
||||
suite.run('bao_api_policy', lambda: stand.probe('bao', roles=('api',), config={'role': 'api'}))
|
||||
suite.run('seaweed_auxiliary_mtls', lambda: seaweed_auxiliary_acl(stand))
|
||||
suite.run('redis_tls_cache_acl', lambda: stand.probe('redis', roles=('api',), credentials=True, config={'role': 'api'}))
|
||||
suite.run('database_privileges', lambda: database_acl(stand))
|
||||
suite.run('s3_prefix_acl', lambda: stand.probe('s3', roles=('operator',), credentials=True))
|
||||
suite.run('plaintext_refusal', lambda: plaintext_audit(stand))
|
||||
try:
|
||||
actors = client.bootstrap()
|
||||
except Exception:
|
||||
suite.results.append({'name': 'public_actors', 'passed': False, 'classification': 'actor_bootstrap_failed'})
|
||||
if actors:
|
||||
suite.run('http_acl_logout_expiry_bounds', lambda: http_security(stand, client, actors))
|
||||
suite.run('real_async_pipeline', lambda: workflow(client, actors))
|
||||
suite.run('shared_rate_limit', lambda: rate_limit(client, actors[2]))
|
||||
suite.run('credential_log_sentinels', lambda: leakage(stand, actors))
|
||||
suite.run('runtime_container_network_isolation', lambda: isolation(stand))
|
||||
result = {'study': 'lab7-security', 'project': stand.project, 'timestamp': dt.datetime.now(dt.timezone.utc).isoformat(),
|
||||
'passed': all(x['passed'] for x in suite.results), 'results': suite.results,
|
||||
'limitations': ['Authorized local synthetic stand only; privilege tests use administrator SET ROLE over a local Unix socket.',
|
||||
'Actual workflow confirms queue processing; standalone consume probe requeues unacknowledged deliveries.',
|
||||
'Session expiry uses an operator expiry update, not a claim about the default configured TTL.']}
|
||||
encoded = json.dumps(result, indent=2, sort_keys=True)
|
||||
if args.output:
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(encoded + '\n')
|
||||
print(encoded)
|
||||
return 0 if result['passed'] else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except ProbeFailure as exc:
|
||||
print(json.dumps({'passed': False, 'classification': exc.classification, 'detail': exc.detail}))
|
||||
raise SystemExit(1)
|
||||
except Exception as exc:
|
||||
print(json.dumps({'passed': False, 'classification': 'suite_exception', 'type': type(exc).__name__}))
|
||||
raise SystemExit(1)
|
||||
Executable
+152
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Presigned direct-upload track (lab4 level 5).
|
||||
|
||||
The mandatory proxy endpoint stays available; this script exercises the
|
||||
optional extension: presign -> direct PUT to S3 -> complete -> message.
|
||||
|
||||
Run against a live stand:
|
||||
python3 student-tests/presign_flow.py --base-url https://localhost:8443
|
||||
|
||||
Set PRESIGN_EXPIRY_WAIT=seconds to also verify that an expired URL is rejected
|
||||
(the stand must run with a matching S3_PRESIGN_TTL).
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE, open_url # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def presign(client, actor, chat, content, filename='presigned.png', content_type='image/png'):
|
||||
body = {
|
||||
'filename': filename,
|
||||
'content_type': content_type,
|
||||
'size_bytes': len(content),
|
||||
'sha256': hashlib.sha256(content).hexdigest(),
|
||||
}
|
||||
response = client.call(
|
||||
'POST', '/api/v1/chats/' + chat['id'] + '/attachments/presign', 201,
|
||||
actor=actor, body=body,
|
||||
)
|
||||
return json.loads(response['bytes'])
|
||||
|
||||
|
||||
def put(url, content, content_type='image/png', ca_file=CA_FILE):
|
||||
request = urllib.request.Request(
|
||||
url, data=content, method='PUT', headers={'Content-Type': content_type},
|
||||
)
|
||||
try:
|
||||
with open_url(request, timeout=15, ca_file=ca_file) as response:
|
||||
return response.status
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code
|
||||
|
||||
|
||||
def complete(client, actor, attachment_id, digest, expected=202):
|
||||
return client.call(
|
||||
'POST', '/api/v1/attachments/' + attachment_id + '/complete', expected,
|
||||
actor=actor, body={'sha256': digest}, schema='Attachment' if expected == 202 else None,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Presigned upload flow (lab4 track 1)')
|
||||
client = Client(args.base_url or BASE_URL, args.ca_file or CA_FILE)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
content = FIXTURE.read_bytes()
|
||||
digest = hashlib.sha256(content).hexdigest()
|
||||
|
||||
# Happy path: direct PUT, completion, message, download.
|
||||
presigned = presign(client, alice, chat, content)
|
||||
check(presigned['method'] == 'PUT', 'presign method must be PUT')
|
||||
check('content-length' in presigned['upload_url'], 'content-length must be signed into the URL')
|
||||
check(put(presigned['upload_url'], content, ca_file=args.ca_file or CA_FILE) == 200, 'direct PUT failed')
|
||||
attachment = complete(client, alice, presigned['attachment_id'], digest)['json']
|
||||
check(attachment['sha256'] == digest and attachment['size_bytes'] == len(content), 'completed metadata mismatch')
|
||||
attachment = client.wait_ready(alice, attachment)
|
||||
print('happy path: direct PUT 200, complete queued, ready after worker')
|
||||
|
||||
client.message(alice, chat, '', attachments=[attachment['id']])
|
||||
download = client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)
|
||||
check(download['bytes'] == content, 'download differs from the presigned original')
|
||||
print('message with attachment downloaded as the second chat member')
|
||||
|
||||
# Completion is idempotent.
|
||||
again = complete(client, alice, presigned['attachment_id'], digest)['json']
|
||||
check(again['id'] == attachment['id'], 'repeated complete returned another attachment')
|
||||
check(again['status'] in ('queued', 'processing', 'ready'), 'repeated complete returned an invalid state')
|
||||
print('repeated complete is idempotent')
|
||||
|
||||
# A foreign user cannot complete someone else's pending upload.
|
||||
pending = presign(client, alice, chat, content)
|
||||
complete(client, bob, pending['attachment_id'], digest, expected=404)
|
||||
print('foreign complete: 404')
|
||||
|
||||
# Incomplete upload: complete before PUT.
|
||||
incomplete = presign(client, alice, chat, content)
|
||||
complete(client, alice, incomplete['attachment_id'], digest, expected=409)
|
||||
print('complete before PUT: 409')
|
||||
|
||||
# Wrong checksum: the object is rejected and removed.
|
||||
mismatch = presign(client, alice, chat, content)
|
||||
check(put(mismatch['upload_url'], content, ca_file=args.ca_file or CA_FILE) == 200, 'direct PUT failed')
|
||||
complete(client, alice, mismatch['attachment_id'], '0' * 64, expected=409)
|
||||
print('wrong completion checksum: 409')
|
||||
|
||||
# Content-Length is signed, so S3 rejects a different number of bytes at
|
||||
# write time instead of storing an oversized staging object.
|
||||
oversized = presign(client, alice, chat, content)
|
||||
check(put(oversized['upload_url'], content + b'x', ca_file=args.ca_file or CA_FILE) == 403, 'oversized PUT must be rejected by S3')
|
||||
complete(client, alice, oversized['attachment_id'], digest, expected=409)
|
||||
print('oversized direct PUT: 403 from S3; complete: 409 (nothing stored)')
|
||||
|
||||
# Last PUT wins before completion; the declared checksum must describe it.
|
||||
# The replacement is the same length because Content-Length is signed.
|
||||
overwrite = presign(client, alice, chat, content)
|
||||
corrupt = bytearray(content)
|
||||
corrupt[0] ^= 0xFF
|
||||
check(put(overwrite['upload_url'], bytes(corrupt), ca_file=args.ca_file or CA_FILE) == 200, 'first PUT failed')
|
||||
check(put(overwrite['upload_url'], content, ca_file=args.ca_file or CA_FILE) == 200, 'second PUT failed')
|
||||
overwritten = complete(client, alice, overwrite['attachment_id'], digest)['json']
|
||||
check(overwritten['sha256'] == digest, 'last PUT was not the completed object')
|
||||
print('same-size overwrite: last PUT wins, checksum verified')
|
||||
|
||||
# A user outside the chat cannot obtain a presigned URL.
|
||||
other = client.call(
|
||||
'POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Приватный чат', 'member_ids': [alice['id'], eve['id']]}, schema='Chat',
|
||||
)['json']
|
||||
client.call(
|
||||
'POST', '/api/v1/chats/' + other['id'] + '/attachments/presign', 404,
|
||||
actor=bob,
|
||||
body={
|
||||
'filename': 'x.png', 'content_type': 'image/png',
|
||||
'size_bytes': len(content), 'sha256': digest,
|
||||
},
|
||||
)
|
||||
|
||||
wait = float(os.environ.get('PRESIGN_EXPIRY_WAIT', '0'))
|
||||
if wait > 0:
|
||||
expired = presign(client, alice, chat, content)
|
||||
time.sleep(wait)
|
||||
status = put(expired['upload_url'], content, ca_file=args.ca_file or CA_FILE)
|
||||
check(status == 403, 'expired presigned URL must be 403, got ' + str(status))
|
||||
print('EXPIRED: presigned URL rejected after', wait, 'seconds')
|
||||
|
||||
print('PASS: lab4 presigned upload flow')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+199
@@ -0,0 +1,199 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Последовательная остановка каждой API-реплики с измерениями (lab3).
|
||||
|
||||
Отличие от публичного `make test-failover`: здесь реплика выбирается явно
|
||||
(сначала первая, затем вторая), печатается реально остановленный контейнер и
|
||||
собираются метрики: успешные записи, ошибки, время восстановления записи через
|
||||
LB, набор реплик после отказа и отсутствие дублей при повторе одного ключа.
|
||||
|
||||
Запуск (стенд поднят, LB на 8080, hooks в scripts/):
|
||||
python3 student-tests/replica_failover.py --action-script scripts/stop-one.sh
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
|
||||
from client import Client, LAB, Failure, arguments, check, run # noqa: E402
|
||||
from tests_helpers import compose, containers_by_hostname, messages_path # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
|
||||
WINDOW_SECONDS = 15.0
|
||||
RECOVERY_DEADLINE_SECONDS = 10.0
|
||||
STOP_DELAY_SECONDS = 0.5
|
||||
|
||||
|
||||
def observed_instances(client, actor, tries=40):
|
||||
seen = {}
|
||||
|
||||
for _ in range(tries):
|
||||
response = client.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
||||
instance = response['headers']['X-Instance-Id']
|
||||
seen[instance] = seen.get(instance, 0) + 1
|
||||
|
||||
return seen
|
||||
|
||||
|
||||
def stop_replica(script, instance):
|
||||
started = time.monotonic()
|
||||
env = dict(os.environ, TARGET_INSTANCE_ID=instance)
|
||||
proc = subprocess.run([str(script)], env=env, capture_output=True, text=True)
|
||||
|
||||
return {
|
||||
'returncode': proc.returncode,
|
||||
'seconds': round(time.monotonic() - started, 3),
|
||||
'stdout': proc.stdout.strip(),
|
||||
'stderr': proc.stderr.strip(),
|
||||
}
|
||||
|
||||
|
||||
def measure_outage(client, actor, chat, target, script):
|
||||
"""Пишет сообщения сквозь LB, пока hook останавливает выбранную реплику."""
|
||||
hook = ThreadPoolExecutor(max_workers=1)
|
||||
stop_started = time.monotonic()
|
||||
hook_future = hook.submit(lambda: (time.sleep(STOP_DELAY_SECONDS), stop_replica(script, target))[1])
|
||||
|
||||
successes, failures, uncertain = 0, 0, 0
|
||||
instances_after = []
|
||||
first_recovery = None
|
||||
key, text = None, None
|
||||
stop_finished = None
|
||||
|
||||
try:
|
||||
while time.monotonic() - stop_started < WINDOW_SECONDS:
|
||||
if key is None:
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Отказ ' + target + ' ' + key
|
||||
|
||||
try:
|
||||
response = client.message(actor, chat, text, key=key)
|
||||
except Failure:
|
||||
failures += 1
|
||||
uncertain += 1
|
||||
continue
|
||||
|
||||
successes += 1
|
||||
instances_after.append(response['headers']['X-Instance-Id'])
|
||||
key, text = None, None
|
||||
|
||||
if hook_future.done() and stop_finished is None:
|
||||
stop_finished = time.monotonic() - stop_started
|
||||
first_recovery = first_recovery or round(stop_finished, 3)
|
||||
|
||||
time.sleep(0.1)
|
||||
finally:
|
||||
stopped = hook_future.result()
|
||||
|
||||
if first_recovery is None:
|
||||
first_recovery = round(time.monotonic() - stop_started, 3)
|
||||
|
||||
elapsed = time.monotonic() - stop_started
|
||||
|
||||
return {
|
||||
'stopped_container': stopped['stdout'],
|
||||
'hook_returncode': stopped['returncode'],
|
||||
'hook_seconds': stopped['seconds'],
|
||||
'hook_error': stopped['stderr'],
|
||||
'successful_writes': successes,
|
||||
'successful_rps': round(successes / elapsed, 2) if elapsed else None,
|
||||
'failed_attempts': failures,
|
||||
'uncertain_retries': uncertain,
|
||||
'first_recovery_seconds': first_recovery,
|
||||
'instances_after_recovery': sorted(set(instances_after[-5:])),
|
||||
}
|
||||
|
||||
|
||||
def all_messages(client, actor, chat, limit=2000):
|
||||
"""Вся история чата с keyset-пагинацией (проверка дублей не должна зависеть от одной страницы)."""
|
||||
items = []
|
||||
cursor = None
|
||||
|
||||
while True:
|
||||
query = messages_path(chat) + '?limit=100'
|
||||
if cursor:
|
||||
query += '&cursor=' + quote(cursor, safe='')
|
||||
|
||||
page = client.call('GET', query, actor=actor, schema='MessagePage')['json']
|
||||
items.extend(page['items'])
|
||||
cursor = page['next_cursor']
|
||||
|
||||
if not cursor:
|
||||
return items
|
||||
|
||||
check(len(items) <= limit, 'история больше защитного предела проверки')
|
||||
|
||||
|
||||
def ensure_no_duplicates(client, actor, chat):
|
||||
items = all_messages(client, actor, chat)
|
||||
texts = [message['text'] for message in items]
|
||||
ids = [message['id'] for message in items]
|
||||
check(len(texts) == len(set(texts)), 'повтор с тем же ключом создал дубль')
|
||||
check(len(ids) == len(set(ids)), 'дубли ID в истории')
|
||||
|
||||
return len(items)
|
||||
|
||||
|
||||
def restore(instance, timeout=90):
|
||||
started = time.monotonic()
|
||||
compose('up', '-d', '--no-deps', 'api')
|
||||
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
hosts = containers_by_hostname()
|
||||
if instance in hosts:
|
||||
return {'seconds': round(time.monotonic() - started, 3), 'instances': sorted(hosts)}
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
raise Failure('реплика ' + instance + ' не вернулась в строй')
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--action-script', required=True, help='stop-one hook, executable, authored by student')
|
||||
|
||||
args = arguments('Последовательная остановка реплик с метриками (lab3)', configure)
|
||||
check(LAB >= 3, 'отказ API-реплики требует lab3+')
|
||||
|
||||
script = Path(args.action_script).expanduser().resolve()
|
||||
check(script.is_file() and os.access(script, os.X_OK), 'hook должен существовать и быть исполняемым')
|
||||
|
||||
client = Client(args.base_url or BASE_URL, args.ca_file or CA_FILE)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
|
||||
observed = observed_instances(client, alice)
|
||||
check(len(observed) >= 2, 'через LB видно меньше двух реплик: ' + str(sorted(observed)))
|
||||
|
||||
report = {'before': {'instances': sorted(observed)}, 'replicas': []}
|
||||
|
||||
for instance in sorted(observed):
|
||||
result = measure_outage(client, alice, chat, instance, script)
|
||||
check(result['hook_returncode'] == 0, 'hook завершился неуспешно: ' + result['hook_error'])
|
||||
check(
|
||||
result['first_recovery_seconds'] <= RECOVERY_DEADLINE_SECONDS,
|
||||
'запись не восстановилась за ' + str(RECOVERY_DEADLINE_SECONDS) + ' c',
|
||||
)
|
||||
check(result['successful_writes'] >= 5, 'слишком мало подтверждённых записей после отказа')
|
||||
check(instance not in result['instances_after_recovery'], 'остановленная реплика продолжает обслуживать')
|
||||
result['messages_in_history'] = ensure_no_duplicates(client, alice, chat)
|
||||
|
||||
restored = restore(instance)
|
||||
result['restored_seconds'] = restored['seconds']
|
||||
result['instances_restored'] = restored['instances']
|
||||
|
||||
report['replicas'].append({'stopped': instance, **result})
|
||||
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
print('PASS: каждая реплика остановлена по очереди; записи продолжились, дублей и потерь нет')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+159
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Толерантный генератор записи для сценариев отказа (lab3).
|
||||
|
||||
Публичный `tests/load.py` не переживает разрыв соединения во время удаления
|
||||
реплики: он падает на уровне http.client. Этот генератор создан для измерений
|
||||
во время rolling update и отказов: он считает успешные запросы, ошибки по видам
|
||||
и увиденные реплики, а не падает на обрыве.
|
||||
|
||||
python3 student-tests/rolling_update_load.py --duration 60 --concurrency 16 --output evidence/rolling-update/load.json
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
|
||||
from client import Client, LAB, Failure, arguments, check, run # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
|
||||
|
||||
def classify(error):
|
||||
name = type(error).__name__
|
||||
message = str(error)
|
||||
|
||||
if name == 'Failure':
|
||||
# client.call сообщает о проблемах соединения как Failure с этим текстом,
|
||||
# отделяя их от HTTP-статусов, которые тоже приходят как Failure.
|
||||
if 'connection/TLS failure' in message:
|
||||
return 'connection_broken'
|
||||
|
||||
return 'http_error'
|
||||
if name in ('RemoteDisconnected', 'BadStatusLine', 'IncompleteRead', 'ConnectionResetError'):
|
||||
return 'connection_broken'
|
||||
if name in ('TimeoutError', 'socket.timeout'):
|
||||
return 'timeout'
|
||||
|
||||
return name
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--duration', type=float, default=30)
|
||||
parser.add_argument('--concurrency', type=int, default=8)
|
||||
parser.add_argument('--output', default=None)
|
||||
|
||||
args = arguments('Запись сообщений сквозь LB с учётом ошибок (lab3)', configure)
|
||||
check(LAB >= 3, 'сценарий требует lab3+')
|
||||
check(1 <= args.duration <= 3600, 'duration должен быть 1..3600')
|
||||
check(1 <= args.concurrency <= 128, 'concurrency должен быть 1..128')
|
||||
|
||||
bootstrap = Client(args.base_url or BASE_URL, args.ca_file or CA_FILE)
|
||||
|
||||
# Стенд в момент старта может быть в переходном состоянии (например, сразу
|
||||
# после возврата БД), поэтому однократный 502 на bootstrap не должен ломать
|
||||
# измерение: пробуем несколько раз и сообщаем, сколько попыток понадобилось.
|
||||
attempts = 0
|
||||
while True:
|
||||
attempts += 1
|
||||
try:
|
||||
alice, _, _, chat = bootstrap.bootstrap()
|
||||
break
|
||||
except Failure as error:
|
||||
if attempts >= 10:
|
||||
raise
|
||||
print('bootstrap attempt %d failed: %s' % (attempts, error), file=sys.stderr)
|
||||
time.sleep(2)
|
||||
|
||||
if attempts > 1:
|
||||
print('bootstrap attempts: %d' % attempts, file=sys.stderr)
|
||||
|
||||
barrier = threading.Barrier(args.concurrency)
|
||||
lock = threading.Lock()
|
||||
latencies = []
|
||||
errors = {}
|
||||
instances = {}
|
||||
|
||||
def worker(worker_id):
|
||||
client = Client(args.base_url or BASE_URL, args.ca_file or CA_FILE, timeout=5)
|
||||
local_latencies = []
|
||||
local_errors = {}
|
||||
local_instances = {}
|
||||
barrier.wait()
|
||||
|
||||
deadline = time.monotonic() + args.duration
|
||||
index = 0
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
started = time.monotonic()
|
||||
|
||||
try:
|
||||
response = client.message(alice, chat, 'rolling-%s-%s' % (worker_id, index), key=uuid.uuid4().hex)
|
||||
except Exception as error: # noqa: BLE001 - протокол и сеть дают разные типы
|
||||
category = classify(error)
|
||||
local_errors[category] = local_errors.get(category, 0) + 1
|
||||
else:
|
||||
local_latencies.append(time.monotonic() - started)
|
||||
instance = response['headers']['X-Instance-Id']
|
||||
local_instances[instance] = local_instances.get(instance, 0) + 1
|
||||
|
||||
index += 1
|
||||
|
||||
with lock:
|
||||
latencies.extend(local_latencies)
|
||||
|
||||
for category, count in local_errors.items():
|
||||
errors[category] = errors.get(category, 0) + count
|
||||
|
||||
for instance, count in local_instances.items():
|
||||
instances[instance] = instances.get(instance, 0) + count
|
||||
|
||||
started = time.monotonic()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
list(pool.map(worker, range(args.concurrency)))
|
||||
|
||||
elapsed = time.monotonic() - started
|
||||
ordered = sorted(latencies)
|
||||
|
||||
def percentile(value):
|
||||
return round(1000 * ordered[max(0, math.ceil(value * len(ordered)) - 1)], 3) if ordered else None
|
||||
|
||||
failed = sum(errors.values())
|
||||
|
||||
report = {
|
||||
'lab': LAB,
|
||||
'workload': 'closed-loop POST messages; failures counted, not raised',
|
||||
'requested_duration_seconds': args.duration,
|
||||
'elapsed_seconds': round(elapsed, 3),
|
||||
'concurrency': args.concurrency,
|
||||
'successful_requests': len(ordered),
|
||||
'failed_requests': failed,
|
||||
'error_ratio': round(failed / (failed + len(ordered)), 6) if (failed + len(ordered)) else None,
|
||||
'errors_by_kind': errors,
|
||||
'successful_rps': round(len(ordered) / elapsed, 3),
|
||||
'successful_latency_ms': {'p50': percentile(.50), 'p95': percentile(.95), 'p99': percentile(.99)},
|
||||
'instances': instances,
|
||||
'bootstrap_attempts': attempts,
|
||||
'note': 'Percentiles cover successful writes only; transitional errors are expected during a rolling update.',
|
||||
}
|
||||
|
||||
text = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
print(text)
|
||||
|
||||
if args.output:
|
||||
destination = Path(args.output)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(text + '\n')
|
||||
|
||||
check(bool(ordered), 'не было ни одной успешной записи')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Обвязки для собственных проверок ЛР3: docker compose и карта реплик.
|
||||
|
||||
Собственные тесты лежат в student-tests/ (CONTRIBUTING.md). X-Instance-Id равен
|
||||
hostname контейнера, поэтому по нему можно найти реально обслуживший контейнер.
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
|
||||
from lab7_environment import Environment
|
||||
from securityctl import GATEWAY_PAIRS
|
||||
|
||||
|
||||
def compose(*args, check=True, env=None):
|
||||
environment = Environment()
|
||||
environment.process_env.update(env or {})
|
||||
owners = [value for value in args[1:] if value in GATEWAY_PAIRS] if args else []
|
||||
children = [child for owner in owners for child in GATEWAY_PAIRS[owner]]
|
||||
operation = args[0] if args else ''
|
||||
if operation == 'stop':
|
||||
return environment.compose(*args, *(child for child in children if child not in args), check=check)
|
||||
result = environment.compose(*args, check=check)
|
||||
if result.returncode == 0 and operation in ('up', 'start', 'restart') and children:
|
||||
environment.compose('up', '-d', '--no-build', '--force-recreate', '--no-deps', *children)
|
||||
return result
|
||||
|
||||
|
||||
def jobctl(*args, check=True):
|
||||
"""Run the dedicated operator CLI, never the worker's application credentials."""
|
||||
return operator_command('jobctl', *args, check=check)
|
||||
|
||||
|
||||
def psql(sql):
|
||||
"""Read a scalar/list through the dedicated TLS PostgreSQL operator."""
|
||||
return operator_command('psql', data=sql).stdout.strip()
|
||||
|
||||
|
||||
def operator_command(command, *args, data=None, check=True):
|
||||
environment = Environment()
|
||||
return environment.run(
|
||||
[sys.executable, str(ROOT / 'scripts/securityctl.py'), command, *map(str, args)],
|
||||
data=data, check=check,
|
||||
)
|
||||
|
||||
|
||||
def redis(*args):
|
||||
"""Run authenticated Redis TLS operator probes without exposing credentials."""
|
||||
return operator_command('redis', *args).stdout.strip()
|
||||
|
||||
|
||||
def containers_by_hostname(service='api'):
|
||||
"""{hostname: {id, name, status}} для контейнеров сервиса."""
|
||||
listed = compose('ps', '-q', service).stdout.split()
|
||||
|
||||
result = {}
|
||||
for container in listed:
|
||||
info = subprocess.run(
|
||||
['docker', 'inspect', '--format', '{{.Config.Hostname}} {{.Name}} {{.State.Status}}', container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
).stdout.split()
|
||||
|
||||
result[info[0]] = {'id': container[:12], 'name': info[1].lstrip('/'), 'status': info[2]}
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def messages_path(chat):
|
||||
return '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) < 2:
|
||||
raise SystemExit('expected compose, psql, redis or jobctl command')
|
||||
command, *args = sys.argv[1:]
|
||||
if command == 'compose':
|
||||
result = compose(*args, check=False)
|
||||
elif command in ('psql', 'redis', 'jobctl'):
|
||||
result = operator_command(command, *args, data=sys.stdin.read() if command == 'psql' else None,
|
||||
check=False)
|
||||
else:
|
||||
raise SystemExit('unsupported operator helper command')
|
||||
sys.stdout.write(result.stdout)
|
||||
sys.stderr.write(result.stderr)
|
||||
raise SystemExit(result.returncode)
|
||||
Reference in New Issue
Block a user