Skip to content

fix(infra): make the plan gate actually pass — three real gaps it found - #354

Merged
athvin merged 2 commits into
mainfrom
bm/infra-plan-gate-fixes
Oct 30, 2026
Merged

athvin merged 2 commits into
mainfrom
bm/infra-plan-gate-fixes

Conversation

@athvin

@athvin athvin commented Oct 30, 2026

Copy link
Copy Markdown
Owner

PR #352's plan gate ran for the first time against live state and found three
things. None was a workflow bug; all three were pre-existing.

1. plan (core): ReadOnlyAccess does not cover bcm-data-exports

AccessDeniedException: User: …assumed-role/er-ci-tf-plan/GitHubActions is
not authorized to perform: bcm-data-exports:GetExport … because no
identity-based policy allows the bcm-data-exports:GetExport action

aws_bcmdataexports_export.cur2 (the CUR 2.0 export) cannot refresh without
it, which fails the whole env. AWS's ReadOnlyAccess managed policy simply
omits that service — the same shape as the KMS Decrypt gap already handled a
few lines above. Added the four read actions; a plan never writes.

2. plan (dev): the env was never plannable non-interactively

Two required variables with no defaults and no tfvars file — so
terraform plan prompted, and in CI got "No value for required variable". But
supplying them would not have been enough: ses.tf's own line 28 says
"running a plan over this needs CLOUDFLARE_API_TOKEN exported", and the
Cloudflare provider cannot authenticate without it. envs/dev has therefore
never been plannable by anything that did not already hold that token.

SES is now opt-in. Both variables default to null, and with either unset
the module, the three DNS records and the mail policy all drop to count = 0.
Supply both plus the token and it returns in full.

Safe because nothing here has ever been applied: terraform state list over
dev's 101 resources matched no ses/cloudflare/mail resource, so switching to
count destroys nothing. Verified before changing it rather than trusted to
the commit message that said SES was written-but-unapplied.

The alternative was putting a real Cloudflare token in repository secrets,
which trades a planning gap for a long-lived credential in a PUBLIC repo's
secrets — the thing §11's zero-secrets property exists to avoid. A planning gap
on one dormant subsystem is the cheaper side of that trade.

The three outputs needed one(module.ses[*].…) rather than
module.ses[0].…: an output has no count, so it evaluates even when the
module is empty and fails with "module.ses is empty tuple". The resource
references are fine as [0] because they sit under count = 0 and are never
evaluated.

3. dev's lockfile was missing a provider it declares

.terraform.lock.hcl had no cloudflare/cloudflare entry despite versions.tf
requiring it, so init resolved it unpinned within ~> 5.0 — exactly the drift
a lockfile exists to stop. Now pinned at 5.28.1.

Verified

terraform plan run locally against live state, both envs:

envs/core → (was failing) now reaches the diff
envs/dev  → 4 to add, 0 to change, 0 to destroy

and dev's four are precisely the intended ones: aws_iam_role.ci_deploy_dev,
its policy, and the EKS access entry + policy association. No destroys in
either env.

Co-Authored-By: Claude Opus 5 (1M context) [email protected]

🤖 Generated with Claude Code

bmoore813 and others added 2 commits October 29, 2026 20:18
PR #352's plan gate ran for the first time against live state and found three
things. None was a workflow bug; all three were pre-existing.

## 1. `plan (core)`: ReadOnlyAccess does not cover bcm-data-exports

    AccessDeniedException: User: …assumed-role/er-ci-tf-plan/GitHubActions is
    not authorized to perform: bcm-data-exports:GetExport … because no
    identity-based policy allows the bcm-data-exports:GetExport action

`aws_bcmdataexports_export.cur2` (the CUR 2.0 export) cannot refresh without
it, which fails the whole env. AWS's `ReadOnlyAccess` managed policy simply
omits that service — the same shape as the KMS Decrypt gap already handled a
few lines above. Added the four read actions; a plan never writes.

## 2. `plan (dev)`: the env was never plannable non-interactively

Two required variables with no defaults and no tfvars file — so
`terraform plan` prompted, and in CI got "No value for required variable". But
supplying them would not have been enough: `ses.tf`'s own line 28 says
"running a plan over this needs `CLOUDFLARE_API_TOKEN` exported", and the
Cloudflare provider cannot authenticate without it. `envs/dev` has therefore
never been plannable by anything that did not already hold that token.

**SES is now opt-in.** Both variables default to `null`, and with either unset
the module, the three DNS records and the mail policy all drop to `count = 0`.
Supply both plus the token and it returns in full.

Safe because nothing here has ever been applied: `terraform state list` over
dev's 101 resources matched no ses/cloudflare/mail resource, so switching to
`count` destroys nothing. Verified before changing it rather than trusted to
the commit message that said SES was written-but-unapplied.

The alternative was putting a real Cloudflare token in repository secrets,
which trades a planning gap for a long-lived credential in a PUBLIC repo's
secrets — the thing §11's zero-secrets property exists to avoid. A planning gap
on one dormant subsystem is the cheaper side of that trade.

The three `output`s needed `one(module.ses[*].…)` rather than
`module.ses[0].…`: an output has no `count`, so it evaluates even when the
module is empty and fails with "module.ses is empty tuple". The resource
references are fine as `[0]` because they sit under `count = 0` and are never
evaluated.

## 3. dev's lockfile was missing a provider it declares

`.terraform.lock.hcl` had no `cloudflare/cloudflare` entry despite versions.tf
requiring it, so `init` resolved it unpinned within `~> 5.0` — exactly the drift
a lockfile exists to stop. Now pinned at 5.28.1.

## Verified

`terraform plan` run locally against live state, both envs:

    envs/core → (was failing) now reaches the diff
    envs/dev  → 4 to add, 0 to change, 0 to destroy

and dev's four are precisely the intended ones: `aws_iam_role.ci_deploy_dev`,
its policy, and the EKS access entry + policy association. No destroys in
either env.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Correcting both the fix and my verification of it.

## The verification mistake

I claimed the previous commit was "verified locally against live state". It was
not, in the way that mattered: I ran the plan as `er-mgmt`, which holds
AdministratorAccess. That proves the CONFIG is valid; it says nothing about what
`er-ci-tf-plan` can do. The gate then failed again in CI on a permission the
local run never exercised, which is exactly the hole that kind of verification
leaves.

## What the second failure showed

`plan (core)` still failed on `bcm-data-exports:GetExport` — my grant for it was
in the Terraform but not APPLIED, and the plan role's policy only changes when
`envs/core` is applied. And `plan (dev)` failed on something new:

    not authorized to perform: secretsmanager:GetSecretValue on resource:
    …secret:er/dev/shared/postgres-… / s3-… / builder-…

AWS leaves `GetSecretValue` out of `ReadOnlyAccess` on purpose: reading a
secret's VALUE is the sensitive action, not a read. Terraform needs it to
refresh `aws_secretsmanager_secret_version`.

## Why granting it would have been wrong

This role is assumable from ANY ref, because a plan has to run on the pull
request. A same-repo PR can also edit `.github/workflows/infra.yml`, since
`pull_request` runs the PR's own copy of the workflow. So granting secret-read
to this role lets a PR print dev's Postgres and S3 credentials into a public
build log. Chasing two AccessDenied errors with two grants would have quietly
turned a read-only gate into a credential-exfiltration path.

## The fix needs no permissions at all

`-refresh=false`. A non-refreshing plan makes neither privileged call, so both
failures disappear and the role stays genuinely read-only — the
`bcm-data-exports` grant from the previous commit is removed rather than kept,
because an unused permission is the thing least-privilege is against.

What is lost is out-of-band drift detection. What is kept is the
config-versus-state diff, which is what a reviewer is actually reading on a PR.
Drift is still caught at APPLY time, where the apply role refreshes fully and
the plan output is visible before the environment gate is released — so the
property moves from "every PR" to "every apply", which is where it matters.

## Verified, with the limit stated

Locally, `-refresh=false` plans cleanly in both envs: `core` reports no changes
(correct — dropping the unapplied grant returns it to the applied state) and
`dev` reports the same 4 to add, 0 to change, 0 to destroy. That is a
config-validity check, NOT a permission check: I cannot assume `er-ci-tf-plan`
from here, since its trust requires a GitHub OIDC token. CI is the only thing
that can prove the permission question, and this time I am letting it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@athvin
athvin merged commit edf86c2 into main Oct 30, 2026
22 checks passed
@athvin
athvin deleted the bm/infra-plan-gate-fixes branch October 30, 2026 04:58
athvin added a commit that referenced this pull request Nov 1, 2026
…sed) (#363)

This file has carried a "NOT built yet" note about §14.2's prod-scoped
apply role since the plan/apply gate landed, and the note's premise went
stale: it said the gap was "briefly covered by a required-reviewer
environment", which stopped requiring anyone in #355, and prod has held an
Aurora cluster since #352. So the only thing between a merge and a
production teardown has been branch protection plus the destroy guard.

`er-ci-tf-apply-prod`: AdministratorAccess, reachable from exactly two
principals.

**What the hop buys, narrowly stated**, because overclaiming it would be
worse than not having it:

1. Auditability — a prod write becomes a distinct `AssumeRole` into a
   prod-named role in CloudTrail instead of being indistinguishable from a
   dev write by the same principal, and the chained session carries the
   GitHub session tags (Repository, Workflow, Actor, Commit, Branch), so
   the trail records who merged what.
2. No *accidental* prod apply from the non-prod path, once the companion
   PR denies `er-ci-tf-apply` the prod state object.
3. A break-glass path with the same permissions CI uses, so a human
   recovering prod is not improvising a different identity.

**What it does not buy:** containment of a compromised `er-ci-tf-apply`.
That role can assume this one — that is the design — so anyone holding it
reaches prod through the front door. The control there is still its own
`main`-only trust policy plus branch protection.

AdministratorAccess for a sharper reason than the apply role's: narrowing
it would buy nothing, because both principals that can reach it already
hold AdministratorAccess. A tighter policy would only block Terraform,
never an actor, while adding the mid-apply AccessDenied failure mode.

**`sts:TagSession` is in the trust policy and is load-bearing.** Read from
configure-aws-credentials' own source at the SHA this repo pins: both
web-identity paths `delete params.Tags`, which is why no other role here
needs it — but role CHAINING takes the plain `AssumeRole` path, which keeps
them. Without this grant the prod apply would have failed on an
AccessDenied for TagSession with nothing in the diff explaining it, the
same shape as the three bugs #354 found. Allowing it is also the better end
of the trade: `role-skip-session-tagging: true` would have worked and
thrown away the tags that make reason 1 true.

**ProdAdmin is trusted by pattern, not by ARN.** `envs/prod/eks.tf`
hardcodes today's `AWSReservedSSO_ProdAdmin_<hash>`, which is fine for an
EKS access entry and wrong for a trust policy: IAM resolves a principal ARN
to the role's unique id on write, so once the permission set is recreated
the policy holds a dangling id. Account root plus an `ArnLike` on the
caller's own ARN survives that, and is not "anyone in the account" — the
effective set is principals matching a ProdAdmin SSO session that also hold
`sts:AssumeRole`. `PlatformAdmin` does not match; neither does the
`er-dev-builder` key.

**Nothing uses it yet, on purpose.** The chaining step and the companion
deny land separately, because `apply (core)` creates this role and
`apply (prod)` would consume it in the same run. They do run in that order
today — measured core → dev → prod, strictly sequential under
`max-parallel: 1` — but GitHub documents no ordering guarantee for a
matrix, and resting a prod apply on undocumented ordering is the #358 trap
again. Split, it is order-independent.

Co-authored-by: bmoore813 <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
athvin added a commit that referenced this pull request Nov 1, 2026
…367)

* feat(infra): detect out-of-band drift, which -refresh=false gives up

§14.2 gives up one thing on purpose: the plan tier runs `-refresh=false`,
because `er-ci-tf-plan` is assumable from any PR branch and a refreshing
plan reads secret VALUES. What that loses is drift — a console edit, a
manual fix during an incident, an AWS-side default that moved.

Nothing noticed. The only thing that refreshes is `apply` on `main`, which
then silently reconciles whatever it finds, so drift stayed invisible until
some unrelated infra PR merged and quietly fixed or failed on it with
nobody connecting the two. Dev has already shown this once: #357's apply
reported `0 added, 1 changed, 0 destroyed` against a PR plan that had shown
nothing.

`drift.yml` runs `plan -refresh-only` daily across all four stacks.
`-refresh-only` is a different question from the plan tier's and that is
why this is a separate workflow rather than a flag: it compares STATE
against REALITY and ignores the configuration entirely, so what it reports
is only ever "something changed outside Terraform", never "someone edited
a .tf file".

**A third read role, because the second one must not grow.**
`er-ci-tf-drift` holds the two reads `ReadOnlyAccess` omits —
`secretsmanager:GetSecretValue` and `bcm-data-exports:GetExport`, the two
that broke the first run of the plan gate in #354 — which a refresh needs
and the plan role must never have.

That is safe only because of who can reach it, and it takes TWO trust
conditions rather than one:

- `sub` pinned to `:ref:refs/heads/main`. No PR branch can mint that
  claim. On its own it still admits any `main`-ref job, including the plan
  tier on a push, so it is necessary and not sufficient.
- `job_workflow_ref` pinned to `drift.yml` on `main`. This is the condition
  that narrows it to one file's jobs, so adding a step to another workflow
  cannot quietly inherit secret-read.

Matched with `StringLike` and a leading wildcard deliberately: the
repository prefix in `job_workflow_ref` is not the customised immutable
`sub` prefix, and pinning a format that AWS and GitHub both have to agree
on would be a silent never-match rather than a visible error.
`GetSecretValue` is scoped to `er/*` in this account, not `*`.

Read-only including the lock, so `-lock=false` like the plan tier — the
role holds no S3 write and acquiring the lockfile is one. A refresh-only
PLAN writes no state; only `apply -refresh-only` would, and nothing here
applies. **Drift is reported for a human, never auto-reconciled:** writing
reality back into state is how a console change becomes permanent without
anyone deciding so.

Drift FAILS the run rather than warning, because a scheduled workflow that
goes red notifies and one that warns is a line in a log nobody opens. If an
environment turns out to drift chronically the answer is to fix the
configuration or record the exception, not to lower this to a warning —
which would retire the check while leaving it in the tree.

It can never be a required check: it never runs on a pull request.

One PR rather than the two the last three IAM changes needed. The ordering
trap does not apply here — `apply (core)` creates the role, and nothing
consumes it until the next cron or a manual dispatch, so there is no
same-run dependency to lose.

Verified by extracting both steps from the YAML and running them against a
stub terraform: exit 0 → `drifted=false` → job green; 2 → `drifted=true` →
red naming the env; 1 and an init failure → `drifted=error` → red saying it
is not a clean result; and an empty value fails closed. The summary step is
`always()` and ordered before the gate, so a red run explains itself
without opening the log.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(ci): exempt drift.yml from the Rust gate too, and state the fail-safe rule

Noticed on this PR's own run: it correctly paid the full backend gate
(because it touches `docs/`, which is never exempt), but `drift.yml` is a
new workflow and #366 had only named `infra.yml`. Leaving an inconsistency
I created one commit earlier is worse than one more regex token.

Same argument as `infra.yml`: `drift.yml` defines no Rust job and cannot
affect the workspace build. `rust.yml`, `frontend.yml` and `images.yml` stay
out of the exempt set, because a change to a gate must keep reporting on
exactly the PR most likely to break it.

While here, the rule behind the enumeration is now written down rather than
implied: naming files, instead of exempting `^\.github/workflows/` and
listing exceptions, is the FAIL-SAFE direction. A workflow added later runs
the gate until someone argues it should not, rather than skipping it until
someone notices. Verified with a hypothetical `something-new.yml`, which
still runs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: bmoore813 <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
athvin added a commit that referenced this pull request Nov 1, 2026
… red on it (#368)

#367's `apply (core)` failed and `main` is red. The drift role was never
created, so nothing partially applied and nothing needs cleaning up — the
next apply retries from a clean state.

AWS rejected the trust policy:

  MalformedPolicyDocument: Trust policy with trusted principal
  …oidc-provider/token.actions.githubusercontent.com must evaluate, using
  StringEquals, StringLike or StringEqualsIgnoreCase,
  …:sub or …:job_workflow_ref which is not scoped to all.

I had written `job_workflow_ref` as `StringLike` on
`*/.github/workflows/drift.yml@refs/heads/main`, with the leading wildcard
deliberately hedging whether that claim carries the customised immutable
prefix this repo's `sub` uses. Two things I had wrong:

- a pattern that STARTS with `*` is "scoped to all" to that validator, and
- it refuses on any such condition rather than being satisfied by the exact
  `sub` StringEquals sitting beside it, which is what I assumed the
  message's "sub **or** job_workflow_ref" wording allowed.

So the uncertainty has to be resolved rather than wildcarded. Both
candidate formats are now listed as literals under `StringEquals`, which
ORs them: the documented `OWNER/REPO/.github/workflows/FILE@REF`, and the
same claim with the immutable ids in case it carries them. That is strictly
better than the wildcard was — no pattern to widen, and if GitHub ever
changes the format the role stops being assumable LOUDLY at
`AssumeRoleWithWebIdentity` rather than quietly matching more than intended.

Worth recording why the second condition not pinning the repository costs
nothing: `sub` already pins owner and repository by numeric id, immutably.
`job_workflow_ref` only has to answer "which workflow file, on which ref".

§14.2 and the infra-platform skill described the wildcard form, so both are
corrected, and the skill now states the rule as AWS enforces it rather than
as a preference — an exact match is not a style choice here, a
wildcard-leading one fails `CreateRole`.

This is the fourth bug in this series that only a real apply could find,
after the environment-vs-ref `sub` in #356, the two reads `ReadOnlyAccess`
omits in #354, and `sts:TagSession` on a chained role in #363. The pattern
is consistent: IAM trust policies and OIDC claims are not verifiable by
`terraform validate`, and every one of them has cost exactly one red run.

Co-authored-by: bmoore813 <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
athvin added a commit that referenced this pull request Nov 1, 2026
…y noise (#369)

* fix(infra): AWS refuses a wildcard-leading job_workflow_ref — main is red on it

#367's `apply (core)` failed and `main` is red. The drift role was never
created, so nothing partially applied and nothing needs cleaning up — the
next apply retries from a clean state.

AWS rejected the trust policy:

  MalformedPolicyDocument: Trust policy with trusted principal
  …oidc-provider/token.actions.githubusercontent.com must evaluate, using
  StringEquals, StringLike or StringEqualsIgnoreCase,
  …:sub or …:job_workflow_ref which is not scoped to all.

I had written `job_workflow_ref` as `StringLike` on
`*/.github/workflows/drift.yml@refs/heads/main`, with the leading wildcard
deliberately hedging whether that claim carries the customised immutable
prefix this repo's `sub` uses. Two things I had wrong:

- a pattern that STARTS with `*` is "scoped to all" to that validator, and
- it refuses on any such condition rather than being satisfied by the exact
  `sub` StringEquals sitting beside it, which is what I assumed the
  message's "sub **or** job_workflow_ref" wording allowed.

So the uncertainty has to be resolved rather than wildcarded. Both
candidate formats are now listed as literals under `StringEquals`, which
ORs them: the documented `OWNER/REPO/.github/workflows/FILE@REF`, and the
same claim with the immutable ids in case it carries them. That is strictly
better than the wildcard was — no pattern to widen, and if GitHub ever
changes the format the role stops being assumable LOUDLY at
`AssumeRoleWithWebIdentity` rather than quietly matching more than intended.

Worth recording why the second condition not pinning the repository costs
nothing: `sub` already pins owner and repository by numeric id, immutably.
`job_workflow_ref` only has to answer "which workflow file, on which ref".

§14.2 and the infra-platform skill described the wildcard form, so both are
corrected, and the skill now states the rule as AWS enforces it rather than
as a preference — an exact match is not a style choice here, a
wildcard-leading one fails `CreateRole`.

This is the fourth bug in this series that only a real apply could find,
after the environment-vs-ref `sub` in #356, the two reads `ReadOnlyAccess`
omits in #354, and `sts:TagSession` on a chained role in #363. The pattern
is consistent: IAM trust policies and OIDC claims are not verifiable by
`terraform validate`, and every one of them has cost exactly one red run.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(infra): the first drift run measured the signal, and it was mostly noise

`drift.yml` ran for the first time (41280636155) and failed on all four
stacks. The trust policy worked — `Authenticated as assumedRoleId
AROA3TP35ULXVJ57LM6EF` — so #368 was right. Everything after it was wrong,
in three separate ways, and none of them was findable without running it.

**1. `-detailed-exitcode` is not a drift signal.** `dev` and `prod` both
printed "found no differences" and both exited 2. A refresh-only plan has
something to persist almost by construction. Treating 2 as drift would have
turned the schedule red every single day — the alarm fatigue I argued
against in the very commit that introduced it.

**2. The text sentinel is not one either.** "Objects have changed outside of
Terraform" fired on `core` and `state-backend`. Neither was drift:

    state-backend  aws_kms_key.state  — `tags` appearing as {} where state
                   holds null
                   aws_s3_bucket.state — `tags`, plus `policy` reporting what
                   a SEPARATE aws_s3_bucket_policy resource manages
    core           aws_iam_role.ci_tf_drift — `managed_policy_arns` reporting
                   what a SEPARATE aws_iam_role_policy_attachment manages

Same shape each time: an attribute the provider computes from something
Terraform manages elsewhere, or a null/empty normalisation. And
`state-backend` makes it permanent rather than transient — CI plans that
stack and never applies it, so nothing reconciles its state snapshot and it
would have reported drift forever.

So drift is now decided PER ATTRIBUTE by `scripts/ci/tf-drift-classify.sh`,
from the plan JSON, against an ignore list where every entry was observed in
that run. Extend it the same way — from evidence — never pre-emptively,
because each entry is a place real drift can hide. The ignored entries are
still printed, so they do not vanish.

`policy` is ignored only on `aws_s3_bucket`, not globally: a real change to
an `aws_iam_role_policy` document must stay loud. There is a test for
exactly that.

Nothing from the JSON is printed but addresses and attribute NAMES — the
same rule the apply tier follows, for the same reason. `driftplan` and
`plan.json` carry values in cleartext and there is deliberately no upload
step in the workflow.

**3. A third missing read: `bcm-data-exports:ListTagsForResource`.**
Refreshing the CUR export reads its tags as a separate call and
`ReadOnlyAccess` omits that too. #354 found `GetExport` by failing on it and
then switched the plan tier to `-refresh=false` — so until this workflow
existed nothing had ever COMPLETED a full refresh, and this call had never
been reached. A fourth may appear with the next resource type.

Also recorded, because "read-only role" reads safer than it is: the drift
role's `er/*` secret scope reaches `er/dev/shared/builder`, the
never-expiring AdministratorAccess key. It does not widen anything —
reaching this role takes a merge to `main`, and anyone who can merge can
already use `er-ci-tf-apply`, which is admin outright — so the grant sits
inside an existing boundary. The policy is deliberately not contorted to
exclude it, because the dev stack stores that key in a
`secretsmanager_secret_version` and excluding it would fail every dev
refresh. The thing to fix is the key.

The helper suite is now 41 assertions, and the new ten are mutation-checked:
emptying the ignore list, ignoring `policy` globally, making the classifier
unable to report drift, and letting a parse failure pass each turn it red.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: bmoore813 <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants