from pathlib import Path import json import secrets root = Path(__file__).resolve().parents[1] directory = root / "secrets" directory.mkdir(mode=0o700, exist_ok=True) def ensure(name, value): path = directory / name try: with path.open("x", encoding="utf-8") as file: file.write(value + "\n") except FileExistsError: pass return path.read_text(encoding="utf-8").strip() password = ensure("db_password", secrets.token_hex(24)) ensure("database_url", f"postgresql://messenger:{password}@db:5432/messenger") ensure("cache_url", "redis://cache:6379/0") ensure("cursor_key", secrets.token_hex(32)) admin = ensure("s3_admin_access_key", "admin-" + secrets.token_hex(8)) admin_password = ensure("s3_admin_secret_key", secrets.token_hex(24)) app = ensure("s3_access_key_id", "app-" + secrets.token_hex(8)) app_password = ensure("s3_secret_access_key", secrets.token_hex(20)) try: with (root / ".env").open("xb") as file: file.write((root / ".env.example").read_bytes()) except FileExistsError: pass env = dict( line.split("=", 1) for line in (root / ".env").read_text(encoding="utf-8").splitlines() if line and not line.startswith("#") and "=" in line ) bucket = env["S3_BUCKET"] config = {"identities": [ {"name": "bootstrap", "credentials": [{"accessKey": admin, "secretKey": admin_password}], "actions": ["Admin"]}, {"name": "messenger", "credentials": [{"accessKey": app, "secretKey": app_password}], "actions": [f"Read:{bucket}", f"Write:{bucket}", f"List:{bucket}"]}, ]} (directory / "s3_config").write_text(json.dumps(config) + "\n", encoding="utf-8")