Выполнить лабораторную 7 по безопасности мессенджера
This commit is contained in:
@@ -0,0 +1,186 @@
|
||||
"""Measure secure ingress rollover and lease expiry under a fixed local load."""
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import http.client
|
||||
import json
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path[:0] = [str(ROOT), str(ROOT / "tests")]
|
||||
from client import Client
|
||||
from scripts.operator import administrative_bao, operator_credentials, settings, unseal
|
||||
from scripts.pki import SECRETS, renew_edge
|
||||
|
||||
TRUST = SECRETS / "trust"
|
||||
RATE = 8
|
||||
WORKERS = 24
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, port, token):
|
||||
self.port = port
|
||||
self.token = token
|
||||
self.points = []
|
||||
self.pending = threading.BoundedSemaphore(WORKERS)
|
||||
self.stop = threading.Event()
|
||||
self.thread = threading.Thread(target=self.pump)
|
||||
|
||||
def sample(self, ca=None):
|
||||
started = time.monotonic()
|
||||
connection = None
|
||||
try:
|
||||
tls = ssl.create_default_context(cafile=str(ca or TRUST / "edge.crt"))
|
||||
connection = http.client.HTTPSConnection("localhost", self.port, context=tls, timeout=1.5)
|
||||
connection.request("GET", "/api/v1/users/me", headers={"Authorization": "Bearer " + self.token})
|
||||
with connection.getresponse() as response:
|
||||
response.read()
|
||||
result = str(response.status)
|
||||
except ssl.SSLCertVerificationError as exc:
|
||||
result = "expired_certificate" if exc.verify_code == 10 else "untrusted_certificate"
|
||||
except (OSError, http.client.HTTPException):
|
||||
result = "connection_error"
|
||||
finally:
|
||||
if connection:
|
||||
connection.close()
|
||||
return started, result, (time.monotonic() - started) * 1000
|
||||
|
||||
def request(self):
|
||||
try:
|
||||
self.points.append(self.sample())
|
||||
finally:
|
||||
self.pending.release()
|
||||
|
||||
def pump(self):
|
||||
with ThreadPoolExecutor(WORKERS) as pool:
|
||||
deadline = time.monotonic()
|
||||
while not self.stop.is_set():
|
||||
if self.pending.acquire(blocking=False):
|
||||
pool.submit(self.request)
|
||||
else:
|
||||
self.points.append((time.monotonic(), "client_queue_full", 0))
|
||||
deadline += 1 / RATE
|
||||
self.stop.wait(max(0, deadline - time.monotonic()))
|
||||
|
||||
def wait(self, expected, since, timeout):
|
||||
until = time.monotonic() + timeout
|
||||
while time.monotonic() < until:
|
||||
matches = [tick for tick, status, _ in self.points if tick >= since and status == expected]
|
||||
if matches:
|
||||
return round(min(matches) - since, 3)
|
||||
time.sleep(0.08)
|
||||
raise AssertionError(f"Timed out waiting for {expected}")
|
||||
|
||||
def summarize(self, start, end):
|
||||
points = [(status, elapsed) for tick, status, elapsed in self.points if start <= tick < end]
|
||||
status = Counter(status for status, _ in points)
|
||||
timings = sorted(duration for code, duration in points if code == "200")
|
||||
percentiles = ([round(timings[round((len(timings) - 1) * percentile)], 2)
|
||||
for percentile in (0.50, 0.95, 0.99)] if timings else [])
|
||||
return {"seconds": round(end - start, 3), "counts": dict(status),
|
||||
"success_rps": round(status["200"] / (end - start), 2),
|
||||
"error_pct": round(100 * (len(points) - status["200"]) / max(len(points), 1), 2),
|
||||
"success_p50_p95_p99_ms": percentiles}
|
||||
|
||||
|
||||
def pki(*arguments):
|
||||
subprocess.run([sys.executable, "scripts/pki.py", *arguments], cwd=ROOT, check=True,
|
||||
stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def run_experiment():
|
||||
port = int(settings().get("HTTPS_PORT", 8443))
|
||||
bao = administrative_bao()
|
||||
admin = operator_credentials()["root_token"]
|
||||
# Starting at A makes the experiment repeatable after a prior successful A → B rollover.
|
||||
pki("edge-trust", "edge-a")
|
||||
pki("edge-issue", "edge-a", "--reload")
|
||||
pki("edge-retire", "edge-a")
|
||||
client = Client(f"https://localhost:{port}", str(TRUST / "edge.crt"))
|
||||
time.sleep(3)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
original = client.message(alice, chat, "PKI lifecycle synthetic checkpoint")["json"]["id"]
|
||||
attachment, content = client.attachment(alice, chat)
|
||||
load = Load(port, alice["token"])
|
||||
load.thread.start()
|
||||
warmup = time.monotonic()
|
||||
phases = {}
|
||||
report = {"offered_rps": RATE, "max_concurrency": WORKERS, "phase": {}}
|
||||
try:
|
||||
# Keep the effects of the setup reload visible, outside the control window.
|
||||
time.sleep(10)
|
||||
start = time.monotonic()
|
||||
phases["warmup"] = (warmup, start)
|
||||
time.sleep(8)
|
||||
phases["baseline"] = (start, time.monotonic())
|
||||
|
||||
overlap = time.monotonic()
|
||||
pki("edge-trust", "edge-b")
|
||||
pki("edge-issue", "edge-b", "--lifetime", "16", "--reload")
|
||||
time.sleep(3)
|
||||
assert load.sample(TRUST / "edge-a.crt")[1] == "untrusted_certificate"
|
||||
assert load.sample(TRUST / "edge-b.crt")[1] == "200"
|
||||
pki("edge-retire", "edge-b")
|
||||
report["old_ca_only"] = "denied"
|
||||
time.sleep(3)
|
||||
phases["trust_overlap_and_cutover"] = (overlap, time.monotonic())
|
||||
|
||||
expiry_start = time.monotonic()
|
||||
report["expired_detected_after_s"] = load.wait("expired_certificate", expiry_start, 25)
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=1.5) as plain:
|
||||
plain.sendall(b"GET /health/live HTTP/1.0\r\nHost: localhost\r\n\r\n")
|
||||
try:
|
||||
assert b" 200 " not in plain.recv(256)
|
||||
except (ConnectionResetError, TimeoutError):
|
||||
pass
|
||||
report["plaintext_after_expiry"] = "denied"
|
||||
time.sleep(3)
|
||||
phases["short_leaf_expiry"] = (expiry_start, time.monotonic())
|
||||
recovery = time.monotonic()
|
||||
assert renew_edge("edge-b", 86400, 1800, True)
|
||||
report["leaf_recovery_after_s"] = load.wait("200", recovery, 15)
|
||||
time.sleep(5)
|
||||
phases["leaf_renewal"] = (recovery, time.monotonic())
|
||||
|
||||
outage = time.monotonic()
|
||||
bao.request("sys/seal", {}, admin, method="PUT")
|
||||
report["sealed_to_first_503_s"] = load.wait("503", outage, 65)
|
||||
time.sleep(3)
|
||||
phases["sealed_bao"] = (outage, time.monotonic())
|
||||
|
||||
recovery = time.monotonic()
|
||||
unseal(bao)
|
||||
report["unseal_to_first_200_s"] = load.wait("200", recovery, 45)
|
||||
time.sleep(7)
|
||||
phases["lease_recovery"] = (recovery, time.monotonic())
|
||||
client = Client(f"https://localhost:{port}", str(TRUST / "edge.crt"))
|
||||
response = client.call("GET", f"/api/v1/chats/{chat['id']}/messages", actor=alice, schema="MessagePage")
|
||||
assert original in {item["id"] for item in response["json"]["items"]}
|
||||
client.wait_ready(alice, attachment)
|
||||
retrieved = client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=alice)
|
||||
assert retrieved["bytes"] == content
|
||||
report["previous_session_message_and_attachment"] = "verified"
|
||||
finally:
|
||||
load.stop.set()
|
||||
load.thread.join(timeout=5)
|
||||
if bao.request("sys/seal-status")["sealed"]:
|
||||
unseal(bao)
|
||||
pki("edge-trust", "edge-b")
|
||||
renew_edge("edge-b", 86400, 1800, True)
|
||||
|
||||
report["phase"] = {name: load.summarize(*interval) for name, interval in phases.items()}
|
||||
print(json.dumps(report, indent=2, ensure_ascii=False))
|
||||
for phase in report["phase"].values():
|
||||
assert "client_queue_full" not in phase["counts"], "load generator saturated"
|
||||
assert report["phase"]["short_leaf_expiry"]["counts"]["expired_certificate"] > 0
|
||||
assert report["phase"]["sealed_bao"]["counts"]["503"] > 0
|
||||
assert report["phase"]["baseline"]["error_pct"] == 0, "control window returned errors"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_experiment()
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Public security assertions using disposable users and fixtures only."""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from scripts.operator import settings
|
||||
|
||||
|
||||
def db(sql):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "postgres", "psql", "-XAt", "-U", "owner",
|
||||
"-d", "messenger", "--set=ON_ERROR_STOP=1"], input=sql.encode(), capture_output=True, check=True, cwd=ROOT,
|
||||
)
|
||||
return result.stdout.decode().strip()
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
return {"Authorization": "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()}
|
||||
|
||||
|
||||
def main():
|
||||
port = settings().get("HTTPS_PORT", "8443")
|
||||
ca = str(ROOT / "secrets/trust/edge.crt")
|
||||
client = Client(f"https://localhost:{port}", ca)
|
||||
verifier = ssl.create_default_context(cafile=ca)
|
||||
with socket.create_connection(("127.0.0.1", int(port)), timeout=3) as sock:
|
||||
try:
|
||||
with verifier.wrap_socket(sock, server_hostname="wrong.lab7"):
|
||||
raise AssertionError("certificate accepted for an unrelated hostname")
|
||||
except ssl.SSLCertVerificationError:
|
||||
pass
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
attachment, _ = client.attachment(alice, chat)
|
||||
fake = {"X-User-Id": alice["id"]}
|
||||
for suffix in ("", "/content"):
|
||||
client.call("GET", "/api/v1/attachments/" + attachment["id"] + suffix, 404, actor=eve, headers=fake)
|
||||
me = client.call("GET", "/api/v1/users/me", actor=eve, headers=fake, schema="User")["json"]
|
||||
check(me["id"] == eve["id"], "header overrode Bearer identity")
|
||||
other = client.call("POST", "/api/v1/chats", 201, actor=eve, schema="Chat",
|
||||
body={"title": "Synthetic", "member_ids": [eve["id"], bob["id"]]})["json"]
|
||||
client.call("POST", f"/api/v1/chats/{other['id']}/messages", (400, 404, 409),
|
||||
actor=eve, body={"text": "synthetic", "attachment_ids": [attachment["id"]]},
|
||||
headers={"Idempotency-Key": uuid4().hex})
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=eve)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=eve)
|
||||
digest = hashlib.sha256(bob["token"].encode()).hexdigest()
|
||||
db(f"UPDATE sessions SET expires_at=created_at+interval '1 second' WHERE token_hash='{digest}';")
|
||||
time.sleep(1.2)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=bob)
|
||||
|
||||
username = "old_" + uuid4().hex[:12]
|
||||
password = "Synthetic-" + uuid4().hex
|
||||
client.call("POST", "/api/v1/users", 201, body={"username": username, "display_name": "Rehash", "password": password})
|
||||
old_hash = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "api", "python", "-c",
|
||||
"import sys; from argon2 import PasswordHasher; print(PasswordHasher(time_cost=2,memory_cost=19456,parallelism=1).hash(sys.stdin.read()))"],
|
||||
input=password.encode(), capture_output=True, check=True, cwd=ROOT,
|
||||
).stdout.decode().strip()
|
||||
check(old_hash.startswith("$argon2id$"), "failed to create legacy fixture")
|
||||
db(f"UPDATE users SET password_hash='{old_hash}' WHERE username='{username}';")
|
||||
check(db(f"SELECT password_hash LIKE '%m=19456,t=2,p=1%' FROM users WHERE username='{username}';") == "t",
|
||||
"legacy fixture missing")
|
||||
client.call("POST", "/api/v1/auth/sessions", 201, headers=basic(username, password))
|
||||
check(db(f"SELECT password_hash LIKE '%m=24576,t=2,p=1%' FROM users WHERE username='{username}';") == "t",
|
||||
"password not upgraded")
|
||||
|
||||
name = "limit_" + uuid4().hex[:12]
|
||||
while time.time() % 10 > 6:
|
||||
time.sleep(0.1)
|
||||
workers = set()
|
||||
codes = []
|
||||
for _ in range(10):
|
||||
reply = client.call("POST", "/api/v1/auth/sessions", (401, 429), headers=basic(name, "Wrong-synthetic-secret"))
|
||||
codes.append(reply["status"])
|
||||
workers.add(reply["headers"]["X-Instance-Id"])
|
||||
if reply["status"] == 429:
|
||||
check(1 <= int(reply["headers"]["Retry-After"]) <= 10, "missing retry window")
|
||||
check(codes.count(401) == 8 and codes.count(429) == 2, "shared rate limit did not engage at 8")
|
||||
check(len(workers) >= 2, "rate test must see both replicas")
|
||||
print(json.dumps({"hostname_mismatch": "PASS", "acl": "PASS", "logout": "PASS", "expiry": "PASS", "argon2_rehash": "PASS",
|
||||
"login_attempt_statuses": codes, "replica_count": len(workers)}, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Rotate a worker's scoped key while synthetic jobs are queued."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path[:0] = [str(ROOT), str(ROOT / "tests")]
|
||||
from client import Client
|
||||
from scripts.operator import administrative_bao, operator_credentials, settings
|
||||
|
||||
PROBE = """
|
||||
import json, sys, secrets
|
||||
sys.path.insert(0, "/audit")
|
||||
from botocore.exceptions import ClientError
|
||||
from tls_matrix import storage
|
||||
client = storage(json.load(sys.stdin))
|
||||
try:
|
||||
client.put_object(Bucket="messenger-attachments",
|
||||
Key="attachments/audit-" + secrets.token_hex(8), Body=b"synthetic")
|
||||
except ClientError as error:
|
||||
print(error.response["Error"]["Code"])
|
||||
else:
|
||||
print("ok")
|
||||
"""
|
||||
|
||||
|
||||
def command(*args, **kwargs):
|
||||
return subprocess.run(args, cwd=ROOT, check=True, text=True, **kwargs)
|
||||
|
||||
|
||||
def probe(key):
|
||||
result = command("docker", "compose", "run", "--rm", "--no-deps", "-T",
|
||||
"audit", "python", "-c", PROBE, input=json.dumps(key), stdout=subprocess.PIPE)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
port = settings().get("HTTPS_PORT", "8443")
|
||||
client = Client(f"https://localhost:{port}", str(ROOT / "secrets/trust/edge.crt"))
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
bao = administrative_bao()
|
||||
admin = operator_credentials()["root_token"]
|
||||
path = "runtime/data/worker"
|
||||
old = bao.request(path, token=admin)["data"]["data"]
|
||||
assert probe(old) == "ok"
|
||||
before, first_bytes = client.attachment(alice, chat)
|
||||
start = time.monotonic()
|
||||
prior = command(sys.executable, "scripts/operator.py", "rotate-s3-add", stdout=subprocess.PIPE).stdout.strip()
|
||||
assert prior == old["S3_ACCESS_KEY_ID"]
|
||||
current = bao.request(path, token=admin)["data"]["data"]
|
||||
assert current != old and probe(current) == "ok"
|
||||
during, second_bytes = client.attachment(alice, chat)
|
||||
for attachment, content in ((before, first_bytes), (during, second_bytes)):
|
||||
client.wait_ready(alice, attachment)
|
||||
assert client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=alice)["bytes"] == content
|
||||
command(sys.executable, "scripts/operator.py", "rotate-s3-remove", prior, stdout=subprocess.DEVNULL)
|
||||
decision = probe(old)
|
||||
assert decision in ("AccessDenied", "InvalidAccessKeyId", "SignatureDoesNotMatch"), decision
|
||||
after, body = client.attachment(alice, chat)
|
||||
client.wait_ready(alice, after)
|
||||
assert client.call("GET", f"/api/v1/attachments/{after['id']}/content", actor=alice)["bytes"] == body
|
||||
print(json.dumps({"jobs_with_verified_original": 3, "old_key_before": "ok",
|
||||
"old_key_after": decision, "new_key": "ok", "seconds": round(time.monotonic() - start, 2)}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Follow a synthetic request via Grafana and check logs/traces for sensitive values."""
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path[:0] = [str(ROOT), str(ROOT / "tests")]
|
||||
from client import Client
|
||||
from scripts.operator import settings
|
||||
from scripts.pki import SECRETS
|
||||
|
||||
CONFIG = settings()
|
||||
GRAFANA = "https://127.0.0.1:" + CONFIG.get("GRAFANA_PORT", "3007")
|
||||
TLS = ssl.create_default_context(cafile=str(SECRETS / "trust" / "grafana.crt"))
|
||||
|
||||
|
||||
def query(source, path, **parameters):
|
||||
password = (SECRETS / "runtime/grafana-config/grafana_password").read_text().strip()
|
||||
credentials = base64.b64encode(("admin:" + password).encode()).decode()
|
||||
url = f"{GRAFANA}/api/datasources/proxy/uid/{source}{path}"
|
||||
if parameters:
|
||||
url += "?" + urlencode(parameters)
|
||||
request = Request(url, headers={"Authorization": "Basic " + credentials})
|
||||
with urlopen(request, context=TLS, timeout=5) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def poll(action, nonempty, seconds=30):
|
||||
end = time.monotonic() + seconds
|
||||
while time.monotonic() < end:
|
||||
value = action()
|
||||
if nonempty(value):
|
||||
return value
|
||||
time.sleep(1)
|
||||
raise AssertionError("telemetry did not arrive before deadline")
|
||||
|
||||
|
||||
def main():
|
||||
client = Client("https://localhost:" + CONFIG.get("HTTPS_PORT", "8443"), str(SECRETS / "trust/edge.crt"))
|
||||
actor = client.user("audit")
|
||||
probe = "sensitive-canary-" + uuid4().hex
|
||||
start = time.time_ns() - 3_000_000_000
|
||||
response = client.call("GET", "/api/v1/users/me?probe=" + probe, 400, actor=actor,
|
||||
headers={"X-User-Id": probe})
|
||||
request_id = response["headers"]["X-Request-Id"]
|
||||
log = poll(
|
||||
lambda: query("loki", "/loki/api/v1/query_range",
|
||||
query='{service_name="messenger-api"} | request_id="' + request_id + '"',
|
||||
start=str(start), limit=50),
|
||||
lambda value: value.get("data", {}).get("result"),
|
||||
)
|
||||
traces = poll(
|
||||
lambda: query("tempo", "/api/search", q='{span.request_id = "' + request_id + '"}', limit=3),
|
||||
lambda value: value.get("traces"),
|
||||
)
|
||||
trace_id = traces["traces"][0]["traceID"]
|
||||
trace = query("tempo", "/api/traces/" + trace_id)
|
||||
metrics = poll(lambda: query("prometheus", "/api/v1/query", query='up{job="messenger"}'),
|
||||
lambda value: value.get("data", {}).get("result"))
|
||||
assert any(series["value"][1] == "1" for series in metrics["data"]["result"])
|
||||
payload = json.dumps([log, trace], ensure_ascii=False)
|
||||
for value in (actor["token"], actor["registration"]["password"], actor["registration"]["username"], probe):
|
||||
assert value not in payload, "a synthetic sensitive value appeared in telemetry"
|
||||
print("PASS Grafana queries over mTLS: request in Loki and Tempo, Prometheus scrape up; secret canaries absent")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Positive and negative checks inside the Compose network of the local test fixture."""
|
||||
import json
|
||||
import secrets
|
||||
import socket
|
||||
import ssl
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
import pika
|
||||
import psycopg
|
||||
from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest
|
||||
from bao_client import Bao, BaoError
|
||||
|
||||
IDENTITIES = Path("/run/audit")
|
||||
CA = str(IDENTITIES / "auditor" / "ca.crt")
|
||||
QUEUE = "attachment-processing-v1"
|
||||
|
||||
|
||||
def context(identity=None):
|
||||
tls = ssl.create_default_context(cafile=CA)
|
||||
tls.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
if identity:
|
||||
folder = IDENTITIES / identity
|
||||
tls.load_cert_chain(folder / "service.crt", folder / "service.key")
|
||||
return tls
|
||||
|
||||
|
||||
def http(url, identity=None, body=None, headers=None):
|
||||
request = Request(url, data=body, headers=headers or {})
|
||||
with urlopen(request, context=context(identity), timeout=4) as response:
|
||||
return response.status, response.read()
|
||||
|
||||
|
||||
def denied(action, exceptions):
|
||||
try:
|
||||
action()
|
||||
except exceptions:
|
||||
return
|
||||
raise AssertionError("an expected denial did not occur")
|
||||
|
||||
|
||||
def expires_at_role(connection):
|
||||
return connection.execute("SELECT rolvaliduntil FROM pg_roles WHERE rolname=current_user").fetchone()[0]
|
||||
|
||||
|
||||
def check_ingress():
|
||||
host = socket.getaddrinfo("api", 8080, socket.AF_INET, socket.SOCK_STREAM)
|
||||
replicas = {info[4][0] for info in host}
|
||||
assert len(replicas) >= 2, "expected at least two API replicas"
|
||||
|
||||
def probe(address, identity, server_name="api"):
|
||||
with socket.create_connection((address, 8080), timeout=3) as sock:
|
||||
with context(identity).wrap_socket(sock, server_hostname=server_name) as peer:
|
||||
peer.sendall(b"GET /health/ready HTTP/1.0\r\nHost: api\r\n\r\n")
|
||||
response = peer.recv(256)
|
||||
if not response:
|
||||
raise ConnectionError("peer closed before HTTP")
|
||||
assert response.startswith(b"HTTP/1.0 200 "), response.split(b"\r\n")[0]
|
||||
for address in replicas:
|
||||
probe(address, "ingress")
|
||||
for identity in (None, "foreign", "worker"):
|
||||
denied(lambda: probe(address, identity), (OSError,))
|
||||
denied(lambda: probe(address, "ingress", "wrong.lab7"), (ssl.SSLCertVerificationError,))
|
||||
print(f"PASS LB → {len(replicas)} API: valid client; none/foreign CA/wrong identity/hostname denied")
|
||||
|
||||
|
||||
def broker(identity):
|
||||
return pika.BlockingConnection(pika.ConnectionParameters(
|
||||
host="rabbitmq", port=5671, virtual_host="/messenger",
|
||||
credentials=pika.credentials.ExternalCredentials(),
|
||||
ssl_options=pika.SSLOptions(context(identity), "rabbitmq"),
|
||||
socket_timeout=3, stack_timeout=5,
|
||||
))
|
||||
|
||||
|
||||
def check_broker():
|
||||
for role in ("api", "worker"):
|
||||
with broker(role):
|
||||
pass
|
||||
for identity in (None, "foreign", "auditor"):
|
||||
denied(lambda: broker(identity), (pika.exceptions.AMQPConnectionError, OSError))
|
||||
with broker("api") as connection:
|
||||
denied(lambda: connection.channel().basic_get(QUEUE),
|
||||
(pika.exceptions.ChannelClosedByBroker,))
|
||||
with broker("worker") as connection:
|
||||
denied(lambda: connection.channel().queue_declare("lab7-acl-denied"),
|
||||
(pika.exceptions.ChannelClosedByBroker,))
|
||||
denied(lambda: socket.create_connection(("rabbitmq", 5672), timeout=2), (OSError,))
|
||||
print("PASS RabbitMQ EXTERNAL + ACL: api/worker allowed, unknown identities/roles/plaintext denied")
|
||||
|
||||
|
||||
def check_telemetry_transport():
|
||||
ingest = "https://collector:4318/v1/traces"
|
||||
headers = {"Content-Type": "application/x-protobuf"}
|
||||
for role in ("api", "worker"):
|
||||
assert http(ingest, role, b"", headers)[0] == 200
|
||||
for identity in (None, "foreign"):
|
||||
denied(lambda: http(ingest, identity, b"", headers), (URLError, OSError))
|
||||
denied(lambda: http(ingest, "auditor", b"", headers), (HTTPError,))
|
||||
for port in (8888, 8889):
|
||||
endpoint = f"https://collector:{port}/metrics"
|
||||
assert http(endpoint, "prometheus")[0] == 200
|
||||
denied(lambda: http(endpoint, "worker"), (HTTPError,))
|
||||
logs = ExportLogsServiceRequest()
|
||||
resource = logs.resource_logs.add()
|
||||
label = resource.resource.attributes.add()
|
||||
label.key, label.value.string_value = "service.name", "lab7-audit"
|
||||
record = resource.scope_logs.add().log_records.add()
|
||||
record.body.string_value = "synthetic TLS audit"
|
||||
record.time_unix_nano = time.time_ns()
|
||||
assert http("https://loki:3100/otlp/v1/logs", "collector", logs.SerializeToString(), headers)[0] in (200, 204)
|
||||
assert http("https://tempo:4318/v1/traces", "collector", b"", headers)[0] == 200
|
||||
queries = (
|
||||
"https://prometheus:9090/api/v1/query?query=up",
|
||||
"https://loki:3100/loki/api/v1/labels",
|
||||
"https://tempo:3200/api/search?limit=1",
|
||||
)
|
||||
for query in queries:
|
||||
assert http(query, "grafana")[0] == 200
|
||||
denied(lambda: http(query, "collector"), (HTTPError,))
|
||||
denied(lambda: http("https://tempo:4318/v1/traces", "grafana", b"", headers), (HTTPError,))
|
||||
for host, port in (("loki", 13100), ("tempo", 13200), ("collector", 14318),
|
||||
("prometheus", 19090), ("rustfs", 19000), ("loki", 9095), ("tempo", 9095)):
|
||||
denied(lambda: socket.create_connection((host, port), timeout=2), (OSError,))
|
||||
assert http("https://grafana:3000/api/health")[0] == 200
|
||||
print("PASS Collector mTLS, backend role ACL, scrape/Grafana mTLS, localhost-only plaintext hops")
|
||||
|
||||
|
||||
def session(role):
|
||||
bao = Bao("https://openbao:8200", context(role))
|
||||
auth = bao.request("auth/cert/login", {"name": role})["auth"]
|
||||
assert auth["lease_duration"] <= 45 and auth["policies"] == [role]
|
||||
return bao, auth["client_token"]
|
||||
|
||||
|
||||
def postgres(credentials, mode="verify-full"):
|
||||
return psycopg.connect(host="postgres", dbname="messenger", user=credentials["username"],
|
||||
password=credentials["password"], sslmode=mode, sslrootcert=CA,
|
||||
connect_timeout=3)
|
||||
|
||||
|
||||
def storage(config):
|
||||
return boto3.client("s3", endpoint_url="https://rustfs:9000", region_name="us-east-1",
|
||||
aws_access_key_id=config["S3_ACCESS_KEY_ID"],
|
||||
aws_secret_access_key=config["S3_SECRET_ACCESS_KEY"],
|
||||
verify=CA, config=Config(retries={"max_attempts": 0}))
|
||||
|
||||
|
||||
def check_credentials():
|
||||
s3 = {}
|
||||
denied(lambda: Bao("https://openbao:8200", context("auditor")).request(
|
||||
"auth/cert/login", {"name": "worker"}), (BaoError,))
|
||||
denied(lambda: Bao("https://openbao:8200", context()).request(
|
||||
"sys/policies/acl"), (BaoError,))
|
||||
for role, other in (("api", "worker"), ("worker", "api")):
|
||||
bao, token = session(role)
|
||||
for path in (f"runtime/data/{other}", f"database/creds/{other}", "sys/policies/acl/root"):
|
||||
denied(lambda: bao.request(path, token=token), (BaoError,))
|
||||
denied(lambda: bao.request(f"runtime/data/{role}", {"data": {}}, token), (BaoError,))
|
||||
config = bao.request(f"runtime/data/{role}", token=token)["data"]["data"]
|
||||
assert ("CURSOR_SECRET" in config) == (role == "api")
|
||||
s3[role] = storage(config)
|
||||
issued = bao.request(f"database/creds/{role}", token=token)
|
||||
assert issued["lease_duration"] <= 40 and issued["renewable"]
|
||||
with postgres(issued["data"]) as connection:
|
||||
assert connection.execute("SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()").fetchone() == (True,)
|
||||
until = expires_at_role(connection)
|
||||
if role == "worker":
|
||||
denied(lambda: connection.execute("SELECT password_hash FROM users LIMIT 1"),
|
||||
(psycopg.errors.InsufficientPrivilege,))
|
||||
connection.rollback()
|
||||
time.sleep(2)
|
||||
bao.request("sys/leases/renew/" + issued["lease_id"], {}, token)
|
||||
with postgres(issued["data"]) as connection:
|
||||
assert expires_at_role(connection) > until
|
||||
denied(lambda: postgres(issued["data"], "disable"), (psycopg.OperationalError,))
|
||||
bucket = "messenger-attachments"
|
||||
key = "staging/audit-" + secrets.token_hex(8)
|
||||
api, worker = s3["api"], s3["worker"]
|
||||
api.put_object(Bucket=bucket, Key=key, Body=b"synthetic fixture")
|
||||
with worker.get_object(Bucket=bucket, Key=key)["Body"] as body:
|
||||
assert body.read() == b"synthetic fixture"
|
||||
denied(lambda: worker.put_object(Bucket=bucket, Key="outside/" + key, Body=b"fixture"), (ClientError,))
|
||||
denied(lambda: api.put_object(Bucket=bucket, Key="attachments/" + key, Body=b"fixture"), (ClientError,))
|
||||
denied(lambda: worker.list_buckets(), (ClientError,))
|
||||
worker.delete_object(Bucket=bucket, Key=key)
|
||||
print("PASS OpenBao scopes & renewal, PostgreSQL verify-full and worker DB ACL, S3 prefix ACL")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
check_ingress()
|
||||
check_broker()
|
||||
check_telemetry_transport()
|
||||
check_credentials()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Contract boundaries for decoded pixels using two small synthetic PNG files."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path[:0] = [str(ROOT), str(ROOT / "tests")]
|
||||
from client import Client
|
||||
from scripts.operator import settings
|
||||
|
||||
|
||||
def chunk(tag, data):
|
||||
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data))
|
||||
|
||||
|
||||
def rgba_png(width, height):
|
||||
stream = zlib.compressobj(1)
|
||||
row = b"\0" + b"\x80\x70\x60\x60" * width
|
||||
data = b"".join(stream.compress(row) for _ in range(height)) + stream.flush()
|
||||
header = struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", data) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def main():
|
||||
port = settings().get("HTTPS_PORT", "8443")
|
||||
client = Client(f"https://localhost:{port}", str(ROOT / "secrets/trust/edge.crt"), timeout=15)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
upload = f"/api/v1/chats/{chat['id']}/attachments?filename=large.png"
|
||||
headers = {"Content-Type": "image/png"}
|
||||
client.call("POST", upload, 413, actor=alice, raw=rgba_png(8000, 5001), headers=headers)
|
||||
raw = rgba_png(8000, 5000)
|
||||
received = client.call("POST", upload, 202, actor=alice, raw=raw, headers=headers, schema="Attachment")
|
||||
ready = client.wait_ready(alice, received["json"])
|
||||
assert ready["sha256"] == hashlib.sha256(raw).hexdigest()
|
||||
assert client.call("GET", f"/api/v1/attachments/{ready['id']}/content", actor=alice)["bytes"] == raw
|
||||
print("PASS 40,008,000 decoded pixels rejected; 40,000,000 decoded pixels processed, bytes preserved")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user