#!/usr/bin/env python3 """Generate scoped RustFS credentials in the local .env file.""" import os import re import secrets from pathlib import Path ENV_FILE = Path(__file__).resolve().parent.parent / ".env" CREDENTIALS = { "S3_API_ACCESS_KEY": "messenger_s3_api", "S3_API_SECRET_KEY": secrets.token_hex(32), "S3_WORKER_ACCESS_KEY": "messenger_s3_worker", "S3_WORKER_SECRET_KEY": secrets.token_hex(32), } def main(): if not ENV_FILE.is_file(): raise SystemExit("FAIL: existing .env file not found") original = ENV_FILE.read_text(encoding="utf-8") existing = set( re.findall( r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=", original, flags=re.MULTILINE, ) ) conflicts = existing.intersection(CREDENTIALS) if conflicts: print("FAIL: S3 service credentials already exist") print("Existing variable names:", ", ".join(sorted(conflicts))) print("Refusing to overwrite existing credentials") raise SystemExit(1) addition = "\n# Scoped RustFS IAM credentials\n" for name, value in CREDENTIALS.items(): addition += f"{name}={value}\n" prefix = "" if not original or original.endswith("\n") else "\n" with ENV_FILE.open("a", encoding="utf-8") as file: file.write(prefix + addition) if os.name == "posix": ENV_FILE.chmod(0o600) print("PASS: API IAM credentials generated") print("PASS: worker IAM credentials generated") print("PASS: credentials saved to local .env") print("PASS: existing S3 root credentials preserved") if __name__ == "__main__": main()