Skip to content

test(iam): one coverage gate for every spore.host principal's AWS calls (#254) - #1347

Merged
scttfrdmn merged 3 commits into
mainfrom
test/254-iam-drift-guard
Oct 27, 2026
Merged

scttfrdmn merged 3 commits into
mainfrom
test/254-iam-drift-guard

Conversation

@scttfrdmn

Copy link
Copy Markdown
Contributor

Fixes #254
Refs spore-host/spore-host#610 (part 4, the CI gate; this PR does not close it)

What this does

There is now one mechanism, internal/iamcoverage, that holds every role spore.host provisions to the AWS calls its code actually makes.

Discovery. It works from the code, not from a list.

  • It type-checks the principal's main package and its dependencies from source.
  • It builds SSA, runs RTA from main, init and every handler passed to aws-lambda-go, then refines the result with VTA. Without VTA, one io.Reader makes every Read in the program reachable from everything.
  • It scans every reachable function for AWS SDK operations, recognising them by shape: a call, interface invocation or method value named Op whose signature takes a *svc.OpInput. Paginators and waiters are recognised by their <Op>APIClient parameter, and presigners by their name.
  • Three non-operation routes are mapped explicitly: the S3 transfer manager (mapped at its API, since SDK internals are not scanned), stscreds.NewAssumeRoleProvider, and v4.Signer.SignHTTP. For SignHTTP the signing service must be a constant, and lambda maps to lambda:InvokeFunctionUrl.
  • Calls through narrow interfaces and in other packages are therefore all found: pkg/bucketsweep, pkg/instancerole, pkg/spotrequest, truffle and strata. The old reaper regex missed all of these.
  • I chose this over a per-package scan because a per-package scan cannot attribute a call to the principal whose code runs it. spored's pool-worker, pipeline-stage, provenance and batch-queue subcommands run on different roles. Each is its own principal, cut out of the core by function.

Mapping. An SDK package goes to its IAM prefix through a closed table, and an unknown package fails. An operation goes to its actions through an exceptions table: S3 HeadBucket→ListBucket, DeleteBucketTagging→PutBucketTagging, the multipart family→PutObject, lambda:Invoke→InvokeFunction, PostToConnection→execute-api:ManageConnections, sts:GetCallerIdentity→nothing, and so on. Anything not listed maps to itself, so a wrong guess fails closed.

Policies. These are read from what spore.host actually provisions:

  • Go-built documents: SporedBaselinePolicyDocument, SporedInstanceRolePolicyDocument, PoolWorkerPolicy, StageDataPolicy, TaskRunPolicyFor, ScanSelfPolicyDocument.
  • CloudFormation and SAM templates, including !If branches and SAM policy templates. The SAM templates' action lists were copied from samtranslator 1.170.0, not from memory.
  • put-role-policy heredocs in deploy scripts.

Each principal declares its credential contexts. For example, the reaper's route53, sts and dynamodb calls run on its own role, and its ec2, fsx, ssm, s3 and iam calls run on the target-account role. A principal can also have several role variants, such as spored under spored-instance-role or under a spawn-instance-* role, and each variant must cover the calls on its own.

The gate fails when:

  • an action is granted only by a wildcard (*, s3:*, ec2:Describe* or NotAction); wildcards are reported separately and never count;
  • an operation is unmapped;
  • discovery comes back empty;
  • a root or cut function no longer exists;
  • a main package in the repo has no registered principal;
  • or a knownGaps entry is no longer a gap.

pkg/reaperiam's drift gates (TestPolicyCoversEveryReaperAPICall etc.) now use this discovery instead of their regex. grantedElsewhere is now checked in both directions, against the template and against the calls.

CLI inventory (#610's other half). docs/reference/cli-iam-actions.md is generated by make cli-iam-actions. It walks the live cobra tree, matches each command's RunE to its SSA function by declaration position, and inventories it for darwin, linux and windows. It covers 122 runnable commands and 152 distinct actions, plus an "outside any command" section, which is shell completion's ec2:DescribeInstances. TestCLIActionInventoryIsCurrent fails when the committed copy is stale. The umbrella docs can consume it as-is.

Gaps found

Principals checked: spored core (2 role variants), spored pool-worker, run-pipeline-stage, provenance (task and pool roles), run-queue, ttl-reaper (base role plus 3 target-account variants), sweep-orchestrator (function role and member role), scheduler-handler, dns-updater (deploy-custom-dns.sh role), pipeline-orchestrator, dashboard-api (function role and member read role), dashboard-websocket, dashboard-websocket-processor and cost-history-collector. The alert Lambdas no longer exist (#783, #794).

Fixed here (each is intended by the code and scoped):

Principal / role Missing Effect before the fix Fix
sweep-orchestrator / SpawnSweepCrossAccountRole ec2:DescribeAvailabilityZones The orchestrator validates every region with this call on the assumed role, and marks all of a region's params failed ("Region access denied") when it is refused scripts/setup-sweep-cross-account-role.sh
same ec2:DeletePlacementGroup spawn-mpi-* placement groups are never cleaned up at sweep end Same script, conditioned on spawn:managed=true
pipeline-orchestrator / SAM sns:CreateTopic, sns:Subscribe, sns:ListSubscriptionsByTopic, sns:Publish Pipeline notifications denied lambda/pipeline-orchestrator/template.yaml, on spawn-pipeline-* topics
same ec2:DescribeInstanceTypes The AMI architecture lookup is denied Same template
spored provenance (task and pool roles), spored run-pipeline-stage s3:AbortMultipartUpload A failed multipart upload can't be aborted, so its parts bill until lifecycle removes them taskiam.ObjectWriteActions, used beside every generated s3:PutObject (taskiam, StageDataPolicy, poolWorkerPolicy)

Left for you to decide. These are recorded in internal/iamcoverage/gaps_test.go and filed as #1344 with evidence:

  1. spored xray:PutTraceSegments, on both role variants. Tracing is opt-in, off by default, and spawn launch cannot set it.
  2. spored run-queue on spored-instance-role: s3:PutObject and s3:AbortMultipartUpload. A --batch-queue launch without --iam-role cannot upload its results. This is a Sizing: on a price tie, prefer the smallest type that fits (hpc7g cpu=16 → hpc7g.16xlarge) #610 violation.
  3. SpawnDashboardLambdaRole (setup-dashboard-lambda-role.sh) is far behind the code. It is missing dynamodb PutItem/DeleteItem (4 Lambdas), secretsmanager:GetSecretValue, s3:GetObject/PutObject (strata registry), sts:AssumeRole and execute-api:ManageConnections. The live role is hand-managed.
  4. Dashboard member read role. It carries only AWS-managed read-only policies, which are not modelled, and are wildcards anyway. The dashboard's terminate path assumes it to call ec2:TerminateInstances and CancelSpotInstanceRequests.

The reaper, scheduler-handler and dns-updater are clean.

Watched failing (compiling reverts)

  • I added p.ec2Client.DescribeImages(...) to EC2Provider.Stop; it builds. TestEveryPrincipalCallIsGranted failed for both spored role variants, naming the site and the call chain runDaemon -> Monitor -> checkAndAct -> ... -> Stop.
  • I added r53.ListHostedZones(...) to the reaper's configure (it builds) and added Action: 'route53:*' to the SAM function policy. The gate failed with "only a wildcard in template.yaml#TTLReaperFunction matches it, and a wildcard does not count". pkg/reaperiam's TestPolicyCoversEveryReaperAPICall and TestCrossAccountRoleCoversEveryReaperAPICall also failed.
  • I made Policy.Grants return Exact for globs, and TestAWildcardNeverSatisfiesTheGate failed on all four forms.
  • I disabled the operation-signature rule, and TestDiscoversEveryShapeOfCall failed (direct, method-value and transfer-manager calls disappeared).
  • I removed sts:GetCallerIdentity from the exceptions table, and both the fixture and mapping tests failed.
  • I added a bogus ledger entry and renamed a principal's directory. The gate reported "no longer a gap" for both, and TestEveryMainPackageIsAPrincipal named the unregistered lambda/cost-history-collector.

Checks

make check, make lint (0 issues), semgrep scan --config=auto --error . (clean), make api-snapshot (two additions in pkg/aws), and make check-tidy all pass. The new package and pkg/reaperiam also pass under the hermetic wrapper.

Notes / limits

  • CI step added. "Download nested module dependencies" runs before Test, in both the Linux and Windows jobs. The gate loads the lambda modules offline (GOPROXY=off), so their deps must be cached before the root tests run. internal/iamcoverage is skipped on Windows, with the reason recorded in windows-test-skips.txt. It analyses all GOOS builds from Linux.
  • Runtime. The package takes about 60s on an M-series Mac: 14 program loads, of about 3s each, plus the CLI inventory. That is all in -short, because it is the gate.
  • Names, not resources. The gate checks action names only. It does not infer implicit permissions, such as iam:PassRole for RunInstances or s3:PutObjectTagging for tagged uploads, and it does not see aws s3 cp in shell. These limits are listed in IAM coverage gaps found by the #254 gate: dashboard role script, batch-queue results upload, spored X-Ray, dashboard terminate #1344.
  • Role hash churn. Adding s3:AbortMultipartUpload changes the policy hash, so the first launch after upgrade creates new spawn-instance-* roles. That is in the CHANGELOG, including how the old roles get removed.
  • New exported symbols (for the gate): aws.SporedBaselinePolicyDocument, aws.SporedInstanceRolePolicyDocument, cmd.PoolWorkerPolicy, cmd.RootCommand, taskiam.ObjectWriteActions.

…ls (#254)

internal/iamcoverage type-checks each principal's program, builds its call
graph (RTA then VTA), discovers every AWS SDK operation reachable from its
entry points, maps each to its IAM action, and fails unless the policy
spore.host provisions for that role grants it by name. Wildcards never
count; unmapped operations fail; every main package must be a registered
principal; a ledger of known gaps (#1344) fails when an entry goes stale.

pkg/reaperiam's drift gates use the same discovery instead of a regex.
docs/reference/cli-iam-actions.md is the CLI's per-command inventory,
generated by make cli-iam-actions (#610).

Grants the gate found missing and that are clearly intended: sweep
cross-account role DescribeAvailabilityZones + tag-scoped
DeletePlacementGroup; pipeline-orchestrator SNS + DescribeInstanceTypes;
s3:AbortMultipartUpload beside every generated s3:PutObject.
@scttfrdmn
scttfrdmn force-pushed the test/254-iam-drift-guard branch from bb112ba to b738f8f Compare October 27, 2026 01:15
@codecov

codecov Bot commented Oct 27, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.00787% with 66 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
internal/iamcoverage/policy.go 84.03% 34 Missing ⚠️
internal/iamcoverage/discover.go 89.81% 25 Missing and 2 partials ⚠️
cmd/iam_coverage_exports.go 0.00% 2 Missing ⚠️
pkg/aws/iam_coverage.go 0.00% 2 Missing ⚠️
internal/iamcoverage/actions.go 95.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn
scttfrdmn merged commit 6052351 into main Oct 27, 2026
9 checks passed
@scttfrdmn
scttfrdmn deleted the test/254-iam-drift-guard branch October 27, 2026 01:48
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.

Guard against spored/reaper IAM drift: code calls AWS APIs the role doesn't grant (recurring class)

1 participant