feat: complete lab 7 for grade 4
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
"""Measure the configured per-replica Argon2id slot budget on the app image."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from math import ceil
|
||||
import resource
|
||||
from time import perf_counter
|
||||
|
||||
from src.auth import hash_password, iterations, memory, parallelism, verify_password
|
||||
from src.login_limits import KDF_SLOTS
|
||||
|
||||
|
||||
def timed_verify(encoded):
|
||||
started = perf_counter()
|
||||
assert not verify_password(encoded, "another synthetic password")
|
||||
return (perf_counter() - started) * 1000
|
||||
|
||||
|
||||
def main():
|
||||
encoded = hash_password("synthetic benchmark password")
|
||||
timed_verify(encoded)
|
||||
with ThreadPoolExecutor(max_workers=KDF_SLOTS) as executor:
|
||||
samples = sorted(executor.map(lambda _: timed_verify(encoded), range(24)))
|
||||
print(f"Argon2id memory={memory} KiB time={iterations} lanes={parallelism} slots={KDF_SLOTS} "
|
||||
f"samples={len(samples)} p50={samples[11]:.1f}ms p95={samples[ceil(.95 * len(samples)) - 1]:.1f}ms "
|
||||
f"peak_rss={resource.getrusage(resource.RUSAGE_SELF).ru_maxrss} KiB")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,8 @@
|
||||
# Use with a unique COMPOSE_PROJECT_NAME and a new LAB7_STATE.
|
||||
services:
|
||||
openbao:
|
||||
ports: !override ["127.0.0.1:28200:8200"]
|
||||
lb:
|
||||
ports: !override ["127.0.0.1:28443:8443"]
|
||||
grafana:
|
||||
ports: !override ["127.0.0.1:23007:3000"]
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Isolated API qualification. Sends synthetic requests only to the grade-4 port."""
|
||||
import argparse
|
||||
import base64
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import subprocess
|
||||
from time import monotonic, sleep, time
|
||||
from uuid import uuid4
|
||||
|
||||
from observability import Grafana, wait
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WINDOW = int(os.getenv("LOGIN_WINDOW_SECONDS", "10"))
|
||||
LIMIT = int(os.getenv("LOGIN_WINDOW_LIMIT", "40"))
|
||||
|
||||
|
||||
def call(context, method, path, *, data=None, token=None, authorization=None):
|
||||
connection = http.client.HTTPSConnection("localhost", 28443, context=context, timeout=5)
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token or authorization:
|
||||
headers["Authorization"] = authorization or "Bearer " + token
|
||||
try:
|
||||
connection.request(method, path, None if data is None else json.dumps(data), headers)
|
||||
reply = connection.getresponse()
|
||||
return (reply.status, reply.getheader("X-Instance-Id"), reply.getheader("Retry-After"),
|
||||
reply.read(), reply.getheader("X-Request-Id"))
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def next_window():
|
||||
sleep(WINDOW - time() % WINDOW + 0.15)
|
||||
|
||||
|
||||
def login(context):
|
||||
next_window()
|
||||
start = monotonic()
|
||||
path = "/api/v1/auth/sessions"
|
||||
with ThreadPoolExecutor(max_workers=12) as executor:
|
||||
replies = list(executor.map(lambda _: call(context, "POST", path), range(LIMIT * 2)))
|
||||
assert monotonic() - start < WINDOW - 1
|
||||
assert Counter(row[0] for row in replies) == {401: LIMIT, 429: LIMIT}
|
||||
assert len({row[1] for row in replies if row[0] == 401 and row[1]}) == 2
|
||||
assert all(row[2] and 1 <= int(row[2]) <= WINDOW for row in replies if row[0] == 429)
|
||||
print(f"PASS: {LIMIT} shared admissions and {LIMIT} throttled across both API replicas")
|
||||
|
||||
next_window()
|
||||
basic = base64.b64encode(b"absent_fixture_user:synthetic_password").decode()
|
||||
start = monotonic()
|
||||
with ThreadPoolExecutor(max_workers=12) as executor:
|
||||
replies = list(executor.map(lambda _: call(context, "POST", path,
|
||||
authorization="Basic " + basic), range(LIMIT * 2)))
|
||||
elapsed = monotonic() - start
|
||||
counts = Counter(row[0] for row in replies)
|
||||
assert elapsed < WINDOW - 1 and counts.keys() == {401, 429}
|
||||
assert counts[401] <= LIMIT and sum(counts.values()) == LIMIT * 2
|
||||
assert call(context, "GET", "/health/ready")[0] == 200
|
||||
print(f"PASS: wrong-password burst {elapsed:.3f}s: {counts[401]} rejected after hash, {counts[429]} throttled")
|
||||
next_window()
|
||||
assert call(context, "POST", path)[0] == 401
|
||||
print("PASS: admissions resume in the next window")
|
||||
|
||||
|
||||
def rehash(context):
|
||||
username = "rehash_" + uuid4().hex[:12]
|
||||
password = uuid4().hex
|
||||
assert call(context, "POST", "/api/v1/users", data={
|
||||
"username": username, "display_name": "Rehash fixture", "password": password
|
||||
})[0] == 201
|
||||
compose = ["sh", str(ROOT / "scripts/compose.sh"), "exec", "-T", "api-a", "python", "-c"]
|
||||
code = """
|
||||
import json, sys
|
||||
from argon2 import PasswordHasher
|
||||
import psycopg
|
||||
from src.credentials import credentials
|
||||
from src.auth import password_hasher
|
||||
username, password, operation = json.load(sys.stdin)
|
||||
credentials.start()
|
||||
with psycopg.connect(credentials.get()["database_url"]) as conn:
|
||||
old = PasswordHasher(memory_cost=19456, time_cost=2, parallelism=1)
|
||||
if operation == "seed":
|
||||
conn.execute("UPDATE users SET password_hash=%s WHERE username=%s", (old.hash(password), username))
|
||||
else:
|
||||
value = conn.execute("SELECT password_hash FROM users WHERE username=%s", (username,)).fetchone()[0]
|
||||
assert password_hasher.verify(value, password) and not password_hasher.check_needs_rehash(value)
|
||||
credentials.stop.set()
|
||||
"""
|
||||
subprocess.run([*compose, code], input=json.dumps([username, password, "seed"]), text=True, check=True)
|
||||
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
next_window()
|
||||
assert call(context, "POST", "/api/v1/auth/sessions", authorization="Basic " + basic)[0] == 201
|
||||
subprocess.run([*compose, code], input=json.dumps([username, password, "verify"]), text=True, check=True)
|
||||
print("PASS: successful login rehashed an older Argon2id profile")
|
||||
|
||||
|
||||
def rotation(context, kind):
|
||||
username = "rotate_" + uuid4().hex[:12]
|
||||
password = uuid4().hex
|
||||
assert call(context, "POST", "/api/v1/users", data={
|
||||
"username": username, "display_name": "Rotation fixture", "password": password
|
||||
})[0] == 201
|
||||
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
result = call(context, "POST", "/api/v1/auth/sessions", authorization="Basic " + basic)
|
||||
assert result[0] == 201
|
||||
token = json.loads(result[3])["token"]
|
||||
counts = Counter()
|
||||
instances = set()
|
||||
with subprocess.Popen(["python3", str(ROOT / "scripts" / f"rotate-{kind}.py")], cwd=ROOT) as process:
|
||||
while process.poll() is None:
|
||||
try:
|
||||
status, instance, *_ = call(context, "GET", "/api/v1/users/me", token=token)
|
||||
counts[status] += 1
|
||||
if status == 200 and instance:
|
||||
instances.add(instance)
|
||||
except (OSError, http.client.HTTPException):
|
||||
counts["transport_error"] += 1
|
||||
sleep(0.1)
|
||||
print(f"During {kind} rotation: {dict(counts)}, API replicas observed: {len(instances)}")
|
||||
assert process.returncode == 0 and counts.keys() == {200} and len(instances) == 2
|
||||
|
||||
|
||||
def log_hygiene(context):
|
||||
username, password = "logs_" + uuid4().hex[:12], uuid4().hex
|
||||
assert call(context, "POST", "/api/v1/users", data={
|
||||
"username": username, "display_name": "Log fixture", "password": password
|
||||
})[0] == 201
|
||||
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
next_window()
|
||||
result = call(context, "POST", "/api/v1/auth/sessions", authorization="Basic " + basic)
|
||||
assert result[0] == 201
|
||||
token = json.loads(result[3])["token"]
|
||||
authenticated = call(context, "GET", "/api/v1/users/me", token=token)
|
||||
assert authenticated[0] == 200
|
||||
logs = subprocess.check_output(
|
||||
["sh", str(ROOT / "scripts/compose.sh"), "logs", "--no-color",
|
||||
"api-a", "api-b", "worker", "recovery", "postgres", "otel-collector"], text=True
|
||||
)
|
||||
grafana = Grafana("https://localhost:23007")
|
||||
secrets = (password, token, basic)
|
||||
assert all(value not in logs for value in secrets)
|
||||
for request_id in (result[4], authenticated[4]):
|
||||
assert request_id
|
||||
query = '{service_name="messenger-api"} | json | request_id="' + request_id + '"'
|
||||
telemetry = wait(lambda: grafana.logs(query), timeout=45)
|
||||
trace_id = next(log["trace_id"] for log in telemetry if log.get("trace_id"))
|
||||
spans = wait(lambda: grafana.trace(trace_id), timeout=45)
|
||||
sampled = json.dumps((telemetry, spans))
|
||||
assert all(value not in sampled for value in secrets)
|
||||
subprocess.run(
|
||||
["sh", str(ROOT / "scripts/compose.sh"), "exec", "-T", "--user", "postgres", "postgres",
|
||||
"psql", "-Xq", "-v", "ON_ERROR_STOP=1", "-d", "messenger"],
|
||||
input=f"UPDATE sessions SET expires_at=now()-interval '1 second' WHERE user_id="
|
||||
f"(SELECT id FROM users WHERE username='{username}');",
|
||||
text=True, check=True,
|
||||
)
|
||||
assert call(context, "GET", "/api/v1/users/me", token=token)[0] == 401
|
||||
print("PASS: container logs and correlated Loki/Tempo records exclude synthetic credentials")
|
||||
print("PASS: the same bearer is denied after session expiry")
|
||||
|
||||
|
||||
def await_ready(context, status, seconds):
|
||||
deadline = monotonic() + seconds
|
||||
while monotonic() < deadline:
|
||||
try:
|
||||
if call(context, "GET", "/health/ready")[0] == status:
|
||||
return
|
||||
except (OSError, http.client.HTTPException):
|
||||
pass
|
||||
sleep(0.5)
|
||||
raise AssertionError(f"Readiness did not reach HTTP {status}")
|
||||
|
||||
|
||||
def availability(context, kind):
|
||||
compose = ["sh", str(ROOT / "scripts/compose.sh")]
|
||||
if kind == "login-recovery":
|
||||
subprocess.run([*compose, "stop", "postgres"], check=True)
|
||||
try:
|
||||
subprocess.run([*compose, "run", "--rm", "-T", "probe", "login-unavailable"], check=True)
|
||||
finally:
|
||||
subprocess.run([*compose, "start", "postgres"], check=True)
|
||||
await_ready(context, 200, 45)
|
||||
next_window()
|
||||
assert call(context, "POST", "/api/v1/auth/sessions")[0] == 401
|
||||
print("PASS: both login endpoints fail closed with PostgreSQL down and recover after restart")
|
||||
else:
|
||||
seal = "import bao; bao.request('sys/seal', token=bao.operator()['root_token'], method='PUT')"
|
||||
subprocess.run(["python3", "-c", seal], env=dict(os.environ, PYTHONPATH=str(ROOT / "scripts")), check=True)
|
||||
try:
|
||||
await_ready(context, 503, 45)
|
||||
finally:
|
||||
subprocess.run(["python3", str(ROOT / "scripts/bao.py"), "unseal"], check=True)
|
||||
await_ready(context, 200, 45)
|
||||
print("PASS: sealed OpenBao drains bounded snapshots, fails closed, and recovers after unseal")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("test", choices=("login", "rehash", "db", "leaf", "login-recovery",
|
||||
"sealed", "log-hygiene"))
|
||||
args = parser.parse_args()
|
||||
if (not os.environ.get("COMPOSE_PROJECT_NAME", "").startswith("lab7-grade4-")
|
||||
or "grade4.compose.yaml" not in os.environ.get("COMPOSE_FILE", "")
|
||||
or os.environ.get("LAB7_OPENBAO_URL") != "https://localhost:28200"):
|
||||
parser.error("Use the isolated Compose override and OpenBao port documented in REPORT.md")
|
||||
context = ssl.create_default_context(cafile=str(Path(os.environ["LAB7_STATE"]) / "trust/ca.crt"))
|
||||
if args.test == "login":
|
||||
login(context)
|
||||
elif args.test == "rehash":
|
||||
rehash(context)
|
||||
elif args.test == "log-hygiene":
|
||||
log_hygiene(context)
|
||||
elif args.test in ("login-recovery", "sealed"):
|
||||
availability(context, args.test)
|
||||
else:
|
||||
rotation(context, args.test)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,451 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read live Grafana data sources and run bounded faults in Compose lab6."""
|
||||
import argparse
|
||||
import base64
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import json
|
||||
import ssl
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, check
|
||||
|
||||
COMPOSE = ROOT / 'scripts/compose.sh'
|
||||
FIXTURE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
ROUTE = '/api/v1/chats/{chat_id}/messages'
|
||||
SUPPRESS = (HTTPError, URLError, TimeoutError)
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def compose(*args, capture=True):
|
||||
result = subprocess.run([COMPOSE, *args], cwd=ROOT, check=True, text=True,
|
||||
capture_output=capture, timeout=75)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def sql_command(statement):
|
||||
return [COMPOSE, 'exec', '-T', '--user', 'postgres', 'postgres', 'psql', '-XAt', '-v', 'ON_ERROR_STOP=1',
|
||||
'-U', 'postgres', '-d', 'messenger', '-c', statement]
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return subprocess.check_output(sql_command(statement), text=True, timeout=10).strip()
|
||||
|
||||
|
||||
def wait(action, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
result = action()
|
||||
except SUPPRESS:
|
||||
result = None
|
||||
if result:
|
||||
return result
|
||||
time.sleep(1)
|
||||
raise AssertionError(f'timeout after {timeout}s')
|
||||
|
||||
|
||||
class Grafana:
|
||||
def __init__(self, url):
|
||||
self.url = url
|
||||
state = Path(os.getenv("LAB7_STATE", f"/private/tmp/mtusi2026lab7-{os.getuid()}"))
|
||||
password = (state / "grafana/admin").read_text().strip()
|
||||
self.context = ssl.create_default_context(cafile=str(state / "trust/ca.crt"))
|
||||
self.headers = {'Authorization': 'Basic ' + base64.b64encode(f'admin:{password}'.encode()).decode()}
|
||||
|
||||
def get(self, path, **params):
|
||||
query = '?' + urlencode(params) if params else ''
|
||||
with urlopen(Request(self.url + path + query, headers=self.headers), timeout=10, context=self.context) as response:
|
||||
return json.load(response)
|
||||
|
||||
def proxy(self, uid, path, **params):
|
||||
return self.get(f'/api/datasources/proxy/uid/{uid}{path}', **params)
|
||||
|
||||
def prom(self, expression, timestamp=None):
|
||||
params = {'query': expression}
|
||||
if timestamp is not None:
|
||||
params['time'] = timestamp
|
||||
return self.proxy('prometheus', '/api/v1/query', **params)['data']['result']
|
||||
|
||||
def scalar(self, expression):
|
||||
values = self.prom(expression)
|
||||
return float(values[0]['value'][1]) if values else None
|
||||
|
||||
def alerts(self):
|
||||
return {item['labels']['alertname']: item['state']
|
||||
for item in self.proxy('prometheus', '/api/v1/alerts')['data']['alerts']}
|
||||
|
||||
def logs(self, query):
|
||||
data = self.proxy('loki', '/loki/api/v1/query_range', query=query, limit=50,
|
||||
start=int((time.time()-600)*1e9), end=time.time_ns())['data']['result']
|
||||
return [json.loads(line) for stream in data for _, line, *_ in stream['values']]
|
||||
|
||||
def trace(self, trace_id):
|
||||
trace = self.proxy('tempo', f'/api/traces/{trace_id}')
|
||||
spans = []
|
||||
for batch in trace.get('batches', trace.get('resourceSpans', [])):
|
||||
resource = {item['key']: next(iter(item['value'].values()))
|
||||
for item in batch['resource']['attributes']}
|
||||
for scope in batch['scopeSpans']:
|
||||
for span in scope['spans']:
|
||||
spans.append(dict(span, service_name=resource['service.name']))
|
||||
return spans
|
||||
|
||||
|
||||
def save(name, data):
|
||||
(ROOT / 'evidence' / (name + '.json')).write_text(json.dumps(data, indent=2, ensure_ascii=False,
|
||||
allow_nan=False) + '\n')
|
||||
|
||||
|
||||
def upload(client, actor, chat, trace_id=None):
|
||||
headers = {'Content-Type': 'image/png'}
|
||||
if trace_id:
|
||||
headers.update(traceparent=f'00-{trace_id}-0123456789abcdef-01', tracestate='lab=synthetic')
|
||||
return client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png',
|
||||
202, actor=actor, raw=FIXTURE, headers=headers, schema='Attachment')
|
||||
|
||||
|
||||
def raw_read(client, actor, chat, trace_id=None):
|
||||
headers = {'Authorization': 'Bearer ' + actor['token']}
|
||||
if trace_id:
|
||||
headers['traceparent'] = f'00-{trace_id}-0123456789abcdef-01'
|
||||
request = Request(client.base + ROUTE.format(chat_id=chat['id']), headers=headers)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
response = urlopen(request, timeout=10, context=ssl.create_default_context(cafile=os.environ["CA_FILE"]))
|
||||
except HTTPError as exc:
|
||||
response = exc
|
||||
except (URLError, TimeoutError):
|
||||
return {'status': 0, 'seconds': time.monotonic()-started}
|
||||
with response:
|
||||
response.read()
|
||||
return {'status': response.code, 'seconds': time.monotonic()-started,
|
||||
'request_id': response.headers.get('X-Request-Id')}
|
||||
|
||||
|
||||
def verify(client, grafana, retry):
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
trace_id = uuid4().hex
|
||||
marker = upload(client, actor, chat, trace_id)
|
||||
started = time.time()
|
||||
client.wait_ready(actor, marker['json'])
|
||||
if retry:
|
||||
# Stop uses a local, fixed Compose service. Resume even after an assertion.
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
trace_id = uuid4().hex
|
||||
marker = upload(client, actor, chat, trace_id)
|
||||
attachment_id = marker['json']['id']
|
||||
sql(f"""INSERT INTO pipeline_faults(attachment_id,pipeline_version,point,action)
|
||||
VALUES ('{attachment_id}',1,'before_s3','temporary')""")
|
||||
finally:
|
||||
compose('start', 'worker')
|
||||
client.wait_ready(actor, marker['json'])
|
||||
request_id = marker['headers']['X-Request-Id']
|
||||
|
||||
required = {'attachment.accept', 'outbox.enqueue', 's3.put_object', 's3.read_original',
|
||||
'job.claim', 'job.publish_ready', 'postgresql.execute', 'postgresql.transaction.close'}
|
||||
|
||||
def complete_trace():
|
||||
spans = grafana.trace(trace_id)
|
||||
by_id = {item['spanId']: item for item in spans}
|
||||
consumers = [item for item in spans if item['kind'] in (5, 'SPAN_KIND_CONSUMER')]
|
||||
if len(consumers) < (2 if retry else 1):
|
||||
return None
|
||||
for consumer in consumers:
|
||||
producer = by_id.get(consumer.get('parentSpanId'))
|
||||
if not producer or producer.get('parentSpanId') not in by_id:
|
||||
return None
|
||||
return spans if required <= {item['name'] for item in spans} else None
|
||||
|
||||
spans = wait(complete_trace)
|
||||
check(required <= {s['name'] for s in spans}, 'missing spans along upload path')
|
||||
by_id = {s['spanId']: s for s in spans}
|
||||
consumers = [s for s in spans if s['kind'] in (5, 'SPAN_KIND_CONSUMER')]
|
||||
check(len(consumers) >= (2 if retry else 1), 'consumer / retry span absent')
|
||||
for consumer in consumers:
|
||||
producer = by_id[consumer['parentSpanId']]
|
||||
check(producer['kind'] in (4, 'SPAN_KIND_PRODUCER'), 'consumer parent must be producer')
|
||||
check(by_id[producer['parentSpanId']]['name'] == 'attachment.accept', 'producer parent mismatch')
|
||||
query = '{service_name=~"messenger-api|messenger-worker|messenger-publisher"} | json | trace_id="' + trace_id + '"'
|
||||
logs = wait(lambda: (rows if (rows := grafana.logs(query)) and
|
||||
{'messenger-api', 'messenger-worker', 'messenger-publisher'}
|
||||
<= {row['service.name'] for row in rows} else None))
|
||||
check(any(row.get('request_id') == request_id for row in logs), 'request id not correlated')
|
||||
check(all(row['trace_id'] == trace_id for row in logs), 'different trace IDs in Loki')
|
||||
if retry:
|
||||
check({'retry','ready'} <= {row.get('outcome') for row in logs}, 'retry and ready should be in one trace')
|
||||
prometheus = grafana.proxy('prometheus', '/api/v1/query_exemplars', query='lab_http_duration_seconds_bucket',
|
||||
start=started-15, end=time.time())['data']
|
||||
dashboard = grafana.get('/api/dashboards/uid/messenger-lab6')['dashboard']
|
||||
metrics = {}
|
||||
for panel in dashboard['panels']:
|
||||
if panel['datasource']['uid'] != 'prometheus':
|
||||
continue
|
||||
metrics[panel['title']] = {target['expr']: grafana.prom(target['expr']) for target in panel['targets']}
|
||||
save('signals-retry' if retry else 'signals', {
|
||||
'timestamp': now(), 'trace_id': trace_id, 'request_id': request_id, 'spans': spans, 'logs': logs,
|
||||
'dashboard_queries': metrics, 'exemplar_count': sum(len(x['exemplars']) for x in prometheus),
|
||||
})
|
||||
|
||||
|
||||
class Incident:
|
||||
queries = {
|
||||
'queue_depth': 'max(lab_queue_depth)', 'oldest_seconds': 'max(lab_oldest_job_age_seconds)',
|
||||
'api_waiting': 'sum(lab_db_pool_waiting{service_name="messenger-api"})',
|
||||
'api_pool_used': 'sum(lab_db_pool_used{service_name="messenger-api"})',
|
||||
'workers': 'sum(lab_worker_capacity)', 'api_p95': 'histogram_quantile(0.95,sum by(le)(rate(lab_http_duration_seconds_bucket[30s])))',
|
||||
'api_burn_30s': 'lab:burn_api:30s', 'api_burn_2m': 'lab:burn_api:2m',
|
||||
'api_burn_5m': 'lab:burn_api:5m',
|
||||
'ready_burn_30s': 'lab:burn_ready:30s', 'ready_burn_2m': 'lab:burn_ready:2m',
|
||||
'ready_burn_5m': 'lab:burn_ready:5m',
|
||||
'ready_burn_1h': 'lab:burn_ready:1h', 'api_burn_1h': 'lab:burn_api:1h',
|
||||
'ready_cohort_1h': 'lab:sli_ready_total:1h', 'api_cohort_1h': 'lab:sli_api_total:1h',
|
||||
'collector_rss': 'otelcol_process_memory_rss_bytes',
|
||||
'tempo_queue': 'sum(otelcol_exporter_queue_size{exporter="otlphttp/tempo"})',
|
||||
'tempo_queue_limit': 'sum(otelcol_exporter_queue_capacity{exporter="otlphttp/tempo"})',
|
||||
'tempo_drop': 'sum(otelcol_exporter_send_failed_spans_total{exporter="otlphttp/tempo"})',
|
||||
'tempo_enqueue_drop': 'sum(otelcol_exporter_enqueue_failed_spans_total{exporter="otlphttp/tempo"})',
|
||||
}
|
||||
|
||||
def __init__(self, grafana, name):
|
||||
self.grafana, self.name = grafana, name
|
||||
self.started = time.time()
|
||||
self.data = {'started': now(), 'samples': [], 'markers': {}}
|
||||
|
||||
def mark(self, name):
|
||||
self.data['markers'][name] = {'timestamp': now(), 't': round(time.time()-self.started, 2)}
|
||||
|
||||
def sample(self, phase):
|
||||
t = time.time()
|
||||
alerts = self.grafana.alerts()
|
||||
row = {'phase': phase, 't': round(t-self.started, 2), 'timestamp': now(), 'alerts': alerts}
|
||||
# A single Prometheus query gets metrics at the same evaluation timestamp.
|
||||
expression = ' or '.join(f'label_replace(({expr}),"measurement","{key}","","")'
|
||||
for key, expr in self.queries.items())
|
||||
for result in self.grafana.prom(expression, t):
|
||||
value = float(result['value'][1])
|
||||
if abs(value) < float('inf'):
|
||||
row[result['metric']['measurement']] = value
|
||||
self.data['samples'].append(row)
|
||||
save(self.name, self.data)
|
||||
return row
|
||||
|
||||
def settle(self, names, phase='recovery', timeout=330, predicate=None):
|
||||
deadline = time.monotonic()+timeout
|
||||
while time.monotonic() < deadline:
|
||||
row = self.sample(phase)
|
||||
if names.isdisjoint(row['alerts']) and (predicate is None or predicate(row)):
|
||||
self.mark('resolved')
|
||||
return
|
||||
time.sleep(5)
|
||||
raise AssertionError('alerts did not resolve')
|
||||
|
||||
def finish(self):
|
||||
transitions = {}
|
||||
names = {name for row in self.data['samples'] for name in row['alerts']}
|
||||
for name in sorted(names):
|
||||
fired = next((row for row in self.data['samples']
|
||||
if row['alerts'].get(name) == 'firing'), None)
|
||||
if fired is None:
|
||||
continue
|
||||
resolved = next((row for row in self.data['samples']
|
||||
if row['t'] > fired['t'] and name not in row['alerts']), None)
|
||||
transitions[name] = {'firing_t': fired['t'], 'resolved_t': resolved['t'] if resolved else None}
|
||||
self.data['transitions'] = transitions
|
||||
save(self.name, self.data)
|
||||
|
||||
|
||||
def queue_incident(client, grafana):
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
trial = Incident(grafana, 'incident-queue')
|
||||
target = {'QueueLag', 'ReadyBurnFast', 'ReadyBurnSlow'}
|
||||
trial.settle(target, phase='baseline', timeout=330)
|
||||
attachments = []
|
||||
compose('stop', 'worker')
|
||||
trial.mark('worker_stopped')
|
||||
fired = set()
|
||||
try:
|
||||
deadline = time.monotonic()+140
|
||||
while time.monotonic() < deadline:
|
||||
start = time.monotonic()
|
||||
attachments.append(upload(client, actor, chat)['json'])
|
||||
if len(attachments) % 3 == 1:
|
||||
row = trial.sample('worker_stopped')
|
||||
fired.update(name for name, state in row['alerts'].items() if state == 'firing')
|
||||
time.sleep(max(0, 2 - (time.monotonic()-start)))
|
||||
check(target <= fired, 'queue / ready burn alerts did not all fire')
|
||||
samples = [row for row in trial.data['samples'] if row['phase'] == 'worker_stopped']
|
||||
check(max(row.get('queue_depth', 0) for row in samples) > 10, 'no backlog growth')
|
||||
check(max(row.get('oldest_seconds', 0) for row in samples) > 30, 'no age growth')
|
||||
finally:
|
||||
compose('start', 'worker')
|
||||
trial.mark('worker_restarted')
|
||||
trial.finish()
|
||||
for attachment in attachments:
|
||||
client.wait_ready(actor, attachment)
|
||||
trial.mark('all_ready')
|
||||
trial.data['accepted'] = len(attachments)
|
||||
trial.settle(target, predicate=lambda row: row.get('queue_depth') == 0 and row.get('oldest_seconds') == 0)
|
||||
trial.finish()
|
||||
|
||||
|
||||
def db_incident(client, grafana, spike):
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
trial = Incident(grafana, 'incident-db-spike' if spike else 'incident-db-long')
|
||||
target = {'HighHTTPErrorRate', 'APIBurnFast', 'APIBurnSlow'}
|
||||
trial.settle(target, phase='baseline')
|
||||
statuses = Counter()
|
||||
trace_id = uuid4().hex
|
||||
if spike:
|
||||
# A real short PostgreSQL lock. First warm the same route at 3 requests/s.
|
||||
deadline = time.monotonic() + 125
|
||||
while time.monotonic() < deadline:
|
||||
start = time.monotonic()
|
||||
reading = raw_read(client, actor, chat)
|
||||
statuses[f'baseline_{reading["status"]}'] += 1
|
||||
time.sleep(max(0, 1/3-(time.monotonic()-start)))
|
||||
lock_seconds = 7 if spike else 140
|
||||
# The transaction lock is released by PostgreSQL even if this client exits.
|
||||
statement = (f"SET statement_timeout='{lock_seconds+2}s'; "
|
||||
f'BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep({lock_seconds}); ROLLBACK')
|
||||
lock = subprocess.Popen(sql_command(statement), cwd=ROOT, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL)
|
||||
fired = set()
|
||||
probe = None
|
||||
try:
|
||||
wait(lambda: sql("""SELECT count(*) FROM pg_locks
|
||||
WHERE relation='messages'::regclass AND mode='AccessExclusiveLock'
|
||||
AND granted""") == '1', timeout=6)
|
||||
trial.mark('db_lock_acquired')
|
||||
with ThreadPoolExecutor(max_workers=32) as pool:
|
||||
first = pool.submit(raw_read, client, actor, chat, trace_id)
|
||||
concurrency = 11 if spike else 30
|
||||
load = [pool.submit(raw_read, client, actor, chat) for _ in range(concurrency)]
|
||||
trial.sample('db_lock')
|
||||
for response in load:
|
||||
statuses[str(response.result()['status'])] += 1
|
||||
probe = first.result()
|
||||
statuses[str(probe['status'])] += 1
|
||||
while lock.poll() is None:
|
||||
start = time.monotonic()
|
||||
# Fixed number of in-flight requests, no client retries.
|
||||
if spike:
|
||||
reads = [pool.submit(raw_read, client, actor, chat)]
|
||||
else:
|
||||
reads = [pool.submit(raw_read, client, actor, chat) for _ in range(6)]
|
||||
row = trial.sample('db_lock')
|
||||
fired.update(name for name, state in row['alerts'].items() if state == 'firing')
|
||||
for response in reads:
|
||||
statuses[str(response.result()['status'])] += 1
|
||||
time.sleep(max(0, 1-(time.monotonic()-start)))
|
||||
finally:
|
||||
lock.wait(timeout=lock_seconds+5)
|
||||
trial.mark('db_lock_released')
|
||||
trial.finish()
|
||||
check(probe and probe['status'] == 503, 'locked SQL did not yield expected API 503')
|
||||
spans = wait(lambda: grafana.trace(trace_id))
|
||||
sql_spans = [span for span in spans if span['name'] == 'postgresql.execute']
|
||||
check(any(int(span['endTimeUnixNano'])-int(span['startTimeUnixNano']) >= 4e9 for span in sql_spans),
|
||||
'trace does not distinguish a slow DB query')
|
||||
request_id = probe['request_id']
|
||||
logs = wait(lambda: grafana.logs('{service_name="messenger-api"} | json | request_id="' + request_id + '"'))
|
||||
check(any(row['trace_id'] == trace_id and row['status'] == 503 for row in logs), 'no correlated HTTP error log')
|
||||
trial.data.update(statuses=dict(statuses), failing_probe=probe, trace_id=trace_id, spans=spans, logs=logs)
|
||||
check(raw_read(client, actor, chat)['status'] == 200, 'DB did not recover')
|
||||
if spike:
|
||||
deadline = time.monotonic()+45
|
||||
while time.monotonic() < deadline:
|
||||
trial.sample('post_spike')
|
||||
for _ in range(9):
|
||||
reading = raw_read(client, actor, chat)
|
||||
statuses[f'recovery_{reading["status"]}'] += 1
|
||||
time.sleep(1/3)
|
||||
observations = [row['alerts'] for row in trial.data['samples']]
|
||||
check(not any(set(row) & {'APIBurnFast','APIBurnSlow'} for row in observations),
|
||||
'short spike caused an API burn alert')
|
||||
else:
|
||||
check(target <= fired, 'sustained DB incident did not fire all API alerts')
|
||||
trial.data['statuses'] = dict(statuses)
|
||||
trial.finish()
|
||||
trial.settle(target)
|
||||
trial.finish()
|
||||
|
||||
|
||||
def telemetry_incident(client, grafana):
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
trial = Incident(grafana, 'incident-telemetry')
|
||||
base = trial.sample('baseline')
|
||||
check(base.get('collector_rss', 0) > 0, 'collector RSS metric missing')
|
||||
compose('stop', 'tempo')
|
||||
trial.mark('tempo_stopped')
|
||||
confirmed = 0
|
||||
try:
|
||||
deadline = time.monotonic()+50
|
||||
while time.monotonic() < deadline:
|
||||
client.message(actor, chat, 'synthetic upload during trace outage')
|
||||
marker = upload(client, actor, chat)
|
||||
client.wait_ready(actor, marker['json'])
|
||||
confirmed += 1
|
||||
if confirmed % 3 == 1:
|
||||
trial.sample('tempo_stopped')
|
||||
time.sleep(1)
|
||||
finally:
|
||||
compose('start', 'tempo')
|
||||
trial.mark('tempo_restarted')
|
||||
trial.finish()
|
||||
trial.data['writes_and_ready'] = confirmed
|
||||
loss = lambda row: row.get('tempo_drop', 0)+row.get('tempo_enqueue_drop', 0)
|
||||
check(max(map(loss, trial.data['samples'])) > loss(base), 'trace losses not observed')
|
||||
wait(lambda: trace_after_recovery(client, grafana, actor, chat),
|
||||
timeout=100)
|
||||
trial.mark('new_trace_available')
|
||||
trial.settle({'TelemetryExportLoss'})
|
||||
trial.finish()
|
||||
|
||||
|
||||
def trace_after_recovery(client, grafana, actor, chat):
|
||||
trace_id = uuid4().hex
|
||||
upload(client, actor, chat, trace_id)
|
||||
try:
|
||||
return wait(lambda: grafana.trace(trace_id), timeout=8)
|
||||
except AssertionError:
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('test', choices=['signals', 'retry', 'queue', 'spike', 'db', 'telemetry'])
|
||||
parser.add_argument('--base-url', default='https://localhost:8443')
|
||||
parser.add_argument('--grafana', default='https://localhost:3007')
|
||||
args = parser.parse_args()
|
||||
client, grafana = Client(args.base_url), Grafana(args.grafana)
|
||||
if args.test in ('signals', 'retry'):
|
||||
verify(client, grafana, args.test == 'retry')
|
||||
else:
|
||||
{
|
||||
'queue': queue_incident,
|
||||
'spike': lambda c,g: db_incident(c,g,True),
|
||||
'db': lambda c,g: db_incident(c,g,False),
|
||||
'telemetry': telemetry_incident,
|
||||
}[args.test](client, grafana)
|
||||
print(f'PASS {args.test} {now()}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,366 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Destructive fault injection for a disposable, dedicated LAB6 Compose project."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, check
|
||||
from image_probe import jpeg_size
|
||||
|
||||
COMPOSE = str(ROOT / 'scripts/compose.sh')
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run([COMPOSE, *args], check=True, text=True, capture_output=True, timeout=120).stdout.strip()
|
||||
|
||||
|
||||
def sql(query):
|
||||
return compose('exec', '-T', '--user', 'postgres', 'postgres', 'psql', '-XAt', '-v', 'ON_ERROR_STOP=1',
|
||||
'-U', 'postgres', '-d', 'messenger', '-c', query)
|
||||
|
||||
|
||||
def job(attachment, version=1):
|
||||
return json.loads(sql(f"""SELECT row_to_json(j) FROM image_jobs j
|
||||
WHERE attachment_id='{attachment['id']}' AND pipeline_version={version}"""))
|
||||
|
||||
|
||||
def events(job_id, name):
|
||||
return int(sql(f"SELECT count(*) FROM job_events WHERE job_id='{job_id}' AND event='{name}'"))
|
||||
|
||||
|
||||
def operator(command, identifier, *args):
|
||||
return json.loads(compose('run', '--rm', '-T', 'ops', command,
|
||||
identifier, *args))
|
||||
|
||||
|
||||
def wait(predicate, description, timeout=105):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if predicate():
|
||||
return
|
||||
time.sleep(0.2)
|
||||
raise AssertionError(f'timeout: {description}')
|
||||
|
||||
|
||||
def arm(attachment, point, action, version=1):
|
||||
sql(f"""INSERT INTO pipeline_faults(attachment_id,pipeline_version,point,action)
|
||||
VALUES ('{attachment['id']}',{version},'{point}','{action}')""")
|
||||
|
||||
|
||||
def hit(attachment, point, release=False):
|
||||
scope = f"attachment_id='{attachment['id']}' AND pipeline_version=1 AND point='{point}'"
|
||||
wait(lambda: sql(f'SELECT hit_at IS NOT NULL FROM pipeline_faults WHERE {scope}') == 't', point)
|
||||
if release:
|
||||
sql(f'UPDATE pipeline_faults SET released=true WHERE {scope}')
|
||||
|
||||
|
||||
def objects(attachment, version):
|
||||
prefix = f"results/{attachment['id']}/v{version}/"
|
||||
# Operator-only inspection on the disposable stand keeps Recovery's IAM
|
||||
# policy limited to staging. MinIO prints relative keys for this prefix.
|
||||
code = '''
|
||||
MC_CONFIG_DIR=$(mktemp -d)
|
||||
export MC_CONFIG_DIR
|
||||
trap 'rm -rf "$MC_CONFIG_DIR"' EXIT
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /run/trust/ca.crt "$MC_CONFIG_DIR/certs/CAs/lab.crt"
|
||||
mc alias set local https://s3:9000 labroot "$(cat /run/identity/admin)" >/dev/null 2>&1
|
||||
mc --json ls --recursive "local/messenger-attachments/$1"
|
||||
'''
|
||||
lines = compose('exec', '-T', 's3', 'sh', '-ec', code, 'sh', prefix).splitlines()
|
||||
return sorted(prefix + json.loads(line)['key'] for line in lines)
|
||||
|
||||
|
||||
def report(name, started, attachment, **metrics):
|
||||
print(json.dumps(dict(scenario=name, result='PASS', seconds=round(time.monotonic() - started, 3),
|
||||
attachment_id=attachment['id'], **metrics), ensure_ascii=False), flush=True)
|
||||
|
||||
|
||||
def service_health(service):
|
||||
return [json.loads(line)['Health'] for line in
|
||||
compose('ps', '--format', 'json', service).splitlines()]
|
||||
|
||||
|
||||
def experiments(client):
|
||||
sql('GRANT SELECT, UPDATE(hit_at) ON pipeline_faults TO publisher, worker')
|
||||
compose('up', '-d', '--no-deps', '--wait', 'publisher', 'worker')
|
||||
worker_count = compose('ps', '-q', 'worker').splitlines()
|
||||
check(len(worker_count) >= 2, 'two workers are required')
|
||||
for service in ('publisher', 'worker'):
|
||||
enabled = compose('exec', '-T', service, 'printenv', 'PIPELINE_FAULTS')
|
||||
check(enabled == '1', f'fault injection disabled on {service}')
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
|
||||
def upload():
|
||||
return client.attachment(alice, chat)
|
||||
|
||||
def meta(attachment, status=200):
|
||||
return client.call('GET', '/api/v1/attachments/' + attachment['id'], status,
|
||||
actor=bob, schema='Attachment')['json']
|
||||
|
||||
def verify(attachment, content, version=1):
|
||||
wait(lambda: job(attachment, version)['state'] == 'ready', f'job v{version} ready')
|
||||
ready = meta(attachment)
|
||||
check(ready['status'] == 'ready', 'attachment is not ready')
|
||||
row = job(attachment, version)
|
||||
active = int(sql(f"SELECT active_version FROM attachments WHERE id='{attachment['id']}'"))
|
||||
check(active == version, 'wrong active version')
|
||||
check(events(row['id'], 'published') == 1, 'expected one published manifest')
|
||||
check(set(row['manifest']) == {'original', 'thumbnail', 'crop', 'optimized'}, 'manifest incomplete')
|
||||
check(set(objects(attachment, version)) == {v['key'] for v in row['manifest'].values()},
|
||||
'unexpected keys or duplicated side effects')
|
||||
path = '/api/v1/attachments/' + attachment['id'] + '/content?variant='
|
||||
check({v['name'] for v in ready['variants']} == {'thumbnail', 'crop', 'optimized'}, 'wrong API variants')
|
||||
for variant, entry in row['manifest'].items():
|
||||
downloaded = client.call('GET', path + variant, actor=bob)
|
||||
data = downloaded['bytes']
|
||||
check(downloaded['headers'].get_content_type() == entry['content_type'], 'wrong MIME')
|
||||
check(len(data) == entry['size_bytes'], 'wrong size')
|
||||
check(hashlib.sha256(data).hexdigest() == entry['sha256'], 'wrong checksum')
|
||||
if variant == 'original':
|
||||
check(data == content, 'original changed')
|
||||
elif variant == 'optimized':
|
||||
check(data[:4] == b'RIFF' and data[8:12] == b'WEBP', 'invalid WebP signature')
|
||||
check((entry['width'], entry['height']) == (320, 200), 'WebP must not be enlarged')
|
||||
else:
|
||||
expected = (256, 160) if variant == 'thumbnail' else (128, 128)
|
||||
check(jpeg_size(data) == expected, 'wrong JPEG dimensions')
|
||||
return row
|
||||
|
||||
started = time.monotonic()
|
||||
key = 'concurrent-message-' + chat['id']
|
||||
def post_message(_):
|
||||
return client.message(alice, chat, 'concurrent', key=key)
|
||||
with ThreadPoolExecutor(max_workers=6) as executor:
|
||||
responses = list(executor.map(post_message, range(6)))
|
||||
check(len({response['json']['id'] for response in responses}) == 1, 'concurrent writes created duplicates')
|
||||
check(len({response['headers']['X-Instance-Id'] for response in responses}) >= 2,
|
||||
'concurrent requests did not reach two API instances')
|
||||
report('concurrent_message', started, {'id': None}, requests=6)
|
||||
|
||||
started = time.monotonic()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png'
|
||||
fixture = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
client.call('POST', path, 404, actor=eve, raw=fixture, headers={'Content-Type': 'image/png'})
|
||||
client.call('POST', path, 415, actor=alice, raw=fixture, headers={'Content-Type': 'image/jpeg'})
|
||||
client.call('POST', path, 415, actor=alice, raw=b'not a png', headers={'Content-Type': 'image/png'})
|
||||
client.call('POST', path, 413, actor=alice, raw=b'',
|
||||
headers={'Content-Type': 'image/png', 'Content-Length': '10485761'})
|
||||
report('upload_validation', started, {'id': None}, statuses=[404, 415, 415, 413])
|
||||
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'broker')
|
||||
try:
|
||||
attachment, content = upload()
|
||||
row = job(attachment)
|
||||
check(meta(attachment)['status'] == 'queued', 'upload did not remain queued')
|
||||
check(sql(f"SELECT count(*) FROM job_outbox WHERE job_id='{row['id']}'") == '1',
|
||||
'lost intent during real broker outage')
|
||||
wait(lambda: service_health('publisher') == ['unhealthy']
|
||||
and service_health('worker') == ['unhealthy'] * len(worker_count),
|
||||
'AMQP outage reflected in publisher and worker health', timeout=45)
|
||||
finally:
|
||||
compose('start', 'broker')
|
||||
verify(attachment, content)
|
||||
wait(lambda: service_health('publisher') == ['healthy']
|
||||
and service_health('worker') == ['healthy'] * len(worker_count),
|
||||
'publisher and all workers became healthy again', timeout=45)
|
||||
report('broker_unavailable', started, attachment, attempt=1, pipeline_health_recovered=True)
|
||||
|
||||
for point in ('before_publish', 'after_confirm', 'before_s3', 'after_s3', 'after_commit'):
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'publisher')
|
||||
if point in ('before_publish', 'after_confirm'):
|
||||
compose('stop', '-t', '1', 'worker')
|
||||
attachment, content = upload()
|
||||
arm(attachment, point, 'crash')
|
||||
compose('start', 'publisher')
|
||||
hit(attachment, point)
|
||||
if point in ('before_publish', 'after_confirm'):
|
||||
job_id = job(attachment)['id']
|
||||
wait(lambda: events(job_id, 'broker_confirmed'), 'outbox drained after publisher crash')
|
||||
compose('start', 'worker')
|
||||
if point in ('before_s3', 'after_s3'):
|
||||
keys = objects(attachment, 1)
|
||||
check(len(keys) == (0 if point == 'before_s3' else 4), 'wrong S3 effects at crash')
|
||||
check(job(attachment)['state'] == 'processing', 'manifest was already committed at crash')
|
||||
row = verify(attachment, content)
|
||||
wanted = {'before_s3': 2, 'after_s3': 2}.get(point, 1)
|
||||
check(row['attempt'] == wanted, f'wrong attempt after {point}')
|
||||
crash_logs = [json.loads(line[line.index('{'):]) for line in
|
||||
compose('logs', '--no-color', 'publisher', 'worker').splitlines()
|
||||
if '"event":"pipeline_fault"' in line]
|
||||
check(any(item['point'] == point and item['action'] == 'crash' and item['job_id'] == row['id']
|
||||
for item in crash_logs), 'missing crash log')
|
||||
if point in ('after_commit', 'after_confirm'):
|
||||
wait(lambda: events(row['id'], 'delivery_ignored'), 'duplicate delivery ignored')
|
||||
report(point, started, attachment, attempt=row['attempt'], published=1)
|
||||
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'publisher')
|
||||
attachment, content = upload()
|
||||
arm(attachment, 'before_s3', 'pause')
|
||||
compose('start', 'publisher')
|
||||
hit(attachment, 'before_s3')
|
||||
initial = job(attachment)
|
||||
operator('redeliver', initial['id'])
|
||||
wait(lambda: events(initial['id'], 'delivery_ignored'), 'parallel duplicate rejected')
|
||||
check(events(initial['id'], 'claimed') == 1, 'duplicate obtained live lease')
|
||||
current = verify(attachment, content)
|
||||
check(current['fence'] > initial['fence'] and current['attempt'] == 2, 'lease was not reclaimed')
|
||||
hit(attachment, 'before_s3', release=True)
|
||||
wait(lambda: events(initial['id'], 'fence_rejected'), 'old attempt fenced')
|
||||
ignored = events(initial['id'], 'delivery_ignored')
|
||||
operator('redeliver', initial['id'])
|
||||
wait(lambda: events(initial['id'], 'delivery_ignored') > ignored, 'completed duplicate rejected')
|
||||
check(verify(attachment, content)['manifest'] == current['manifest'], 'duplicate changed the manifest')
|
||||
report('duplicate_and_fencing', started, attachment, fence=current['fence'], attempt=current['attempt'])
|
||||
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'publisher')
|
||||
attachment, content = upload()
|
||||
arm(attachment, 'after_s3', 'pause')
|
||||
compose('start', 'publisher')
|
||||
hit(attachment, 'after_s3')
|
||||
operator('reprocess', attachment['id'], '2')
|
||||
second = verify(attachment, content, 2)
|
||||
hit(attachment, 'after_s3', release=True)
|
||||
old = job(attachment)
|
||||
wait(lambda: job(attachment)['state'] == 'superseded' or events(old['id'], 'fence_rejected'),
|
||||
'v1 completed after v2 without publication')
|
||||
ignored = events(old['id'], 'delivery_ignored')
|
||||
operator('redeliver', old['id'])
|
||||
wait(lambda: events(old['id'], 'delivery_ignored') > ignored, 'reordered v1 redelivery ignored')
|
||||
check(verify(attachment, content, 2)['manifest'] == second['manifest'], 'v1 changed v2')
|
||||
check(events(old['id'], 'published') == 0, 'v1 published despite newer version')
|
||||
report('reorder_in_flight', started, attachment, active_version=2)
|
||||
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'publisher')
|
||||
attachment, content = upload()
|
||||
old = job(attachment)
|
||||
second = operator('reprocess', attachment['id'], '2')
|
||||
operator('redeliver', second['job_id'])
|
||||
verify(attachment, content, 2)
|
||||
check(job(attachment)['state'] == 'queued', 'v1 must still be queued before late delivery')
|
||||
operator('redeliver', old['id'])
|
||||
wait(lambda: events(old['id'], 'superseded') == 1, 'late v1 delivery superseded')
|
||||
check(events(old['id'], 'claimed') == 0, 'late v1 obtained a lease')
|
||||
compose('start', 'publisher')
|
||||
check(not objects(attachment, 1), 'late v1 produced S3 side effects')
|
||||
verify(attachment, content, 2)
|
||||
report('late_old_delivery', started, attachment, active_version=2)
|
||||
|
||||
started = time.monotonic()
|
||||
attachment, content = upload()
|
||||
first = verify(attachment, content)
|
||||
compose('stop', '-t', '1', 'publisher')
|
||||
try:
|
||||
operator('reprocess', attachment['id'], '2')
|
||||
check(meta(attachment)['status'] == 'ready', 'reprocessing hid the published version')
|
||||
visible = client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content?variant=thumbnail',
|
||||
actor=bob)['bytes']
|
||||
check(hashlib.sha256(visible).hexdigest() == first['manifest']['thumbnail']['sha256'],
|
||||
'published version changed before v2 commit')
|
||||
finally:
|
||||
compose('start', 'publisher')
|
||||
second = verify(attachment, content, 2)
|
||||
for name in ('thumbnail', 'crop', 'optimized'):
|
||||
check(first['manifest'][name]['sha256'] != second['manifest'][name]['sha256'], 'v2 did not change bytes')
|
||||
operator('redeliver', first['id'])
|
||||
wait(lambda: events(first['id'], 'delivery_ignored'), 'duplicate of published v1')
|
||||
check(verify(attachment, content, 2)['manifest'] == second['manifest'], 'old duplicate changed v2')
|
||||
report('atomic_version_switch', started, attachment, active_version=2)
|
||||
|
||||
for action in ('temporary', 'permanent'):
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'publisher')
|
||||
attachment, content = upload()
|
||||
arm(attachment, 'before_s3', action)
|
||||
compose('start', 'publisher')
|
||||
initial = job(attachment)
|
||||
if action == 'permanent':
|
||||
wait(lambda: job(attachment)['state'] == 'failed', 'permanent failure')
|
||||
check(meta(attachment)['error_code'] == 'invalid_image', 'unsafe or wrong error code')
|
||||
path = '/api/v1/attachments/' + attachment['id'] + '/content'
|
||||
client.call('GET', path, 409, actor=bob)
|
||||
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [attachment['id']]},
|
||||
headers={'Idempotency-Key': attachment['id']})
|
||||
check(sql(f"SELECT error_code FROM job_dead_letters WHERE job_id='{initial['id']}'") == 'invalid_image',
|
||||
'missing DLQ entry')
|
||||
operator('replay', initial['id'])
|
||||
check(sql(f"SELECT replayed_at IS NOT NULL FROM job_dead_letters WHERE job_id='{initial['id']}'") == 't',
|
||||
'missing replay audit')
|
||||
completed = verify(attachment, content)
|
||||
check(completed['attempt'] == 2, 'expected two attempts')
|
||||
if action == 'temporary':
|
||||
check(events(initial['id'], 'retry_scheduled') == 1, 'missing transient retry')
|
||||
report(action + '_error', started, attachment, attempt=2)
|
||||
|
||||
stable_attachment, stable_content = attachment, content
|
||||
stable_manifest = completed['manifest']
|
||||
started = time.monotonic()
|
||||
compose('stop', '-t', '1', 'worker')
|
||||
attachment, content = upload()
|
||||
row = job(attachment)
|
||||
wait(lambda: events(row['id'], 'broker_confirmed'), 'durable queue entry')
|
||||
check(meta(attachment)['status'] == 'queued', 'worker processed despite stop')
|
||||
client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', 409, actor=bob)
|
||||
message = client.message(alice, chat, '', attachments=[attachment['id']])['json']
|
||||
compose('restart', 'postgres', 's3', 'broker', 'api-a', 'api-b', 'lb', 'publisher', 'recovery')
|
||||
wait(lambda: health(client), 'HAProxy readiness')
|
||||
check(not compose('ps', '-q', 'worker'), 'restart brought workers back too early')
|
||||
check(meta(attachment)['status'] == 'queued', 'confirmed job changed before worker restart')
|
||||
client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', 409, actor=bob)
|
||||
compose('start', 'worker')
|
||||
verify(attachment, content)
|
||||
page = client.call('GET', f"/api/v1/chats/{chat['id']}/messages", actor=bob,
|
||||
schema='MessagePage')['json']
|
||||
check(any(item['id'] == message['id'] and attachment['id'] in item['attachment_ids']
|
||||
for item in page['items']), 'attachment link did not survive restart')
|
||||
wait(lambda: sql(f"SELECT staging_key IS NULL FROM attachments WHERE id='{attachment['id']}'") == 't',
|
||||
'recovery cleaned staging after publication')
|
||||
wait(lambda: service_health('recovery') == ['healthy'], 'recovery health after restart')
|
||||
check(verify(stable_attachment, stable_content)['manifest'] == stable_manifest,
|
||||
'published attachment changed on restart')
|
||||
check(job(attachment)['attempt'] == 1, 'broker restart lost the original delivery')
|
||||
report('restart_with_queued_attachment', started, attachment, attempt=1,
|
||||
message_link_preserved=True, staging_cleaned=True)
|
||||
|
||||
|
||||
def health(client):
|
||||
try:
|
||||
client.call('GET', '/health/ready')
|
||||
except (OSError, AssertionError):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--base-url', default='https://localhost:8443')
|
||||
parser.add_argument('--disposable', action='store_true', required=True,
|
||||
help='confirm this is an isolated test project')
|
||||
args = parser.parse_args()
|
||||
if (not os.environ.get('COMPOSE_PROJECT_NAME', '').startswith('lab7-grade4-')
|
||||
or 'grade4.compose.yaml' not in os.environ.get('COMPOSE_FILE', '')
|
||||
or args.base_url.rstrip('/') != 'https://localhost:28443'):
|
||||
parser.error('Use the isolated Compose project documented in REPORT.md')
|
||||
try:
|
||||
try:
|
||||
experiments(Client(args.base_url))
|
||||
finally:
|
||||
sql('REVOKE SELECT, UPDATE(hit_at) ON pipeline_faults FROM publisher, worker')
|
||||
except (AssertionError, OSError, ValueError, subprocess.SubprocessError) as exc:
|
||||
# Subprocess output can include internal details. Keep the public summary short.
|
||||
print('FAIL:', str(exc), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/bin/sh
|
||||
# Use an isolated loopback network and tmpfs storage. No Compose services or volumes.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
root=$PWD
|
||||
app_image=${RECOVERY_TEST_APP_IMAGE:-mtusi2026lab7-app:local}
|
||||
pg_image=${RECOVERY_TEST_PG_IMAGE:-postgres:16.16-bookworm@sha256:cd0e9518bda5f2ea667ff84d22795d089720c883f288e215d97ce57437e8ef37}
|
||||
s3_image=bitnamilegacy/minio:2025.7.23-debian-12-r5@sha256:6dabb4a2088c9a79908de3bc05f4586c23ad2182c8908e7e3acbf61c1467fb20
|
||||
work=$(mktemp -d)
|
||||
work=$(cd "$work" && pwd -P)
|
||||
pg=
|
||||
s3=
|
||||
cleanup() {
|
||||
if [ -n "$s3" ]; then docker stop "$s3" >/dev/null 2>&1 || :; fi
|
||||
if [ -n "$pg" ]; then docker stop "$pg" >/dev/null 2>&1 || :; fi
|
||||
rm -f "$work"/ca.key "$work"/ca.crt "$work"/ca.srl "$work"/server.csr \
|
||||
"$work"/server.ext "$work"/certs/private.key "$work"/certs/public.crt
|
||||
rmdir "$work"/certs "$work"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
mkdir "$work/certs"
|
||||
openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj '/CN=Recovery test CA' \
|
||||
-addext 'keyUsage=critical,keyCertSign,cRLSign' -keyout "$work/ca.key" -out "$work/ca.crt" >/dev/null 2>&1
|
||||
openssl req -new -newkey rsa:2048 -nodes -subj '/CN=localhost' \
|
||||
-keyout "$work/certs/private.key" -out "$work/server.csr" >/dev/null 2>&1
|
||||
printf '%s\n' 'subjectAltName=IP:127.0.0.1' 'extendedKeyUsage=serverAuth' > "$work/server.ext"
|
||||
openssl x509 -req -in "$work/server.csr" -CA "$work/ca.crt" -CAkey "$work/ca.key" \
|
||||
-CAcreateserial -days 1 -extfile "$work/server.ext" -out "$work/certs/public.crt" >/dev/null 2>&1
|
||||
|
||||
pg=$(docker run --rm -d --network none --tmpfs /var/lib/postgresql/data \
|
||||
-e POSTGRES_DB=recovery_test -e POSTGRES_HOST_AUTH_METHOD=trust "$pg_image")
|
||||
for attempt in $(seq 1 30); do
|
||||
if docker exec "$pg" pg_isready -h 127.0.0.1 -U postgres -d recovery_test >/dev/null 2>&1; then break; fi
|
||||
test "$attempt" -lt 30
|
||||
sleep 1
|
||||
done
|
||||
|
||||
# Scratch MinIO runs as root solely to read the host-owned disposable TLS key.
|
||||
s3=$(docker run --rm -d --network "container:$pg" --user 0:0 \
|
||||
--tmpfs /data --tmpfs /certs --tmpfs /bitnami/minio/data \
|
||||
--mount "type=bind,src=$work,dst=/fixture,readonly" \
|
||||
--mount "type=bind,src=$root/infra/minio,dst=/policy,readonly" \
|
||||
-e MINIO_ROOT_USER=fixture-admin -e MINIO_ROOT_PASSWORD=fixture-admin-password \
|
||||
--entrypoint /opt/bitnami/minio/bin/minio "$s3_image" server /data --certs-dir /fixture/certs)
|
||||
for attempt in $(seq 1 30); do
|
||||
if docker exec "$s3" curl -fsS --cacert /fixture/ca.crt https://127.0.0.1:9000/minio/health/ready >/dev/null 2>&1; then break; fi
|
||||
test "$attempt" -lt 30
|
||||
sleep 1
|
||||
done
|
||||
docker exec "$s3" sh -ec '
|
||||
export MC_CONFIG_DIR=/tmp/recovery-test-mc
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /fixture/ca.crt "$MC_CONFIG_DIR/certs/CAs/fixture.crt"
|
||||
mc alias set fixture https://127.0.0.1:9000 fixture-admin fixture-admin-password >/dev/null
|
||||
mc mb fixture/messenger-attachments >/dev/null
|
||||
mc admin user add fixture lab-recovery fixture-recovery-password >/dev/null
|
||||
mc admin policy create fixture lab-recovery /policy/recovery.json >/dev/null
|
||||
mc admin policy attach fixture lab-recovery --user lab-recovery >/dev/null
|
||||
'
|
||||
docker run --rm --network "container:$pg" \
|
||||
--mount "type=bind,src=$root,dst=/workspace,readonly" \
|
||||
--mount "type=bind,src=$work/ca.crt,dst=/fixture-ca.crt,readonly" \
|
||||
-w /workspace -e PYTHONDONTWRITEBYTECODE=1 \
|
||||
-e 'RECOVERY_TEST_DSN=host=127.0.0.1 dbname=recovery_test user=postgres' \
|
||||
-e RECOVERY_TEST_S3=https://127.0.0.1:9000 -e RECOVERY_TEST_CA=/fixture-ca.crt \
|
||||
-e RECOVERY_TEST_ADMIN_USER=fixture-admin -e RECOVERY_TEST_ADMIN_PASSWORD=fixture-admin-password \
|
||||
-e RECOVERY_TEST_SCOPED_USER=lab-recovery -e RECOVERY_TEST_SCOPED_PASSWORD=fixture-recovery-password \
|
||||
--entrypoint python "$app_image" -m unittest discover -s student-tests -p 'test_recovery_*.py' -v
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check image encoders, geometry, EXIF orientation and alpha on local fixtures."""
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import zlib
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
FIXTURE = ROOT / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def render(directory, version):
|
||||
subprocess.run([sys.executable, '-m', 'src.render_image', str(directory), str(version)],
|
||||
cwd=ROOT, check=True)
|
||||
outputs = {}
|
||||
for variant, format_name in [('thumbnail', 'JPEG'), ('crop', 'JPEG'), ('optimized', 'WEBP')]:
|
||||
with Image.open(directory / variant) as image:
|
||||
image.load()
|
||||
assert image.format == format_name
|
||||
assert not image.getexif()
|
||||
outputs[variant] = (image.size, (directory / variant).read_bytes())
|
||||
return outputs
|
||||
|
||||
|
||||
def validate(path, mime):
|
||||
return subprocess.run([sys.executable, '-m', 'src.image_check', str(path), mime],
|
||||
cwd=ROOT, timeout=10, check=False).returncode
|
||||
|
||||
|
||||
def main():
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
directory = Path(temp)
|
||||
original = directory / 'original'
|
||||
data = FIXTURE.read_bytes()
|
||||
original.write_bytes(data)
|
||||
assert validate(original, 'image/png') == 0
|
||||
assert validate(original, 'image/jpeg') == 15
|
||||
original.write_bytes(b'corrupt')
|
||||
assert validate(original, 'image/png') == 15
|
||||
Image.new('RGB', (1, 1)).save(original, format='TIFF')
|
||||
assert validate(original, 'image/png') == 15
|
||||
# Rewrite only IHDR, with a valid CRC, to exercise the pre-decode limit.
|
||||
header = data[12:16] + struct.pack('>II', 10000, 10000) + data[24:29]
|
||||
original.write_bytes(data[:12] + header + struct.pack('>I', zlib.crc32(header)) + data[33:])
|
||||
assert validate(original, 'image/png') == 13
|
||||
original.write_bytes(data)
|
||||
print('PASS: PNG validation, MIME mismatch, corrupt input and pixel cap before decoding')
|
||||
first = render(directory, 1)
|
||||
assert first == render(directory, 1)
|
||||
second = render(directory, 2)
|
||||
assert first.keys() == second.keys()
|
||||
for variant, shape in [('thumbnail', (256, 160)), ('crop', (128, 128)), ('optimized', (320, 200))]:
|
||||
assert first[variant][0] == second[variant][0] == shape
|
||||
assert first[variant][1] != second[variant][1]
|
||||
assert original.read_bytes() == data
|
||||
print('PASS: fixture geometry, original preserved, deterministic v1, different v2')
|
||||
transparent = Image.new('RGBA', (7, 3), (255, 0, 0, 0))
|
||||
transparent.save(original, format='PNG')
|
||||
alpha = render(directory, 1)
|
||||
assert alpha['thumbnail'][0] == (7, 3)
|
||||
with Image.open(directory / 'thumbnail') as thumbnail:
|
||||
assert thumbnail.getpixel((0, 0)) == (255, 255, 255)
|
||||
rotated = Image.new('RGB', (17, 31), 'red')
|
||||
exif = rotated.getexif()
|
||||
exif[274] = 6
|
||||
rotated.save(original, format='JPEG', exif=exif)
|
||||
assert render(directory, 1)['thumbnail'][0] == (31, 17)
|
||||
print('PASS: alpha on white, no upscaling, EXIF orientation applied and metadata removed')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,70 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
|
||||
|
||||
|
||||
def load(name):
|
||||
spec = importlib.util.spec_from_file_location(name, SCRIPTS / (name + ".py"))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
with patch.object(sys, "path", [str(SCRIPTS), *sys.path]):
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
db = load("rotate-db")
|
||||
hardening = load("check-hardening")
|
||||
|
||||
|
||||
class RotationSafetyTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.old = db.conninfo("api_blue", "fixture")
|
||||
self.new = db.conninfo("api_green", "replacement")
|
||||
self.document = {"metadata": {"version": 2}, "data": {"database_url": self.old, "extra": "fixture"}}
|
||||
self.read = self.enterContext(patch.object(db, "read_generation",
|
||||
return_value=(self.document, self.old, "api_blue")))
|
||||
self.probe = self.enterContext(patch.object(db, "db_probe", side_effect=["api_blue", "api_green"]))
|
||||
self.sql = self.enterContext(patch.object(db, "sql"))
|
||||
self.request = self.enterContext(patch.object(db, "request"))
|
||||
self.enterContext(patch.object(db.secrets, "token_hex", return_value="replacement"))
|
||||
|
||||
def test_timeout_during_cas_preserves_both_login_passwords(self):
|
||||
self.request.side_effect = TimeoutError()
|
||||
with self.assertRaisesRegex(RuntimeError, "CAS outcome uncertain"):
|
||||
db.rotate("synthetic token")
|
||||
self.assertIn("ALTER ROLE api_green LOGIN", self.sql.call_args.args[0])
|
||||
self.sql.assert_called_once()
|
||||
self.assertEqual(self.request.call_args.args[1]["options"]["cas"], 2)
|
||||
self.assertEqual(self.request.call_args.args[1]["data"]["extra"], "fixture")
|
||||
|
||||
def test_replica_convergence_failure_never_retires_old_password(self):
|
||||
current = {"metadata": {"version": 3}, "data": {"database_url": self.new}}
|
||||
self.read.side_effect = [(self.document, self.old, "api_blue"), (current, self.new, "api_green")]
|
||||
with patch.object(db, "await_active", side_effect=RuntimeError("replica unavailable")):
|
||||
with self.assertRaisesRegex(RuntimeError, "replica unavailable"):
|
||||
db.rotate("synthetic token")
|
||||
self.sql.assert_called_once()
|
||||
|
||||
def test_cas_generation_change_during_retire_preserves_other_password(self):
|
||||
self.sql.return_value = "0"
|
||||
with patch.object(db, "await_active"):
|
||||
with self.assertRaisesRegex(RuntimeError, "generation changed"):
|
||||
db.retire("synthetic token", {"metadata": {"version": 1}}, self.old, "api_blue")
|
||||
self.assertTrue(all("ALTER" not in item.args[0] for item in self.sql.call_args_list))
|
||||
|
||||
|
||||
class HardeningTest(unittest.TestCase):
|
||||
def test_flags_root_and_docker_socket(self):
|
||||
service = {"image": "example", "read_only": True, "cap_drop": ["ALL"],
|
||||
"security_opt": ["no-new-privileges:true"], "mem_limit": 1, "cpus": 1, "pids_limit": 1,
|
||||
"volumes": [{"source": "/var/run/docker.sock"}]}
|
||||
failures = hardening.check({"services": {"worker": service}}, lambda _: "0")
|
||||
self.assertTrue(any("Docker socket" in item for item in failures))
|
||||
self.assertTrue(any("root" in item for item in failures))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Integration tests for a disposable database and bucket, see recovery-test.sh."""
|
||||
from contextlib import contextmanager
|
||||
import hashlib
|
||||
import multiprocessing
|
||||
import os
|
||||
from pathlib import Path
|
||||
from threading import Event, Thread
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from uuid import uuid4
|
||||
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
import psycopg
|
||||
from psycopg.conninfo import conninfo_to_dict
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from src import jobs, recovery, worker
|
||||
|
||||
DSN = os.getenv("RECOVERY_TEST_DSN")
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BUCKET = "messenger-attachments"
|
||||
DATA = b"synthetic attachment"
|
||||
|
||||
|
||||
def reclaim(barrier, queue):
|
||||
barrier.wait(timeout=10)
|
||||
queue.put(jobs.recover_one())
|
||||
|
||||
|
||||
def collect_staging(barrier):
|
||||
barrier.wait(timeout=10)
|
||||
recovery.cleanup()
|
||||
|
||||
|
||||
@unittest.skipUnless(DSN, "requires the disposable recovery-test.sh stand")
|
||||
class RecoveryTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if conninfo_to_dict(DSN).get("dbname") != "recovery_test":
|
||||
raise ValueError("The integration database must be named recovery_test")
|
||||
with psycopg.connect(DSN) as conn:
|
||||
conn.execute("CREATE ROLE api_runtime; CREATE ROLE publisher; CREATE ROLE worker; "
|
||||
"CREATE ROLE recovery; CREATE ROLE ops")
|
||||
for path in sorted((ROOT / "db/migrations").glob("*.sql")):
|
||||
conn.execute(path.read_text())
|
||||
cls.manage = cls.client("RECOVERY_TEST_ADMIN")
|
||||
cls.scoped = cls.client("RECOVERY_TEST_SCOPED")
|
||||
|
||||
@staticmethod
|
||||
def client(prefix):
|
||||
return boto3.client("s3", endpoint_url=os.environ["RECOVERY_TEST_S3"],
|
||||
verify=os.environ["RECOVERY_TEST_CA"], region_name="us-east-1",
|
||||
aws_access_key_id=os.environ[prefix + "_USER"],
|
||||
aws_secret_access_key=os.environ[prefix + "_PASSWORD"])
|
||||
|
||||
@contextmanager
|
||||
def connection(self, role=None):
|
||||
with psycopg.connect(DSN, row_factory=dict_row) as conn:
|
||||
if role:
|
||||
conn.execute({"recovery": "SET LOCAL ROLE recovery", "worker": "SET LOCAL ROLE worker"}[role])
|
||||
yield conn
|
||||
|
||||
def setUp(self):
|
||||
for module in (jobs, recovery):
|
||||
self.enterContext(patch.object(module, "get_connection", lambda: self.connection("recovery")))
|
||||
self.enterContext(patch.object(worker, "get_connection", lambda: self.connection("worker")))
|
||||
self.enterContext(patch.object(recovery, "s3", self.scoped))
|
||||
self.enterContext(patch.object(worker, "s3", self.manage))
|
||||
for obj in self.manage.list_objects_v2(Bucket=BUCKET).get("Contents", []):
|
||||
self.manage.delete_object(Bucket=BUCKET, Key=obj["Key"])
|
||||
with self.connection() as conn:
|
||||
conn.execute("TRUNCATE users CASCADE")
|
||||
self.owner, self.chat = uuid4(), uuid4()
|
||||
conn.execute("INSERT INTO users (id,username,display_name,password_hash)"
|
||||
" VALUES (%s,'fixture','Fixture','unused')", (self.owner,))
|
||||
conn.execute("INSERT INTO chats (id,title,created_by) VALUES (%s,'Fixture',%s)",
|
||||
(self.chat, self.owner))
|
||||
|
||||
def attachment(self, status="queued", *, upload=True):
|
||||
aid = uuid4()
|
||||
key = f"staging/{aid}"
|
||||
if upload:
|
||||
self.manage.put_object(Bucket=BUCKET, Key=key, Body=DATA)
|
||||
checksum = hashlib.sha256(DATA).hexdigest()
|
||||
with self.connection() as conn:
|
||||
conn.execute("""
|
||||
INSERT INTO attachments (id,chat_id,owner_id,filename,object_key,size_bytes,
|
||||
content_type,sha256,staging_key,status,error_code,updated_at)
|
||||
VALUES (%s,%s,%s,'fixture.png',%s,%s,'image/png',%s,%s,%s,%s,now()-interval '2 days')
|
||||
""", (aid, self.chat, self.owner, key, len(DATA), checksum, key, status,
|
||||
"fixture_error" if status == "failed" else None))
|
||||
return aid, key
|
||||
|
||||
def staging(self, aid):
|
||||
with self.connection() as conn:
|
||||
return conn.execute("SELECT staging_key FROM attachments WHERE id=%s", (aid,)).fetchone()["staging_key"]
|
||||
|
||||
def exists(self, key):
|
||||
return any(obj["Key"] == key for obj in self.manage.list_objects_v2(
|
||||
Bucket=BUCKET, Prefix=key).get("Contents", []))
|
||||
|
||||
def test_two_processes_reschedule_one_expired_job_once(self):
|
||||
aid, _ = self.attachment()
|
||||
with self.connection() as conn:
|
||||
job = conn.execute("""
|
||||
INSERT INTO image_jobs (attachment_id,pipeline_version,state,fence,lease_until)
|
||||
VALUES (%s,1,'processing',3,now()-interval '1 second') RETURNING *
|
||||
""", (aid,)).fetchone()
|
||||
ctx = multiprocessing.get_context("fork")
|
||||
barrier, queue = ctx.Barrier(2), ctx.Queue()
|
||||
processes = [ctx.Process(target=reclaim, args=(barrier, queue)) for _ in range(2)]
|
||||
for process in processes:
|
||||
process.start()
|
||||
self.assertEqual(sorted(queue.get(timeout=15) for _ in processes), [False, True])
|
||||
for process in processes:
|
||||
process.join(10)
|
||||
self.assertEqual(process.exitcode, 0)
|
||||
with self.connection() as conn:
|
||||
current = conn.execute("SELECT state,attempt,failures,lease_until FROM image_jobs WHERE id=%s",
|
||||
(job["id"],)).fetchone()
|
||||
self.assertEqual(current, {"state": "queued", "attempt": 2, "failures": 1, "lease_until": None})
|
||||
self.assertEqual(conn.execute("SELECT count(*) AS n FROM job_outbox WHERE job_id=%s",
|
||||
(job["id"],)).fetchone()["n"], 1)
|
||||
self.assertEqual(conn.execute(
|
||||
"SELECT count(*) AS n FROM job_events WHERE event='retry_scheduled'"
|
||||
).fetchone()["n"], 1)
|
||||
self.assertEqual(jobs.fail(job, "late worker"), "ignored")
|
||||
|
||||
def test_cleanup_keeps_queued_and_recent_orphan_and_handles_missing(self):
|
||||
queued, queued_key = self.attachment()
|
||||
missing, _ = self.attachment("failed", upload=False)
|
||||
failed, failed_key = self.attachment("failed")
|
||||
recent = "staging/recent-orphan"
|
||||
self.manage.put_object(Bucket=BUCKET, Key=recent, Body=DATA)
|
||||
recovery.cleanup()
|
||||
recovery.cleanup()
|
||||
self.assertEqual(self.staging(queued), queued_key)
|
||||
self.assertTrue(self.exists(queued_key))
|
||||
self.assertTrue(self.exists(recent))
|
||||
self.assertIsNone(self.staging(missing))
|
||||
self.assertIsNone(self.staging(failed))
|
||||
self.assertFalse(self.exists(failed_key))
|
||||
with patch.object(recovery, "RETENTION", 0):
|
||||
recovery.cleanup()
|
||||
self.assertFalse(self.exists(recent))
|
||||
self.assertTrue(self.exists(queued_key))
|
||||
|
||||
def test_cleanup_respects_worker_read_lock_and_published_original(self):
|
||||
aid, key = self.attachment()
|
||||
result = f"results/{aid}/v1/original/fixture"
|
||||
self.manage.put_object(Bucket=BUCKET, Key=result, Body=DATA)
|
||||
with self.connection() as conn:
|
||||
attachment = conn.execute("SELECT * FROM attachments WHERE id=%s", (aid,)).fetchone()
|
||||
conn.execute("""
|
||||
INSERT INTO image_jobs (attachment_id,pipeline_version,state,manifest)
|
||||
VALUES (%s,1,'ready',jsonb_build_object('original',jsonb_build_object('key',%s::text)))
|
||||
""", (aid, result))
|
||||
conn.execute("UPDATE attachments SET active_version=1,status='ready',object_key=%s WHERE id=%s",
|
||||
(result, aid))
|
||||
at_read, release = Event(), Event()
|
||||
outcome = []
|
||||
|
||||
def buffered_read(source_key):
|
||||
at_read.set()
|
||||
if not release.wait(5):
|
||||
raise TimeoutError("test reader was not released")
|
||||
return DATA
|
||||
|
||||
with patch.object(worker, "read_original", side_effect=buffered_read):
|
||||
reader = Thread(target=lambda: outcome.append(worker.original(attachment)))
|
||||
reader.start()
|
||||
try:
|
||||
self.assertTrue(at_read.wait(5))
|
||||
recovery.cleanup()
|
||||
self.assertEqual(self.staging(aid), key)
|
||||
self.assertTrue(self.exists(key))
|
||||
finally:
|
||||
release.set()
|
||||
reader.join(5)
|
||||
self.assertEqual(outcome, [DATA])
|
||||
recovery.cleanup()
|
||||
self.assertIsNone(self.staging(aid))
|
||||
self.assertFalse(self.exists(key))
|
||||
self.assertTrue(self.exists(result))
|
||||
with self.assertRaises(ClientError):
|
||||
self.scoped.delete_object(Bucket=BUCKET, Key=result)
|
||||
|
||||
def test_delete_timeout_does_not_restore_replayable_pointer(self):
|
||||
aid, key = self.attachment("failed")
|
||||
delete = self.scoped.delete_object
|
||||
|
||||
def lose_response(**kwargs):
|
||||
delete(**kwargs)
|
||||
raise TimeoutError("synthetic lost delete response")
|
||||
|
||||
with patch.object(self.scoped, "delete_object", side_effect=lose_response):
|
||||
with self.assertRaises(TimeoutError):
|
||||
recovery.cleanup()
|
||||
self.assertIsNone(self.staging(aid))
|
||||
self.assertFalse(self.exists(key))
|
||||
recovery.cleanup()
|
||||
recovery.cleanup()
|
||||
|
||||
def test_two_cleanup_processes_leave_active_staging_alone(self):
|
||||
queued, queued_key = self.attachment()
|
||||
failed, failed_key = self.attachment("failed")
|
||||
ctx = multiprocessing.get_context("fork")
|
||||
barrier = ctx.Barrier(2)
|
||||
collectors = [ctx.Process(target=collect_staging, args=(barrier,)) for _ in range(2)]
|
||||
for collector in collectors:
|
||||
collector.start()
|
||||
for collector in collectors:
|
||||
collector.join(10)
|
||||
self.assertEqual(collector.exitcode, 0)
|
||||
self.assertEqual(self.staging(queued), queued_key)
|
||||
self.assertTrue(self.exists(queued_key))
|
||||
self.assertIsNone(self.staging(failed))
|
||||
self.assertFalse(self.exists(failed_key))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,149 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
from urllib.error import HTTPError, URLError
|
||||
|
||||
import boto3
|
||||
from botocore.stub import Stubber
|
||||
|
||||
from src import credentials as bao, storage
|
||||
|
||||
|
||||
def response(payload):
|
||||
return io.BytesIO(json.dumps(payload).encode())
|
||||
|
||||
|
||||
def http_error(status):
|
||||
return HTTPError("https://bao.invalid", status, "private diagnostic", {}, io.BytesIO(b"private body"))
|
||||
|
||||
|
||||
class StorageTest(unittest.TestCase):
|
||||
def test_positional_paginator_and_keyword_s3_calls(self):
|
||||
client = boto3.client("s3", region_name="us-east-1",
|
||||
aws_access_key_id="fixture", aws_secret_access_key="fixture")
|
||||
proxy = storage.Storage()
|
||||
key = {"Bucket": "bucket", "Key": "staging/key"}
|
||||
with Stubber(client) as stub, patch.dict(os.environ, TLS_CA_FILE="/test/ca"), \
|
||||
patch.object(storage.boto3, "client", return_value=client) as factory, \
|
||||
patch.object(storage.credentials, "get") as get:
|
||||
get.return_value = {"s3_user": "fixture", "s3_password": "fixture"}
|
||||
stub.add_response("list_objects_v2", {"IsTruncated": True, "NextContinuationToken": "next"},
|
||||
{"Bucket": "bucket", "Prefix": "staging/"})
|
||||
stub.add_response("list_objects_v2", {"IsTruncated": False},
|
||||
{"Bucket": "bucket", "Prefix": "staging/", "ContinuationToken": "next"})
|
||||
paginator = proxy.get_paginator("list_objects_v2")
|
||||
self.assertEqual(len(list(paginator.paginate(Bucket="bucket", Prefix="staging/"))), 2)
|
||||
stub.add_response("put_object", {}, dict(key, Body=b"sample"))
|
||||
self.assertEqual(proxy.put_object(**key, Body=b"sample"), {})
|
||||
stub.add_response("get_object", {"Body": b"sample"}, key)
|
||||
self.assertEqual(proxy.get_object(**key)["Body"], b"sample")
|
||||
stub.add_response("delete_object", {}, key)
|
||||
self.assertEqual(proxy.delete_object(**key), {})
|
||||
factory.assert_called_once()
|
||||
get.return_value = {"s3_user": "fixture", "s3_password": "rotated"}
|
||||
proxy.get_paginator(operation_name="list_objects_v2")
|
||||
self.assertEqual(factory.call_count, 2)
|
||||
stub.assert_no_pending_responses()
|
||||
|
||||
|
||||
class CredentialTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.source = bao.CredentialSource()
|
||||
self.source.opener = Mock()
|
||||
self.source.address = "https://bao.invalid"
|
||||
self.source.scope = self.source.role = "recovery"
|
||||
self.source.max_age = 10
|
||||
self.clock = self.enterContext(patch.object(bao, "monotonic", return_value=100))
|
||||
self.log = self.enterContext(patch.object(bao, "log"))
|
||||
|
||||
def token(self, value="initial"):
|
||||
return response({"auth": {"client_token": value, "lease_duration": 10}})
|
||||
|
||||
def kv(self, version=1):
|
||||
return response({"data": {"data": {"database_url": "fixture-dsn", "s3_user": "lab-recovery",
|
||||
"s3_password": "fixture-password"}, "metadata": {"version": version}}})
|
||||
|
||||
def test_start_loads_only_recovery_scope_before_background_refresh(self):
|
||||
env = {"BAO_ROLE": "recovery", "BAO_ADDR": "https://bao.invalid", "TLS_CA_FILE": "/test/ca"}
|
||||
self.source.opener.open.side_effect = [self.token(), self.kv()]
|
||||
with patch.dict(os.environ, env, clear=True), patch.object(bao, "Thread") as thread, \
|
||||
patch.object(bao.ssl, "create_default_context") as tls, \
|
||||
patch.object(bao, "build_opener", return_value=self.source.opener):
|
||||
self.source.start()
|
||||
self.assertEqual(self.source.get()["s3_user"], "lab-recovery")
|
||||
requests = [item.args[0] for item in self.source.opener.open.call_args_list]
|
||||
self.assertEqual(requests[0].full_url, "https://bao.invalid/v1/auth/cert/login")
|
||||
self.assertEqual(json.loads(requests[0].data), {"name": "recovery"})
|
||||
self.assertEqual(requests[1].full_url, "https://bao.invalid/v1/kv/data/messenger/recovery")
|
||||
tls.return_value.load_cert_chain.assert_called_once_with("/run/identity/bao.crt", "/run/identity/bao.key")
|
||||
thread.return_value.start.assert_called_once()
|
||||
|
||||
def test_token_renewal_refreshes_snapshot_and_login_fallback(self):
|
||||
self.source.opener.open.side_effect = [self.token(), self.kv(), self.token("renewed"), self.kv(2),
|
||||
http_error(403), self.token("new-login"), self.kv(3)]
|
||||
self.source.refresh_once()
|
||||
self.clock.return_value = 106
|
||||
self.source.refresh_once()
|
||||
self.assertEqual(self.source.token, "renewed")
|
||||
self.assertEqual(self.source.get()["version"], 2)
|
||||
self.clock.return_value = 112
|
||||
self.source.refresh_once()
|
||||
self.assertEqual(self.source.token, "new-login")
|
||||
self.assertEqual(self.source.get()["version"], 3)
|
||||
requests = [item.args[0] for item in self.source.opener.open.call_args_list]
|
||||
self.assertTrue(requests[2].full_url.endswith("/auth/token/renew-self"))
|
||||
self.assertIsNone(requests[5].get_header("X-vault-token"))
|
||||
|
||||
def test_unavailable_keeps_snapshot_only_until_deadline(self):
|
||||
self.source.opener.open.side_effect = [self.token(), self.kv(), http_error(503),
|
||||
URLError("private network error")]
|
||||
self.source.refresh_once()
|
||||
self.clock.return_value = 105
|
||||
self.source.refresh_once()
|
||||
self.assertEqual(self.source.get()["version"], 1)
|
||||
self.clock.return_value = 110
|
||||
self.source.refresh_once()
|
||||
with self.assertRaises(bao.CredentialsUnavailable):
|
||||
self.source.get()
|
||||
self.assertEqual([call.kwargs["reason"] for call in self.log.call_args_list],
|
||||
["unavailable", "unavailable"])
|
||||
|
||||
def test_bad_certificate_is_diagnosed_without_certificate_details(self):
|
||||
self.source.opener.open.side_effect = URLError(ssl.SSLCertVerificationError("private cert details"))
|
||||
self.source.refresh_once()
|
||||
with self.assertRaises(bao.CredentialsUnavailable):
|
||||
self.source.get()
|
||||
self.assertEqual(self.log.call_args.kwargs["reason"], "tls_error")
|
||||
self.assertNotIn("private", str(self.log.call_args))
|
||||
|
||||
def test_server_rejects_certificate_login(self):
|
||||
self.source.opener.open.side_effect = http_error(400)
|
||||
self.source.refresh_once()
|
||||
with self.assertRaises(bao.CredentialsUnavailable):
|
||||
self.source.get()
|
||||
self.assertEqual(self.log.call_args.kwargs["operation"], "login")
|
||||
self.assertEqual(self.log.call_args.kwargs["reason"], "certificate_auth_rejected")
|
||||
|
||||
def test_forbidden_or_missing_kv_invalidates_previous_snapshot(self):
|
||||
for status, reason in ((403, "forbidden"), (404, "kv_missing")):
|
||||
with self.subTest(status=status):
|
||||
self.source.token = None
|
||||
self.source.opener.open.side_effect = [self.token(), self.kv(), http_error(status)]
|
||||
self.source.refresh_once()
|
||||
self.source.refresh_once()
|
||||
with self.assertRaises(bao.CredentialsUnavailable):
|
||||
self.source.get()
|
||||
self.assertEqual(self.log.call_args.kwargs["reason"], reason)
|
||||
self.assertNotIn("private", str(self.log.call_args))
|
||||
|
||||
def test_recovery_cannot_configure_another_services_scope(self):
|
||||
with patch.dict(os.environ, {"BAO_ROLE": "recovery", "BAO_SCOPE": "api"}, clear=True):
|
||||
with self.assertRaisesRegex(ValueError, "role/scope"):
|
||||
self.source.start()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,271 @@
|
||||
"""Black-box TLS and AMQP qualification in the disposable operator probe profile."""
|
||||
import argparse
|
||||
import base64
|
||||
import http.client
|
||||
import json
|
||||
import socket
|
||||
import ssl
|
||||
from time import time_ns
|
||||
from pathlib import Path
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
import pika
|
||||
import psycopg
|
||||
from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest
|
||||
|
||||
PKI = Path("/probe")
|
||||
CA = "/run/trust/ca.crt"
|
||||
|
||||
|
||||
def context(identity=None):
|
||||
result = ssl.create_default_context(cafile=CA)
|
||||
if identity and identity.endswith(".pem"):
|
||||
result.load_cert_chain(str(PKI / identity))
|
||||
elif identity:
|
||||
result.load_cert_chain(str(PKI / (identity + ".crt")), str(PKI / (identity + ".key")))
|
||||
return result
|
||||
|
||||
|
||||
def probe(host, port, identity, path="/health/live", method="GET", body=None, headers=None):
|
||||
client = http.client.HTTPSConnection(host, port, context=context(identity), timeout=3)
|
||||
try:
|
||||
client.request(method, path, body, headers or {"Content-Type": "application/x-protobuf"})
|
||||
response = client.getresponse()
|
||||
response.read()
|
||||
return response.status
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
def deny_tls(operation):
|
||||
try:
|
||||
operation()
|
||||
except ssl.SSLError as exc:
|
||||
assert any(part in str(exc).lower() for part in
|
||||
("alert", "certificate", "eof")), type(exc).__name__
|
||||
except pika.exceptions.ProbableAuthenticationError:
|
||||
pass
|
||||
except pika.exceptions.IncompatibleProtocolError as exc:
|
||||
assert "certificate" in str(exc).lower(), type(exc).__name__
|
||||
else:
|
||||
raise AssertionError("Peer accepted unwanted certificate")
|
||||
|
||||
|
||||
def amqp(identity):
|
||||
peer = pika.ConnectionParameters(host="broker", port=5671, virtual_host="messenger",
|
||||
credentials=pika.credentials.ExternalCredentials(),
|
||||
ssl_options=pika.SSLOptions(context(identity), "broker"), socket_timeout=3,
|
||||
stack_timeout=4, connection_attempts=1)
|
||||
return pika.BlockingConnection(peer)
|
||||
|
||||
|
||||
def leafs(mode):
|
||||
assert probe("lb", 8443, None, "/health/ready") == 200
|
||||
for host in ("api-a-tls", "api-b-tls"):
|
||||
assert probe(host, 8444, "lb/client.pem") == 200
|
||||
if mode == "leaf-revoked":
|
||||
deny_tls(lambda: probe(host, 8444, "rotation/old.pem"))
|
||||
if mode == "matrix":
|
||||
deny_tls(lambda: probe(host, 8444, None))
|
||||
deny_tls(lambda: probe(host, 8444, "probe/foreign"))
|
||||
assert probe(host, 8444, "probe/client") == 403
|
||||
for direct in ("api-a", "api-b"):
|
||||
try:
|
||||
with socket.create_connection((direct, 8080), timeout=2):
|
||||
raise AssertionError("Direct HTTP connection to Uvicorn")
|
||||
except (socket.gaierror, ConnectionRefusedError):
|
||||
pass
|
||||
|
||||
|
||||
def matrix():
|
||||
leafs("matrix")
|
||||
for identity in (None, "probe/foreign", "probe/client"):
|
||||
deny_tls(lambda: amqp(identity))
|
||||
for identity in ("publisher/amqp", "worker/amqp", "ops/amqp"):
|
||||
with amqp(identity):
|
||||
pass
|
||||
with amqp("worker/amqp") as connection:
|
||||
channel = connection.channel()
|
||||
channel.confirm_delivery()
|
||||
try:
|
||||
channel.basic_publish("attachments", "attachment.process.v1", b"{}", mandatory=True)
|
||||
except pika.exceptions.ChannelClosedByBroker as exc:
|
||||
assert exc.reply_code == 403
|
||||
else:
|
||||
raise AssertionError("Worker was allowed to publish")
|
||||
with amqp("publisher/amqp") as connection:
|
||||
try:
|
||||
connection.channel().basic_get("attachment.process.v1")
|
||||
except pika.exceptions.ChannelClosedByBroker as exc:
|
||||
assert exc.reply_code == 403
|
||||
else:
|
||||
raise AssertionError("Publisher was allowed to consume")
|
||||
def otlp(identity):
|
||||
return probe("otel-collector", 4318, identity, "/v1/traces", "POST", b"")
|
||||
for identity in ("api-a/otel", "api-b/otel", "worker/otel"):
|
||||
assert otlp(identity) == 200
|
||||
assert otlp("probe/client") == 403
|
||||
deny_tls(lambda: otlp(None))
|
||||
deny_tls(lambda: otlp("probe/foreign"))
|
||||
|
||||
|
||||
def bao_call(identity, path, *, token=None, data=None):
|
||||
client = http.client.HTTPSConnection("openbao", 8200, context=context(identity), timeout=3)
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
try:
|
||||
client.request("GET" if data is None else "POST", "/v1/" + path,
|
||||
None if data is None else json.dumps(data), headers)
|
||||
reply = client.getresponse()
|
||||
payload = reply.read()
|
||||
return reply.status, json.loads(payload) if reply.status == 200 else {}
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
def scoped_kv(role, scope):
|
||||
identity = f"{role}/bao"
|
||||
code, login = bao_call(identity, "auth/cert/login", data={"name": role})
|
||||
assert code == 200
|
||||
token = login["auth"]["client_token"]
|
||||
assert 0 < login["auth"]["lease_duration"] <= 60
|
||||
assert bao_call(identity, "auth/token/renew-self", token=token, data={})[0] == 200
|
||||
foreign = "recovery" if scope == "api" else "api"
|
||||
assert bao_call(identity, "kv/data/messenger/" + foreign, token=token)[0] == 403
|
||||
assert bao_call(identity, "sys/policies/acl/probe-denied", token=token,
|
||||
data={"policy": ""})[0] == 403
|
||||
code, own = bao_call(identity, "kv/data/messenger/" + scope, token=token)
|
||||
assert code == 200
|
||||
return own["data"]["data"]
|
||||
|
||||
|
||||
def storage_and_secrets():
|
||||
api = scoped_kv("api-a", "api")
|
||||
assert scoped_kv("api-b", "api") == api
|
||||
worker = scoped_kv("worker", "worker")
|
||||
assert scoped_kv("recovery", "recovery")["s3_user"] == "lab-recovery"
|
||||
for identity in (None, "probe/foreign", "probe/client", "worker/bao"):
|
||||
assert bao_call(identity, "auth/cert/login", data={"name": "api-a"})[0] in (400, 403)
|
||||
|
||||
for info, user in ((api, ("api_blue", "api_green")), (worker, ("worker",))):
|
||||
with psycopg.connect(info["database_url"], connect_timeout=3) as db:
|
||||
actual, tls = db.execute(
|
||||
"SELECT current_user, ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()"
|
||||
).fetchone()
|
||||
assert actual in user and tls
|
||||
try:
|
||||
db.execute("SELECT 1 FROM pg_authid")
|
||||
except psycopg.errors.InsufficientPrivilege:
|
||||
db.rollback()
|
||||
else:
|
||||
raise AssertionError("Application role can read PostgreSQL password verifiers")
|
||||
try:
|
||||
psycopg.connect(info["database_url"], sslmode="disable", connect_timeout=3)
|
||||
except psycopg.OperationalError as exc:
|
||||
assert "rejects connection" in str(exc)
|
||||
else:
|
||||
raise AssertionError("PostgreSQL accepted plaintext")
|
||||
client = boto3.client("s3", endpoint_url="https://s3:9000", region_name="us-east-1",
|
||||
verify=CA, aws_access_key_id=info["s3_user"],
|
||||
aws_secret_access_key=info["s3_password"],
|
||||
config=Config(s3={"addressing_style": "path"}, connect_timeout=2,
|
||||
retries={"total_max_attempts": 1}))
|
||||
try:
|
||||
client.list_buckets()
|
||||
except ClientError as exc:
|
||||
assert exc.response["ResponseMetadata"]["HTTPStatusCode"] == 403
|
||||
else:
|
||||
raise AssertionError("Application identity could enumerate buckets")
|
||||
try:
|
||||
client.get_object(Bucket="messenger-attachments", Key="operators/authorization-probe")
|
||||
except ClientError as exc:
|
||||
assert exc.response["ResponseMetadata"]["HTTPStatusCode"] == 403
|
||||
else:
|
||||
raise AssertionError("Application identity could read an operator prefix")
|
||||
assert probe("s3", 9000, None, "/minio/health/ready") == 200
|
||||
|
||||
|
||||
def telemetry():
|
||||
logs = ExportLogsServiceRequest()
|
||||
resource = logs.resource_logs.add()
|
||||
service = resource.resource.attributes.add()
|
||||
service.key = "service.name"
|
||||
service.value.string_value = "lab7-matrix-probe"
|
||||
record = resource.scope_logs.add().log_records.add()
|
||||
record.time_unix_nano = time_ns()
|
||||
record.body.string_value = "synthetic TLS matrix probe"
|
||||
cases = (
|
||||
("prometheus", 9090, "grafana/client", "/api/v1/status/buildinfo", "GET", None),
|
||||
("loki", 3100, "grafana/client", "/loki/api/v1/labels", "GET", None),
|
||||
("tempo", 3200, "grafana/client", "/api/search", "GET", None),
|
||||
("loki", 3100, "otel/client", "/otlp/v1/logs", "POST", logs.SerializeToString()),
|
||||
("tempo", 4318, "otel/client", "/v1/traces", "POST", b""),
|
||||
)
|
||||
for host, port, identity, path, method, body in cases:
|
||||
status = probe(host, port, identity, path, method, body)
|
||||
assert status in (200, 204), (host, port, path, status)
|
||||
assert probe(host, port, "probe/client", path, method, body) == 403
|
||||
deny_tls(lambda: probe(host, port, None, path, method, body))
|
||||
assert probe("grafana", 3000, None, "/api/health") == 200
|
||||
assert probe("grafana", 3000, None, "/api/datasources") == 401
|
||||
admin = (PKI / "grafana/admin").read_bytes().strip()
|
||||
headers = {"Authorization": "Basic " + base64.b64encode(b"admin:" + admin).decode()}
|
||||
for backend, path in (("prometheus", "/api/v1/status/buildinfo"),
|
||||
("loki", "/loki/api/v1/labels"), ("tempo", "/api/search")):
|
||||
assert probe("grafana", 3000, None, f"/api/datasources/proxy/uid/{backend}{path}",
|
||||
headers=headers) == 200, backend
|
||||
for host, port in (("lb", 8404), ("otel-collector", 9464), ("otel-collector", 8888)):
|
||||
assert probe(host, port, "prometheus/client", "/metrics") == 200, (host, port)
|
||||
assert probe(host, port, "probe/client", "/metrics") == 403, (host, port)
|
||||
deny_tls(lambda: probe(host, port, None, "/metrics"))
|
||||
for host, port in (("otel-collector", 14318), ("prometheus", 19090), ("loki", 13100), ("tempo", 13200)):
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=2):
|
||||
raise AssertionError(f"Reachable local cleartext hop: {host}:{port}")
|
||||
except ConnectionRefusedError:
|
||||
pass
|
||||
|
||||
|
||||
def ingress():
|
||||
with socket.create_connection(("lb", 8443), timeout=3) as peer:
|
||||
try:
|
||||
context().wrap_socket(peer, server_hostname="wrong.invalid")
|
||||
except ssl.SSLCertVerificationError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("Wrong hostname was accepted")
|
||||
for host, port in (("lb", 8443), ("api-a-tls", 8444), ("api-b-tls", 8444),
|
||||
("broker", 5671), ("otel-collector", 4318), ("openbao", 8200), ("s3", 9000),
|
||||
("loki", 3100), ("tempo", 3200), ("prometheus", 9090), ("grafana", 3000)):
|
||||
conn = http.client.HTTPConnection(host, port, timeout=3)
|
||||
try:
|
||||
conn.request("GET", "/health/live")
|
||||
answer = conn.getresponse()
|
||||
except (ConnectionResetError, http.client.RemoteDisconnected):
|
||||
pass
|
||||
except http.client.BadStatusLine as exc:
|
||||
assert exc.line.startswith("\x15\x03"), (host, port)
|
||||
else:
|
||||
assert answer.status == 400, (host, port, answer.status)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("mode", choices=("matrix", "leaf-current", "leaf-revoked", "login-unavailable"))
|
||||
mode = parser.parse_args().mode
|
||||
if mode == "matrix":
|
||||
matrix()
|
||||
ingress()
|
||||
storage_and_secrets()
|
||||
telemetry()
|
||||
elif mode == "login-unavailable":
|
||||
for host in ("api-a-tls", "api-b-tls"):
|
||||
assert probe(host, 8444, "lb/client.pem", "/api/v1/auth/sessions", "POST") == 503
|
||||
else:
|
||||
leafs(mode)
|
||||
print(f"PASS: {mode}")
|
||||
Reference in New Issue
Block a user