Files
mtusi2026lab7/student-tests/broker_permissions.py
T
zemiles 9cc80d2529 ЛР 7 — БПИ2303 — Лазарев — на 3
Перенесена реализация lab6; бизнес-API без изменений, транспорт — HTTPS.

- Внешний HTTPS (public-ca) на 127.0.0.1:8443; HSTS, TLS >= 1.2.
- Обязательное mTLS LB -> каждая API-реплика: API проверяет цепочку
  internal-ca и SAN клиента (allowlist: lb); health только на 127.0.0.1.
- TLS с проверкой сервера ко всем зависимостям: PostgreSQL verify-full
  (pg_hba только hostssl), HTTPS S3, AMQPS, OTLP/HTTPS с client cert,
  mTLS Collector -> Prometheus/Loki/Tempo, Grafana -> datasources, scrape.
- OpenBao 2.7.2 не в dev-mode: Raft на volume, init/unseal оператором,
  auth/cert с ролью и policy на сервис, TTL 15 мин + renew/re-login.
- Отдельные роли PostgreSQL с грантами по таблицам; разные ключи S3 и
  пользователи брокера выдаются из OpenBao.
- Argon2id (m=19 MiB, t=2, p=1, замер на стенде) и rehash при входе.
- Случайный X-Instance-Id; hardening контейнеров (non-root, cap_drop ALL,
  no-new-privileges, read-only, лимиты); TCP_NODELAY на сокете API.
- Модель угроз, trust matrix, отрицательные тесты TLS/mTLS, API, OpenBao,
  hardening; evidence, в т.ч. прогон из чистого clone.
2026-11-18 23:59:35 +03:00

100 lines
4.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Права пользователей RabbitMQ (минимальные привилегии). Хост-оркестратор:
python3 student-tests/broker_permissions.py --output evidence/broker-permissions.json
Внутри контейнеров relay, worker и ops (каждый — со СВОИМ BROKER_URL_FILE) выполняется
проба (--probe): publish в exchange attachments (с mandatory и неизвестным routing key —
сообщение никуда не попадает, но право write проверяется), basic.get из рабочей очереди и
из DLQ (право read), queue.declare (право configure). Ожидаемая матрица:
relay — publish; worker — read рабочей очереди; ops — publish + read DLQ; configure — никто.
Также: пользователя guest нет; порты брокера на хост не опубликованы.
"""
import argparse
import json
import subprocess
import sys
from pathlib import Path
EXPECT = {
"relay": {"publish": True, "get_work_queue": False, "get_dlq": False, "declare_queue": False},
"worker": {"publish": False, "get_work_queue": True, "get_dlq": False, "declare_queue": False},
"ops": {"publish": True, "get_work_queue": False, "get_dlq": True, "declare_queue": False},
}
def probe():
sys.path.insert(0, "/app/src")
import pika
import common
out = {}
conn = pika.BlockingConnection(common.broker_parameters())
def attempt(name, fn):
ch = conn.channel()
try:
fn(ch)
out[name] = True
except pika.exceptions.UnroutableError:
out[name] = True # write разрешён, просто нет binding
except pika.exceptions.ChannelClosedByBroker as exc:
out[name] = False if exc.reply_code == 403 else "error %d" % exc.reply_code
finally:
if ch.is_open:
ch.close()
def publish(ch):
ch.confirm_delivery()
ch.basic_publish(common.EXCHANGE, "permission.check.unbound", b"{}", mandatory=True)
def get(queue):
def fn(ch):
m, _p, _b = ch.basic_get(queue, auto_ack=False)
if m is not None:
ch.basic_nack(m.delivery_tag, requeue=True)
return fn
attempt("publish", publish)
attempt("get_work_queue", get(common.QUEUE))
attempt("get_dlq", get(common.DLQ))
attempt("declare_queue", lambda ch: ch.queue_declare("evil-queue", durable=True))
conn.close()
print(json.dumps(out))
def main():
p = argparse.ArgumentParser()
p.add_argument("--probe", action="store_true")
p.add_argument("--output")
args = p.parse_args()
if args.probe:
return probe()
root = Path(__file__).resolve().parents[1]
script = (root / "student-tests/broker_permissions.py").read_text()
results, ok = {}, True
runners = {"relay": ["docker", "compose", "exec", "-T", "relay", "python", "-", "--probe"],
"worker": ["docker", "compose", "exec", "-T", "worker", "python", "-", "--probe"],
"ops": ["docker", "compose", "--profile", "tools", "run", "--rm", "-T", "--entrypoint", "python",
"ops", "-", "--probe"]}
for user, cmd in runners.items():
r = subprocess.run(cmd, input=script, capture_output=True, text=True, cwd=root, timeout=120)
got = json.loads(r.stdout.strip().splitlines()[-1])
results[user] = {"got": got, "expected": EXPECT[user], "pass": got == EXPECT[user]}
ok &= got == EXPECT[user]
print("%s %-6s %s" % ("PASS" if got == EXPECT[user] else "FAIL", user, got))
users = subprocess.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_users"],
capture_output=True, text=True, cwd=root).stdout.split()
ports = subprocess.run(["docker", "compose", "port", "broker", "5672"], capture_output=True, text=True, cwd=root)
results["guest_absent"] = "guest" not in users
results["broker_port_published_to_host"] = bool(ports.stdout.strip())
ok &= results["guest_absent"] and not results["broker_port_published_to_host"]
print("guest absent:", results["guest_absent"], "| port 5672 on host:", results["broker_port_published_to_host"])
if args.output:
Path(args.output).write_text(json.dumps(results, ensure_ascii=False, indent=1) + "\n")
print("PASS" if ok else "FAIL")
return 0 if ok else 1
if __name__ == "__main__":
sys.exit(main() or 0)