Spaces:
Runtime error

File size: 10,045 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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
"""Push a batch of env vars from a .env file to a Render service.

Wraps Render's REST API ``PUT /services/{id}/env-vars/{key}`` so the operator
can:
    1. Edit ``.env.production`` (gitignored) once
    2. Run this script
    3. Render redeploys with the new env

Connection details:
    --service-id   srv-…       (also reads RENDER_SERVICE_ID env)
    --api-key      rnda_…      (also reads RENDER_API_KEY env)

Source file selection:
    --env-file     path        (default: .env.production.local then .env.production)

Safety:
    - Skips lines that look like comments / blanks.
    - Refuses to push values containing literal "your_…_here" placeholders
      (unless --force is given) β€” those are template stubs.
    - Dry-run mode prints what *would* be sent without hitting the API.
    - Only updates keys listed in --include (if given) or excluded by --exclude.
    - Logs masked previews of secret values (last 4 chars).

Usage::

    # Dry-run from .env.production.local
    python scripts/push_env_to_render.py --dry-run

    # Real run
    RENDER_API_KEY=rnda_xxx RENDER_SERVICE_ID=srv-xxx \
        python scripts/push_env_to_render.py

    # Selective push
    python scripts/push_env_to_render.py \
        --include APP_SECRETS_MASTER_KEY,DATABASE_URL,SUPABASE_URL

After a successful push Render auto-deploys (unless auto-deploy is disabled).
"""

from __future__ import annotations

import argparse
import json
import os
import sys
import time
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Set
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen

DEFAULT_CANDIDATES = (".env.production.local", ".env.production")
PLACEHOLDER_MARKERS = ("your_", "_here", "xxx_replace_me", "<your-", "[pending", "[db_password")
REPO_ROOT = Path(__file__).resolve().parent.parent


def _autoload_env() -> None:
    """Auto-load .env.production.local so that --service-id / --api-key
    fall back to env vars when not provided on the command line."""
    for candidate in DEFAULT_CANDIDATES:
        path = REPO_ROOT / candidate
        if not path.exists():
            continue
        try:
            from dotenv import load_dotenv  # type: ignore[import-not-found]

            load_dotenv(path, override=False)
        except ImportError:
            for line in path.read_text(encoding="utf-8").splitlines():
                stripped = line.strip()
                if not stripped or stripped.startswith("#") or "=" not in stripped:
                    continue
                key, _, value = stripped.partition("=")
                os.environ.setdefault(key.strip(), value.strip().strip("'\""))
        return


_autoload_env()

# Control-plane variables β€” only consumed by deploy scripts locally.
# Never push these to the Render service: they'd be useless at runtime
# and the API key in particular would be a privilege escalation hazard.
DEFAULT_EXCLUDED_KEYS: Set[str] = {
    "RENDER_API_KEY",
    "RENDER_SERVICE_ID",
    "RENDER_PUBLIC_URL",
    "SUPABASE_DB_URL",  # duplicate of DATABASE_URL; only used by apply_supabase_schema.py
}


def _mask(value: str) -> str:
    if not value:
        return "(empty)"
    if len(value) <= 8:
        return "****"
    return f"{value[:2]}…{value[-4:]}"


def _looks_like_placeholder(value: str) -> bool:
    low = value.strip().lower()
    return any(marker in low for marker in PLACEHOLDER_MARKERS)


def parse_env_file(path: Path) -> Dict[str, str]:
    result: Dict[str, str] = {}
    if not path.exists():
        return result
    for line_no, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
        stripped = raw.strip()
        if not stripped or stripped.startswith("#"):
            continue
        if "=" not in stripped:
            continue
        key, _, value = stripped.partition("=")
        # Strip surrounding quotes if present.
        v = value.strip()
        if (v.startswith('"') and v.endswith('"')) or (v.startswith("'") and v.endswith("'")):
            v = v[1:-1]
        result[key.strip()] = v
    return result


def _select_env_file(explicit: Optional[Path]) -> Path:
    if explicit:
        if not explicit.exists():
            raise SystemExit(f"--env-file not found: {explicit}")
        return explicit
    for candidate in DEFAULT_CANDIDATES:
        p = Path(candidate)
        if p.exists():
            return p
    raise SystemExit(
        f"no env file found β€” looked for {' or '.join(DEFAULT_CANDIDATES)}; "
        "pass --env-file"
    )


def render_put_env_var(
    base_url: str,
    service_id: str,
    api_key: str,
    key: str,
    value: str,
    timeout: float = 20.0,
) -> Dict[str, object]:
    endpoint = f"{base_url.rstrip('/')}/services/{quote(service_id)}/env-vars/{quote(key)}"
    payload = json.dumps({"value": value}).encode("utf-8")
    req = Request(
        endpoint,
        method="PUT",
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": "ai-tester-platform/render-env-batch",
        },
        data=payload,
    )
    with urlopen(req, timeout=timeout) as response:
        body = response.read().decode("utf-8", errors="ignore").strip()
        return {
            "ok": True,
            "status": int(getattr(response, "status", 200) or 200),
            "body": body[:300] if body else "",
        }


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--service-id", default=os.getenv("RENDER_SERVICE_ID", ""))
    parser.add_argument("--api-key", default=os.getenv("RENDER_API_KEY", ""))
    parser.add_argument("--env-file", type=Path, default=None)
    parser.add_argument("--base-url", default="https://api.render.com/v1")
    parser.add_argument("--dry-run", action="store_true", help="Don't hit the API")
    parser.add_argument(
        "--include",
        default="",
        help="Comma-separated allowlist; if set, only these keys are pushed",
    )
    parser.add_argument(
        "--exclude",
        default="",
        help="Comma-separated denylist; these keys are never pushed",
    )
    parser.add_argument(
        "--force",
        action="store_true",
        help="Push values that look like placeholder text (your_..._here)",
    )
    parser.add_argument(
        "--throttle-seconds",
        type=float,
        default=0.4,
        help="Sleep between PUT calls to avoid Render API rate limits",
    )
    args = parser.parse_args()

    src = _select_env_file(args.env_file)
    pairs = parse_env_file(src)
    if not pairs:
        print(f"no usable key=value lines in {src}", file=sys.stderr)
        return 2

    include: Set[str] = {s.strip() for s in args.include.split(",") if s.strip()}
    user_exclude: Set[str] = {s.strip() for s in args.exclude.split(",") if s.strip()}
    # Default exclusions are always applied unless --include explicitly
    # selects the key (escape hatch for advanced users who really want to
    # push a control-plane var).
    effective_exclude = user_exclude | (DEFAULT_EXCLUDED_KEYS - include)

    selected: List[tuple[str, str]] = []
    skipped_placeholder: List[str] = []
    skipped_excluded: List[str] = []
    for key, value in pairs.items():
        if include and key not in include:
            continue
        if key in effective_exclude:
            skipped_excluded.append(key)
            continue
        if _looks_like_placeholder(value) and not args.force:
            skipped_placeholder.append(key)
            continue
        selected.append((key, value))

    print(f"\npush_env_to_render: source={src}, target_count={len(selected)}\n")
    for key, value in selected:
        print(f"  {key:30s}  =  {_mask(value)}")
    if skipped_placeholder:
        print("\nskipped (look like template placeholders, --force to push anyway):")
        for k in skipped_placeholder:
            print(f"  - {k}")
    if skipped_excluded:
        print("\nskipped (control-plane only, never pushed to Render):")
        for k in skipped_excluded:
            print(f"  - {k}")
    print()

    if args.dry_run:
        print("dry-run: not calling Render API")
        return 0

    if not args.service_id or not args.api_key:
        print(
            "missing creds β€” provide --service-id and --api-key, or set "
            "RENDER_SERVICE_ID + RENDER_API_KEY in env",
            file=sys.stderr,
        )
        return 2

    failures: List[tuple[str, str]] = []
    for key, value in selected:
        try:
            res = render_put_env_var(
                base_url=args.base_url,
                service_id=args.service_id,
                api_key=args.api_key,
                key=key,
                value=value,
            )
            print(f"  βœ“ {key}  http {res.get('status')}")
        except HTTPError as exc:
            body = ""
            try:
                body = exc.read().decode("utf-8", errors="ignore")[:300]
            except Exception:
                body = str(exc)
            failures.append((key, f"HTTP {exc.code}: {body}"))
            print(f"  βœ— {key}  HTTP {exc.code}: {body}", file=sys.stderr)
        except URLError as exc:
            failures.append((key, str(exc)))
            print(f"  βœ— {key}  network: {exc}", file=sys.stderr)
        except Exception as exc:
            failures.append((key, str(exc)))
            print(f"  βœ— {key}  {exc}", file=sys.stderr)
        time.sleep(max(0.0, args.throttle_seconds))

    print()
    if failures:
        print(f"push_env_to_render: FAILED on {len(failures)} key(s):")
        for key, msg in failures:
            print(f"  - {key}: {msg}")
        return 1

    print(f"push_env_to_render: pushed {len(selected)} keys βœ“")
    print("Render will auto-deploy unless auto-deploy is disabled on the service.")
    return 0


if __name__ == "__main__":
    sys.exit(main())