Закрыть оценку 4 и трек 1: отзыв leaf и права worker.

Брокер и Collector принимают только серийный номер текущего leaf. Прогон показывает rehash, 429 до дорогого Argon2, отказ stranger, ротацию пароля worker и сохранность задания.
This commit is contained in:
2026-11-26 20:40:00 +03:00
parent 9de3b01659
commit 2d4c3163fa
16 changed files with 889 additions and 17 deletions
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
"""Same-CA identity check for the broker and the collector.
The public client does not present a certificate. This probe joins the
compose networks and checks that a certificate signed by our CA is still
rejected when its SAN or leaf serial is not the API or worker identity.
"""
from __future__ import annotations
import socket
import ssl
import subprocess
import sys
from pathlib import Path
PROBE = Path(__file__).resolve()
ROOT = PROBE.parents[1] if len(PROBE.parents) > 1 else PROBE.parent
CERTS = Path("/certs") if "--internal" in sys.argv else ROOT / "certs"
def context(cert: Path | None, key: Path | None) -> ssl.SSLContext:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
ctx.load_verify_locations(CERTS / "ca.crt")
ctx.check_hostname = True
ctx.verify_mode = ssl.CERT_REQUIRED
if cert is not None and key is not None:
ctx.load_cert_chain(cert, key)
return ctx
def rabbit(cert: Path | None, key: Path | None) -> str:
try:
raw = socket.create_connection(("rabbitmq", 5671), timeout=5)
tls = context(cert, key).wrap_socket(raw, server_hostname="rabbitmq")
tls.sendall(b"AMQP\x00\x00\x09\x01")
data = tls.recv(8)
tls.close()
return "amqp" if data else "closed"
except ssl.SSLError as exc:
return "ssl:" + exc.__class__.__name__
except OSError as exc:
return "os:" + exc.__class__.__name__
def otel(cert: Path | None, key: Path | None) -> str:
try:
raw = socket.create_connection(("otel-collector", 4318), timeout=5)
tls = context(cert, key).wrap_socket(raw, server_hostname="otel-collector")
tls.sendall(b"GET / HTTP/1.1\r\nHost: otel-collector\r\nConnection: close\r\n\r\n")
data = b""
while True:
chunk = tls.recv(1024)
if not chunk:
break
data += chunk
tls.close()
head = data.split(b"\r\n", 1)[0].decode("ascii", "replace")
return head or "closed"
except ssl.SSLError as exc:
return "ssl:" + exc.__class__.__name__
except OSError as exc:
return "os:" + exc.__class__.__name__
def expect_closed(label: str, result: str) -> None:
denied = result == "closed" or result.startswith("ssl:") or result.startswith("os:") or result.startswith("HTTP/1.1 403")
if not denied:
raise SystemExit("FAIL %s was accepted: %s" % (label, result))
print("PASS", label, result)
def internal() -> None:
pairs = (
("api leaf", CERTS / "api-client.crt", CERTS / "api-client.key"),
("worker leaf", CERTS / "worker-client.crt", CERTS / "worker-client.key"),
)
for label, cert, key in pairs:
rabbit_result = rabbit(cert, key)
otel_result = otel(cert, key)
if rabbit_result != "amqp":
raise SystemExit("FAIL %s broker: %s" % (label, rabbit_result))
if not otel_result.startswith("HTTP/"):
raise SystemExit("FAIL %s collector: %s" % (label, otel_result))
print("PASS", label, "broker", rabbit_result, "collector", otel_result)
expect_closed("broker no cert", rabbit(None, None))
expect_closed("broker stranger same CA", rabbit(CERTS / "stranger.crt", CERTS / "stranger.key"))
expect_closed("broker other CA", rabbit(CERTS / "other-client.crt", CERTS / "other-client.key"))
expect_closed("collector no cert", otel(None, None))
expect_closed("collector stranger same CA", otel(CERTS / "stranger.crt", CERTS / "stranger.key"))
expect_closed("collector other CA", otel(CERTS / "other-client.crt", CERTS / "other-client.key"))
revoked = CERTS / "worker-client.revoked.crt"
if revoked.is_file():
expect_closed(
"broker revoked worker leaf",
rabbit(revoked, CERTS / "worker-client.revoked.key"),
)
expect_closed(
"collector revoked worker leaf",
otel(revoked, CERTS / "worker-client.revoked.key"),
)
expired = CERTS / "expired-worker.crt"
if expired.is_file():
expect_closed(
"broker expired worker leaf",
rabbit(expired, CERTS / "expired-worker.key"),
)
expect_closed(
"collector expired worker leaf",
otel(expired, CERTS / "expired-worker.key"),
)
def main() -> None:
if "--internal" in sys.argv:
internal()
return
if not (CERTS / "ca.crt").is_file():
raise SystemExit("missing certs/ca.crt")
completed = subprocess.run(
[
"docker",
"compose",
"--env-file",
".env",
"run",
"--rm",
"--no-deps",
"--entrypoint",
"python",
"-v",
"%s:/probe.py:ro" % PROBE,
"-v",
"%s:/certs:ro" % CERTS,
"api",
"/probe.py",
"--internal",
],
cwd=ROOT,
check=False,
)
if completed.returncode != 0:
raise SystemExit(completed.returncode)
if __name__ == "__main__":
sys.exit(main() or 0)
+78
View File
@@ -0,0 +1,78 @@
"""Seal OpenBao, prove AppRole login fails, then unseal. Prints no key material."""
from __future__ import annotations
import json
import os
import ssl
import urllib.error
import urllib.request
from pathlib import Path
ADDR = os.environ["BAO_ADDR"].rstrip("/")
CAFILE = os.environ["TLS_CA_FILE"]
INIT = json.loads(Path(os.environ["BAO_INIT_FILE"]).read_text(encoding="utf-8"))
ROLE = Path("/secrets/worker.role_id").read_text(encoding="utf-8").strip()
SECRET = Path("/secrets/worker.secret_id").read_text(encoding="utf-8").strip()
def ctx() -> ssl.SSLContext:
context = ssl.create_default_context(cafile=CAFILE)
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
context.minimum_version = ssl.TLSVersion.TLSv1_2
return context
def call(method: str, path: str, body: dict | None = None, token: str = "") -> int:
data = None if body is None else json.dumps(body).encode("utf-8")
request = urllib.request.Request(ADDR + path, data=data, method=method)
request.add_header("Content-Type", "application/json")
if token:
request.add_header("X-Vault-Token", token)
try:
with urllib.request.urlopen(request, context=ctx(), timeout=5) as response:
response.read()
return response.status
except urllib.error.HTTPError as exc:
exc.read()
return exc.code
def main() -> None:
token = INIT.get("root_token") or ""
key = (INIT.get("keys") or [""])[0]
if not token or not key:
raise SystemExit("operator init file is incomplete")
sealed = False
try:
code = call("PUT", "/v1/sys/seal", token=token)
if code not in (200, 204):
raise SystemExit("FAIL seal returned HTTP %s" % code)
sealed = True
login = call(
"POST",
"/v1/auth/approle/login",
{"role_id": ROLE, "secret_id": SECRET},
)
if login == 200:
raise SystemExit("FAIL sealed OpenBao accepted AppRole")
print("PASS sealed OpenBao rejects AppRole", login)
finally:
if sealed:
status = call("POST", "/v1/sys/unseal", {"key": key})
if status != 200:
raise SystemExit("FAIL unseal returned HTTP %s" % status)
print("PASS OpenBao unsealed")
login = call(
"POST",
"/v1/auth/approle/login",
{"role_id": ROLE, "secret_id": SECRET},
)
if login != 200:
raise SystemExit("FAIL AppRole login after unseal HTTP %s" % login)
print("PASS AppRole login after unseal")
if __name__ == "__main__":
main()
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""Rehash and shared login budget. Prints parameters and timings only."""
from __future__ import annotations
import base64
import json
import socket
import ssl
import subprocess
import sys
import time
import uuid
from pathlib import Path
PROBE = Path(__file__).resolve()
ROOT = PROBE.parents[1] if len(PROBE.parents) > 1 else PROBE.parent
def https(method: str, path: str, body: bytes | None = None, headers: dict | None = None) -> tuple[int, str]:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
ctx.load_verify_locations("/certs/ca.crt")
ctx.check_hostname = True
ctx.verify_mode = ssl.CERT_REQUIRED
raw = socket.create_connection(("host.docker.internal", 8443), timeout=10)
tls = ctx.wrap_socket(raw, server_hostname="localhost")
header_lines = ["%s %s HTTP/1.1" % (method, path), "Host: localhost", "Connection: close"]
for key, value in (headers or {}).items():
header_lines.append("%s: %s" % (key, value))
if body is not None:
header_lines.append("Content-Type: application/json")
header_lines.append("Content-Length: %s" % len(body))
payload = ("\r\n".join(header_lines) + "\r\n\r\n").encode("ascii")
if body is not None:
payload += body
tls.sendall(payload)
data = b""
while True:
chunk = tls.recv(8192)
if not chunk:
break
data += chunk
tls.close()
head, _, _rest = data.partition(b"\r\n\r\n")
text = head.decode("latin1", "replace")
status = int(text.split(" ", 2)[1])
return status, text
def internal() -> None:
import asyncio
from argon2 import PasswordHasher
from app import bao, db
username = "rehash_" + uuid.uuid4().hex[:10]
password = "synthetic-rehash-password"
status, _headers = https(
"POST",
"/api/v1/users",
json.dumps(
{"username": username, "display_name": "rehash probe", "password": password}
).encode("utf-8"),
)
if status != 201:
raise SystemExit("FAIL register %s" % status)
bao.apply()
async def memory_param() -> str:
pool = await db.connect()
try:
row = await pool.fetchrow(
"SELECT substring(password_hash from 'm=[0-9]+') AS param FROM users WHERE username = $1",
username,
)
finally:
await db.close()
return row["param"]
weak = PasswordHasher(memory_cost=8192, time_cost=1, parallelism=1, hash_len=32, salt_len=16).hash(password)
async def store_weak() -> None:
pool = await db.connect()
try:
await pool.execute(
"UPDATE users SET password_hash = $1 WHERE username = $2",
weak,
username,
)
finally:
await db.close()
asyncio.run(store_weak())
before = asyncio.run(memory_param())
print("rehash_before", before)
basic = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
started = time.perf_counter()
status, headers = https(
"POST",
"/api/v1/auth/sessions",
headers={"Authorization": "Basic " + basic},
)
login_ms = (time.perf_counter() - started) * 1000
if status != 201:
raise SystemExit("FAIL rehash login %s" % status)
after = asyncio.run(memory_param())
print("rehash_after", after, "login_ms=%.1f" % login_ms)
if before != "m=8192" or after != "m=19456":
raise SystemExit("FAIL rehash did not move to the floor")
wrong = base64.b64encode((username + ":wrong-password").encode("utf-8")).decode("ascii")
limited_status = None
for attempt in range(2, 12):
started = time.perf_counter()
status, headers = https(
"POST",
"/api/v1/auth/sessions",
headers={"Authorization": "Basic " + wrong},
)
elapsed = (time.perf_counter() - started) * 1000
if status == 429:
if "retry-after" not in headers.lower():
raise SystemExit("FAIL 429 without Retry-After")
print("rate_limit_attempt", attempt, "status", status, "elapsed_ms=%.1f" % elapsed)
limited_status = status
break
if status != 401:
raise SystemExit("FAIL unexpected login status %s" % status)
if attempt == 8:
print("argon2_reject_attempt", attempt, "elapsed_ms=%.1f" % elapsed)
if limited_status != 429:
raise SystemExit("FAIL shared rate limit did not return 429")
print("PASS rehash and shared login limit")
def main() -> None:
if "--internal" in sys.argv:
internal()
return
completed = subprocess.run(
[
"docker",
"compose",
"--env-file",
".env",
"run",
"--rm",
"--no-deps",
"--entrypoint",
"python",
"-e",
"PYTHONPATH=/app",
"-v",
"%s:/probe.py:ro" % PROBE,
"api",
"/probe.py",
"--internal",
],
cwd=ROOT,
check=False,
)
if completed.returncode != 0:
raise SystemExit(completed.returncode)
if __name__ == "__main__":
sys.exit(main() or 0)
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""Grade 4 rotation/revocation plus track 1, the worker compromise comparison.
Stops the worker, leaves one upload queued, revokes the old worker leaf,
rotates the worker database password, then shows the same job still reaches ready.
"""
from __future__ import annotations
import secrets
import shutil
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client # noqa: E402
def run(args: list[str], check: bool = True) -> subprocess.CompletedProcess:
completed = subprocess.run(args, cwd=ROOT, check=False)
if check and completed.returncode != 0:
raise SystemExit("command failed: %s" % " ".join(args[:6]))
return completed
def compose(*args: str, check: bool = True) -> subprocess.CompletedProcess:
return run(["docker", "compose", "--env-file", ".env", *args], check=check)
def reissue(name: str, cn: str, eku: str, san: str, not_before: str = "", not_after: str = "") -> None:
env_args: list[str] = []
if not_before:
env_args.extend(["-e", "NOT_BEFORE=" + not_before])
if not_after:
env_args.extend(["-e", "NOT_AFTER=" + not_after])
run(
[
"docker",
"run",
"--rm",
*env_args,
"-v",
"%s:/work" % (ROOT / "certs"),
"-v",
"%s:/reissue-leaf.sh:ro" % (ROOT / "scripts" / "reissue-leaf.sh"),
"alpine:3.21.3",
"sh",
"/reissue-leaf.sh",
name,
cn,
eku,
san,
]
)
def worker_rights() -> None:
completed = compose(
"run",
"--rm",
"--no-deps",
"--entrypoint",
"python",
"-e",
"PYTHONPATH=/app",
"-e",
"BAO_ROLE_ID_FILE=/run/worker/role_id",
"-e",
"BAO_SECRET_ID_FILE=/run/worker/secret_id",
"-e",
"BAO_SECRET_PATH=secret/data/messenger/worker",
"-e",
"TLS_CERT_FILE=/certs/worker-client.crt",
"-e",
"TLS_KEY_FILE=/certs/worker-client.key",
"-v",
"%s:/run/worker/role_id:ro" % (ROOT / "secrets" / "worker.role_id"),
"-v",
"%s:/run/worker/secret_id:ro" % (ROOT / "secrets" / "worker.secret_id"),
"-v",
"%s:/certs/worker-client.crt:ro" % (ROOT / "certs" / "worker-client.crt"),
"-v",
"%s:/certs/worker-client.key:ro" % (ROOT / "certs" / "worker-client.key"),
"-v",
"%s:/probe.py:ro" % (ROOT / "student-tests" / "worker_rights.py"),
"api",
"/probe.py",
)
if completed.returncode != 0:
raise SystemExit(completed.returncode)
def rotate_db_password() -> None:
path = ROOT / "secrets" / "db_worker_password"
path.write_text(secrets.token_hex(24), encoding="utf-8")
container = subprocess.run(
["docker", "compose", "--env-file", ".env", "ps", "-q", "postgres"],
cwd=ROOT,
check=True,
capture_output=True,
text=True,
).stdout.strip()
run(["docker", "cp", str(path), "%s:/tmp/db_worker_password" % container])
run(
[
"docker",
"exec",
container,
"sh",
"-c",
"psql -v ON_ERROR_STOP=1 -U messenger -d messenger -c \"ALTER ROLE messenger_worker PASSWORD '$(cat /tmp/db_worker_password)'\" && rm -f /tmp/db_worker_password",
]
)
compose(
"--profile",
"bootstrap",
"run",
"--rm",
"--entrypoint",
"python",
"-e",
"BAO_REFRESH_KV_ONLY=1",
"-v",
"%s:/app/app/tools/openbao_bootstrap.py:ro" % (ROOT / "app" / "tools" / "openbao_bootstrap.py"),
"openbao-bootstrap",
"-m",
"app.tools.openbao_bootstrap",
)
def image_id() -> str:
completed = subprocess.run(
["docker", "image", "inspect", "mtusi-messenger:lab7", "--format", "{{.Id}}"],
cwd=ROOT,
check=True,
capture_output=True,
text=True,
)
return completed.stdout.strip()
def main() -> None:
before_image = image_id()
print("image_before", before_image.split(":")[-1][:12])
run(
[
"docker",
"run",
"--rm",
"-v",
"%s:/work" % (ROOT / "certs"),
"-v",
"%s:/gen-certs.sh:ro" % (ROOT / "scripts" / "gen-certs.sh"),
"alpine:3.21.3",
"sh",
"/gen-certs.sh",
]
)
compose("up", "-d", "--no-deps", "--force-recreate", "rabbit-mtls", "otel-mtls")
time.sleep(2)
worker_rights()
users = compose(
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
"messenger",
"-tAc",
"SELECT count(*) FROM users",
)
del users
print("PASS superuser can read users; worker role cannot")
compose("stop", "worker")
client = Client("https://127.0.0.1:8443", str(ROOT / "certs" / "ca.crt"), timeout=10)
alice, _bob, _eve, chat = client.bootstrap()
attachment, _content = client.attachment(alice, chat)
if attachment["status"] != "queued":
raise SystemExit("FAIL upload was not left queued")
print("PASS upload queued while worker is stopped")
certs = ROOT / "certs"
shutil.copyfile(certs / "worker-client.crt", certs / "worker-client.revoked.crt")
shutil.copyfile(certs / "worker-client.key", certs / "worker-client.revoked.key")
reissue(
"worker-client",
"worker",
"clientAuth",
"DNS:worker-client,URI:spiffe://messenger/worker",
)
compose("up", "-d", "--no-deps", "--force-recreate", "rabbit-mtls", "otel-mtls")
time.sleep(2)
probe = subprocess.run([sys.executable, "-X", "utf8", str(ROOT / "student-tests" / "same_ca_probe.py")], cwd=ROOT)
if probe.returncode != 0:
raise SystemExit(probe.returncode)
reissue("lb", "localhost", "serverAuth", "DNS:localhost,IP:127.0.0.1")
compose("restart", "lb")
time.sleep(2)
client.call("GET", "/health/ready", schema="Health")
print("PASS lb leaf rotated without an image rebuild")
rotate_db_password()
compose("start", "worker")
ready = client.wait_ready(alice, attachment, wait_seconds=90)
if ready["status"] != "ready":
raise SystemExit("FAIL queued attachment did not become ready after rotation")
print("PASS queued job survived worker revocation and secret rotation")
worker_rights()
reissue(
"expired-worker",
"worker",
"clientAuth",
"URI:spiffe://messenger/worker",
not_before="20200101000000Z",
not_after="20200102000000Z",
)
probe = subprocess.run([sys.executable, "-X", "utf8", str(ROOT / "student-tests" / "same_ca_probe.py")], cwd=ROOT)
if probe.returncode != 0:
raise SystemExit(probe.returncode)
seal = compose(
"--profile",
"bootstrap",
"run",
"--rm",
"--no-deps",
"--entrypoint",
"python",
"-v",
"%s:/probe.py:ro" % (ROOT / "student-tests" / "seal_probe.py"),
"openbao-bootstrap",
"/probe.py",
)
if seal.returncode != 0:
raise SystemExit(seal.returncode)
after_image = image_id()
if before_image != after_image:
raise SystemExit("FAIL application image changed during rotation")
print("PASS image unchanged", after_image.split(":")[-1][:12])
print("PASS track1 and grade4 lifecycle")
if __name__ == "__main__":
main()
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""What the worker credential can and cannot do. Prints statuses, not secrets."""
from __future__ import annotations
import asyncio
import uuid
import asyncpg
from botocore.exceptions import ClientError
from app import bao, broker, config, db, s3, tlsutil
def openbao_status(path: str) -> str:
try:
login = bao._request(
"POST",
"/v1/auth/approle/login",
{"role_id": config.BAO_ROLE_ID, "secret_id": config.BAO_SECRET_ID},
)
token = (login.get("auth") or {}).get("client_token") or ""
bao._request("GET", path, token=token)
return "200"
except RuntimeError as exc:
text = str(exc)
if "HTTP " in text:
return text.split("HTTP ", 1)[1]
return "error"
async def main() -> None:
bao.apply()
pool = await db.connect()
try:
await pool.fetchval("SELECT count(*) FROM attachments")
print("PASS worker db read attachments")
try:
await pool.fetchval("SELECT count(*) FROM users")
except asyncpg.InsufficientPrivilegeError:
print("PASS worker db cannot read users")
else:
raise SystemExit("FAIL worker read the users table")
finally:
await db.close()
client = s3._client_or_create()
key = "variants/track1-%s" % uuid.uuid4().hex
client.put_object(Bucket=config.S3_BUCKET, Key=key, Body=b"ok")
client.delete_object(Bucket=config.S3_BUCKET, Key=key)
print("PASS worker s3 write variants")
try:
client.put_object(Bucket=config.S3_BUCKET, Key="secrets/track1", Body=b"no")
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
print("PASS worker s3 cannot write secrets", code)
else:
raise SystemExit("FAIL worker wrote secrets/")
connection = await __import__("aio_pika").connect_robust(
config.BROKER_URL,
ssl_context=tlsutil.server_context(),
)
channel = await connection.channel()
try:
await channel.declare_queue("stolen.queue", durable=False, auto_delete=True)
except Exception as exc:
print("PASS worker broker cannot declare stolen.queue", type(exc).__name__)
else:
raise SystemExit("FAIL worker declared stolen.queue")
await connection.close()
connection = await __import__("aio_pika").connect_robust(
config.BROKER_URL,
ssl_context=tlsutil.server_context(),
)
channel = await connection.channel()
await channel.declare_queue(broker.QUEUE, durable=True, passive=True)
await connection.close()
print("PASS worker broker can see attachment.jobs")
own = openbao_status("/v1/secret/data/messenger/worker")
foreign = openbao_status("/v1/secret/data/messenger/api")
print("PASS worker openbao own path", own)
print("PASS worker openbao api path", foreign)
if own != "200" or foreign != "403":
raise SystemExit("FAIL worker OpenBao policy own=%s api=%s" % (own, foreign))
if __name__ == "__main__":
asyncio.run(main())