diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 009c982..6a0bf8b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,7 +31,7 @@ jobs: fetch-depth: 0 - uses: sourceplane/orun-action@v1.2.0 with: - version: v2.39.0 + version: v2.48.0 - env: # Surface the best-effort catalog auto-sync (execution.state.autopushCatalog). # A successful push prints "✓ pushed catalog …"; ORUN_VERBOSE also makes @@ -63,6 +63,10 @@ jobs: if: ${{ needs.plan.outputs.job-matrix != '[]' && needs.plan.outputs.job-matrix != '' }} strategy: fail-fast: false + # Stagger the fan-out: every lane hits the lease-bound resolve at job + # start, and an unbounded herd saturated it twice. The orun DAG already + # serializes dependents, so capped parallelism costs little wall-clock. + max-parallel: 8 matrix: include: ${{ fromJson(needs.plan.outputs.job-matrix) }} name: ${{ matrix.job-name }} @@ -79,33 +83,30 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - uses: sourceplane/orun-action@v1.2.0 with: - version: v2.39.0 + version: v2.48.0 + # exec-id is the RUN id alone (no attempt suffix): a `gh run rerun + # --failed` then RESUMES the same orun execution — jobs that succeeded in + # a prior attempt stay completed, so re-run lanes' cross-job dependencies + # are already satisfied instead of waiting forever on lanes that are not + # re-running (the partial-rerun deadlock). --retry re-opens THIS lane's + # job when it terminally failed in a prior attempt (no-op on first + # attempts) — together they make `gh run rerun --failed` a true resume. - run: | orun run \ --plan plan.json \ --runner github-actions \ --remote-state \ --job "${{ matrix.job-id }}" \ - --exec-id "${{ github.run_id }}-${{ github.run_attempt }}" + --exec-id "${{ github.run_id }}" \ + --retry env: + # GITHUB_TOKEN is the only credential CI holds — GitHub-issued and + # ephemeral. Every provider credential (Cloudflare token + account + # id, Supabase management token + org id) is an orun-managed secret: + # brokered fresh per run from the workspace's integrations, resolved + # lease-bound by the jobs that declare it (profile secretBindings or + # component secretEnv), and log-redacted. Nothing provider-shaped is + # stored in GitHub. GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # CLOUDFLARE_API_TOKEN is now an orun-managed brokered secret - # (secret://lumen/lumen//CLOUDFLARE_API_TOKEN, minted fresh per - # run from the Cloudflare integration): worker deploys receive it via - # the deploy profile's secretBindings, cloudflare-kv via its - # component secretEnv — the resolved value overrides this ambient one. - # The ambient copy remains ONLY for cloudflare-hyperdrive and - # cloudflare-domain, whose Terraform needs Hyperdrive/DNS permissions - # the workers-deploy broker template does not mint yet. Remove it when - # those two components migrate. - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - SUPABASE_API_KEY: ${{ secrets.SUPABASE_API_KEY }} - SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_API_KEY }} - TF_VAR_cloudflare_account_id: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - # Supabase org id is environment/account-specific, so it comes from a - # CI secret rather than a committed component parameter. Used by the - # supabase terraform component as var.supabaseOrgId. - TF_VAR_supabaseOrgId: ${{ secrets.SUPABASE_ORG_ID }} DOCKER_CONFIG: /home/runner/.docker diff --git a/apps/admin-worker/component.yaml b/apps/admin-worker/component.yaml index eda7e71..6608455 100644 --- a/apps/admin-worker/component.yaml +++ b/apps/admin-worker/component.yaml @@ -11,6 +11,13 @@ spec: path: apps/admin-worker dependsOn: - component: cloudflare-hyperdrive + # BF6 wiring documents from orun secrets (SEC-JOB): lease-published by + # the infra components; wire-live renders the wrangler template from + # these instead of Secrets Manager documents. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://lumen/lumen/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://lumen/lumen/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + subscribe: environments: - name: dev @@ -35,8 +42,6 @@ spec: # BF6b: deploy-time wiring — wrangler.jsonc is rendered, never committed. # Verify lanes render from wiring.fixture.json (offline); deploy lanes # resolve real IDs from the Secrets Manager wiring manifest (BF5). - awsAccountId: "306024784101" - awsRegion: us-east-1 orgName: sourceplane owner: sourceplane repo: lumen diff --git a/apps/api-edge/component.yaml b/apps/api-edge/component.yaml index ee1f0aa..3bfa4d7 100644 --- a/apps/api-edge/component.yaml +++ b/apps/api-edge/component.yaml @@ -22,6 +22,15 @@ spec: - component: membership-worker - component: metering-worker - component: notifications-worker + # BF6 wiring documents from orun secrets (SEC-JOB): lease-published by + # the infra components; wire-live renders the wrangler template from + # these instead of Secrets Manager documents. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://lumen/lumen/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://lumen/lumen/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_KV_STAGE: "secret://lumen/lumen/stage/WIRING_CLOUDFLARE_KV" + WIRING_CLOUDFLARE_KV_PROD: "secret://lumen/lumen/prod/WIRING_CLOUDFLARE_KV" + subscribe: environments: - name: dev @@ -56,8 +65,6 @@ spec: wiringComponents: "cloudflare-hyperdrive,cloudflare-kv" wiringEnvs: "stage,prod" wiringFixture: wiring.fixture.json - awsAccountId: "306024784101" - awsRegion: us-east-1 orgName: sourceplane owner: sourceplane repo: lumen diff --git a/apps/billing-worker/component.yaml b/apps/billing-worker/component.yaml index be6f5d5..8488f08 100644 --- a/apps/billing-worker/component.yaml +++ b/apps/billing-worker/component.yaml @@ -11,6 +11,20 @@ spec: path: apps/billing-worker dependsOn: - component: policy-worker + # Runtime secrets, wire-now-seed-later: best-effort references — + # an unseeded key is skipped at resolve (and by secrets-live), so + # this block is inert until the value is stored in orun secrets. + # BF6 wiring documents from orun secrets (SEC-JOB): lease-published by + # the infra components; wire-live renders the wrangler template from + # these instead of Secrets Manager documents. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://lumen/lumen/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://lumen/lumen/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + + optionalSecretEnv: + POLAR_ACCESS_TOKEN: "secret://lumen/lumen/{{ .environment }}/POLAR_ACCESS_TOKEN" + POLAR_WEBHOOK_SECRET: "secret://lumen/lumen/{{ .environment }}/POLAR_WEBHOOK_SECRET" + subscribe: environments: - name: dev @@ -35,14 +49,13 @@ spec: # BF6b: deploy-time wiring — wrangler.jsonc is rendered, never committed. # Verify lanes render from wiring.fixture.json (offline); deploy lanes # resolve real IDs from the Secrets Manager wiring manifest (BF5). - awsAccountId: "306024784101" - awsRegion: us-east-1 orgName: sourceplane owner: sourceplane repo: lumen - # SS2: manifest key for the secrets-live escrow sync (saas-secrets-sync). - secretsWorker: billing-worker + # Runtime worker secrets, pushed by the secrets-live step from the + # values orun resolves for the optionalSecretEnv references below. + runtimeSecrets: "POLAR_ACCESS_TOKEN,POLAR_WEBHOOK_SECRET" turboFilter: "@saas/billing-worker" wranglerConfig: wrangler.jsonc wranglerTemplate: wrangler.template.jsonc diff --git a/apps/config-worker/component.yaml b/apps/config-worker/component.yaml index fc753ca..6325711 100644 --- a/apps/config-worker/component.yaml +++ b/apps/config-worker/component.yaml @@ -12,6 +12,19 @@ spec: dependsOn: - component: membership-worker - component: policy-worker + # Runtime secrets, wire-now-seed-later: best-effort references — + # an unseeded key is skipped at resolve (and by secrets-live), so + # this block is inert until the value is stored in orun secrets. + # BF6 wiring documents from orun secrets (SEC-JOB): lease-published by + # the infra components; wire-live renders the wrangler template from + # these instead of Secrets Manager documents. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://lumen/lumen/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://lumen/lumen/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + + optionalSecretEnv: + SECRET_ENCRYPTION_KEY: "secret://lumen/lumen/{{ .environment }}/SECRET_ENCRYPTION_KEY" + subscribe: environments: - name: dev @@ -36,14 +49,13 @@ spec: # BF6b: deploy-time wiring — wrangler.jsonc is rendered, never committed. # Verify lanes render from wiring.fixture.json (offline); deploy lanes # resolve real IDs from the Secrets Manager wiring manifest (BF5). - awsAccountId: "306024784101" - awsRegion: us-east-1 orgName: sourceplane owner: sourceplane repo: lumen - # SS2: manifest key for the secrets-live escrow sync (saas-secrets-sync). - secretsWorker: config-worker + # Runtime worker secrets, pushed by the secrets-live step from the + # values orun resolves for the optionalSecretEnv references below. + runtimeSecrets: "SECRET_ENCRYPTION_KEY" turboFilter: "@saas/config-worker" wranglerConfig: wrangler.jsonc wranglerTemplate: wrangler.template.jsonc @@ -55,14 +67,15 @@ spec: typecheckCommand: pnpm exec turbo run typecheck --filter=@saas/config-worker dryRunCommand: pnpm exec wrangler deploy --dry-run --config wrangler.jsonc --env prod deployCommand: pnpm exec wrangler deploy --config wrangler.jsonc --env prod - # Ensure the secrets-at-rest encryption key exists on every deploy target - # before the worker ships (PX2 completion — live stage verification found - # "Encryption is not configured"). Generate-if-missing, idempotent: + # Safety net: ensure the secrets-at-rest encryption key exists on every + # deploy target before the worker ships. Generate-if-missing, idempotent — # `wrangler secret list` is the existence probe; the key is generated in # CI, pushed straight to Cloudflare, and never logged or persisted - # elsewhere. Runs only in the deploy profile (pre-deploy capability), so - # PR/verify lanes never touch live secrets. AWS Secrets Manager escrow of - # this key is a named follow-up (BF deploy-time wiring). + # elsewhere. The MANAGED path is orun secrets: seed SECRET_ENCRYPTION_KEY + # (escrow the CURRENTLY DEPLOYED value — a fresh key bricks stored data) + # and the secrets-live step keeps the worker in sync; this pre-deploy + # probe then always finds the key present and does nothing. Remove it + # once the key is seeded in orun. preDeployCommand: | for e in stage prod; do if ! pnpm exec wrangler secret list --config wrangler.jsonc --env "$e" 2>/dev/null | grep -q '"SECRET_ENCRYPTION_KEY"'; then diff --git a/apps/events-worker/component.yaml b/apps/events-worker/component.yaml index affd50a..3251ae6 100644 --- a/apps/events-worker/component.yaml +++ b/apps/events-worker/component.yaml @@ -12,6 +12,13 @@ spec: dependsOn: - component: membership-worker - component: policy-worker + # BF6 wiring documents from orun secrets (SEC-JOB): lease-published by + # the infra components; wire-live renders the wrangler template from + # these instead of Secrets Manager documents. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://lumen/lumen/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://lumen/lumen/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + subscribe: environments: - name: dev @@ -36,8 +43,6 @@ spec: # BF6b: deploy-time wiring — wrangler.jsonc is rendered, never committed. # Verify lanes render from wiring.fixture.json (offline); deploy lanes # resolve real IDs from the Secrets Manager wiring manifest (BF5). - awsAccountId: "306024784101" - awsRegion: us-east-1 orgName: sourceplane owner: sourceplane repo: lumen diff --git a/apps/identity-worker/component.yaml b/apps/identity-worker/component.yaml index 79b4e76..d5dcc49 100644 --- a/apps/identity-worker/component.yaml +++ b/apps/identity-worker/component.yaml @@ -14,6 +14,21 @@ spec: - component: policy-worker - component: membership-worker - component: notifications-worker + # Runtime secrets, wire-now-seed-later: best-effort references — + # an unseeded key is skipped at resolve (and by secrets-live), so + # this block is inert until the value is stored in orun secrets. + # BF6 wiring documents from orun secrets (SEC-JOB): lease-published by + # the infra components; wire-live renders the wrangler template from + # these instead of Secrets Manager documents. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://lumen/lumen/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://lumen/lumen/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + + optionalSecretEnv: + GITHUB_OAUTH_CLIENT_SECRET: "secret://lumen/lumen/{{ .environment }}/GITHUB_OAUTH_CLIENT_SECRET" + GOOGLE_OAUTH_CLIENT_SECRET: "secret://lumen/lumen/{{ .environment }}/GOOGLE_OAUTH_CLIENT_SECRET" + OAUTH_STATE_SECRET: "secret://lumen/lumen/{{ .environment }}/OAUTH_STATE_SECRET" + subscribe: environments: - name: dev @@ -38,14 +53,13 @@ spec: # BF6b: deploy-time wiring — wrangler.jsonc is rendered, never committed. # Verify lanes render from wiring.fixture.json (offline); deploy lanes # resolve real IDs from the Secrets Manager wiring manifest (BF5). - awsAccountId: "306024784101" - awsRegion: us-east-1 orgName: sourceplane owner: sourceplane repo: lumen - # SS2: manifest key for the secrets-live escrow sync (saas-secrets-sync). - secretsWorker: identity-worker + # Runtime worker secrets, pushed by the secrets-live step from the + # values orun resolves for the optionalSecretEnv references below. + runtimeSecrets: "GITHUB_OAUTH_CLIENT_SECRET,GOOGLE_OAUTH_CLIENT_SECRET,OAUTH_STATE_SECRET" turboFilter: "@saas/identity-worker" wranglerConfig: wrangler.jsonc wranglerTemplate: wrangler.template.jsonc diff --git a/apps/integrations-worker/component.yaml b/apps/integrations-worker/component.yaml index f555375..1474fb5 100644 --- a/apps/integrations-worker/component.yaml +++ b/apps/integrations-worker/component.yaml @@ -14,6 +14,23 @@ spec: - component: policy-worker - component: billing-worker - component: projects-worker + # Runtime secrets, wire-now-seed-later: best-effort references — + # an unseeded key is skipped at resolve (and by secrets-live), so + # this block is inert until the value is stored in orun secrets. + # BF6 wiring documents from orun secrets (SEC-JOB): lease-published by + # the infra components; wire-live renders the wrangler template from + # these instead of Secrets Manager documents. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://lumen/lumen/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://lumen/lumen/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + + optionalSecretEnv: + SECRET_ENCRYPTION_KEY: "secret://lumen/lumen/{{ .environment }}/SECRET_ENCRYPTION_KEY" + INTEGRATIONS_STATE_SECRET: "secret://lumen/lumen/{{ .environment }}/INTEGRATIONS_STATE_SECRET" + GITHUB_APP_PRIVATE_KEY: "secret://lumen/lumen/{{ .environment }}/GITHUB_APP_PRIVATE_KEY" + GITHUB_APP_WEBHOOK_SECRET: "secret://lumen/lumen/{{ .environment }}/GITHUB_APP_WEBHOOK_SECRET" + GITHUB_APP_CLIENT_SECRET: "secret://lumen/lumen/{{ .environment }}/GITHUB_APP_CLIENT_SECRET" + subscribe: environments: - name: dev @@ -38,14 +55,13 @@ spec: # BF6b: deploy-time wiring — wrangler.jsonc is rendered, never committed. # Verify lanes render from wiring.fixture.json (offline); deploy lanes # resolve real IDs from the Secrets Manager wiring manifest (BF5). - awsAccountId: "306024784101" - awsRegion: us-east-1 orgName: sourceplane owner: sourceplane repo: lumen - # SS2: manifest key for the secrets-live escrow sync (saas-secrets-sync). - secretsWorker: integrations-worker + # Runtime worker secrets, pushed by the secrets-live step from the + # values orun resolves for the optionalSecretEnv references below. + runtimeSecrets: "SECRET_ENCRYPTION_KEY,INTEGRATIONS_STATE_SECRET,GITHUB_APP_PRIVATE_KEY,GITHUB_APP_WEBHOOK_SECRET,GITHUB_APP_CLIENT_SECRET" turboFilter: "@saas/integrations-worker" wranglerConfig: wrangler.jsonc wranglerTemplate: wrangler.template.jsonc diff --git a/apps/membership-worker/component.yaml b/apps/membership-worker/component.yaml index 46a0a74..c438390 100644 --- a/apps/membership-worker/component.yaml +++ b/apps/membership-worker/component.yaml @@ -12,6 +12,13 @@ spec: dependsOn: - component: policy-worker - component: billing-worker + # BF6 wiring documents from orun secrets (SEC-JOB): lease-published by + # the infra components; wire-live renders the wrangler template from + # these instead of Secrets Manager documents. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://lumen/lumen/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://lumen/lumen/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + subscribe: environments: - name: dev @@ -36,8 +43,6 @@ spec: # BF6b: deploy-time wiring — wrangler.jsonc is rendered, never committed. # Verify lanes render from wiring.fixture.json (offline); deploy lanes # resolve real IDs from the Secrets Manager wiring manifest (BF5). - awsAccountId: "306024784101" - awsRegion: us-east-1 orgName: sourceplane owner: sourceplane repo: lumen diff --git a/apps/metering-worker/component.yaml b/apps/metering-worker/component.yaml index 72a3b09..dd130be 100644 --- a/apps/metering-worker/component.yaml +++ b/apps/metering-worker/component.yaml @@ -12,6 +12,13 @@ spec: dependsOn: - component: membership-worker - component: policy-worker + # BF6 wiring documents from orun secrets (SEC-JOB): lease-published by + # the infra components; wire-live renders the wrangler template from + # these instead of Secrets Manager documents. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://lumen/lumen/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://lumen/lumen/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + subscribe: environments: - name: dev @@ -36,8 +43,6 @@ spec: # BF6b: deploy-time wiring — wrangler.jsonc is rendered, never committed. # Verify lanes render from wiring.fixture.json (offline); deploy lanes # resolve real IDs from the Secrets Manager wiring manifest (BF5). - awsAccountId: "306024784101" - awsRegion: us-east-1 orgName: sourceplane owner: sourceplane repo: lumen diff --git a/apps/notifications-worker/component.yaml b/apps/notifications-worker/component.yaml index 8257007..a821d1e 100644 --- a/apps/notifications-worker/component.yaml +++ b/apps/notifications-worker/component.yaml @@ -12,6 +12,13 @@ spec: dependsOn: - component: events-worker - component: db-migrate + # BF6 wiring documents from orun secrets (SEC-JOB): lease-published by + # the infra components; wire-live renders the wrangler template from + # these instead of Secrets Manager documents. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://lumen/lumen/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://lumen/lumen/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + subscribe: environments: - name: dev @@ -36,8 +43,6 @@ spec: # BF6b: deploy-time wiring — wrangler.jsonc is rendered, never committed. # Verify lanes render from wiring.fixture.json (offline); deploy lanes # resolve real IDs from the Secrets Manager wiring manifest (BF5). - awsAccountId: "306024784101" - awsRegion: us-east-1 orgName: sourceplane owner: sourceplane repo: lumen diff --git a/apps/policy-worker/component.yaml b/apps/policy-worker/component.yaml index 877668a..ff6cfcb 100644 --- a/apps/policy-worker/component.yaml +++ b/apps/policy-worker/component.yaml @@ -32,8 +32,6 @@ spec: appDir: . # BF6: identity/role inputs for the deploy lane's wire-credentials step. # Inert until this worker gets a wrangler template (fleet rollout, BF6b). - awsAccountId: "306024784101" - awsRegion: us-east-1 orgName: sourceplane owner: sourceplane repo: lumen diff --git a/apps/projects-worker/component.yaml b/apps/projects-worker/component.yaml index 8a1b358..569bb8d 100644 --- a/apps/projects-worker/component.yaml +++ b/apps/projects-worker/component.yaml @@ -13,6 +13,13 @@ spec: - component: membership-worker - component: policy-worker - component: billing-worker + # BF6 wiring documents from orun secrets (SEC-JOB): lease-published by + # the infra components; wire-live renders the wrangler template from + # these instead of Secrets Manager documents. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://lumen/lumen/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://lumen/lumen/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + subscribe: environments: - name: dev @@ -37,8 +44,6 @@ spec: # BF6b: deploy-time wiring — wrangler.jsonc is rendered, never committed. # Verify lanes render from wiring.fixture.json (offline); deploy lanes # resolve real IDs from the Secrets Manager wiring manifest (BF5). - awsAccountId: "306024784101" - awsRegion: us-east-1 orgName: sourceplane owner: sourceplane repo: lumen diff --git a/apps/webhooks-worker/component.yaml b/apps/webhooks-worker/component.yaml index d03085e..93911a3 100644 --- a/apps/webhooks-worker/component.yaml +++ b/apps/webhooks-worker/component.yaml @@ -12,6 +12,19 @@ spec: dependsOn: - component: membership-worker - component: policy-worker + # Runtime secrets, wire-now-seed-later: best-effort references — + # an unseeded key is skipped at resolve (and by secrets-live), so + # this block is inert until the value is stored in orun secrets. + # BF6 wiring documents from orun secrets (SEC-JOB): lease-published by + # the infra components; wire-live renders the wrangler template from + # these instead of Secrets Manager documents. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://lumen/lumen/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://lumen/lumen/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + + optionalSecretEnv: + SECRET_ENCRYPTION_KEY: "secret://lumen/lumen/{{ .environment }}/SECRET_ENCRYPTION_KEY" + subscribe: environments: - name: dev @@ -36,14 +49,13 @@ spec: # BF6b: deploy-time wiring — wrangler.jsonc is rendered, never committed. # Verify lanes render from wiring.fixture.json (offline); deploy lanes # resolve real IDs from the Secrets Manager wiring manifest (BF5). - awsAccountId: "306024784101" - awsRegion: us-east-1 orgName: sourceplane owner: sourceplane repo: lumen - # SS2: manifest key for the secrets-live escrow sync (saas-secrets-sync). - secretsWorker: webhooks-worker + # Runtime worker secrets, pushed by the secrets-live step from the + # values orun resolves for the optionalSecretEnv references below. + runtimeSecrets: "SECRET_ENCRYPTION_KEY" turboFilter: "@saas/webhooks-worker" wranglerConfig: wrangler.jsonc wranglerTemplate: wrangler.template.jsonc diff --git a/blueprints/01-foundation.yaml b/blueprints/01-foundation.yaml index 4ae882d..caf97a5 100644 --- a/blueprints/01-foundation.yaml +++ b/blueprints/01-foundation.yaml @@ -61,7 +61,18 @@ ignore: - .next - .wrangler - .open-next -- wrangler.jsonc +- apps/admin-worker/wrangler.jsonc +- apps/api-edge/wrangler.jsonc +- apps/billing-worker/wrangler.jsonc +- apps/config-worker/wrangler.jsonc +- apps/events-worker/wrangler.jsonc +- apps/identity-worker/wrangler.jsonc +- apps/integrations-worker/wrangler.jsonc +- apps/membership-worker/wrangler.jsonc +- apps/metering-worker/wrangler.jsonc +- apps/notifications-worker/wrangler.jsonc +- apps/projects-worker/wrangler.jsonc +- apps/webhooks-worker/wrangler.jsonc - '*.tsbuildinfo' modules: - name: cli diff --git a/blueprints/02-infrastructure.yaml b/blueprints/02-infrastructure.yaml index 499725c..94a5568 100644 --- a/blueprints/02-infrastructure.yaml +++ b/blueprints/02-infrastructure.yaml @@ -61,14 +61,20 @@ ignore: - .next - .wrangler - .open-next -- wrangler.jsonc +- apps/admin-worker/wrangler.jsonc +- apps/api-edge/wrangler.jsonc +- apps/billing-worker/wrangler.jsonc +- apps/config-worker/wrangler.jsonc +- apps/events-worker/wrangler.jsonc +- apps/identity-worker/wrangler.jsonc +- apps/integrations-worker/wrangler.jsonc +- apps/membership-worker/wrangler.jsonc +- apps/metering-worker/wrangler.jsonc +- apps/notifications-worker/wrangler.jsonc +- apps/projects-worker/wrangler.jsonc +- apps/webhooks-worker/wrangler.jsonc - '*.tsbuildinfo' modules: -- name: bootstrap - mode: copy - source: baseline - from: infra/terraform/bootstrap - to: infra/terraform/bootstrap - name: cloudflare-hyperdrive mode: copy source: baseline @@ -93,12 +99,9 @@ modules: source: baseline from: infra/terraform/supabase to: infra/terraform/supabase - dependsOn: - - bootstrap phases: - name: infrastructure modules: - - bootstrap - cloudflare-hyperdrive - cloudflare-kv - db-migrate diff --git a/blueprints/03-workers.yaml b/blueprints/03-workers.yaml index 23ca8e3..9303c1f 100644 --- a/blueprints/03-workers.yaml +++ b/blueprints/03-workers.yaml @@ -61,7 +61,18 @@ ignore: - .next - .wrangler - .open-next -- wrangler.jsonc +- apps/admin-worker/wrangler.jsonc +- apps/api-edge/wrangler.jsonc +- apps/billing-worker/wrangler.jsonc +- apps/config-worker/wrangler.jsonc +- apps/events-worker/wrangler.jsonc +- apps/identity-worker/wrangler.jsonc +- apps/integrations-worker/wrangler.jsonc +- apps/membership-worker/wrangler.jsonc +- apps/metering-worker/wrangler.jsonc +- apps/notifications-worker/wrangler.jsonc +- apps/projects-worker/wrangler.jsonc +- apps/webhooks-worker/wrangler.jsonc - '*.tsbuildinfo' modules: - name: admin-worker @@ -225,11 +236,6 @@ modules: to: tests/projects-worker dependsOn: - projects-worker -- name: secrets-sync-tests - mode: copy - source: baseline - from: tests/secrets-sync - to: tests/secrets-sync - name: webhooks-worker mode: copy source: baseline @@ -270,6 +276,5 @@ phases: - policy-worker-tests - projects-worker - projects-worker-tests - - secrets-sync-tests - webhooks-worker - webhooks-worker-tests diff --git a/blueprints/04-edge.yaml b/blueprints/04-edge.yaml index 9f92833..cb185c4 100644 --- a/blueprints/04-edge.yaml +++ b/blueprints/04-edge.yaml @@ -61,7 +61,18 @@ ignore: - .next - .wrangler - .open-next -- wrangler.jsonc +- apps/admin-worker/wrangler.jsonc +- apps/api-edge/wrangler.jsonc +- apps/billing-worker/wrangler.jsonc +- apps/config-worker/wrangler.jsonc +- apps/events-worker/wrangler.jsonc +- apps/identity-worker/wrangler.jsonc +- apps/integrations-worker/wrangler.jsonc +- apps/membership-worker/wrangler.jsonc +- apps/metering-worker/wrangler.jsonc +- apps/notifications-worker/wrangler.jsonc +- apps/projects-worker/wrangler.jsonc +- apps/webhooks-worker/wrangler.jsonc - '*.tsbuildinfo' modules: - name: api-edge diff --git a/blueprints/05-console.yaml b/blueprints/05-console.yaml index 89acab5..75f2157 100644 --- a/blueprints/05-console.yaml +++ b/blueprints/05-console.yaml @@ -61,7 +61,18 @@ ignore: - .next - .wrangler - .open-next -- wrangler.jsonc +- apps/admin-worker/wrangler.jsonc +- apps/api-edge/wrangler.jsonc +- apps/billing-worker/wrangler.jsonc +- apps/config-worker/wrangler.jsonc +- apps/events-worker/wrangler.jsonc +- apps/identity-worker/wrangler.jsonc +- apps/integrations-worker/wrangler.jsonc +- apps/membership-worker/wrangler.jsonc +- apps/metering-worker/wrangler.jsonc +- apps/notifications-worker/wrangler.jsonc +- apps/projects-worker/wrangler.jsonc +- apps/webhooks-worker/wrangler.jsonc - '*.tsbuildinfo' modules: - name: web-console-next diff --git a/blueprints/06-domain.yaml b/blueprints/06-domain.yaml index ba00b2b..3440799 100644 --- a/blueprints/06-domain.yaml +++ b/blueprints/06-domain.yaml @@ -61,7 +61,18 @@ ignore: - .next - .wrangler - .open-next -- wrangler.jsonc +- apps/admin-worker/wrangler.jsonc +- apps/api-edge/wrangler.jsonc +- apps/billing-worker/wrangler.jsonc +- apps/config-worker/wrangler.jsonc +- apps/events-worker/wrangler.jsonc +- apps/identity-worker/wrangler.jsonc +- apps/integrations-worker/wrangler.jsonc +- apps/membership-worker/wrangler.jsonc +- apps/metering-worker/wrangler.jsonc +- apps/notifications-worker/wrangler.jsonc +- apps/projects-worker/wrangler.jsonc +- apps/webhooks-worker/wrangler.jsonc - '*.tsbuildinfo' modules: - name: cloudflare-domain diff --git a/blueprints/07-workspace.yaml b/blueprints/07-workspace.yaml index 04364a6..f92bc0e 100644 --- a/blueprints/07-workspace.yaml +++ b/blueprints/07-workspace.yaml @@ -61,7 +61,18 @@ ignore: - .next - .wrangler - .open-next -- wrangler.jsonc +- apps/admin-worker/wrangler.jsonc +- apps/api-edge/wrangler.jsonc +- apps/billing-worker/wrangler.jsonc +- apps/config-worker/wrangler.jsonc +- apps/events-worker/wrangler.jsonc +- apps/identity-worker/wrangler.jsonc +- apps/integrations-worker/wrangler.jsonc +- apps/membership-worker/wrangler.jsonc +- apps/metering-worker/wrangler.jsonc +- apps/notifications-worker/wrangler.jsonc +- apps/projects-worker/wrangler.jsonc +- apps/webhooks-worker/wrangler.jsonc - '*.tsbuildinfo' modules: - name: agents @@ -74,6 +85,11 @@ modules: source: baseline from: ai to: ai +- name: flows + mode: copy + source: baseline + from: flows + to: flows - name: github-workflows mode: copy source: baseline @@ -154,6 +170,7 @@ phases: modules: - agents - ai-context + - flows - github-workflows - rebrand-values - root-forking diff --git a/flows/README.md b/flows/README.md new file mode 100644 index 0000000..092c07d --- /dev/null +++ b/flows/README.md @@ -0,0 +1,78 @@ +# Bootstrapping this product + +This product boots **entirely against its Orun Cloud workspace** (the +`workspace:` in `intent.yaml`; a fork carries provenance in +`.orun/provenance.*.lock` and `ai/context/fork-from-baseline.md`) — CI holds +no provider credential; every secret is brokered from the workspace's +integrations at run time. Every command below takes the workspace org slug; +the examples write ``. + +## One-time operator prerequisites + +The workflow preflights each of these and stops with instructions if missing: + +1. **CLI login** — `orun auth login --device`, approve the code at + `https://app.orun.dev/cli/device` in a browser session that belongs to the + workspace owner. (When the operator is an agent, the Claude Chrome + extension can fill and submit the approval form — the CLI itself cannot.) +2. **Integrations** — connect **Cloudflare** (paste an Account API token per + the in-console recipe; the same account may already back other workspaces + — that is supported) and **Supabase** (OAuth; pick the organization that + should own this product's projects) in the console → Integrations. +3. **Repo allow-list** — the workspace must trust this repo's CI identity + (OIDC). `orun cloud check --org ` verifies; granting is done in the + console (Git Repos) — the CLI cannot grant it. `orun cloud link` must have + been run from a clone with a GitHub remote (it records the numeric repo id + the OIDC exchange resolves by). +4. **AWS (org-owned, via `aws-admin`)** — the per-repo GitHub-OIDC roles + (`-github-sourceplane--plan`) and the Terraform state prefix. + Without them the `bootstrap` Terraform batch fails at its first plan. + +## The workflow + +```bash +orun workflow run flows/bootstrap-flow.yaml --set org= +``` + +- **preflight** — auth, allow-list, integrations present. +- **create-secrets** — five project-rung secrets from the integrations + (workers-deploy / hyperdrive-edit / account-id / management-access / + org-id). Brokered and fact templates only: no value is ever typed or seen. +- **batches** — every deployable component starts *parked* + (`subscribe.environments: []`, originals stashed in + `flows/subscriptions/`). Each batch step un-parks a group, opens a PR, + requires its checks green, merges, then requires the merge's main + convergence run (the deploy + per-worker smoke) green before the next + batch starts: + + | # | batch | components | + |---|---|---| + | 1 | infra-foundation | cloudflare-kv | + | 2 | data-a | supabase (its secretOutputs lease-publish the DB creds the next batch reads) | + | 3 | data-b | db-migrate, cloudflare-hyperdrive | + | 4 | workers-a | policy, membership, events, projects | + | 5 | workers-b | identity, config, webhooks, notifications, metering, admin | + | 6 | workers-c | billing, integrations | + | 7 | edge | api-edge | + | 8 | console | web-console-next | + + `cloudflare-domain` stays parked until the `lumen.app` zone exists in the + Cloudflare account. +- **verify-live** — curls the deployed api-edge + console endpoints on both + environments and fails on any dead endpoint. + +Every step is also runnable by hand (`flows/batch.sh `, +`flows/create-secrets.sh `), and a failed batch resumes by re-running the +workflow — completed batches are no-ops (their components are already +un-parked and deployed). `create-secrets` also self-heals: a key whose +integration connection was revoked (health `orphaned`) is revoked and +recreated against the current ACTIVE connection. + +## Runtime worker secrets (wire-now-seed-later) + +Workers declare their runtime keys in `optionalSecretEnv` + `runtimeSecrets` +(OAuth client secrets, Polar keys, `SECRET_ENCRYPTION_KEY`, …). They are +**inert until seeded**: add a value in the console (Secrets → New secret) or +via `orun secrets set --org --env ` and the next deploy pushes +it to the worker via the stack's `secrets-live` step. No repo change per +secret. diff --git a/flows/batch.sh b/flows/batch.sh new file mode 100755 index 0000000..c1ca629 --- /dev/null +++ b/flows/batch.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# One bootstrap batch: un-park the named components, PR the change, wait for +# checks, merge, then wait for the main convergence run that DEPLOYS the batch +# and require it green. Driven by flows/bootstrap-flow.yaml, usable by hand: +# +# flows/batch.sh [component…] +# +# Requires: gh authenticated for this repo; a clean tree on main. +set -euo pipefail + +batch="${1:?usage: batch.sh …}" +shift +[ "$#" -gt 0 ] || { echo "batch.sh: name at least one component" >&2; exit 2; } + +git checkout main -q +git pull -q +git checkout -qb "bootstrap/${batch}" + +node flows/park.mjs unpark "$@" + +git add -A +git commit -qm "bootstrap(${batch}): enable ${*} + +Un-parks this batch's environment subscriptions; the merge's main +convergence deploys exactly these components, in dependency order." +git push -qu origin "bootstrap/${batch}" + +pr_url="$(gh pr create --title "bootstrap(${batch}): enable ${*}" \ + --body "Bootstrap batch \`${batch}\`: un-parks ${*}. Merging deploys this batch via the main convergence run." )" +echo "PR: ${pr_url}" + +# Wait for PR checks (verify lanes for the newly-enabled components). +until state="$(gh pr checks "${pr_url}" --json bucket \ + --jq 'if length == 0 then "pending" elif all(.[].bucket; . != "pending") then "done" else "pending" end' 2>/dev/null)" \ + && [ "${state}" = "done" ]; do + sleep 30 +done +fails="$(gh pr checks "${pr_url}" --json bucket --jq '[.[]|select(.bucket=="fail")]|length')" +if [ "${fails}" != "0" ]; then + echo "batch ${batch}: ${fails} check(s) failed on the PR — fix before merging" >&2 + gh pr checks "${pr_url}" --json name,bucket --jq '.[]|select(.bucket=="fail")|.name' >&2 + exit 1 +fi + +gh pr merge "${pr_url}" --squash --delete-branch +git checkout main -q +git pull -q + +# The merge's main run is the DEPLOY — wait for it and require green. +sleep 30 +run_id="$(gh run list --branch main --limit 1 --json databaseId --jq '.[0].databaseId')" +echo "convergence run: ${run_id}" +until st="$(gh run view "${run_id}" --json status --jq .status 2>/dev/null)" && [ "${st}" = "completed" ]; do + sleep 40 +done +conclusion="$(gh run view "${run_id}" --json conclusion --jq .conclusion)" +if [ "${conclusion}" != "success" ]; then + echo "batch ${batch}: main convergence ${conclusion}" >&2 + gh run view "${run_id}" --json jobs --jq '.jobs[]|select(.conclusion=="failure")|.name' >&2 + exit 1 +fi +echo "✓ batch ${batch} deployed and verified (run ${run_id})" diff --git a/flows/bootstrap-flow.yaml b/flows/bootstrap-flow.yaml new file mode 100644 index 0000000..22beff3 --- /dev/null +++ b/flows/bootstrap-flow.yaml @@ -0,0 +1,122 @@ +apiVersion: orun.dev/v1 +kind: Workflow +metadata: + name: bootstrap-flow +# Full first-boot of this product against its Orun Cloud workspace (the +# `workspace:` in intent.yaml): verify CLI auth, repo allow-listing, and provider +# integrations; create the five provider secrets from those integrations +# (brokered — no value is ever typed or seen); then deploy the platform in +# dependency-ordered batches, one PR each, requiring the PR checks AND the +# merge's main convergence run green before the next batch starts. +# +# Run it from the repo root: orun workflow run flows/bootstrap-flow.yaml +# Operator prerequisites (once, documented in flows/README.md): +# - orun auth login --device (approve at app.orun.dev/cli/device; +# a browser session in the workspace — +# the Chrome extension works when the +# operator is an agent) +# - Cloudflare + Supabase connected in the workspace (console → Integrations) +# - This repo allow-listed for CI OIDC (console → Git Repos; `orun cloud +# check` verifies — the CLI cannot grant it, the console can) +inputs: + org: + type: string + default: "lumen" + description: >- + Workspace slug/id the secrets and runs resolve against. A fork MUST pass + its own workspace org (--set org=); the baseline default fails + loudly at preflight for any operator without access to it. +steps: + - name: preflight + run: + - /bin/sh + - -c + - | + set -e + echo "── auth" + orun auth status | grep -q "User:" || { + echo "not logged in: run \`orun auth login --device\` and approve at https://app.orun.dev/cli/device (browser session in the workspace; the Chrome extension can approve it for agent operators)" >&2 + exit 1 + } + echo "── repo allow-list" + orun cloud check --org "{{ inputs.org }}" || { + echo "repo not allow-listed for {{ inputs.org }}: allow it in the console (Git Repos) — the CLI cannot grant this" >&2 + exit 1 + } + echo "── integrations (ACTIVE connections required)" + list="$(orun integrations list --org "{{ inputs.org }}" --json)" + active() { + printf '%s' "$list" | python3 -c "import json,sys; rows=json.load(sys.stdin); sys.exit(0 if any(r.get('provider')=='$1' and r.get('status')=='active' for r in rows) else 1)" + } + active cloudflare || { echo "no ACTIVE Cloudflare connection in {{ inputs.org }}: console → Integrations → Cloudflare → Connect (paste an Account API token per the in-console recipe)" >&2; exit 1; } + active supabase || { echo "no ACTIVE Supabase connection in {{ inputs.org }}: console → Integrations → Supabase → Connect (OAuth; pick the organization that should own this product's projects)" >&2; exit 1; } + timeout: 2m + + - name: create-secrets + needs: [preflight] + run: ["/bin/sh", "-c", "flows/create-secrets.sh {{ inputs.org }}"] + timeout: 5m + + # ── Deploy batches (dependency order; each waits for PR checks AND the + # merge's main convergence run — the deploy — to be green). ── + - name: batch-infra-foundation + needs: [create-secrets] + run: ["/bin/sh", "-c", "flows/batch.sh infra-foundation cloudflare-kv"] + timeout: 45m + # Split data batches: supabase must APPLY (its secretOutputs lease-publish + # SUPABASE_PROJECT_REF/DB_PASSWORD/DB_URL) before db-migrate and hyperdrive + # can even PLAN — their secretEnv refs resolve at job start. + - name: batch-data-a + needs: [batch-infra-foundation] + run: ["/bin/sh", "-c", "flows/batch.sh data-a supabase"] + timeout: 45m + - name: batch-data-b + needs: [batch-data-a] + run: ["/bin/sh", "-c", "flows/batch.sh data-b db-migrate cloudflare-hyperdrive"] + timeout: 60m + - name: batch-workers-a + needs: [batch-data-b] + run: ["/bin/sh", "-c", "flows/batch.sh workers-a policy-worker membership-worker events-worker projects-worker"] + timeout: 60m + - name: batch-workers-b + needs: [batch-workers-a] + run: ["/bin/sh", "-c", "flows/batch.sh workers-b identity-worker config-worker webhooks-worker notifications-worker metering-worker admin-worker"] + timeout: 90m + - name: batch-workers-c + needs: [batch-workers-b] + run: ["/bin/sh", "-c", "flows/batch.sh workers-c billing-worker integrations-worker"] + timeout: 60m + - name: batch-edge + needs: [batch-workers-c] + run: ["/bin/sh", "-c", "flows/batch.sh edge api-edge"] + timeout: 45m + - name: batch-console + needs: [batch-edge] + run: ["/bin/sh", "-c", "flows/batch.sh console web-console-next"] + timeout: 45m + # cloudflare-domain stays parked: its zone (lumen.app) must exist in the + # Cloudflare account first — see the restore note in its component.yaml. + + - name: verify-live + needs: [batch-console] + run: + - /bin/sh + - -c + - | + set -e + ok=0; fail=0 + for url in \ + https://lumen-api-edge-stage.rahulvarghesepullely.workers.dev/health \ + https://lumen-api-edge-prod.rahulvarghesepullely.workers.dev/health \ + https://lumen-web-console-next-stage.rahulvarghesepullely.workers.dev \ + https://lumen-web-console-next-prod.rahulvarghesepullely.workers.dev; do + code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 "$url" || echo 000)" + if [ "$code" -ge 200 ] && [ "$code" -lt 500 ]; then + echo "✓ $url → $code"; ok=$((ok+1)) + else + echo "✕ $url → $code" >&2; fail=$((fail+1)) + fi + done + [ "$fail" -eq 0 ] || { echo "$fail endpoint(s) unhealthy" >&2; exit 1; } + echo "bootstrap complete: $ok live endpoints" + timeout: 5m diff --git a/flows/create-secrets.sh b/flows/create-secrets.sh new file mode 100755 index 0000000..5b7a7bf --- /dev/null +++ b/flows/create-secrets.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# Create this product's five provider secrets from the workspace's +# integrations — brokered/fact templates only, so NO credential value is ever +# typed, seen, or stored here. Idempotent: keys that already exist are kept. +# +# flows/create-secrets.sh +# +# | Key | Provider | Template | What resolves | +# |-----------------------------|------------|-------------------|---------------| +# | CLOUDFLARE_API_TOKEN | cloudflare | workers-deploy | fresh per-run worker-deploy token | +# | CLOUDFLARE_HYPERDRIVE_TOKEN | cloudflare | hyperdrive-edit | fresh per-run Hyperdrive token | +# | CLOUDFLARE_ACCOUNT_ID | cloudflare | account-id | connection fact (non-secret) | +# | SUPABASE_ACCESS_TOKEN | supabase | management-access | fresh per-run management token | +# | SUPABASE_ORG_ID | supabase | org-id | connection fact (non-secret) | +set -euo pipefail + +org="${1:?usage: create-secrets.sh }" + +connections="$(orun integrations list --org "$org" --json)" +conn_for() { + # First ACTIVE connection id for the provider. + printf '%s' "$connections" | python3 -c " +import json,sys +rows=json.load(sys.stdin) +for r in rows: + if r.get('provider')=='$1' and r.get('status')=='active': + print(r['id']); break +" +} + +cf="$(conn_for cloudflare)" +sb="$(conn_for supabase)" +[ -n "$cf" ] || { echo "no active cloudflare connection in $org" >&2; exit 1; } +[ -n "$sb" ] || { echo "no active supabase connection in $org" >&2; exit 1; } + +existing="$(orun secrets list --org "$org" --project --json 2>/dev/null || echo '[]')" + +# healthy KEY → 0 when the key exists AND is not orphaned (its broker +# connection can still mint). An orphaned key (bound to a revoked/replaced +# connection) is revoked and recreated against the CURRENT connection. +state() { + printf '%s' "$existing" | python3 -c " +import json,sys +rows=json.load(sys.stdin) +for r in rows: + if r.get('secretKey')=='$1' or r.get('key')=='$1': + print('orphaned' if (r.get('health')=='orphaned' or r.get('orphaned')) else 'ok'); break +else: + print('absent') +" +} + +create() { # key provider connection template + case "$(state "$1")" in + ok) echo "✓ $1 exists and is healthy — kept"; return ;; + orphaned) + echo "↻ $1 is orphaned (its connection was revoked) — recreating against the current connection" + orun secrets revoke "$1" --org "$org" --project --yes 2>/dev/null || orun secrets revoke "$1" --org "$org" --project 2>/dev/null || true + ;; + esac + orun integrations "$2" secret create "$1" --org "$org" --connection "$3" --template "$4" --project + echo "✓ $1 created ($2/$4)" +} + +create CLOUDFLARE_API_TOKEN cloudflare "$cf" workers-deploy +create CLOUDFLARE_HYPERDRIVE_TOKEN cloudflare "$cf" hyperdrive-edit +create CLOUDFLARE_ACCOUNT_ID cloudflare "$cf" account-id +create SUPABASE_ACCESS_TOKEN supabase "$sb" management-access +create SUPABASE_ORG_ID supabase "$sb" org-id + +echo "secrets ready:" +orun secrets list --org "$org" --project diff --git a/flows/park.mjs b/flows/park.mjs new file mode 100644 index 0000000..c91bd3f --- /dev/null +++ b/flows/park.mjs @@ -0,0 +1,121 @@ +#!/usr/bin/env node +// Park / unpark deployable components (zero-dependency). +// +// The bootstrap model: the FULL tree lands on main in one push, but every +// component that would DEPLOY on a main push starts "parked" — its +// `subscribe.environments` emptied, the original block stashed under +// flows/subscriptions/.yaml — so the first push runs only the offline +// verify fleet. Each bootstrap batch PR then UN-parks its components, and the +// merge's main convergence deploys exactly that batch, in order. (The same +// mechanism the baseline uses to park cloudflare-domain.) +// +// Usage: +// node flows/park.mjs park # park every deployable component +// node flows/park.mjs unpark … # restore named components +// node flows/park.mjs status # list parked / live +// +// Verify-only components (turbo-package builds and tests) are never parked — +// they carry no deploy profile, and their lanes are the fleet smoke-check. + +import * as fs from "node:fs"; +import * as path from "node:path"; + +const STASH_DIR = "flows/subscriptions"; +// Component types whose main-push profileRules deploy/apply/migrate. +const DEPLOYABLE_TYPES = new Set([ + "cloudflare-worker-turbo", + "cloudflare-workers-assets-turbo", + "terraform", + "db-migrate", +]); + +function componentFiles() { + const roots = ["apps", "infra", "packages", "tests"]; + const out = []; + const walk = (dir) => { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, entry.name); + if (entry.isDirectory() && entry.name !== "node_modules") walk(p); + else if (entry.name === "component.yaml") out.push(p); + } + }; + for (const r of roots) if (fs.existsSync(r)) walk(r); + return out.sort(); +} + +function readMeta(file) { + const s = fs.readFileSync(file, "utf8"); + const name = (s.match(/^\s{2}name:\s*(\S+)/m) ?? [])[1]; + const type = (s.match(/^\s{2}type:\s*(\S+)/m) ?? [])[1]; + return { s, name, type }; +} + +// The subscribe block: from the ` subscribe:` line to the next top-level +// spec key (2-space indent) or EOF/comment-tail. +function findSubscribe(s) { + const start = s.search(/^ subscribe:\s*$/m); + if (start === -1) return null; + const rest = s.slice(start); + const m = rest.slice(1).search(/^ [a-zA-Z]/m); + const end = m === -1 ? s.length : start + 1 + m; + return { start, end, block: s.slice(start, end) }; +} + +const mode = process.argv[2]; +if (mode === "park") { + fs.mkdirSync(STASH_DIR, { recursive: true }); + let parked = 0; + for (const file of componentFiles()) { + const { s, name, type } = readMeta(file); + if (!DEPLOYABLE_TYPES.has(type)) continue; + const sub = findSubscribe(s); + if (!sub || /environments:\s*\[\]/.test(sub.block)) continue; + fs.writeFileSync(path.join(STASH_DIR, `${name}.yaml`), sub.block); + const replacement = + " # PARKED by flows/park.mjs — restored per bootstrap batch\n" + + " # (flows/bootstrap-flow.yaml); original block in\n" + + ` # ${STASH_DIR}/${name}.yaml\n` + + " subscribe:\n environments: []\n"; + fs.writeFileSync(file, s.slice(0, sub.start) + replacement + s.slice(sub.end)); + parked++; + console.log(`parked ${name} (${file})`); + } + console.log(`${parked} component(s) parked`); +} else if (mode === "unpark") { + const names = process.argv.slice(3); + if (names.length === 0) { + console.error("unpark: name at least one component"); + process.exit(2); + } + for (const nm of names) { + const stash = path.join(STASH_DIR, `${nm}.yaml`); + if (!fs.existsSync(stash)) { + console.error(`unpark: no stashed subscription for ${nm}`); + process.exit(1); + } + const file = componentFiles().find((f) => readMeta(f).name === nm); + if (!file) { + console.error(`unpark: no component.yaml with name ${nm}`); + process.exit(1); + } + const { s } = readMeta(file); + const sub = findSubscribe(s); + if (!sub) { + console.error(`unpark: ${nm} has no subscribe block`); + process.exit(1); + } + fs.writeFileSync(file, s.slice(0, sub.start) + fs.readFileSync(stash, "utf8") + s.slice(sub.end)); + fs.unlinkSync(stash); + console.log(`unparked ${nm}`); + } +} else if (mode === "status") { + for (const file of componentFiles()) { + const { s, name, type } = readMeta(file); + if (!DEPLOYABLE_TYPES.has(type)) continue; + const parked = fs.existsSync(path.join(STASH_DIR, `${name}.yaml`)); + console.log(`${parked ? "parked" : "live "} ${name}`); + } +} else { + console.error("usage: park.mjs park | unpark … | status"); + process.exit(2); +} diff --git a/infra/db-migrate/component.yaml b/infra/db-migrate/component.yaml index c5005f1..963cb63 100644 --- a/infra/db-migrate/component.yaml +++ b/infra/db-migrate/component.yaml @@ -17,7 +17,8 @@ spec: dependsOn: - component: db - # Migrations read the Supabase connection from the secret `supabase` writes. + # Migrations read the Supabase connection from the orun secrets the + # `supabase` component lease-publishes post-apply. - component: supabase path: packages/db/src/migrations @@ -25,12 +26,20 @@ spec: parameters: nodeVersion: "20" pnpmVersion: "10.12.1" - awsRegion: us-east-1 - awsAccountId: "306024784101" - secretName: sourceplane/lumen/supabase owner: sourceplane repo: lumen + # The migration runner's Management-API token (required in apply mode) + # resolves from orun secrets — minted fresh per run from the Supabase + # integration (management-access template). Replaces the ambient + # SUPABASE_ACCESS_TOKEN CI value. + secretEnv: + SUPABASE_ACCESS_TOKEN: "secret://lumen/lumen/{{ .environment }}/SUPABASE_ACCESS_TOKEN" + # The runner's DB identity (de-AWS — replaces the Secrets Manager read). + SUPABASE_PROJECT_REF: "secret://lumen/lumen/{{ .environment }}/SUPABASE_PROJECT_REF" + SUPABASE_DB_PASSWORD: "secret://lumen/lumen/{{ .environment }}/SUPABASE_DB_PASSWORD" + SUPABASE_DB_URL: "secret://lumen/lumen/{{ .environment }}/SUPABASE_DB_URL" + subscribe: environments: - name: stage diff --git a/infra/terraform/bootstrap/README.md b/infra/terraform/bootstrap/README.md deleted file mode 100644 index f01970a..0000000 --- a/infra/terraform/bootstrap/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# Bootstrap Terraform Component - -Minimal Terraform component that proves the AWS S3 backend and Secrets Manager -access path for `lumen` Terraform components. - -## Purpose - -- Validates that the OIDC-assumed IAM roles from `aws-admin` (Task 0004) work - correctly for this repository. -- Confirms S3 state bucket read/write access. -- Establishes the pattern for future Terraform components (e.g., Supabase in - Task 0006). - -## Backend - -| Setting | Value | -| -------------------- | -------------------------------------------------------- | -| Bucket | `sourceplane-` | -| Key | `lumen/bootstrap/terraform.tfstate` | -| workspace_key_prefix | `env` | -| encrypt | `true` | -| use_lockfile | `true` | -| Region | `us-east-1` | - -Effective state path: `env//lumen/bootstrap/terraform.tfstate` - -## AWS Roles - -Credential assumption is handled by the Orun Terraform composition -(the `terraform` composition in the stack-tectonic catalog) via `aws-actions/configure-aws-credentials@v4`. - -The account ID and `owner`/`repo` are not hard-coded in the composition: the -role ARN is rendered from `{{.parameters.awsAccountId}}` (set in `intent.yaml` -under `parameterDefaults.terraform`, and in `infra/db-migrate/component.yaml` -for the migration runner) plus `{{.parameters.owner}}`/`{{.parameters.repo}}`. - -| Profile | Role | -| --------- | --------------------------------------------------------------------------------- | -| plan-only | `arn:aws:iam:::role/-github---plan` | -| apply | `arn:aws:iam:::role/-github---production-deploy` | - -> **Note:** The deploy role requires GitHub environment `production` in the -> workflow. Apply behavior is gated on this environment being configured in the -> repository settings. - -## Secrets Manager - -The deploy role has write access to secrets under the prefix: -`sourceplane/lumen/*` - -Smoke verification uses `dev` only to avoid production artifacts. diff --git a/infra/terraform/bootstrap/component.yaml b/infra/terraform/bootstrap/component.yaml deleted file mode 100644 index 7900a25..0000000 --- a/infra/terraform/bootstrap/component.yaml +++ /dev/null @@ -1,51 +0,0 @@ -apiVersion: sourceplane.io/v1 -kind: Component - -metadata: - name: bootstrap - description: Proves S3 backend and Secrets Manager access for lumen Terraform components - labels: - domain: infra - scope: bootstrap - -spec: - type: terraform - lifecycle: production - owner: platform - domain: infra - - parameters: - orgName: sourceplane - stackName: bootstrap - terraformDir: terraform - terraformVersion: "1.15.3" - - env: - AWS_EC2_METADATA_DISABLED: "true" - - subscribe: - environments: - - name: dev - profile: plan-only - profileRules: - - profile: apply - when: - triggerRef: github-push-main - - profile: local - when: - triggerRef: local-development - - - name: stage - profile: plan-only - profileRules: - - profile: apply - when: - triggerRef: github-push-main - - - name: prod - profile: plan-only - profileRules: - - profile: apply - when: - triggerRef: github-push-main -# ci: trigger convergence — first-boot infra bring-up (bootstrap access check) diff --git a/infra/terraform/bootstrap/terraform/.terraform.lock.hcl b/infra/terraform/bootstrap/terraform/.terraform.lock.hcl deleted file mode 100644 index cdc1668..0000000 --- a/infra/terraform/bootstrap/terraform/.terraform.lock.hcl +++ /dev/null @@ -1,25 +0,0 @@ -# This file is maintained automatically by "terraform init". -# Manual edits may be lost in future updates. - -provider "registry.terraform.io/hashicorp/aws" { - version = "5.100.0" - constraints = "~> 5.0" - hashes = [ - "h1:Ijt7pOlB7Tr7maGQIqtsLFbl7pSMIj06TVdkoSBcYOw=", - "zh:054b8dd49f0549c9a7cc27d159e45327b7b65cf404da5e5a20da154b90b8a644", - "zh:0b97bf8d5e03d15d83cc40b0530a1f84b459354939ba6f135a0086c20ebbe6b2", - "zh:1589a2266af699cbd5d80737a0fe02e54ec9cf2ca54e7e00ac51c7359056f274", - "zh:6330766f1d85f01ae6ea90d1b214b8b74cc8c1badc4696b165b36ddd4cc15f7b", - "zh:7c8c2e30d8e55291b86fcb64bdf6c25489d538688545eb48fd74ad622e5d3862", - "zh:99b1003bd9bd32ee323544da897148f46a527f622dc3971af63ea3e251596342", - "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", - "zh:9f8b909d3ec50ade83c8062290378b1ec553edef6a447c56dadc01a99f4eaa93", - "zh:aaef921ff9aabaf8b1869a86d692ebd24fbd4e12c21205034bb679b9caf883a2", - "zh:ac882313207aba00dd5a76dbd572a0ddc818bb9cbf5c9d61b28fe30efaec951e", - "zh:bb64e8aff37becab373a1a0cc1080990785304141af42ed6aa3dd4913b000421", - "zh:dfe495f6621df5540d9c92ad40b8067376350b005c637ea6efac5dc15028add4", - "zh:f0ddf0eaf052766cfe09dea8200a946519f653c384ab4336e2a4a64fdd6310e9", - "zh:f1b7e684f4c7ae1eed272b6de7d2049bb87a0275cb04dbb7cda6636f600699c9", - "zh:ff461571e3f233699bf690db319dfe46aec75e58726636a0d97dd9ac6e32fb70", - ] -} diff --git a/infra/terraform/bootstrap/terraform/main.tf b/infra/terraform/bootstrap/terraform/main.tf deleted file mode 100644 index c8481d8..0000000 --- a/infra/terraform/bootstrap/terraform/main.tf +++ /dev/null @@ -1,111 +0,0 @@ -terraform { - required_version = ">= 1.15.0" - - backend "s3" { - encrypt = true - use_lockfile = true - workspace_key_prefix = "env" - } - - required_providers { - aws = { - source = "hashicorp/aws" - version = "~> 5.0" - } - } -} - -provider "aws" { - region = var.awsRegion - - default_tags { - tags = { - ManagedBy = "terraform" - Repository = "${var.owner}/${var.repo}" - Component = var.component - Environment = var.environment - } - } -} - -# --- Variables --- - -variable "awsRegion" { - type = string - default = "us-east-1" -} - -variable "orgName" { - type = string - default = "sourceplane" -} - -variable "owner" { - type = string - default = "sourceplane" -} - -variable "repo" { - type = string - default = "lumen" -} - -variable "namespace" { - type = string - default = "sourceplane" -} - -variable "namespacePrefix" { - type = string - default = "" -} - -variable "lane" { - type = string - default = "verify" -} - -variable "environment" { - type = string - default = "dev" -} - -variable "component" { - type = string - default = "bootstrap" -} - -variable "stackName" { - type = string - default = "bootstrap" -} - -variable "terraformDir" { - type = string - default = "terraform" -} - -variable "terraformVersion" { - type = string - default = "1.15.3" -} - -# --- Data sources to verify access --- - -data "aws_caller_identity" "current" {} - -data "aws_s3_bucket" "state" { - bucket = "${var.orgName}-${var.environment}" -} - -# --- Outputs --- - -output "account_id" { - description = "AWS account ID confirming role assumption" - value = data.aws_caller_identity.current.account_id -} - -output "state_bucket_arn" { - description = "ARN of the S3 state bucket confirming access" - value = data.aws_s3_bucket.state.arn -} diff --git a/infra/terraform/cloudflare-domain/component.yaml b/infra/terraform/cloudflare-domain/component.yaml index b60145c..991aac7 100644 --- a/infra/terraform/cloudflare-domain/component.yaml +++ b/infra/terraform/cloudflare-domain/component.yaml @@ -36,9 +36,6 @@ spec: # variable itself already defaults to "" in # `terraform/variables.tf`, so absence here is safe for dev. - env: - AWS_EC2_METADATA_DISABLED: "true" - dependsOn: - component: web-console-next diff --git a/infra/terraform/cloudflare-domain/terraform/.terraform.lock.hcl b/infra/terraform/cloudflare-domain/terraform/.terraform.lock.hcl index 813b92d..68087c3 100644 --- a/infra/terraform/cloudflare-domain/terraform/.terraform.lock.hcl +++ b/infra/terraform/cloudflare-domain/terraform/.terraform.lock.hcl @@ -24,25 +24,3 @@ provider "registry.terraform.io/cloudflare/cloudflare" { ] } -provider "registry.terraform.io/hashicorp/aws" { - version = "5.100.0" - constraints = "~> 5.0" - hashes = [ - "h1:Ijt7pOlB7Tr7maGQIqtsLFbl7pSMIj06TVdkoSBcYOw=", - "zh:054b8dd49f0549c9a7cc27d159e45327b7b65cf404da5e5a20da154b90b8a644", - "zh:0b97bf8d5e03d15d83cc40b0530a1f84b459354939ba6f135a0086c20ebbe6b2", - "zh:1589a2266af699cbd5d80737a0fe02e54ec9cf2ca54e7e00ac51c7359056f274", - "zh:6330766f1d85f01ae6ea90d1b214b8b74cc8c1badc4696b165b36ddd4cc15f7b", - "zh:7c8c2e30d8e55291b86fcb64bdf6c25489d538688545eb48fd74ad622e5d3862", - "zh:99b1003bd9bd32ee323544da897148f46a527f622dc3971af63ea3e251596342", - "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", - "zh:9f8b909d3ec50ade83c8062290378b1ec553edef6a447c56dadc01a99f4eaa93", - "zh:aaef921ff9aabaf8b1869a86d692ebd24fbd4e12c21205034bb679b9caf883a2", - "zh:ac882313207aba00dd5a76dbd572a0ddc818bb9cbf5c9d61b28fe30efaec951e", - "zh:bb64e8aff37becab373a1a0cc1080990785304141af42ed6aa3dd4913b000421", - "zh:dfe495f6621df5540d9c92ad40b8067376350b005c637ea6efac5dc15028add4", - "zh:f0ddf0eaf052766cfe09dea8200a946519f653c384ab4336e2a4a64fdd6310e9", - "zh:f1b7e684f4c7ae1eed272b6de7d2049bb87a0275cb04dbb7cda6636f600699c9", - "zh:ff461571e3f233699bf690db319dfe46aec75e58726636a0d97dd9ac6e32fb70", - ] -} diff --git a/infra/terraform/cloudflare-domain/terraform/main.tf b/infra/terraform/cloudflare-domain/terraform/main.tf index 98dd5b9..90e4475 100644 --- a/infra/terraform/cloudflare-domain/terraform/main.tf +++ b/infra/terraform/cloudflare-domain/terraform/main.tf @@ -1,17 +1,11 @@ terraform { required_version = ">= 1.15.0" - backend "s3" { - encrypt = true - use_lockfile = true - workspace_key_prefix = "env" - } + # State lives on the platform (SB1): the runner exports TF_HTTP_* per job, so + # this block stays empty — no S3 bucket, no AWS role, no workspaces. + backend "http" {} required_providers { - aws = { - source = "hashicorp/aws" - version = "~> 5.0" - } cloudflare = { source = "cloudflare/cloudflare" version = "~> 4.52" @@ -21,19 +15,6 @@ terraform { # --- Providers --- -provider "aws" { - region = var.awsRegion - - default_tags { - tags = { - ManagedBy = "terraform" - Repository = "${var.owner}/${var.repo}" - Component = var.component - Environment = var.environment - } - } -} - # Authenticates via the CLOUDFLARE_API_TOKEN env var (provider-native): the # token is an orun-managed secret resolved into the job env at run time, so it # never transits Terraform variables. @@ -41,11 +22,6 @@ provider "cloudflare" {} # --- Variables (standard Orun parameters) --- -variable "awsRegion" { - type = string - default = "us-east-1" -} - variable "cloudflare_account_id" { type = string sensitive = true diff --git a/infra/terraform/cloudflare-hyperdrive/component.yaml b/infra/terraform/cloudflare-hyperdrive/component.yaml index c6a3f84..0e723de 100644 --- a/infra/terraform/cloudflare-hyperdrive/component.yaml +++ b/infra/terraform/cloudflare-hyperdrive/component.yaml @@ -24,10 +24,24 @@ spec: stackName: cloudflare-hyperdrive terraformDir: terraform terraformVersion: "1.15.3" - - env: - AWS_EC2_METADATA_DISABLED: "true" - + # SEC-JOB: the wiring document (hyperdrive id/name) is lease-published + # post-apply; worker deploys read it back as WIRING_CLOUDFLARE_HYPERDRIVE_. + secretOutputs: "WIRING_CLOUDFLARE_HYPERDRIVE=wiring" + + # All three values resolve from orun secrets (project rung, brokered from + # the Cloudflare integration): the provider credential is minted fresh per + # run from the hyperdrive-edit template (Workers Hyperdrive Write — the + # workers-deploy token deliberately cannot touch Hyperdrive), and the + # account id is a non-secret connection fact (account-id template). + # Component-level because plan-only lanes refresh against the live API too. + secretEnv: + CLOUDFLARE_API_TOKEN: "secret://lumen/lumen/{{ .environment }}/CLOUDFLARE_HYPERDRIVE_TOKEN" + CLOUDFLARE_ACCOUNT_ID: "secret://lumen/lumen/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + TF_VAR_cloudflare_account_id: "secret://lumen/lumen/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + # Supabase origin, lease-published by the supabase component's + # secretOutputs — the replacement for the Secrets Manager data source. + TF_VAR_supabase_project_ref: "secret://lumen/lumen/{{ .environment }}/SUPABASE_PROJECT_REF" + TF_VAR_supabase_db_password: "secret://lumen/lumen/{{ .environment }}/SUPABASE_DB_PASSWORD" subscribe: environments: diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl b/infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl index 94f0915..39479b2 100644 --- a/infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl +++ b/infra/terraform/cloudflare-hyperdrive/terraform/.terraform.lock.hcl @@ -24,25 +24,3 @@ provider "registry.terraform.io/cloudflare/cloudflare" { ] } -provider "registry.terraform.io/hashicorp/aws" { - version = "5.100.0" - constraints = "~> 5.0" - hashes = [ - "h1:Ijt7pOlB7Tr7maGQIqtsLFbl7pSMIj06TVdkoSBcYOw=", - "zh:054b8dd49f0549c9a7cc27d159e45327b7b65cf404da5e5a20da154b90b8a644", - "zh:0b97bf8d5e03d15d83cc40b0530a1f84b459354939ba6f135a0086c20ebbe6b2", - "zh:1589a2266af699cbd5d80737a0fe02e54ec9cf2ca54e7e00ac51c7359056f274", - "zh:6330766f1d85f01ae6ea90d1b214b8b74cc8c1badc4696b165b36ddd4cc15f7b", - "zh:7c8c2e30d8e55291b86fcb64bdf6c25489d538688545eb48fd74ad622e5d3862", - "zh:99b1003bd9bd32ee323544da897148f46a527f622dc3971af63ea3e251596342", - "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", - "zh:9f8b909d3ec50ade83c8062290378b1ec553edef6a447c56dadc01a99f4eaa93", - "zh:aaef921ff9aabaf8b1869a86d692ebd24fbd4e12c21205034bb679b9caf883a2", - "zh:ac882313207aba00dd5a76dbd572a0ddc818bb9cbf5c9d61b28fe30efaec951e", - "zh:bb64e8aff37becab373a1a0cc1080990785304141af42ed6aa3dd4913b000421", - "zh:dfe495f6621df5540d9c92ad40b8067376350b005c637ea6efac5dc15028add4", - "zh:f0ddf0eaf052766cfe09dea8200a946519f653c384ab4336e2a4a64fdd6310e9", - "zh:f1b7e684f4c7ae1eed272b6de7d2049bb87a0275cb04dbb7cda6636f600699c9", - "zh:ff461571e3f233699bf690db319dfe46aec75e58726636a0d97dd9ac6e32fb70", - ] -} diff --git a/infra/terraform/cloudflare-hyperdrive/terraform/main.tf b/infra/terraform/cloudflare-hyperdrive/terraform/main.tf index 0152882..f974af9 100644 --- a/infra/terraform/cloudflare-hyperdrive/terraform/main.tf +++ b/infra/terraform/cloudflare-hyperdrive/terraform/main.tf @@ -1,17 +1,11 @@ terraform { required_version = ">= 1.15.0" - backend "s3" { - encrypt = true - use_lockfile = true - workspace_key_prefix = "env" - } + # State lives on the platform (SB1): the runner exports TF_HTTP_* per job, so + # this block stays empty — no S3 bucket, no AWS role, no workspaces. + backend "http" {} required_providers { - aws = { - source = "hashicorp/aws" - version = "~> 5.0" - } cloudflare = { source = "cloudflare/cloudflare" version = "~> 4.30" @@ -21,19 +15,6 @@ terraform { # --- Providers --- -provider "aws" { - region = var.awsRegion - - default_tags { - tags = { - ManagedBy = "terraform" - Repository = "${var.owner}/${var.repo}" - Component = var.component - Environment = var.environment - } - } -} - # Authenticates via the CLOUDFLARE_API_TOKEN env var (provider-native): the # token is an orun-managed secret resolved into the job env at run time, so it # never transits Terraform variables. @@ -41,11 +22,6 @@ provider "cloudflare" {} # --- Variables (standard Orun parameters) --- -variable "awsRegion" { - type = string - default = "us-east-1" -} - variable "cloudflare_account_id" { type = string sensitive = true @@ -108,30 +84,34 @@ variable "terraformVersion" { default = "1.15.3" } -# --- Data sources --- +# --- Supabase origin (from orun secrets, not Secrets Manager) --- +# +# The supabase component wires its outputs into the workspace's project/{{env}} +# secret rung (wireSecrets → SUPABASE_PROJECT_REF, SUPABASE_DB_PASSWORD); this +# component declares them in secretEnv as TF_VAR_supabase_project_ref / +# TF_VAR_supabase_db_password. Host/port/db/user derive from the project ref — +# the same derivation the old Secrets Manager payload carried. -# Fetch Supabase connection details from AWS Secrets Manager -# Written by the supabase component -data "aws_secretsmanager_secret_version" "supabase" { - secret_id = "${var.orgName}/${var.repo}/supabase/${var.environment}" +variable "supabase_project_ref" { + type = string + description = "Supabase project reference (from SUPABASE_PROJECT_REF secret)" } -locals { - supabase_secret = jsondecode(data.aws_secretsmanager_secret_version.supabase.secret_string) +variable "supabase_db_password" { + type = string + sensitive = true + description = "Supabase database password (from SUPABASE_DB_PASSWORD secret)" +} - database_host = local.supabase_secret.database_host - database_port = tonumber(local.supabase_secret.database_port) - database_name = local.supabase_secret.database_name - database_user = local.supabase_secret.database_user +locals { + database_host = "db.${var.supabase_project_ref}.supabase.co" + database_port = 5432 + database_name = "postgres" + database_user = "postgres" hyperdrive_name = "${var.namespacePrefix}lumen-${var.environment}" } -# --- Fetch Cloudflare account ID from env or variable --- -# In Orun CI, CLOUDFLARE_ACCOUNT_ID is available as an env var -# We pass it through as a TF_VAR_cloudflareAccountId -# For local testing, it can be hardcoded or passed via -var - # --- Create Hyperdrive resource --- resource "cloudflare_hyperdrive_config" "postgres" { @@ -144,7 +124,7 @@ resource "cloudflare_hyperdrive_config" "postgres" { port = local.database_port database = local.database_name user = local.database_user - password = local.supabase_secret.database_password + password = var.supabase_db_password } caching = { @@ -152,25 +132,18 @@ resource "cloudflare_hyperdrive_config" "postgres" { } } -# --- Wiring manifest (BF5) --- -# Publish the consumable outputs of this component at the conventional -# `///` Secrets Manager path so downstream consumers -# (BF6 deploy-time wiring) resolve resource IDs from here instead of committed -# literals. Stable secret container + rotating version, mirroring the supabase -# component's pattern. - -resource "aws_secretsmanager_secret" "wiring" { - name = "${var.orgName}/${var.repo}/${var.component}/${var.environment}" - description = "Wiring outputs of the cloudflare-hyperdrive component (consumed by Worker deploy-time binding resolution)" +# --- Wiring manifest (BF5, via orun secrets) --- +# +# The consumable outputs of this component are published by the composition's +# wire-secrets step as the WIRING_CLOUDFLARE_HYPERDRIVE secret on the +# project/{{env}} rung; worker deploys read it back as +# WIRING_CLOUDFLARE_HYPERDRIVE_ secretEnv and render committed +# @@wiring(...)@@ tokens from it (BF6). Same document shape the Secrets +# Manager path carried. - lifecycle { - prevent_destroy = true - } -} - -resource "aws_secretsmanager_secret_version" "wiring" { - secret_id = aws_secretsmanager_secret.wiring.id - secret_string = jsonencode({ +output "wiring" { + description = "Wiring document for downstream deploy-time binding resolution (pushed to orun secrets)" + value = jsonencode({ hyperdrive_id = cloudflare_hyperdrive_config.postgres.id hyperdrive_name = cloudflare_hyperdrive_config.postgres.name }) @@ -178,11 +151,6 @@ resource "aws_secretsmanager_secret_version" "wiring" { # --- Outputs (non-secret) --- -output "wiring_secret_arn" { - description = "ARN of the wiring-manifest secret for this component/environment" - value = aws_secretsmanager_secret.wiring.arn -} - output "hyperdrive_id" { description = "Cloudflare Hyperdrive config ID" value = cloudflare_hyperdrive_config.postgres.id @@ -198,27 +166,3 @@ output "hyperdrive_connection_string" { # Note: actual connection string is built at binding time; this is the resource ID value = "hyperdrive://${cloudflare_hyperdrive_config.postgres.id}" } - -output "database_host" { - description = "Database host (from Supabase secrets)" - value = local.database_host - sensitive = true -} - -output "database_port" { - description = "Database port (from Supabase secrets)" - value = local.database_port - sensitive = true -} - -output "database_name" { - description = "Database name (from Supabase secrets)" - value = local.database_name - sensitive = true -} - -output "database_user" { - description = "Database user (from Supabase secrets)" - value = local.database_user - sensitive = true -} diff --git a/infra/terraform/cloudflare-kv/component.yaml b/infra/terraform/cloudflare-kv/component.yaml index 7e37f02..4a31532 100644 --- a/infra/terraform/cloudflare-kv/component.yaml +++ b/infra/terraform/cloudflare-kv/component.yaml @@ -19,9 +19,9 @@ spec: stackName: cloudflare-kv terraformDir: terraform terraformVersion: "1.15.3" - - env: - AWS_EC2_METADATA_DISABLED: "true" + # SEC-JOB: the wiring document (KV namespace id/title) is lease-published + # post-apply; api-edge deploys read it back as WIRING_CLOUDFLARE_KV_. + secretOutputs: "WIRING_CLOUDFLARE_KV=wiring" # The Cloudflare Terraform provider authenticates via the CLOUDFLARE_API_TOKEN # env var, resolved by orun from the project-rung brokered secret (fresh per @@ -29,6 +29,10 @@ spec: # lanes refresh against the live Cloudflare API too, not just apply. secretEnv: CLOUDFLARE_API_TOKEN: "secret://lumen/lumen/{{ .environment }}/CLOUDFLARE_API_TOKEN" + # Non-secret connection fact (account-id template) — replaces the ambient + # CLOUDFLARE_ACCOUNT_ID / TF_VAR_cloudflare_account_id CI values. + CLOUDFLARE_ACCOUNT_ID: "secret://lumen/lumen/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + TF_VAR_cloudflare_account_id: "secret://lumen/lumen/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" subscribe: environments: diff --git a/infra/terraform/cloudflare-kv/terraform/.terraform.lock.hcl b/infra/terraform/cloudflare-kv/terraform/.terraform.lock.hcl index 94f0915..39479b2 100644 --- a/infra/terraform/cloudflare-kv/terraform/.terraform.lock.hcl +++ b/infra/terraform/cloudflare-kv/terraform/.terraform.lock.hcl @@ -24,25 +24,3 @@ provider "registry.terraform.io/cloudflare/cloudflare" { ] } -provider "registry.terraform.io/hashicorp/aws" { - version = "5.100.0" - constraints = "~> 5.0" - hashes = [ - "h1:Ijt7pOlB7Tr7maGQIqtsLFbl7pSMIj06TVdkoSBcYOw=", - "zh:054b8dd49f0549c9a7cc27d159e45327b7b65cf404da5e5a20da154b90b8a644", - "zh:0b97bf8d5e03d15d83cc40b0530a1f84b459354939ba6f135a0086c20ebbe6b2", - "zh:1589a2266af699cbd5d80737a0fe02e54ec9cf2ca54e7e00ac51c7359056f274", - "zh:6330766f1d85f01ae6ea90d1b214b8b74cc8c1badc4696b165b36ddd4cc15f7b", - "zh:7c8c2e30d8e55291b86fcb64bdf6c25489d538688545eb48fd74ad622e5d3862", - "zh:99b1003bd9bd32ee323544da897148f46a527f622dc3971af63ea3e251596342", - "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", - "zh:9f8b909d3ec50ade83c8062290378b1ec553edef6a447c56dadc01a99f4eaa93", - "zh:aaef921ff9aabaf8b1869a86d692ebd24fbd4e12c21205034bb679b9caf883a2", - "zh:ac882313207aba00dd5a76dbd572a0ddc818bb9cbf5c9d61b28fe30efaec951e", - "zh:bb64e8aff37becab373a1a0cc1080990785304141af42ed6aa3dd4913b000421", - "zh:dfe495f6621df5540d9c92ad40b8067376350b005c637ea6efac5dc15028add4", - "zh:f0ddf0eaf052766cfe09dea8200a946519f653c384ab4336e2a4a64fdd6310e9", - "zh:f1b7e684f4c7ae1eed272b6de7d2049bb87a0275cb04dbb7cda6636f600699c9", - "zh:ff461571e3f233699bf690db319dfe46aec75e58726636a0d97dd9ac6e32fb70", - ] -} diff --git a/infra/terraform/cloudflare-kv/terraform/main.tf b/infra/terraform/cloudflare-kv/terraform/main.tf index f01290b..1dba000 100644 --- a/infra/terraform/cloudflare-kv/terraform/main.tf +++ b/infra/terraform/cloudflare-kv/terraform/main.tf @@ -1,17 +1,11 @@ terraform { required_version = ">= 1.15.0" - backend "s3" { - encrypt = true - use_lockfile = true - workspace_key_prefix = "env" - } + # State lives on the platform (SB1): the runner exports TF_HTTP_* per job, so + # this block stays empty — no S3 bucket, no AWS role, no workspaces. + backend "http" {} required_providers { - aws = { - source = "hashicorp/aws" - version = "~> 5.0" - } cloudflare = { source = "cloudflare/cloudflare" version = "~> 4.30" @@ -21,19 +15,6 @@ terraform { # --- Providers --- -provider "aws" { - region = var.awsRegion - - default_tags { - tags = { - ManagedBy = "terraform" - Repository = "${var.owner}/${var.repo}" - Component = var.component - Environment = var.environment - } - } -} - # Authenticates via the CLOUDFLARE_API_TOKEN env var (provider-native): the # token is an orun-managed secret resolved into the job env at run time, so it # never transits Terraform variables. @@ -41,11 +22,6 @@ provider "cloudflare" {} # --- Variables (standard Orun parameters) --- -variable "awsRegion" { - type = string - default = "us-east-1" -} - variable "cloudflare_account_id" { type = string sensitive = true @@ -130,25 +106,15 @@ resource "cloudflare_workers_kv_namespace" "api_edge_idempotency" { title = local.idempotency_namespace_title } -# --- Wiring manifest (BF5) --- -# Publish the consumable outputs of this component at the conventional -# `///` Secrets Manager path so downstream consumers -# (BF6 deploy-time wiring) resolve resource IDs from here instead of committed -# literals. Stable secret container + rotating version, mirroring the supabase -# component's pattern. - -resource "aws_secretsmanager_secret" "wiring" { - name = "${var.orgName}/${var.repo}/${var.component}/${var.environment}" - description = "Wiring outputs of the cloudflare-kv component (consumed by Worker deploy-time binding resolution)" - - lifecycle { - prevent_destroy = true - } -} +# --- Wiring manifest (BF5, via orun secrets) --- +# The consumable outputs are published by the composition's wire-secrets step +# as the WIRING_CLOUDFLARE_KV secret on the project/{{env}} rung; worker +# deploys read it back as WIRING_CLOUDFLARE_KV_ secretEnv (BF6). Same +# document shape the Secrets Manager path carried. -resource "aws_secretsmanager_secret_version" "wiring" { - secret_id = aws_secretsmanager_secret.wiring.id - secret_string = jsonencode({ +output "wiring" { + description = "Wiring document for downstream deploy-time binding resolution (pushed to orun secrets)" + value = jsonencode({ api_edge_idempotency_kv_id = cloudflare_workers_kv_namespace.api_edge_idempotency.id api_edge_idempotency_kv_title = cloudflare_workers_kv_namespace.api_edge_idempotency.title }) @@ -156,11 +122,6 @@ resource "aws_secretsmanager_secret_version" "wiring" { # --- Outputs (non-secret) --- -output "wiring_secret_arn" { - description = "ARN of the wiring-manifest secret for this component/environment" - value = aws_secretsmanager_secret.wiring.arn -} - output "api_edge_idempotency_kv_id" { description = "Cloudflare Workers KV namespace ID for api-edge idempotency replay store" value = cloudflare_workers_kv_namespace.api_edge_idempotency.id diff --git a/infra/terraform/supabase/component.yaml b/infra/terraform/supabase/component.yaml index 50adfeb..5b91699 100644 --- a/infra/terraform/supabase/component.yaml +++ b/infra/terraform/supabase/component.yaml @@ -3,7 +3,7 @@ kind: Component metadata: name: supabase - description: Provisions Supabase projects for stage and prod and stores credentials in AWS Secrets Manager + description: Provisions Supabase projects for stage and prod and wires credentials into orun secrets labels: domain: infra scope: database @@ -14,11 +14,6 @@ spec: owner: platform domain: infra - # Supabase provisioning writes credentials to AWS Secrets Manager and stores - # Terraform state in S3; both are proven by `bootstrap` first. - dependsOn: - - component: bootstrap - parameters: orgName: sourceplane stackName: supabase @@ -30,9 +25,19 @@ spec: # SUPABASE_ORG_ID CI secret (see .github/workflows/ci.yml). Keeping it out of # parameters also prevents the param→TF_VAR loop from overriding the secret. supabaseRegion: ap-southeast-1 + # SEC-JOB: post-apply, these outputs are queued on the runner's sink and + # lease-published onto the project/{{env}} rung by the runner. + secretOutputs: "SUPABASE_PROJECT_REF=project_ref,SUPABASE_DB_PASSWORD=database_password,SUPABASE_DB_URL=connection_uri" - env: - AWS_EC2_METADATA_DISABLED: "true" + # Both values resolve from orun secrets (project rung, brokered from the + # Supabase integration): a short-lived Management-API access token minted + # fresh per run (management-access template — the provider reads + # SUPABASE_ACCESS_TOKEN from env natively), and the org id as a non-secret + # connection fact (org-id template) surfaced straight to Terraform. The + # SUPABASE_ORG_ID CI secret and its TF_VAR mapping are retired. + secretEnv: + SUPABASE_ACCESS_TOKEN: "secret://lumen/lumen/{{ .environment }}/SUPABASE_ACCESS_TOKEN" + TF_VAR_supabaseOrgId: "secret://lumen/lumen/{{ .environment }}/SUPABASE_ORG_ID" subscribe: environments: diff --git a/infra/terraform/supabase/terraform/.terraform.lock.hcl b/infra/terraform/supabase/terraform/.terraform.lock.hcl index e60135d..36d0ff4 100644 --- a/infra/terraform/supabase/terraform/.terraform.lock.hcl +++ b/infra/terraform/supabase/terraform/.terraform.lock.hcl @@ -1,29 +1,6 @@ # This file is maintained automatically by "terraform init". # Manual edits may be lost in future updates. -provider "registry.terraform.io/hashicorp/aws" { - version = "5.100.0" - constraints = "~> 5.0" - hashes = [ - "h1:Ijt7pOlB7Tr7maGQIqtsLFbl7pSMIj06TVdkoSBcYOw=", - "zh:054b8dd49f0549c9a7cc27d159e45327b7b65cf404da5e5a20da154b90b8a644", - "zh:0b97bf8d5e03d15d83cc40b0530a1f84b459354939ba6f135a0086c20ebbe6b2", - "zh:1589a2266af699cbd5d80737a0fe02e54ec9cf2ca54e7e00ac51c7359056f274", - "zh:6330766f1d85f01ae6ea90d1b214b8b74cc8c1badc4696b165b36ddd4cc15f7b", - "zh:7c8c2e30d8e55291b86fcb64bdf6c25489d538688545eb48fd74ad622e5d3862", - "zh:99b1003bd9bd32ee323544da897148f46a527f622dc3971af63ea3e251596342", - "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", - "zh:9f8b909d3ec50ade83c8062290378b1ec553edef6a447c56dadc01a99f4eaa93", - "zh:aaef921ff9aabaf8b1869a86d692ebd24fbd4e12c21205034bb679b9caf883a2", - "zh:ac882313207aba00dd5a76dbd572a0ddc818bb9cbf5c9d61b28fe30efaec951e", - "zh:bb64e8aff37becab373a1a0cc1080990785304141af42ed6aa3dd4913b000421", - "zh:dfe495f6621df5540d9c92ad40b8067376350b005c637ea6efac5dc15028add4", - "zh:f0ddf0eaf052766cfe09dea8200a946519f653c384ab4336e2a4a64fdd6310e9", - "zh:f1b7e684f4c7ae1eed272b6de7d2049bb87a0275cb04dbb7cda6636f600699c9", - "zh:ff461571e3f233699bf690db319dfe46aec75e58726636a0d97dd9ac6e32fb70", - ] -} - provider "registry.terraform.io/hashicorp/random" { version = "3.9.0" constraints = "~> 3.0" diff --git a/infra/terraform/supabase/terraform/main.tf b/infra/terraform/supabase/terraform/main.tf index 7416d5b..0903f89 100644 --- a/infra/terraform/supabase/terraform/main.tf +++ b/infra/terraform/supabase/terraform/main.tf @@ -1,20 +1,20 @@ terraform { required_version = ">= 1.15.0" - backend "s3" { - encrypt = true - use_lockfile = true - workspace_key_prefix = "env" - } + # State lives on the platform (SB1): the runner exports TF_HTTP_* per job + # (address = …/state/tfstate/{component}/{env}, run token as password), so + # this block stays empty — no S3 bucket, no AWS role, no workspaces (the + # environment is in the address). + backend "http" {} required_providers { - aws = { - source = "hashicorp/aws" - version = "~> 5.0" - } supabase = { - source = "supabase/supabase" - version = "~> 1.0" + source = "supabase/supabase" + # Pinned below 1.6: from 1.6.0 the provider reads /billing/addons on + # every project create/read, and Supabase does not serve billing + # endpoints to OAuth tokens yet ("does not support oauth access") — + # which is exactly the credential the platform brokers. + version = "~> 1.5.1" } random = { source = "hashicorp/random" @@ -25,29 +25,13 @@ terraform { # --- Providers --- -provider "aws" { - region = var.awsRegion - - default_tags { - tags = { - ManagedBy = "terraform" - Repository = "${var.owner}/${var.repo}" - Component = var.component - Environment = var.environment - } - } -} - -# Authenticates via SUPABASE_ACCESS_TOKEN env var (mapped from SUPABASE_API_KEY in CI) +# Authenticates via the SUPABASE_ACCESS_TOKEN env var (provider-native): a +# short-lived Management-API token minted per run from the workspace's +# Supabase integration, resolved into the job env by orun. provider "supabase" {} # --- Variables (standard Orun parameters) --- -variable "awsRegion" { - type = string - default = "us-east-1" -} - variable "orgName" { type = string default = "sourceplane" @@ -104,10 +88,10 @@ variable "terraformVersion" { } # Supabase target identity. supabaseRegion comes from the component's -# `spec.parameters`; supabaseOrgId is account-specific and injected as -# TF_VAR_supabaseOrgId from the SUPABASE_ORG_ID CI secret (see -# .github/workflows/ci.yml). Both are required (no default) so a missing value -# fails plan loudly instead of silently pointing at the wrong org or region. +# `spec.parameters`; supabaseOrgId is injected as TF_VAR_supabaseOrgId from the +# workspace's SUPABASE_ORG_ID secret (org-id connection fact). Both are +# required (no default) so a missing value fails plan loudly instead of +# silently pointing at the wrong org or region. variable "supabaseOrgId" { type = string } @@ -122,18 +106,6 @@ locals { supabase_org_id = var.supabaseOrgId supabase_region = var.supabaseRegion project_name = "lumen-${var.environment}" - secret_name = "${var.orgName}/lumen/supabase/${var.environment}" - - supabase_secret_payload = { - project_ref = supabase_project.this.id - project_url = "https://${supabase_project.this.id}.supabase.co" - database_host = "db.${supabase_project.this.id}.supabase.co" - database_port = "5432" - database_name = "postgres" - database_user = "postgres" - database_password = random_password.db_password.result - connection_uri = "postgresql://postgres:${random_password.db_password.result}@db.${supabase_project.this.id}.supabase.co:5432/postgres" - } } # --- Generate database password --- @@ -154,34 +126,13 @@ resource "supabase_project" "this" { region = local.supabase_region } -# --- Store credentials in AWS Secrets Manager --- - -resource "aws_secretsmanager_secret" "supabase" { - name = local.secret_name - description = "Supabase project credentials for ${local.project_name}" - recovery_window_in_days = 30 - - tags = { - Project = local.project_name - Environment = var.environment - } - - lifecycle { - # Keep the named secret as a stable container. Credential changes must create - # a new aws_secretsmanager_secret_version rather than replacing the secret, - # because AWS prevents immediate reuse of a deleted secret name during the - # recovery window. - prevent_destroy = true - } -} - -resource "aws_secretsmanager_secret_version" "supabase" { - secret_id = aws_secretsmanager_secret.supabase.id - secret_string = jsonencode(local.supabase_secret_payload) - version_stages = ["AWSCURRENT"] -} - -# --- Outputs (non-secret only) --- +# --- Outputs --- +# +# Credentials leave this module ONLY through the composition's wire-secrets +# step (component.yaml `wireSecrets`), which pushes each named output into the +# workspace's project/{{env}} secret rung via `orun secrets set` (value over +# stdin, never argv). Consumers (cloudflare-hyperdrive, db-migrate, workers) +# read the same keys back as secretEnv references. No Secrets Manager. output "project_ref" { description = "Supabase project reference ID" @@ -198,13 +149,14 @@ output "project_url" { value = "https://${supabase_project.this.id}.supabase.co" } -output "secret_arn" { - description = "ARN of the AWS Secrets Manager secret storing credentials" - value = aws_secretsmanager_secret.supabase.arn -} - output "database_password" { - description = "Generated database password (sensitive)" + description = "Generated database password (sensitive; wired to orun secrets)" value = random_password.db_password.result sensitive = true } + +output "connection_uri" { + description = "Direct Postgres connection URI (sensitive; wired to orun secrets)" + value = "postgresql://postgres:${random_password.db_password.result}@db.${supabase_project.this.id}.supabase.co:5432/postgres" + sensitive = true +} diff --git a/intent.yaml b/intent.yaml index 859051d..994f283 100644 --- a/intent.yaml +++ b/intent.yaml @@ -31,7 +31,7 @@ compositions: # a commit here. Bumping the tag is the deliberate upgrade step. - name: stack-tectonic kind: oci - ref: oci://ghcr.io/sourceplane/stack-tectonic:0.14.0 + ref: oci://ghcr.io/sourceplane/stack-tectonic:0.18.0 resolution: precedence: - stack-tectonic @@ -88,8 +88,6 @@ environments: - local-development parameterDefaults: terraform: - awsRegion: us-east-1 - awsAccountId: "306024784101" lane: verify namespace: sourceplane namespacePrefix: dev- @@ -99,7 +97,6 @@ environments: policies: requireApproval: "false" env: - AWS_REGION: us-east-1 BASE_DOMAIN: lumen.app stage: @@ -109,8 +106,6 @@ environments: - github-push-main parameterDefaults: terraform: - awsRegion: us-east-1 - awsAccountId: "306024784101" lane: verify namespace: sourceplane namespacePrefix: stg- @@ -120,7 +115,6 @@ environments: policies: requireApproval: "false" env: - AWS_REGION: us-east-1 BASE_DOMAIN: lumen.app prod: @@ -133,8 +127,6 @@ environments: - environment: stage parameterDefaults: terraform: - awsRegion: us-east-1 - awsAccountId: "306024784101" lane: verify namespace: sourceplane namespacePrefix: prod- @@ -144,5 +136,4 @@ environments: policies: requireApproval: "false" env: - AWS_REGION: us-east-1 BASE_DOMAIN: lumen.app diff --git a/packages/db/package.json b/packages/db/package.json index e51d90e..86c0a6b 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -33,7 +33,6 @@ "migrate:apply": "node --loader ts-node/esm src/runner/cli.ts apply" }, "dependencies": { - "@aws-sdk/client-secrets-manager": "^3.700.0", "pg": "^8.13.0", "postgres": "^3.4.5" }, diff --git a/packages/db/src/runner/cli.ts b/packages/db/src/runner/cli.ts index 83bc5c4..a56fc60 100644 --- a/packages/db/src/runner/cli.ts +++ b/packages/db/src/runner/cli.ts @@ -3,15 +3,13 @@ import { resolve, dirname } from "node:path"; import { fileURLToPath } from "node:url"; import { manifest } from "../manifest.js"; import { runMigrations } from "./runner.js"; -import { loadSecret } from "./secrets.js"; +import { loadSecretFromEnv } from "./secrets.js"; import { SupabaseApiAdapter } from "./supabase-api-adapter.js"; import type { MigrationAdapter, RunMode } from "./types.js"; const __dirname = dirname(fileURLToPath(import.meta.url)); const MIGRATIONS_DIR = resolve(__dirname, "../migrations"); -const SECRET_PREFIX = "sourceplane/lumen/supabase"; -const AWS_REGION = process.env["AWS_REGION"] ?? "us-east-1"; const SUPABASE_ACCESS_TOKEN = process.env["SUPABASE_ACCESS_TOKEN"]; function usage(): never { @@ -26,8 +24,8 @@ function usage(): never { ` --env target environment (required)\n` + `\n` + `Environment:\n` + - ` AWS_REGION AWS region for Secrets Manager (default: us-east-1)\n` + - ` SUPABASE_ACCESS_TOKEN Supabase management API token (required for apply)\n`, + ` SUPABASE_ACCESS_TOKEN Supabase management API token (required for apply)\n` + + ` SUPABASE_PROJECT_REF Supabase project ref (required for apply; wired from orun secrets)\n`, ); process.exit(1); } @@ -80,9 +78,8 @@ async function resolveAdapter( throw new Error("SUPABASE_ACCESS_TOKEN is required for apply mode"); } - const secretName = `${SECRET_PREFIX}/${env}`; - process.stderr.write(`Loading credentials from Secrets Manager: ${secretName}\n`); - const secret = await loadSecret(secretName, AWS_REGION); + process.stderr.write(`Loading credentials from the wired environment (orun secrets)\n`); + const secret = loadSecretFromEnv(); return new SupabaseApiAdapter(secret.project_ref, SUPABASE_ACCESS_TOKEN); } diff --git a/packages/db/src/runner/index.ts b/packages/db/src/runner/index.ts index 1fc34ed..916727c 100644 --- a/packages/db/src/runner/index.ts +++ b/packages/db/src/runner/index.ts @@ -2,5 +2,5 @@ export type { MigrationAdapter, AppliedMigration, RunnerConfig, RunMode, Migrati export { runMigrations, buildPlan } from "./runner.js"; export { PgAdapter } from "./pg-adapter.js"; export { SupabaseApiAdapter } from "./supabase-api-adapter.js"; -export { loadConnectionUri, loadSecret } from "./secrets.js"; +export { loadConnectionUriFromEnv, loadSecretFromEnv } from "./secrets.js"; export type { SupabaseSecret } from "./secrets.js"; diff --git a/packages/db/src/runner/secrets.ts b/packages/db/src/runner/secrets.ts index ca77768..e575b57 100644 --- a/packages/db/src/runner/secrets.ts +++ b/packages/db/src/runner/secrets.ts @@ -1,3 +1,9 @@ +// Supabase credentials from the ENVIRONMENT (de-AWS): the supabase terraform +// component wires its outputs into the workspace's project/env secret rung +// (composition wire-secrets step), and orun resolves the keys this runner +// declares in its component secretEnv into the job env — SUPABASE_PROJECT_REF, +// SUPABASE_DB_PASSWORD, SUPABASE_DB_URL. No Secrets Manager, no AWS SDK. + export interface SupabaseSecret { project_ref: string; project_url: string; @@ -9,60 +15,48 @@ export interface SupabaseSecret { connection_uri: string; } -async function fetchSecret( - secretName: string, - region: string, -): Promise { - const { - SecretsManagerClient, - GetSecretValueCommand, - } = await import("@aws-sdk/client-secrets-manager"); - - const client = new SecretsManagerClient({ region }); - const response = await client.send( - new GetSecretValueCommand({ SecretId: secretName }), - ); - - if (!response.SecretString) { - throw new Error(`Secret ${secretName} has no string value`); +function requireEnv(name: string): string { + const value = process.env[name]?.trim(); + if (!value) { + throw new Error( + `${name} is not set — declare it in the component's secretEnv (wired from the supabase component's outputs)`, + ); } - - return JSON.parse(response.SecretString) as SupabaseSecret; + return value; } -export async function loadSecret( - secretName: string, - region: string, -): Promise { - const parsed = await fetchSecret(secretName, region); - if (!parsed.project_ref) { - throw new Error(`Secret ${secretName} missing project_ref field`); - } - return parsed; +/** Assembles the credential document from the wired env vars. The derived + * fields (host/port/db/user) follow the same convention the supabase + * component's payload always used. */ +export function loadSecretFromEnv(): SupabaseSecret { + const projectRef = requireEnv("SUPABASE_PROJECT_REF"); + const password = requireEnv("SUPABASE_DB_PASSWORD"); + const host = `db.${projectRef}.supabase.co`; + const connectionUri = + process.env["SUPABASE_DB_URL"]?.trim() || + `postgresql://postgres:${encodeURIComponent(password)}@${host}:5432/postgres`; + return { + project_ref: projectRef, + project_url: `https://${projectRef}.supabase.co`, + database_host: host, + database_port: "5432", + database_name: "postgres", + database_user: "postgres", + database_password: password, + connection_uri: connectionUri, + }; } -export async function loadConnectionUri( - secretName: string, - region: string, - poolerRegion?: string, -): Promise { - const parsed = await fetchSecret(secretName, region); - - if (!parsed.connection_uri) { - throw new Error( - `Secret ${secretName} missing connection_uri field`, - ); - } - - // When a pooler region is provided, use the Supabase session pooler to avoid - // IPv6 connectivity issues with the direct database host. The pooler has IPv4 - // addresses and supports session-level advisory locks and transactions. - if (poolerRegion && parsed.project_ref && parsed.database_password) { +/** Direct or pooler connection URI. When a pooler region is provided, use the + * Supabase session pooler to avoid IPv6 connectivity issues with the direct + * database host — the pooler has IPv4 addresses and supports session-level + * advisory locks and transactions. */ +export function loadConnectionUriFromEnv(poolerRegion?: string): string { + const secret = loadSecretFromEnv(); + if (poolerRegion) { const poolerHost = `aws-0-${poolerRegion}.pooler.supabase.com`; - const user = `postgres.${parsed.project_ref}`; - const db = parsed.database_name ?? "postgres"; - return `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(parsed.database_password)}@${poolerHost}:6543/${db}`; + const user = `postgres.${secret.project_ref}`; + return `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(secret.database_password)}@${poolerHost}:6543/${secret.database_name}`; } - - return parsed.connection_uri; + return secret.connection_uri; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0dce8d6..3539827 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -522,9 +522,6 @@ importers: packages/db: dependencies: - '@aws-sdk/client-secrets-manager': - specifier: ^3.700.0 - version: 3.1051.0 pg: specifier: ^8.13.0 version: 8.21.0 @@ -1153,30 +1150,6 @@ importers: specifier: ^5.8.3 version: 5.9.3 - tests/secrets-sync: - devDependencies: - '@saas/eslint-config': - specifier: workspace:* - version: link:../../tooling/eslint - '@saas/tsconfig': - specifier: workspace:* - version: link:../../tooling/tsconfig - '@types/jest': - specifier: ^29.5.14 - version: 29.5.14 - '@types/node': - specifier: ^20.17.0 - version: 20.19.41 - jest: - specifier: ^29.7.0 - version: 29.7.0(@types/node@20.19.41) - ts-jest: - specifier: ^29.3.4 - version: 29.4.9(@babel/core@7.29.0)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.0))(jest-util@29.7.0)(jest@29.7.0)(typescript@5.9.3) - typescript: - specifier: ^5.8.3 - version: 5.9.3 - tests/web-console-next: devDependencies: '@saas/contracts': @@ -1376,10 +1349,6 @@ packages: resolution: {integrity: sha512-7ny2Slr93Y+QniuluvcfWwyDi32zWQfznynL56Tk0vVh7bWrvS/odm8WP2nInKicRVNipcJHY2YInur6Q/9V0A==} engines: {node: '>=20.0.0'} - '@aws-sdk/client-secrets-manager@3.1051.0': - resolution: {integrity: sha512-bJN7+ck68aCFnTHGysMYqdXJY7qVMxRo99rZoqR5aG0Zm/uH6ZaFxO5qLSdOBV5CnBEbhmzsS6xNCaBk75WHiA==} - engines: {node: '>=20.0.0'} - '@aws-sdk/client-sqs@3.984.0': resolution: {integrity: sha512-TDvHpOUWlpanc3xQ5Xw0y8L2hoojBFCCSmXQ/6rKqGOf1ScX3dMA+K9aF0Zp0iwjhSh4VvsHD42esl8XwQZDjA==} engines: {node: '>=20.0.0'} @@ -7126,19 +7095,6 @@ snapshots: '@smithy/util-waiter': 4.4.5 tslib: 2.8.1 - '@aws-sdk/client-secrets-manager@3.1051.0': - dependencies: - '@aws-crypto/sha256-browser': 5.2.0 - '@aws-crypto/sha256-js': 5.2.0 - '@aws-sdk/core': 3.974.12 - '@aws-sdk/credential-provider-node': 3.972.43 - '@aws-sdk/types': 3.973.8 - '@smithy/core': 3.24.3 - '@smithy/fetch-http-handler': 5.4.3 - '@smithy/node-http-handler': 4.7.3 - '@smithy/types': 4.14.2 - tslib: 2.8.1 - '@aws-sdk/client-sqs@3.984.0': dependencies: '@aws-crypto/sha256-browser': 5.2.0 diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml index 4754e0b..0f45f24 100644 --- a/repo-blueprint.yaml +++ b/repo-blueprint.yaml @@ -90,11 +90,26 @@ ignore: # happens to have built — and a fork would ship with the BASELINE's rendered # config baked in. # - # wrangler.jsonc is the important one: it is rendered from + # For the TEMPLATED workers, wrangler.jsonc is rendered from # wrangler.template.jsonc at deploy time and carries resolved values # (baseline domains, and per BF6 the deploy-time binding IDs that must never - # be committed). Only the committed *.template.jsonc belongs in a fork. - - wrangler.jsonc + # be committed) — those renders are ignored EXPLICITLY, per app. The two + # legacy non-templated workers (policy-worker, web-console-next) COMMIT + # their wrangler.jsonc as the real config; a global ignore silently dropped + # them from forks (their verify lanes then failed `test -f`), which is why + # this list names paths instead of a pattern. + - apps/admin-worker/wrangler.jsonc + - apps/api-edge/wrangler.jsonc + - apps/billing-worker/wrangler.jsonc + - apps/config-worker/wrangler.jsonc + - apps/events-worker/wrangler.jsonc + - apps/identity-worker/wrangler.jsonc + - apps/integrations-worker/wrangler.jsonc + - apps/membership-worker/wrangler.jsonc + - apps/metering-worker/wrangler.jsonc + - apps/notifications-worker/wrangler.jsonc + - apps/projects-worker/wrangler.jsonc + - apps/webhooks-worker/wrangler.jsonc - "*.tsbuildinfo" # ── MODULES ─────────────────────────────────────────────────────────────── @@ -146,11 +161,6 @@ modules: from: tests/billing-worker to: tests/billing-worker dependsOn: [billing-worker, contracts, db] - - name: bootstrap - mode: copy - source: baseline - from: infra/terraform/bootstrap - to: infra/terraform/bootstrap - name: cli mode: copy source: baseline @@ -334,11 +344,11 @@ modules: from: packages/sdk to: packages/sdk dependsOn: [contracts] - - name: secrets-sync-tests + - name: flows mode: copy source: baseline - from: tests/secrets-sync - to: tests/secrets-sync + from: flows + to: flows - name: shared mode: copy source: baseline @@ -519,9 +529,9 @@ phases: - name: foundation modules: [cli, contracts, contracts-tests, db, db-tests, notifications-client, notifications-client-tests, policy-engine, policy-engine-tests, sdk, shared, testing, webhook-verifier] - name: infrastructure - modules: [bootstrap, cloudflare-hyperdrive, cloudflare-kv, db-migrate, supabase] + modules: [cloudflare-hyperdrive, cloudflare-kv, db-migrate, supabase] - name: workers - modules: [admin-worker, admin-worker-tests, billing-worker, billing-worker-tests, config-worker, config-worker-tests, events-worker, events-worker-tests, identity-worker, identity-worker-tests, integrations-worker, integrations-worker-tests, membership-worker, membership-worker-tests, metering-worker, metering-worker-tests, notifications-worker, notifications-worker-tests, policy-worker, policy-worker-tests, projects-worker, projects-worker-tests, secrets-sync-tests, webhooks-worker, webhooks-worker-tests] + modules: [admin-worker, admin-worker-tests, billing-worker, billing-worker-tests, config-worker, config-worker-tests, events-worker, events-worker-tests, identity-worker, identity-worker-tests, integrations-worker, integrations-worker-tests, membership-worker, membership-worker-tests, metering-worker, metering-worker-tests, notifications-worker, notifications-worker-tests, policy-worker, policy-worker-tests, projects-worker, projects-worker-tests, webhooks-worker, webhooks-worker-tests] - name: edge modules: [api-edge, api-edge-tests] - name: console @@ -530,7 +540,7 @@ phases: modules: [cloudflare-domain] - name: workspace description: Root manifests, tooling, compositions, and the rebrand values file. - modules: [agents, ai-context, github-workflows, rebrand-values, root-forking, root-gitignore, root-intent, root-kiox, root-kiox-lock, root-package-json, root-pnpm-lock, root-pnpm-workspace, root-readme, root-turbo, tooling, vscode] + modules: [agents, ai-context, flows, github-workflows, rebrand-values, root-forking, root-gitignore, root-intent, root-kiox, root-kiox-lock, root-package-json, root-pnpm-lock, root-pnpm-workspace, root-readme, root-turbo, tooling, vscode] # ── HOOKS ───────────────────────────────────────────────────────────────── # Declared, ecosystem-specific, run OUTSIDE the template sandbox and opt-in diff --git a/tests/secrets-sync/component.yaml b/tests/secrets-sync/component.yaml deleted file mode 100644 index f46c9cc..0000000 --- a/tests/secrets-sync/component.yaml +++ /dev/null @@ -1,22 +0,0 @@ -apiVersion: sourceplane.io/v1 -kind: Component -metadata: - name: secrets-sync-tests -spec: - type: turbo-package - lifecycle: production - owner: platform - domain: starter-tests - subscribe: - environments: - - name: dev - profile: quick-check - parameters: - nodeVersion: "20" - pnpmVersion: "10.12.1" - buildCommand: pnpm exec turbo run build --filter=./ - typecheckCommand: pnpm exec turbo run typecheck --filter=./ - preBuildCommand: pnpm exec turbo run test --filter=./ - labels: - team: platform - layer: test diff --git a/tests/secrets-sync/eslint.config.js b/tests/secrets-sync/eslint.config.js deleted file mode 100644 index 2e905dc..0000000 --- a/tests/secrets-sync/eslint.config.js +++ /dev/null @@ -1,2 +0,0 @@ -import config from "../../tooling/eslint/index.js"; -export default config; diff --git a/tests/secrets-sync/package.json b/tests/secrets-sync/package.json deleted file mode 100644 index e3a1e1c..0000000 --- a/tests/secrets-sync/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "@saas/secrets-sync-tests", - "version": "0.0.0", - "private": true, - "type": "module", - "scripts": { - "build": "tsc --noEmit", - "typecheck": "tsc --noEmit", - "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js", - "lint": "eslint src" - }, - "devDependencies": { - "@saas/eslint-config": "workspace:*", - "@saas/tsconfig": "workspace:*", - "@types/jest": "^29.5.14", - "@types/node": "^20.17.0", - "jest": "^29.7.0", - "ts-jest": "^29.3.4", - "typescript": "^5.8.3" - }, - "jest": { - "preset": "ts-jest/presets/default-esm", - "extensionsToTreatAsEsm": [".ts"], - "moduleNameMapper": { - "^(\\.{1,2}/.*)\\.js$": "$1" - }, - "transform": { - "^.+\\.ts$": ["ts-jest", { "useESM": true }] - }, - "testEnvironment": "node" - } -} diff --git a/tests/secrets-sync/src/assemble.test.ts b/tests/secrets-sync/src/assemble.test.ts deleted file mode 100644 index 34274b4..0000000 --- a/tests/secrets-sync/src/assemble.test.ts +++ /dev/null @@ -1,177 +0,0 @@ -import { execFileSync } from "node:child_process"; -import * as fs from "node:fs"; -import * as os from "node:os"; -import * as path from "node:path"; -import { fileURLToPath } from "node:url"; - -const here = path.dirname(fileURLToPath(import.meta.url)); -const toolDir = path.resolve(here, "../../../tooling/secrets-sync"); -const assembleScript = path.join(toolDir, "assemble.mjs"); -const integrationsManifestPath = path.join(toolDir, "integrations.manifest.json"); -const integrationsFixturePath = path.join(toolDir, "integrations.fixture.json"); -const secretsManifestPath = path.join(toolDir, "secrets.manifest.json"); - -interface RunResult { - status: number; - stdout: string; - stderr: string; -} - -function run(args: string[]): RunResult { - try { - return { status: 0, stdout: execFileSync("node", [assembleScript, ...args], { encoding: "utf8" }), stderr: "" }; - } catch (err) { - const e = err as { status: number; stdout: string; stderr: string }; - return { status: e.status, stdout: String(e.stdout), stderr: String(e.stderr) }; - } -} - -const readJson = (file: string): Record => - JSON.parse(fs.readFileSync(file, "utf8")) as Record; - -function w(map: Record>, name: string): Record { - const entry = map[name]; - if (!entry) throw new Error(`expected worker ${name} in projection`); - return entry; -} - -interface IntegrationSpec { - config: string[]; - secret: string[]; - consumers: string[]; - deferred?: string; -} -interface IntegrationsManifest { - environments: string[]; - deferredConsumers: string[]; - integrations: Record; - platform: { secret: Record }; -} -const im = readJson(integrationsManifestPath) as unknown as IntegrationsManifest; - -function tmpFile(value: unknown): string { - const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "as-")), "f.json"); - fs.writeFileSync(file, JSON.stringify(value)); - return file; -} - -function assembleStage(fixture: string): { secrets: Record>; config: Record>; result: RunResult } { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "as-out-")); - const outS = path.join(dir, "s.json"); - const outC = path.join(dir, "c.json"); - const result = run(["--env", "stage", "--fixture", fixture, "--out-secrets", outS, "--out-config", outC]); - return { - secrets: result.status === 0 ? (readJson(outS) as Record>) : {}, - config: result.status === 0 ? (readJson(outC) as Record>) : {}, - result, - }; -} - -describe("integrations manifest projection (SS6)", () => { - it("the committed secrets.manifest.json equals the projection of integrations.manifest.json", () => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "as-proj-")); - const out = path.join(dir, "projected.json"); - expect(run(["--project-manifest", "--out", out]).status).toBe(0); - expect(fs.readFileSync(out, "utf8")).toBe(fs.readFileSync(secretsManifestPath, "utf8")); - }); - - it("the fixture covers every config and secret key the manifest declares (stage + prod)", () => { - const fixture = readJson(integrationsFixturePath) as Record>>; - const deferred = new Set(im.deferredConsumers); - for (const env of im.environments) { - for (const [name, spec] of Object.entries(im.integrations)) { - // Fully-deferred integrations (all consumers deferred) are not seeded - // yet, so the fixture legitimately omits their documents. - if (spec.consumers.every((c) => deferred.has(c))) continue; - const doc = fixture[env]?.[name] ?? {}; - for (const key of [...spec.config, ...spec.secret]) { - expect(typeof doc[key]).toBe("string"); - } - } - const platform = fixture[env]?.["platform"] ?? {}; - for (const key of Object.keys(im.platform.secret)) { - expect(typeof platform[key]).toBe("string"); - } - } - }); -}); - -describe("assemble projection from documents (SS6)", () => { - it("projects per-worker secrets matching the sync.mjs input contract", () => { - const { secrets } = assembleStage(integrationsFixturePath); - expect(Object.keys(w(secrets,"identity-worker")).sort()).toEqual([ - "GITHUB_OAUTH_CLIENT_SECRET", - "GOOGLE_OAUTH_CLIENT_SECRET", - "OAUTH_STATE_SECRET", - ]); - expect(Object.keys(w(secrets,"billing-worker")).sort()).toEqual([ - "POLAR_ACCESS_TOKEN", - "POLAR_WEBHOOK_SECRET", - ]); - // SECRET_ENCRYPTION_KEY fans out from the single platform doc to both workers. - expect(w(secrets,"webhooks-worker")["SECRET_ENCRYPTION_KEY"]).toBeDefined(); - expect(w(secrets,"config-worker")["SECRET_ENCRYPTION_KEY"]).toBeDefined(); - }); - - it("projects per-worker config and keeps it disjoint from secrets", () => { - const { secrets, config } = assembleStage(integrationsFixturePath); - expect(w(config,"identity-worker")["GITHUB_OAUTH_CLIENT_ID"]).toBeDefined(); - expect(w(config,"billing-worker")["POLAR_PRODUCT_MAP"]).toBeDefined(); - expect(w(config,"notifications-worker")["EMAIL_FROM_ADDRESS"]).toBeDefined(); - // No secret name leaks into config, no config name into secrets. - const allSecretNames = new Set(); - for (const spec of Object.values(im.integrations)) for (const s of spec.secret) allSecretNames.add(s); - for (const s of Object.keys(im.platform.secret)) allSecretNames.add(s); - for (const worker of Object.values(config)) { - for (const key of Object.keys(worker)) expect(allSecretNames.has(key)).toBe(false); - } - const allConfigNames = new Set(); - for (const spec of Object.values(im.integrations)) for (const c of spec.config) allConfigNames.add(c); - for (const worker of Object.values(secrets)) { - for (const key of Object.keys(worker)) expect(allConfigNames.has(key)).toBe(false); - } - }); - - it("excludes deferred consumers entirely (integrations-worker has no projected secrets)", () => { - const { secrets, config } = assembleStage(integrationsFixturePath); - expect(secrets["integrations-worker"]).toBeUndefined(); - expect(config["integrations-worker"]).toBeUndefined(); - }); - - it("fails closed when an integration document is absent", () => { - const fixture = readJson(integrationsFixturePath) as Record>; - const stage = fixture["stage"]; - if (!stage) throw new Error("fixture missing stage"); - delete stage["polar"]; - const { result } = assembleStage(tmpFile(fixture)); - expect(result.status).toBe(1); - expect(result.stderr).toContain("polar.json not fetched"); - }); - - it("fails closed when a required key is empty", () => { - const fixture = readJson(integrationsFixturePath) as Record>>; - const stage = fixture["stage"]; - if (!stage?.["platform"]) throw new Error("fixture missing stage/platform"); - stage["platform"]["SECRET_ENCRYPTION_KEY"] = ""; - const { result } = assembleStage(tmpFile(fixture)); - expect(result.status).toBe(1); - expect(result.stderr).toContain("platform: secret SECRET_ENCRYPTION_KEY missing or empty"); - }); - - it("never prints secret values (config values are allowed)", () => { - const { result } = assembleStage(integrationsFixturePath); - const fixture = readJson(integrationsFixturePath) as Record>>; - const secretValues: string[] = []; - for (const [name, spec] of Object.entries(im.integrations)) { - for (const key of spec.secret) { - const v = fixture["stage"]?.[name]?.[key]; - if (v) secretValues.push(v); - } - } - for (const key of Object.keys(im.platform.secret)) { - const v = fixture["stage"]?.["platform"]?.[key]; - if (v) secretValues.push(v); - } - for (const value of secretValues) expect(result.stdout).not.toContain(value); - }); -}); diff --git a/tests/secrets-sync/src/check.test.ts b/tests/secrets-sync/src/check.test.ts deleted file mode 100644 index 65b1240..0000000 --- a/tests/secrets-sync/src/check.test.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { execFileSync } from "node:child_process"; -import * as fs from "node:fs"; -import * as os from "node:os"; -import * as path from "node:path"; -import { fileURLToPath } from "node:url"; - -const here = path.dirname(fileURLToPath(import.meta.url)); -const toolDir = path.resolve(here, "../../../tooling/secrets-sync"); -const checkScript = path.join(toolDir, "check.mjs"); -const manifestPath = path.join(toolDir, "secrets.manifest.json"); -const fixturePath = path.join(toolDir, "escrow.fixture.json"); - -interface RunResult { - status: number; - stdout: string; - stderr: string; -} - -function runCheck(args: string[]): RunResult { - try { - const stdout = execFileSync("node", [checkScript, ...args], { - encoding: "utf8", - }); - return { status: 0, stdout, stderr: "" }; - } catch (err) { - const e = err as { status: number; stdout: string; stderr: string }; - return { status: e.status, stdout: String(e.stdout), stderr: String(e.stderr) }; - } -} - -function tmpJson(value: unknown): string { - const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "ss-")), "payload.json"); - fs.writeFileSync(file, JSON.stringify(value)); - return file; -} - -type Fixture = Record>>; -const loadFixture = (): Fixture => - JSON.parse(fs.readFileSync(fixturePath, "utf8")) as Fixture; - -function workerSecrets(fixture: Fixture, env: string, worker: string): Record { - const secrets = fixture[env]?.[worker]; - if (!secrets) throw new Error(`fixture missing ${env}/${worker}`); - return secrets; -} - -interface Manifest { - escrowPath: string; - environments: string[]; - workers: Record; -} -const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")) as Manifest; - -describe("secrets manifest (SS0)", () => { - it("declares the escrow path under this repo's Secrets Manager namespace", () => { - expect(manifest.escrowPath).toBe( - "sourceplane/lumen/worker-secrets/", - ); - }); - - it("covers every worker template that documents a `wrangler secret put`", () => { - const apps = path.resolve(here, "../../../apps"); - // The manifest is a projection that also includes config-only consumers - // (e.g. notifications-worker) with no secrets; the coverage invariant is - // over workers that actually carry secrets (required or deferred). - const withSecrets = Object.entries( - manifest.workers as Record, - ) - .filter(([, spec]) => spec.required.length > 0 || spec.deferred !== undefined) - .map(([name]) => name) - .sort(); - const fromTemplates = fs - .readdirSync(apps) - .filter((app) => { - const template = path.join(apps, app, "wrangler.template.jsonc"); - return ( - fs.existsSync(template) && - fs.readFileSync(template, "utf8").includes("secret put") - ); - }) - .sort(); - expect(withSecrets).toEqual(fromTemplates); - }); - - it("never contains secret-looking values, only names", () => { - const raw = fs.readFileSync(manifestPath, "utf8"); - expect(raw).not.toMatch(/[A-Za-z0-9+/]{40,}/); - }); -}); - -describe("secrets-check (SS1)", () => { - it("passes against the committed fixture", () => { - const result = runCheck(["--fixture", fixturePath]); - expect(result.stdout).toContain("in sync"); - expect(result.status).toBe(0); - }); - - it("fails listing a missing required secret", () => { - const broken = loadFixture(); - delete workerSecrets(broken, "stage", "identity-worker")["OAUTH_STATE_SECRET"]; - const result = runCheck(["--fixture", tmpJson(broken)]); - expect(result.status).toBe(1); - expect(result.stderr).toContain("stage/identity-worker: missing OAUTH_STATE_SECRET"); - }); - - it("fails on unknown secret names (typo detection)", () => { - const broken = loadFixture(); - workerSecrets(broken, "prod", "billing-worker")["POLAR_ACCESS_TOKEN_TYPO"] = "x"; - const result = runCheck(["--fixture", tmpJson(broken)]); - expect(result.status).toBe(1); - expect(result.stderr).toContain("unknown secret POLAR_ACCESS_TOKEN_TYPO"); - }); - - it("fails on empty values", () => { - const broken = loadFixture(); - workerSecrets(broken, "stage", "billing-worker")["POLAR_ACCESS_TOKEN"] = ""; - const result = runCheck(["--fixture", tmpJson(broken)]); - expect(result.status).toBe(1); - expect(result.stderr).toContain("POLAR_ACCESS_TOKEN is empty"); - }); - - it("treats deferred secrets as required only under --strict", () => { - const relaxed = runCheck(["--fixture", fixturePath]); - expect(relaxed.status).toBe(0); - const strict = runCheck(["--fixture", fixturePath, "--strict"]); - expect(strict.status).toBe(1); - expect(strict.stderr).toContain("integrations-worker: missing GITHUB_APP_PRIVATE_KEY"); - }); - - it("never prints secret values, only fingerprints", () => { - const result = runCheck(["--fixture", fixturePath]); - const fixture = loadFixture(); - const fixtureValues = manifest.environments - .flatMap((env) => Object.values(fixture[env] ?? {})) - .flatMap((worker) => Object.values(worker)); - for (const value of fixtureValues) { - expect(result.stdout).not.toContain(value); - } - expect(result.stdout).toMatch(/sha256:[0-9a-f]{16}/); - }); - - it("validates deployed secret-name listings (wrangler secret list shape)", () => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ss-deployed-")); - for (const env of manifest.environments) { - for (const [worker, spec] of Object.entries(manifest.workers)) { - if (spec.required.length === 0) continue; - fs.writeFileSync( - path.join(dir, `${worker}__${env}.json`), - JSON.stringify(spec.required.map((name) => ({ name }))), - ); - } - } - expect(runCheck(["--deployed-dir", dir]).status).toBe(0); - - fs.writeFileSync( - path.join(dir, "identity-worker__prod.json"), - JSON.stringify([{ name: "GITHUB_OAUTH_CLIENT_SECRET" }]), - ); - const result = runCheck(["--deployed-dir", dir]); - expect(result.status).toBe(1); - expect(result.stderr).toContain("prod/identity-worker: OAUTH_STATE_SECRET not deployed"); - }); -}); diff --git a/tests/secrets-sync/src/sync.test.ts b/tests/secrets-sync/src/sync.test.ts deleted file mode 100644 index 41910b6..0000000 --- a/tests/secrets-sync/src/sync.test.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { execFileSync } from "node:child_process"; -import * as fs from "node:fs"; -import * as os from "node:os"; -import * as path from "node:path"; -import { fileURLToPath } from "node:url"; - -const here = path.dirname(fileURLToPath(import.meta.url)); -const toolDir = path.resolve(here, "../../../tooling/secrets-sync"); -const syncScript = path.join(toolDir, "sync.mjs"); - -interface RunResult { - status: number; - stdout: string; - stderr: string; -} - -interface SyncFiles { - bulk: string; - record: string; -} - -function runSync(args: { - worker: string; - env: string; - escrow: unknown; - record?: unknown; -}): RunResult & SyncFiles { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ss-sync-")); - const escrowFile = path.join(dir, "escrow.json"); - const recordFile = path.join(dir, "record.json"); - const bulkFile = path.join(dir, "bulk.json"); - const recordOutFile = path.join(dir, "record.next.json"); - fs.writeFileSync(escrowFile, JSON.stringify(args.escrow)); - fs.writeFileSync(recordFile, JSON.stringify(args.record ?? {})); - const argv = [ - syncScript, - "--worker", args.worker, - "--env", args.env, - "--escrow", escrowFile, - "--record", recordFile, - "--out-bulk", bulkFile, - "--out-record", recordOutFile, - ]; - try { - const stdout = execFileSync("node", argv, { encoding: "utf8" }); - return { status: 0, stdout, stderr: "", bulk: bulkFile, record: recordOutFile }; - } catch (err) { - const e = err as { status: number; stdout: string; stderr: string }; - return { - status: e.status, - stdout: String(e.stdout), - stderr: String(e.stderr), - bulk: bulkFile, - record: recordOutFile, - }; - } -} - -const readJson = (file: string): Record => - JSON.parse(fs.readFileSync(file, "utf8")) as Record; - -const billingEscrow = { - "billing-worker": { - POLAR_ACCESS_TOKEN: "polar-token-value", - POLAR_WEBHOOK_SECRET: "polar-webhook-value", - }, -}; - -describe("secrets-sync sync.mjs (SS2)", () => { - it("first run pushes everything and writes the fingerprint record", () => { - const result = runSync({ worker: "billing-worker", env: "stage", escrow: billingEscrow }); - expect(result.status).toBe(0); - expect(readJson(result.bulk)).toEqual(billingEscrow["billing-worker"]); - const record = readJson(result.record) as Record>; - expect(Object.keys(record["billing-worker"] ?? {}).sort()).toEqual([ - "POLAR_ACCESS_TOKEN", - "POLAR_WEBHOOK_SECRET", - ]); - }); - - it("is a no-op when fingerprints match the record", () => { - const first = runSync({ worker: "billing-worker", env: "stage", escrow: billingEscrow }); - const second = runSync({ - worker: "billing-worker", - env: "stage", - escrow: billingEscrow, - record: readJson(first.record), - }); - expect(second.status).toBe(0); - expect(readJson(second.bulk)).toEqual({}); - expect(second.stdout).toContain("in sync — nothing to push"); - }); - - it("pushes on any value change", () => { - const first = runSync({ worker: "billing-worker", env: "stage", escrow: billingEscrow }); - const rotated = { - "billing-worker": { ...billingEscrow["billing-worker"], POLAR_ACCESS_TOKEN: "rotated" }, - }; - const second = runSync({ - worker: "billing-worker", - env: "stage", - escrow: rotated, - record: readJson(first.record), - }); - expect(second.status).toBe(0); - expect(readJson(second.bulk)).toEqual(rotated["billing-worker"]); - expect(second.stdout).toContain("POLAR_ACCESS_TOKEN"); - expect(second.stdout).toContain("(changed)"); - }); - - it("fails closed when the escrow exists but misses a required secret", () => { - const result = runSync({ - worker: "billing-worker", - env: "stage", - escrow: { "billing-worker": { POLAR_ACCESS_TOKEN: "only-one" } }, - }); - expect(result.status).toBe(1); - expect(result.stderr).toContain("missing POLAR_WEBHOOK_SECRET"); - }); - - it("rejects workers not declared in the manifest", () => { - const result = runSync({ worker: "unknown-worker", env: "stage", escrow: {} }); - expect(result.status).toBe(2); - expect(result.stderr).toContain("not declared"); - }); - - it("preserves other workers' fingerprint entries in the record", () => { - const result = runSync({ - worker: "billing-worker", - env: "stage", - escrow: billingEscrow, - record: { "identity-worker": { OAUTH_STATE_SECRET: "deadbeefdeadbeef" } }, - }); - const record = readJson(result.record) as Record>; - expect(record["identity-worker"]).toEqual({ OAUTH_STATE_SECRET: "deadbeefdeadbeef" }); - expect(record["billing-worker"]).toBeDefined(); - }); - - it("never prints secret values", () => { - const result = runSync({ worker: "billing-worker", env: "stage", escrow: billingEscrow }); - for (const value of Object.values(billingEscrow["billing-worker"])) { - expect(result.stdout).not.toContain(value); - expect(result.stderr).not.toContain(value); - } - }); -}); diff --git a/tests/secrets-sync/tsconfig.json b/tests/secrets-sync/tsconfig.json deleted file mode 100644 index e8c0428..0000000 --- a/tests/secrets-sync/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "../../tooling/tsconfig/base.json", - "compilerOptions": { - "types": ["jest", "node"], - "allowSyntheticDefaultImports": true, - "composite": false, - "incremental": false, - "declaration": false, - "declarationMap": false - }, - "include": ["src/**/*.ts"] -} diff --git a/tooling/migrations/tfstate-to-orun.sh b/tooling/migrations/tfstate-to-orun.sh new file mode 100755 index 0000000..547ad4c --- /dev/null +++ b/tooling/migrations/tfstate-to-orun.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +# One-time migration of LIVE terraform state: S3 (AWS) → the orun platform +# state backend (SB1). Run BEFORE merging the de-AWS flip — after the flip, +# applies read the http backend, and an empty one would plan to re-create +# resources that already exist. +# +# Requirements: +# - AWS credentials able to read the sourceplane state buckets (the old +# -github-sourceplane-lumen-plan role's power, or an admin profile) +# - orun logged in (orun auth login) as a workspace member +# - terraform >= 1.15 +# +# What it does, per component × environment: +# 1. init against the OLD S3 backend (workspace env:) and `state pull` +# 2. `state rm` every aws_secretsmanager_* resource + data source — the +# flipped config no longer declares them, and their prevent_destroy +# guards would otherwise ERROR every future plan. The SM secrets remain +# in AWS untouched (delete them manually after the 30d recovery window). +# 3. init against the PLATFORM http backend (TF_HTTP_* below) + `state push` +# +# tooling/migrations/tfstate-to-orun.sh +# +# The token is only used as the terraform http backend password; prefer a +# short-lived one (it is NOT stored). Get the ids from the console URL or +# `orun cloud status`. +set -euo pipefail + +org="${1:?org public id (org_…)}" +prj="${2:?project public id (prj_…)}" +token="${3:?orun access token (backend password)}" +backend="${ORUN_BACKEND_URL:-https://api-edge-prod.oruncloud.workers.dev}" + +COMPONENTS=(supabase cloudflare-kv cloudflare-hyperdrive cloudflare-domain) +ENVS=(stage prod) + +repo_root="$(git rev-parse --show-toplevel)" + +for comp in "${COMPONENTS[@]}"; do + dir="$repo_root/infra/terraform/$comp/terraform" + [ -d "$dir" ] || { echo "skip $comp (no terraform dir)"; continue; } + for env in "${ENVS[@]}"; do + echo "══ $comp/$env" + work="$(mktemp -d)" + state="$work/terraform.tfstate" + + # 1. Pull from the OLD S3 backend. Uses a scratch copy of the module with + # the s3 backend restored, so the working tree stays flipped. + scratch="$work/module" + cp -R "$dir" "$scratch" + python3 - "$scratch/main.tf" <<'PYEOF' +import sys +p = sys.argv[1] +s = open(p).read() +s = s.replace('backend "http" {}', 'backend "s3" {\n encrypt = true\n use_lockfile = true\n workspace_key_prefix = "env"\n }') +open(p, "w").write(s) +PYEOF + terraform -chdir="$scratch" init -input=false -reconfigure \ + -backend-config="bucket=sourceplane-$env" \ + -backend-config="key=lumen/$comp/terraform.tfstate" \ + -backend-config="region=${AWS_REGION:-us-east-1}" >/dev/null + TF_WORKSPACE="$env" terraform -chdir="$scratch" state pull > "$state" + [ -s "$state" ] || { echo " no state for $comp/$env — skipping"; rm -rf "$work"; continue; } + + # 2. Drop the Secrets Manager resources from the pulled state. + sm_addrs=$(TF_WORKSPACE="$env" terraform -chdir="$scratch" state list -state="$state" 2>/dev/null \ + | grep -E '^(data\.)?aws_secretsmanager' || true) + if [ -n "$sm_addrs" ]; then + # shellcheck disable=SC2086 + TF_WORKSPACE="$env" terraform -chdir="$scratch" state rm -state="$state" $sm_addrs + fi + + # 3. Push into the platform backend (the flipped module, real dir). + addr="$backend/v1/organizations/$org/projects/$prj/state/tfstate/$comp/$env" + TF_HTTP_ADDRESS="$addr" TF_HTTP_LOCK_ADDRESS="$addr" TF_HTTP_UNLOCK_ADDRESS="$addr" \ + TF_HTTP_LOCK_METHOD=LOCK TF_HTTP_UNLOCK_METHOD=UNLOCK \ + TF_HTTP_USERNAME=orun TF_HTTP_PASSWORD="$token" \ + terraform -chdir="$dir" init -input=false -reconfigure >/dev/null + TF_HTTP_ADDRESS="$addr" TF_HTTP_LOCK_ADDRESS="$addr" TF_HTTP_UNLOCK_ADDRESS="$addr" \ + TF_HTTP_LOCK_METHOD=LOCK TF_HTTP_UNLOCK_METHOD=UNLOCK \ + TF_HTTP_USERNAME=orun TF_HTTP_PASSWORD="$token" \ + terraform -chdir="$dir" state push "$state" + echo " ✓ migrated $comp/$env" + rm -rf "$work" + done +done + +echo "state migration complete — verify with a plan-only CI run, then merge the flip." diff --git a/tooling/secrets-sync/assemble.mjs b/tooling/secrets-sync/assemble.mjs deleted file mode 100644 index 14d5edd..0000000 --- a/tooling/secrets-sync/assemble.mjs +++ /dev/null @@ -1,195 +0,0 @@ -#!/usr/bin/env node -// SS6 integration-document projector (zero-dependency, no cloud access). -// -// integrations.manifest.json is the source of truth: per-integration documents -// in Secrets Manager, each holding config + secret(s) for one provider, plus a -// single platform-secrets document for non-integration secrets. This tool -// projects that storage model into the per-worker views the rest of the -// pipeline already consumes: -// - per-worker SECRETS → the shape sync.mjs / check.mjs use (secrets-live) -// - per-worker CONFIG → non-secret vars rendered into wrangler configs -// -// Modes: -// --project-manifest --out -// Regenerate the per-worker secret manifest (secrets.manifest.json shape) -// from integrations.manifest.json. Deterministic; no cloud data. The -// committed secrets.manifest.json must equal this output (asserted in -// tests) so the shipped check.mjs/sync.mjs contract stays a true -// projection. -// -// --env --docs-dir --out-secrets --out-config -// Read one JSON document per integration (.json) and the platform -// doc (platform.json) from (fetched from Secrets Manager by the -// composition), validate completeness against the manifest, and emit the -// per-worker secrets and config projections. Secret values are never -// printed; config values may be. -// -// Exit codes: 0 ok · 1 validation failure (all listed) · 2 usage/config. - -import * as fs from "node:fs"; -import * as path from "node:path"; -import { fileURLToPath } from "node:url"; - -function arg(name) { - const i = process.argv.indexOf(`--${name}`); - return i >= 0 ? process.argv[i + 1] : undefined; -} -const has = (name) => process.argv.includes(`--${name}`); - -const manifestPath = - arg("manifest") ?? - path.join(path.dirname(fileURLToPath(import.meta.url)), "integrations.manifest.json"); - -function readJson(file, fallback) { - if (fallback !== undefined && !fs.existsSync(file)) return fallback; - try { - return JSON.parse(fs.readFileSync(file, "utf8")); - } catch (err) { - console.error(`assemble: cannot read ${file}: ${err.message}`); - process.exit(2); - } -} - -const manifest = readJson(manifestPath); -const integrations = manifest.integrations ?? {}; -const platform = manifest.platform ?? { secret: {} }; -const deferredConsumers = new Set(manifest.deferredConsumers ?? []); -const allWorkers = () => { - const set = new Set(); - for (const spec of Object.values(integrations)) for (const c of spec.consumers) set.add(c); - for (const consumers of Object.values(platform.secret ?? {})) for (const c of consumers) set.add(c); - return [...set].sort(); -}; - -// Per-worker required secret names (active) and deferred secret names. -function projectSecretManifest() { - const workers = {}; - for (const worker of allWorkers()) workers[worker] = { required: [], deferredNames: [] }; - const place = (worker, name) => { - const bucket = deferredConsumers.has(worker) ? "deferredNames" : "required"; - if (!workers[worker][bucket].includes(name)) workers[worker][bucket].push(name); - }; - for (const spec of Object.values(integrations)) { - for (const name of spec.secret ?? []) for (const w of spec.consumers) place(w, name); - } - for (const [name, consumers] of Object.entries(platform.secret ?? {})) { - for (const w of consumers) place(w, name); - } - const out = {}; - for (const [worker, { required, deferredNames }] of Object.entries(workers)) { - out[worker] = { required: required.sort() }; - if (deferredNames.length > 0) { - out[worker].deferred = { - reason: "deferred consumer — activate by removing from manifest.deferredConsumers", - names: deferredNames.sort(), - }; - } - } - return out; -} - -if (has("project-manifest")) { - const outFile = arg("out"); - if (!outFile) { - console.error("usage: assemble.mjs --project-manifest --out "); - process.exit(2); - } - const projected = { - $comment: - "GENERATED from integrations.manifest.json by assemble.mjs --project-manifest. Do not edit by hand; edit integrations.manifest.json and regenerate. Per-worker secret view consumed by check.mjs and sync.mjs.", - escrowPath: `${manifest.escrowRoot}/worker-secrets/`, - environments: manifest.environments, - workers: projectSecretManifest(), - }; - fs.writeFileSync(outFile, JSON.stringify(projected, null, 2) + "\n"); - console.log(`assemble: wrote per-worker secret manifest to ${outFile}`); - process.exit(0); -} - -// --- projection from live/fixture documents --- -const env = arg("env"); -const docsDir = arg("docs-dir"); -const fixturePath = arg("fixture"); -const outSecrets = arg("out-secrets"); -const outConfig = arg("out-config"); -if (!env || (!docsDir && !fixturePath) || !outSecrets || !outConfig) { - console.error( - "usage: assemble.mjs --env (--docs-dir | --fixture ) --out-secrets --out-config ", - ); - process.exit(2); -} -if (!(manifest.environments ?? []).includes(env)) { - console.error(`assemble: environment ${env} is not declared in the manifest`); - process.exit(2); -} - -// In fixture mode, documents come from fixture[env][]; otherwise from -// /.json (one file per document, fetched from Secrets Manager). -const fixtureDocs = fixturePath ? (readJson(fixturePath)[env] ?? {}) : null; - -const violations = []; -const workerSecrets = {}; -const workerConfig = {}; -const ensure = (map, worker) => (map[worker] ??= {}); - -function readDoc(name) { - if (fixtureDocs) return fixtureDocs[name]; - const file = path.join(docsDir, `${name}.json`); - if (!fs.existsSync(file)) return undefined; - return readJson(file); -} - -for (const [name, spec] of Object.entries(integrations)) { - const consumersActive = spec.consumers.filter((w) => !deferredConsumers.has(w)); - const doc = readDoc(name); - if (consumersActive.length === 0) continue; // fully deferred integration - if (doc === undefined) { - violations.push(`${env}: integration document ${name}.json not fetched (doc ${spec.doc})`); - continue; - } - for (const key of spec.config ?? []) { - const value = doc[key]; - if (typeof value !== "string" || value.length === 0) - violations.push(`${env}/${name}: config ${key} missing or empty`); - else for (const w of consumersActive) ensure(workerConfig, w)[key] = value; - } - for (const key of spec.secret ?? []) { - const value = doc[key]; - if (typeof value !== "string" || value.length === 0) - violations.push(`${env}/${name}: secret ${key} missing or empty`); - else for (const w of consumersActive) ensure(workerSecrets, w)[key] = value; - } -} - -const platformDoc = readDoc("platform"); -const platformActive = Object.entries(platform.secret ?? {}).filter(([, consumers]) => - consumers.some((w) => !deferredConsumers.has(w)), -); -if (platformActive.length > 0) { - if (platformDoc === undefined) { - violations.push(`${env}: platform document platform.json not fetched (doc ${platform.doc})`); - } else { - for (const [name, consumers] of platformActive) { - const value = platformDoc[name]; - if (typeof value !== "string" || value.length === 0) { - violations.push(`${env}/platform: secret ${name} missing or empty`); - } else { - for (const w of consumers) if (!deferredConsumers.has(w)) ensure(workerSecrets, w)[name] = value; - } - } - } -} - -if (violations.length > 0) { - console.error(`assemble: ${violations.length} violation(s):`); - for (const v of violations) console.error(` - ${v}`); - process.exit(1); -} - -fs.writeFileSync(outSecrets, JSON.stringify(workerSecrets)); -fs.writeFileSync(outConfig, JSON.stringify(workerConfig)); -const configKeys = Object.values(workerConfig).reduce((n, c) => n + Object.keys(c).length, 0); -const secretWorkers = Object.keys(workerSecrets).length; -console.log( - `assemble: ${env}: projected secrets for ${secretWorkers} worker(s), ${configKeys} config value(s) across ${Object.keys(workerConfig).length} worker(s)`, -); diff --git a/tooling/secrets-sync/check.mjs b/tooling/secrets-sync/check.mjs deleted file mode 100644 index a0a8baa..0000000 --- a/tooling/secrets-sync/check.mjs +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env node -// SS1 secrets drift detector (zero-dependency). -// -// Validates worker runtime secrets against the committed manifest -// (secrets.manifest.json) without ever printing a secret value — output is -// names and truncated SHA-256 fingerprints only. -// -// Sources (exactly one required): -// --fixture committed escrow.fixture.json keyed by env — offline -// PR verify lanes -// --escrow-dir one JSON file per env named worker-secrets__.json, -// each the escrow payload fetched from AWS Secrets -// Manager by the composition's secrets step -// --deployed-dir one JSON file per worker/env named __.json -// containing `wrangler secret list` output (array of -// { "name": ... }) — checks deployed names only -// -// Options: -// --manifest defaults to secrets.manifest.json next to this script -// --strict deferred secrets count as required -// -// Exit codes: 0 in sync · 1 violations (all listed) · 2 usage/IO error. -// -// Usage: -// node check.mjs --fixture escrow.fixture.json -// node check.mjs --escrow-dir /tmp/escrow -// node check.mjs --deployed-dir /tmp/deployed --strict - -import * as fs from "node:fs"; -import * as path from "node:path"; -import { createHash } from "node:crypto"; -import { fileURLToPath } from "node:url"; - -function arg(name) { - const i = process.argv.indexOf(`--${name}`); - return i >= 0 ? process.argv[i + 1] : undefined; -} -const flag = (name) => process.argv.includes(`--${name}`); - -const fixturePath = arg("fixture"); -const escrowDir = arg("escrow-dir"); -const deployedDir = arg("deployed-dir"); -const strict = flag("strict"); -const manifestPath = - arg("manifest") ?? - path.join(path.dirname(fileURLToPath(import.meta.url)), "secrets.manifest.json"); - -const sources = [fixturePath, escrowDir, deployedDir].filter(Boolean); -if (sources.length !== 1) { - console.error( - "usage: check.mjs (--fixture | --escrow-dir | --deployed-dir ) [--manifest ] [--strict]", - ); - process.exit(2); -} - -function readJson(file) { - try { - return JSON.parse(fs.readFileSync(file, "utf8")); - } catch (err) { - console.error(`secrets-check: cannot read ${file}: ${err.message}`); - process.exit(2); - } -} - -const manifest = readJson(manifestPath); -const environments = manifest.environments ?? []; -const workers = manifest.workers ?? {}; -const fingerprint = (value) => - createHash("sha256").update(String(value)).digest("hex").slice(0, 16); - -// expected: env -> worker -> Set of required names (deferred folded in under --strict) -function expectedNames(worker) { - const spec = workers[worker] ?? {}; - const names = [...(spec.required ?? [])]; - if (strict) names.push(...(spec.deferred?.names ?? [])); - return names; -} - -const violations = []; -const notes = []; - -function checkPayload(env, payload, { values }) { - for (const worker of Object.keys(workers)) { - const expected = expectedNames(worker); - const actual = payload[worker] ?? {}; - const actualNames = new Set(Object.keys(actual)); - - for (const name of expected) { - if (!actualNames.has(name)) { - violations.push(`${env}/${worker}: missing ${name}`); - } else if (values) { - const value = actual[name]; - if (typeof value !== "string" || value.length === 0) { - violations.push(`${env}/${worker}: ${name} is empty or not a string`); - } else { - notes.push(`${env}/${worker}: ${name} sha256:${fingerprint(value)}`); - } - } - } - - const known = new Set([ - ...(workers[worker]?.required ?? []), - ...(workers[worker]?.deferred?.names ?? []), - ]); - for (const name of actualNames) { - if (!known.has(name)) { - violations.push(`${env}/${worker}: unknown secret ${name} (typo, or add it to the manifest)`); - } - } - } - for (const worker of Object.keys(payload)) { - if (worker.startsWith("$")) continue; - if (!(worker in workers)) { - violations.push(`${env}: unknown worker ${worker} in payload`); - } - } -} - -if (fixturePath) { - const fixture = readJson(fixturePath); - for (const env of environments) { - if (!(env in fixture)) { - violations.push(`${env}: missing from fixture`); - continue; - } - checkPayload(env, fixture[env], { values: true }); - } -} else if (escrowDir) { - for (const env of environments) { - const file = path.join(escrowDir, `worker-secrets__${env}.json`); - if (!fs.existsSync(file)) { - violations.push(`${env}: escrow payload ${file} not fetched`); - continue; - } - checkPayload(env, readJson(file), { values: true }); - } -} else { - // deployed-dir: `wrangler secret list` output per worker/env — names only. - for (const env of environments) { - for (const worker of Object.keys(workers)) { - const expected = expectedNames(worker); - if (expected.length === 0) continue; - const file = path.join(deployedDir, `${worker}__${env}.json`); - if (!fs.existsSync(file)) { - violations.push(`${env}/${worker}: deployed secret list ${file} not fetched`); - continue; - } - const deployed = new Set(readJson(file).map((s) => s.name)); - for (const name of expected) { - if (!deployed.has(name)) { - violations.push(`${env}/${worker}: ${name} not deployed`); - } - } - } - } -} - -for (const note of notes) console.log(`secrets-check: ${note}`); -if (violations.length > 0) { - console.error(`secrets-check: ${violations.length} violation(s):`); - for (const v of violations) console.error(` - ${v}`); - process.exit(1); -} -console.log( - `secrets-check: in sync (${environments.join(", ")}; ${strict ? "strict" : "deferred excluded"})`, -); diff --git a/tooling/secrets-sync/escrow.fixture.json b/tooling/secrets-sync/escrow.fixture.json deleted file mode 100644 index c7a481b..0000000 --- a/tooling/secrets-sync/escrow.fixture.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "$comment": "SS1 offline fixture — dummy escrow payloads for PR verify lanes, mirroring the shape of sourceplane/orun-cloud/worker-secrets/. Never put a real value here.", - "stage": { - "identity-worker": { - "GITHUB_OAUTH_CLIENT_SECRET": "fixture-identity-github-stage", - "GOOGLE_OAUTH_CLIENT_SECRET": "fixture-identity-google-stage", - "OAUTH_STATE_SECRET": "fixture-identity-state-stage" - }, - "billing-worker": { - "POLAR_ACCESS_TOKEN": "fixture-billing-token-stage", - "POLAR_WEBHOOK_SECRET": "fixture-billing-webhook-stage" - }, - "webhooks-worker": { - "SECRET_ENCRYPTION_KEY": "fixture-webhooks-key-stage" - }, - "config-worker": { - "SECRET_ENCRYPTION_KEY": "fixture-config-key-stage" - } - }, - "prod": { - "identity-worker": { - "GITHUB_OAUTH_CLIENT_SECRET": "fixture-identity-github-prod", - "GOOGLE_OAUTH_CLIENT_SECRET": "fixture-identity-google-prod", - "OAUTH_STATE_SECRET": "fixture-identity-state-prod" - }, - "billing-worker": { - "POLAR_ACCESS_TOKEN": "fixture-billing-token-prod", - "POLAR_WEBHOOK_SECRET": "fixture-billing-webhook-prod" - }, - "webhooks-worker": { - "SECRET_ENCRYPTION_KEY": "fixture-webhooks-key-prod" - }, - "config-worker": { - "SECRET_ENCRYPTION_KEY": "fixture-config-key-prod" - } - } -} diff --git a/tooling/secrets-sync/integrations.fixture.json b/tooling/secrets-sync/integrations.fixture.json deleted file mode 100644 index 4a6ccf4..0000000 --- a/tooling/secrets-sync/integrations.fixture.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "$comment": "SS6 offline fixture — dummy per-integration documents for PR verify lanes and tests, mirroring the shape of the AWS Secrets Manager documents (one key per integration/platform doc name). Never put a real value here.", - "stage": { - "github-oauth": { - "GITHUB_OAUTH_CLIENT_ID": "fixture-gh-client-id-stage", - "GITHUB_OAUTH_CLIENT_SECRET": "fixture-gh-client-secret-stage" - }, - "google-oauth": { - "GOOGLE_OAUTH_CLIENT_ID": "fixture-google-client-id-stage", - "GOOGLE_OAUTH_CLIENT_SECRET": "fixture-google-client-secret-stage" - }, - "polar": { - "BILLING_PROVIDER": "polar", - "POLAR_SERVER": "sandbox", - "POLAR_PRODUCT_MAP": "{\"pro\":\"fixture-pro\",\"business\":\"fixture-business\"}", - "POLAR_SUCCESS_URL": "https://stage.example.test/", - "POLAR_ACCESS_TOKEN": "fixture-polar-token-stage", - "POLAR_WEBHOOK_SECRET": "fixture-polar-webhook-stage" - }, - "cloudflare-email": { - "NOTIFICATIONS_PROVIDER": "cloudflare-email", - "EMAIL_FROM_ADDRESS": "no-reply@mail.example.test", - "EMAIL_FROM_NAME": "Example" - }, - "platform": { - "SECRET_ENCRYPTION_KEY": "fixture-encryption-key-stage", - "OAUTH_STATE_SECRET": "fixture-oauth-state-stage", - "INTEGRATIONS_STATE_SECRET": "fixture-integrations-state-stage" - } - }, - "prod": { - "github-oauth": { - "GITHUB_OAUTH_CLIENT_ID": "fixture-gh-client-id-prod", - "GITHUB_OAUTH_CLIENT_SECRET": "fixture-gh-client-secret-prod" - }, - "google-oauth": { - "GOOGLE_OAUTH_CLIENT_ID": "fixture-google-client-id-prod", - "GOOGLE_OAUTH_CLIENT_SECRET": "fixture-google-client-secret-prod" - }, - "polar": { - "BILLING_PROVIDER": "polar", - "POLAR_SERVER": "production", - "POLAR_PRODUCT_MAP": "{\"pro\":\"fixture-pro\",\"business\":\"fixture-business\"}", - "POLAR_SUCCESS_URL": "https://app.example.test/", - "POLAR_ACCESS_TOKEN": "fixture-polar-token-prod", - "POLAR_WEBHOOK_SECRET": "fixture-polar-webhook-prod" - }, - "cloudflare-email": { - "NOTIFICATIONS_PROVIDER": "cloudflare-email", - "EMAIL_FROM_ADDRESS": "no-reply@mail.example.test", - "EMAIL_FROM_NAME": "Example" - }, - "platform": { - "SECRET_ENCRYPTION_KEY": "fixture-encryption-key-prod", - "OAUTH_STATE_SECRET": "fixture-oauth-state-prod", - "INTEGRATIONS_STATE_SECRET": "fixture-integrations-state-prod" - } - } -} diff --git a/tooling/secrets-sync/integrations.manifest.json b/tooling/secrets-sync/integrations.manifest.json deleted file mode 100644 index 53f7f80..0000000 --- a/tooling/secrets-sync/integrations.manifest.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "$comment": "SS6 source of truth (saas-secrets-sync): per-integration documents in AWS Secrets Manager, each holding the non-secret config AND the secret(s) for ONE provider integration. Non-integration secrets (repo/account-generated, not tied to a provider) live in a single platform-secrets doc. assemble.mjs projects this into (a) the per-worker secret view committed as secrets.manifest.json and consumed by check.mjs/sync.mjs, and (b) the per-worker config view rendered into wrangler vars. config keys are non-secret and may be logged; secret keys never are.", - "escrowRoot": "sourceplane/lumen", - "environments": ["stage", "prod"], - "deferredConsumers": ["integrations-worker"], - "integrations": { - "github-oauth": { - "doc": "integrations/github-oauth/", - "config": ["GITHUB_OAUTH_CLIENT_ID"], - "secret": ["GITHUB_OAUTH_CLIENT_SECRET"], - "consumers": ["identity-worker"] - }, - "google-oauth": { - "doc": "integrations/google-oauth/", - "config": ["GOOGLE_OAUTH_CLIENT_ID"], - "secret": ["GOOGLE_OAUTH_CLIENT_SECRET"], - "consumers": ["identity-worker"] - }, - "polar": { - "doc": "integrations/polar/", - "config": ["BILLING_PROVIDER", "POLAR_SERVER", "POLAR_PRODUCT_MAP", "POLAR_SUCCESS_URL"], - "secret": ["POLAR_ACCESS_TOKEN", "POLAR_WEBHOOK_SECRET"], - "consumers": ["billing-worker"] - }, - "cloudflare-email": { - "doc": "integrations/cloudflare-email/", - "config": ["NOTIFICATIONS_PROVIDER", "EMAIL_FROM_ADDRESS", "EMAIL_FROM_NAME"], - "secret": [], - "consumers": ["notifications-worker"] - }, - "github-app": { - "doc": "integrations/github-app/", - "config": ["GITHUB_APP_ID", "GITHUB_APP_SLUG", "GITHUB_APP_CLIENT_ID"], - "secret": ["GITHUB_APP_PRIVATE_KEY", "GITHUB_APP_WEBHOOK_SECRET", "GITHUB_APP_CLIENT_SECRET"], - "consumers": ["integrations-worker"], - "deferred": "saas-integrations D1 — GitHub App not yet registered" - } - }, - "platform": { - "doc": "platform-secrets/", - "secret": { - "SECRET_ENCRYPTION_KEY": ["webhooks-worker", "config-worker", "integrations-worker"], - "OAUTH_STATE_SECRET": ["identity-worker"], - "INTEGRATIONS_STATE_SECRET": ["integrations-worker"] - } - } -} diff --git a/tooling/secrets-sync/secrets.manifest.json b/tooling/secrets-sync/secrets.manifest.json deleted file mode 100644 index 1fd0a1d..0000000 --- a/tooling/secrets-sync/secrets.manifest.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "$comment": "GENERATED from integrations.manifest.json by assemble.mjs --project-manifest. Do not edit by hand; edit integrations.manifest.json and regenerate. Per-worker secret view consumed by check.mjs and sync.mjs.", - "escrowPath": "sourceplane/lumen/worker-secrets/", - "environments": [ - "stage", - "prod" - ], - "workers": { - "billing-worker": { - "required": [ - "POLAR_ACCESS_TOKEN", - "POLAR_WEBHOOK_SECRET" - ] - }, - "config-worker": { - "required": [ - "SECRET_ENCRYPTION_KEY" - ] - }, - "identity-worker": { - "required": [ - "GITHUB_OAUTH_CLIENT_SECRET", - "GOOGLE_OAUTH_CLIENT_SECRET", - "OAUTH_STATE_SECRET" - ] - }, - "integrations-worker": { - "required": [], - "deferred": { - "reason": "deferred consumer — activate by removing from manifest.deferredConsumers", - "names": [ - "GITHUB_APP_CLIENT_SECRET", - "GITHUB_APP_PRIVATE_KEY", - "GITHUB_APP_WEBHOOK_SECRET", - "INTEGRATIONS_STATE_SECRET", - "SECRET_ENCRYPTION_KEY" - ] - } - }, - "notifications-worker": { - "required": [] - }, - "webhooks-worker": { - "required": [ - "SECRET_ENCRYPTION_KEY" - ] - } - } -} diff --git a/tooling/secrets-sync/seed.md b/tooling/secrets-sync/seed.md deleted file mode 100644 index 77b4e9b..0000000 --- a/tooling/secrets-sync/seed.md +++ /dev/null @@ -1,74 +0,0 @@ -# SS3/SS6 — Seeding the integration & platform documents (human runbook) - -One-time (per environment) operator action that moves the manually-managed -worker secrets **and** their paired non-secret config into AWS Secrets -Manager. After this, the deploy lane owns Cloudflare-side secrets and config — -never run `wrangler secret put` by hand, and never edit a client ID / product -map in a `wrangler.template.jsonc` again. Rotate by updating the document and -letting the next deploy push it. - -## Storage model (SS6) - -`integrations.manifest.json` is the source of truth. Each **provider -integration** is one document holding its config + secret(s); non-integration -secrets share one **platform** document. - -| Document (per ``) | Keys | -|---|---| -| `sourceplane/lumen/integrations/github-oauth/` | `GITHUB_OAUTH_CLIENT_ID`, `GITHUB_OAUTH_CLIENT_SECRET` | -| `…/integrations/google-oauth/` | `GOOGLE_OAUTH_CLIENT_ID`, `GOOGLE_OAUTH_CLIENT_SECRET` | -| `…/integrations/polar/` | `BILLING_PROVIDER`, `POLAR_SERVER`, `POLAR_PRODUCT_MAP`, `POLAR_SUCCESS_URL`, `POLAR_ACCESS_TOKEN`, `POLAR_WEBHOOK_SECRET` | -| `…/integrations/cloudflare-email/` | `NOTIFICATIONS_PROVIDER`, `EMAIL_FROM_ADDRESS`, `EMAIL_FROM_NAME` (no secret) | -| `…/integrations/github-app/` | GitHub App config + secrets — **deferred** until the App is registered (`saas-integrations` D1) | -| `…/platform-secrets/` | `SECRET_ENCRYPTION_KEY`, `OAUTH_STATE_SECRET`, `INTEGRATIONS_STATE_SECRET` | - -**Critical:** `SECRET_ENCRYPTION_KEY` encrypts data at rest — escrow the value -currently deployed, do NOT generate a new one (a fresh key bricks stored -webhook endpoints and integration tokens). - -## Steps (per environment: stage, then prod) - -1. In a private shell (never a repo checkout, never echoed), build one JSON - file per document above. Use the **current live values**; for config keys, - copy what's in the matching `wrangler.template.jsonc` `vars` today. Shape - for an integration doc, e.g. `github-oauth-stage.json`: - - ```json - { "GITHUB_OAUTH_CLIENT_ID": "Ov23li…", "GITHUB_OAUTH_CLIENT_SECRET": "…" } - ``` - -2. Validate completeness offline (fingerprints only, never values). Drop the - per-doc files into a directory named `.json` (e.g. `github-oauth.json`, - `polar.json`, `platform.json`) and run the projector for that env: - - ```bash - node tooling/secrets-sync/assemble.mjs --env stage \ - --docs-dir /tmp/seed-stage \ - --out-secrets /tmp/ws.json --out-config /tmp/wc.json - # exit 0 = every required key present; non-zero lists what's missing - ``` - -3. Upload each document: - - ```bash - aws secretsmanager create-secret \ - --name sourceplane/lumen/integrations/github-oauth/stage \ - --secret-string file://github-oauth-stage.json - # …repeat for google-oauth, polar, cloudflare-email, and platform-secrets - # (use put-secret-value if the secret already exists) - ``` - -4. Shred the local files: `shred -u *-stage.json`. - -5. Deploy any worker (or merge any PR touching one). The `secrets-live` step - pushes only what changed; first run after seeding pushes everything. - -6. Confirm: the deploy log shows `secrets-live: … pushing N secret(s)`; a - second deploy shows `in sync — nothing to push`. - -## Rotation (after seeding) - -Update the value in the relevant document (`put-secret-value` with the full -updated JSON), then deploy the affected worker. Never touch Cloudflare -directly. For a config change (e.g. a new Polar product id), edit the `polar` -document — no code change, no template edit. diff --git a/tooling/secrets-sync/sync.mjs b/tooling/secrets-sync/sync.mjs deleted file mode 100644 index 2b85cdf..0000000 --- a/tooling/secrets-sync/sync.mjs +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env node -// SS2 secrets-live decision tool (zero-dependency, no cloud access). -// -// Given the committed manifest, one environment's escrow payload (fetched -// from AWS Secrets Manager by the composition's secrets-live step), and the -// previous fingerprint record, decide what to push to Cloudflare for one -// worker. Emits: -// --out-bulk JSON map { SECRET_NAME: value } for `wrangler -// secret bulk` — `{}` when nothing changed -// --out-record updated fingerprint record (worker's entry replaced; -// other workers' entries preserved) -// -// Stdout reports names and truncated SHA-256 fingerprints only — never values. -// The escrow payload existing but missing a required secret is a hard error: -// it blocks the deploy rather than shipping a worker with stale/absent -// secrets. (The step itself skips cleanly when no escrow document exists at -// all — that is the pre-SS3 state.) -// -// Usage: -// node sync.mjs --worker identity-worker --env stage \ -// --escrow /tmp/escrow.json --record /tmp/record.json \ -// --out-bulk /tmp/bulk.json --out-record /tmp/record.out.json \ -// [--manifest secrets.manifest.json] -// -// Exit codes: 0 ok (bulk may be empty) · 1 escrow violations · 2 usage/config. - -import * as fs from "node:fs"; -import * as path from "node:path"; -import { createHash } from "node:crypto"; -import { fileURLToPath } from "node:url"; - -function arg(name) { - const i = process.argv.indexOf(`--${name}`); - return i >= 0 ? process.argv[i + 1] : undefined; -} - -const worker = arg("worker"); -const env = arg("env"); -const escrowPath = arg("escrow"); -const recordPath = arg("record"); -const outBulkPath = arg("out-bulk"); -const outRecordPath = arg("out-record"); -const manifestPath = - arg("manifest") ?? - path.join(path.dirname(fileURLToPath(import.meta.url)), "secrets.manifest.json"); - -if (!worker || !env || !escrowPath || !recordPath || !outBulkPath || !outRecordPath) { - console.error( - "usage: sync.mjs --worker --env --escrow --record --out-bulk --out-record [--manifest ]", - ); - process.exit(2); -} - -function readJson(file, fallback) { - if (fallback !== undefined && !fs.existsSync(file)) return fallback; - try { - return JSON.parse(fs.readFileSync(file, "utf8")); - } catch (err) { - console.error(`secrets-sync: cannot read ${file}: ${err.message}`); - process.exit(2); - } -} - -const manifest = readJson(manifestPath); -const spec = manifest.workers?.[worker]; -if (!spec) { - console.error( - `secrets-sync: worker ${worker} is not declared in ${manifestPath} — set the component's secretsWorker to a manifest key or add the worker to the manifest`, - ); - process.exit(2); -} -if (!(manifest.environments ?? []).includes(env)) { - console.error(`secrets-sync: environment ${env} is not declared in the manifest`); - process.exit(2); -} - -const required = spec.required ?? []; -const escrow = readJson(escrowPath); -const record = readJson(recordPath, {}); -const payload = escrow[worker] ?? {}; -const fingerprint = (value) => - createHash("sha256").update(String(value)).digest("hex").slice(0, 16); - -const violations = []; -for (const name of required) { - const value = payload[name]; - if (value === undefined) violations.push(`missing ${name} in escrow ${env}/${worker}`); - else if (typeof value !== "string" || value.length === 0) - violations.push(`${name} is empty or not a string in escrow ${env}/${worker}`); -} -if (violations.length > 0) { - console.error(`secrets-sync: ${violations.length} escrow violation(s):`); - for (const v of violations) console.error(` - ${v}`); - process.exit(1); -} - -const fingerprints = Object.fromEntries( - required.map((name) => [name, fingerprint(payload[name])]), -); -const previous = record[worker] ?? {}; -const changed = required.filter((name) => previous[name] !== fingerprints[name]); - -for (const name of required) { - const marker = changed.includes(name) ? "changed" : "unchanged"; - console.log(`secrets-sync: ${env}/${worker}: ${name} sha256:${fingerprints[name]} (${marker})`); -} - -const bulk = - changed.length === 0 - ? {} - : Object.fromEntries(required.map((name) => [name, payload[name]])); -fs.writeFileSync(outBulkPath, JSON.stringify(bulk)); -fs.writeFileSync( - outRecordPath, - JSON.stringify({ ...record, [worker]: fingerprints }, null, 2), -); -console.log( - changed.length === 0 - ? `secrets-sync: ${env}/${worker}: in sync — nothing to push` - : `secrets-sync: ${env}/${worker}: ${changed.length} change(s) — pushing ${required.length} secret(s)`, -);