An open-source, faster Devin alternative
TypeScript
Temporary: copy production secrets into Infisical (work 097 step 1) (#1008)
opencomputer-app[bot]4f3bf02a9607
diff --git a/.github/workflows/copy-secrets-to-infisical.yml b/.github/workflows/copy-secrets-to-infisical.ymlnew file mode 100644index 00000000..f470c4ec--- /dev/null+++ b/.github/workflows/copy-secrets-to-infisical.yml@@ -0,0 +1,297 @@+# Temporary: copy this repository's production secrets into Infisical and verify+# them (serverless-agents-ws work 097, step 1, Track E). Delete after the move.+#+# Covers opencomputer's repository secrets used by deploy-api-edge.yml,+# deploy-log-tail.yml and apply-d1-migrations.yml. Not copied: NPM_TOKEN+# (publishing moves to trusted publishing), POSTHOG_PROJECT_TOKEN and+# POSTHOG_HOST (public build-time values, already deploy-repo variables), or+# the legacy CLOUDFLARE_API_TOKEN. Its scoped replacement already lives at+# /log-tail and is imported into /api-edge.+#+# Run by hand only. The default is a dry run: it lists secret names (present or+# empty in GitHub), what each would do in Infisical, and compares secret *names*+# on each production Worker against GitHub. With dry_run=false it creates or+# updates secrets in Infisical (never deletes; a secret that already exists with+# a different value is skipped unless overwrite=true) and reads each one back to+# verify it. Secret values are masked and travel in request bodies only.+#+# Merge this temporary workflow first, then run it from protected main.+# Infisical sign-in is a machine identity over GitHub OIDC (subject+# `repo:diggerhq/opencomputer:ref:refs/heads/main`, audience+# `https://github.com/diggerhq`), so no Infisical token is stored in GitHub.+# The destination is pinned by repository variables INFISICAL_IDENTITY_ID /+# INFISICAL_PROJECT_SLUG (and optional INFISICAL_DOMAIN); dispatchers cannot+# redirect production secrets to another project.+name: Copy secrets to Infisical (temporary)++on:+ workflow_dispatch:+ inputs:+ dry_run:+ description: Dry run (list names and planned actions; write nothing)+ type: boolean+ default: true+ overwrite:+ description: Replace secrets that already exist in Infisical with a different value+ type: boolean+ default: false++permissions:+ contents: read+ id-token: write++concurrency:+ group: copy-secrets-to-infisical+ cancel-in-progress: false++jobs:+ copy:+ runs-on: ubuntu-latest+ timeout-minutes: 15+ env:+ DRY_RUN: ${{ inputs.dry_run }}+ OVERWRITE: ${{ inputs.overwrite }}+ INFISICAL_IDENTITY_ID: ${{ vars.INFISICAL_IDENTITY_ID }}+ INFISICAL_PROJECT_SLUG: ${{ vars.INFISICAL_PROJECT_SLUG }}+ INFISICAL_DOMAIN: ${{ vars.INFISICAL_DOMAIN }}+ INFISICAL_ENV_SLUG: prod+ CF_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}+ CF_ACCOUNT_ID: b8f23cb87a7a6c64040d3134643da448+ # Every secret this repository's deploy workflows read, as S_<name>.+ S_AGENT_RUNTIME_USAGE_HMAC_SECRET: ${{ secrets.AGENT_RUNTIME_USAGE_HMAC_SECRET }}+ S_LOOPS_API_KEY: ${{ secrets.LOOPS_API_KEY }}+ S_LOOPS_EXCLUDE_EMAILS: ${{ secrets.LOOPS_EXCLUDE_EMAILS }}+ S_OC_MANAGED_CRED_HMAC_SECRET: ${{ secrets.OC_MANAGED_CRED_HMAC_SECRET }}+ S_SLACK_CONNECT_TOKEN: ${{ secrets.SLACK_CONNECT_TOKEN }}+ # Infisical folder -> GitHub secret names ("GITHUB_NAME:INFISICAL_NAME" when+ # the Worker binding differs), and production Worker -> the folder that feeds it+ # ("" = no GitHub-sourced secrets expected on that Worker).+ MANIFEST: |+ {+ "folders": {+ "/api-edge": [+ "OC_MANAGED_CRED_HMAC_SECRET",+ "AGENT_RUNTIME_USAGE_HMAC_SECRET",+ "LOOPS_API_KEY",+ "LOOPS_EXCLUDE_EMAILS",+ "SLACK_CONNECT_TOKEN"+ ]+ },+ "workers": {+ "opencomputer-edge-prod": "/api-edge",+ "opencomputer-log-tail-prod": ""+ }+ }+ steps:+ - name: Copy and verify+ shell: bash+ run: |+ umask 077+ cat > "$RUNNER_TEMP/infisical_copy.py" <<'PY'+ # Copy GitHub Actions secrets into Infisical and verify them, printing names only.+ # Temporary (work 097 step 1, Track E). Deleted after the move is verified.+ import json, os, sys, urllib.request, urllib.parse, urllib.error++ DRY = os.environ.get("DRY_RUN", "true") != "false"+ OVERWRITE = os.environ.get("OVERWRITE", "false") == "true"+ DOMAIN = (os.environ.get("INFISICAL_DOMAIN") or "https://app.infisical.com").rstrip("/")+ IDENTITY = os.environ.get("INFISICAL_IDENTITY_ID", "")+ PROJECT_SLUG = os.environ.get("INFISICAL_PROJECT_SLUG", "")+ ENV_SLUG = os.environ.get("INFISICAL_ENV_SLUG") or "prod"+ MANIFEST = json.loads(os.environ["MANIFEST"])+ OPTIONAL_GITHUB_SECRETS = {"LOOPS_API_KEY", "LOOPS_EXCLUDE_EMAILS", "SLACK_CONNECT_TOKEN"}+ SUMMARY = []+ FAILED = False++ def out(line=""):+ print(line, flush=True); SUMMARY.append(line)++ def fail(msg):+ global FAILED+ FAILED = True; out(f"::error::{msg}")++ def mask(value):+ for line in value.splitlines():+ if line.strip():+ print(f"::add-mask::{line}", flush=True)++ def normalize(v): # what Infisical stores: trimmed, one trailing newline kept+ return v.strip() + ("\n" if v.endswith("\n") else "")++ def api(method, path, body=None, token=None, form=False, query=None):+ url = DOMAIN + path + ("?" + urllib.parse.urlencode(query) if query else "")+ data = None; headers = {"Accept": "application/json"}+ if body is not None:+ if form:+ data = urllib.parse.urlencode(body).encode(); headers["Content-Type"] = "application/x-www-form-urlencoded"+ else:+ data = json.dumps(body).encode(); headers["Content-Type"] = "application/json"+ if token: headers["Authorization"] = f"Bearer {token}"+ req = urllib.request.Request(url, data=data, method=method, headers=headers)+ try:+ with urllib.request.urlopen(req, timeout=60) as r:+ return json.loads(r.read() or b"{}")+ except urllib.error.HTTPError as e:+ raise RuntimeError(f"{method} {path}: HTTP {e.code}") from None++ def github_oidc_token():+ url = os.environ["ACTIONS_ID_TOKEN_REQUEST_URL"]; tok = os.environ["ACTIONS_ID_TOKEN_REQUEST_TOKEN"]+ req = urllib.request.Request(url, headers={"Authorization": f"bearer {tok}", "Accept": "application/json"})+ with urllib.request.urlopen(req, timeout=60) as r:+ return json.loads(r.read())["value"]++ def cf(path, token):+ req = urllib.request.Request("https://api.cloudflare.com/client/v4" + path, headers={"Authorization": f"Bearer {token}"})+ try:+ with urllib.request.urlopen(req, timeout=60) as r:+ return json.loads(r.read())+ except urllib.error.HTTPError as e:+ return {"success": False, "errors": [{"message": f"HTTP {e.code}"}]}++ # 1. Inventory of the GitHub side: folder -> [(infisical_name, github_name, value)]+ plan = {}+ out(f"## Secrets to Infisical ({'dry run' if DRY else 'WRITE'}; overwrite={OVERWRITE})")+ out(f"Project `{PROJECT_SLUG}`, environment `{ENV_SLUG}`, domain `{DOMAIN}`")+ out()+ out("| Folder | Infisical name | GitHub secret | In GitHub |")+ out("|---|---|---|---|")+ for folder, names in MANIFEST["folders"].items():+ plan[folder] = []+ for entry in names:+ gh_name, _, inf_name = entry.partition(":")+ inf_name = inf_name or gh_name+ value = os.environ.get("S_" + gh_name, "")+ if value: mask(value)+ state = "present" if value else "EMPTY (skipped)"+ if not value and not DRY and gh_name not in OPTIONAL_GITHUB_SECRETS:+ fail(f"Required GitHub secret {gh_name} is empty; refusing an incomplete write run")+ if value and normalize(value) != value:+ state += ", trailing/leading whitespace would be trimmed by Infisical"+ out(f"| `{folder}` | `{inf_name}` | `{gh_name}` | {state} |")+ plan[folder].append((inf_name, gh_name, value))+ out()++ # 2. Infisical: sign in over GitHub OIDC, resolve the project.+ token = None; project_id = None+ if not IDENTITY or not PROJECT_SLUG:+ fail("INFISICAL_IDENTITY_ID / INFISICAL_PROJECT_SLUG not set; refusing to run")+ elif FAILED:+ out("Write preflight failed; skipping Infisical authentication and all writes.")+ else:+ try:+ jwt = github_oidc_token()+ mask(jwt)+ token = api("POST", "/api/v1/auth/oidc-auth/login", {"identityId": IDENTITY, "jwt": jwt}, form=True)["accessToken"]+ print(f"::add-mask::{token}", flush=True)+ proj = api("GET", f"/api/v1/projects/slug/{PROJECT_SLUG}", token=token)+ project_id = proj.get("id") or proj.get("project", {}).get("id")+ if not project_id:+ raise RuntimeError("project lookup returned no project id")+ out(f"Signed in to Infisical as identity `{IDENTITY}`; project id resolved.")+ except Exception as e:+ fail(f"Infisical sign-in failed: {e}")++ if token and project_id:+ # 3. Folders+ try:+ existing = {f"/{f['name']}" for f in api("GET", "/api/v2/folders", token=token,+ query={"projectId": project_id, "environment": ENV_SLUG, "path": "/"})["folders"]}+ except Exception as e:+ fail(f"Listing folders failed: {e}"); existing = set()+ missing = set(plan) - existing+ for folder in plan:+ if folder in existing: continue+ if DRY:+ out(f"- folder `{folder}`: missing, would be created")+ else:+ try:+ api("POST", "/api/v2/folders", {"projectId": project_id, "environment": ENV_SLUG,+ "name": folder.strip("/"), "path": "/"}, token=token)+ existing.add(folder)+ out(f"- folder `{folder}`: created")+ except Exception as e:+ fail(f"Creating folder {folder} failed: {e}")+ out()+ # 4. Per folder: compare, upsert, verify. Values never leave this process.+ out("| Folder | Name | Before | Action | Verified |")+ out("|---|---|---|---|---|")+ for folder, entries in plan.items():+ def fetch():+ r = api("GET", "/api/v4/secrets", token=token, query={"projectId": project_id, "environment": ENV_SLUG,+ "secretPath": folder, "viewSecretValue": "true", "includeImports": "false", "expandSecretReferences": "false"})+ vals = {}+ for s in r.get("secrets", []):+ v = s.get("secretValue")+ if v: mask(v)+ vals[s["secretKey"]] = v+ return vals+ if DRY and folder in missing:+ before = {}+ else:+ try:+ before = fetch()+ except Exception as e:+ fail(f"Listing {folder} failed: {e}"); before = {}; continue+ to_write = []+ rows = []+ for inf_name, gh_name, value in entries:+ if not value:+ rows.append([folder, inf_name, "n/a", "skipped: empty in GitHub", "-"]); continue+ want = normalize(value)+ if inf_name not in before:+ state, action = "absent", "create"+ elif before[inf_name] == want:+ state, action = "same value", "none"+ else:+ state = "DIFFERENT value"+ action = "overwrite" if OVERWRITE else "SKIPPED (differs; rerun with overwrite=true to replace)"+ if action in ("create", "overwrite"):+ to_write.append({"secretKey": inf_name, "secretValue": value})+ rows.append([folder, inf_name, state, action, ""])+ if to_write and not DRY:+ try:+ api("PATCH", "/api/v4/secrets/batch", {"projectId": project_id, "environment": ENV_SLUG,+ "secretPath": folder, "mode": "upsert", "secrets": to_write}, token=token)+ except Exception as e:+ fail(f"Writing to {folder} failed: {e}")+ after = fetch() if not DRY else before+ for row in rows:+ inf_name = row[1]; value = next(v for n, g, v in entries if n == inf_name)+ if not value: pass+ elif DRY: row[4] = "dry run"+ else:+ ok = after.get(inf_name) == normalize(value)+ row[4] = "yes" if ok else "NO"+ if not ok and "SKIPPED" in row[3]: fail(f"{folder}/{inf_name}: Infisical holds a different value than GitHub; left as is")+ elif not ok: fail(f"{folder}/{inf_name}: value read back from Infisical does not match GitHub")+ out("| " + " | ".join(f"`{c}`" if i < 2 else c for i, c in enumerate(row)) + " |")+ out()++ # 5. Worker secret names (Cloudflare, read-only) vs the folder that feeds each Worker.+ cf_token = os.environ.get("CF_API_TOKEN", ""); cf_account = os.environ.get("CF_ACCOUNT_ID", "")+ if MANIFEST.get("workers"):+ out("## Worker secrets vs GitHub")+ if not cf_token or not cf_account:+ fail("CF_API_TOKEN / CF_ACCOUNT_ID missing: Worker comparison cannot run")+ for worker, folder in MANIFEST["workers"].items():+ if not cf_token or not cf_account: break+ r = cf(f"/accounts/{cf_account}/workers/scripts/{worker}/secrets", cf_token)+ if not r.get("success"):+ fail(f"{worker}: could not list Worker secrets"); continue+ on_worker = {s["name"] for s in r["result"]}+ in_github = {n for n, g, v in plan.get(folder, []) if v}+ listed_empty = {n for n, g, v in plan.get(folder, []) if not v}+ out(f"- `{worker}` (fed from `{folder}`): {len(on_worker)} secret bindings on the Worker")+ for n in sorted(on_worker - in_github):+ note = " (listed in GitHub but EMPTY there)" if n in listed_empty else " (NO GitHub source: set by hand?)"+ out(f" - `{n}`: on Worker only{note}")+ for n in sorted(in_github - on_worker):+ out(f" - `{n}`: in GitHub only (never pushed to this Worker)")+ if on_worker == in_github: out(" - names match exactly")+ out()++ with open(os.environ.get("GITHUB_STEP_SUMMARY", "/dev/null"), "a") as f:+ f.write("\n".join(SUMMARY) + "\n")+ sys.exit(1 if FAILED else 0)+ PY+ python3 -I "$RUNNER_TEMP/infisical_copy.py"