forked from mtusi2026/mtusi2026lab7
81 lines
2.7 KiB
Python
81 lines
2.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Provision isolated RabbitMQ API and worker users through verified HTTPS."""
|
|
import base64
|
|
import json
|
|
import os
|
|
import ssl
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
|
|
def request(path, username, password, context, method="GET", body=None):
|
|
headers = {
|
|
"Authorization": "Basic " + base64.b64encode(
|
|
(username + ":" + password).encode("utf-8")
|
|
).decode("ascii"),
|
|
"Content-Type": "application/json",
|
|
}
|
|
data = json.dumps(body).encode("utf-8") if body is not None else None
|
|
req = urllib.request.Request(
|
|
"https://broker:15671/api" + path,
|
|
data=data,
|
|
headers=headers,
|
|
method=method,
|
|
)
|
|
with urllib.request.urlopen(req, context=context, timeout=5) as response:
|
|
response.read()
|
|
return response.status
|
|
|
|
|
|
def main():
|
|
context = ssl.create_default_context(cafile=os.environ["INTERNAL_CA_CERT"])
|
|
admin_user = os.environ["RABBITMQ_DEFAULT_USER"]
|
|
admin_password = os.environ["RABBITMQ_DEFAULT_PASS"]
|
|
for attempt in range(30):
|
|
try:
|
|
request("/overview", admin_user, admin_password, context)
|
|
break
|
|
except (OSError, urllib.error.URLError):
|
|
if attempt == 29:
|
|
raise RuntimeError("RabbitMQ HTTPS management endpoint unavailable") from None
|
|
time.sleep(2)
|
|
|
|
configure = r"^attachment\.jobs(\.v1|\.dlx|\.dead)$"
|
|
read_main = r"^attachment\.jobs\.v1$"
|
|
write_main = r"^attachment\.jobs\.v1$"
|
|
api_write = r"^(attachment\.jobs(\.v1|\.dlx|\.dead)|amq\.default)$"
|
|
api_read = r"^attachment\.jobs(\.v1|\.dlx|\.dead)$"
|
|
worker_write = r"^attachment\.jobs(\.v1|\.dlx|\.dead)$"
|
|
worker_read = r"^attachment\.jobs(\.v1|\.dlx|\.dead)$"
|
|
for role in ("API", "WORKER"):
|
|
user = os.environ["BROKER_" + role + "_USER"]
|
|
password = os.environ["BROKER_" + role + "_PASSWORD"]
|
|
encoded_user = urllib.parse.quote(user, safe="")
|
|
request(
|
|
"/users/" + encoded_user,
|
|
admin_user,
|
|
admin_password,
|
|
context,
|
|
method="PUT",
|
|
body={"password": password, "tags": ""},
|
|
)
|
|
request(
|
|
"/permissions/%2F/" + encoded_user,
|
|
admin_user,
|
|
admin_password,
|
|
context,
|
|
method="PUT",
|
|
body={
|
|
"configure": configure,
|
|
"write": api_write if role == "API" else worker_write,
|
|
"read": api_read if role == "API" else worker_read,
|
|
},
|
|
)
|
|
print("PASS: RabbitMQ API/worker users have separate queue-scoped permissions")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|