Files
mtusi2026lab7/scripts/rabbitmq-definitions.py
T

40 lines
1.5 KiB
Python

import base64
import hashlib
import json
import secrets
import sys
from pathlib import Path
directory = Path(sys.argv[1])
users = []
permissions = []
for role in ("api", "worker"):
name = f"lab7-{role}"
password = secrets.token_hex(32)
salt = secrets.token_bytes(4)
digest = hashlib.sha256(salt + password.encode()).digest()
users.append({
"name": name, "tags": [],
"password_hash": base64.b64encode(salt + digest).decode(),
"hashing_algorithm": "rabbit_password_hashing_sha256",
})
permissions.append({
"user": name, "vhost": "/", "configure": "(?!)",
"write": "^attachments$" if role == "api" else "(?!)",
"read": r"^attachments\.process$" if role == "worker" else "(?!)",
})
(directory / f"{role}.url").write_text(f"amqps://{name}:{password}@rabbitmq:5671/%2F\n")
definitions = {
"users": users,
"vhosts": [{"name": "/"}],
"permissions": permissions,
"exchanges": [{"name": "attachments", "vhost": "/", "type": "direct",
"durable": True, "auto_delete": False, "internal": False, "arguments": {}}],
"queues": [{"name": "attachments.process", "vhost": "/", "durable": True,
"auto_delete": False, "arguments": {}}],
"bindings": [{"source": "attachments", "vhost": "/", "destination": "attachments.process",
"destination_type": "queue", "routing_key": "process", "arguments": {}}],
}
(directory / "definitions.json").write_text(json.dumps(definitions))