Skip to content

feat(sweep): spawn provisions SpawnSweepCrossAccountRole (#1537) - #1561

Merged
scttfrdmn merged 1 commit into
mainfrom
fix/1537-provision-sweep-role
Nov 9, 2026
Merged

scttfrdmn merged 1 commit into
mainfrom
fix/1537-provision-sweep-role

Conversation

@scttfrdmn

@scttfrdmn scttfrdmn commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1537

Was stacked on #1560. #1560 merged to main (cfed8988) while this PR was open, so this branch is now rebased onto main and holds a single commit, 095be86a. It builds on #1560's putVersionedRolePolicy.

What changes

SpawnSweepCrossAccountRole used to be created only by scripts/setup-sweep-cross-account-role.sh, run by hand in each account. Since #1535, a detached sweep without it was refused. Now spawn provisions it, keeps it current, and has a named deleter for it.

  • Detached sweeps create it. spawn launch --param-file (detached, the default) and spawn sweep resume --detach ensure the role in the compute account. This runs at the point where requireDetachedSweepRole used to refuse, before anything else is created. It adopts the script's role if one exists, and converges trust and policy on every run. TestDetachedSweepCreatesTheRoleFirst checks that when CreateRole runs, nothing but the identity lookups has reached the account.
  • spawn sweep setup does the same on its own. Every failure is an error there.
  • spawn sweep teardown is the deleter. It deletes every inline policy, detaches every managed policy, and then deletes the role. It refuses while any sweep in spawn-sweep-orchestration with aws_account_id = this account is not COMPLETED/FAILED/CANCELLED. It also refuses when it cannot read the table. --force overrides both.
  • spawn doctor gets a new check, "sweep cross-account role":
    • Pass: the role exists with policy v1, or a newer version.
    • Warn: the role is absent, or its policy is older or the script's.
    • Fail: the role exists in an account it must never be in.
  • Degradation. Most outcomes match what the code did before:
  • scripts/setup-sweep-cross-account-role.sh is deleted. The tests that parsed it now read the Go document. No page in docs/ or in the umbrella docs referenced it (checked with grep).

⚠️ ExternalId: the brief's premise does not hold

The brief said to keep "the existing ExternalId fail-closed scheme". There is no ExternalId on this role today. The orchestrator's three AssumeRole sites send none:

  • lambda/sweep-orchestrator/main.go createCrossAccountEC2Client
  • lambda/sweep-orchestrator/main.go initializeRegionalOrchestrator
  • lambda/sweep-orchestrator/cancel.go assumeMemberClients

The script's trust had no condition either. The #374 fail-closed ExternalId belongs to SpawnBotCrossAccount (spore-bot), not to this role. A trust that required an ExternalId would make every detached sweep fail at assume.

Adding one would take more than this PR:

  • a new field on the sweep record and on the schedule record;
  • a change to the orchestrator and to scheduler-handler;
  • a Lambda deploy ordered before the CLI.

It would also break sweeps already queued and scheduled sweeps whose records predate the field. And it would buy little: writing a sweep record already requires infra-account credentials, and the records sit in the same table the CLI scans.

So this PR keeps the exact current semantics: no ExternalId. TestTheOrchestratorSendsNoExternalID pins that to the Lambda's code, so whoever adds one has to change the trust and the records together. The trust is still a single exact principal. Owner decision needed if you want an ExternalId anyway; it would be a separate issue.

Trust (exact document)

{"Statement":[{"Action":"sts:AssumeRole","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::<infra-account>:role/SpawnSweepOrchestratorRole"}}],"Version":"2012-10-17"}
  • <infra-account> is the account of the infra credentials. The CLI invokes that account's orchestrator (sweep.InvokeSweepOrchestrator with LoadInfraAWSConfig): 966362334030 in shared mode. It is not hardcoded.
  • An adopted trust that is not exactly this gets replaced, and the old one is printed. The cases are: extra principals, a condition, or a principal IAM rewrote to an AROA… unique ID.

Policy

The golden file is pkg/aws/testdata/sweep-cross-account-policy.golden.json. It is written as SweepCrossAccountEC2Policy-v1 through #1560's putVersionedRolePolicy. The script's unversioned SweepCrossAccountEC2Policy is deleted after the write. A re-run of the old script, or an old CLI, can only add to the role.

Least privilege, derived from the code. internal/iamcoverage discovered these member-account calls by the orchestrator:

  • ec2: RunInstances, CreateTags, DescribeInstances, DescribeAvailabilityZones, DescribeSecurityGroups, TerminateInstances, CancelSpotInstanceRequests, DeletePlacementGroup, CreateSecurityGroup, Authorize/RevokeSecurityGroupIngress/Egress
  • iam:PassRole
  • ssm:SendCommand and ssm:GetCommandInvocation

Changes from the script's statements:

  • Dropped: ec2:DescribeImages, DescribeInstanceStatus, DescribeKeyPairs, DescribeSubnets, DescribeVpcs. Nothing calls them, and git log -S finds them in source never, only in tracked binaries.
  • Kept: iam:CreateServiceLinkedRole (Spot SLR), which RunInstances authorizes implicitly. It is recorded with that reason in sweepRoleUncalledGrants.
  • Added Sids. The conditions and the ARNs are unchanged. The PassRole Allow covers spored-instance-role, spawnd-role and spawn-instance-*, to EC2 only. The explicit Deny of spawn-instance-nested-* stays.
  • No policy variables. The account is bound with bindPolicyAccount.

New gates:

  • TestSweepCrossAccountRoleGrantsOnlyWhatTheOrchestratorCalls fails on any grant the orchestrator does not call. It is the over-grant half of TestEveryPrincipalCallIsGranted.
  • TestSweepPolicyGolden pins sha256 of the template to sweepRolePolicySchema = 1.

Account guard

aws.CheckSweepRoleAccounts(ctx, computeAccount, orchestratorAccount, mgmtLookup, warn) runs before any IAM call, and EnsureSweepCrossAccountRole re-checks the hardcoded list itself. It refuses when:

  • either account is 942542972736. This is hardcoded in forbiddenTrustAccounts, with the reason in the error: an Amazon-internal account, the management account of o-pygqyjjoym, "ExternalId does not change that". Organizations is not even asked.
  • either account is the Organizations management account of the compute account's org. pkg/orgaccount calls organizations:DescribeOrganization and reads MasterAccountId. AWSOrganizationsNotInUse means no org. Denied or unreadable is a warning, and the check goes on: the hardcoded deny holds regardless.
  • the compute account is the shared infra account 966362334030, as the script refused.

A refused detached sweep stops with "…spawn will not create it: refusing to create or trust SpawnSweepCrossAccountRole with account 942542972736: it is an Amazon-internal account… Nothing was created. Run the sweep with --no-detach…". Teardown is not guarded, because removing a forbidden trust is always allowed.

Adoption path (script-created role)

  1. GetRole finds the role, and the outcome is Found.
  2. The trust is URL-decoded and compared semantically (SweepTrustMatches). The script's trust already matches, so it is left alone.
  3. putVersionedRolePolicy writes SweepCrossAccountEC2Policy-v1, then deletes SweepCrossAccountEC2Policy. Put comes before Delete, so the role is never without its grants. This is tested.
  4. A role carrying a newer schema is left alone, with a warning.
  5. A concurrent CreateRole that returns EntityAlreadyExists makes this run adopt the role instead.

Tests (all hermetic; the AWS env stripped)

  • Boundary:
    • pkg/aws: 942542972736 as compute and as orchestrator (zero IAM calls, Organizations not asked); the management account as compute and as orchestrator; member, no-org and unreadable-org cases; the shared infra account.
    • cmd: the same refusals through ensureSweepRole, detached and strict.
  • Adopting the script's role: trust untouched, Put before Delete, idempotent second run.
  • Converging a stale role:
  • Teardown:
    • pkg/aws: every inline and managed policy, then the role; a no-op when there is no role.
    • cmd: refuses while a sweep runs (and names it), refuses on an unreadable table, --force warns and deletes.
  • Trust shape: the exact JSON, no ExternalId or Condition, and a matcher table.
  • Least privilege: the golden policy file, the schema pin, and the over-grant gate.
  • Other:
    • the emulator lifecycle: create, script re-write, adopt, inspect, teardown;
    • pkg/sweep ActiveInAccount on substrate;
    • pkg/orgaccount;
    • the doctor verdicts and severity;
    • the dispatch tests updated to "absent and not creatable".
  • Generated files: docs/reference/cli-iam-actions.md, docs-gen/sweep.md and api/public-surface.txt are regenerated.

Filed scttfrdmn/substrate#1452: substrate flattens {"AWS": arn} trust principals and returns the trust un-encoded. The emulator test notes it and does not assert TrustUpdated there.

Locally: fmt, vet (all GOOS), staticcheck, golangci-lint (all 10 modules), hermetic short tests, tidy (all modules), check-docs (clean once committed) and semgrep scan --config=auto --error . all pass.

Two make check steps fail only because the worktree path contains a space (/Volumes/External HD/…):

  • lambda/dashboard-api TestSetupAllRunsEveryStepFromAnyDirectory (lstat …/HD);
  • check-build-tags' file accounting.

Neither touches this change; CI runs them on a normal path.

New CLI permissions in the compute account:

  • iam:UpdateAssumeRolePolicy
  • iam:DeleteRole, iam:ListAttachedRolePolicies, iam:DetachRolePolicy (teardown)
  • organizations:DescribeOrganization

Teardown also calls dynamodb:Scan with the infra credentials. No Lambda changes, so no Lambda deploy is needed.

Live plan (owner; spore-host-dev 435415984226 ONLY)

Never run any of this with AWS_PROFILE=aws, or anything else that resolves to 942542972736. Step 3 also proves the guard there without creating anything.

0. Build and pin the accounts.

  • go build -o ~/.xtmp/spawn-1537/bin/spawn . from this branch.
  • export AWS_PROFILE=spore-host-dev SPAWN_COMPUTE_PROFILE=spore-host-dev SPAWN_INFRA_PROFILE=spore-host-infra.
  • aws sts get-caller-identity --query Account must print 435415984226.

1. Snapshot the existing role, then reach a clean state.

  • aws iam get-role --role-name SpawnSweepCrossAccountRole > before-role.json.
  • aws iam list-role-policies --role-name SpawnSweepCrossAccountRole, then get-role-policy for each name, > before-policy.json. Keep both for rollback.
  • Check no sweep is running: spawn sweep list --status RUNNING.
  • spawn sweep teardown. It refuses if one is running.
  • aws iam get-role --role-name SpawnSweepCrossAccountRole must return NoSuchEntity.

2. Run a real detached sweep end to end from that clean state.

  • Command: spawn launch live1537 --param-file p.yaml --instance-type t4g.small --max-concurrent 2 --ttl 20m --yes, with 2 rows. --max-concurrent is what makes it really detach (--detach without --max-concurrent silently runs the sweep in the foreground (prints 'Lambda (detached)') #1535).
  • The output must show "🔐 Created SpawnSweepCrossAccountRole in account 435415984226, trusted by arn:aws:iam::966362334030:role/SpawnSweepOrchestratorRole".
  • Verify the role: aws iam get-role shows the trust above and the tag spawn:managed=true. list-role-policies shows exactly SweepCrossAccountEC2Policy-v1.
  • This is also the "one real PutRolePolicy" check for the changed document.
  • Simulate allow and deny with aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::435415984226:role/SpawnSweepCrossAccountRole:
    • allowed: ec2:RunInstances, ec2:TerminateInstances;
    • allowed: iam:PassRole on role/spored-instance-role with iam:PassedToService=ec2.amazonaws.com;
    • implicitDeny: ec2:DescribeImages;
    • explicitDeny: iam:PassRole on role/spawn-instance-nested-x.
  • spawn sweep status <id> must reach COMPLETED with both members launched. The orchestrator assumed the new role, so the trust works.
  • spawn doctor must show "sweep cross-account role ✓ … policy v1 (current)".

3. Check the guard read-only, if you want.

  • With the 942542972736 profile, run spawn sweep setup. It must refuse with the Amazon-internal reason before any IAM call.
  • Then confirm with that account's own profile that aws iam get-role --role-name SpawnSweepCrossAccountRole is still NoSuchEntity.

4. Teardown.

  • Once the sweep is COMPLETED, run spawn sweep teardown.
  • aws iam get-role must return NoSuchEntity.
  • Also run spawn sweep teardown during a running sweep once, to see the refusal.

5. Leak check in 435415984226, every region the sweep used.

  • aws ec2 describe-instances --filters Name=tag:spawn:sweep-id,Values=<id> Name=instance-state-name,Values=pending,running,stopping,stopped must be empty.
  • aws ec2 describe-spot-instance-requests --filters Name=state,Values=open,active must show none from the sweep.
  • spawn orphans must report nothing new.

6. Restore, if needed. If the account should keep the role, run spawn sweep setup. Restoring the exact old role from before-*.json should not be needed: the new role is a superset of what the orchestrator calls.

@scttfrdmn scttfrdmn added this to the Hardening milestone Nov 8, 2026
@scttfrdmn scttfrdmn added area:infra IAM, buckets, CloudFormation, releases component:spawn type:infra CI, build, and repo infrastructure labels Nov 8, 2026
A detached sweep (the default for spawn launch --param-file) and spawn
sweep resume --detach now create SpawnSweepCrossAccountRole in the
compute account before anything else, or adopt the one
scripts/setup-sweep-cross-account-role.sh made, and converge its trust
and policy on every run. spawn sweep setup does the same on its own;
spawn sweep teardown deletes the role and every policy on it, refusing
while a sweep with members in the account is running unless --force.

- Trust: sts:AssumeRole by SpawnSweepOrchestratorRole in the infra
  credentials' account, nothing else (the script's trust). No ExternalId:
  the orchestrator sends none at any of its three AssumeRole sites.
- Policy: SweepCrossAccountEC2Policy-v1 via putVersionedRolePolicy
  (#1558); the script's unversioned copy is deleted after the write.
  Five Describe grants the orchestrator never calls are dropped, and an
  iamcoverage test now fails on any uncalled grant.
- Boundary: refuses 942542972736 (hardcoded), any Organizations
  management account (organizations:DescribeOrganization where
  readable), and the shared infra account, before any IAM call.
- spawn doctor reports the role's presence and policy version.
- The manual script is removed; its policy tests now read the Go
  document.
@scttfrdmn
scttfrdmn force-pushed the fix/1537-provision-sweep-role branch from 4d90e47 to 095be86 Compare November 9, 2026 00:00
@codecov

codecov Bot commented Nov 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 78.31978% with 80 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
cmd/sweep_role.go 60.18% 43 Missing ⚠️
pkg/aws/sweep_role.go 88.50% 23 Missing ⚠️
pkg/doctor/aws_prober.go 64.28% 10 Missing ⚠️
pkg/sweep/store.go 82.35% 3 Missing ⚠️
pkg/orgaccount/orgaccount.go 90.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn

Copy link
Copy Markdown
Contributor Author

Live verification on 095be86a: spore-host-dev (435415984226) only

Setup: branch CLI built from a fresh clone at 095be86a (0.161.1-0.20261108235815-095be86a9b82). AWS_PROFILE=spore-host-dev SPAWN_COMPUTE_PROFILE=spore-host-dev SPAWN_INFRA_PROFILE=spore-host-infra. sts get-caller-identity returned 435415984226 (dev) and 966362334030 (infra).

Step 3 (the guard against 942542972736) was deliberately not run. No call went to that account; the unit tests cover the refusal.

Step Result
0 Build + pin accounts PASS
1 Snapshot, teardown of the script-created role, NoSuchEntity PASS
2 Real detached sweep from a clean state: create, trust, tag, policy, simulate, COMPLETED, doctor PASS
3 Guard against 942542972736 NOT RUN (excluded on purpose)
4 Teardown refuses while RUNNING, succeeds after COMPLETED; sweep setup re-creates it PASS
5 Leak check (us-east-1, us-west-2) PASS (nothing leaked)

1. Snapshot, then teardown

  • Pre-check: no sweep was in a non-terminal state (scan of spawn-sweep-orchestration: 32 COMPLETED, 1 CANCELLED), and no instances were running in dev.
  • Snapshot of the script role, created 2026-01-16:
    • trust: the single principal arn:aws:iam::966362334030:role/SpawnSweepOrchestratorRole, no condition;
    • inline policies: SweepCrossAccountEC2Policy only; no managed policies; no tags.
  • spawn sweep teardown printed ✓ Deleted SpawnSweepCrossAccountRole from account 435415984226, and get-role then returned NoSuchEntity.
  • This also exercised teardown of a script-created role (unversioned policy, no tag).

2. Detached sweep sweep-20261108-551000

  • 2 rows, t4g.small Spot, us-east-1, --max-concurrent 2 --ttl 20m, on_complete: terminate.
  • Output: 🔐 Created SpawnSweepCrossAccountRole in account 435415984226, trusted by arn:aws:iam::966362334030:role/SpawnSweepOrchestratorRole: …
  • Trust: {"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::966362334030:role/SpawnSweepOrchestratorRole"},"Action":"sts:AssumeRole"}. Exactly one statement, no Condition, no ExternalId.
  • Tag spawn:managed=true. list-role-policies returns exactly ["SweepCrossAccountEC2Policy-v1"], with no managed policies. This was the one real PutRolePolicy, and IAM accepted it.
  • The live SweepCrossAccountEC2Policy-v1 is identical to pkg/aws/testdata/sweep-cross-account-policy.golden.json once 111122223333 is replaced with 435415984226 (jq -S diff is empty).
  • simulate-principal-policy against the role:
    ec2:RunInstances        *                                   allowed
    ec2:TerminateInstances  *                                   allowed
    iam:PassRole  role/spored-instance-role (PassedToService=ec2)     allowed
    ec2:DescribeImages      *                                   implicitDeny
    iam:PassRole  role/spawn-instance-nested-x (PassedToService=ec2)  explicitDeny
    iam:PassRole  role/spored-instance-role (PassedToService=lambda)  implicitDeny   (extra negative)
    
  • CloudTrail (dev) recorded AssumeRole into the role at 2026-11-09T00:25:11Z by …:spawn-sweep-orchestrator, with no error. The new trust works.
  • Both members launched as Spot in us-east-1b (i-012234576e16d93ba, i-0ad558581c3ee8d22). spawn sweep status showed ✅ COMPLETED, 2/2 launched, 0 failed, about 60 s after creation.
  • spawn doctor: ✓ sweep cross-account role: SpawnSweepCrossAccountRole, policy v1 (current), trusts arn:aws:iam::966362334030:role/SpawnSweepOrchestratorRole

4. Teardown guard, teardown, re-create

  • While RUNNING, spawn sweep teardown exited 1 with: not deleting SpawnSweepCrossAccountRole: 1 sweep(s) with members in account 435415984226 are still running: sweep-20261108-551000 (RUNNING). … Wait for them, cancel them ('spawn sweep cancel <id>'), or pass --force. The role was untouched.
  • After COMPLETED, teardown printed ✓ Deleted …, and get-role returned NoSuchEntity.
  • spawn sweep setup printed 🔐 Created … and then ✓ … is current (policy SweepCrossAccountEC2Policy-v1). A second setup printed only ✓ … is current, so it is idempotent. Dev is left with a current, spawn-managed role.

Snapshot (script role) vs final (spawn-managed role):

  • Trust: identical.
  • Managed policies: none before, none after.
  • Inline policy name: SweepCrossAccountEC2Policy became SweepCrossAccountEC2Policy-v1.
  • Tags: none before; spawn:managed=true after.
  • Description: replaced by the spawn-managed text.
  • Policy, compared statement by statement with Sids ignored: the only difference is the 5 documented drops, ec2:DescribeImages, DescribeInstanceStatus, DescribeKeyPairs, DescribeSubnets and DescribeVpcs. Every Resource and Condition, including the PassRole allow and the nested deny, is unchanged.

5. Leak check

  • I compared a baseline taken before the run with the state after it, in us-east-1 and us-west-2.
  • Instances: none non-terminated. Both members terminated themselves through on_complete at 00:27:27Z and 00:28:15Z.
  • Spot requests: both were one-time and both are now closed / instance-terminated-by-user. One took about 2 minutes after its instance terminated to close. Open/active Spot requests in both regions: 0.
  • Volumes, EIPs, security groups, key pairs and placement groups: unchanged from the baseline.
  • spawn orphans output is identical before and after. It lists only a pre-existing us-west-2 key pair from 2026-10-24.
  • Usage: about 5 min 16 s of t4g.small Spot, roughly 0.09 instance-hours (well under $0.01).

Out of scope (none of this is in this PR's diff; noted for follow-up)

  • The launch output said Region: us-west-2 (SPORE_REGION/AWS_REGION or your spore config) because my shell had AWS_REGION set. The rows actually launched in us-east-1 from defaults.region, and sweep status reports us-east-1. The message comes from cmd/launch_regions.go.
  • The positional NAME live1537 was not used: the sweep shows Sweep Name: sweep.
  • After COMPLETED, sweep status still showed Next to Launch: 2, and both instances as pending although they were running.

Not merged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:infra IAM, buckets, CloudFormation, releases component:spawn type:infra CI, build, and repo infrastructure

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SpawnSweepCrossAccountRole is provisioned only by a manual script; detached sweeps (the default) need it

1 participant