Rates API Worker

Rates API Worker (tofu-exchange-rate) #

The Terraform module tools/app-infra/modules/tofu-exchange-rate, applied from dev-mng, holds the Cloudflare side of the Rates API Worker (apps/tofu-exchange-rate):

  • the D1 database tofu-exchange-rate, in weur next to BonsAPI, which a plan can never replace;
  • mTLS with Cloudflare’s managed CA on exchange-rate.gotofu.com.

The Worker itself, its cron and its two custom domains deploy with wrangler deploy, from main only, through two jobs named deploy-tofu-exchange-rate:

  • in .github/workflows/dev-mng-deploy.yaml, dispatched by hand with service set to tofu-exchange-rate (all leaves it out);
  • in .github/workflows/dev-mng-pr-build-deploy.yaml, on every push to main.

Both stay off until the repository variable TOFU_EXCHANGE_RATE_DEPLOY_ENABLED is true (step 6): the push job is skipped, and a dispatch that names the Worker fails.

It’s the one Worker prod calls too. wrangler deploy creates each custom domain with its DNS record and certificate. In Terraform the domains would need the Worker to exist first.

Host Callers Auth
exchange-rate.gotofu.com BonsAPI production and dev Client certificate, enforced at the edge
exchange-rate.internal.gotofu.com BonsAPI previews and Coder Authorization: Bearer <API_TOKEN>

Manual steps #

Everything Terraform doesn’t do, in order. Blocks the first deploy marks the steps the deploy-tofu-exchange-rate jobs fail without.

1. Cloudflare API tokens #

In the account that holds gotofu.com:

  • Terraform’s plan token, read-only (TF_VAR_CLOUDFLARE_API_TOKEN, step 2). CI’s dev-mng plan runs every infra PR’s own code with it, so it must not be able to change anything:

    • Account: D1 Read, Account Settings Read;
    • Zone gotofu.com: Zone Read, SSL and Certificates Read.
  • Terraform’s apply token, never stored. Make it just before step 5’s apply, with an end date (TTL) and ideally your IP under Client IP Address Filtering, and delete it right after:

    • Account: D1 Edit, Account Settings Read;
    • Zone gotofu.com: Zone Read, SSL and Certificates Edit.
  • The deploy jobs’ token, its own, not Storybook’s. Blocks the first deploy.

    • Account: Workers Scripts Edit, D1 Edit;
    • Zone gotofu.com: Workers Routes Edit, DNS Edit (for the custom domains).

    It goes in the GitHub environment tofu-exchange-rate, which a repository admin creates with deployment branches limited to main, as the environment secrets CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID (the same account). Never as a repository or organization secret: those reach any branch’s workflows.

Check that neither hostname has a DNS record or belongs to another Worker. In CI, wrangler deploy silently replaces both.

In Zero Trust, give exchange-rate.internal.gotofu.com its own Access application with a Bypass policy for everyone, so the Worker’s API_TOKEN is the only check. Otherwise the *.internal.gotofu.com application stops previews and Coder before the Worker.

2. Secrets #

  • The Worker’s secrets, set by hand in Cloudflare (Workers → tofu-exchange-rate → Settings → Variables and Secrets, or pnpm tofu-exchange-rate exec wrangler secret put <NAME>). CI never touches them, and wrangler deploy keeps them:
    • FIXER_API_KEY, MAS_API_KEY, HMRC_CLIENT_ID, HMRC_CLIENT_SECRET;
    • API_TOKEN, a new random value (openssl rand -hex 32), for the token host.
  • Doppler bonsai → dev_aws, for dev-mng’s Terraform: TF_VAR_CLOUDFLARE_API_TOKEN (step 1’s read-only plan token, never the apply token) and TF_VAR_CLOUDFLARE_ACCOUNT_ID. CI’s dev-mng plan fails until both exist.
  • Previews’ and Coder’s BonsAPI configs:
    • RATES_API_URL = https://exchange-rate.internal.gotofu.com;
    • RATES_API_TOKEN = the Worker’s API_TOKEN.
  • BonsAPI production (prd) and dev:
    • RATES_API_URL = https://exchange-rate.gotofu.com;
    • RATES_API_CLIENT_CERT and RATES_API_CLIENT_KEY, each environment its own (step 3).

3. Client certificates #

  1. In SSL/TLS → Client Certificates, create two certificates with a Cloudflare-generated key: BonsAPI production’s and BonsAPI dev’s.

  2. Store each certificate and key as PEM in its own caller’s Doppler config only (step 2).

  3. Get each fingerprint, lowercase hex with no colons:

    openssl x509 -noout -fingerprint -sha256 -in bonsapi-dev.pem | cut -d= -f2 | tr -d : | tr A-F a-f
    
  4. Put both into CLIENT_CERTS in apps/tofu-exchange-rate/wrangler.jsonc and deploy (step 6):

    "CLIENT_CERTS": {
      "<production fingerprint>": "bonsapi-production",
      "<dev fingerprint>": "bonsapi-dev"
    }
    

A fingerprint in another form never matches cf.tlsClientAuth.certFingerprintSHA256 and gets 401. Step 6’s certificate check catches that.

4. The WAF rule #

In gotofu.com: Security → WAF → Custom rules → Create rule:

  • Name: tofu-exchange-rate mTLS;

  • Expression:

    (http.host eq "exchange-rate.gotofu.com" and (not cf.tls_client_auth.cert_verified or cf.tls_client_auth.cert_revoked))
    
  • Action: Block.

It isn’t in Terraform: a cloudflare_ruleset for the zone’s http_request_firewall_custom phase owns every custom rule on gotofu.com, and none of the others are in Terraform.

5. Terraform apply, right before the merge to main #

Someone with dev AWS access (dev-mng’s state), after steps 1–4, from the branch that brings the module to main, then the merge right after it.

Between the two, dev-mng’s shared state has the module and main’s code doesn’t:

  • dev-mng plans from main, CI’s on other pull requests included, fail or plan to destroy it;
  • nobody may apply dev-mng from main: it would try to delete the D1 database and the mTLS host, and succeed with an edit token. prevent_destroy doesn’t protect a resource whose block is gone.
  1. Delete the database made by hand before this module (0f7689f2-…). D1 names are unique in an account, so Terraform can’t create its own while that one exists. Deleting is permanent, so first check for rows (a “no such table” error means it’s empty):

    pnpm tofu-exchange-rate exec wrangler d1 execute tofu-exchange-rate --remote \
      --command "SELECT (SELECT count(*) FROM currency_rate) AS rates, (SELECT count(*) FROM rate_fetch) AS fetches"
    pnpm tofu-exchange-rate exec wrangler d1 delete tofu-exchange-rate
    
  2. Plan and apply from that branch. The plan runs on Doppler’s read-only token. The apply needs step 1’s apply token, passed with -var-file, which beats Doppler’s TF_VAR_ value:

    cd tools/app-infra/environments
    ./tf.sh -e dev-mng -c plan
    read -rs CF_APPLY_TOKEN   # paste step 1's apply token; nothing is echoed or kept in history
    f=$(mktemp) && chmod 600 "$f"
    printf 'CLOUDFLARE_API_TOKEN = "%s"\n' "$CF_APPLY_TOKEN" > "$f"
    ./tf.sh -e dev-mng -c "apply -var-file=$f"
    rm -f "$f"; unset CF_APPLY_TOKEN
    

    Then delete the apply token in Cloudflare. A dev-mng apply without it can’t change Cloudflare: those resources fail on the read-only token while the AWS ones still apply.

    For this module the plan should show:

    • the D1 database created, with primary_location_hint = "weur";
    • the hostname association imported, adding exchange-rate.gotofu.com.

    Applying the association replaces the zone’s whole list of mTLS hosts. If the plan removes any other host, stop: that host would stop asking for client certificates.

    Blocks the first deploy: the Worker’s wrangler.jsonc has no database_id, so wrangler finds the database by its name, tofu-exchange-rate. Nothing needs copying after the apply. Any deploy before the apply binds whatever database has that name: the hand-made one while it exists, which 5.1 then deletes under the Worker. With no database of that name, the job’s migrations step fails with “Couldn’t find a D1 DB”, before wrangler deploy could create one without weur. So turn deploys on (step 6) only after the apply, and don’t run wrangler deploy by hand before it.

6. The first deploy #

After step 5’s apply and merge, a repository admin sets the repository variable TOFU_EXCHANGE_RATE_DEPLOY_ENABLED to true (Settings → Secrets and variables → Actions → Variables). Then run the “Deploy to DEV-MNG Environment” workflow from main with service = tofu-exchange-rate (image-tag is required but unused by this job). Once that job is done, check:

# mTLS host: no certificate is blocked at the edge (403), BonsAPI dev's gets 200.
curl -i https://exchange-rate.gotofu.com/health
curl -i --cert bonsapi-dev.pem --key bonsapi-dev.key https://exchange-rate.gotofu.com/health

# Token host: the token gets 200, no token 401.
curl -i -H "Authorization: Bearer $API_TOKEN" https://exchange-rate.internal.gotofu.com/health
curl -i https://exchange-rate.internal.gotofu.com/health

A 401 for the certificate means its fingerprint in CLIENT_CERTS is wrong (step 3).

From then on every push to main deploys it, and the same workflow redeploys it without a merge.