diff --git a/infra/terraform/cloudflare-d1/component.yaml b/infra/terraform/cloudflare-d1/component.yaml new file mode 100644 index 0000000..c1e3b4d --- /dev/null +++ b/infra/terraform/cloudflare-d1/component.yaml @@ -0,0 +1,52 @@ +apiVersion: sourceplane.io/v1 +kind: Component + +metadata: + name: cloudflare-d1 + description: Provisions the Cloudflare D1 platform database for stage and prod + labels: + domain: infra + scope: runtime-database + +spec: + type: terraform + lifecycle: production + owner: platform + domain: infra + + parameters: + orgName: sourceplane + stackName: cloudflare-d1 + terraformDir: terraform + terraformVersion: "1.15.3" + # SEC-JOB: the wiring document (database id/name) is lease-published + # post-apply; worker deploys read it back as WIRING_CLOUDFLARE_D1_, + # and db-migrate reads it to find the database it migrates. + secretOutputs: "WIRING_CLOUDFLARE_D1=wiring" + + # The Cloudflare Terraform provider authenticates via the CLOUDFLARE_API_TOKEN + # env var, resolved by orun from the project-rung brokered secret — minted + # fresh per run from the d1-edit template (D1 Write; the workers-deploy token + # deliberately cannot touch D1). Declared at component level because + # plan-only lanes refresh against the live Cloudflare API too, not just apply. + secretEnv: + CLOUDFLARE_API_TOKEN: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/{{ .environment }}/CLOUDFLARE_D1_TOKEN" + # Non-secret connection fact (account-id template). + CLOUDFLARE_ACCOUNT_ID: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + TF_VAR_cloudflare_account_id: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + + subscribe: + environments: + - 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 diff --git a/infra/terraform/cloudflare-d1/docs/architecture.md b/infra/terraform/cloudflare-d1/docs/architecture.md new file mode 100644 index 0000000..313da8f --- /dev/null +++ b/infra/terraform/cloudflare-d1/docs/architecture.md @@ -0,0 +1,14 @@ +# cloudflare-d1 — architecture + +A `terraform` component rooted at `infra/terraform/cloudflare-d1/terraform`. + +- **State** lives in the platform's HTTP state backend (run-token auth) — + no local state, no cloud-vendor state buckets. +- **Credentials are brokered per run** from the workspace's Cloudflare + connection; no long-lived provider secrets exist anywhere in CI. +- **Outputs are published as job-output secrets** on the environment + rungs: `WIRING_CLOUDFLARE_D1` (database id/name for deploy-time binding). Downstream deploy lanes resolve them by name. +- **Self-healing adoption** (`adopt.tf`): when the platform state is + empty but the resource already exists at the provider, plan-time import + adopts it instead of failing with "already exists" — safe re-bootstrap + over half-torn-down attempts. diff --git a/infra/terraform/cloudflare-d1/docs/overview.md b/infra/terraform/cloudflare-d1/docs/overview.md new file mode 100644 index 0000000..0038326 --- /dev/null +++ b/infra/terraform/cloudflare-d1/docs/overview.md @@ -0,0 +1,16 @@ +# cloudflare-d1 + +Provisions the Cloudflare D1 platform database for stage and prod + +Terraform-managed infrastructure for new-test, per environment (`stage`, `prod`; `dev` is verify-only and provisions nothing). + +## Depends on + +- (none) + +## Depended on by + +- **admin-worker** — Internal Cloudflare Worker for audited support/administration diagnostics +- **api-edge** — Cloudflare Worker for the API edge Runtime +- **db-migrate** — Applies database migrations to the stage and prod Cloudflare D1 databases +- **identity-worker** — Cloudflare Worker for the Identity auth runtime diff --git a/infra/terraform/cloudflare-d1/docs/runbook.md b/infra/terraform/cloudflare-d1/docs/runbook.md new file mode 100644 index 0000000..843684f --- /dev/null +++ b/infra/terraform/cloudflare-d1/docs/runbook.md @@ -0,0 +1,35 @@ +# cloudflare-d1 — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +```bash +# published outputs (names only, per environment) +orun secrets list --org --env stage +orun secrets list --org --env prod +``` + +## Common failures + +- **"Resource already exists" with empty platform state**: adoption + (`adopt.tf`) imports at plan time; if a root lacks adoption the + resource must be state-migrated or deleted. +- **Provider auth failure**: the workspace's Cloudflare connection is + missing or revoked — reconnect it in the console; secrets are brokered + from it per run. +- **`Authentication error (10000)` on a D1 resource**: the lane resolved + the `workers-deploy` token, which deliberately cannot touch D1 — bind + `CLOUDFLARE_D1_TOKEN` (the `d1-edit` template) instead. diff --git a/infra/terraform/cloudflare-d1/terraform/adopt.tf b/infra/terraform/cloudflare-d1/terraform/adopt.tf new file mode 100644 index 0000000..08407cd --- /dev/null +++ b/infra/terraform/cloudflare-d1/terraform/adopt.tf @@ -0,0 +1,43 @@ +# --- Self-healing adoption --- +# +# When the platform state does not yet track the database but Cloudflare +# already has one under this name (a re-bootstrap after a torn-down workspace, +# or state recovered onto a fresh backend), the create would collide with the +# duplicate-name guard. Instead: look the database up at plan time with the +# job's brokered credentials and import it. Fresh products resolve to id = "" +# and create normally, and a resource already tracked in state short-circuits +# the lookup — so this block is inert everywhere except the one case it exists +# for. Both lookups run inside the job: process env carries the brokered +# CLOUDFLARE_API_TOKEN/CLOUDFLARE_ACCOUNT_ID and the TF_HTTP_* state +# credentials, so no extra secrets are needed. + +data "external" "adopt_platform_database" { + program = ["bash", "-c", <<-EOT + set -euo pipefail + name="$(jq -r .name)" + state_file="$(mktemp)" + trap 'rm -f "$state_file"' EXIT + code="$(curl -s -o "$state_file" -w '%%{http_code}' \ + -u "$TF_HTTP_USERNAME:$TF_HTTP_PASSWORD" "$TF_HTTP_ADDRESS" || echo 000)" + if [ "$code" = "200" ] && jq -e \ + '[.resources[]? | select(.type == "cloudflare_d1_database" and .name == "platform")] | length > 0' \ + "$state_file" >/dev/null 2>&1; then + jq -n '{id: ""}' + exit 0 + fi + resp="$(curl -fsS --retry 3 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/d1/database?per_page=100")" + printf '%s' "$resp" | jq -c --arg n "$name" \ + '{id: ([.result[] | select(.name == $n) | .uuid] | first // "")}' + EOT + ] + query = { + name = local.database_name + } +} + +import { + for_each = toset(compact([data.external.adopt_platform_database.result.id])) + to = cloudflare_d1_database.platform + id = "${var.cloudflare_account_id}/${each.value}" +} diff --git a/infra/terraform/cloudflare-d1/terraform/backend.tf b/infra/terraform/cloudflare-d1/terraform/backend.tf new file mode 100644 index 0000000..ff89f5f --- /dev/null +++ b/infra/terraform/cloudflare-d1/terraform/backend.tf @@ -0,0 +1,5 @@ +# Terraform backend configuration is provided by Orun at runtime +# through environment variables and automatic backend initialization. +# +# S3 backend details are set via CLI args in the Orun runner. +# Local placeholder file for clarity. diff --git a/infra/terraform/cloudflare-d1/terraform/main.tf b/infra/terraform/cloudflare-d1/terraform/main.tf new file mode 100644 index 0000000..e2b8f3e --- /dev/null +++ b/infra/terraform/cloudflare-d1/terraform/main.tf @@ -0,0 +1,143 @@ +terraform { + required_version = ">= 1.15.0" + + # 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 { + cloudflare = { + source = "cloudflare/cloudflare" + version = "~> 4.30" + } + external = { + source = "hashicorp/external" + version = "~> 2.3" + } + } +} + +# --- Providers --- + +# 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. +provider "cloudflare" {} + +# --- Variables (standard Orun parameters) --- + +variable "cloudflare_account_id" { + type = string + sensitive = true + default = "" + description = "Cloudflare account ID (from CLOUDFLARE_ACCOUNT_ID env var)" +} + +variable "orgName" { + type = string + default = "sourceplane" +} + +variable "owner" { + type = string + default = "sourceplane" +} + +variable "repo" { + type = string + default = "new-test" +} + +variable "namespace" { + type = string + default = "sourceplane" +} + +variable "namespacePrefix" { + type = string + default = "" +} + +variable "lane" { + type = string + default = "verify" +} + +variable "environment" { + type = string + default = "stage" +} + +variable "component" { + type = string + default = "cloudflare-d1" +} + +variable "stackName" { + type = string + default = "cloudflare-d1" +} + +variable "terraformDir" { + type = string + default = "terraform" +} + +variable "terraformVersion" { + type = string + default = "1.15.3" +} + +# --- The platform database --- +# +# One D1 database per environment holds every bounded context's tables. They +# are separated by name prefix (`identity_users`, `membership_organizations`, +# …) rather than by Postgres schema, because SQLite has no schemas — the +# bounded-context boundary is enforced in the repositories, as it always was. +# +# Why one database and not one per context: D1 offers no cross-database query +# or foreign key, and the console's read paths join across contexts (an org's +# members and their user records, an invoice and its subscription). Splitting +# would move those joins into the workers, which is a much larger change than +# the isolation is worth at this size. + +locals { + # Brand-namespaced with var.repo so the name is unique to this fork. D1 + # database names are unique per account, and a fork may share an account with + # the baseline. Workers resolve the database by ID through the wiring secret, + # so the name is free to change. + database_name = "${var.namespacePrefix}${var.repo}-${var.environment}" +} + +resource "cloudflare_d1_database" "platform" { + account_id = var.cloudflare_account_id + name = local.database_name +} + +# --- Wiring manifest (BF5, via orun secrets) --- +# +# The consumable outputs are published by the composition's wire-secrets step +# as the WIRING_CLOUDFLARE_D1 secret on the project/{{env}} rung; worker +# deploys read it back as WIRING_CLOUDFLARE_D1_ secretEnv and render the +# committed @@wiring(...)@@ tokens from it (BF6). The `db-migrate` component +# reads the same document to find the database it migrates. + +output "wiring" { + description = "Wiring document for downstream deploy-time binding resolution (pushed to orun secrets)" + value = jsonencode({ + d1_database_id = cloudflare_d1_database.platform.id + d1_database_name = cloudflare_d1_database.platform.name + }) +} + +# --- Outputs (non-secret) --- + +output "d1_database_id" { + description = "Cloudflare D1 database ID (the Workers binding's database_id)" + value = cloudflare_d1_database.platform.id +} + +output "d1_database_name" { + description = "Cloudflare D1 database name (human-readable identifier)" + value = cloudflare_d1_database.platform.name +} diff --git a/infra/terraform/cloudflare-d1/terraform/outputs.tf b/infra/terraform/cloudflare-d1/terraform/outputs.tf new file mode 100644 index 0000000..9653334 --- /dev/null +++ b/infra/terraform/cloudflare-d1/terraform/outputs.tf @@ -0,0 +1,2 @@ +# Output definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/infra/terraform/cloudflare-d1/terraform/variables.tf b/infra/terraform/cloudflare-d1/terraform/variables.tf new file mode 100644 index 0000000..9c92c69 --- /dev/null +++ b/infra/terraform/cloudflare-d1/terraform/variables.tf @@ -0,0 +1,2 @@ +# Variable definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/infra/terraform/cloudflare-kv/README.md b/infra/terraform/cloudflare-kv/README.md new file mode 100644 index 0000000..2058775 --- /dev/null +++ b/infra/terraform/cloudflare-kv/README.md @@ -0,0 +1,201 @@ +# cloudflare-kv + +Provisions Cloudflare Workers KV namespaces consumed by the `api-edge` Worker. +Today the slice ships exactly one logical store: the **api-edge idempotency +replay store** introduced in Task 0095, which closes the open-risks entry +where a duplicate POST with a valid `Idempotency-Key` could still create +duplicate pending invitations. + +This component is the first KV slice in the monorepo. Future KV-backed +features (rate limiting, short-lived caches) will land here as additional +`cloudflare_workers_kv_namespace` resources rather than parallel slices, so +backend / provider configuration stays in one place. + +## Overview + +- **What it provisions:** one Workers KV namespace per environment + (`stage`, `prod`), titled `${namespacePrefix}api-edge-idempotency-${environment}` + (e.g. `stg-api-edge-idempotency-stage`, `prod-api-edge-idempotency-prod`). +- **What consumes it:** `apps/api-edge` binds the namespace as + `IDEMPOTENCY_KV` in `wrangler.jsonc` (env.stage, env.prod). `env.dev` does + NOT receive a binding — dev is a verify-only profile, no live worker. KV + absence on a runtime path degrades to "execute downstream once, no + replay" — never 5xx — by design (see api-edge `idempotency.ts`). +- **TTL:** there is no Terraform-side TTL on a KV namespace; entries are + TTL'd per `put()` call from the Worker (`expirationTtl: 86400`, 24h). + +## Architecture + +``` + ┌─────────────────────┐ +POST → │ api-edge Worker │ ──── parseIdempotencyKey() (Task 0094) + └──────────┬──────────┘ + │ + │ replayOrExecute(req, requestId, env, downstream) + │ + ▼ + ┌─────────────────────┐ (kv hit) → reconstructed Response + │ IDEMPOTENCY_KV │ ◀──┐ + │ (Cloudflare KV) │ │ + └──────────┬──────────┘ │ + │ (kv miss) │ put(envelope, ttl=86400) + ▼ │ + downstream worker fetch ──┘ +``` + +Key shape: `idem:v1:{orgId|"anon"}:{routePath}:{idempotencyKey}` truncated ++ SHA-256 fingerprinted to fit Cloudflare's 512-byte KV key cap. +Value: JSON envelope `{ status, headers (allow-listed), body, contentType, +bodyEncoding: "utf8"|"base64", storedAt, requestId }`. + +## Resources Created + +| Resource | Per-env | Description | +|---|---|---| +| `cloudflare_workers_kv_namespace.api_edge_idempotency` | stage, prod | KV namespace bound to the `api-edge` Worker as `IDEMPOTENCY_KV` | + +## Parameters + +Standard Orun parameters (matching `cloudflare-hyperdrive`): + +| Name | Type | Default | Description | +|---|---|---|---| +| `awsRegion` | string | `us-east-1` | AWS region for Terraform state backend | +| `cloudflare_account_id` | string (sensitive) | `""` | From `CLOUDFLARE_ACCOUNT_ID` env var | +| `orgName` | string | `new-test` | Org identifier | +| `owner` | string | `new-test` | GitHub owner | +| `repo` | string | `new-test` | GitHub repo | +| `namespace` | string | `new-test` | Logical namespace | +| `namespacePrefix` | string | `""` | Stage/prod prefix (`stg-`, `prod-`) | +| `lane` | string | `verify` | Orun lane | +| `environment` | string | `stage` | Target environment | +| `component` | string | `cloudflare-kv` | Component identifier | +| `stackName` | string | `cloudflare-kv` | Stack identifier | +| `terraformDir` | string | `terraform` | Terraform module dir | +| `terraformVersion` | string | `1.15.3` | Terraform version | + +## Outputs + +| Output | Description | Use | +|---|---|---| +| `api_edge_idempotency_kv_id` | KV namespace ID | Referenced from `apps/api-edge/wrangler.jsonc` `kv_namespaces[*].id` | +| `api_edge_idempotency_kv_title` | KV namespace title (human-readable) | Cross-checked by the verifier via `wrangler kv namespace list` | + +## Dependencies + +- **Cloudflare credentials**: `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID` + must be in scope (Orun CI provides them; locally they come from your + shell). The token needs Workers KV write permission on the target + account. +- **No upstream Terraform component**: this slice does not consume any + AWS Secrets Manager value or other component output. It is a peer of + `cloudflare-hyperdrive`, not a downstream consumer. + +## Environments + +| Environment | Profile (default) | Profile (push-main) | Notes | +|---|---|---|---| +| `stage` | `plan-only` | `apply` | Plan on PR, apply on merge | +| `prod` | `plan-only` | `apply` | Plan on PR, apply on merge | +| `dev` | n/a | n/a | Not subscribed; api-edge dev profile has no KV binding | + +`prod` waits on `stage` per `intent.yaml#environments.prod.promotion.dependsOn`. + +## Secret Storage + +- KV namespace IDs are NOT secrets and are surfaced as Terraform outputs + + embedded in `apps/api-edge/wrangler.jsonc`. +- The Cloudflare API token / account ID stay sensitive Terraform variables; + never logged, never echoed to outputs. +- KV value contents (response bodies) are stored encrypted at rest by + Cloudflare. The api-edge Worker enforces a header allow-list before + storing, so caller-controlled `set-cookie` / `authorization` headers + never reach the cache. + +## Configuration Details + +- **Provider pin**: `cloudflare ~> 4.30` — matches the repo posture + (`cloudflare-hyperdrive` resolves to `4.52.7`). The deferred Task 0085b + v4→v5 upgrade owns the migration. **Do not edit the pin here.** +- **AWS provider pin**: `aws ~> 5.0`, again matching peer slices. +- **Terraform backend**: shared S3 backend, key supplied at runtime by Orun + (`workspace_key_prefix = "env"`). +- **TTL**: no namespace-level TTL exists in the Cloudflare KV API; per-PUT + TTL is the only knob, owned by the Worker. + +## Usage in Downstream Tasks + +The Worker reads `env.IDEMPOTENCY_KV` and treats the binding as optional — +absence falls through to "execute downstream, no replay." This means the +slice can be created idempotently before or after the api-edge bindings +land; the cutover is purely additive. + +## Local Verification + +```bash +# Validate intent +kiox exec -- orun validate + +# Discover component +kiox exec -- orun component | grep cloudflare-kv + +# Plan (dry) +kiox exec -- orun plan --intent intent.yaml --output plan.json + +# Inspect plan +cat plan.json | jq '.jobs[] | select(.component == "cloudflare-kv") | {id, profile}' + +# Dry run +kiox exec -- orun run --plan plan.json --dry-run --runner github-actions + +# Terraform fmt check +terraform -chdir=infra/terraform/cloudflare-kv/terraform fmt -check +``` + +## Operational Notes + +- **Scaling limits**: Workers KV gives you 1 GB per namespace and ~25 MB + per value. Idempotency envelopes are small (kilobytes); we are + comfortably below. +- **Read latency**: ~50ms p99 globally, eventually consistent within a + region (Cloudflare-published). Stripe accepts this window. +- **Backup / restore**: KV is best-effort cache by design. Loss of a + namespace re-opens the Task 0094 risk window (duplicate POSTs may + re-execute) but does NOT corrupt persisted data — invitations, + memberships, etc., live in Postgres behind the workers. + +## Troubleshooting + +| Symptom | Likely cause | Fix | +|---|---|---| +| `Error: required field is not set` on `account_id` | `CLOUDFLARE_ACCOUNT_ID` not in env | Export `CLOUDFLARE_ACCOUNT_ID` (Orun CI does this automatically) | +| `Error: 10000: Authentication error` | Token lacks Workers KV scope | Issue a new API token with `Workers KV Storage: Edit` | +| Plan shows `0 components × N envs → 0 jobs` | Component not subscribed to PR-active env | Verify `subscribe.environments` matches `intent.yaml#environments.*.activation` | +| Wrangler `kv namespace list` doesn't show the namespace | apply didn't run, or wrong CF account | Run `kiox exec -- orun plan --intent intent.yaml` and confirm an apply job exists for the env | + +## Security + +- Credentials: `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID` only via env + vars; never committed. +- State: encrypted S3 backend with use_lockfile = true. +- Audit: namespace creation visible in Cloudflare dashboard audit log. +- Compliance: KV is multi-region replicated; no PII is intentionally cached + (header allow-list enforced in Worker). + +## Related Tasks + +- **Task 0009**: `cloudflare-hyperdrive` — pattern template for this slice. +- **Task 0090**: notifications-worker queue-level idempotency (separate + layer, Postgres column; do not conflate). +- **Task 0094**: edge `Idempotency-Key` validation gate — landed the parser + consumed by this replay store. +- **Task 0095** (this task): adds the durable replay store on top. +- **Task 0085b** (deferred): cloudflare provider v4→v5 migration. Do NOT + bump this slice's pin until that task lands. + +## References + +- Cloudflare Workers KV: https://developers.cloudflare.com/kv/ +- Stripe Idempotency-Key contract: https://stripe.com/docs/api/idempotent_requests +- Orun Terraform component spec: see the `terraform` composition in the + [stack-tectonic](https://github.com/sourceplane/stack-tectonic) catalog diff --git a/infra/terraform/cloudflare-kv/component.yaml b/infra/terraform/cloudflare-kv/component.yaml new file mode 100644 index 0000000..dcaf5ba --- /dev/null +++ b/infra/terraform/cloudflare-kv/component.yaml @@ -0,0 +1,52 @@ +apiVersion: sourceplane.io/v1 +kind: Component + +metadata: + name: cloudflare-kv + description: Provisions Cloudflare KV namespaces backing the api-edge idempotency replay store (stage and prod) + labels: + domain: infra + scope: edge-idempotency-replay-store + +spec: + type: terraform + lifecycle: production + owner: platform + domain: infra + + parameters: + orgName: sourceplane + stackName: cloudflare-kv + terraformDir: terraform + terraformVersion: "1.15.3" + # 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 + # run, Deploy Workers scope). Declared at component level because plan-only + # lanes refresh against the live Cloudflare API too, not just apply. + secretEnv: + CLOUDFLARE_API_TOKEN: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/{{ .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://org_c126e518fd9b4cae9706f760c9f8551b/new-test/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + TF_VAR_cloudflare_account_id: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + + subscribe: + environments: + - 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: re-trigger kv apply with brand-namespaced title (baseline collision fix) diff --git a/infra/terraform/cloudflare-kv/docs/architecture.md b/infra/terraform/cloudflare-kv/docs/architecture.md new file mode 100644 index 0000000..cf7f4ed --- /dev/null +++ b/infra/terraform/cloudflare-kv/docs/architecture.md @@ -0,0 +1,14 @@ +# cloudflare-kv — architecture + +A `terraform` component rooted at `infra/terraform/cloudflare-kv/terraform`. + +- **State** lives in the platform's HTTP state backend (run-token auth) — + no local state, no cloud-vendor state buckets. +- **Credentials are brokered per run** from the workspace's Cloudflare + connection; no long-lived provider secrets exist anywhere in CI. +- **Outputs are published as job-output secrets** on the environment + rungs: `WIRING_CLOUDFLARE_KV` (namespace id/title for deploy-time binding). Downstream deploy lanes resolve them by name. +- **Self-healing adoption** (`adopt.tf`): when the platform state is + empty but the resource already exists at the provider, plan-time import + adopts it instead of failing with "already exists" — safe re-bootstrap + over half-torn-down attempts. diff --git a/infra/terraform/cloudflare-kv/docs/overview.md b/infra/terraform/cloudflare-kv/docs/overview.md new file mode 100644 index 0000000..2f8086e --- /dev/null +++ b/infra/terraform/cloudflare-kv/docs/overview.md @@ -0,0 +1,13 @@ +# cloudflare-kv + +Provisions Cloudflare KV namespaces backing the api-edge idempotency replay store (stage and prod) + +Terraform-managed infrastructure for new-test, per environment (`stage`, `prod`; `dev` is verify-only and provisions nothing). + +## Depends on + +- (none) + +## Depended on by + +- **api-edge** — Cloudflare Worker for the API edge Runtime diff --git a/infra/terraform/cloudflare-kv/docs/runbook.md b/infra/terraform/cloudflare-kv/docs/runbook.md new file mode 100644 index 0000000..a1dbc8d --- /dev/null +++ b/infra/terraform/cloudflare-kv/docs/runbook.md @@ -0,0 +1,35 @@ +# cloudflare-kv — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +```bash +# published outputs (names only, per environment) +orun secrets list --org --env stage +orun secrets list --org --env prod +``` + +## Common failures + +- **"Resource already exists" with empty platform state**: adoption + (`adopt.tf`) imports at plan time; if a root lacks adoption the + resource must be state-migrated or deleted. +- **Provider auth failure**: the workspace's Cloudflare connection is + missing or revoked — reconnect it in the console; secrets are brokered + from it per run. +- **`Authentication error (10000)` on a D1 resource**: the lane resolved + the `workers-deploy` token, which deliberately cannot touch D1 — bind + `CLOUDFLARE_D1_TOKEN` (the `d1-edit` template) instead. diff --git a/infra/terraform/cloudflare-kv/terraform/.terraform.lock.hcl b/infra/terraform/cloudflare-kv/terraform/.terraform.lock.hcl new file mode 100644 index 0000000..c133371 --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/.terraform.lock.hcl @@ -0,0 +1,50 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/cloudflare/cloudflare" { + version = "4.52.7" + constraints = "~> 4.30" + hashes = [ + "h1:pPItIWii5oymR+geZB219ROSPuSODPLTlM4S/u8xLvM=", + "h1:uUUa9dY0XQOycI8pxg16PFFtL0WCTi9uEJz8trTQ7pU=", + "h1:y3rV8KF2q6GEMANNlf5EkKJurlfbKlIKpjGcdxoy7pQ=", + "zh:0c904ce31a4c6c4a5b3bf7ff1560e77c0cc7e2450c8553ded8e8c90398e1418b", + "zh:36183d310c36373fe4cb936b83c595c6fd3b0a94bc7827f28e5789ccbf59752e", + "zh:556a568a6f0235e8f41647de9e4d3a1e7b1d6502df8b19b54ec441f1c653ea10", + "zh:633ebbd5b0245e75e500ef9be4d9e62288f97e8da3baaa51323892a786d90285", + "zh:6acfe60cf52a65ba8f044f748548d2119e7f4fd7f8ebcb14698960d87c68f529", + "zh:890df766e9b839623b1f0437355032a3c006226a6c200cd911e15ee1a9014e9f", + "zh:904acc31ebb9d6ef68c792074b30532ee61bf515f19e0a3c75b46f126cca1f13", + "zh:a1d0a81246afc8750286d3f6fe7a8fbe6460dd2662407b28dbfbabb612e5fa9d", + "zh:a41a36fe253fc365fe2b7ffc749624688b2693b4634862fda161179ab100029f", + "zh:a7ef269e77ffa8715c8945a2c14322c7ff159ea44c15f62505f3cbb2cae3b32d", + "zh:b01aa3bed30610633b762df64332b26f8844a68c3960cebcb30f04918efc67fe", + "zh:b069cc2cd18cae10757df3ae030508eac8d55de7e49eda7a5e3e11f2f7fe6455", + "zh:b2d2c6313729ebb7465dceece374049e2d08bda34473901be9ff46a8836d42b2", + "zh:db0e114edaf4bc2f3d4769958807c83022bfbc619a00bdf4c4bd17faa4ab2d8b", + "zh:ecc0aa8b9044f664fd2aaf8fa992d976578f78478980555b4b8f6148e8d1a5fe", + ] +} + +provider "registry.terraform.io/hashicorp/external" { + version = "2.4.0" + constraints = "~> 2.3" + hashes = [ + "h1:AmY6ZeIvqoTT5ZjzD+P49PeQH6Va1QLMkX+7MUQfYoA=", + "h1:K0eLC86zbhVoyS4THmY00KJZKAQORuz6dt9Ro3xo/wA=", + "h1:gXyK3ZkweDqkwEV9waEDWpljUY4yZXi/nRUSEuJn83k=", + "zh:0772afb42b658468ac5e15df33bf2080456f8f0b8ab163bfe9c50d2b2ea02135", + "zh:0ac31a9aaa43dfcff5944b791596cdc94e153348e4bb4642282d034dff548134", + "zh:32d8492b1bdcc956ca3c6d00c6392d0a83942ff11d4820c7ee63ca6796e06950", + "zh:3c0482e894429f528ce6655a76ab0d8a9f7c0dacc6c828865e1515d4a7dbb852", + "zh:61e68100b4db2f930b31491f23c602126382fd5e51252be1b551f0e17f8ddbee", + "zh:6d60f615a0ad85eb962c9eb94f25e3eba7a72684ce276ba5dfb23f36b295a8f8", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:9ced2745eb5f1346203027d2dd7bf856ad1d279a25730ff7dbc6eec187aaca0c", + "zh:a8378558a177d43f55aa0d79d4fae91a704695122a1b109668c1daa8fb76f09d", + "zh:aadd98086133d3ebea67437d56512fdcc6dfb3bd34dfc23f276c0db9272e27b4", + "zh:beff701b653841e70441978137768f54e7dc6c27e7bf12a4589087f01f5bbcee", + "zh:c91c2223b29fdbc0044d20e1936ccc051d010727a13f2ff1e75e51f09bff33a3", + "zh:d491f9c2d32a39dc4031628469ae7c8aec0074312a7c1f0286b173cdcf854a54", + ] +} diff --git a/infra/terraform/cloudflare-kv/terraform/adopt.tf b/infra/terraform/cloudflare-kv/terraform/adopt.tf new file mode 100644 index 0000000..54882dc --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/adopt.tf @@ -0,0 +1,43 @@ +# --- Self-healing adoption (AWS-free state seeding) --- +# +# When the platform state does not yet track the namespace but Cloudflare +# already has one under this title (a baseline whose state predates the +# platform backend, or a recovered workspace), the create would collide with +# the duplicate-title guard (error 10014). Instead: look the namespace up at +# plan time with the job's brokered credentials and import it. Fresh products +# resolve to id = "" and create normally, and a resource already tracked in +# state short-circuits the lookup — so this block is inert everywhere except +# the one case it exists for. Both lookups run inside the job: process env +# carries the brokered CLOUDFLARE_API_TOKEN/CLOUDFLARE_ACCOUNT_ID and the +# TF_HTTP_* state credentials, so no extra secrets and no AWS access. + +data "external" "adopt_idempotency_namespace" { + program = ["bash", "-c", <<-EOT + set -euo pipefail + title="$(jq -r .title)" + state_file="$(mktemp)" + trap 'rm -f "$state_file"' EXIT + code="$(curl -s -o "$state_file" -w '%%{http_code}' \ + -u "$TF_HTTP_USERNAME:$TF_HTTP_PASSWORD" "$TF_HTTP_ADDRESS" || echo 000)" + if [ "$code" = "200" ] && jq -e \ + '[.resources[]? | select(.type == "cloudflare_workers_kv_namespace" and .name == "api_edge_idempotency")] | length > 0' \ + "$state_file" >/dev/null 2>&1; then + jq -n '{id: ""}' + exit 0 + fi + resp="$(curl -fsS --retry 3 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/storage/kv/namespaces?per_page=100")" + printf '%s' "$resp" | jq -c --arg t "$title" \ + '{id: ([.result[] | select(.title == $t) | .id] | first // "")}' + EOT + ] + query = { + title = local.idempotency_namespace_title + } +} + +import { + for_each = toset(compact([data.external.adopt_idempotency_namespace.result.id])) + to = cloudflare_workers_kv_namespace.api_edge_idempotency + id = "${var.cloudflare_account_id}/${each.value}" +} diff --git a/infra/terraform/cloudflare-kv/terraform/backend.tf b/infra/terraform/cloudflare-kv/terraform/backend.tf new file mode 100644 index 0000000..ff89f5f --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/backend.tf @@ -0,0 +1,5 @@ +# Terraform backend configuration is provided by Orun at runtime +# through environment variables and automatic backend initialization. +# +# S3 backend details are set via CLI args in the Orun runner. +# Local placeholder file for clarity. diff --git a/infra/terraform/cloudflare-kv/terraform/main.tf b/infra/terraform/cloudflare-kv/terraform/main.tf new file mode 100644 index 0000000..8c315af --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/main.tf @@ -0,0 +1,137 @@ +terraform { + required_version = ">= 1.15.0" + + # 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 { + cloudflare = { + source = "cloudflare/cloudflare" + version = "~> 4.30" + } + external = { + source = "hashicorp/external" + version = "~> 2.3" + } + } +} + +# --- Providers --- + +# 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. +provider "cloudflare" {} + +# --- Variables (standard Orun parameters) --- + +variable "cloudflare_account_id" { + type = string + sensitive = true + default = "" + description = "Cloudflare account ID (from CLOUDFLARE_ACCOUNT_ID env var)" +} + +variable "orgName" { + type = string + default = "sourceplane" +} + +variable "owner" { + type = string + default = "sourceplane" +} + +variable "repo" { + type = string + default = "new-test" +} + +variable "namespace" { + type = string + default = "sourceplane" +} + +variable "namespacePrefix" { + type = string + default = "" +} + +variable "lane" { + type = string + default = "verify" +} + +variable "environment" { + type = string + default = "stage" +} + +variable "component" { + type = string + default = "cloudflare-kv" +} + +variable "stackName" { + type = string + default = "cloudflare-kv" +} + +variable "terraformDir" { + type = string + default = "terraform" +} + +variable "terraformVersion" { + type = string + default = "1.15.3" +} + +# --- KV namespace for api-edge idempotency replay store --- +# +# Backs the Stripe-style idempotency replay store added in Task 0095. Keys are +# scoped (orgId|"anon", routePath, idempotencyKey) and entries TTL'd via the +# api-edge Worker (`expirationTtl: 86400`); no Terraform-side TTL knob exists +# for KV namespaces themselves — TTL is per-PUT, owned by the Worker. + +locals { + # Brand-namespaced with var.repo so the title is unique to this fork. Cloudflare + # KV namespace titles must be unique per account, and this fork shares an account + # with the baseline (which uses the un-branded title) — without the brand the + # create fails with "a namespace with this account ID and title already exists" + # (10014). Workers resolve this KV by ID via the wiring secret, so the title is + # free to change. + idempotency_namespace_title = "${var.namespacePrefix}${var.repo}-api-edge-idempotency-${var.environment}" +} + +resource "cloudflare_workers_kv_namespace" "api_edge_idempotency" { + account_id = var.cloudflare_account_id + title = local.idempotency_namespace_title +} + +# --- 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. + +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 + }) +} + +# --- Outputs (non-secret) --- + +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 +} + +output "api_edge_idempotency_kv_title" { + description = "Cloudflare Workers KV namespace title (human-readable identifier)" + value = cloudflare_workers_kv_namespace.api_edge_idempotency.title +} diff --git a/infra/terraform/cloudflare-kv/terraform/outputs.tf b/infra/terraform/cloudflare-kv/terraform/outputs.tf new file mode 100644 index 0000000..9653334 --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/outputs.tf @@ -0,0 +1,2 @@ +# Output definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/infra/terraform/cloudflare-kv/terraform/variables.tf b/infra/terraform/cloudflare-kv/terraform/variables.tf new file mode 100644 index 0000000..9c92c69 --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/variables.tf @@ -0,0 +1,2 @@ +# Variable definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern.