Добавил защиту сервисов
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
from scripts import provision as p
|
||||
|
||||
|
||||
def compose(*args, input=None):
|
||||
result=subprocess.run(['docker','compose','--project-name',p.PROJECT,'--env-file','.env',*args],
|
||||
cwd=p.ROOT,input=input,text=True,capture_output=True,encoding='utf-8')
|
||||
if result.returncode:
|
||||
raise RuntimeError('Operator command failed: ' + ' '.join(args[:3]))
|
||||
return result.stdout
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return compose('exec','-T','db','psql','-U','messenger','-d','messenger','-v','ON_ERROR_STOP=1','-At','-f','-',input=statement)
|
||||
|
||||
|
||||
def grants():
|
||||
v=p.values()
|
||||
statement=''
|
||||
for role in ('api','worker','cleanup'):
|
||||
statement+=f"DO $$ BEGIN CREATE ROLE {role} LOGIN; EXCEPTION WHEN duplicate_object THEN NULL; END $$; ALTER ROLE {role} PASSWORD '{v[role+'_db']}';\n"
|
||||
statement+='REVOKE ALL ON SCHEMA public FROM PUBLIC; GRANT USAGE ON SCHEMA public TO api,worker,cleanup;\n'
|
||||
statement+='GRANT SELECT ON ALL TABLES IN SCHEMA public TO api;\n'
|
||||
statement+='GRANT INSERT ON users,chats,chat_members,messages,message_attachments,sessions,idempotency_keys,attachments,attachment_jobs,upload_intents TO api;\n'
|
||||
statement+='GRANT DELETE ON sessions,idempotency_keys,upload_intents TO api; GRANT UPDATE ON upload_intents TO api; GRANT UPDATE(published_at) ON attachment_jobs TO api;\n'
|
||||
statement+='GRANT SELECT ON attachments,attachment_jobs,attachment_variants,schema_migrations TO worker; GRANT INSERT,UPDATE ON attachment_variants TO worker;\n'
|
||||
statement+='GRANT UPDATE(status,error_code,updated_at) ON attachments TO worker; GRANT UPDATE(attempt,next_attempt_at) ON attachment_jobs TO worker;\n'
|
||||
statement+='GRANT SELECT ON attachments,attachment_jobs,upload_intents,schema_migrations TO cleanup; GRANT UPDATE,DELETE ON upload_intents TO cleanup; GRANT UPDATE(status,error_code,updated_at,staging_deleted) ON attachments TO cleanup;\n'
|
||||
sql(statement)
|
||||
print('PASS: separate database roles configured')
|
||||
|
||||
|
||||
def main():
|
||||
action=sys.argv[1]
|
||||
if action=='setup':
|
||||
p.pki();p.configuration()
|
||||
print('Local PKI/configuration ready; operator profile encrypted outside repository')
|
||||
elif action=='bao-bootstrap':
|
||||
deadline=time.monotonic()+90
|
||||
while True:
|
||||
try:
|
||||
p.bao_request('sys/init');break
|
||||
except Exception:
|
||||
if time.monotonic()>deadline:raise RuntimeError('OpenBao TLS startup timeout') from None
|
||||
time.sleep(1)
|
||||
p.bootstrap_bao();print('PASS: OpenBao initialized/unsealed, cert auth and scoped policies configured')
|
||||
elif action=='pki-renew':
|
||||
p.pki(renew=True);p.configuration();state=p.operator_load();state['renew_roles']=True;p.operator_save(state)
|
||||
print('Leaf certificates reissued; CA and application data preserved')
|
||||
elif action=='grants':
|
||||
grants()
|
||||
elif action=='bao-unseal':
|
||||
p.unseal();print('OpenBao unsealed')
|
||||
elif action=='bao-status':
|
||||
status=p.bao_request('sys/seal-status');print(json.dumps({k:status[k] for k in ('sealed','initialized','type')}))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
+693
@@ -0,0 +1,693 @@
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import secrets
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import URLError
|
||||
from urllib.request import ProxyHandler, build_opener
|
||||
import venv
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LOG = []
|
||||
LOCAL_HTTP = build_opener(ProxyHandler({}))
|
||||
|
||||
|
||||
def settings():
|
||||
path = ROOT / ".env"
|
||||
result = {}
|
||||
if path.exists():
|
||||
for line in path.read_text(encoding="utf-8-sig").splitlines():
|
||||
key, separator, value = line.partition("=")
|
||||
if separator and not key.strip().startswith("#"):
|
||||
result[key.strip()] = value.strip()
|
||||
return result
|
||||
|
||||
|
||||
def environment(args):
|
||||
result = os.environ.copy()
|
||||
result.update(PYTHONUTF8="1", PYTHONIOENCODING="utf-8", PYTHONDONTWRITEBYTECODE="1",
|
||||
COMPOSE_PROJECT_NAME=args.project, HTTP_PORT=str(args.port),
|
||||
GRAFANA_PORT=str(getattr(args, "grafana_port", None) or (3311 if args.project.endswith("-ttl") else (3310 if "clean" in args.project else int(settings().get("GRAFANA_PORT", "3309"))))),
|
||||
SESSION_TTL_SECONDS=str(args.ttl), LAB7_PROJECT=args.project,
|
||||
LAB7_PORT=str(args.port), LAB7_TTL=str(args.ttl))
|
||||
result['CA_FILE'] = str(ROOT / 'runtime' / args.project / 'pki/ca.crt')
|
||||
result['BAO_TOKEN_TTL'] = '2' if args.project.endswith('-bao-ttl') else '900'
|
||||
result['BASE_URL'] = f'https://127.0.0.1:{args.port}'
|
||||
result['BAO_PORT'] = '18202' if args.project.endswith('-ttl') else ('18201' if 'clean' in args.project else '18200')
|
||||
result["LAB7_GRAFANA_PORT"] = result["GRAFANA_PORT"]
|
||||
subnet = 72 if args.project.endswith('-ttl') else (74 if 'clean' in args.project else 70)
|
||||
result['LAB7_APP_SUBNET'] = f'10.240.{subnet}.0/24'
|
||||
result['LAB7_STORAGE_SUBNET'] = f'10.240.{subnet+1}.0/24'
|
||||
for key in ("NO_PROXY", "no_proxy"):
|
||||
result[key] = ",".join(filter(None, [result.get(key), "localhost", "127.0.0.1"]))
|
||||
return result
|
||||
|
||||
|
||||
def say(value):
|
||||
line = str(value).replace(str(ROOT), ".")
|
||||
print(line, flush=True)
|
||||
LOG.append(line)
|
||||
|
||||
|
||||
def run(args, command, quiet=False):
|
||||
command = [str(item) for item in command]
|
||||
if not quiet:
|
||||
say("$ " + subprocess.list2cmdline(command))
|
||||
with subprocess.Popen(command, cwd=ROOT, env=environment(args), stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace") as process:
|
||||
lines = []
|
||||
for line in process.stdout:
|
||||
lines.append(line)
|
||||
if not quiet:
|
||||
say(line.rstrip())
|
||||
code = process.wait()
|
||||
if code:
|
||||
raise RuntimeError(f"{command[0]} exited with code {code}")
|
||||
return "".join(lines)
|
||||
|
||||
|
||||
def compose(args, *command, quiet=False):
|
||||
if args.project != "mtusi-lab7" and not args.project.startswith("mtusi-lab7-"):
|
||||
raise RuntimeError("Only lab7 projects are allowed")
|
||||
return run(args, ["docker", "compose", "--project-name", args.project, "--env-file", ".env", *command], quiet)
|
||||
|
||||
|
||||
def interpreter():
|
||||
return ROOT / ".venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
|
||||
|
||||
|
||||
def evidence(name, value):
|
||||
path = ROOT / "evidence" / name
|
||||
path.parent.mkdir(exist_ok=True)
|
||||
content = json.dumps(value, ensure_ascii=False, indent=2) if not isinstance(value, str) else value
|
||||
path.write_text(content.rstrip() + "\n", encoding="utf-8", newline="\n")
|
||||
|
||||
|
||||
def setup(args):
|
||||
if not (ROOT / '.env').exists():
|
||||
shutil.copyfile(ROOT / '.env.example', ROOT / '.env')
|
||||
if not interpreter().exists():
|
||||
venv.EnvBuilder(with_pip=True).create(ROOT / '.venv')
|
||||
locks = [ROOT / 'requirements.lock', ROOT / 'requirements-validation.lock']
|
||||
fingerprint = hashlib.sha256(b''.join(p.read_bytes() for p in locks)).hexdigest()
|
||||
marker = ROOT / '.venv/.lab-dependencies'
|
||||
if not marker.exists() or marker.read_text() != fingerprint:
|
||||
run(args, [interpreter(), '-m', 'pip', 'install', '--quiet', '--disable-pip-version-check', '-r', locks[0], '-r', locks[1]])
|
||||
marker.write_text(fingerprint)
|
||||
admin(args, 'setup')
|
||||
|
||||
|
||||
def admin(args, action):
|
||||
return run(args, [interpreter(), '-X', 'utf8', 'scripts/admin.py', action])
|
||||
|
||||
|
||||
def tls_opener(args):
|
||||
import ssl
|
||||
from urllib.request import HTTPSHandler
|
||||
return build_opener(ProxyHandler({}), HTTPSHandler(context=ssl.create_default_context(cafile=environment(args)['CA_FILE'])))
|
||||
|
||||
|
||||
def base_url(args):
|
||||
return f"https://127.0.0.1:{args.port}"
|
||||
|
||||
|
||||
def wait_storage(args, timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
container = compose(args, "ps", "--all", "--quiet", "s3-storage", quiet=True).strip()
|
||||
if container:
|
||||
status = run(args, ["docker", "inspect", "--format", "{{.State.Health.Status}}", container], quiet=True).strip()
|
||||
if status == "healthy":
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError("S3 storage readiness timeout")
|
||||
|
||||
|
||||
def wait_ready(args, timeout=90):
|
||||
wait_storage(args, timeout)
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with tls_opener(args).open(base_url(args) + "/health/ready", timeout=4) as response:
|
||||
if response.status == 200 and json.load(response) == {"status": "ok"}:
|
||||
return
|
||||
except (URLError, OSError, ValueError):
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
raise RuntimeError("API readiness timeout")
|
||||
|
||||
|
||||
def build(args):
|
||||
compose(args, "config", "--quiet")
|
||||
compose(args, "build", "api1")
|
||||
compose(args, "run", "--rm", "--no-deps", "lb", "haproxy", "-c", "-f",
|
||||
"/usr/local/etc/haproxy/haproxy.cfg")
|
||||
|
||||
|
||||
def start(args):
|
||||
compose(args, 'up', '-d', '--no-build', 'db', 'openbao', 'broker', 's3-storage', 's3', 's3-tls')
|
||||
wait_storage(args)
|
||||
admin(args, 'bao-bootstrap')
|
||||
compose(args, 'run', '--rm', '--no-deps', 'migrate')
|
||||
admin(args, 'grants')
|
||||
compose(args, 'run', '--rm', '--no-deps', 'bootstrap')
|
||||
compose(args, 'up', '-d', '--no-build', 'loki', 'tempo', 'prometheus', 'loki-tls', 'tempo-tls', 'prometheus-tls',
|
||||
'otel-collector', 'otel-collector-tls', 'grafana', 'api1', 'api2', 'worker', 'cleanup', 'api1-tls', 'api2-tls', 'lb')
|
||||
wait_ready(args)
|
||||
wait_replicas(args)
|
||||
say('Two API replicas ready over verified HTTPS: ' + base_url(args))
|
||||
|
||||
|
||||
def states(args):
|
||||
services = ("api1", "api2", "db", "lb", "s3", "s3-storage", "cleanup", "broker", "worker", "otel-collector", "prometheus", "loki", "tempo", "grafana", "openbao", "api1-tls", "api2-tls", "s3-tls", "otel-collector-tls", "loki-tls", "tempo-tls", "prometheus-tls")
|
||||
containers = compose(args, "ps", "--all", "--quiet", *services, quiet=True).split()
|
||||
if len(set(containers)) != len(services):
|
||||
raise RuntimeError("Missing runtime container")
|
||||
result = {}
|
||||
for data in json.loads(run(args, ["docker", "inspect", *containers], quiet=True)):
|
||||
labels = data["Config"].get("Labels", {})
|
||||
service = labels.get("com.docker.compose.service")
|
||||
if labels.get("com.docker.compose.project") != args.project or service not in services or service in result:
|
||||
raise RuntimeError("Unexpected container ownership")
|
||||
result[service] = {
|
||||
"id": data["Id"], "image": data["Image"], "started_at": data["State"]["StartedAt"],
|
||||
"running": data["State"]["Running"], "oom_killed": data["State"]["OOMKilled"],
|
||||
"restart_count": data["RestartCount"], "user": data["Config"]["User"],
|
||||
"volumes": [mount["Name"] for mount in data["Mounts"] if mount["Type"] == "volume"],
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def restart(args):
|
||||
before = states(args)
|
||||
compose(args, 'stop', '--timeout', '10')
|
||||
start(args)
|
||||
after = states(args)
|
||||
for name in before:
|
||||
if before[name]['started_at'] == after[name]['started_at'] or before[name]['volumes'] != after[name]['volumes']:
|
||||
raise RuntimeError('Restart/volume mismatch: ' + name)
|
||||
evidence('restart.json', {'before': before, 'after': after, 'operator_unseal': True})
|
||||
say('PASS: all runtime services restarted, OpenBao unsealed, volumes preserved')
|
||||
|
||||
|
||||
def contract_tests(args):
|
||||
run(args, [interpreter(), "-X", "utf8", "scripts/check_contract.py"])
|
||||
run(args, [interpreter(), "-X", "utf8", "scripts/validate_openapi.py"])
|
||||
compose(args, "config", "--quiet")
|
||||
|
||||
|
||||
def api_tests(args):
|
||||
wait_ready(args)
|
||||
run(args, [interpreter(), "-X", "utf8", "tests/smoke.py", "--base-url", base_url(args)])
|
||||
os.environ["BASE_URL"] = base_url(args)
|
||||
run(args, [interpreter(), "-X", "utf8", "-m", "unittest", "discover", "-s", "student-tests", "-v"])
|
||||
|
||||
|
||||
def client(args):
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client
|
||||
for key in ("NO_PROXY", "no_proxy"):
|
||||
os.environ[key] = environment(args)[key]
|
||||
return Client(base_url(args), ca_file=environment(args)["CA_FILE"])
|
||||
|
||||
|
||||
def database_stats(args):
|
||||
sql = """SELECT json_build_object(
|
||||
'users',(SELECT count(*) FROM users),'chats',(SELECT count(*) FROM chats),
|
||||
'members',(SELECT count(*) FROM chat_members),'messages',(SELECT count(*) FROM messages),
|
||||
'sessions',(SELECT count(*) FROM sessions),'migrations',(SELECT count(*) FROM schema_migrations),
|
||||
'idempotency_keys',(SELECT count(*) FROM idempotency_keys),
|
||||
'attachments',(SELECT count(*) FROM attachments),'message_attachments',(SELECT count(*) FROM message_attachments),
|
||||
'upload_intents',(SELECT count(*) FROM upload_intents),
|
||||
'expiry_fingerprint',(SELECT md5(COALESCE(string_agg(user_id::text || created_at::text || expires_at::text,
|
||||
',' ORDER BY token_hash),'')) FROM sessions),
|
||||
'passwords_are_argon2id',(SELECT bool_and(password_hash LIKE '$argon2id$%') FROM users),
|
||||
'session_hashes_only',(SELECT bool_and(token_hash ~ '^[0-9a-f]{64}$') FROM sessions))"""
|
||||
result = compose(args, "exec", "-T", "db", "psql", "-U", "messenger", "-d", "messenger",
|
||||
"-At", "-c", sql, quiet=True)
|
||||
return json.loads(result)
|
||||
|
||||
|
||||
def restart_check(args):
|
||||
from urllib.parse import urlencode
|
||||
c = client(args)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
replay_key = secrets.token_hex(16)
|
||||
original = c.message(alice, chat, "first", key=replay_key)["json"]
|
||||
last = c.message(bob, chat, "second")["json"]
|
||||
page = c.call("GET", path + "?limit=1", actor=alice, schema="MessagePage")["json"]
|
||||
revoked = c.user("revoked")
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=revoked)
|
||||
hook = ROOT / "scripts" / ("restart.cmd" if os.name == "nt" else "restart.sh")
|
||||
run(args, [interpreter(), "-X", "utf8", "tests/resilience.py", "--mode", "persistence",
|
||||
"--action-script", hook, "--base-url", base_url(args)])
|
||||
continued = c.call("GET", path + "?" + urlencode({"cursor": page["next_cursor"]}),
|
||||
actor=alice, schema="MessagePage")["json"]
|
||||
if continued != {"items": [last], "next_cursor": None}:
|
||||
raise RuntimeError("Old cursor did not survive restart")
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=revoked)
|
||||
c.call("GET", "/api/v1/chats/" + chat["id"], 404, actor=eve)
|
||||
before = database_stats(args)
|
||||
compose(args, "run", "--rm", "--no-deps", "migrate")
|
||||
compose(args, "run", "--rm", "--no-deps", "migrate")
|
||||
after = database_stats(args)
|
||||
stable_before = {key: value for key, value in before.items() if key != "upload_intents"}
|
||||
stable_after = {key: value for key, value in after.items() if key != "upload_intents"}
|
||||
if stable_before != stable_after or after["migrations"] != 4:
|
||||
raise RuntimeError("Migration replay changed existing data")
|
||||
if not after["passwords_are_argon2id"] or not after["session_hashes_only"]:
|
||||
raise RuntimeError("Unexpected credential representation in DB")
|
||||
repeated = c.message(alice, chat, "first", key=replay_key)["json"]
|
||||
if repeated != original:
|
||||
raise RuntimeError("Idempotency result was not preserved")
|
||||
result = {"idempotency_after_restart": "PASS", "public_persistence": "PASS", "cursor_after_restart": "PASS",
|
||||
"logout_after_restart": "PASS", "migration_replay": "PASS", "database": after}
|
||||
evidence("persistence.json", result)
|
||||
say("PASS: old session/cursor, durable logout and repeatable migrations")
|
||||
return result
|
||||
|
||||
|
||||
def ttl_check(args):
|
||||
test = argparse.Namespace(project=args.project + "-ttl", port=args.test_port, ttl=2,
|
||||
test_port=args.test_port, action="start")
|
||||
try:
|
||||
setup(test)
|
||||
start(test)
|
||||
c = client(test)
|
||||
actor = c.user("expiry")
|
||||
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
before = database_stats(test)["expiry_fingerprint"]
|
||||
compose(test, "stop", "--timeout", "3", "api1-tls", "api2-tls")
|
||||
compose(test, "restart", "--timeout", "3", "api1", "api2")
|
||||
compose(test, "start", "api1-tls", "api2-tls")
|
||||
wait_ready(test)
|
||||
after = database_stats(test)["expiry_fingerprint"]
|
||||
if before != after:
|
||||
raise RuntimeError("Session expiry changed during restart")
|
||||
time.sleep(2.2)
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
registration = actor["registration"]
|
||||
import base64
|
||||
basic = base64.b64encode((registration["username"] + ":" + registration["password"]).encode()).decode()
|
||||
c.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + basic}, schema="Session")
|
||||
say("PASS: TTL=2, expired token rejected after API restart; fresh login works")
|
||||
result = {"ttl_seconds": 2, "expiry_unchanged_on_restart": True, "before_restart": 200,
|
||||
"after_expiry_and_restart": 401, "new_login": 201}
|
||||
evidence("expiry.json", result)
|
||||
return result
|
||||
finally:
|
||||
compose(test, "down", "--timeout", "10")
|
||||
|
||||
|
||||
def dependency_check(args):
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request
|
||||
c = client(args)
|
||||
actor = c.user('dependencies')
|
||||
result = {}
|
||||
for service in ('db', 's3', 'broker'):
|
||||
try:
|
||||
compose(args, 'stop', '--timeout', '10', service)
|
||||
c.call('GET', '/health/live', schema='Health')
|
||||
outage_response(args, '/health/ready')
|
||||
deadline = time.monotonic() + 20
|
||||
while True:
|
||||
try:
|
||||
with tls_opener(args).open(Request(base_url(args) + '/api/v1/users/me',
|
||||
headers={'Authorization': 'Bearer ' + actor['token']}), timeout=5) as response:
|
||||
if response.status != 200:
|
||||
raise RuntimeError('Unexpected dependency response')
|
||||
except HTTPError as error:
|
||||
if error.code != 503:
|
||||
raise RuntimeError('Unexpected dependency status') from None
|
||||
error.close()
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError('LB did not withdraw unready replicas')
|
||||
time.sleep(0.3)
|
||||
outage_response(args, '/api/v1/users/me', actor['token'])
|
||||
finally:
|
||||
compose(args, 'start', service)
|
||||
wait_ready(args)
|
||||
c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
||||
result[service] = {'live': 200, 'ready': 503, 'business': 503, 'recovered': 200}
|
||||
say('PASS: ' + service + ' outage and recovery')
|
||||
return result
|
||||
|
||||
|
||||
def observability_check(args, mode):
|
||||
run(args, [interpreter(), '-X', 'utf8', 'scripts/observability_checks.py', mode])
|
||||
return json.loads((ROOT / ('evidence/' + mode + '.json')).read_text(encoding='utf-8'))
|
||||
|
||||
|
||||
def verify(args):
|
||||
summary = {"date_utc": datetime.now(timezone.utc).isoformat(), "platform": platform.platform(),
|
||||
"source_commit": run(args, ["git", "rev-parse", "HEAD"], quiet=True).strip(),
|
||||
"worktree_dirty_at_start": bool(run(args, ["git", "status", "--porcelain"], quiet=True).strip()),
|
||||
"project": args.project, "status": "FAIL"}
|
||||
try:
|
||||
setup(args)
|
||||
contract_tests(args)
|
||||
build(args)
|
||||
start(args)
|
||||
api_tests(args)
|
||||
summary["queue"] = queue_check(args)
|
||||
summary["retry"] = retry_check(args)
|
||||
summary["persistence"] = restart_check(args)
|
||||
summary["failover"] = failover_check(args)
|
||||
summary["attachments_failover"] = attachment_failover_check(args)
|
||||
summary["expiry"] = ttl_check(args)
|
||||
summary["dependency"] = dependency_check(args)
|
||||
run(args, [interpreter(), "-X", "utf8", "tests/smoke.py", "--base-url", base_url(args)])
|
||||
summary["telemetry"] = observability_check(args, 'telemetry')
|
||||
summary["incidents"] = observability_check(args, 'incidents')
|
||||
summary["telemetry_outage"] = observability_check(args, 'outage')
|
||||
run(args, [interpreter(),'-X','utf8','tests/security.py','--base-url',base_url(args)])
|
||||
run(args, [interpreter(),'-X','utf8','scripts/security_checks.py','security-check'])
|
||||
run(args, [interpreter(),'-X','utf8','scripts/security_checks.py','bao-check'])
|
||||
summary['security'] = json.loads((ROOT/'evidence/policies.json').read_text())
|
||||
summary['bao_expiry'] = json.loads((ROOT/'evidence/bao-expiry.json').read_text())
|
||||
summary["containers"] = states(args)
|
||||
summary["docker"] = run(args, ["docker", "version", "--format", "{{.Server.Version}}"], quiet=True).strip()
|
||||
summary["resources"] = json.loads(run(
|
||||
args, ["docker", "info", "--format", '{"cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}}}'], quiet=True))
|
||||
summary["status"] = "PASS"
|
||||
say("PASS: full lab7 verification")
|
||||
finally:
|
||||
evidence("verification.txt", "\n".join(LOG))
|
||||
evidence("summary.json", summary)
|
||||
|
||||
|
||||
def instance_map(args):
|
||||
current = states(args)
|
||||
result = {}
|
||||
for service in ("api1", "api2"):
|
||||
item = current[service]
|
||||
if not item["running"]:
|
||||
continue
|
||||
code = (
|
||||
"import urllib.request; "
|
||||
"o=urllib.request.build_opener(urllib.request.ProxyHandler({})); "
|
||||
"r=o.open('http://127.0.0.1:8080/health/live',timeout=1); "
|
||||
"print(r.headers['X-Instance-Id'])"
|
||||
)
|
||||
alias = run(args, ["docker", "exec", item["id"], "python", "-c", code], quiet=True).strip()
|
||||
import re
|
||||
if not re.fullmatch(r"[0-9a-f]{32}", alias):
|
||||
raise RuntimeError("Invalid API instance alias")
|
||||
result[service] = {"instance_id": alias, "container_id": item["id"]}
|
||||
return result
|
||||
|
||||
|
||||
def wait_replicas(args):
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
mapping = instance_map(args)
|
||||
if len(mapping) == 2:
|
||||
c = client(args)
|
||||
seen = {c.call("GET", "/health/ready", schema="Health")["headers"]["X-Instance-Id"]
|
||||
for _ in range(8)}
|
||||
if seen == {item["instance_id"] for item in mapping.values()}:
|
||||
return mapping
|
||||
except (RuntimeError, OSError, AssertionError):
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
raise RuntimeError("Two healthy API replicas were not observed through LB")
|
||||
|
||||
|
||||
def restore(args):
|
||||
compose(args, "start", "api1", "api2")
|
||||
compose(args, "restart", "api1-tls", "api2-tls")
|
||||
wait_ready(args)
|
||||
return wait_replicas(args)
|
||||
|
||||
|
||||
def stop_one(args):
|
||||
target = os.environ.get("TARGET_INSTANCE_ID", "")
|
||||
before = instance_map(args)
|
||||
matches = [(name, item) for name, item in before.items() if item["instance_id"] == target]
|
||||
if len(before) != 2 or len(matches) != 1:
|
||||
raise RuntimeError("Target must match exactly one of two running API replicas")
|
||||
service, item = matches[0]
|
||||
started = time.monotonic()
|
||||
compose(args, "stop", "--timeout", "3", service + "-tls", service)
|
||||
after = states(args)
|
||||
if after[service]["running"] or not after["api1" if service == "api2" else "api2"]["running"]:
|
||||
raise RuntimeError("Unexpected API state after stop")
|
||||
elapsed = time.monotonic() - started
|
||||
if elapsed >= 10:
|
||||
raise RuntimeError("Stopping the selected API exceeded 10 seconds")
|
||||
evidence("stop-one.json", {"service": service, "target_instance": target, "before": before,
|
||||
"after": after, "stop_seconds": round(elapsed, 3)})
|
||||
say("Stopped only " + service)
|
||||
|
||||
|
||||
def failover_check(args):
|
||||
wait_replicas(args)
|
||||
hook = ROOT / "scripts" / ("stop-one.cmd" if os.name == "nt" else "stop-one.sh")
|
||||
try:
|
||||
output = run(args, [interpreter(), "-X", "utf8", "tests/resilience.py", "--mode", "failover",
|
||||
"--action-script", hook, "--base-url", base_url(args)])
|
||||
first = json.loads((ROOT / "evidence/stop-one.json").read_text(encoding="utf-8"))
|
||||
first["metrics"] = next(json.loads(line) for line in output.splitlines()
|
||||
if line.startswith("{") and "first_recovery_seconds" in line)
|
||||
if first["after"][first["service"]]["running"]:
|
||||
raise RuntimeError("Public hook did not leave the target stopped")
|
||||
finally:
|
||||
restore(args)
|
||||
other_service = "api2" if first["service"] == "api1" else "api1"
|
||||
mapping = instance_map(args)
|
||||
target = mapping[other_service]["instance_id"]
|
||||
c = client(args)
|
||||
c.timeout = 2
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
for _ in range(10):
|
||||
replay_key = secrets.token_hex(16)
|
||||
replay_text = "before-failure-" + replay_key
|
||||
response = c.message(alice, chat, replay_text, key=replay_key)
|
||||
if response["headers"]["X-Instance-Id"] == target:
|
||||
original = response["json"]
|
||||
break
|
||||
else:
|
||||
raise RuntimeError("Second API was not reached through LB")
|
||||
env = environment(args)
|
||||
env["TARGET_INSTANCE_ID"] = target
|
||||
started = time.monotonic()
|
||||
process = subprocess.Popen([str(hook)], cwd=ROOT, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
from client import Failure
|
||||
from resilience import history
|
||||
confirmations, after_instances = [], []
|
||||
failures = 0
|
||||
recovered = None
|
||||
key = secrets.token_hex(16)
|
||||
text = "during-failure-" + key
|
||||
try:
|
||||
while time.monotonic() - started < 15:
|
||||
code = process.poll()
|
||||
if code not in (None, 0):
|
||||
raise RuntimeError("Second stop hook failed")
|
||||
if code is None and time.monotonic() - started >= 10:
|
||||
raise RuntimeError("Second stop hook exceeded 10 seconds")
|
||||
try:
|
||||
response = c.message(alice, chat, text, key=key)
|
||||
confirmations.append(response["json"])
|
||||
if code == 0:
|
||||
if recovered is None:
|
||||
recovered = time.monotonic() - started
|
||||
after_instances.append(response["headers"]["X-Instance-Id"])
|
||||
key = secrets.token_hex(16)
|
||||
text = "during-failure-" + key
|
||||
except Failure:
|
||||
failures += 1
|
||||
time.sleep(0.1)
|
||||
if process.poll() != 0 or recovered is None or recovered > 10:
|
||||
raise RuntimeError("Second API failure did not recover within 10 seconds")
|
||||
if len(after_instances) < 5 or target in after_instances[-5:]:
|
||||
raise RuntimeError("Stopped API still serves requests")
|
||||
replayed = c.message(alice, chat, replay_text, key=replay_key)
|
||||
if replayed["json"] != original or replayed["headers"]["X-Instance-Id"] == target:
|
||||
raise RuntimeError("Message replay through the survivor changed the result")
|
||||
messages = history(c, bob, chat)
|
||||
ids = [item["id"] for item in messages]
|
||||
texts = [item["text"] for item in messages]
|
||||
if len(ids) != len(set(ids)) or len(texts) != len(set(texts)):
|
||||
raise RuntimeError("Duplicates appeared during failover")
|
||||
if any(item not in messages for item in [original, *confirmations]):
|
||||
raise RuntimeError("A confirmed message was lost")
|
||||
second = json.loads((ROOT / "evidence/stop-one.json").read_text(encoding="utf-8"))
|
||||
if second["service"] != other_service:
|
||||
raise RuntimeError("Wrong second API was stopped")
|
||||
second["metrics"] = {"successful_writes": len(confirmations), "failed_attempts": failures,
|
||||
"first_recovery_seconds": round(recovered, 3),
|
||||
"replay_on_survivor": "PASS"}
|
||||
result = {"public": first, "second_replica": second, "status": "PASS"}
|
||||
evidence("failover.json", result)
|
||||
say("PASS: both physical API replicas stopped separately; no lost messages or duplicates")
|
||||
return result
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(timeout=5)
|
||||
restore(args)
|
||||
|
||||
|
||||
def outage_response(args, path, token=None):
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request
|
||||
from client import shape
|
||||
headers = {"Authorization": "Bearer " + token} if token else {}
|
||||
try:
|
||||
response = tls_opener(args).open(Request(base_url(args) + path, headers=headers), timeout=10)
|
||||
except HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
payload = json.load(response)
|
||||
if response.status != 503 or not response.headers.get("X-Request-Id"):
|
||||
raise RuntimeError("Unexpected dependency failure response")
|
||||
shape(payload, "Error")
|
||||
if payload["error"]["request_id"] != response.headers["X-Request-Id"]:
|
||||
raise RuntimeError("LB error request ID mismatch")
|
||||
|
||||
|
||||
|
||||
def attachment_failover_check(args):
|
||||
import hashlib
|
||||
results = []
|
||||
raw = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
try:
|
||||
for service in ("api1", "api2"):
|
||||
mapping = wait_replicas(args)
|
||||
c = client(args)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
target = mapping[service]["instance_id"]
|
||||
for _ in range(8):
|
||||
uploaded = c.call(
|
||||
"POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=failover.png", 202,
|
||||
actor=alice, raw=raw, headers={"Content-Type": "image/png"}, schema="Attachment",
|
||||
)
|
||||
if uploaded["headers"]["X-Instance-Id"] == target:
|
||||
break
|
||||
else:
|
||||
raise RuntimeError("Selected upload replica was not observed")
|
||||
attachment = uploaded["json"]
|
||||
c.wait_ready(alice, attachment)
|
||||
linked = c.message(alice, chat, "", attachments=[attachment["id"]])["json"]
|
||||
hook = ROOT / "scripts" / ("stop-one.cmd" if os.name == "nt" else "stop-one.sh")
|
||||
previous = os.environ.get("TARGET_INSTANCE_ID")
|
||||
os.environ["TARGET_INSTANCE_ID"] = target
|
||||
started = time.monotonic()
|
||||
try:
|
||||
run(args, [str(hook)])
|
||||
finally:
|
||||
if previous is None:
|
||||
os.environ.pop("TARGET_INSTANCE_ID", None)
|
||||
else:
|
||||
os.environ["TARGET_INSTANCE_ID"] = previous
|
||||
from client import Client
|
||||
reads = Client(base_url(args), ca_file=environment(args)["CA_FILE"], timeout=2)
|
||||
errors = 0
|
||||
while True:
|
||||
try:
|
||||
downloaded = reads.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob)
|
||||
history_response = reads.call(
|
||||
"GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, schema="MessagePage",
|
||||
)
|
||||
break
|
||||
except (AssertionError, OSError) as error:
|
||||
if isinstance(error, AssertionError) and not any(
|
||||
text in str(error) for text in ("received 502", "received 503", "connection/TLS failure")
|
||||
):
|
||||
raise
|
||||
errors += 1
|
||||
if time.monotonic() - started >= 10:
|
||||
raise RuntimeError("File and history did not recover within 10 seconds") from None
|
||||
time.sleep(0.1)
|
||||
recovered = time.monotonic() - started
|
||||
if downloaded["bytes"] != raw or hashlib.sha256(raw).hexdigest() != attachment["sha256"]:
|
||||
raise RuntimeError("Original file changed after API failure")
|
||||
if downloaded["headers"]["X-Instance-Id"] == target or recovered > 10:
|
||||
raise RuntimeError("Upload replica was not replaced")
|
||||
history = history_response["json"]["items"]
|
||||
if history_response["headers"]["X-Instance-Id"] == target:
|
||||
raise RuntimeError("Stopped API returned history")
|
||||
if history != [linked]:
|
||||
raise RuntimeError("Attached message changed during failover")
|
||||
results.append({"stopped_service": service, "upload_instance": target,
|
||||
"download_instance": downloaded["headers"]["X-Instance-Id"],
|
||||
"recovery_seconds": round(recovered, 3), "transitional_errors": errors,
|
||||
"same_original": True, "message_preserved": True})
|
||||
restore(args)
|
||||
result = {"status": "PASS", "cases": results}
|
||||
evidence("attachment-failover.json", result)
|
||||
say("PASS: stopped each uploader; other API downloaded the same original")
|
||||
return result
|
||||
finally:
|
||||
restore(args)
|
||||
|
||||
|
||||
def queue_check(args):
|
||||
run(args, [interpreter(), '-X', 'utf8', 'scripts/pipeline_checks.py', 'queue'])
|
||||
return json.loads((ROOT / 'evidence/queue.json').read_text(encoding='utf-8'))
|
||||
|
||||
|
||||
def retry_check(args):
|
||||
run(args, [interpreter(), '-X', 'utf8', 'scripts/pipeline_checks.py', 'retry'])
|
||||
return json.loads((ROOT / 'evidence/retry.json').read_text(encoding='utf-8'))
|
||||
|
||||
|
||||
def jobs_failed(args):
|
||||
query = "SELECT a.id,a.error_code,j.attempt FROM attachments a JOIN attachment_jobs j ON a.id=j.attachment_id WHERE a.status='failed' ORDER BY a.updated_at DESC LIMIT 100"
|
||||
say(compose(args, 'exec', '-T', 'db', 'psql', '-U', 'messenger', '-d', 'messenger', '-c', query, quiet=True))
|
||||
|
||||
|
||||
def main():
|
||||
saved = settings()
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=["setup", "build", "start", "test", "restart", "stop-one",
|
||||
"restart-check", "failover-check", "restore", "stop", "verify", "queue-check", "retry-check", "worker-stop", "worker-start", "jobs-failed", "telemetry-check", "incident-check", "telemetry-outage-check", "bao-check", "tls-check", "policy-check", "security-check", "bao-status", "bao-unseal", "pki-renew"])
|
||||
parser.add_argument("--project", default=os.environ.get("LAB7_PROJECT", saved.get("COMPOSE_PROJECT_NAME", "mtusi-lab7")))
|
||||
parser.add_argument("--port", type=int, default=int(os.environ.get("LAB7_PORT", saved.get("HTTP_PORT", "8443"))))
|
||||
parser.add_argument("--ttl", type=int, default=int(os.environ.get("LAB7_TTL", saved.get("SESSION_TTL_SECONDS", "3600"))))
|
||||
parser.add_argument("--grafana-port", type=int, default=int(os.environ["LAB7_GRAFANA_PORT"]) if "LAB7_GRAFANA_PORT" in os.environ else None)
|
||||
parser.add_argument("--test-port", type=int, default=18444)
|
||||
args = parser.parse_args()
|
||||
if not 1 <= args.port <= 65535 or not 1 <= args.test_port <= 65534 or not 1 <= args.ttl <= 86400:
|
||||
parser.error("Invalid port or session TTL")
|
||||
if args.action in ("setup", "build", "start", "test", "restart-check", "failover-check", "queue-check", "retry-check"):
|
||||
setup(args)
|
||||
actions = {"setup": lambda item: None, "build": build, "start": start,
|
||||
"test": lambda item: (contract_tests(item), api_tests(item)),
|
||||
"restart": restart, "restart-check": restart_check, "verify": verify,
|
||||
"queue-check": queue_check, "retry-check": retry_check, "jobs-failed": jobs_failed,
|
||||
"worker-stop": lambda item: compose(item, "stop", "--timeout", "3", "worker"),
|
||||
"worker-start": lambda item: compose(item, "start", "worker"),
|
||||
"stop-one": stop_one, "restore": restore, "failover-check": failover_check,
|
||||
|
||||
"stop": lambda item: compose(item, "stop", "--timeout", "10")}
|
||||
for action, mode in (("telemetry-check", "telemetry"), ("incident-check", "incidents"), ("telemetry-outage-check", "outage")):
|
||||
actions[action] = lambda item, mode=mode: observability_check(item, mode)
|
||||
for action in ('bao-status','bao-unseal'):
|
||||
actions[action] = lambda item, action=action: admin(item, action)
|
||||
for action in ('tls-check','policy-check','security-check','bao-check'):
|
||||
actions[action] = lambda item, action=action: run(item,[interpreter(),'-X','utf8','scripts/security_checks.py',action])
|
||||
actions['pki-renew'] = lambda item: (compose(item,'stop','--timeout','10'),admin(item,'pki-renew'),start(item))
|
||||
actions[args.action](args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (RuntimeError, OSError, ValueError) as error:
|
||||
print("FAIL: " + str(error), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,322 @@
|
||||
import base64
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from scripts import lab
|
||||
|
||||
|
||||
def arguments():
|
||||
saved = lab.settings()
|
||||
return SimpleNamespace(project=os.environ.get('LAB7_PROJECT', saved['COMPOSE_PROJECT_NAME']),
|
||||
port=int(os.environ.get('LAB7_PORT', saved['HTTP_PORT'])),
|
||||
ttl=int(os.environ.get('LAB7_TTL', saved['SESSION_TTL_SECONDS'])),
|
||||
test_port=18444, grafana_port=int(os.environ["LAB7_GRAFANA_PORT"]) if "LAB7_GRAFANA_PORT" in os.environ else None)
|
||||
|
||||
|
||||
def wait(predicate, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
result = predicate()
|
||||
if result:
|
||||
return result
|
||||
except (RuntimeError, ValueError, OSError) as error:
|
||||
last = type(error).__name__
|
||||
time.sleep(1)
|
||||
raise RuntimeError('Telemetry condition timed out' + (': ' + last if last else ''))
|
||||
|
||||
|
||||
def probe(args, payload):
|
||||
import subprocess
|
||||
result=subprocess.run(['docker','compose','--project-name',args.project,'--env-file','.env','run','--rm','--no-deps','-T','probe','python','/app/probe.py'],
|
||||
cwd=lab.ROOT,env=lab.environment(args),input=json.dumps(payload),text=True,capture_output=True,encoding='utf-8')
|
||||
if result.returncode:
|
||||
raise RuntimeError('TLS probe failed: ' + result.stderr[-350:])
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def backend(args, url):
|
||||
return backend_many(args,[url])[0]
|
||||
|
||||
|
||||
def backend_many(args, urls):
|
||||
return probe(args, {'op':'fetch','urls':[url.replace('http://','https://') for url in urls]})
|
||||
|
||||
|
||||
def prom(args, query, at=None):
|
||||
params = {'query': query}
|
||||
if at:
|
||||
params['time'] = at
|
||||
result = backend(args, 'http://prometheus:9090/api/v1/query?' + urlencode(params))
|
||||
if result['status'] != 'success':
|
||||
raise RuntimeError('Prometheus query failed')
|
||||
return result['data']['result']
|
||||
|
||||
|
||||
def logs(args, query, start=None):
|
||||
params = {'query': query, 'limit': 2000, 'start': str(int((start or time.time() - 300) * 1e9)),
|
||||
'end': str(time.time_ns()), 'direction': 'backward'}
|
||||
result = backend(args, 'http://loki:3100/loki/api/v1/query_range?' + urlencode(params))
|
||||
entries = []
|
||||
for stream in result['data']['result']:
|
||||
for value in stream['values']:
|
||||
item = {**stream['stream'], 'timestamp_ns': value[0], 'body': value[1]}
|
||||
if len(value) > 2:
|
||||
item.update(value[2])
|
||||
entries.append(item)
|
||||
return entries
|
||||
|
||||
|
||||
def trace_data(args, trace_id):
|
||||
return backend(args, 'http://tempo:3200/api/traces/' + trace_id)
|
||||
|
||||
|
||||
def spans(data):
|
||||
found = []
|
||||
if isinstance(data, dict):
|
||||
if 'spanId' in data and 'name' in data:
|
||||
found.append(data)
|
||||
for value in data.values():
|
||||
found.extend(spans(value))
|
||||
elif isinstance(data, list):
|
||||
for value in data:
|
||||
found.extend(spans(value))
|
||||
return found
|
||||
|
||||
|
||||
def correlated(args, query, kind, start=None):
|
||||
entry = wait(lambda: next((item for item in logs(args, query, start) if item.get('trace_id')), None))
|
||||
data = wait(lambda: trace_data(args, entry['trace_id']))
|
||||
candidates = [span for span in spans(data) if span.get('kind') in (kind, 'SPAN_KIND_' + kind)]
|
||||
if not candidates or not any(int(span['endTimeUnixNano']) > int(span['startTimeUnixNano']) for span in candidates):
|
||||
raise RuntimeError('Real span with required kind/duration not found')
|
||||
matched = next((span for span in candidates if
|
||||
(span['spanId'] if len(span['spanId']) == 16 else base64.b64decode(span['spanId']).hex()) == entry['span_id']), None)
|
||||
if matched is None:
|
||||
raise RuntimeError('Log span ID does not match the trace')
|
||||
return {'trace_id': entry['trace_id'], 'span_id': entry['span_id'], 'event': entry['body'],
|
||||
'kind': kind, 'span_name': matched['name'], 'span_status': matched.get('status', {}),
|
||||
'span_duration_seconds': (int(matched['endTimeUnixNano']) - int(matched['startTimeUnixNano'])) / 1e9,
|
||||
'span_attributes': matched.get('attributes', []), 'log': entry}
|
||||
|
||||
|
||||
def sql(args, statement):
|
||||
return lab.compose(args, 'exec', '-T', 'db', 'psql', '-U', 'messenger', '-d', 'messenger',
|
||||
'-v', 'ON_ERROR_STOP=1', '-At', '-c', statement, quiet=True).strip()
|
||||
|
||||
|
||||
def job_id(args, attachment):
|
||||
return sql(args, "SELECT id FROM attachment_jobs WHERE attachment_id='" + attachment['id'] + "'")
|
||||
|
||||
|
||||
def grafana(args):
|
||||
port = int(lab.environment(args)['GRAFANA_PORT'])
|
||||
password = (lab.ROOT / 'runtime' / args.project / 'grafana/password').read_text().strip()
|
||||
authorization = 'Basic ' + base64.b64encode(('admin:' + password).encode()).decode()
|
||||
|
||||
def get(path):
|
||||
with lab.tls_opener(args).open(Request('https://127.0.0.1:' + str(port) + path,
|
||||
headers={'Authorization': authorization}), timeout=10) as response:
|
||||
return json.load(response)
|
||||
|
||||
sources = wait(lambda: get('/api/datasources'))
|
||||
if {source['uid'] for source in sources} != {'prometheus', 'loki', 'tempo'}:
|
||||
raise RuntimeError('Grafana data sources missing')
|
||||
dashboard = get('/api/dashboards/uid/messenger-lab6')['dashboard']
|
||||
queries = [target['expr'] for panel in dashboard['panels'] for target in panel.get('targets', [])
|
||||
if panel.get('datasource', {}).get('uid') == 'prometheus']
|
||||
for query in queries:
|
||||
prom(args, query.replace("$instance", ".*"))
|
||||
for source in sources:
|
||||
health = get('/api/datasources/uid/' + source['uid'] + '/health')
|
||||
if health['status'] != 'OK':
|
||||
raise RuntimeError('Grafana data source health failed')
|
||||
loki = next(source for source in sources if source['uid'] == 'loki')
|
||||
if loki['jsonData']['derivedFields'][0]['url'] != '${__value.raw}':
|
||||
raise RuntimeError('Loki trace link is not provisioned correctly')
|
||||
query_checks = []
|
||||
for uid, query in (('loki', {'expr': '{service_name="messenger-api"}', 'queryType': 'range', 'maxLines': 5}),
|
||||
('tempo', {'query': '{ resource.service.name = "messenger-api" }', 'queryType': 'traceql', 'limit': 5})):
|
||||
payload = json.dumps({'from': str(int((time.time() - 300) * 1000)), 'to': str(time.time_ns() // 1000000),
|
||||
'queries': [{'refId': 'A', 'datasource': {'type': uid, 'uid': uid}, **query}]}).encode()
|
||||
request = Request('https://127.0.0.1:' + str(port) + '/api/ds/query', data=payload,
|
||||
headers={'Authorization': authorization, 'Content-Type': 'application/json'})
|
||||
with lab.tls_opener(args).open(request, timeout=15) as response:
|
||||
result = json.load(response)['results']['A']
|
||||
if result.get('error') or result.get('status') != 200 or not result.get('frames'):
|
||||
raise RuntimeError('Grafana log/trace query failed')
|
||||
query_checks.append(uid)
|
||||
return {'log_trace_queries': query_checks, 'dashboard_uid': dashboard['uid'], 'data_sources': [s['uid'] for s in sources],
|
||||
'prometheus_queries_valid': len(queries), 'source_health': 'PASS'}
|
||||
|
||||
|
||||
def telemetry(args):
|
||||
c = lab.client(args)
|
||||
start = time.time()
|
||||
actor, bob, eve, chat = c.bootstrap()
|
||||
marker = 'private-content-' + uuid4().hex
|
||||
c.message(actor, chat, marker)
|
||||
response = c.call('GET', '/api/v1/users/me', actor=actor)
|
||||
request_id = response['headers']['X-Request-Id']
|
||||
api = correlated(args, '{service_name="messenger-api"} | request_id="' + request_id + '"', 'SERVER', start)
|
||||
filename = 'private-name-' + uuid4().hex + '.png'
|
||||
raw = (lab.ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
attachment = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename,
|
||||
202, actor=actor, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
c.wait_ready(actor, attachment)
|
||||
job = job_id(args, attachment)
|
||||
worker = correlated(args, '{service_name="messenger-worker"} | job_id="' + job + '" | event="job.completed"', 'CONSUMER', start)
|
||||
try:
|
||||
lab.compose(args, 'stop', '--timeout', '10', 'worker')
|
||||
broken, _ = c.attachment(actor, chat)
|
||||
stage = sql(args, "SELECT staging_key FROM attachment_jobs WHERE attachment_id='" + broken['id'] + "'")
|
||||
code = ("from src.objects import Objects; from io import BytesIO; o=Objects(admin=True); "
|
||||
"o.put(" + repr(stage) + ",BytesIO(b'broken'),6,'image/png'); o.close()")
|
||||
lab.compose(args, 'run', '--rm', '--no-deps', '-T', 'bootstrap', 'python', '-c', code, quiet=True)
|
||||
finally:
|
||||
lab.compose(args, 'start', 'worker')
|
||||
wait(lambda: sql(args, "SELECT status FROM attachments WHERE id='" + broken['id'] + "'") == 'failed')
|
||||
failed_job = job_id(args, broken)
|
||||
failed = correlated(args, '{service_name="messenger-worker"} | job_id="' + failed_job + '" | event="job.completed"', 'CONSUMER', start)
|
||||
failed_counter = wait(lambda: prom(args, 'messenger_jobs_total{outcome="failed"}'))
|
||||
for _ in range(4):
|
||||
c.call('GET', '/api/v1/chats/' + str(uuid4()), 404, actor=actor)
|
||||
c.call('GET', '/not-a-route-' + uuid4().hex, 404)
|
||||
c.call('GET', '/api/v1/users/me', 401)
|
||||
http = wait(lambda: prom(args, 'messenger_http_requests_total{route="/api/v1/users/me"}'))
|
||||
jobs = wait(lambda: prom(args, 'messenger_jobs_total{outcome="success"}'))
|
||||
histograms = wait(lambda: prom(args, 'messenger_job_duration_seconds_bucket'))
|
||||
http_histograms = wait(lambda: prom(args, 'messenger_http_duration_seconds_bucket'))
|
||||
series = prom(args, 'messenger_http_requests_total')
|
||||
forbidden = {'request_id', 'user_id', 'chat_id', 'message_id', 'attachment_id', 'filename', 'url', 'url_full'}
|
||||
for sample in series:
|
||||
labels = sample['metric']
|
||||
if forbidden.intersection(labels) or any(value in labels.get('route', '') for value in (chat['id'], actor['id'])):
|
||||
raise RuntimeError('High cardinality metric attributes')
|
||||
current_instances = '|'.join(item['instance_id'] for item in lab.instance_map(args).values())
|
||||
if prom(args, '{__name__=~"http_server_request_duration.*",service_instance_id=~"' + current_instances + '"}'):
|
||||
raise RuntimeError('Duplicate native FastAPI metrics found')
|
||||
records = logs(args, '{service_name=~"messenger-api|messenger-worker"}', start)
|
||||
ids = sorted({item['trace_id'] for item in records if item.get('trace_id')})
|
||||
traces = wait(lambda: backend_many(args, ['http://tempo:3200/api/traces/' + value for value in ids]))
|
||||
exported = json.dumps(records, ensure_ascii=False) + json.dumps(traces, ensure_ascii=False)
|
||||
private = [marker, filename, actor['token'], actor['registration']['password'], actor['registration']['display_name']]
|
||||
if any(value in exported for value in private):
|
||||
raise RuntimeError('Private data exported')
|
||||
if not all(key in api['log'] for key in ('severity_text', 'service_name', 'event', 'trace_id', 'span_id')):
|
||||
raise RuntimeError('Required structured log fields missing')
|
||||
result = {'status': 'PASS', 'api': api, 'worker': worker, 'failed_worker': failed, 'failed_job_series': len(failed_counter), 'privacy': 'PASS',
|
||||
'route_cardinality': 'PASS', 'no_duplicate_instrumentation': True,
|
||||
'http_series': len(http), 'job_series': len(jobs),
|
||||
'http_histogram_buckets': len(http_histograms), 'job_histogram_buckets': len(histograms),
|
||||
'grafana': grafana(args), 'metric_time': time.time()}
|
||||
lab.evidence('telemetry.json', result)
|
||||
lab.say('PASS: real API/worker traces and related logs, metrics, privacy and Grafana provisioning')
|
||||
return result
|
||||
|
||||
|
||||
def incidents(args):
|
||||
c = lab.client(args)
|
||||
actor, bob, eve, chat = c.bootstrap()
|
||||
started = time.time()
|
||||
lab.run(args, [lab.interpreter(), '-X', 'utf8', 'tests/load.py', '--base-url', lab.base_url(args),
|
||||
'--duration', '30', '--concurrency', '4', '--output', 'evidence/load.json'])
|
||||
queue = []
|
||||
try:
|
||||
lab.compose(args, 'stop', '--timeout', '10', 'worker')
|
||||
stopped_at = time.time()
|
||||
for _ in range(3):
|
||||
item, _ = c.attachment(actor, chat)
|
||||
state = c.call('GET', '/api/v1/attachments/' + item['id'], actor=actor, schema='Attachment')['json']
|
||||
if state['status'] != 'queued':
|
||||
raise RuntimeError('Stopped worker processed a job')
|
||||
queue.append((item, job_id(args, item)))
|
||||
time.sleep(5)
|
||||
pending = logs(args, '{service_name="messenger-worker"} | event="job.started"', stopped_at)
|
||||
if any(record.get('job_id') in {job for _, job in queue} for record in pending):
|
||||
raise RuntimeError('Stopped worker emitted processing events')
|
||||
finally:
|
||||
lab.compose(args, 'start', 'worker')
|
||||
completed = []
|
||||
for item, job in queue:
|
||||
c.wait_ready(actor, item)
|
||||
completed.append(correlated(args, '{service_name="messenger-worker"} | job_id="' + job + '" | event="job.completed"', 'CONSUMER', stopped_at))
|
||||
worker_incident = {'started_at': stopped_at, 'queued_jobs': [job for _, job in queue],
|
||||
'accepted_logs': wait(lambda: logs(args, '{service_name="messenger-api"} | event="job.accepted"', stopped_at)),
|
||||
'recovered_jobs': completed, 'recovered_at': time.time()}
|
||||
try:
|
||||
lab.compose(args, 'stop', '--timeout', '10', 'db')
|
||||
db_at = time.time()
|
||||
response = c.call('GET', '/api/v1/users/me', 503, actor=actor)
|
||||
request_id = response['headers']['X-Request-Id']
|
||||
db_trace = correlated(args, '{service_name="messenger-api"} | request_id="' + request_id + '"', 'SERVER', db_at)
|
||||
db_logs = wait(lambda: logs(args, '{service_name="messenger-api"} | event="dependency.postgresql_unavailable"', db_at))
|
||||
errors = wait(lambda: prom(args, 'messenger_http_requests_total{status_class="5xx",route="/api/v1/users/me"}'))
|
||||
finally:
|
||||
lab.compose(args, 'start', 'db')
|
||||
lab.wait_ready(args)
|
||||
c.call('GET', '/api/v1/users/me', actor=actor)
|
||||
result = {'status': 'PASS', 'started_at': started, 'worker': worker_incident,
|
||||
'postgresql': {'started_at': db_at, 'request': db_trace, 'dependency_logs': db_logs[:4],
|
||||
'error_series': errors, 'recovered_at': time.time(), 'recovered_status': 200}}
|
||||
lab.evidence('incidents.json', result)
|
||||
lab.say('PASS: bounded worker and PostgreSQL incidents observed and recovered')
|
||||
return result
|
||||
|
||||
|
||||
def outage(args):
|
||||
c = lab.client(args)
|
||||
actor, bob, eve, chat = c.bootstrap()
|
||||
before = lab.states(args)
|
||||
cases = []
|
||||
for service in ('otel-collector', 'loki'):
|
||||
try:
|
||||
lab.compose(args, 'stop', '--timeout', '10', service+'-tls', service)
|
||||
start = time.monotonic()
|
||||
confirmations = []
|
||||
for index in range(6):
|
||||
confirmations.append(c.message(actor, chat, 'telemetry-outage-' + str(index))['json']['id'])
|
||||
item, _ = c.attachment(actor, chat)
|
||||
c.wait_ready(actor, item)
|
||||
time.sleep(5)
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
elapsed = time.monotonic() - start
|
||||
finally:
|
||||
lab.compose(args, 'start', service)
|
||||
lab.compose(args, 'start', service+'-tls')
|
||||
response = c.call('GET', '/api/v1/users/me', actor=actor)
|
||||
observed = correlated(args, '{service_name="messenger-api"} | request_id="' + response['headers']['X-Request-Id'] + '"', 'SERVER')
|
||||
cases.append({'stopped': service, 'duration_seconds': round(elapsed, 2),
|
||||
'confirmed_messages': len(confirmations), 'ready_attachments': 6,
|
||||
'business_ready': 200, 'telemetry_recovered': observed})
|
||||
preserved = telemetry(args)
|
||||
lab.restart(args)
|
||||
lab.wait_ready(args)
|
||||
wait(lambda: trace_data(args, preserved['api']['trace_id']))
|
||||
wait(lambda: logs(args, '{service_name="messenger-api"} | trace_id="' + preserved['api']['trace_id'] + '"'))
|
||||
wait(lambda: prom(args, 'messenger_http_requests_total', preserved['metric_time']))
|
||||
after = lab.states(args)
|
||||
if any(after[name]['oom_killed'] for name in after):
|
||||
raise RuntimeError('Container OOM observed')
|
||||
result = {'status': 'PASS', 'cases': cases, 'history_after_restart': 'PASS', 'oom_killed': False,
|
||||
'preserved_trace_id': preserved['api']['trace_id'],
|
||||
'same_volumes': all(before[name]['volumes'] == after[name]['volumes'] for name in before),
|
||||
'loss_policy': 'Bounded in-memory SDK/Collector queues; telemetry during outage may be lost.'}
|
||||
lab.evidence('outage.json', result)
|
||||
lab.say('PASS: telemetry outages do not break messages/jobs; stored telemetry survives restart')
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
mode = sys.argv[1]
|
||||
{'telemetry': telemetry, 'incidents': incidents, 'outage': outage}[mode](arguments())
|
||||
@@ -0,0 +1,204 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import time
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def check(args, lab, retry=False):
|
||||
c = lab.client(args)
|
||||
actor, bob, eve, chat = c.bootstrap()
|
||||
|
||||
def sql(statement):
|
||||
return lab.compose(args, 'exec', '-T', 'db', 'psql', '-U', 'messenger', '-d', 'messenger',
|
||||
'-v', 'ON_ERROR_STOP=1', '-At', '-c', statement, quiet=True).strip()
|
||||
|
||||
def wait(predicate, seconds=60):
|
||||
end = time.monotonic() + seconds
|
||||
while time.monotonic() < end:
|
||||
if predicate():
|
||||
return
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError('Pipeline test condition timed out')
|
||||
|
||||
def ready(att):
|
||||
done = c.wait_ready(actor, att)
|
||||
path = '/api/v1/attachments/' + att['id'] + '/content'
|
||||
raw = c.call('GET', path, actor=bob)['bytes']
|
||||
if hashlib.sha256(raw).hexdigest() != att['sha256']:
|
||||
raise RuntimeError('Original checksum changed')
|
||||
thumb = c.call('GET', path + '?variant=thumbnail', actor=bob)['bytes']
|
||||
with Image.open(io.BytesIO(thumb)) as image:
|
||||
if image.format != 'JPEG' or image.size != (256, 160):
|
||||
raise RuntimeError('Thumbnail format or size mismatch')
|
||||
if hashlib.sha256(thumb).hexdigest() != done['variants'][0]['sha256']:
|
||||
raise RuntimeError('Thumbnail checksum mismatch')
|
||||
return done
|
||||
|
||||
def duplicate(att):
|
||||
code = ('from src.storage import PostgresStore; from src.broker import publish,envelope; '
|
||||
's=PostgresStore(); s.open()\n'
|
||||
'with s.connection() as c: j=c.execute("SELECT * FROM attachment_jobs WHERE attachment_id=%s",'
|
||||
'("' + att['id'] + '",)).fetchone()\n'
|
||||
'publish(envelope(j)); publish(envelope(j)); s.close()')
|
||||
lab.compose(args, 'exec', '-T', 'api1', 'python', '-c', code, quiet=True)
|
||||
def drained():
|
||||
lines = lab.compose(args, 'exec', '-T', 'broker', 'rabbitmqctl', '-q',
|
||||
'list_queues', '-p', 'messenger', 'name', 'messages', quiet=True)
|
||||
return any(line.split() == ['attachment.process.v1', '0'] for line in lines.splitlines())
|
||||
wait(drained, 30)
|
||||
now = c.call('GET', '/api/v1/attachments/' + att['id'], actor=actor, schema='Attachment')['json']
|
||||
if now != att:
|
||||
raise RuntimeError('Duplicate delivery changed ready metadata')
|
||||
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
||||
try:
|
||||
attachment, original = c.attachment(actor, chat)
|
||||
path = '/api/v1/attachments/' + attachment['id']
|
||||
if not retry:
|
||||
from jsonschema import Draft202012Validator, FormatChecker
|
||||
job_row = json.loads(sql("SELECT row_to_json(j) FROM attachment_jobs j WHERE attachment_id='" + attachment['id'] + "'"))
|
||||
carrier = {'schema_version': 1, 'job_id': job_row['id'], 'attachment_id': attachment['id'],
|
||||
'type': 'attachment.process.v1', 'pipeline_version': 1, 'attempt': 1,
|
||||
'created_at': job_row['created_at']}
|
||||
schema = json.loads((lab.ROOT / 'contracts/jobs.schema.json').read_text())
|
||||
Draft202012Validator(schema, format_checker=FormatChecker()).validate(carrier)
|
||||
anonymous = (
|
||||
"import os,boto3; from botocore import UNSIGNED; from botocore.config import Config; "
|
||||
"from botocore.exceptions import ClientError\n"
|
||||
"c=boto3.client('s3',endpoint_url=os.environ['S3_ENDPOINT'],verify=os.environ['TLS_CA_FILE'],config=Config(signature_version=UNSIGNED,proxies={}))\n"
|
||||
"try:\n r=c.get_object(Bucket=os.environ['S3_BUCKET'],Key='system/readiness'); r['Body'].close(); status=200\n"
|
||||
"except ClientError as e:\n status=e.response['ResponseMetadata']['HTTPStatusCode']\n"
|
||||
"assert status==403; print(status)"
|
||||
)
|
||||
if lab.compose(args, 'exec', '-T', 'api1', 'python', '-c', anonymous, quiet=True).strip() != '403':
|
||||
raise RuntimeError('Anonymous S3 access allowed')
|
||||
linked = c.message(actor, chat, '', attachments=[attachment['id']])['json']
|
||||
for variant in ('original', 'thumbnail'):
|
||||
c.call('GET', path + '/content?variant=' + variant, 409, actor=bob)
|
||||
c.call('GET', path, 404, actor=eve)
|
||||
c.message(bob, chat, 'worker is stopped')
|
||||
before = lab.states(args)
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'api1-tls', 'api2-tls')
|
||||
lab.compose(args, 'restart', '--timeout', '10', 'api1', 'api2', 'broker')
|
||||
lab.compose(args, 'start', 'api1-tls', 'api2-tls')
|
||||
lab.wait_ready(args)
|
||||
after = lab.states(args)
|
||||
for name in ('api1', 'api2', 'broker'):
|
||||
if before[name]['started_at'] == after[name]['started_at'] or before[name]['volumes'] != after[name]['volumes']:
|
||||
raise RuntimeError('Queue restart evidence mismatch')
|
||||
queued = c.call('GET', path, actor=actor, schema='Attachment')['json']
|
||||
if queued['status'] != 'queued':
|
||||
raise RuntimeError('Stopped worker unexpectedly processed the upload')
|
||||
lab.compose(args, 'start', 'worker')
|
||||
done = ready(attachment)
|
||||
duplicate(done)
|
||||
c.call('GET', path + '/content?variant=crop', 404, actor=bob)
|
||||
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=bob, schema='MessagePage')['json']['items']
|
||||
if linked not in history:
|
||||
raise RuntimeError('Queued attachment message was lost')
|
||||
result = {'status': 'PASS', 'upload_with_stopped_worker': 202, 'pending_content': 409,
|
||||
'same_attachment_after_api_broker_restart': True, 'original_and_thumbnail': 'PASS',
|
||||
'duplicate_noop': 'PASS', 'job_schema': 'PASS', 'anonymous_s3': 403, 'before': before, 'after': after}
|
||||
lab.evidence('queue.json', result)
|
||||
lab.say('PASS: accepted upload survived API/broker restart; thumbnail and duplicate delivery checked')
|
||||
return result
|
||||
|
||||
job = json.loads(sql("SELECT row_to_json(j) FROM attachment_jobs j WHERE attachment_id='" + attachment['id'] + "'"))
|
||||
sql("UPDATE attachment_jobs SET staging_key='missing-test/" + attachment['id'] + "' WHERE id='" + job['id'] + "'")
|
||||
lab.compose(args, 'start', 'worker')
|
||||
wait(lambda: int(sql("SELECT attempt FROM attachment_jobs WHERE id='" + job['id'] + "'")) >= 1)
|
||||
sql("UPDATE attachment_jobs SET staging_key='" + job['staging_key'] + "' WHERE id='" + job['id'] + "'")
|
||||
ready(attachment)
|
||||
attempts = int(sql("SELECT attempt FROM attachment_jobs WHERE id='" + job['id'] + "'"))
|
||||
if attempts < 2:
|
||||
raise RuntimeError('Transient error did not cause a retry')
|
||||
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
||||
failed, _ = c.attachment(actor, chat)
|
||||
failed_job = json.loads(sql("SELECT row_to_json(j) FROM attachment_jobs j WHERE attachment_id='" + failed['id'] + "'"))
|
||||
sql("UPDATE attachment_jobs SET staging_key='missing-test/" + failed['id'] + "' WHERE id='" + failed_job['id'] + "'")
|
||||
lab.compose(args, 'start', 'worker')
|
||||
wait(lambda: sql("SELECT status FROM attachments WHERE id='" + failed['id'] + "'") == 'failed', 75)
|
||||
state = c.call('GET', '/api/v1/attachments/' + failed['id'], actor=actor, schema='Attachment')['json']
|
||||
count = int(sql("SELECT attempt FROM attachment_jobs WHERE id='" + failed_job['id'] + "'"))
|
||||
if count != 5 or state['error_code'] != 'retry_exhausted':
|
||||
raise RuntimeError('Retry budget was not enforced')
|
||||
c.call('GET', '/api/v1/attachments/' + failed['id'] + '/content', 409, actor=actor)
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=actor,
|
||||
body={'text': '', 'attachment_ids': [failed['id']]}, headers={'Idempotency-Key': uuid4().hex})
|
||||
sql("UPDATE attachment_jobs SET staging_key='" + failed_job['staging_key'] + "' WHERE id='" + failed_job['id'] + "'")
|
||||
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
||||
corrupt, _ = c.attachment(actor, chat)
|
||||
stage = sql("SELECT staging_key FROM attachment_jobs WHERE attachment_id='" + corrupt['id'] + "'")
|
||||
code = ("from src.objects import Objects; from io import BytesIO; o=Objects(admin=True); "
|
||||
"o.put(" + repr(stage) + ",BytesIO(b'broken'),6,'image/png'); o.close()")
|
||||
lab.compose(args, 'run', '--rm', '--no-deps', '-T', 'bootstrap', 'python', '-c', code, quiet=True)
|
||||
lab.compose(args, 'start', 'worker')
|
||||
wait(lambda: sql("SELECT status FROM attachments WHERE id='" + corrupt['id'] + "'") == 'failed')
|
||||
if sql("SELECT error_code FROM attachments WHERE id='" + corrupt['id'] + "'") != 'invalid_image':
|
||||
raise RuntimeError('Permanent image error was not classified')
|
||||
if sql("SELECT attempt FROM attachment_jobs WHERE attachment_id='" + corrupt['id'] + "'") != '1':
|
||||
raise RuntimeError('Permanent error retried')
|
||||
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
||||
crash, _ = c.attachment(actor, chat)
|
||||
function = 'test_pause_' + uuid4().hex
|
||||
sql("CREATE FUNCTION " + function + "() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_sleep(30); RETURN NEW; END $$; "
|
||||
"CREATE TRIGGER " + function + " BEFORE INSERT ON attachment_variants FOR EACH ROW "
|
||||
"WHEN (NEW.attachment_id='" + crash['id'] + "'::uuid) EXECUTE FUNCTION " + function + "()")
|
||||
try:
|
||||
lab.compose(args, 'start', 'worker')
|
||||
wait(lambda: sql("SELECT count(*) FROM pg_stat_activity WHERE wait_event='PgSleep'") != '0')
|
||||
if sql("SELECT status FROM attachments WHERE id='" + crash['id'] + "'") != 'processing':
|
||||
raise RuntimeError('Processing state not observed')
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
||||
finally:
|
||||
sql('DROP TRIGGER IF EXISTS ' + function + ' ON attachment_variants; DROP FUNCTION IF EXISTS ' + function + '()')
|
||||
lab.compose(args, 'start', 'worker')
|
||||
ready(crash)
|
||||
if sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='" + crash['id'] + "'") != '1':
|
||||
raise RuntimeError('Worker restart duplicated variants')
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
||||
pending, _ = c.attachment(actor, chat)
|
||||
sql("UPDATE attachment_jobs SET created_at=clock_timestamp()-INTERVAL '25 hours' "
|
||||
"WHERE attachment_id='" + pending['id'] + "'; UPDATE attachments SET "
|
||||
"updated_at=clock_timestamp()-INTERVAL '25 hours' WHERE id='" + failed['id'] + "'")
|
||||
cleanup = ('from src.storage import PostgresStore; from src.objects import Objects; '
|
||||
'from src.cleanup import clean_once; s=PostgresStore(); s.open(); o=Objects(); '
|
||||
'clean_once(s,o); o.close(); s.close()')
|
||||
lab.compose(args, 'exec', '-T', 'cleanup', 'python', '-c', cleanup, quiet=True)
|
||||
if sql("SELECT status || ':' || staging_deleted FROM attachments WHERE id='" + pending['id'] + "'") != 'queued:false':
|
||||
raise RuntimeError('Cleanup removed accepted waiting work')
|
||||
if sql("SELECT staging_deleted FROM attachments WHERE id='" + failed['id'] + "'") != 't':
|
||||
raise RuntimeError('Expired failed staging was not cleaned')
|
||||
if sql("SELECT staging_deleted FROM attachments WHERE id='" + corrupt['id'] + "'") != 'f':
|
||||
raise RuntimeError('Fresh failed staging was removed early')
|
||||
ready(attachment)
|
||||
lab.compose(args, 'start', 'worker')
|
||||
ready(pending)
|
||||
result = {'status': 'PASS', 'transient_attempts': attempts, 'max_attempts': count,
|
||||
'failed_content': 409, 'failed_link': 409, 'processing_observed': True,
|
||||
'permanent_error_attempts': 1, 'worker_stopped_before_result_commit': True,
|
||||
'staging_retention_and_pending_protection': True, 'redelivery_same_result': True}
|
||||
lab.evidence('retry.json', result)
|
||||
lab.say('PASS: retry recovery, final failed and real worker interruption')
|
||||
return result
|
||||
finally:
|
||||
lab.compose(args, 'start', 'worker')
|
||||
lab.wait_ready(args)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from scripts import lab
|
||||
args = SimpleNamespace(project=os.environ['LAB7_PROJECT'], port=int(os.environ['LAB7_PORT']),
|
||||
ttl=int(os.environ['LAB7_TTL']), test_port=18444)
|
||||
check(args, lab, retry=sys.argv[1] == 'retry')
|
||||
@@ -0,0 +1,379 @@
|
||||
import base64
|
||||
import ctypes
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import ssl
|
||||
import subprocess
|
||||
import time
|
||||
from urllib.request import build_opener, HTTPSHandler, ProxyHandler, Request
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
|
||||
import yaml
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PROJECT = os.environ.get('LAB7_PROJECT', 'mtusi-lab7')
|
||||
if not __import__('re').fullmatch(r'mtusi-lab7(?:-[a-z0-9]+)*', PROJECT):
|
||||
raise RuntimeError('Invalid lab7 project name')
|
||||
RUNTIME = ROOT / 'runtime' / PROJECT
|
||||
CA = RUNTIME / 'pki/ca.crt'
|
||||
|
||||
|
||||
def write(path, value):
|
||||
path = RUNTIME / path
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
value = yaml.safe_dump(value, sort_keys=False) if isinstance(value, dict) else value
|
||||
path.write_text(value, encoding='utf-8', newline='\n')
|
||||
path.chmod(0o644)
|
||||
|
||||
|
||||
def operator_path():
|
||||
folder = Path(os.environ.get('LOCALAPPDATA', str(Path.home() / '.local/share'))) / 'Codex/Lab7'
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
return folder / (PROJECT + ('.dpapi' if os.name=='nt' else '.enc'))
|
||||
|
||||
|
||||
def dpapi(data, decrypt=False):
|
||||
if os.name != 'nt':
|
||||
import getpass
|
||||
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
global _operator_passphrase
|
||||
if '_operator_passphrase' not in globals():
|
||||
_operator_passphrase=getpass.getpass('Operator profile passphrase: ')
|
||||
if not decrypt and _operator_passphrase!=getpass.getpass('Repeat passphrase: '):
|
||||
raise RuntimeError('Passphrase mismatch')
|
||||
if not _operator_passphrase:raise RuntimeError('Empty operator passphrase')
|
||||
salt=data[:16] if decrypt else secrets.token_bytes(16)
|
||||
key=Scrypt(salt=salt,length=32,n=32768,r=8,p=1).derive(_operator_passphrase.encode())
|
||||
if decrypt:return AESGCM(key).decrypt(data[16:28],data[28:],b'lab7-operator')
|
||||
nonce=secrets.token_bytes(12)
|
||||
return salt+nonce+AESGCM(key).encrypt(nonce,data,b'lab7-operator')
|
||||
class Blob(ctypes.Structure):
|
||||
_fields_ = [('size', ctypes.c_ulong), ('data', ctypes.POINTER(ctypes.c_ubyte))]
|
||||
buffer = ctypes.create_string_buffer(data)
|
||||
source = Blob(len(data), ctypes.cast(buffer, ctypes.POINTER(ctypes.c_ubyte)))
|
||||
output = Blob()
|
||||
function = ctypes.windll.crypt32.CryptUnprotectData if decrypt else ctypes.windll.crypt32.CryptProtectData
|
||||
if not function(ctypes.byref(source), None, None, None, None, 1, ctypes.byref(output)):
|
||||
raise RuntimeError('DPAPI operation failed')
|
||||
try:
|
||||
return ctypes.string_at(output.data, output.size)
|
||||
finally:
|
||||
ctypes.windll.kernel32.LocalFree(output.data)
|
||||
|
||||
|
||||
def operator_load():
|
||||
return json.loads(dpapi(operator_path().read_bytes(), True)) if operator_path().exists() else {}
|
||||
|
||||
|
||||
def operator_save(data):
|
||||
operator_path().write_bytes(dpapi(json.dumps(data).encode()))
|
||||
|
||||
|
||||
def new_key():
|
||||
return ec.generate_private_key(ec.SECP256R1())
|
||||
|
||||
|
||||
def private(key):
|
||||
return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption()).decode()
|
||||
|
||||
|
||||
def pki(renew=False):
|
||||
RUNTIME.parent.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
RUNTIME.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
if os.name!='nt':
|
||||
RUNTIME.parent.chmod(0o700)
|
||||
RUNTIME.chmod(0o700)
|
||||
state = operator_load()
|
||||
if not CA.exists():
|
||||
key = new_key()
|
||||
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, 'MTUSI Lab7 ' + PROJECT)])
|
||||
now = datetime.now(timezone.utc)
|
||||
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now - timedelta(minutes=5))
|
||||
.not_valid_after(now + timedelta(days=365)).add_extension(x509.BasicConstraints(ca=True, path_length=0), True)
|
||||
.add_extension(x509.KeyUsage(False, False, False, False, False, True, True, False, False), True)
|
||||
.sign(key, hashes.SHA256()))
|
||||
write('pki/ca.crt', cert.public_bytes(serialization.Encoding.PEM).decode())
|
||||
state['ca_key'] = private(key)
|
||||
operator_save(state)
|
||||
cert = x509.load_pem_x509_certificate(CA.read_bytes())
|
||||
try:
|
||||
cert.extensions.get_extension_for_class(x509.SubjectKeyIdentifier)
|
||||
except x509.ExtensionNotFound:
|
||||
key = serialization.load_pem_private_key(state['ca_key'].encode(), None)
|
||||
now = datetime.now(timezone.utc)
|
||||
cert = (x509.CertificateBuilder().subject_name(cert.subject).issuer_name(cert.subject).public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now-timedelta(minutes=5)).not_valid_after(now+timedelta(days=365))
|
||||
.add_extension(x509.BasicConstraints(ca=True,path_length=0),True)
|
||||
.add_extension(x509.KeyUsage(False,False,False,False,False,True,True,False,False),True)
|
||||
.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),False)
|
||||
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).sign(key,hashes.SHA256()))
|
||||
write('pki/ca.crt',cert.public_bytes(serialization.Encoding.PEM).decode())
|
||||
key = serialization.load_pem_private_key(state['ca_key'].encode(), None)
|
||||
now = datetime.now(timezone.utc)
|
||||
for kind, identities in [('server', ['lb','api1','api2','db','s3','broker','otel-collector','prometheus','loki','tempo','grafana','openbao']),
|
||||
('client', ['lb','api1','api2','worker','cleanup','collector','grafana','scraper','operator','wrong-role'])]:
|
||||
for identity in identities:
|
||||
path = RUNTIME / f'pki/{kind}/{identity}'
|
||||
if (path / 'client.crt').exists() and not renew:
|
||||
leaf = x509.load_pem_x509_certificate((path / 'client.crt').read_bytes())
|
||||
if leaf.not_valid_after_utc <= now:
|
||||
raise RuntimeError('Expired certificate: ' + identity)
|
||||
try:
|
||||
leaf.extensions.get_extension_for_class(x509.AuthorityKeyIdentifier)
|
||||
continue
|
||||
except x509.ExtensionNotFound:
|
||||
pass
|
||||
leaf_key = new_key()
|
||||
sans = [x509.DNSName(identity)]
|
||||
if kind == 'server' and identity in ('lb','grafana','openbao'):
|
||||
sans += [x509.DNSName('localhost'), x509.IPAddress(ipaddress.ip_address('127.0.0.1'))]
|
||||
eku = ExtendedKeyUsageOID.SERVER_AUTH if kind == 'server' else ExtendedKeyUsageOID.CLIENT_AUTH
|
||||
leaf = (x509.CertificateBuilder().subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, identity)]))
|
||||
.issuer_name(cert.subject).public_key(leaf_key.public_key()).serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now - timedelta(minutes=5)).not_valid_after(now + timedelta(days=30))
|
||||
.add_extension(x509.BasicConstraints(ca=False, path_length=None), True)
|
||||
.add_extension(x509.SubjectAlternativeName(sans), False)
|
||||
.add_extension(x509.ExtendedKeyUsage([eku]), False)
|
||||
.add_extension(x509.SubjectKeyIdentifier.from_public_key(leaf_key.public_key()),False)
|
||||
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False)
|
||||
.add_extension(x509.KeyUsage(True,False,False,False,False,False,False,False,False),True)
|
||||
.sign(key, hashes.SHA256()))
|
||||
write(f'pki/{kind}/{identity}/client.crt', leaf.public_bytes(serialization.Encoding.PEM).decode())
|
||||
write(f'pki/{kind}/{identity}/client.key', private(leaf_key))
|
||||
write(f'pki/{kind}/{identity}/bundle.pem', private(leaf_key) + leaf.public_bytes(serialization.Encoding.PEM).decode())
|
||||
|
||||
|
||||
def values():
|
||||
state = operator_load()
|
||||
if 'credentials' not in state:
|
||||
state['credentials'] = {name: secrets.token_hex(24) for name in
|
||||
['dbadmin','api_db','worker_db','cleanup_db','api_s3_id','api_s3_key','worker_s3_id','worker_s3_key',
|
||||
'cleanup_s3_id','cleanup_s3_key','admin_s3_id','admin_s3_key','api_mq','worker_mq','mqadmin',
|
||||
'api_otel','worker_otel','grafana','cursor']}
|
||||
operator_save(state)
|
||||
return state['credentials']
|
||||
|
||||
|
||||
def bundle(role):
|
||||
v = values()
|
||||
data = {'database_url': f"postgresql://{role}:{v[role+'_db']}@db:5432/messenger?sslmode=verify-full&sslrootcert=/run/pki/ca.crt",
|
||||
's3_access_key_id': v[role+'_s3_id'], 's3_secret_access_key': v[role+'_s3_key']}
|
||||
if role in ('api','worker'):
|
||||
data['broker_url'] = f"amqps://{role}:{v[role+'_mq']}@broker:5671/messenger"
|
||||
data['otel_authorization'] = 'Basic ' + base64.b64encode((role + ':' + v[role+'_otel']).encode()).decode()
|
||||
if role == 'api':
|
||||
data['cursor_key'] = v['cursor']
|
||||
return data
|
||||
|
||||
|
||||
def tls_context(server, clients=None):
|
||||
common = {'tls_certificates': [{'certificate_chain': {'filename': '/run/server/client.crt'},
|
||||
'private_key': {'filename': '/run/server/client.key'}}],
|
||||
'tls_params': {'tls_minimum_protocol_version': 'TLSv1_2'}}
|
||||
if clients:
|
||||
common['validation_context'] = {'trusted_ca': {'filename': '/run/pki/ca.crt'},
|
||||
'match_typed_subject_alt_names': [{'san_type': 'DNS','matcher': {'exact': name}} for name in clients]}
|
||||
return {'name': 'envoy.transport_sockets.tls', 'typed_config': {
|
||||
'@type': 'type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext',
|
||||
'require_client_certificate': bool(clients), 'common_tls_context': common}}
|
||||
|
||||
|
||||
def gateway(name, listeners):
|
||||
chains, clusters = [], []
|
||||
for external, internal, clients, access in listeners:
|
||||
cluster = 'local_' + str(internal)
|
||||
clusters.append({'name': cluster, 'type': 'STATIC', 'connect_timeout': '2s', 'load_assignment': {
|
||||
'cluster_name': cluster, 'endpoints': [{'lb_endpoints': [{'endpoint': {'address': {'socket_address': {
|
||||
'address': '127.0.0.1', 'port_value': internal}}}}]}]}})
|
||||
filters = [{'name':'envoy.filters.network.tcp_proxy','typed_config': {
|
||||
'@type':'type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy',
|
||||
'stat_prefix':cluster,'cluster':cluster,'idle_timeout':'65s'}}]
|
||||
if access:
|
||||
policies = {}
|
||||
for identity, pattern in access.items():
|
||||
policies[identity] = {'permissions':[{'and_rules':{'rules':[
|
||||
{'header':{'name':':path','string_match':{'safe_regex':{'regex':pattern}}}},
|
||||
{'header':{'name':':method','string_match':{'safe_regex':{'regex': '.*' if identity=='operator' else ('POST' if identity=='collector' else ('GET|POST' if name=='prometheus' else 'GET'))}}}}]}}],
|
||||
'principals':[{'authenticated':{'principal_name':{'exact':identity}}}]}
|
||||
filters = [{'name':'envoy.filters.network.http_connection_manager','typed_config': {
|
||||
'@type':'type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager',
|
||||
'stat_prefix':cluster,'codec_type':'AUTO','stream_idle_timeout':'65s',
|
||||
'route_config':{'name':'routes','virtual_hosts':[{'name':'local','domains':['*'],
|
||||
'routes':[{'match':{'prefix':'/'},'route':{'cluster':cluster,'timeout':'60s'}}]}]},
|
||||
'http_filters':[{'name':'envoy.filters.http.rbac','typed_config': {
|
||||
'@type':'type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBAC',
|
||||
'rules':{'action':'ALLOW','policies':policies}}},
|
||||
{'name':'envoy.filters.http.router','typed_config':{
|
||||
'@type':'type.googleapis.com/envoy.extensions.filters.http.router.v3.Router'}}]}}]
|
||||
chains.append({'name':name+str(external),'address':{'socket_address':{'address':'0.0.0.0','port_value':external}},
|
||||
'filter_chains':[{'transport_socket':tls_context(name, clients),'filters':filters}]})
|
||||
write('envoy/'+name+'.yaml', {'static_resources':{'listeners':chains,'clusters':clusters}})
|
||||
|
||||
|
||||
def configuration():
|
||||
v = values()
|
||||
write('db/password', v['dbadmin'])
|
||||
write('operator/database_url', f"postgresql://messenger:{v['dbadmin']}@db:5432/messenger?sslmode=verify-full&sslrootcert=/run/pki/ca.crt")
|
||||
write('operator/s3_admin_access_key_id', v['admin_s3_id'])
|
||||
write('operator/s3_admin_secret_access_key', v['admin_s3_key'])
|
||||
write('operator/s3_access_key_id', v['api_s3_id'])
|
||||
write('operator/s3_secret_access_key', v['api_s3_key'])
|
||||
write('grafana/password', v['grafana'])
|
||||
write('db/pg_hba.conf', 'local all all trust\nhostnossl all all all reject\nhostssl messenger all all scram-sha-256\n')
|
||||
accounts = []
|
||||
rules = {'api':['Read:messenger-attachments/originals/*','Read:messenger-attachments/variants/*',
|
||||
'Read:messenger-attachments/system/*','Write:messenger-attachments/staging/*','List:messenger-attachments'],
|
||||
'worker':['Read:messenger-attachments/staging/*','Write:messenger-attachments/originals/*',
|
||||
'Write:messenger-attachments/variants/*'],
|
||||
'cleanup':['Write:messenger-attachments/staging/*','Write:messenger-attachments/originals/*',
|
||||
'Write:messenger-attachments/variants/*']}
|
||||
for role, actions in rules.items():
|
||||
accounts.append({'name':role,'credentials':[{'accessKey':v[role+'_s3_id'],'secretKey':v[role+'_s3_key']}], 'actions':actions})
|
||||
accounts.append({'name':'operator','credentials':[{'accessKey':v['admin_s3_id'],'secretKey':v['admin_s3_key']}],
|
||||
'actions':['Admin','Read','Write','List']})
|
||||
write('s3/config.json', json.dumps({'identities':accounts}))
|
||||
write('broker/rabbitmq.conf', 'listeners.tcp = none\nlisteners.ssl.default = 5671\nssl_options.cacertfile = /run/pki/ca.crt\nssl_options.certfile = /run/server/client.crt\nssl_options.keyfile = /run/server/client.key\nssl_options.verify = verify_none\nprometheus.tcp.ip = 127.0.0.1\nmanagement.tcp.ip = 127.0.0.1\nmanagement.tcp.port = 15672\ndefinitions.import_backend = local_filesystem\ndefinitions.local.path = /run/config/definitions.json\n')
|
||||
users = [{'name':role,'password_hash':base64.b64encode((salt:=secrets.token_bytes(4))+hashlib.sha256(salt+v[key].encode()).digest()).decode(),
|
||||
'hashing_algorithm':'rabbit_password_hashing_sha256','tags': 'administrator' if role=='operator' else ''}
|
||||
for role,key in [('operator','mqadmin'),('api','api_mq'),('worker','worker_mq')]]
|
||||
permissions=[{'user':'operator','vhost':'messenger','configure':'.*','write':'.*','read':'.*'},
|
||||
{'user':'api','vhost':'messenger','configure':'^$','write':'^(attachment.jobs|attachment.process.v1)$','read':'^$'},
|
||||
{'user':'worker','vhost':'messenger','configure':'^$','write':'^(attachment.jobs|attachment.process.v1)$','read':'^attachment.process.v1$'}]
|
||||
write('broker/definitions.json',json.dumps({'users':users,'vhosts':[{'name':'messenger'}],'permissions':permissions,
|
||||
'queues':[{'name':'attachment.process.v1','vhost':'messenger','durable':True,'auto_delete':False,'arguments':{}}],
|
||||
'exchanges':[{'name':'attachment.jobs','vhost':'messenger','type':'direct','durable':True,'auto_delete':False,'internal':False,'arguments':{}}],
|
||||
'bindings':[{'source':'attachment.jobs','vhost':'messenger','destination':'attachment.process.v1','destination_type':'queue','routing_key':'attachment.process.v1','arguments':{}}]}))
|
||||
gateway('api1',[(8443,8080,['lb'],None)])
|
||||
gateway('api2',[(8443,8080,['lb'],None)])
|
||||
gateway('s3',[(9000,9001,None,None)])
|
||||
gateway('otel-collector',[(4318,4319,None,None),(8889,8890,['scraper','operator'],None)])
|
||||
gateway('loki',[(3100,3101,['collector','grafana','operator'],{
|
||||
'collector':r'/otlp/v1/logs','grafana':r'/(loki/api/.*|ready)','operator':r'/.*'})])
|
||||
gateway('tempo',[(4318,4319,['collector','operator'],None),(3200,3201,['grafana','operator'],{
|
||||
'grafana':r'/api/.*','operator':r'/.*'})])
|
||||
gateway('prometheus',[(9090,9091,['grafana','operator'],{'grafana':r'/api/v1/(query.*|labels.*|label/.*|series.*|status/.*|metadata.*|exemplars.*)', 'operator':r'/.*'})])
|
||||
write('bao/config.json', json.dumps({'ui':False,'api_addr':'https://openbao:8200',
|
||||
'cluster_addr':'https://127.0.0.1:8201','storage':{'raft':{'path':'/bao/data','node_id':'lab7'}},
|
||||
'listener':{'tcp':{'address':'0.0.0.0:8200','cluster_address':'127.0.0.1:8201',
|
||||
'tls_cert_file':'/run/server/client.crt','tls_key_file':'/run/server/client.key',
|
||||
'tls_client_ca_file':'/run/pki/ca.crt','tls_min_version':'tls12'}}}))
|
||||
collector = yaml.safe_load((ROOT/'infra/otel/collector.yaml').read_text())
|
||||
collector['receivers']['otlp']['protocols']['http']={'endpoint':'127.0.0.1:4319','auth':{'authenticator':'basicauth/server'}}
|
||||
collector['exporters']['prometheus']['endpoint']='127.0.0.1:8890'
|
||||
collector['exporters'].pop('otlp_grpc/tempo',None)
|
||||
collector['exporters']['otlphttp/tempo']={'endpoint':'https://tempo:4318','tls':{'ca_file':'/run/pki/ca.crt','cert_file':'/run/identity/client.crt','key_file':'/run/identity/client.key'},'sending_queue':{'queue_size':128},'timeout':'2s'}
|
||||
collector['exporters']['otlphttp/loki']['endpoint']='https://loki:3100/otlp'
|
||||
collector['exporters']['otlphttp/loki']['tls']={'ca_file':'/run/pki/ca.crt','cert_file':'/run/identity/client.crt','key_file':'/run/identity/client.key'}
|
||||
collector['service']['pipelines']['traces']['exporters']=['otlphttp/tempo']
|
||||
collector['extensions']['health_check']['endpoint']='127.0.0.1:13133'
|
||||
collector['extensions']['basicauth/server']={'htpasswd':{'file':'/run/config/htpasswd'}}
|
||||
collector['service']['extensions'].append('basicauth/server')
|
||||
write('otel/collector.yaml',collector)
|
||||
write('otel/htpasswd',''.join(role+':{SHA}'+base64.b64encode(hashlib.sha1(v[role+'_otel'].encode()).digest()).decode()+'\n' for role in ('api','worker')))
|
||||
write('otel/prometheus.yaml',{'global':{'scrape_interval':'5s'},'scrape_configs':[{'job_name':'messenger','scheme':'https',
|
||||
'tls_config':{'ca_file':'/run/pki/ca.crt','cert_file':'/run/identity/client.crt','key_file':'/run/identity/client.key'},
|
||||
'static_configs':[{'targets':['otel-collector:8889']}]}]})
|
||||
loki=yaml.safe_load((ROOT/'infra/otel/loki.yaml').read_text());loki['server'].update(http_listen_address='127.0.0.1',http_listen_port=3101,grpc_listen_address='127.0.0.1')
|
||||
loki['common']['instance_addr']='127.0.0.1';write('otel/loki.yaml',loki)
|
||||
tempo=yaml.safe_load((ROOT/'infra/otel/tempo.yaml').read_text());tempo['server'].update(http_listen_address='127.0.0.1',http_listen_port=3201,grpc_listen_address='127.0.0.1')
|
||||
tempo['distributor']['receivers']['otlp']['protocols']={'http':{'endpoint':'127.0.0.1:4319'}};write('otel/tempo.yaml',tempo)
|
||||
write('grafana/provisioning/dashboards/dashboards.yaml',yaml.safe_load((ROOT/'infra/grafana/provisioning/dashboards/dashboards.yaml').read_text(encoding='utf-8')))
|
||||
sources=yaml.safe_load((ROOT/'infra/grafana/provisioning/datasources/sources.yaml').read_text())
|
||||
for source in sources['datasources']:
|
||||
source['url']=source['url'].replace('http://','https://')
|
||||
source.setdefault('jsonData',{}).update(tlsAuth=True,tlsAuthWithCACert=True)
|
||||
source['secureJsonData']={'tlsCACert':CA.read_text(),'tlsClientCert':(RUNTIME/'pki/client/grafana/client.crt').read_text(),
|
||||
'tlsClientKey':(RUNTIME/'pki/client/grafana/client.key').read_text()}
|
||||
write('grafana/provisioning/datasources/sources.yaml',sources)
|
||||
|
||||
|
||||
def negative_certificates():
|
||||
state=operator_load()
|
||||
root=x509.load_pem_x509_certificate(CA.read_bytes())
|
||||
for identity in ('foreign','expired'):
|
||||
path=RUNTIME/f'pki/client/{identity}/client.crt'
|
||||
if path.exists():continue
|
||||
signer=new_key() if identity=='foreign' else serialization.load_pem_private_key(state['ca_key'].encode(),None)
|
||||
key=new_key()
|
||||
now=datetime.now(timezone.utc)
|
||||
issuer=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'Foreign CA')]) if identity=='foreign' else root.subject
|
||||
cert=(x509.CertificateBuilder().subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'lb')]))
|
||||
.issuer_name(issuer).public_key(key.public_key()).serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now-timedelta(days=2)).not_valid_after(now-timedelta(days=1) if identity=='expired' else now+timedelta(days=1))
|
||||
.add_extension(x509.SubjectAlternativeName([x509.DNSName('lb')]),False)
|
||||
.add_extension(x509.BasicConstraints(False,None),True)
|
||||
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]),False)
|
||||
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(signer.public_key()),False).sign(signer,hashes.SHA256()))
|
||||
write(f'pki/client/{identity}/client.crt',cert.public_bytes(serialization.Encoding.PEM).decode())
|
||||
write(f'pki/client/{identity}/client.key',private(key))
|
||||
|
||||
|
||||
def bao_request(path, data=None, token=None, identity='operator', method=None):
|
||||
context=ssl.create_default_context(cafile=str(CA))
|
||||
context.load_cert_chain(str(RUNTIME/f'pki/client/{identity}/client.crt'),str(RUNTIME/f'pki/client/{identity}/client.key'))
|
||||
opener=build_opener(ProxyHandler({}),HTTPSHandler(context=context))
|
||||
headers={'Content-Type':'application/json'}
|
||||
if token:headers['X-Vault-Token']=token
|
||||
port=int(os.environ.get('BAO_PORT','18200'))
|
||||
raw=json.dumps(data).encode() if data is not None else None
|
||||
with opener.open(Request(f'https://127.0.0.1:{port}/v1/'+path,data=raw,headers=headers,method=method),timeout=10) as r:
|
||||
payload=r.read()
|
||||
return json.loads(payload) if payload else {}
|
||||
|
||||
|
||||
def unseal():
|
||||
state=operator_load()
|
||||
for share in state.get('unseal',[]):
|
||||
if not bao_request('sys/seal-status')['sealed']:break
|
||||
bao_request('sys/unseal',{'key':share})
|
||||
|
||||
|
||||
def bootstrap_bao():
|
||||
state=operator_load()
|
||||
if not bao_request('sys/init')['initialized']:
|
||||
result=bao_request('sys/init',{'secret_shares':5,'secret_threshold':3})
|
||||
state.update(unseal=result['keys_base64'],root_token=result['root_token'],configured=False)
|
||||
operator_save(state)
|
||||
unseal()
|
||||
if state.get('configured'):
|
||||
if state.pop('renew_roles',False):
|
||||
token=bao_request('auth/cert/login',{'name':'operator'})['auth']['client_token']
|
||||
register_roles(token)
|
||||
bao_request('auth/token/revoke-self',{},token)
|
||||
operator_save(state)
|
||||
return
|
||||
token=state['root_token']
|
||||
if 'secret/' not in bao_request('sys/mounts',token=token):
|
||||
bao_request('sys/mounts/secret',{'type':'kv','options':{'version':'2'}},token)
|
||||
if 'cert/' not in bao_request('sys/auth',token=token):
|
||||
bao_request('sys/auth/cert',{'type':'cert'},token)
|
||||
for role in ('api','worker','cleanup'):
|
||||
bao_request('secret/data/'+role,{'data':bundle(role)},token)
|
||||
policy='path "secret/data/'+role+'" { capabilities = ["read"] }\n'
|
||||
bao_request('sys/policies/acl/lab7-'+role,{'policy':policy},token,method='PUT')
|
||||
operator_policy='''path "secret/*" { capabilities = ["create", "read", "update", "delete", "list"] }
|
||||
path "auth/cert/*" { capabilities = ["create", "read", "update", "delete", "list", "sudo"] }
|
||||
path "sys/policies/acl/lab7-*" { capabilities = ["create", "read", "update", "delete", "list"] }
|
||||
path "sys/seal" { capabilities = ["update", "sudo"] }
|
||||
'''
|
||||
bao_request('sys/policies/acl/lab7-operator',{'policy':operator_policy},token,method='PUT')
|
||||
register_roles(token)
|
||||
bao_request('auth/token/revoke-self',{},token)
|
||||
state.pop('root_token',None);state['configured']=True;operator_save(state)
|
||||
|
||||
|
||||
def register_roles(token):
|
||||
for identity,role in [('api1','api'),('api2','api'),('worker','worker'),('cleanup','cleanup'),('operator','operator')]:
|
||||
bao_request('auth/cert/certs/'+identity,{'certificate':CA.read_text(),
|
||||
'allowed_dns_sans':[identity],'token_policies':['lab7-'+role],'token_ttl':int(os.environ.get('BAO_TOKEN_TTL','900')),'token_max_ttl':max(4,int(os.environ.get('BAO_TOKEN_TTL','900'))*4)},token)
|
||||
@@ -0,0 +1,145 @@
|
||||
import json
|
||||
import ssl
|
||||
import sys
|
||||
from urllib.request import build_opener, HTTPSHandler, ProxyHandler, Request
|
||||
|
||||
|
||||
def opener(identity='operator', trusted=True):
|
||||
context=ssl.create_default_context(cafile='/run/pki/ca.crt') if trusted else ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
if identity:
|
||||
context.load_cert_chain('/run/all-pki/client/'+identity+'/client.crt','/run/all-pki/client/'+identity+'/client.key')
|
||||
return build_opener(ProxyHandler({}),HTTPSHandler(context=context))
|
||||
|
||||
|
||||
def fetch(url, identity='operator', data=None, headers=None, method=None):
|
||||
raw=json.dumps(data).encode() if data is not None else None
|
||||
with opener(identity).open(Request(url,data=raw,headers={'Accept':'application/json','Content-Type':'application/json',**(headers or {})},method=method),timeout=10) as r:
|
||||
raw=r.read()
|
||||
return json.loads(raw) if raw else {}
|
||||
|
||||
|
||||
def secret(role, identity):
|
||||
auth=fetch('https://openbao:8200/v1/auth/cert/login',identity,{'name':identity})['auth']
|
||||
return fetch('https://openbao:8200/v1/secret/data/'+role,identity,
|
||||
headers={'X-Vault-Token':auth['client_token']})['data']['data']
|
||||
|
||||
|
||||
def main():
|
||||
spec=json.load(sys.stdin)
|
||||
if spec['op']=='fetch':
|
||||
print(json.dumps([fetch(url) for url in spec['urls']]))
|
||||
elif spec['op']=='tls':
|
||||
import socket
|
||||
results={}
|
||||
reasons={}
|
||||
for server in ('api1','api2'):
|
||||
for identity in (None,'wrong-role','foreign','expired','lb'):
|
||||
context=ssl.create_default_context(cafile='/run/pki/ca.crt')
|
||||
if identity:
|
||||
context.load_cert_chain('/run/all-pki/client/'+identity+'/client.crt','/run/all-pki/client/'+identity+'/client.key')
|
||||
try:
|
||||
with socket.create_connection((server,8443),timeout=5) as raw:
|
||||
with context.wrap_socket(raw,server_hostname=server) as connection:
|
||||
connection.sendall(b'GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n')
|
||||
data=connection.recv(4096)
|
||||
success=b'200 OK' in data
|
||||
except (TimeoutError,ConnectionRefusedError):
|
||||
raise RuntimeError('TLS test endpoint unavailable') from None
|
||||
except (ssl.SSLError,ConnectionResetError) as error:
|
||||
reasons[server+':'+str(identity)]=type(error).__name__
|
||||
success=False
|
||||
results[server+':'+str(identity)]=success
|
||||
try:
|
||||
with socket.create_connection((server,8080),timeout=2):
|
||||
results[server+':plaintext']=True
|
||||
except OSError:
|
||||
results[server+':plaintext']=False
|
||||
results['reject_reasons']=reasons
|
||||
print(json.dumps(results))
|
||||
elif spec['op']=='audit':
|
||||
import socket
|
||||
results={}
|
||||
hidden={'api1':[8080],'api2':[8080],'s3':[7333,8080,8888,9333,19001],
|
||||
'broker':[4369,5672,15672,15692,25672],'otel-collector':[4319,8890,8888,13133],
|
||||
'loki':[3101,9095],'tempo':[3201,4319,9095],'prometheus':[9091],'openbao':[8201]}
|
||||
for host,ports in hidden.items():
|
||||
for port in ports:
|
||||
try:
|
||||
with socket.create_connection((host,port),timeout=1):results[host+':'+str(port)]=False
|
||||
except (ConnectionRefusedError,TimeoutError):results[host+':'+str(port)]=True
|
||||
print(json.dumps(results))
|
||||
elif spec['op']=='rights':
|
||||
import boto3,pika
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
from pika.exceptions import ChannelClosedByBroker
|
||||
results={}
|
||||
for role,identity in [('api','api1'),('worker','worker')]:
|
||||
v=secret(role,identity)
|
||||
c=boto3.client('s3',endpoint_url='https://s3:9000',verify='/run/pki/ca.crt',
|
||||
aws_access_key_id=v['s3_access_key_id'],aws_secret_access_key=v['s3_secret_access_key'],
|
||||
config=Config(signature_version='s3v4',proxies={},retries={'total_max_attempts':1}))
|
||||
operation=(lambda:c.get_object(Bucket='messenger-attachments',Key='staging/forbidden')) if role=='api' else (lambda:c.get_object(Bucket='messenger-attachments',Key='system/readiness'))
|
||||
try:
|
||||
operation();results[role+':s3_denied']=False
|
||||
except ClientError as error:
|
||||
results[role+':s3_denied']=error.response['ResponseMetadata']['HTTPStatusCode']==403
|
||||
try:
|
||||
c.create_bucket(Bucket='forbidden-security-probe');results[role+':bucket_admin_denied']=False
|
||||
except ClientError as error:
|
||||
results[role+':bucket_admin_denied']=error.response['ResponseMetadata']['HTTPStatusCode']==403
|
||||
params=pika.URLParameters(v['broker_url']);params.ssl_options=pika.SSLOptions(ssl.create_default_context(cafile='/run/pki/ca.crt'),'broker')
|
||||
conn=pika.BlockingConnection(params)
|
||||
try:
|
||||
ch=conn.channel();ch.queue_declare(queue='attachment.process.v1',passive=True)
|
||||
results[role+':amqps']=True
|
||||
try:
|
||||
ch.basic_get(queue='attachment.process.v1') if role=='api' else ch.queue_declare(queue='forbidden')
|
||||
results[role+':broker_denied']=False
|
||||
except ChannelClosedByBroker as error:
|
||||
results[role+':broker_denied']=error.reply_code==403
|
||||
finally:conn.close()
|
||||
from urllib.error import HTTPError
|
||||
for label,url,identity in [('grafana_ingest','https://loki:3100/otlp/v1/logs','grafana'),('collector_query','https://loki:3100/loki/api/v1/query_range','collector'),('anonymous_otlp','https://otel-collector:4318/v1/logs',None)]:
|
||||
try:
|
||||
fetch(url,identity,{} if label!='collector_query' else None);results[label]=False
|
||||
except HTTPError as error:
|
||||
results[label]=error.code in (401,403);error.close()
|
||||
print(json.dumps(results))
|
||||
elif spec['op']=='argon2':
|
||||
import time,statistics
|
||||
from argon2 import PasswordHasher
|
||||
h=PasswordHasher(memory_cost=19456,time_cost=2,parallelism=1)
|
||||
hashed=h.hash('synthetic-benchmark-password')
|
||||
h.verify(hashed,'synthetic-benchmark-password')
|
||||
timings={}
|
||||
for name,operation in [('hash',lambda:h.hash('synthetic-benchmark-password')),('verify',lambda:h.verify(hashed,'synthetic-benchmark-password'))]:
|
||||
values=[]
|
||||
for _ in range(30):
|
||||
started=time.perf_counter();operation();values.append((time.perf_counter()-started)*1000)
|
||||
timings[name]={'p50_ms':round(statistics.median(values),3),'p95_ms':round(sorted(values)[28],3),'samples':30}
|
||||
print(json.dumps({'timings':timings,'context':'Linux application image, one CPU'}))
|
||||
elif spec['op']=='database':
|
||||
import psycopg
|
||||
results={}
|
||||
for role,identity in [('api','api1'),('worker','worker'),('cleanup','cleanup')]:
|
||||
values=secret(role,identity)
|
||||
with psycopg.connect(values['database_url'],autocommit=True) as db:
|
||||
results[role+':tls']=db.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()[0]
|
||||
try:
|
||||
db.execute('CREATE TABLE forbidden_probe(id int)')
|
||||
results[role+':ddl_denied']=False
|
||||
db.execute('DROP TABLE forbidden_probe')
|
||||
except psycopg.errors.InsufficientPrivilege:
|
||||
results[role+':ddl_denied']=True
|
||||
if role!='api':
|
||||
try:
|
||||
db.execute('SELECT password_hash FROM users LIMIT 1')
|
||||
results[role+':users_denied']=False
|
||||
except psycopg.errors.InsufficientPrivilege:
|
||||
results[role+':users_denied']=True
|
||||
print(json.dumps(results))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
python "%~dp0lab.py" restart
|
||||
exit /b %errorlevel%
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
TASK_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
exec python3 "$TASK_DIR/lab.py" restart
|
||||
@@ -0,0 +1,147 @@
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import ssl
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request
|
||||
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
from scripts import lab, provision as p
|
||||
from scripts.observability_checks import arguments, probe
|
||||
|
||||
|
||||
def denied(function, allowed=(400,403)):
|
||||
try:
|
||||
function()
|
||||
except HTTPError as error:
|
||||
status=error.code;error.close()
|
||||
if status not in allowed:raise RuntimeError('Unexpected deny status: '+str(status))
|
||||
return status
|
||||
raise RuntimeError('Forbidden operation was permitted')
|
||||
|
||||
|
||||
def tls(args):
|
||||
p.negative_certificates()
|
||||
c=lab.client(args)
|
||||
c.call('GET','/health/live',schema='Health')
|
||||
results=probe(args,{'op':'tls'})
|
||||
for server in ('api1','api2'):
|
||||
for identity in ('None','wrong-role','foreign','expired'):
|
||||
if results[server+':'+identity]:raise RuntimeError('Unauthorized TLS identity reached API')
|
||||
if not results[server+':lb'] or results[server+':plaintext']:
|
||||
raise RuntimeError('mTLS positive/plaintext boundary failed')
|
||||
for name in ('untrusted-ca','wrong-hostname'):
|
||||
context=ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) if name=='untrusted-ca' else ssl.create_default_context(cafile=lab.environment(args)['CA_FILE'])
|
||||
try:
|
||||
with socket.create_connection(('127.0.0.1',args.port),timeout=5) as raw:
|
||||
with context.wrap_socket(raw,server_hostname='localhost' if name=='untrusted-ca' else 'wrong.lab'):pass
|
||||
except ssl.SSLCertVerificationError:
|
||||
results[name]='CERTIFICATE_VERIFY_FAILED'
|
||||
else:raise RuntimeError('Bad external TLS trust accepted')
|
||||
lab.evidence('tls.json',{'status':'PASS','checks':results})
|
||||
lab.say('PASS: external CA/hostname, both mTLS identities, foreign CA, expiry and no plaintext bypass')
|
||||
return results
|
||||
|
||||
|
||||
def policies(args):
|
||||
result={}
|
||||
result['wrong_certificate_role']=denied(lambda:p.bao_request('auth/cert/login',{'name':'api1'},identity='wrong-role'))
|
||||
result['local_boundaries']=probe(args,{'op':'audit'})
|
||||
if not all(result['local_boundaries'].values()):raise RuntimeError('Unexpected plaintext/admin listener exposed')
|
||||
for identity,role in [('api1','api'),('api2','api'),('worker','worker'),('cleanup','cleanup')]:
|
||||
auth=p.bao_request('auth/cert/login',{'name':identity},identity=identity)['auth']
|
||||
token=auth['client_token']
|
||||
own=p.bao_request('secret/data/'+role,token=token,identity=identity)['data']['data']
|
||||
result[identity]={'own_secret':True,'ttl_seconds':auth['lease_duration']}
|
||||
other='api' if role!='api' else 'worker'
|
||||
result[identity]['other_secret']=denied(lambda:p.bao_request('secret/data/'+other,token=token,identity=identity))
|
||||
result[identity]['write_policy']=denied(lambda:p.bao_request('sys/policies/acl/forbidden',{'policy':''},token,identity,method='PUT'))
|
||||
p.bao_request('auth/token/revoke-self',{},token,identity)
|
||||
result[identity]['revoked_token']=denied(lambda:p.bao_request('secret/data/'+role,token=token,identity=identity))
|
||||
if role!='api' and ('cursor_key' in own or 'api' in own['database_url'].split('@')[0]):
|
||||
raise RuntimeError('Wrong secret bundle')
|
||||
result['database']=probe(args,{'op':'database'})
|
||||
if not all(result['database'].values()):raise RuntimeError('Database role check failed')
|
||||
result['dependencies']=probe(args,{'op':'rights'})
|
||||
if not all(result['dependencies'].values()):raise RuntimeError('Dependency ACL check failed')
|
||||
for name, state in lab.states(args).items():
|
||||
if name in ('api1','api2','worker') and state['user']!='messenger':
|
||||
raise RuntimeError('Application user is not non-root')
|
||||
if 'root_token' in p.operator_load():raise RuntimeError('Initial root token not revoked')
|
||||
lab.evidence('policies.json',{'status':'PASS','results':result})
|
||||
lab.say('PASS: scoped OpenBao policies, revoked tokens, DB/S3/broker/telemetry permissions')
|
||||
return result
|
||||
|
||||
|
||||
def limits(args):
|
||||
c=lab.client(args)
|
||||
c.call('POST','/api/v1/users',413,raw=b' '*65537,headers={'Content-Type':'application/json'})
|
||||
def chunks():
|
||||
for _ in range(17):yield b' '*4096
|
||||
c.call('POST','/api/v1/users',413,raw=chunks(),headers={'Content-Type':'application/json'})
|
||||
authorization='Basic '+base64.b64encode(b'unknown:wrong-password').decode()
|
||||
def login(_):
|
||||
return c.call('POST','/api/v1/auth/sessions',[401,429],headers={'Authorization':authorization})
|
||||
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||
replies=list(pool.map(login,range(60)))
|
||||
rejected=[r for r in replies if r['status']==429]
|
||||
if not rejected or not all(r['headers'].get('Retry-After') for r in rejected):
|
||||
raise RuntimeError('No valid login rate limit observed')
|
||||
time.sleep(2)
|
||||
actor=c.user('after_rate_limit')
|
||||
c.call('GET','/api/v1/users/me',actor=actor)
|
||||
measured=probe(args,{'op':'argon2'})
|
||||
timings=measured['timings']
|
||||
result={'status':'PASS','json_limit_bytes':65536,'chunked_limit':'PASS','login_429':len(rejected),
|
||||
'retry_after':'PASS','recovered_login':201,'measurement_context':measured['context'],'argon2id':{'memory_kib':19456,'t':2,'p':1,'timings':timings}}
|
||||
lab.evidence('limits.json',result)
|
||||
lab.say('PASS: JSON/chunked limits, login 429/Retry-After, Argon2id measurements')
|
||||
return result
|
||||
|
||||
|
||||
def bao_expiry(args):
|
||||
import argparse
|
||||
test=argparse.Namespace(project=args.project+'-bao-ttl',port=args.test_port,ttl=3600,
|
||||
test_port=args.test_port,grafana_port=3311,action='start')
|
||||
try:
|
||||
lab.setup(test)
|
||||
lab.start(test)
|
||||
lab.run(test,[lab.interpreter(),'-X','utf8','scripts/security_checks.py','bao-expiry'])
|
||||
finally:
|
||||
lab.compose(test,'down','--timeout','10')
|
||||
|
||||
|
||||
def sealed_case(args):
|
||||
c=lab.client(args)
|
||||
actor=c.user('bao_expiry')
|
||||
c.call('GET','/api/v1/users/me',actor=actor)
|
||||
auth=p.bao_request('auth/cert/login',{'name':'operator'})['auth']
|
||||
try:
|
||||
p.bao_request('sys/seal',{},auth['client_token'])
|
||||
time.sleep(5)
|
||||
c.call('GET','/health/live',schema='Health')
|
||||
c.call('GET','/health/ready',503)
|
||||
c.call('GET','/api/v1/users/me',503,actor=actor)
|
||||
finally:
|
||||
p.unseal()
|
||||
lab.wait_ready(args)
|
||||
c.call('GET','/api/v1/users/me',actor=actor)
|
||||
result={'status':'PASS','service_token_ttl':2,'while_sealed':{'live':200,'ready':503,'business':503},
|
||||
'after_unseal':200,'old_session_preserved':True,'operator_unseal_outside_containers':True}
|
||||
lab.evidence('bao-expiry.json',result)
|
||||
lab.say('PASS: sealed OpenBao, bounded credential cache and recovery with old session')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
args=arguments()
|
||||
if sys.argv[1] in ('tls-check','security-check'):tls(args)
|
||||
if sys.argv[1] in ('policy-check','security-check'):policies(args)
|
||||
if sys.argv[1]=='security-check':limits(args)
|
||||
if sys.argv[1]=='bao-check':bao_expiry(args)
|
||||
if sys.argv[1]=='bao-expiry':sealed_case(args)
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
python "%~dp0lab.py" stop-one
|
||||
exit /b %errorlevel%
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?missing TARGET_INSTANCE_ID}"
|
||||
TASK_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
exec python3 "$TASK_DIR/lab.py" stop-one
|
||||
@@ -0,0 +1,118 @@
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ENVOY = 'envoyproxy/envoy:v1.40.2@sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb'
|
||||
BAO = 'openbao/openbao:2.7.3@sha256:ba4b133eb9586630024e71a617e66f37f29cc3534cdd46a6233e098ceded8dc9'
|
||||
|
||||
|
||||
def certs(server=None, client=None):
|
||||
mounts = ['./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro']
|
||||
if server:
|
||||
mounts.append(f'./runtime/${{COMPOSE_PROJECT_NAME}}/pki/server/{server}:/run/server:ro')
|
||||
if client:
|
||||
mounts.append(f'./runtime/${{COMPOSE_PROJECT_NAME}}/pki/client/{client}:/run/identity:ro')
|
||||
return mounts
|
||||
|
||||
|
||||
def render():
|
||||
base = yaml.safe_load((ROOT/'infra/base-compose.yaml').read_text(encoding='utf-8'))
|
||||
original = base['services']
|
||||
services = deepcopy(original)
|
||||
for service in services.values():
|
||||
service.pop('secrets', None)
|
||||
service.pop('networks', None)
|
||||
service.pop('depends_on', None)
|
||||
service['mem_limit'] = service.get('mem_limit','512m')
|
||||
service['cpus'] = 1.0
|
||||
app_environment = deepcopy(original['api1']['environment'])
|
||||
app_environment.update(APP_HOST='127.0.0.1', SERVICE_VERSION='lab7', TLS_CA_FILE='/run/pki/ca.crt',
|
||||
S3_ENDPOINT='https://s3:9000',S3_BUCKET='messenger-attachments',
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT='https://otel-collector:4318')
|
||||
for key in ('DATABASE_URL_FILE','CURSOR_SECRET_FILE','S3_ACCESS_KEY_ID_FILE','S3_SECRET_ACCESS_KEY_FILE','BROKER_URL_FILE'):
|
||||
app_environment[key] = app_environment[key].replace('/run/secrets/','/run/runtime/')
|
||||
for name in ('api1','api2','worker','cleanup'):
|
||||
service = services[name]
|
||||
role = 'api' if name.startswith('api') else name
|
||||
service['image']='mtusi-messenger:lab7'
|
||||
service['environment']=dict(app_environment,SERVICE_IDENTITY=name,SECRET_ROLE=role)
|
||||
if role=='cleanup':
|
||||
for key in ('CURSOR_SECRET_FILE','BROKER_URL_FILE'):
|
||||
service['environment'].pop(key)
|
||||
service['volumes']=certs(client=name)
|
||||
service['tmpfs']=['/run/runtime:uid=10001,gid=10001,mode=0700','/tmp:uid=10001,gid=10001,mode=0700']
|
||||
service['cap_drop']=['ALL']
|
||||
service['security_opt']=['no-new-privileges:true']
|
||||
service['stop_grace_period']='20s'
|
||||
db=services['db']
|
||||
db['environment']['POSTGRES_PASSWORD_FILE']='/run/config/password'
|
||||
db['volumes'] += ['./runtime/${COMPOSE_PROJECT_NAME}/db:/run/config:ro'] + certs(server='db')
|
||||
db['entrypoint']=['/bin/sh','-c','install -o postgres -g postgres -m 600 /run/server/client.key /var/lib/postgresql/server.key; exec docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/run/server/client.crt -c ssl_key_file=/var/lib/postgresql/server.key -c hba_file=/run/config/pg_hba.conf']
|
||||
storage=services['s3-storage']
|
||||
storage['command']=[str(x).replace('-ip=s3-storage','-ip=127.0.0.1').replace('-ip.bind=0.0.0.0','-ip.bind=127.0.0.1') for x in storage['command']]
|
||||
storage['networks']={'default':{'aliases':['s3']}}
|
||||
s3=services['s3']
|
||||
s3['network_mode']='service:s3-storage'
|
||||
s3['command']=['s3','-filer=127.0.0.1:8888','-port=9001','-ip.bind=127.0.0.1',
|
||||
'-config=/run/config/config.json','-iam=false','-port.iceberg=0','-port.lance=0']
|
||||
s3['volumes']=['./runtime/${COMPOSE_PROJECT_NAME}/s3:/run/config:ro']
|
||||
s3['depends_on']={'s3-storage':{'condition':'service_healthy'}}
|
||||
broker=services['broker']
|
||||
broker['environment']['RABBITMQ_CONFIG_FILE']='/run/config/rabbitmq'
|
||||
broker['environment']['RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS']='-kernel inet_dist_use_interface {127,0,0,1}'
|
||||
broker['environment']['ERL_EPMD_ADDRESS']='127.0.0.1'
|
||||
broker['extra_hosts']={'broker':'127.0.0.1'}
|
||||
broker['volumes'] += ['./runtime/${COMPOSE_PROJECT_NAME}/broker:/run/config:ro']+certs(server='broker')
|
||||
for name in ('migrate','bootstrap'):
|
||||
service=services[name]
|
||||
service['image']='mtusi-messenger:lab7'
|
||||
service['environment']=dict(app_environment)
|
||||
service['environment'].pop('CURSOR_SECRET_FILE')
|
||||
for key in ('DATABASE_URL_FILE','S3_ACCESS_KEY_ID_FILE','S3_SECRET_ACCESS_KEY_FILE'):
|
||||
service['environment'][key]=service['environment'][key].replace('/run/runtime/','/run/operator/')
|
||||
if name=='bootstrap':
|
||||
service['environment'].update(S3_ADMIN_ACCESS_KEY_ID_FILE='/run/operator/s3_admin_access_key_id',
|
||||
S3_ADMIN_SECRET_ACCESS_KEY_FILE='/run/operator/s3_admin_secret_access_key')
|
||||
service['volumes']=certs()+['./runtime/${COMPOSE_PROJECT_NAME}/operator:/run/operator:ro']
|
||||
services['lb']['volumes']=['./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro']+certs(server='lb',client='lb')
|
||||
services['lb']['ports']=['127.0.0.1:${HTTP_PORT:-8443}:8443']
|
||||
services['lb']['user']='99:99'
|
||||
for name in ('otel-collector','prometheus','loki','tempo'):
|
||||
service=services[name]
|
||||
client={'otel-collector':'collector','prometheus':'scraper'}.get(name)
|
||||
service['volumes']=[mount.replace('./infra/otel/','./runtime/${COMPOSE_PROJECT_NAME}/otel/') for mount in service['volumes']]+certs(client=client)
|
||||
if name=='otel-collector':
|
||||
service['volumes'].append('./runtime/${COMPOSE_PROJECT_NAME}/otel/htpasswd:/run/config/htpasswd:ro')
|
||||
if name=='prometheus':
|
||||
service['command'].append('--web.listen-address=127.0.0.1:9091')
|
||||
grafana=services['grafana']
|
||||
grafana['volumes']=[mount.replace('./infra/grafana/provisioning:/etc/grafana/provisioning:ro','./runtime/${COMPOSE_PROJECT_NAME}/grafana/provisioning:/etc/grafana/provisioning:ro') for mount in grafana['volumes']]+certs(server='grafana')
|
||||
grafana['volumes'] += ['./runtime/${COMPOSE_PROJECT_NAME}/grafana/password:/run/config/password:ro']
|
||||
grafana['environment'].update(GF_SERVER_PROTOCOL='https',GF_SERVER_CERT_FILE='/run/server/client.crt',
|
||||
GF_SERVER_CERT_KEY='/run/server/client.key',GF_SECURITY_ADMIN_PASSWORD__FILE='/run/config/password')
|
||||
grafana['ports']=['127.0.0.1:${GRAFANA_PORT:-3309}:3000']
|
||||
for name in ('api1','api2','s3','otel-collector','prometheus','loki','tempo'):
|
||||
owner='s3-storage' if name=='s3' else name
|
||||
services[name+'-tls']={'image':ENVOY,'user':'101:101','network_mode':'service:'+owner,
|
||||
'command':['envoy','-c','/etc/envoy/envoy.yaml','--concurrency','2','--disable-hot-restart'],
|
||||
'volumes':certs(server=name)+[f'./runtime/${{COMPOSE_PROJECT_NAME}}/envoy/{name}.yaml:/etc/envoy/envoy.yaml:ro'],
|
||||
'cap_drop':['ALL'],'security_opt':['no-new-privileges:true'],'mem_limit':'128m','cpus':0.5,
|
||||
'depends_on':{owner:{'condition':'service_started'}},'stop_grace_period':'5s'}
|
||||
services['openbao']={'image':BAO,'command':['server','-config=/run/config/config.json'],
|
||||
'volumes':['baodata:/bao/data','./runtime/${COMPOSE_PROJECT_NAME}/bao:/run/config:ro']+certs(server='openbao'),
|
||||
'ports':['127.0.0.1:${BAO_PORT:-18200}:8200'],'mem_limit':'512m','cpus':1.0,
|
||||
'environment':{'SKIP_SETCAP':'true'},'cap_drop':['IPC_LOCK'],'stop_grace_period':'10s'}
|
||||
services['bao-volume-init']={'image':'mtusi-messenger:lab7','user':'0:0','network_mode':'none','volumes':['baodata:/bao/data'],'command':['python','-c',"import os; os.chown('/bao/data',100,1000)"],'mem_limit':'64m','cap_drop':['ALL'],'cap_add':['CHOWN'],'healthcheck':{'disable':True}}
|
||||
services['openbao']['depends_on']={'bao-volume-init':{'condition':'service_completed_successfully'}}
|
||||
services['probe']={'image':'mtusi-messenger:lab7','profiles':['tools'],'user':'0:0',
|
||||
'volumes':['./runtime/${COMPOSE_PROJECT_NAME}/pki:/run/all-pki:ro','./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro',
|
||||
'./runtime/${COMPOSE_PROJECT_NAME}/pki/client/operator:/run/identity:ro'], 'mem_limit':'256m','cpus':1.0,
|
||||
'healthcheck':{'disable':True}}
|
||||
base={'name':'mtusi-lab7','services':services,'volumes':{**base['volumes'],'baodata':{}},
|
||||
'networks':{'default':{'ipam':{'config':[{'subnet':'${LAB7_APP_SUBNET:-10.240.70.0/24}'}]}}}}
|
||||
(ROOT/'compose.yaml').write_text(yaml.safe_dump(base,sort_keys=False),encoding='utf-8',newline='\n')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
render()
|
||||
Reference in New Issue
Block a user