import os import secrets from pathlib import Path from urllib.parse import quote ROOT = Path(__file__).resolve().parents[1] def read_values(path): values = {} if path.exists(): for line in path.read_text(encoding="utf-8").splitlines(): line = line.strip() if line and not line.startswith("#") and "=" in line: key, value = line.split("=", 1) values[key.strip()] = value.strip().strip("\"'") return values def main(): path = ROOT / ".env" existing = read_values(path) defaults = read_values(ROOT / ".env.example") defaults.update( POSTGRES_DB="messenger", POSTGRES_USER="messenger", POSTGRES_PASSWORD=secrets.token_hex(24), ) defaults.update(UPLOAD_CLEANUP_GRACE_SECONDS="600", UPLOAD_TMP_DIR="/tmp/uploads", S3_PUBLIC_ENDPOINT="http://127.0.0.1:9000", S3_CORS_ORIGINS="http://127.0.0.1:5173,http://localhost:5173") values = defaults | existing for name, lower, upper in ( ("APP_PORT", 1, 65535), ("API_REPLICAS", 2, 32), ("SESSION_TTL_SECONDS", 1, 31536000), ("IDEMPOTENCY_TTL_SECONDS", 1, 31536000), ): try: valid = lower <= int(values[name]) <= upper except (ValueError, KeyError): valid = False if not valid: raise SystemExit(f"{name} must be between {lower} and {upper}") for name in ( "POSTGRES_DB", "POSTGRES_USER", "POSTGRES_PASSWORD", "APP_HOST", "APP_ENV", ): if not values[name]: raise SystemExit(f"{name} must not be empty") # Existing values, including credentials, are never replaced. missing = {key: value for key, value in values.items() if key not in existing} if missing: prefix = "\n" if path.exists() and path.stat().st_size else "" with path.open("a", encoding="utf-8") as file: file.write( prefix + "".join(f"{key}={value}\n" for key, value in missing.items()) ) os.chmod(path, 0o600) secret_dir = ROOT / "secrets" secret_dir.mkdir(mode=0o700, exist_ok=True) database_url = "postgres://{}:{}@db:5432/{}?sslmode=disable".format( quote(values["POSTGRES_USER"], safe=""), quote(values["POSTGRES_PASSWORD"], safe=""), quote(values["POSTGRES_DB"], safe=""), ) for filename,content in (("broker_user","messenger"),("broker_password",secrets.token_hex(32))): target=secret_dir/filename if not target.exists(): target.write_text(content+"\n",encoding="utf-8") os.chmod(target,0o644) broker_url="amqp://{}:{}@broker:5672/%2F".format( quote((secret_dir/"broker_user").read_text().strip(),safe=""), quote((secret_dir/"broker_password").read_text().strip(),safe="")) # Migrate only the generated legacy Redis URL; preserve custom AMQP settings. broker_file=secret_dir/"broker_url" if broker_file.exists() and broker_file.read_text().strip()=="redis://broker:6379/0": broker_file.write_text(broker_url+"\n",encoding="utf-8") for name, content in ( ("DATABASE_URL_FILE", database_url), ("CACHE_URL_FILE", "redis://redis:6379/0"), ("BROKER_URL_FILE", broker_url), ("S3_ACCESS_KEY_ID_FILE", secrets.token_hex(12)), ("S3_SECRET_ACCESS_KEY_FILE", secrets.token_hex(32)), ): container_path = Path(values[name]) if container_path.parent != Path("/run/secrets") or not container_path.name: raise SystemExit(f"{name} must name a file directly inside /run/secrets") target = ( secret_dir / { "DATABASE_URL_FILE": "database_url", "CACHE_URL_FILE": "cache_url", "BROKER_URL_FILE": "broker_url", "S3_ACCESS_KEY_ID_FILE": "s3_access_key_id", "S3_SECRET_ACCESS_KEY_FILE": "s3_secret_access_key", }[name] ) if not target.exists(): # Containers run as an unprivileged user; the private host directory # protects the files, while read permission lets the API consume them. with target.open("x", encoding="utf-8") as file: file.write(content + "\n") os.chmod(target, 0o644) # Existing S3 files remain the root credentials; API gets a new, separate identity. for filename, content in ( ("s3_api_access_key_id", secrets.token_hex(12)), ("s3_api_secret_access_key", secrets.token_hex(32)), ): target = secret_dir / filename if not target.exists(): with target.open("x", encoding="utf-8") as file: file.write(content + "\n") os.chmod(target, 0o644) print("Local .env and connection files ready; existing values and files preserved.") if __name__ == "__main__": main()