lab7
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
"""Measure CPU/wall time and peak RSS inside the API cgroup without user data."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import resource
|
||||
import secrets
|
||||
import statistics
|
||||
import time
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
|
||||
|
||||
hasher = PasswordHasher(memory_cost=19456, time_cost=2, parallelism=1)
|
||||
password = secrets.token_urlsafe(32)
|
||||
hashed = hasher.hash(password)
|
||||
|
||||
|
||||
def verify(_):
|
||||
start = time.perf_counter()
|
||||
assert hasher.verify(hashed, password)
|
||||
return 1000 * (time.perf_counter() - start)
|
||||
|
||||
|
||||
def sample(concurrency):
|
||||
start, cpu = time.perf_counter(), time.process_time()
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
samples = sorted(pool.map(verify, range(50)))
|
||||
print(json.dumps({
|
||||
"checks": len(samples), "concurrency": concurrency, "p50_ms": round(statistics.median(samples), 3),
|
||||
"p95_ms": round(samples[47], 3), "cpu_seconds": round(time.process_time() - cpu, 3),
|
||||
"wall_seconds": round(time.perf_counter() - start, 3),
|
||||
"peak_rss_mib": round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, 3),
|
||||
}))
|
||||
|
||||
|
||||
sample(1)
|
||||
sample(2)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Inspect running services without dumping Docker environment or secret mounts."""
|
||||
from collections import defaultdict
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
|
||||
def main():
|
||||
ids = subprocess.check_output(["docker", "compose", "ps", "-q"], text=True).splitlines()
|
||||
rows = json.loads(subprocess.check_output(["docker", "inspect", *ids]))
|
||||
ports = defaultdict(list)
|
||||
for item in rows:
|
||||
cfg = item["HostConfig"]
|
||||
service = item["Config"]["Labels"]["com.docker.compose.service"]
|
||||
assert not cfg["Privileged"] and cfg["NetworkMode"] != "host", service
|
||||
assert cfg["ReadonlyRootfs"] and "ALL" in cfg["CapDrop"], service
|
||||
assert "no-new-privileges:true" in cfg["SecurityOpt"], service
|
||||
assert cfg["Memory"] > 0 and cfg["NanoCpus"] > 0 and cfg["PidsLimit"] > 0, service
|
||||
assert not any("docker.sock" in mount["Destination"] for mount in item["Mounts"]), service
|
||||
for binds in (cfg.get("PortBindings") or {}).values():
|
||||
for bind in binds:
|
||||
assert bind["HostIp"] == "127.0.0.1", service
|
||||
ports[service].append(bind["HostPort"])
|
||||
user = item["Config"]["User"]
|
||||
if service in {"api", "worker", "dispatcher", "reconciler"}:
|
||||
assert user == "10001:10001" and not cfg["CapAdd"], service
|
||||
assert "/tmp" in cfg["Tmpfs"], service
|
||||
print(json.dumps({"service": service, "user": user or "entrypoint default", "cpu": cfg["NanoCpus"]/1e9,
|
||||
"memory_mib": cfg["Memory"]//2**20, "pids": cfg["PidsLimit"],
|
||||
"added_caps": cfg["CapAdd"] or [], "rootfs_read_only": True}))
|
||||
assert dict(ports) == {"lb": ["8443"], "openbao": ["8207"], "grafana": ["3007"]}, ports
|
||||
assert sum(row["Config"]["Labels"]["com.docker.compose.service"] == "api" for row in rows) == 2
|
||||
print("PASS all running services audited, only TLS loopback ports", json.dumps(ports))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Public-path ACL, bounded input, Argon2 rehash and shared admission measurements."""
|
||||
import argparse
|
||||
import base64
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import ssl
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
CA = str(ROOT / "secrets/authority/ca.crt")
|
||||
LOGIN = "/api/v1/auth/sessions"
|
||||
ME = "/api/v1/users/me"
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
return {"Authorization": "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()}
|
||||
|
||||
|
||||
def db(query):
|
||||
proc = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "-u", "postgres", "db", "psql", "-qAt",
|
||||
"-v", "ON_ERROR_STOP=1", "-d", "messenger"],
|
||||
input=query, text=True, capture_output=True, check=True)
|
||||
return proc.stdout.strip()
|
||||
|
||||
|
||||
def test_expiry(c):
|
||||
actor = c.user("expiry")
|
||||
c.call("GET", ME, actor=actor, schema="User")
|
||||
time.sleep(2.5)
|
||||
c.call("GET", ME, 401, actor=actor)
|
||||
print("PASS 2s TTL: immediate 200, after 2.5s 401")
|
||||
|
||||
|
||||
def test_http(c):
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
attachment, _ = c.attachment(alice, chat)
|
||||
path = "/api/v1/attachments/" + attachment["id"]
|
||||
for endpoint in (path, path + "/content"):
|
||||
c.call("GET", endpoint, 404, actor=eve, headers={"X-User-Id": alice["id"]})
|
||||
other = c.call("POST", "/api/v1/chats", 201, actor=eve,
|
||||
body={"title": "Чужой чат", "member_ids": [eve["id"]]}, schema="Chat")["json"]
|
||||
c.call("POST", "/api/v1/chats/" + other["id"] + "/messages", 404, actor=eve,
|
||||
body={"text": "", "attachment_ids": [attachment["id"]]},
|
||||
headers={"Idempotency-Key": secrets.token_hex(8)})
|
||||
c.call("GET", ME, 401, headers={"X-User-Id": alice["id"]})
|
||||
actual = c.call("GET", ME, actor=eve, headers={"X-User-Id": alice["id"]}, schema="User")["json"]
|
||||
check(actual["id"] == eve["id"], "forged identity")
|
||||
c.call("DELETE", LOGIN + "/current", 204, actor=eve)
|
||||
c.call("GET", ME, 401, actor=eve)
|
||||
print("PASS outsider metadata/content/link 404; forged ID ignored; revoked token 401")
|
||||
|
||||
upload = "/api/v1/chats/" + chat["id"] + "/attachments"
|
||||
c.call("POST", upload + "?filename=x.png", 413, actor=alice,
|
||||
raw=b"x" * (10_485_760 + 1), headers={"Content-Type": "image/png"})
|
||||
c.call("POST", upload + "?filename=x.png", 415, actor=alice, raw=b"invalid",
|
||||
headers={"Content-Type": "image/png"})
|
||||
c.call("POST", upload + "?filename=..%2Fx.png", 400, actor=alice, raw=b"x",
|
||||
headers={"Content-Type": "image/png"})
|
||||
c.call("POST", "/api/v1/users", 413, raw=b"x" * 65_537,
|
||||
headers={"Content-Type": "application/json"})
|
||||
print("PASS upload bytes/MIME/filename and JSON streaming limit")
|
||||
|
||||
ctx = ssl.create_default_context(cafile=CA)
|
||||
try:
|
||||
with socket.create_connection(("localhost", 8443), timeout=3) as conn:
|
||||
ctx.wrap_socket(conn, server_hostname="wrong.lab7")
|
||||
except ssl.SSLCertVerificationError as exc:
|
||||
check(exc.verify_code == 62, "unexpected certificate verification failure")
|
||||
else:
|
||||
raise AssertionError("incorrect ingress hostname accepted")
|
||||
print("PASS ingress rejects hostname mismatch on reachable listener")
|
||||
|
||||
username = alice["registration"]["username"]
|
||||
password = alice["registration"]["password"]
|
||||
command = [
|
||||
"docker", "compose", "exec", "-T", "--index", "1", "api", "python", "-c",
|
||||
"from argon2 import PasswordHasher; import sys; "
|
||||
"print(PasswordHasher(memory_cost=8192,time_cost=1,parallelism=1).hash(sys.stdin.read()))",
|
||||
]
|
||||
legacy = subprocess.run(command, input=password, text=True, capture_output=True, check=True).stdout.strip()
|
||||
db(f"UPDATE users SET password_hash='{legacy}' WHERE username='{username}';")
|
||||
fresh = c.call("POST", LOGIN, 201, headers=basic(username, password), schema="Session")["json"]
|
||||
stored = db(f"SELECT password_hash FROM users WHERE username='{username}';")
|
||||
check(stored != legacy and stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$"), "rehash absent")
|
||||
hashed_token = hashlib.sha256(fresh["token"].encode()).hexdigest()
|
||||
count = db(f"SELECT count(*) FROM sessions WHERE token_hash='{hashed_token}';")
|
||||
check(count == "1" and fresh["token"] != hashed_token, "session hash absent")
|
||||
print("PASS old Argon2id rehashed after login; DB stores SHA-256 of 256-bit bearer")
|
||||
|
||||
|
||||
def percentile(samples, p):
|
||||
values = sorted(samples)
|
||||
return round(1000 * values[min(len(values) - 1, int((len(values) - 1) * p))], 3)
|
||||
|
||||
|
||||
def test_budget(c):
|
||||
# A fixed window starts on first use. No competing harness should be running.
|
||||
time.sleep(10.2)
|
||||
wrong = basic("missing_" + secrets.token_hex(6), "synthetic_wrong_password")
|
||||
|
||||
def attempt(_):
|
||||
res = c.call("POST", LOGIN, [401, 429], headers=wrong)
|
||||
if res["status"] == 429:
|
||||
check(res["headers"].get("Retry-After", "").isdigit(), "Retry-After missing")
|
||||
return res
|
||||
|
||||
start = time.monotonic()
|
||||
serial = [attempt(i) for i in range(38)]
|
||||
seconds = time.monotonic() - start
|
||||
statuses = Counter(r["status"] for r in serial)
|
||||
aliases = sorted({r["headers"]["X-Instance-Id"] for r in serial})
|
||||
check(seconds < 10 and statuses == {401: 24, 429: 14} and len(aliases) == 2, "shared limit")
|
||||
time.sleep(10.2)
|
||||
start = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||
burst = list(pool.map(attempt, range(72)))
|
||||
burst_seconds = time.monotonic() - start
|
||||
burst_counts = Counter(r["status"] for r in burst)
|
||||
check(burst_seconds < 10 and 0 < burst_counts[401] <= 24 and burst_counts[429] >= 48, "burst limit")
|
||||
time.sleep(10.2)
|
||||
check(attempt(0)["status"] == 401, "budget did not replenish")
|
||||
print(json.dumps({
|
||||
"serial": {"requests": len(serial), "seconds": round(seconds, 3), "status": statuses,
|
||||
"replicas": len(aliases), "p95_401_ms": percentile(
|
||||
[r["elapsed"] for r in serial if r["status"] == 401], .95)},
|
||||
"burst": {"requests": len(burst), "concurrency": 12, "seconds": round(burst_seconds, 3),
|
||||
"status": burst_counts, "p95_ms": percentile([r["elapsed"] for r in burst], .95)},
|
||||
}))
|
||||
print("PASS shared login window, KDF concurrency bound, Retry-After and recovery")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("scenario", choices=("http", "expiry", "budget"))
|
||||
args = parser.parse_args()
|
||||
{"http": test_http, "expiry": test_expiry, "budget": test_budget}[args.scenario](Client(ca_file=CA))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Run isolated worker, database and telemetry incidents and always restore the services."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
DC = ["docker", "compose"]
|
||||
AUDIT = DC + ["run", "--rm", "--no-deps", "-T", "audit", "python", "/app/student-tests/telemetry_probe.py"]
|
||||
|
||||
|
||||
def run(args, capture=False, **kwargs):
|
||||
return subprocess.run(args, check=True, text=True, capture_output=capture, **kwargs)
|
||||
|
||||
|
||||
def metric(expression):
|
||||
result = run(AUDIT + [expression], capture=True)
|
||||
return [float(x) for x in json.loads(result.stdout.splitlines()[-1])["values"]]
|
||||
|
||||
|
||||
def await_condition(predicate, seconds):
|
||||
end = time.monotonic() + seconds
|
||||
while time.monotonic() < end:
|
||||
if predicate():
|
||||
return round(seconds - (end - time.monotonic()), 3)
|
||||
time.sleep(3)
|
||||
raise AssertionError("timeout waiting for incident signal")
|
||||
|
||||
|
||||
def worker(c, actor, chat):
|
||||
run(DC + ["stop", "-t", "1", "worker"])
|
||||
started = time.monotonic()
|
||||
try:
|
||||
att, _ = c.attachment(actor, chat)
|
||||
alert = 'ALERTS{alertname="QueueLagGrowing",alertstate="firing"}'
|
||||
firing = await_condition(lambda: metric(alert) == [1], 70)
|
||||
age = max(metric("max(queue_oldest_age_seconds)"))
|
||||
depth = max(metric("max(queue_depth)"))
|
||||
check(age > 15 and depth >= 1, "unexpected queue measurement")
|
||||
finally:
|
||||
run(DC + ["start", "worker"])
|
||||
resumed = time.monotonic()
|
||||
c.wait_ready(actor, att)
|
||||
ready = time.monotonic() - resumed
|
||||
resolved = await_condition(lambda: not metric(alert) and metric("max(queue_depth)") == [0], 40)
|
||||
print(json.dumps({"incident": "worker_stop", "age_seconds": age, "depth": depth,
|
||||
"alert_firing_seconds": firing, "ready_after_restart_seconds": round(ready, 3),
|
||||
"alert_resolved_seconds": resolved, "total_seconds": round(time.monotonic() - started, 3)}))
|
||||
|
||||
|
||||
def database(c, actor, chat):
|
||||
psql = DC + ["exec", "-T", "-u", "postgres", "db", "psql", "-qAt", "-d", "messenger", "-c"]
|
||||
lock = subprocess.Popen(psql + [
|
||||
"BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(24); ROLLBACK;"
|
||||
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
def acquired():
|
||||
return run(psql + ["SELECT count(*) FROM pg_locks WHERE relation='messages'::regclass "
|
||||
"AND mode='AccessExclusiveLock' AND granted"], capture=True).stdout.strip() == "1"
|
||||
await_condition(acquired, 10)
|
||||
c.call("GET", "/health/ready", schema="Health")
|
||||
start = time.monotonic()
|
||||
results = []
|
||||
for _ in range(5):
|
||||
from uuid import uuid4
|
||||
res = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", 503, actor=actor,
|
||||
body={"text": "lock probe"}, headers={"Idempotency-Key": uuid4().hex})
|
||||
results.append(res)
|
||||
run(AUDIT + ["--trace-error", results[0]["headers"]["X-Trace-Id"]])
|
||||
finally:
|
||||
lock.wait(timeout=30)
|
||||
after = c.message(actor, chat, "database recovered")
|
||||
print(json.dumps({"incident": "database_lock", "blocked_requests": len(results),
|
||||
"failure_ms": [round(r["elapsed"] * 1000, 2) for r in results],
|
||||
"first_success_ms": round(after["elapsed"] * 1000, 2),
|
||||
"since_locked_requests_seconds": round(time.monotonic() - start, 3)}))
|
||||
|
||||
|
||||
def telemetry(c, actor, chat):
|
||||
start = time.time()
|
||||
run(DC + ["stop", "-t", "1", "traces"])
|
||||
try:
|
||||
requests = 0
|
||||
until = time.monotonic() + 17
|
||||
att, _ = c.attachment(actor, chat)
|
||||
c.wait_ready(actor, att)
|
||||
while time.monotonic() < until:
|
||||
c.message(actor, chat, "backend outage")
|
||||
requests += 1
|
||||
time.sleep(1)
|
||||
otel = run(DC + ["ps", "-q", "otel"], capture=True).stdout.strip()
|
||||
stats = run(["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", otel], capture=True)
|
||||
logs = run(DC + ["logs", "--since", str(int(start)), "otel"], capture=True).stdout
|
||||
dropped = sum(int(x) for x in re.findall(r'"dropped_items":\s*(\d+)', logs))
|
||||
check(dropped > 0, "bounded telemetry loss not observed")
|
||||
finally:
|
||||
run(DC + ["start", "traces"])
|
||||
print(json.dumps({"incident": "tempo_backend_stop", "successful_writes": requests,
|
||||
"upload_ready": True, "collector_memory": stats.stdout.strip(),
|
||||
"dropped_spans_reported": dropped, "outage_seconds": round(time.time() - start, 3)}))
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(ca_file=str(ROOT / "secrets/authority/ca.crt"))
|
||||
actor, _, _, chat = c.bootstrap()
|
||||
for scenario in (worker, database, telemetry):
|
||||
scenario(c, actor, chat)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Prove real credential rejection, service token renewal and the sealed lease limit."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from urllib.error import HTTPError
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path[:0] = [str(ROOT), str(ROOT / "tests")]
|
||||
from scripts.bao_operator import ADDRESS, call, login, rotate_db, rotate_s3, unseal
|
||||
from scripts.wait_ready import wait
|
||||
from src.bao import client, request
|
||||
from client import Client, check
|
||||
|
||||
CA = "secrets/authority/ca.crt"
|
||||
COMPOSE = ["docker", "compose"]
|
||||
|
||||
|
||||
def code(args):
|
||||
subprocess.run(args, check=True, stdin=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def image_id(service):
|
||||
result = subprocess.check_output(COMPOSE + ["ps", "-q", service], text=True).splitlines()
|
||||
return sorted({subprocess.check_output(["docker", "inspect", "-f", "{{.Image}}", cid],
|
||||
text=True).strip() for cid in result})
|
||||
|
||||
|
||||
def verify_db(dsn, expected):
|
||||
result = subprocess.run(
|
||||
COMPOSE + ["exec", "-T", "--index", "1", "api", "python", "-c", """
|
||||
import psycopg,sys
|
||||
try:
|
||||
with psycopg.connect(sys.stdin.read(),connect_timeout=3) as db:
|
||||
assert db.execute('SELECT current_user').fetchone()[0]=='lab_api'
|
||||
print('connected')
|
||||
except psycopg.OperationalError as e:
|
||||
print('invalid_password' if 'password authentication failed' in str(e) else 'other_error')
|
||||
"""], input=dsn, text=True, capture_output=True, check=True)
|
||||
check(result.stdout.strip() == expected, f"DB connection expected {expected}")
|
||||
|
||||
|
||||
def db_rotation():
|
||||
token = login()["client_token"]
|
||||
old = call("messenger/data/api", token=token)["data"]["data"]["DATABASE_URL"]
|
||||
verify_db(old, "connected")
|
||||
previous = image_id("api")
|
||||
started = time.monotonic()
|
||||
rotate_db()
|
||||
verify_db(old, "invalid_password")
|
||||
print("PASS old API DB password rejected on fresh TLS connection")
|
||||
code(COMPOSE + ["up", "-d", "--force-recreate", "--no-deps", "api"])
|
||||
wait(2, 60)
|
||||
new = call("messenger/data/api", token=token)["data"]["data"]["DATABASE_URL"]
|
||||
verify_db(new, "connected")
|
||||
check(previous == image_id("api"), "API image unexpectedly changed")
|
||||
print("PASS new API DB password works with same image",
|
||||
json.dumps({"recovery_seconds": round(time.monotonic() - started, 3)}))
|
||||
|
||||
|
||||
def leaf_rotation():
|
||||
previous = image_id("lb")
|
||||
started = time.monotonic()
|
||||
code(["python3", "scripts/local_pki.py", "rotate-lb"])
|
||||
code(COMPOSE + ["restart", "lb"])
|
||||
wait(2, 60)
|
||||
code(COMPOSE + ["run", "--rm", "--no-deps", "-T", "audit",
|
||||
"python", "/app/student-tests/trust.py", "rotation"])
|
||||
check(previous == image_id("lb"), "LB image unexpectedly changed")
|
||||
print("PASS leaf revoked on both APIs without rebuild",
|
||||
json.dumps({"recovery_seconds": round(time.monotonic() - started, 3)}))
|
||||
|
||||
|
||||
def s3_status(values, expected):
|
||||
result = subprocess.run(
|
||||
COMPOSE + ["exec", "-T", "--index", "1", "api", "python", "-c", """
|
||||
import boto3,json,sys
|
||||
from botocore.exceptions import ClientError
|
||||
v=json.load(sys.stdin)
|
||||
s3=boto3.client("s3",endpoint_url="https://s3:9000",region_name="us-east-1",verify="/pki/ca.crt",
|
||||
aws_access_key_id=v["S3_ACCESS_KEY_ID"],aws_secret_access_key=v["S3_SECRET_ACCESS_KEY"])
|
||||
try:
|
||||
s3.list_objects_v2(Bucket="messenger-attachments",Prefix="originals/",MaxKeys=1)
|
||||
print("accepted")
|
||||
except ClientError as exc:
|
||||
print("rejected" if exc.response["ResponseMetadata"]["HTTPStatusCode"]==403 else "other_error")
|
||||
"""], input=json.dumps(values), text=True, capture_output=True, check=True)
|
||||
check(result.stdout.strip() == expected, f"S3 credentials expected {expected}")
|
||||
|
||||
|
||||
def s3_rotation():
|
||||
token = login()["client_token"]
|
||||
path = "messenger/data/api"
|
||||
old = call(path, token=token)["data"]["data"]
|
||||
s3_status(old, "accepted")
|
||||
previous = image_id("api")
|
||||
started = time.monotonic()
|
||||
rotate_s3()
|
||||
s3_status(old, "rejected")
|
||||
print("PASS old S3 secret rejected on fresh TLS connection")
|
||||
code(COMPOSE + ["up", "-d", "--force-recreate", "--no-deps", "api"])
|
||||
wait(2, 60)
|
||||
new = call(path, token=token)["data"]["data"]
|
||||
s3_status(new, "accepted")
|
||||
check(previous == image_id("api"), "API image unexpectedly changed")
|
||||
print("PASS new scoped S3 secret accepted with same image",
|
||||
json.dumps({"recovery_seconds": round(time.monotonic() - started, 3)}))
|
||||
|
||||
|
||||
def collector_rotation():
|
||||
probe = COMPOSE + ["run", "--rm", "--no-deps", "-T", "audit", "python", "/app/student-tests/trust.py"]
|
||||
code(probe + ["collector-current"])
|
||||
images = [image_id(role) for role in ("otel", "loki", "tempo")]
|
||||
started = time.monotonic()
|
||||
code(["python3", "scripts/local_pki.py", "rotate-collector"])
|
||||
code(COMPOSE + ["stop", "otel", "logs", "traces"])
|
||||
code(COMPOSE + ["restart", "loki", "tempo"])
|
||||
code(COMPOSE + ["start", "logs", "traces", "otel"])
|
||||
end = time.monotonic() + 30
|
||||
while True:
|
||||
try:
|
||||
code(probe + ["collector-rotation"])
|
||||
break
|
||||
except subprocess.CalledProcessError:
|
||||
if time.monotonic() >= end:
|
||||
raise
|
||||
time.sleep(2)
|
||||
check(images == [image_id(role) for role in ("otel", "loki", "tempo")], "image unexpectedly changed")
|
||||
print("PASS Collector exporter leaf rotated without rebuild",
|
||||
json.dumps({"recovery_seconds": round(time.monotonic() - started, 3)}))
|
||||
|
||||
|
||||
def ingress_status(path):
|
||||
ctx = ssl.create_default_context(cafile=CA)
|
||||
try:
|
||||
with urllib.request.urlopen("https://localhost:8443" + path, context=ctx, timeout=4) as res:
|
||||
return res.status
|
||||
except HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
def bao_lifecycle():
|
||||
pki = Path("secrets/runtime/api")
|
||||
opener = client(*(str(pki / f) for f in ("service.crt", "service.key", "ca.crt")))
|
||||
|
||||
def api(path, data=None, token=None):
|
||||
return request(opener, ADDRESS, path, data, token)
|
||||
|
||||
auth = api("auth/cert/login", {"name": "api"})["auth"]
|
||||
original_ttl = auth["lease_duration"]
|
||||
token = auth["client_token"]
|
||||
renewed = api("auth/token/renew-self", {"increment": f"{original_ttl}s"}, token)["auth"]
|
||||
check(renewed["renewable"] and renewed["lease_duration"] > 0, "token renewal")
|
||||
api("messenger/data/api", token=token)
|
||||
print(f"PASS role token renewal, lease {original_ttl}s → {renewed['lease_duration']}s")
|
||||
operator = login()["client_token"]
|
||||
call("auth/token/revoke-accessor", {"accessor": auth["accessor"]}, operator)
|
||||
try:
|
||||
api("messenger/data/api", token=token)
|
||||
except HTTPError as exc:
|
||||
check(exc.code == 403, "revocation should deny with HTTP 403")
|
||||
else:
|
||||
raise AssertionError("revoked token still works")
|
||||
print("PASS revoked scoped token denied on fresh HTTPS request")
|
||||
|
||||
c = Client(ca_file=CA)
|
||||
actor = c.user("seal")
|
||||
check(ingress_status("/health/ready") == 200, "pre-seal readiness")
|
||||
started = time.monotonic()
|
||||
call("sys/seal", token=operator, method="PUT")
|
||||
try:
|
||||
immediate = ingress_status("/health/ready")
|
||||
check(immediate == 200, "expected short grace before expiry")
|
||||
deadline = time.monotonic() + original_ttl + 12
|
||||
consecutive = 0
|
||||
while time.monotonic() < deadline and consecutive < 4:
|
||||
consecutive = consecutive + 1 if ingress_status("/health/ready") == 503 else 0
|
||||
time.sleep(.4)
|
||||
expiry_seconds = time.monotonic() - started
|
||||
check(consecutive == 4, "sealed credential grace exceeded")
|
||||
check(ingress_status("/health/live") == 200, "API process died while sealed")
|
||||
print("PASS sealed: readiness 200 → 503, liveness 200",
|
||||
json.dumps({"after_seconds": round(expiry_seconds, 3)}))
|
||||
finally:
|
||||
resumed = time.monotonic()
|
||||
unseal()
|
||||
wait(2, 65)
|
||||
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
print("PASS after unseal same user session resumes",
|
||||
json.dumps({"recovery_seconds": round(time.monotonic() - resumed, 3)}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("scenario", choices=("db", "s3", "leaf", "collector", "bao"))
|
||||
{"db": db_rotation, "s3": s3_rotation, "leaf": leaf_rotation,
|
||||
"collector": collector_rotation, "bao": bao_lifecycle}[parser.parse_args().scenario]()
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Create a synthetic upload and check its signals without persisting secret canaries."""
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from urllib.error import HTTPError
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
CA = ROOT / "secrets/authority/ca.crt"
|
||||
|
||||
|
||||
def main():
|
||||
start = time.time_ns()
|
||||
c = Client(ca_file=str(CA))
|
||||
alice = c.user("telemetry")
|
||||
chat = c.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "Проверка сигналов", "member_ids": [alice["id"]]}, schema="Chat")["json"]
|
||||
body = "message-canary-" + secrets.token_hex(16)
|
||||
message = c.message(alice, chat, body)
|
||||
original = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
filename = "filename-canary-" + secrets.token_hex(12) + ".png"
|
||||
uploaded = c.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + filename,
|
||||
202, actor=alice, raw=original, headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
c.wait_ready(alice, uploaded["json"])
|
||||
login = alice["registration"]
|
||||
basic = base64.b64encode(f'{login["username"]}:{login["password"]}'.encode()).decode()
|
||||
canaries = [alice["token"], login["password"], basic, body, filename, base64.b64encode(original).decode()]
|
||||
payload = {"start": start, "trace_id": uploaded["headers"]["X-Trace-Id"],
|
||||
"request_id": uploaded["headers"]["X-Request-Id"], "canaries": canaries,
|
||||
"message_trace_id": message["headers"]["X-Trace-Id"]}
|
||||
subprocess.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "audit",
|
||||
"python", "/app/student-tests/telemetry_probe.py"],
|
||||
input=json.dumps(payload), text=True, check=True)
|
||||
logs = subprocess.check_output(["docker", "compose", "logs", "--since", "3m"], text=True)
|
||||
check(not any(value in logs for value in canaries), "sensitive synthetic value in container logs")
|
||||
print("PASS no synthetic sensitive values in Compose logs")
|
||||
|
||||
# Grafana must actually query its provisioned datasources through mTLS.
|
||||
ctx = ssl.create_default_context(cafile=str(CA))
|
||||
password = (ROOT / "secrets/bootstrap/grafana/admin").read_text()
|
||||
headers = {"Authorization": "Basic " + base64.b64encode(("admin:" + password).encode()).decode()}
|
||||
base = "https://localhost:3007"
|
||||
try:
|
||||
urllib.request.urlopen(base + "/api/datasources", context=ctx, timeout=5)
|
||||
except HTTPError as exc:
|
||||
check(exc.code == 401, "Grafana endpoint did not require authentication")
|
||||
else:
|
||||
raise AssertionError("Grafana allows unauthenticated datasource list")
|
||||
print("PASS Grafana anonymous datasource list denied")
|
||||
paths = (
|
||||
"prometheus/api/v1/query?query=up",
|
||||
"loki/loki/api/v1/labels",
|
||||
"tempo/api/search?limit=1",
|
||||
)
|
||||
for path in paths:
|
||||
req = urllib.request.Request(base + "/api/datasources/proxy/uid/" + path, headers=headers)
|
||||
with urllib.request.urlopen(req, context=ctx, timeout=8) as res:
|
||||
check(res.status == 200, "Grafana datasource proxy failure")
|
||||
print("PASS Grafana HTTPS/mTLS proxy", path.split("/")[0])
|
||||
req = urllib.request.Request(base + "/api/dashboards/uid/lab7", headers=headers)
|
||||
with urllib.request.urlopen(req, context=ctx, timeout=8) as res:
|
||||
dashboard = json.load(res)["dashboard"]
|
||||
check(dashboard["title"].startswith("Lab7") and len(dashboard["panels"]) > 0,
|
||||
"Grafana dashboard provisioning")
|
||||
print("PASS provisioned Lab7 Grafana dashboard", len(dashboard["panels"]), "panels")
|
||||
print("upload_trace_id", payload["trace_id"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Query all three TLS backends from the operator probe namespace."""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from trust import check, https
|
||||
|
||||
|
||||
def query(host, port, path):
|
||||
status, raw, _ = https(host, port, path, "operator")
|
||||
return status, raw
|
||||
|
||||
|
||||
def promql(expression):
|
||||
status, raw = query("prometheus", 9090, "/api/v1/query?" + urlencode({"query": expression}))
|
||||
if status != 200:
|
||||
raise AssertionError("Prometheus TLS query failed")
|
||||
return json.loads(raw)["data"]["result"]
|
||||
|
||||
|
||||
def event_trace(trace):
|
||||
return query("tempo", 3200, "/api/traces/" + trace)
|
||||
|
||||
|
||||
def verify_signals(payload):
|
||||
trace_id = payload["trace_id"]
|
||||
loki_path = "/loki/api/v1/query_range?" + urlencode({
|
||||
"query": '{service_name=~"messenger-api|messenger-worker"} |= "' + trace_id + '"',
|
||||
"start": str(payload["start"]),
|
||||
"end": str(time.time_ns() + 60_000_000_000),
|
||||
"limit": "100",
|
||||
})
|
||||
spans = (b"POST /api/v1/chats/{chat_id}/attachments", b"attachments publish",
|
||||
b"attachment.process", b"s3.", b"db.execute")
|
||||
end = time.monotonic() + 40
|
||||
while time.monotonic() < end:
|
||||
loki_code, logs = query("loki", 3100, loki_path)
|
||||
tempo_code, trace = event_trace(trace_id)
|
||||
if loki_code == tempo_code == 200 and b"attachment_ready" in logs and all(fragment in trace for fragment in spans):
|
||||
break
|
||||
time.sleep(1.5)
|
||||
check("upload HTTP request ID and ready worker event share one Loki trace ID",
|
||||
payload["request_id"].encode() in logs and b"attachment_ready" in logs)
|
||||
check("Tempo trace joins HTTP, producer, consumer, S3 and DB",
|
||||
tempo_code == 200 and all(fragment in trace for fragment in spans))
|
||||
window_path = "/loki/api/v1/query_range?" + urlencode({
|
||||
"query": '{service_name=~"messenger-api|messenger-worker"}',
|
||||
"start": str(payload["start"]), "end": str(time.time_ns()), "limit": "2000",
|
||||
})
|
||||
status, window_logs = query("loki", 3100, window_path)
|
||||
message_code, message_trace = event_trace(payload["message_trace_id"])
|
||||
check("Loki and Tempo contain none of the synthetic sensitive values",
|
||||
status == message_code == 200 and not any(
|
||||
item.encode() in window_logs or item.encode() in trace or item.encode() in message_trace
|
||||
for item in payload["canaries"]))
|
||||
|
||||
for expression in (
|
||||
"app_http_requests_total", "app_http_duration_seconds_bucket",
|
||||
"jobs_processed_total", "attachment_ready_seconds_bucket", "queue_depth",
|
||||
"queue_oldest_age_seconds", "worker_capacity", "db_pool_used",
|
||||
"process_memory_bytes", "otelcol_receiver_accepted_spans_total",
|
||||
):
|
||||
for _ in range(18):
|
||||
if promql(expression):
|
||||
check("metric " + expression, True)
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise AssertionError("metric missing: " + expression)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if sys.argv[1:2] == ["--trace-error"]:
|
||||
trace_id = sys.argv[2]
|
||||
for _ in range(15):
|
||||
status, raw = event_trace(trace_id)
|
||||
if status == 200 and all(x in raw for x in (b"LockNotAvailable", b"db.execute", b"POST /api/v1/chats/{chat_id}/messages")):
|
||||
print("PASS Tempo HTTP 503 trace includes DB span with LockNotAvailable")
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise SystemExit("expected DB error trace missing")
|
||||
elif sys.argv[1:]:
|
||||
for expression in sys.argv[1:]:
|
||||
result = promql(expression)
|
||||
print(json.dumps({"expression": expression, "values": [row["value"][1] for row in result]}))
|
||||
else:
|
||||
verify_signals(json.load(sys.stdin))
|
||||
@@ -0,0 +1,251 @@
|
||||
"""Operator-only integration probe, on the Compose network with synthetic credentials."""
|
||||
import http.client
|
||||
import json
|
||||
import socket
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import HTTPError
|
||||
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
import psycopg
|
||||
import redis
|
||||
|
||||
sys.path.insert(0, "/app")
|
||||
from src.bao import client, request
|
||||
|
||||
PKI = Path("/audit/runtime")
|
||||
CA = str(PKI / "api" / "ca.crt")
|
||||
SEEN = []
|
||||
|
||||
|
||||
def check(label, condition):
|
||||
if not condition:
|
||||
raise AssertionError(label)
|
||||
SEEN.append(label)
|
||||
print("PASS", label, flush=True)
|
||||
|
||||
|
||||
def context(role=None, ca=CA):
|
||||
ctx = ssl.create_default_context(cafile=ca)
|
||||
if role == "foreign":
|
||||
ctx.load_cert_chain("/audit/foreign/client/service.crt", "/audit/foreign/client/service.key")
|
||||
elif role == "lb-old":
|
||||
ctx.load_cert_chain("/audit/rotation/previous.pem")
|
||||
elif role == "collector-previous":
|
||||
ctx.load_cert_chain("/audit/rotation/collector-previous.pem")
|
||||
elif role == "collector-export":
|
||||
ctx.load_cert_chain(PKI / "collector/client/service.crt", PKI / "collector/client/service.key")
|
||||
elif role == "lb-active":
|
||||
ctx.load_cert_chain(PKI / "lb" / "client.pem")
|
||||
elif role:
|
||||
ctx.load_cert_chain(PKI / role / "service.crt", PKI / role / "service.key")
|
||||
return ctx
|
||||
|
||||
|
||||
def https(host, port, path, role=None, method="GET", body=None, address=None, ca=CA, content_type="application/json"):
|
||||
conn = http.client.HTTPSConnection(host, port, context=context(role, ca), timeout=4)
|
||||
if address:
|
||||
conn._create_connection = lambda _addr, timeout, source_address: socket.create_connection(
|
||||
(address, port), timeout, source_address)
|
||||
try:
|
||||
conn.request(method, path, body=body, headers={"Content-Type": content_type})
|
||||
res = conn.getresponse()
|
||||
return res.status, res.read(), dict(res.getheaders())
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def rejected_http(*args, **kwargs):
|
||||
try:
|
||||
return https(*args, **kwargs)[0] == 403
|
||||
except (ssl.SSLError, ConnectionResetError, http.client.RemoteDisconnected):
|
||||
return True
|
||||
|
||||
|
||||
def denied(action, error, verify=lambda _exc: True):
|
||||
try:
|
||||
action()
|
||||
except error as exc:
|
||||
return verify(exc)
|
||||
return False
|
||||
|
||||
|
||||
def bao_client(role):
|
||||
path = PKI / role
|
||||
return client(str(path / "service.crt"), str(path / "service.key"), CA)
|
||||
|
||||
|
||||
def bao(role, path, data=None, token=None, method=None):
|
||||
return request(bao_client(role), "https://openbao:8200", path, data, token, method)
|
||||
|
||||
|
||||
def get_auth(role):
|
||||
return bao(role, "auth/cert/login", {"name": role})["auth"]
|
||||
|
||||
|
||||
def get_values(role, token=None):
|
||||
return bao(role, "messenger/data/" + role, token=token or get_auth(role)["client_token"])["data"]["data"]
|
||||
|
||||
|
||||
def broker(url, role):
|
||||
folder = (Path("/audit/foreign/client") if role == "foreign" else PKI / role) if role else None
|
||||
return redis.Redis.from_url(url, socket_timeout=3, socket_connect_timeout=3,
|
||||
ssl_ca_certs=CA, ssl_check_hostname=True,
|
||||
ssl_certfile=str(folder / "service.crt") if folder else None,
|
||||
ssl_keyfile=str(folder / "service.key") if folder else None)
|
||||
|
||||
|
||||
def s3(values):
|
||||
return boto3.client("s3", endpoint_url="https://s3:9000", region_name="us-east-1",
|
||||
verify=CA, aws_access_key_id=values["S3_ACCESS_KEY_ID"],
|
||||
aws_secret_access_key=values["S3_SECRET_ACCESS_KEY"])
|
||||
|
||||
|
||||
def verify_revocation():
|
||||
addresses = {item[4][0] for item in socket.getaddrinfo("api", 8444, socket.AF_INET)}
|
||||
check("rotation tests both API addresses", len(addresses) == 2)
|
||||
for index, address in enumerate(sorted(addresses), 1):
|
||||
args = ("api", 8444, "/health/ready")
|
||||
check(f"API {index} rejects previous same-SAN leaf on new TLS connection",
|
||||
rejected_http(*args, "lb-old", address=address))
|
||||
check(f"API {index} permits replacement leaf on new TLS connection",
|
||||
https(*args, "lb-active", address=address)[0] == 200)
|
||||
|
||||
|
||||
def collector_status(role):
|
||||
from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest
|
||||
payload = ExportLogsServiceRequest()
|
||||
logs = payload.resource_logs.add()
|
||||
logs.resource.attributes.add(key="service.name").value.string_value = "lab7-audit"
|
||||
record = logs.scope_logs.add().log_records.add(time_unix_nano=time.time_ns(), severity_text="INFO")
|
||||
record.body.string_value = "TLS audit event"
|
||||
loki = https("loki", 3100, "/otlp/v1/logs", role, "POST",
|
||||
payload.SerializeToString(), content_type="application/x-protobuf")[0]
|
||||
tempo = https("tempo", 4318, "/v1/traces", role, "POST", b"{}")[0]
|
||||
return loki, tempo
|
||||
|
||||
|
||||
def main():
|
||||
addresses = sorted({item[4][0] for item in socket.getaddrinfo("api", 8444, socket.AF_INET)})
|
||||
check("two API addresses resolved", len(addresses) == 2)
|
||||
for index, address in enumerate(addresses, 1):
|
||||
args = ("api", 8444, "/health/ready")
|
||||
check(f"API {index} allows active LB", https(*args, "lb-active", address=address)[0] == 200)
|
||||
for role in (None, "foreign", "intruder"):
|
||||
check(f"API {index} rejects {role or 'missing cert'}",
|
||||
rejected_http(*args, role, address=address))
|
||||
|
||||
for role in (None, "foreign", "intruder"):
|
||||
check(f"Collector rejects {role or 'missing cert'}", rejected_http(
|
||||
"collector", 4318, "/v1/metrics", role, "POST", b"{}"))
|
||||
for role in ("api", "worker", "dispatcher", "reconciler"):
|
||||
check(f"Collector allows {role} OTLP", https(
|
||||
"collector", 4318, "/v1/metrics", role, "POST", b"{}")[0] == 200)
|
||||
for port in (8888, 8889):
|
||||
check(f"Collector scrape {port} permits only scraper",
|
||||
https("collector", port, "/metrics", "scraper")[0] == 200
|
||||
and https("collector", port, "/metrics", "api")[0] == 403)
|
||||
|
||||
api = get_values("api")
|
||||
worker = get_values("worker")
|
||||
dispatcher = get_values("dispatcher")
|
||||
for role, values in (("worker", worker), ("dispatcher", dispatcher)):
|
||||
url = values["BROKER_URL"]
|
||||
check(f"broker allows {role}", broker(url, role).ping())
|
||||
for wrong in (None, "foreign", "intruder", "api"):
|
||||
check(f"broker rejects {wrong or 'missing cert'} with valid {role} Redis password",
|
||||
denied(lambda: broker(url, wrong).ping(), redis.ConnectionError))
|
||||
check("Redis producer cannot read stream", denied(
|
||||
lambda: broker(dispatcher["BROKER_URL"], "dispatcher").xrange("attachments.jobs"),
|
||||
redis.ResponseError, lambda e: "no permissions" in str(e).lower()))
|
||||
check("Redis worker cannot publish", denied(
|
||||
lambda: broker(worker["BROKER_URL"], "worker").xadd("attachments.jobs", {"audit": "denied"}),
|
||||
redis.ResponseError, lambda e: "no permissions" in str(e).lower()))
|
||||
check("Redis worker cannot write foreign key", denied(
|
||||
lambda: broker(worker["BROKER_URL"], "worker").xack("other.stream", "image-workers", "0-0"),
|
||||
redis.ResponseError, lambda e: "no permissions" in str(e).lower()))
|
||||
|
||||
for role, values in (("api", api), ("worker", worker), ("dispatcher", dispatcher),
|
||||
("reconciler", get_values("reconciler"))):
|
||||
dsn = values["DATABASE_URL"]
|
||||
with psycopg.connect(dsn) as db:
|
||||
info = db.execute("SELECT current_user, ssl, version FROM pg_stat_ssl WHERE pid=pg_backend_pid()").fetchone()
|
||||
check(f"DB verify-full and distinct {role} login", info[0] == "lab_" + role and info[1])
|
||||
check(f"DB rejects plaintext {role} login", denied(
|
||||
lambda: psycopg.connect(dsn, sslmode="disable"), psycopg.OperationalError,
|
||||
lambda e: "no encryption" in str(e).lower()))
|
||||
check("DB rejects mismatched SAN", denied(lambda: psycopg.connect(
|
||||
api["DATABASE_URL"], host="intruder", hostaddr=socket.gethostbyname("db")),
|
||||
psycopg.OperationalError, lambda e: "does not match" in str(e).lower()))
|
||||
with psycopg.connect(worker["DATABASE_URL"]) as db:
|
||||
check("worker cannot read users/passwords", denied(
|
||||
lambda: db.execute("SELECT password_hash FROM users"), psycopg.errors.InsufficientPrivilege))
|
||||
|
||||
bucket = "messenger-attachments"
|
||||
original = s3(api).list_objects_v2(Bucket=bucket, Prefix="originals/", MaxKeys=1)
|
||||
check("S3 API allowed to list originals via verified HTTPS",
|
||||
original["ResponseMetadata"]["HTTPStatusCode"] == 200)
|
||||
check("S3 application cannot list all buckets (operator privilege)", denied(
|
||||
lambda: s3(api).list_buckets(), ClientError, lambda e: e.response["ResponseMetadata"]["HTTPStatusCode"] == 403))
|
||||
check("S3 public health verified over TLS", https("s3", 9000, "/minio/health/live")[0] == 200)
|
||||
if original.get("Contents"):
|
||||
key = original["Contents"][0]["Key"]
|
||||
check("S3 original is private even with a known object key", https("s3", 9000, f"/{bucket}/{key}")[0] == 403)
|
||||
for label, fn in [
|
||||
("S3 API cannot put original", lambda: s3(api).put_object(Bucket=bucket, Key="originals/deny", Body=b"deny")),
|
||||
("S3 worker cannot list bucket", lambda: s3(worker).list_objects_v2(Bucket=bucket)),
|
||||
("S3 worker cannot put arbitrary prefix", lambda: s3(worker).put_object(Bucket=bucket, Key="deny/object", Body=b"deny")),
|
||||
]:
|
||||
check(label, denied(fn, ClientError, lambda e: e.response["ResponseMetadata"]["HTTPStatusCode"] == 403))
|
||||
|
||||
for role in ("api", "worker", "dispatcher", "reconciler"):
|
||||
auth = get_auth(role)
|
||||
token = auth["client_token"]
|
||||
check(f"OpenBao {role} scoped TTL and secret", auth["policies"] == [role]
|
||||
and 0 < auth["lease_duration"] <= 90 and "DATABASE_URL" in get_values(role, token))
|
||||
for path, data in (("messenger/data/operator", None), ("sys/policies/acl/escalate", {"policy": 'path "*" {capabilities=["sudo"]}'})):
|
||||
check(f"OpenBao {role} denied {path}", denied(
|
||||
lambda: bao(role, path, data, token), HTTPError, lambda e: e.code == 403))
|
||||
other = "worker" if role == "api" else "api"
|
||||
check(f"OpenBao {role} denied existing {other} secret", denied(
|
||||
lambda: bao(role, "messenger/data/" + other, token=token), HTTPError, lambda e: e.code == 403))
|
||||
check("OpenBao same-CA intruder cannot assume API role", denied(
|
||||
lambda: bao("intruder", "auth/cert/login", {"name": "api"}), HTTPError,
|
||||
lambda e: e.code in (400, 403)))
|
||||
check("OpenBao worker credential has no operator access",
|
||||
set(worker) == {"DATABASE_URL", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY", "BROKER_URL"})
|
||||
|
||||
for host, port, path in (
|
||||
("prometheus", 9090, "/api/v1/query?query=up"),
|
||||
("loki", 3100, "/loki/api/v1/labels"),
|
||||
("tempo", 3200, "/api/search?limit=1"),
|
||||
):
|
||||
check(f"{host} data source read role", https(host, port, path, "grafana")[0] == 200)
|
||||
check(f"{host} denies application reads", https(host, port, path, "api")[0] == 403)
|
||||
check("Loki denies Grafana ingest", https("loki", 3100, "/otlp/v1/logs", "grafana", "POST", b"{}")[0] == 403)
|
||||
check("Tempo denies Grafana ingest", https("tempo", 4318, "/v1/traces", "grafana", "POST", b"{}")[0] == 403)
|
||||
loki, tempo = collector_status("collector-export")
|
||||
check("Loki permits Collector ingest", loki in (200, 204))
|
||||
check("Tempo permits Collector ingest", tempo == 200)
|
||||
for host, port in (("broker", 6379), ("collector", 14318), ("collector", 18889),
|
||||
("prometheus", 19090), ("loki", 13100), ("tempo", 13200), ("tempo", 14318)):
|
||||
check(f"closed plaintext port {host}:{port}", denied(
|
||||
lambda: socket.create_connection((host, port), timeout=2), ConnectionRefusedError))
|
||||
print(f"PASS {len(SEEN)} TLS and ACL assertions")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if sys.argv[1:] == ["rotation"]:
|
||||
verify_revocation()
|
||||
elif sys.argv[1:] == ["collector-current"]:
|
||||
loki, tempo = collector_status("collector-export")
|
||||
check("active Collector exporter leaf accepted by Loki and Tempo", loki in (200, 204) and tempo == 200)
|
||||
elif sys.argv[1:] == ["collector-rotation"]:
|
||||
check("previous Collector leaf denied by Loki and Tempo", collector_status("collector-previous") == (403, 403))
|
||||
loki, tempo = collector_status("collector-export")
|
||||
check("replacement Collector leaf accepted by Loki and Tempo", loki in (200, 204) and tempo == 200)
|
||||
else:
|
||||
main()
|
||||
Reference in New Issue
Block a user