Files
mtusi2026lab7-fork/scripts/init_broker.py
T

35 lines
1.4 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.
"""Готовит RabbitMQ definitions с хешами паролей и правами очереди."""
import base64
import hashlib
import json
import os
from pathlib import Path
import re
def initialize(directory: Path, queue: str, vhost: str, admin: str) -> None:
users, permissions = [], []
for name, filename, read, write in (
(admin, "broker_password", ".*", ".*"),
("attachment-publisher", "publisher_broker_password", "^$", "^amq\\.default$"),
("attachment-worker", "worker_broker_password", f"^{re.escape(queue)}$", "^$a"),
):
salt = os.urandom(4)
password = (directory / filename).read_bytes().strip()
digest = hashlib.sha256(salt + password).digest()
users.append({
"name": name, "password_hash": base64.b64encode(salt + digest).decode(),
"hashing_algorithm": "rabbit_password_hashing_sha256",
"tags": ["administrator"] if name == admin else [],
})
permissions.append({
"user": name, "vhost": vhost, "read": read, "write": write,
"configure": ".*" if name == admin else f"^{re.escape(queue)}$",
})
path = directory / "broker_definitions.json"
if not path.exists():
path.write_text(json.dumps({"users": users, "vhosts": [{"name": vhost}],
"permissions": permissions}))
path.chmod(0o444)