#!/usr/bin/env python3 import os import secrets import subprocess from pathlib import Path ENV_FILE = Path(".env") ROLES = { "messenger_api": "API_DB_PASSWORD", "messenger_worker": "WORKER_DB_PASSWORD", "messenger_dispatcher": "DISPATCHER_DB_PASSWORD", } def main(): if not ENV_FILE.is_file(): raise SystemExit("ERROR: .env not found") lines = ENV_FILE.read_text(encoding="utf-8").splitlines() existing_keys = { line.split("=", 1)[0] for line in lines if "=" in line and not line.startswith("#") } for env_name in ROLES.values(): if env_name in existing_keys: raise SystemExit( f"ERROR: {env_name} already exists. " "Refusing to overwrite credentials." ) # Hexadecimal passwords are easy to use in connection URIs. passwords = { role: secrets.token_hex(32) for role in ROLES } # Passwords are sent to psql via stdin. # They are not passed as command-line arguments. statements = ["BEGIN;"] for role, password in passwords.items(): statements.append( f"ALTER ROLE {role} " f"WITH LOGIN PASSWORD '{password}';" ) statements.append("COMMIT;") sql = "\n".join(statements) + "\n" command = [ "docker", "compose", "exec", "-T", "db", "psql", "-X", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger", "-q", ] result = subprocess.run( command, input=sql, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) if result.returncode != 0: print("ERROR: PostgreSQL role configuration failed.") print("Check database availability and permissions.") raise SystemExit(1) # Update the ignored local .env only after SQL succeeds. # No secret values are printed. with ENV_FILE.open("a", encoding="utf-8") as file: file.write("\n# Lab7 scoped database credentials\n") for role, env_name in ROLES.items(): file.write(f"{env_name}={passwords[role]}\n") os.chmod(ENV_FILE, 0o600) print("PASS: PostgreSQL service roles enabled.") print("PASS: Independent credentials generated.") print("PASS: Credentials saved to ignored .env.") print("Secret values were not displayed.") if __name__ == "__main__": main()