Spaces:
Runtime error
Runtime error
File size: 4,997 Bytes
ed86a97 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | """Generate production secrets and write them to .env.production.local.
Idempotent: never overwrites a value that's already set in the target file.
The output file is gitignored (`.env.*.local` rule in .gitignore) so secrets
never get committed.
Generated values:
- APP_SECRETS_MASTER_KEY: 32-byte url-safe base64 (AES-256-GCM key for the
encryption-at-rest of LLM keys; mandatory in production).
- SUPERADMIN_PASSWORD: 24-character random password (only generated if the
user requests it via --include-superadmin-password β by default we leave
it blank so the operator picks something memorable).
Usage::
python scripts/generate_secrets.py
python scripts/generate_secrets.py --include-superadmin-password
python scripts/generate_secrets.py --output .env.production.local --force-rotate
After running, copy the printed values into Render's "Environment" tab β
NEVER commit .env.production.local to git.
"""
from __future__ import annotations
import argparse
import base64
import secrets
import string
import sys
from pathlib import Path
from typing import Dict, List, Tuple
DEFAULT_OUTPUT = Path(".env.production.local")
# Secrets we know how to generate. (env-var-name, generator, comment).
SECRET_GENERATORS = {
"APP_SECRETS_MASTER_KEY": (
lambda: base64.urlsafe_b64encode(secrets.token_bytes(32)).decode("ascii"),
"AES-256-GCM key for stored LLM keys at rest",
),
"SUPERADMIN_PASSWORD": (
lambda: _strong_password(24),
"First super-admin password β rotate via Supabase after first login",
),
}
def _strong_password(length: int = 24) -> str:
"""Generate a random ASCII password mixing letters, digits and symbols."""
alphabet = string.ascii_letters + string.digits + "!@#$%^&*-_=+"
return "".join(secrets.choice(alphabet) for _ in range(length))
def parse_env_file(path: Path) -> Dict[str, str]:
"""Parse a simple KEY=value env file. Tolerant of comments / blank lines."""
result: Dict[str, str] = {}
if not path.exists():
return result
for line in path.read_text(encoding="utf-8").splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
if "=" not in stripped:
continue
key, _, value = stripped.partition("=")
result[key.strip()] = value.strip()
return result
def write_env_file(path: Path, values: Dict[str, str], header: str) -> None:
"""Write values back, preserving order and adding a header banner."""
lines = [header.rstrip("\n"), ""]
for key, value in values.items():
lines.append(f"{key}={value}")
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
HEADER = """\
# AUTO-GENERATED by scripts/generate_secrets.py
# Do NOT commit this file β it contains production secrets.
# .gitignore already excludes .env.*.local but double-check before pushing.
#
# Copy the values below into Render β Service β Environment.
# Rotate APP_SECRETS_MASTER_KEY only via a coordinated rotation procedure
# (re-encryption of all stored LLM keys); never just edit it in place.
"""
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"--output",
type=Path,
default=DEFAULT_OUTPUT,
help=f"Target env file (default: {DEFAULT_OUTPUT})",
)
parser.add_argument(
"--include-superadmin-password",
action="store_true",
help="Also generate SUPERADMIN_PASSWORD (default: skipped, set manually)",
)
parser.add_argument(
"--force-rotate",
action="store_true",
help="Regenerate values even when already present in the output file",
)
args = parser.parse_args()
existing = parse_env_file(args.output)
new_secrets: List[Tuple[str, str]] = []
skipped: List[str] = []
for key, (generator, _comment) in SECRET_GENERATORS.items():
if key == "SUPERADMIN_PASSWORD" and not args.include_superadmin_password:
continue
if key in existing and existing[key].strip() and not args.force_rotate:
skipped.append(key)
continue
new_secrets.append((key, generator()))
if not new_secrets and not skipped:
print("nothing to do β no generators selected")
return 0
merged = dict(existing)
for key, value in new_secrets:
merged[key] = value
write_env_file(args.output, merged, HEADER)
print(f"wrote: {args.output}")
if new_secrets:
print("\nnew/rotated values (copy into Render env):\n")
for key, value in new_secrets:
comment = SECRET_GENERATORS[key][1]
print(f" # {comment}")
print(f" {key}={value}\n")
if skipped:
print("preserved (already set; pass --force-rotate to regenerate):")
for key in skipped:
print(f" - {key}")
return 0
if __name__ == "__main__":
sys.exit(main())
|