forked from mtusi2026/mtusi2026lab7
ЛР7: отрицательные тесты, отчёт, матрица доверия, модель угроз, runbook
- student-tests: mTLS-матрица LB->API, broker и OTLP, ACL и scoped policy OpenBao, rehash, ротация/отзыв identity, sealed OpenBao, утечки в telemetry, rate limit с 429/Retry-After - заполнены REPORT.md (доказательства по уровням 3-4, эксперименты, scan triage), contracts/trust-matrix.md, security/THREAT_MODEL.md (10 угроз), RUNBOOK.md (bootstrap, ротация, unseal, диагностика) - Makefile: up/down/ps/logs/bootstrap/scan/test-lab7/rotate-* Co-Authored-By: O3 Agent Claude <noreply@ozon.ru>
This commit is contained in:
@@ -0,0 +1,230 @@
|
||||
#!/usr/bin/env python3
|
||||
"""TLS/mTLS probes for lab7. Executed inside the `mtls-probe` container.
|
||||
|
||||
Every probe prints exactly one JSON object with a `result` field:
|
||||
ok — expected positive outcome
|
||||
http — HTTP response received (status in `status`)
|
||||
access_denied — broker refused the operation (ACL)
|
||||
tls_error — TLS handshake/validation failed
|
||||
connect_error — connection refused/closed before protocol
|
||||
denied — S3 returned AccessDenied
|
||||
error — anything else (see `error`)
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import ssl
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
|
||||
def tls_context(ca, cert=None, key=None):
|
||||
ctx = ssl.create_default_context(cafile=ca)
|
||||
if cert:
|
||||
ctx.load_cert_chain(cert, key)
|
||||
return ctx
|
||||
|
||||
|
||||
def emit(payload, code=0):
|
||||
print(json.dumps(payload, ensure_ascii=False))
|
||||
sys.exit(code)
|
||||
|
||||
|
||||
def cmd_api(args):
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
url = "https://%s:%d%s" % (args.host, args.port, args.path)
|
||||
try:
|
||||
ctx = tls_context(args.ca, args.cert, args.key)
|
||||
request = urllib.request.Request(url)
|
||||
with urllib.request.urlopen(request, timeout=10, context=ctx) as resp:
|
||||
emit({"result": "ok", "status": resp.status})
|
||||
except urllib.error.HTTPError as exc:
|
||||
emit({"result": "http", "status": exc.code})
|
||||
except urllib.error.URLError as exc:
|
||||
reason = exc.reason
|
||||
if isinstance(reason, (ssl.SSLError, ssl.CertificateError)):
|
||||
emit({"result": "tls_error", "error": type(reason).__name__})
|
||||
emit({"result": "error", "error": type(reason).__name__})
|
||||
except ssl.SSLError as exc:
|
||||
emit({"result": "tls_error", "error": type(exc).__name__})
|
||||
|
||||
|
||||
def cmd_broker(args):
|
||||
import pika
|
||||
|
||||
try:
|
||||
params = pika.ConnectionParameters(
|
||||
host=args.host,
|
||||
port=args.port,
|
||||
virtual_host="/",
|
||||
credentials=pika.ExternalCredentials(),
|
||||
ssl_options=pika.SSLOptions(tls_context(args.ca, args.cert, args.key),
|
||||
server_hostname=args.host),
|
||||
connection_attempts=1,
|
||||
socket_timeout=10,
|
||||
heartbeat=0,
|
||||
)
|
||||
conn = pika.BlockingConnection(params)
|
||||
except Exception as exc: # noqa: BLE001 - probe must classify any failure
|
||||
emit({"result": "connect_error", "error": type(exc).__name__})
|
||||
|
||||
try:
|
||||
channel = conn.channel()
|
||||
if args.foreign_queue:
|
||||
try:
|
||||
channel.queue_declare("foreign.probe." + uuid.uuid4().hex[:8],
|
||||
durable=False, auto_delete=True)
|
||||
emit({"result": "forbidden_allowed"})
|
||||
except pika.exceptions.ChannelClosedByBroker as exc:
|
||||
emit({"result": "access_denied", "code": getattr(exc, "reply_code", None)})
|
||||
channel.queue_declare("attachment.process.v1", passive=True)
|
||||
emit({"result": "ok"})
|
||||
except pika.exceptions.ChannelClosedByBroker as exc:
|
||||
emit({"result": "access_denied", "code": getattr(exc, "reply_code", None)})
|
||||
except Exception as exc: # noqa: BLE001
|
||||
emit({"result": "error", "error": type(exc).__name__})
|
||||
finally:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
def cmd_otlp(args):
|
||||
import http.client
|
||||
|
||||
try:
|
||||
conn = http.client.HTTPSConnection(
|
||||
args.host, args.port, timeout=10,
|
||||
context=tls_context(args.ca, args.cert, args.key))
|
||||
conn.request("POST", args.path, body=b"", headers={"Content-Type": "application/x-protobuf"})
|
||||
response = conn.getresponse()
|
||||
response.read()
|
||||
emit({"result": "http", "status": response.status})
|
||||
except ssl.SSLError as exc:
|
||||
emit({"result": "tls_error", "error": type(exc).__name__})
|
||||
except (OSError, http.client.HTTPException) as exc:
|
||||
emit({"result": "error", "error": type(exc).__name__})
|
||||
|
||||
|
||||
def cmd_s3(args):
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=args.endpoint,
|
||||
region_name="us-east-1",
|
||||
aws_access_key_id=args.access_key,
|
||||
aws_secret_access_key=args.secret,
|
||||
verify=args.ca,
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"},
|
||||
connect_timeout=5, read_timeout=10, retries={"max_attempts": 0}),
|
||||
)
|
||||
key = args.key_prefix.rstrip("/") + "/probe-" + uuid.uuid4().hex
|
||||
try:
|
||||
client.put_object(Bucket=args.bucket, Key=key, Body=b"probe", ContentType="image/png")
|
||||
emit({"result": "ok", "key": key})
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
emit({"result": "denied" if code in ("AccessDenied", "403", "AllAccessDisabled") else "error",
|
||||
"code": code})
|
||||
except BotoCoreError as exc:
|
||||
emit({"result": "error", "error": type(exc).__name__})
|
||||
|
||||
|
||||
def cmd_leak(args):
|
||||
import re
|
||||
import urllib.request
|
||||
|
||||
ctx = tls_context(args.ca)
|
||||
patterns = [
|
||||
re.compile(r"(?i)(password|passwd|secret|token|authorization)\s*[=:]\s*\S{8,}"),
|
||||
re.compile(r"(?i)bearer\s+[A-Za-z0-9._~+/=-]{16,}"),
|
||||
re.compile(r"(?i)x-vault-token"),
|
||||
re.compile(r"(?i)-----BEGIN [A-Z ]*PRIVATE KEY-----"),
|
||||
]
|
||||
matches = []
|
||||
url = ('https://loki:3100/loki/api/v1/query_range?'
|
||||
'query=%7Bservice_name%3D%22messenger-api%22%7D&limit=500')
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=15, context=ctx) as resp:
|
||||
lines = [json.loads(item)[1] for stream in
|
||||
json.load(resp)["data"]["result"] for item in stream["values"]]
|
||||
except Exception as exc: # noqa: BLE001
|
||||
emit({"result": "error", "error": type(exc).__name__})
|
||||
|
||||
for line in lines:
|
||||
for pattern in patterns:
|
||||
found = pattern.search(line)
|
||||
if found:
|
||||
matches.append(found.group(0)[:60])
|
||||
|
||||
labels = []
|
||||
try:
|
||||
with urllib.request.urlopen("https://prometheus:9090/api/v1/labels",
|
||||
timeout=10, context=ctx) as resp:
|
||||
labels = json.load(resp)["data"]
|
||||
except Exception as exc: # noqa: BLE001
|
||||
emit({"result": "error", "error": "prometheus:" + type(exc).__name__})
|
||||
|
||||
forbidden_labels = [lab for lab in labels
|
||||
if lab in ("user_id", "chat_id", "message_id", "attachment_id",
|
||||
"request_id", "filename")]
|
||||
emit({"result": "leak" if (matches or forbidden_labels) else "ok",
|
||||
"log_matches": matches[:10], "forbidden_labels": forbidden_labels,
|
||||
"lines_scanned": len(lines)})
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
api = sub.add_parser("api")
|
||||
api.add_argument("--host", default="api")
|
||||
api.add_argument("--port", type=int, default=8443)
|
||||
api.add_argument("--path", default="/health/live")
|
||||
api.add_argument("--ca", default="/pki/trust/ca-clients-bundle.crt")
|
||||
api.add_argument("--cert")
|
||||
api.add_argument("--key")
|
||||
api.set_defaults(func=cmd_api)
|
||||
|
||||
broker = sub.add_parser("broker")
|
||||
broker.add_argument("--host", default="rabbitmq")
|
||||
broker.add_argument("--port", type=int, default=5671)
|
||||
broker.add_argument("--ca", default="/pki/trust/ca-clients-bundle.crt")
|
||||
broker.add_argument("--cert")
|
||||
broker.add_argument("--key")
|
||||
broker.add_argument("--foreign-queue", action="store_true")
|
||||
broker.set_defaults(func=cmd_broker)
|
||||
|
||||
otlp = sub.add_parser("otlp")
|
||||
otlp.add_argument("--host", default="ingress")
|
||||
otlp.add_argument("--port", type=int, default=4318)
|
||||
otlp.add_argument("--path", default="/v1/logs")
|
||||
otlp.add_argument("--ca", default="/pki/trust/ca-servers-bundle.crt")
|
||||
otlp.add_argument("--cert")
|
||||
otlp.add_argument("--key")
|
||||
otlp.set_defaults(func=cmd_otlp)
|
||||
|
||||
s3 = sub.add_parser("s3")
|
||||
s3.add_argument("--endpoint", default="https://minio:9000")
|
||||
s3.add_argument("--ca", default="/pki/trust/ca-servers-bundle.crt")
|
||||
s3.add_argument("--bucket", default="messenger-attachments")
|
||||
s3.add_argument("--access-key", required=True)
|
||||
s3.add_argument("--secret", required=True)
|
||||
s3.add_argument("--key-prefix", required=True, choices=["staging", "originals"])
|
||||
s3.set_defaults(func=cmd_s3)
|
||||
|
||||
leak = sub.add_parser("leak")
|
||||
leak.add_argument("--ca", default="/pki/trust/ca-servers-bundle.crt")
|
||||
leak.set_defaults(func=cmd_leak)
|
||||
|
||||
args = parser.parse_args()
|
||||
args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,430 @@
|
||||
#!/usr/bin/env python3
|
||||
"""lab7: сквозные положительные и отрицательные проверки доверия.
|
||||
|
||||
Запуск (Git Bash/WSL, стенд поднят, секреты созданы):
|
||||
python student-tests/test_lab7.py
|
||||
|
||||
Проверяет то, что не покрывают публичные тесты: mTLS LB→API, mTLS к broker и
|
||||
OTLP-ingress, ACL и scoped policies OpenBao, rate limit, rehash Argon2id,
|
||||
ротацию/отзыв identity, sealed OpenBao и отсутствие утечек в telemetry.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
BASE = os.environ.get("BASE_URL", "https://localhost:8443").rstrip("/")
|
||||
CA_PUBLIC = str(ROOT / "pki/trust/public-ca.crt")
|
||||
CA_SERVERS = str(ROOT / "pki/trust/ca-servers-bundle.crt")
|
||||
PY = os.environ.get("PYTHON", sys.executable)
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
RESULTS.append((name, bool(ok), detail))
|
||||
print(("PASS " if ok else "FAIL ") + name + (" — " + detail if detail else ""))
|
||||
return ok
|
||||
|
||||
|
||||
def run(cmd, timeout=240, input_text=None):
|
||||
return subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True,
|
||||
timeout=timeout, input=input_text)
|
||||
|
||||
|
||||
def compose(*args, timeout=240):
|
||||
return run(COMPOSE + list(args), timeout=timeout)
|
||||
|
||||
|
||||
def sh(script, *args, timeout=300):
|
||||
return run(["sh", script, *args], timeout=timeout)
|
||||
|
||||
|
||||
def probe(*args, timeout=180):
|
||||
result = compose("--profile", "tools", "run", "--rm", "-T", "mtls-probe", *args,
|
||||
timeout=timeout)
|
||||
lines = [line for line in result.stdout.splitlines() if line.startswith("{")]
|
||||
if not lines:
|
||||
return {"result": "no_output", "stderr": result.stderr[-400:]}
|
||||
return json.loads(lines[-1])
|
||||
|
||||
|
||||
def http(method, path, body=None, headers=None, token=None, base=None, ca=None):
|
||||
data = json.dumps(body).encode("utf-8") if body is not None else None
|
||||
request = urllib.request.Request((base or BASE) + path, data=data, method=method)
|
||||
if body is not None:
|
||||
request.add_header("Content-Type", "application/json")
|
||||
if token:
|
||||
request.add_header("Authorization", "Bearer " + token)
|
||||
for key, value in (headers or {}).items():
|
||||
request.add_header(key, value)
|
||||
context = ssl.create_default_context(cafile=ca or CA_PUBLIC)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=20, context=context) as resp:
|
||||
raw = resp.read()
|
||||
return resp.status, dict(resp.headers), json.loads(raw) if raw else None
|
||||
except urllib.error.HTTPError as exc:
|
||||
raw = exc.read()
|
||||
try:
|
||||
parsed = json.loads(raw) if raw else None
|
||||
except ValueError:
|
||||
parsed = None
|
||||
return exc.code, dict(exc.headers), parsed
|
||||
|
||||
|
||||
def new_user(prefix="probe"):
|
||||
username = (prefix + uuid.uuid4().hex)[:24]
|
||||
password = "Pw-" + uuid.uuid4().hex
|
||||
status, _, body = http("POST", "/api/v1/users", {
|
||||
"username": username, "display_name": "Probe " + username[-4:], "password": password})
|
||||
if status != 201:
|
||||
raise RuntimeError("create_user failed: %s %s" % (status, body))
|
||||
return username, password, body
|
||||
|
||||
|
||||
def login(username, password):
|
||||
creds = base64.b64encode(("%s:%s" % (username, password)).encode("utf-8")).decode("ascii")
|
||||
return http("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + creds})
|
||||
|
||||
|
||||
def create_chat(token, member_ids, title="probe"):
|
||||
return http("POST", "/api/v1/chats", {"title": title, "member_ids": member_ids}, token=token)
|
||||
|
||||
|
||||
def upload(token, chat_id, filename="probe.png"):
|
||||
payload = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
request = urllib.request.Request(
|
||||
"%s/api/v1/chats/%s/attachments?filename=%s" % (BASE, chat_id, filename),
|
||||
data=payload, method="POST")
|
||||
request.add_header("Authorization", "Bearer " + token)
|
||||
request.add_header("Content-Type", "image/png")
|
||||
with urllib.request.urlopen(request, timeout=30,
|
||||
context=ssl.create_default_context(cafile=CA_PUBLIC)) as resp:
|
||||
return json.loads(resp.read())
|
||||
|
||||
|
||||
def wait_attachment(token, attachment_id, seconds=90):
|
||||
deadline = time.time() + seconds
|
||||
while time.time() < deadline:
|
||||
status, _, body = http("GET", "/api/v1/attachments/" + attachment_id, token=token)
|
||||
if status == 200 and body.get("status") in ("ready", "failed"):
|
||||
return body
|
||||
time.sleep(2)
|
||||
return None
|
||||
|
||||
|
||||
def hostname_probe():
|
||||
"""Внешний TLS к 127.0.0.1: сертификат выписан на localhost, hostname не совпадает."""
|
||||
ctx = ssl.create_default_context(cafile=CA_PUBLIC)
|
||||
try:
|
||||
urllib.request.urlopen("https://127.0.0.1:8443/health/ready", context=ctx, timeout=10)
|
||||
return "ok"
|
||||
except ssl.SSLCertVerificationError as exc:
|
||||
return "cert_error:" + (exc.verify_message or type(exc).__name__)
|
||||
except urllib.error.URLError as exc:
|
||||
return "url_error:" + type(exc.reason).__name__
|
||||
|
||||
|
||||
def image_id():
|
||||
result = run(["docker", "image", "inspect", "messenger-lab7-app:1.7.0",
|
||||
"--format", "{{.Id}}"])
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def psql(sql):
|
||||
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
|
||||
"-tAc", sql)
|
||||
|
||||
|
||||
def main():
|
||||
failures = 0
|
||||
|
||||
# 0. Контракт и PKI-материал для отрицательных тестов.
|
||||
check("make check (offline contract)", run([PY, "scripts/check_contract.py"]).returncode == 0)
|
||||
sh("scripts/pki.sh", "rogue")
|
||||
check("rogue PKI material present",
|
||||
(ROOT / "pki/rogue/rogue-same-ca.crt").exists())
|
||||
|
||||
# 1. Внешний TLS: доверенный CA/hostname проходит, пустой trust store — нет.
|
||||
r = run([PY, "tests/security.py", "--base-url", BASE, "--ca-file", CA_PUBLIC])
|
||||
check("external TLS trust (public test-security)", r.returncode == 0,
|
||||
r.stdout.strip().splitlines()[-1] if r.stdout else r.stderr[-200:])
|
||||
wrong_name = hostname_probe()
|
||||
check("external TLS: wrong hostname rejected by verification",
|
||||
wrong_name.startswith("cert_error"), wrong_name)
|
||||
|
||||
# 2. Публичный smoke по HTTPS.
|
||||
r = run([PY, "tests/smoke.py", "--base-url", BASE, "--ca-file", CA_PUBLIC], timeout=600)
|
||||
check("public smoke over HTTPS", r.returncode == 0,
|
||||
r.stdout.strip().splitlines()[-1] if r.stdout else r.stderr[-300:])
|
||||
if r.returncode != 0:
|
||||
print(r.stdout[-2000:])
|
||||
print(r.stderr[-2000:])
|
||||
|
||||
# 3. LB -> API mTLS: матрица identity.
|
||||
allowed = probe("api", "--ca", "/pki/trust/ca-clients-bundle.crt",
|
||||
"--cert", "/pki/leaf/ingress-client.crt",
|
||||
"--key", "/pki/leaf/ingress-client.key")
|
||||
check("mTLS LB->API: allowed identity lb", allowed.get("result") == "ok", str(allowed))
|
||||
|
||||
no_cert = probe("api", "--ca", "/pki/trust/ca-clients-bundle.crt")
|
||||
check("mTLS LB->API: no client certificate rejected",
|
||||
no_cert.get("result") == "tls_error", str(no_cert))
|
||||
|
||||
rogue = probe("api", "--ca", "/pki/trust/ca-clients-bundle.crt",
|
||||
"--cert", "/pki/rogue/rogue-same-ca.crt",
|
||||
"--key", "/pki/rogue/rogue.key")
|
||||
check("mTLS LB->API: same-CA foreign identity rejected",
|
||||
rogue.get("result") == "http" and rogue.get("status") == 403, str(rogue))
|
||||
|
||||
foreign = probe("api", "--ca", "/pki/trust/ca-clients-bundle.crt",
|
||||
"--cert", "/pki/rogue/foreign.crt",
|
||||
"--key", "/pki/rogue/foreign.key")
|
||||
check("mTLS LB->API: certificate from foreign CA rejected",
|
||||
foreign.get("result") == "tls_error", str(foreign))
|
||||
|
||||
scoped = probe("api", "--path", "/api/v1/users/me",
|
||||
"--ca", "/pki/trust/ca-clients-bundle.crt",
|
||||
"--cert", "/pki/leaf/health-client.crt",
|
||||
"--key", "/pki/leaf/health-client.key")
|
||||
check("mTLS LB->API: health identity cannot call business API",
|
||||
scoped.get("result") == "http" and scoped.get("status") == 403, str(scoped))
|
||||
|
||||
# 4. Broker: mTLS + EXTERNAL auth + ACL.
|
||||
api_broker = probe("broker", "--cert", "/pki/leaf/api-client.crt",
|
||||
"--key", "/pki/leaf/api-client.key")
|
||||
check("broker mTLS: messenger-api identity accepted", api_broker.get("result") == "ok",
|
||||
str(api_broker))
|
||||
worker_broker = probe("broker", "--cert", "/pki/leaf/worker-client.crt",
|
||||
"--key", "/pki/leaf/worker-client.key")
|
||||
check("broker mTLS: messenger-worker identity accepted", worker_broker.get("result") == "ok",
|
||||
str(worker_broker))
|
||||
rogue_broker = probe("broker", "--cert", "/pki/rogue/rogue-same-ca.crt",
|
||||
"--key", "/pki/rogue/rogue.key")
|
||||
check("broker mTLS: same-CA foreign identity rejected",
|
||||
rogue_broker.get("result") in ("connect_error", "access_denied"), str(rogue_broker))
|
||||
acl_broker = probe("broker", "--cert", "/pki/leaf/worker-client.crt",
|
||||
"--key", "/pki/leaf/worker-client.key", "--foreign-queue")
|
||||
check("broker ACL: worker cannot declare a foreign queue",
|
||||
acl_broker.get("result") in ("access_denied", "connect_error"), str(acl_broker))
|
||||
|
||||
# 5. OTLP ingress: mTLS + identity allowlist.
|
||||
otlp_ok = probe("otlp", "--cert", "/pki/leaf/api-client.crt",
|
||||
"--key", "/pki/leaf/api-client.key")
|
||||
check("OTLP ingress: api identity accepted", otlp_ok.get("result") == "http", str(otlp_ok))
|
||||
otlp_rogue = probe("otlp", "--cert", "/pki/rogue/rogue-same-ca.crt",
|
||||
"--key", "/pki/rogue/rogue.key")
|
||||
check("OTLP ingress: same-CA foreign identity rejected",
|
||||
otlp_rogue.get("result") == "http" and otlp_rogue.get("status") == 403, str(otlp_rogue))
|
||||
otlp_none = probe("otlp")
|
||||
check("OTLP ingress: no client certificate rejected",
|
||||
otlp_none.get("result") == "tls_error", str(otlp_none))
|
||||
|
||||
# 6. S3: TLS + раздельные scoped credentials.
|
||||
api_key = (ROOT / "secrets/s3_api_access_key").read_text().strip()
|
||||
api_secret = (ROOT / "secrets/s3_api_secret").read_text().strip()
|
||||
worker_key = (ROOT / "secrets/s3_worker_access_key").read_text().strip()
|
||||
worker_secret = (ROOT / "secrets/s3_worker_secret").read_text().strip()
|
||||
|
||||
s3_api_staging = probe("s3", "--access-key", api_key, "--secret", api_secret,
|
||||
"--key-prefix", "staging")
|
||||
check("S3: api may write staging/", s3_api_staging.get("result") == "ok", str(s3_api_staging))
|
||||
s3_api_originals = probe("s3", "--access-key", api_key, "--secret", api_secret,
|
||||
"--key-prefix", "originals")
|
||||
check("S3: api cannot write originals/",
|
||||
s3_api_originals.get("result") == "denied", str(s3_api_originals))
|
||||
s3_worker_staging = probe("s3", "--access-key", worker_key, "--secret", worker_secret,
|
||||
"--key-prefix", "staging")
|
||||
check("S3: worker cannot write staging/",
|
||||
s3_worker_staging.get("result") == "denied", str(s3_worker_staging))
|
||||
s3_worker_originals = probe("s3", "--access-key", worker_key, "--secret", worker_secret,
|
||||
"--key-prefix", "originals")
|
||||
check("S3: worker may write originals/", s3_worker_originals.get("result") == "ok",
|
||||
str(s3_worker_originals))
|
||||
|
||||
# 7. ACL и идентичность.
|
||||
alice_name, alice_pw, alice = new_user("alice")
|
||||
bob_name, bob_pw, bob = new_user("bob")
|
||||
eve_name, eve_pw, eve = new_user("eve")
|
||||
_, _, alice_session = login(alice_name, alice_pw)
|
||||
_, _, bob_session = login(bob_name, bob_pw)
|
||||
_, _, eve_session = login(eve_name, eve_pw)
|
||||
alice_token = alice_session["token"]
|
||||
bob_token = bob_session["token"]
|
||||
eve_token = eve_session["token"]
|
||||
|
||||
status, _, chat = create_chat(alice_token, [alice["id"], bob["id"]])
|
||||
chat_id = chat["id"]
|
||||
status, _, _ = create_chat(alice_token, [alice["id"]], title="secret")
|
||||
check("ACL: outsider cannot read chat", http("GET", "/api/v1/chats/" + chat_id,
|
||||
token=eve_token)[0] == 404)
|
||||
attachment = upload(alice_token, chat_id)
|
||||
check("ACL: outsider cannot read attachment metadata",
|
||||
http("GET", "/api/v1/attachments/" + attachment["id"], token=eve_token)[0] == 404)
|
||||
check("ACL: forged X-User-Id does not change identity",
|
||||
http("GET", "/api/v1/users/me", token=eve_token,
|
||||
headers={"X-User-Id": alice["id"]})[2]["id"] == eve["id"])
|
||||
http("DELETE", "/api/v1/auth/sessions/current", token=eve_token)
|
||||
check("ACL: token invalid after logout",
|
||||
http("GET", "/api/v1/users/me", token=eve_token)[0] == 401)
|
||||
|
||||
# Ошибка входа не должна различать «неверный пароль» и «нет пользователя».
|
||||
wrong_existing = login(alice_name, "definitely-wrong-" + uuid.uuid4().hex)
|
||||
wrong_missing = login("nosuch" + uuid.uuid4().hex[:12], "definitely-wrong-" + uuid.uuid4().hex)
|
||||
code_existing = (wrong_existing[2] or {}).get("error", {}).get("code")
|
||||
code_missing = (wrong_missing[2] or {}).get("error", {}).get("code")
|
||||
check("auth: identical error for wrong password and unknown user",
|
||||
wrong_existing[0] == wrong_missing[0] == 401 and code_existing == code_missing,
|
||||
"statuses=%s/%s codes=%s/%s" % (wrong_existing[0], wrong_missing[0],
|
||||
code_existing, code_missing))
|
||||
|
||||
ready = wait_attachment(alice_token, attachment["id"], seconds=90)
|
||||
check("worker pipeline ready over TLS", ready is not None and ready.get("status") == "ready",
|
||||
str(ready and ready.get("status")))
|
||||
|
||||
# 8. OpenBao: scoped policy, запрет чужих путей и записи.
|
||||
bao_code = "\n".join([
|
||||
"from app import secrets",
|
||||
"tok, _ = secrets.login()",
|
||||
"own = secrets.read_kv(tok, 'api')",
|
||||
"assert own.get('database_url')",
|
||||
"denied = []",
|
||||
"for path in ('/v1/secret/data/messenger/worker', '/v1/sys/policies/acl/messenger-api'):",
|
||||
" try:",
|
||||
" secrets._request('GET', path, token=tok)",
|
||||
" denied.append(path)",
|
||||
" except secrets.OpenBaoError:",
|
||||
" pass",
|
||||
"try:",
|
||||
" secrets._request('POST', '/v1/secret/data/messenger/api', {'data': {'x': '1'}}, token=tok)",
|
||||
" denied.append('write')",
|
||||
"except secrets.OpenBaoError:",
|
||||
" pass",
|
||||
"import os",
|
||||
"assert not os.environ.get('BAO_TOKEN')",
|
||||
"print('DENIED=' + ','.join(denied))",
|
||||
])
|
||||
r = compose("exec", "-T", "api", "python", "-c", bao_code)
|
||||
output = (r.stdout + r.stderr).strip()
|
||||
check("OpenBao: api reads own secret, denied elsewhere",
|
||||
r.returncode == 0 and output.endswith("DENIED="), output[-200:])
|
||||
|
||||
# 9. Sealed OpenBao: API продолжает работать на загруженных секретах,
|
||||
# новый процесс не стартует, после unseal всё восстанавливается.
|
||||
init = json.loads((ROOT / "secrets/openbao-init.json").read_text())
|
||||
seal_status, _, _ = http("POST", "/v1/sys/seal", {}, token=init["root_token"],
|
||||
base="https://127.0.0.1:8200", ca=CA_SERVERS)
|
||||
check("OpenBao: sealed by operator", seal_status in (200, 204), str(seal_status))
|
||||
check("sealed OpenBao: running API stays ready",
|
||||
http("GET", "/health/ready")[0] == 200)
|
||||
name_sealed, pw_sealed, _ = new_user("sealed")
|
||||
check("sealed OpenBao: running API still serves business requests",
|
||||
login(name_sealed, pw_sealed)[0] == 201)
|
||||
r = compose("exec", "-T", "-e", "OPENBAO_WAIT_SECONDS=5", "api",
|
||||
"python", "-c", "from app import secrets; secrets.load('api')")
|
||||
check("sealed OpenBao: new process fails instead of using cached/file secrets",
|
||||
r.returncode != 0)
|
||||
sh("scripts/openbao-unseal.sh")
|
||||
check("OpenBao: unsealed again", http("GET", "/v1/sys/health", base="https://127.0.0.1:8200",
|
||||
ca=CA_SERVERS)[0] == 200)
|
||||
|
||||
# 10. Ротация и отзыв leaf-certificate без пересборки образа.
|
||||
id_before = image_id()
|
||||
(ROOT / "pki/revoked").mkdir(exist_ok=True)
|
||||
(ROOT / "pki/revoked/ingress-client.crt").write_bytes(
|
||||
(ROOT / "pki/leaf/ingress-client.crt").read_bytes())
|
||||
(ROOT / "pki/revoked/ingress-client.key").write_bytes(
|
||||
(ROOT / "pki/leaf/ingress-client.key").read_bytes())
|
||||
sh("scripts/revoke-identity.sh", "ingress-client")
|
||||
revoked_probe = probe("api", "--cert", "/pki/revoked/ingress-client.crt",
|
||||
"--key", "/pki/revoked/ingress-client.key",
|
||||
"--ca", "/pki/trust/ca-clients-bundle.crt")
|
||||
check("rotation: old lb identity rejected on new connections",
|
||||
revoked_probe.get("result") == "http" and revoked_probe.get("status") == 403,
|
||||
str(revoked_probe))
|
||||
new_probe = probe("api", "--cert", "/pki/leaf/ingress-client.crt",
|
||||
"--key", "/pki/leaf/ingress-client.key",
|
||||
"--ca", "/pki/trust/ca-clients-bundle.crt")
|
||||
check("rotation: new lb identity works", new_probe.get("result") == "ok", str(new_probe))
|
||||
check("rotation: image not rebuilt", image_id() == id_before)
|
||||
|
||||
# 11. Ротация рабочего секрета (S3 worker) без пересборки.
|
||||
id_before = image_id()
|
||||
sh("scripts/rotate-secret.sh", timeout=600)
|
||||
old_pair_file = ROOT / "secrets/.rotated-old-s3-worker"
|
||||
if old_pair_file.exists():
|
||||
old_new_key, old_new_secret = old_pair_file.read_text().strip().splitlines()
|
||||
old_probe = probe("s3", "--access-key", old_new_key, "--secret", old_new_secret,
|
||||
"--key-prefix", "originals")
|
||||
check("rotation: disabled S3 identity denied", old_probe.get("result") == "denied",
|
||||
str(old_probe))
|
||||
old_pair_file.unlink()
|
||||
else:
|
||||
check("rotation: old S3 pair recorded for proof", False, "missing file")
|
||||
rotated_attachment = upload(alice_token, chat_id)
|
||||
rotated_ready = wait_attachment(alice_token, rotated_attachment["id"], seconds=90)
|
||||
check("rotation: worker works with rotated secret",
|
||||
rotated_ready is not None and rotated_ready.get("status") == "ready")
|
||||
check("rotation: image not rebuilt (secret)", image_id() == id_before)
|
||||
|
||||
# 12. Telemetry не содержит секретов и высококардинальных labels.
|
||||
leak = probe("leak")
|
||||
check("telemetry: no secrets or user identifiers in logs/metric labels",
|
||||
leak.get("result") == "ok", str(leak))
|
||||
|
||||
# 13. Rehash Argon2id: старый hash обновляется при успешном входе.
|
||||
legacy_name = ("legacy" + uuid.uuid4().hex)[:24]
|
||||
legacy_pw = "LegacyPw-" + uuid.uuid4().hex
|
||||
r = compose("exec", "-T", "api", "python", "-c",
|
||||
"from argon2 import PasswordHasher, Type;"
|
||||
"print(PasswordHasher(memory_cost=8192, time_cost=2, parallelism=1,"
|
||||
" type=Type.ID).hash('%s'))" % legacy_pw)
|
||||
legacy_hash = (r.stdout or "").strip().splitlines()[-1]
|
||||
psql("INSERT INTO users (id, username, display_name, password_hash) "
|
||||
"VALUES (gen_random_uuid(), '%s', 'Legacy', '%s')" % (legacy_name, legacy_hash))
|
||||
status, _, _ = login(legacy_name, legacy_pw)
|
||||
new_hash = psql("SELECT password_hash FROM users WHERE username='%s'" % legacy_name).stdout.strip()
|
||||
check("rehash: legacy hash replaced on successful login",
|
||||
status == 201 and new_hash.startswith("$argon2id$v=19$m=19456,t=2,p=1"),
|
||||
"status=%s prefix=%s" % (status, new_hash[:32]))
|
||||
|
||||
# 14. Rate limit входа: 429 + Retry-After, общий для реплик.
|
||||
# Идёт последним: после него входы с этого IP на минуту ограничены.
|
||||
lim_name = ("rl" + uuid.uuid4().hex)[:24]
|
||||
statuses, instances, retry_after = [], set(), None
|
||||
for _ in range(40):
|
||||
status, headers, _ = login(lim_name, "wrong-password-" + uuid.uuid4().hex)
|
||||
statuses.append(status)
|
||||
if headers.get("X-Instance-Id"):
|
||||
instances.add(headers["X-Instance-Id"])
|
||||
if status == 429:
|
||||
retry_after = headers.get("Retry-After")
|
||||
break
|
||||
check("rate limit: 429 returned", 429 in statuses,
|
||||
"statuses=" + ",".join(map(str, statuses[-5:])))
|
||||
check("rate limit: Retry-After present", bool(retry_after), str(retry_after))
|
||||
check("rate limit: shared across replicas (both instances observed before 429)",
|
||||
len(instances) >= 2, "instances=" + ",".join(sorted(instances))[:160])
|
||||
|
||||
print()
|
||||
failed = [name for name, ok, _ in RESULTS if not ok]
|
||||
failures = len(failed)
|
||||
print("SUMMARY: %d passed, %d failed" % (len(RESULTS) - failures, failures))
|
||||
for name in failed:
|
||||
print(" FAILED: " + name)
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user