Repository navigation
feat(sweep): spawn provisions SpawnSweepCrossAccountRole (#1537) - #1561
Merged
Merged
Conversation
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
force-pushed
the
fix/1537-provision-sweep-role
branch
from
November 9, 2026 00:00
4d90e47 to
095be86
Compare
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
Author
Live verification on
|
| 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:
SweepCrossAccountEC2Policyonly; no managed policies; no tags.
- trust: the single principal
spawn sweep teardownprinted✓ Deleted SpawnSweepCrossAccountRole from account 435415984226, andget-rolethen 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-policiesreturns exactly["SweepCrossAccountEC2Policy-v1"], with no managed policies. This was the one real PutRolePolicy, and IAM accepted it. - The live
SweepCrossAccountEC2Policy-v1is identical topkg/aws/testdata/sweep-cross-account-policy.golden.jsononce 111122223333 is replaced with 435415984226 (jq -Sdiff is empty). simulate-principal-policyagainst 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
AssumeRoleinto 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 statusshowed✅ 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 teardownexited 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 …, andget-rolereturned NoSuchEntity. spawn sweep setupprinted🔐 Created …and then✓ … is current (policy SweepCrossAccountEC2Policy-v1). A secondsetupprinted 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:
SweepCrossAccountEC2PolicybecameSweepCrossAccountEC2Policy-v1. - Tags: none before;
spawn:managed=trueafter. - 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,DescribeSubnetsandDescribeVpcs. 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_completeat 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 orphansoutput 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 fromdefaults.region, andsweep statusreports us-east-1. The message comes fromcmd/launch_regions.go. - The positional NAME
live1537was not used: the sweep showsSweep Name: sweep. - After COMPLETED,
sweep statusstill showedNext to Launch: 2, and both instances aspendingalthough they were running.
Not merged.
This was referenced Nov 9, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1537
What changes
SpawnSweepCrossAccountRoleused to be created only byscripts/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.spawn launch --param-file(detached, the default) andspawn sweep resume --detachensure the role in the compute account. This runs at the point whererequireDetachedSweepRoleused to refuse, before anything else is created. It adopts the script's role if one exists, and converges trust and policy on every run.TestDetachedSweepCreatesTheRoleFirstchecks that whenCreateRoleruns, nothing but the identity lookups has reached the account.spawn sweep setupdoes the same on its own. Every failure is an error there.spawn sweep teardownis the deleter. It deletes every inline policy, detaches every managed policy, and then deletes the role. It refuses while any sweep inspawn-sweep-orchestrationwithaws_account_id= this account is not COMPLETED/FAILED/CANCELLED. It also refuses when it cannot read the table.--forceoverrides both.spawn doctorgets a new check, "sweep cross-account role":iam:GetRole): warn and go on, as before.scripts/setup-sweep-cross-account-role.shis deleted. The tests that parsed it now read the Go document. No page indocs/or in the umbrella docs referenced it (checked with grep).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.gocreateCrossAccountEC2Clientlambda/sweep-orchestrator/main.goinitializeRegionalOrchestratorlambda/sweep-orchestrator/cancel.goassumeMemberClientsThe 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:
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.
TestTheOrchestratorSendsNoExternalIDpins 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.InvokeSweepOrchestratorwithLoadInfraAWSConfig):966362334030in shared mode. It is not hardcoded.AROA…unique ID.Policy
The golden file is
pkg/aws/testdata/sweep-cross-account-policy.golden.json. It is written asSweepCrossAccountEC2Policy-v1through #1560'sputVersionedRolePolicy. The script's unversionedSweepCrossAccountEC2Policyis 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/iamcoveragediscovered these member-account calls by the orchestrator:ec2:RunInstances, CreateTags, DescribeInstances, DescribeAvailabilityZones, DescribeSecurityGroups, TerminateInstances, CancelSpotInstanceRequests, DeletePlacementGroup, CreateSecurityGroup, Authorize/RevokeSecurityGroupIngress/Egressiam:PassRolessm:SendCommandandssm:GetCommandInvocationChanges from the script's statements:
ec2:DescribeImages,DescribeInstanceStatus,DescribeKeyPairs,DescribeSubnets,DescribeVpcs. Nothing calls them, andgit log -Sfinds them in source never, only in tracked binaries.iam:CreateServiceLinkedRole(Spot SLR), which RunInstances authorizes implicitly. It is recorded with that reason insweepRoleUncalledGrants.spawn-instance-*, to EC2 only. The explicit Deny ofspawn-instance-nested-*stays.bindPolicyAccount.New gates:
TestSweepCrossAccountRoleGrantsOnlyWhatTheOrchestratorCallsfails on any grant the orchestrator does not call. It is the over-grant half ofTestEveryPrincipalCallIsGranted.TestSweepPolicyGoldenpins sha256 of the template tosweepRolePolicySchema = 1.Account guard
aws.CheckSweepRoleAccounts(ctx, computeAccount, orchestratorAccount, mgmtLookup, warn)runs before any IAM call, andEnsureSweepCrossAccountRolere-checks the hardcoded list itself. It refuses when: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.pkg/orgaccountcallsorganizations:DescribeOrganizationand readsMasterAccountId. AWSOrganizationsNotInUse means no org. Denied or unreadable is a warning, and the check goes on: the hardcoded deny holds regardless.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)
GetRolefinds the role, and the outcome isFound.SweepTrustMatches). The script's trust already matches, so it is left alone.putVersionedRolePolicywritesSweepCrossAccountEC2Policy-v1, then deletesSweepCrossAccountEC2Policy. Put comes before Delete, so the role is never without its grants. This is tested.CreateRolethat returnsEntityAlreadyExistsmakes this run adopt the role instead.Tests (all hermetic; the AWS env stripped)
ensureSweepRole, detached and strict.--forcewarns and deletes.pkg/sweepActiveInAccounton substrate;pkg/orgaccount;docs/reference/cli-iam-actions.md,docs-gen/sweep.mdandapi/public-surface.txtare 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 assertTrustUpdatedthere.Locally: fmt, vet (all GOOS), staticcheck, golangci-lint (all 10 modules), hermetic short tests, tidy (all modules),
check-docs(clean once committed) andsemgrep scan --config=auto --error .all pass.Two
make checksteps fail only because the worktree path contains a space (/Volumes/External HD/…):lambda/dashboard-apiTestSetupAllRunsEveryStepFromAnyDirectory(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:UpdateAssumeRolePolicyiam:DeleteRole,iam:ListAttachedRolePolicies,iam:DetachRolePolicy(teardown)organizations:DescribeOrganizationTeardown also calls
dynamodb:Scanwith 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 Accountmust print435415984226.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, thenget-role-policyfor each name,> before-policy.json. Keep both for rollback.spawn sweep list --status RUNNING.spawn sweep teardown. It refuses if one is running.aws iam get-role --role-name SpawnSweepCrossAccountRolemust return NoSuchEntity.2. Run a real detached sweep end to end from that clean state.
spawn launch live1537 --param-file p.yaml --instance-type t4g.small --max-concurrent 2 --ttl 20m --yes, with 2 rows.--max-concurrentis what makes it really detach (--detach without --max-concurrent silently runs the sweep in the foreground (prints 'Lambda (detached)') #1535).aws iam get-roleshows the trust above and the tagspawn:managed=true.list-role-policiesshows exactlySweepCrossAccountEC2Policy-v1.aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::435415984226:role/SpawnSweepCrossAccountRole:ec2:RunInstances,ec2:TerminateInstances;iam:PassRoleonrole/spored-instance-rolewithiam:PassedToService=ec2.amazonaws.com;ec2:DescribeImages;iam:PassRoleonrole/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 doctormust show "sweep cross-account role ✓ … policy v1 (current)".3. Check the guard read-only, if you want.
spawn sweep setup. It must refuse with the Amazon-internal reason before any IAM call.aws iam get-role --role-name SpawnSweepCrossAccountRoleis still NoSuchEntity.4. Teardown.
spawn sweep teardown.aws iam get-rolemust return NoSuchEntity.spawn sweep teardownduring 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,stoppedmust be empty.aws ec2 describe-spot-instance-requests --filters Name=state,Values=open,activemust show none from the sweep.spawn orphansmust report nothing new.6. Restore, if needed. If the account should keep the role, run
spawn sweep setup. Restoring the exact old role frombefore-*.jsonshould not be needed: the new role is a superset of what the orchestrator calls.