forked from mtusi2026/mtusi2026lab5
95 lines
3.2 KiB
Python
95 lines
3.2 KiB
Python
#!/usr/bin/env python3
|
|
import json
|
|
import os
|
|
import secrets
|
|
from pathlib import Path
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
SECRET_DIR = ROOT / "secrets"
|
|
|
|
|
|
def main():
|
|
SECRET_DIR.mkdir(mode=0o700, exist_ok=True)
|
|
names = (
|
|
"postgres_password",
|
|
"database_url",
|
|
"s3_access_key_id",
|
|
"s3_secret_access_key",
|
|
"s3_admin_access_key_id",
|
|
"s3_admin_secret_access_key",
|
|
"rabbitmq_password",
|
|
"rabbitmq.conf",
|
|
"broker_url",
|
|
"s3.json",
|
|
)
|
|
existing = [name for name in names if (SECRET_DIR / name).exists()]
|
|
if existing:
|
|
raise SystemExit(
|
|
"Secret files already exist; refusing to rotate credentials without a migration: "
|
|
+ ", ".join(existing)
|
|
)
|
|
|
|
db_password = secrets.token_hex(24)
|
|
broker_password = secrets.token_urlsafe(32)
|
|
values = {
|
|
"postgres_password": db_password,
|
|
"database_url": f"postgresql://messenger:{db_password}@postgres:5432/messenger",
|
|
"s3_access_key_id": "mngr" + secrets.token_hex(8),
|
|
"s3_secret_access_key": secrets.token_urlsafe(40),
|
|
"s3_admin_access_key_id": "admin" + secrets.token_hex(7),
|
|
"s3_admin_secret_access_key": secrets.token_urlsafe(40),
|
|
"rabbitmq_password": broker_password,
|
|
"broker_url": f"amqp://messenger:{broker_password}@rabbitmq:5672/%2f",
|
|
}
|
|
for name, value in values.items():
|
|
path = SECRET_DIR / name
|
|
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
with os.fdopen(descriptor, "w", encoding="utf-8") as output:
|
|
output.write(value + "\n")
|
|
descriptor = os.open(
|
|
SECRET_DIR / "rabbitmq.conf",
|
|
os.O_WRONLY | os.O_CREAT | os.O_EXCL,
|
|
0o600,
|
|
)
|
|
with os.fdopen(descriptor, "w", encoding="utf-8") as output:
|
|
output.write("default_user = messenger\n")
|
|
output.write(f"default_pass = {broker_password}\n")
|
|
s3_config = {
|
|
"identities": [
|
|
{
|
|
"name": "bootstrap-admin",
|
|
"credentials": [
|
|
{
|
|
"accessKey": values["s3_admin_access_key_id"],
|
|
"secretKey": values["s3_admin_secret_access_key"],
|
|
}
|
|
],
|
|
"actions": ["Admin"],
|
|
},
|
|
{
|
|
"name": "messenger-api",
|
|
"credentials": [
|
|
{
|
|
"accessKey": values["s3_access_key_id"],
|
|
"secretKey": values["s3_secret_access_key"],
|
|
}
|
|
],
|
|
"actions": [
|
|
"Read:messenger-attachments",
|
|
"Write:messenger-attachments",
|
|
"List:messenger-attachments",
|
|
],
|
|
},
|
|
]
|
|
}
|
|
descriptor = os.open(SECRET_DIR / "s3.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
with os.fdopen(descriptor, "w", encoding="utf-8") as output:
|
|
json.dump(s3_config, output, separators=(",", ":"))
|
|
output.write("\n")
|
|
print("Local secrets generated with owner-only permissions; values were not printed.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|