Skip to content

fix(iam): version the spored grant policies so an older CLI cannot strip a newer one's grants (#1558) - #1560

Merged
scttfrdmn merged 2 commits into
mainfrom
fix/1558-monotonic-spored-role
Nov 8, 2026
Merged

scttfrdmn merged 2 commits into
mainfrom
fix/1558-monotonic-spored-role

Conversation

@scttfrdmn

Copy link
Copy Markdown
Contributor

Fixes #1558

What was wrong

The spored instance roles are shared. spored-instance-role serves every launch in the account that names no IAM. A spawn-instance-<hash> role (and the --nested-spawn role) serves every launch with the same IAM flags. On every launch, spawn overwrote the role's spored grants with whatever the launching CLI carried. There are three places that write them:

role policy written by
spored-instance-role spored-policy (sporedDCVRolePolicy) SetupSporedIAMRole
spawn-instance-*, --iam-role, nested-spawn spored-baseline-policy (sporedSelfManagementStatements, incl. sporedReadPermissions) ensureSporedBaselinePolicy
spawn-instance-* with --iam-policy spawn-inline-policy, which also embedded a full copy of the baseline createIAMRole / updateInlinePolicy (buildInlinePolicy)

The role name hashes the IAM config, not the CLI version. So two spawn versions in one account rewrote the same policy back and forth, and running instances lost whatever the newer one added. That is what the #1555 live test hit with ec2:DescribeSpotPriceHistory.

Options considered

  • (a) Monotonic merge by Sid. Rejected as the primary mechanism. The existing statements mostly have no Sid, so there is nothing to key on. A Sid-keyed merge also loses an action added inside an existing statement, and that is exactly the --cost-limit on Spot instances is enforced at the on-demand rate, and terminates the job without a signal #1497 change. Making Sids immutable would fix that, but then you need the schema-pin test below anyway, plus a GetRolePolicy/URL-decode/parse/merge on every launch. It also does nothing about CLIs that are already released.
  • (b) Versioned role names. Rejected. Every running instance holds its instance profile, so a new role per schema means a new profile per schema. You get a new spored-instance-profile-vN that consumers resolving the fixed name do not know about: the batch queue's default iam_role, sweep rows, lagotto's pkg/launcher, the nested-spawn children, iam:PassRole grants that users scope to spored-instance-role, and the reaper's shared-role exclusions. Each schema would also need a deleter that can tell when no instance still holds the profile. It is a much larger change, and it collides with SpawnSweepCrossAccountRole is provisioned only by a manual script; detached sweeps (the default) need it #1537.
  • (c) Schema marker + refuse to downgrade. This is the choice, together with the separate-name idea from the brief, and with the marker carried in the policy name.

The design

  1. A policy name no released CLI writes. spawn now writes spored-policy-v<schema> and spored-baseline-policy-v<schema> (sporedPolicySchema = 1). Every CLI up to v0.161.0 overwrites exactly spored-policy / spored-baseline-policy / spawn-inline-policy and touches no other name. IAM grants the union of a role's inline policies. So when an old CLI rewrites its own name after this one, it can only add. This is the only protection there can be against already-released CLIs, and it is complete for the failure in this issue.
  2. Refuse to downgrade. putVersionedRolePolicy lists the role's policies. If the role holds a version newer than the CLI's schema, the CLI writes nothing and warns ("written by a newer spawn … upgrade spawn"). The newer document already includes this CLI's grants, apart from deliberate retirements. Same schema means byte-identical document. TestSporedPolicySchemaPinsTheDocuments pins sha256 of all three documents to the schema, so changing a document without bumping the schema fails CI. As a result, no CLI from this one onward can remove a grant that a newer CLI added.
  3. A named deleter (leave no trace). After writing its version, the CLI deletes the unversioned policy and every older version. They are covered by the version just written, because every pre-spored-instance-role is shared and rewritten by whichever CLI version launches last; mixed-version accounts silently lose newer grants #1558 writer is older than schema 1.
  4. spawn-inline-policy carries only the templates now. The embedded baseline copy was a third copy that each version rewrote with its own grants. It would have brought back retired grants even from versioned CLIs, and it took about 2.1k of the role's 10,240-character budget. The versioned baseline is written on every role unconditionally (createOrGetInstanceProfile), so the copy was redundant. When no name in the list is a known template, no inline policy is written.

Removal path. Remove the statement, bump sporedPolicySchema, and update the pins. The first launch at schema N+1 deletes vN and the unversioned copy. After that, a schema-N CLI defers to it instead of writing the grant back (tested). For a grant that must be gone at once (dangerous, not just unneeded), also add an explicit Deny in vN+1. An explicit Deny beats any Allow an old CLI writes into its unversioned copy, and no old CLI touches the versioned name. This is documented on the constant and at the top of iam_policy_schema.go.

What happens when an old CLI launches after a new one

  • A v0.161.0 launch rewrites spored-policy (or spored-baseline-policy + spawn-inline-policy) with its own document. spored-policy-v1 is untouched. The effective grants are old ∪ v1 = v1. No grant is lost, so the spored-instance-role is shared and rewritten by whichever CLI version launches last; mixed-version accounts silently lose newer grants #1558 failure cannot recur from any CLI version, old or new, once one new CLI has launched in the account.

  • What old CLIs can still do, and nothing can stop it: (1) put a retired Allow back into their own copy until the next new launch deletes that copy (mitigated by the Deny rule above); (2) leave a second copy behind, which the next new launch deletes.

  • Size in that mixed state, with whitespace not counted, as measured by TestSporedRolesFitTheInlineLimitWhenMixed through a schema bump on a fake that enforces the cap:

    • spored-instance-role with two custom DNS updaters: 5,926 / 10,240.
    • spawn-instance-* with all 13 --iam-policy templates: 7,722.
    • nested-spawn role: 8,067.

    The ordering keeps the role at no more than two spored copies, even during a schema bump: copies covered by an existing version are deleted first, the newest one after the write. Without that, the nested role would hit about 10.3k (three copies) and fail.

Also fixed

ensureSporedBaselinePolicy wrapped PutRolePolicy in retryIAM, which counts LimitExceeded as success. That is right for AddRoleToInstanceProfile. For PutRolePolicy it means the policy was too big and not written, and the launch went ahead without the baseline. The spored writes now use retryIAMWrite (throttle/ConcurrentModification only), so a size refusal fails the launch.

Permissions

Launch now also calls iam:ListRolePolicies and iam:DeleteRolePolicy; docs/reference/cli-iam-actions.md is regenerated. Without them, the CLI still writes its version (purely additive), warns, and leaves the superseded copy. It never fails the launch. A failed delete is a warning that includes the exact aws iam delete-role-policy command. NoSuchEntity on delete (a concurrent launch got there first) counts as success.

Tests

pkg/aws/iam_policy_schema_test.go:

  • Sequences on a fake IAM that enforces the cap:
    • new → old (v0.161.0's document, i.e. without DescribeSpotPriceHistory) → new, for both spored-policy and spored-baseline-policy. The grant never leaves the role.
    • old → new. Call order is asserted: Put before Delete, so the role is never without its grants.
  • Removal path: v1 → v2 (grant dropped), then schema-1 CLI (writes nothing, warns once), then pre-spored-instance-role is shared and rewritten by whichever CLI version launches last; mixed-version accounts silently lose newer grants #1558 CLI (copy reappears), then v2 (copy deleted, grant gone).
  • Schema bump on a role carrying legacy + v1 + v2 → v3: delete order asserted, peak no more than two copies.
  • Unrelated policies: unrelated names and look-alikes (-v0, -vX, -v1-…, the other base) are untouched.
  • Error paths: List denied, Delete denied, already deleted, and LimitExceeded returned as an error.
  • parseVersionedPolicyName table.
  • Schema pin: sha256 of the three documents.
  • Size: every role kind in the mixed state, through a schema bump.
  • Against the substrate emulator: SetupSporedIAMRole new → simulated v0.161.0 PutRolePolicy → new, and a spawn-instance-* role set up by an old CLI and then by a new one, read back from IAM.

Existing tests were moved to the versioned names. Tests that used buildInlinePolicy(nil) as "the baseline" now use sporedBaselinePolicy(). The nested-spawn discovery gate lists the two new actions as "nested spores never write IAM".

make check was run locally with the AWS env stripped (GOTOOLCHAIN=go1.27.3). Everything passed except three failures caused by the worktree's path containing a space (/Volumes/External HD/…):

  • hermetic-exec (worked around with HERMETIC_EXEC=);
  • lambda/dashboard-api TestSetupAllRunsEveryStepFromAnyDirectory (lstat …/HD);
  • the check-build-tags file-coverage cross-check. Every tagged go vet passed.

semgrep scan --config=auto --error . is clean.

Live verification plan (owner)

No AWS access was used to write this. Use AWS_PROFILE=spore-host-dev (435415984226) and region us-east-1 throughout. Set V161=spawn (the Homebrew v0.161.0; check with spawn version) and BR=~/.xtmp/spawn-1558/bin/spawn (go build -o ~/.xtmp/spawn-1558/bin/spawn . on this branch). pol = aws iam list-role-policies --role-name <role> --region us-east-1, and doc <role> <name> = aws iam get-role-policy --role-name <role> --policy-name <name> --query PolicyDocument.

0. Snapshot. pol spored-instance-role, plus doc of each listed policy → ~/.xtmp/1558-before/.

1. One real PutRolePolicy on a throwaway role (branch CLI).
$BR launch 1558-a --instance-type t4g.small --spot --ttl 20m --iam-role spawn-1558-throwaway

  • Expect: pol spawn-1558-throwaway = ["spored-baseline-policy-v1"] (no spawn-inline-policy, no unversioned copy).
  • Expect: doc spawn-1558-throwaway spored-baseline-policy-v1 contains ec2:DescribeSpotPriceHistory and the literal account ID, with no SPAWN-ACCOUNT-ID placeholder.
  • CloudTrail PutRolePolicy for spored-baseline-policy-v1 succeeded.
  • Then $BR terminate 1558-a, wait for terminated, and delete the throwaway role:
    • aws iam delete-role-policy --role-name spawn-1558-throwaway --policy-name spored-baseline-policy-v1
    • aws iam detach-role-policy … --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
    • aws iam remove-role-from-instance-profile …
    • aws iam delete-instance-profile …
    • aws iam delete-role …

2. Mixed versions on spored-instance-role (no IAM flags, t4g.small --spot --ttl 30m):

step command expected pol spored-instance-role expected grant check
2a $V161 launch 1558-b1 … spored-policy (+ any spored-dns-invoke-*) doc … spored-policy has no DescribeSpotPriceHistory; aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::435415984226:role/spored-instance-role --action-names ec2:DescribeSpotPriceHistory → implicitDeny (the bug's state)
2b $BR launch 1558-b2 … spored-policy-v1, no spored-policy simulate → allowed; CloudTrail: PutRolePolicy spored-policy-v1 before DeleteRolePolicy spored-policy
2c $V161 launch 1558-b3 … spored-policy and spored-policy-v1 simulate → allowed (the fix: the old CLI no longer strips it); on the 1558-b2 instance over SSM: aws ec2 describe-spot-price-history --instance-types t4g.small --product-descriptions Linux/UNIX --max-items 1 --region us-east-1 succeeds
2d $BR launch 1558-b4 … spored-policy-v1 only simulate → allowed

3. (Optional) the --iam-policy path. Repeat 2a–2c with --iam-policy s3:ReadOnly on both CLIs, against the same spawn-instance-<hash> role (same flags, so same hash):

  • After the branch launch: spored-baseline-policy-v1 + spawn-inline-policy, and spawn-inline-policy holds only the s3 statement.
  • After v0.161.0 again: spored-baseline-policy + spawn-inline-policy (with v0.161.0's baseline copy) + spored-baseline-policy-v1. Simulate on that role → allowed.

4. (Optional) refuse-to-downgrade, live.

  • Copy spored-policy-v1 to spored-policy-v2: aws iam put-role-policy --role-name spored-instance-role --policy-name spored-policy-v2 --policy-document "$(doc spored-instance-role spored-policy-v1)".
  • $BR launch 1558-c … must print the "written by a newer spawn (policy schema v2; this spawn writes v1)" warning, and CloudTrail must show no PutRolePolicy/DeleteRolePolicy from it.
  • Then delete spored-policy-v2 by hand.

5. Reap and verify (leave no trace).

  • Terminate every 1558-* instance.
  • aws ec2 describe-instances --filters Name=tag:Name,Values='1558-*' Name=instance-state-name,Values=pending,running,stopping,stopped --region us-east-1 must return nothing.
  • aws ec2 describe-spot-instance-requests --filters Name=state,Values=open,active must show no 1558 requests.
  • pol spored-instance-role should be exactly spored-policy-v1 plus whatever spored-dns-invoke-* the snapshot had. Diff against ~/.xtmp/1558-before/: the only difference is spored-policy → spored-policy-v1, including DescribeSpotPriceHistory.

Cost: about four or five t4g.small Spot instances for under 30 min, which is under $0.05.

Follow-ups (not in this PR)

  • lagotto calls pkg/launcher.Provision → SetupSporedIAMRole under its own poller role. When it picks up this spawn, it needs iam:ListRolePolicies + iam:DeleteRolePolicy on spored-instance-role. Until then it degrades to the additive write and logs the warning.
  • SpawnSweepCrossAccountRole is provisioned only by a manual script; detached sweeps (the default) need it #1537 (SpawnSweepCrossAccountRole provisioning) can reuse putVersionedRolePolicy(ctx, api, role, base, doc, schema, warn) for any role that more than one CLI version rewrites. The function takes a narrow rolePolicyAPI interface and a schema, so a second role kind with its own schema constant fits without changes here.
  • PolicyTemplates content (spawn-inline-policy) and the per-function spored-dns-invoke-* grants are also rewritten per launch. They are user-chosen or static, not spored's own grants, and are not versioned here.

@scttfrdmn scttfrdmn added this to the Hardening milestone Nov 8, 2026
@scttfrdmn scttfrdmn added area:spored on-node agent: lifecycle, telemetry, readiness type:bug labels Nov 8, 2026
@codecov

codecov Bot commented Nov 8, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.34513% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
pkg/aws/iam_policy_schema.go 97.05% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn

Copy link
Copy Markdown
Contributor Author

Live verification: spore-host-dev (435415984226), us-east-1, 2026-11-08 23:20–23:37 UTC

Result: every step PASSES. No code issues found.

Setup

  • Branch CLI: built from PR head 9e42dade, which reports 0.161.1-0.20261108225957-9e42dade3cb6.
  • Old CLI: spawn_0.161.0_darwin_arm64.tar.gz from the GitHub release, not Homebrew. Its sha256 0a8378ba…cc1d604 matches the release checksums.txt. It reports commit c2ec109c.
  • Every launch used t4g.small --spot --ttl 1h --no-dns --yes.
  • Before anything, sts get-caller-identity returned account 435415984226.
  • Negative control in every simulate: iam:CreateUser came back implicitDeny each time.

0. Snapshot: PASS

spored-instance-role before the run:

  • inline: spored-binary-download-policy, spored-mpi-s3-policy, spored-policy;
  • attached: AmazonSSMManagedInstanceCore.

The pre-existing spored-policy already contained DescribeSpotPriceHistory. A #1555 branch build had written it, and it is byte-identical to this PR's v1 document.

1. Throwaway role (branch): PASS

  • --iam-role spawn-1558-throwaway: list-role-policies = ["spored-baseline-policy-v1"]. There is no spawn-inline-policy and no unversioned copy.
  • The doc contains ec2:DescribeSpotPriceHistory, the literal account ID twice, and no SPAWN-ACCOUNT-ID placeholder. It is 2,105 chars minified.
  • Trust is ec2.amazonaws.com with aws:SourceAccount=435415984226.
  • CloudTrail 23:21:11 PutRolePolicy spawn-1558-throwaway spored-baseline-policy-v1: ok. That is the real PutRolePolicy, accepted.
  • simulate: ec2:DescribeSpotPriceHistory allowed (spored-baseline-policy-v1), iam:CreateUser implicitDeny.
  • The instance was terminated, and the role and profile were deleted.

2. Mixed versions on spored-instance-role: PASS

In the policies column, the two unrelated inline policies (spored-binary-download-policy, spored-mpi-s3-policy) are present at every step and unchanged; they are left out below.

step CLI spored policies after DescribeSpotPriceHistory in doc simulate ec2:DescribeSpotPriceHistory
2a v0.161.0 (1558-b1) spored-policy 0 implicitDeny (the bug reproduced)
2b branch (1558-b2) spored-policy-v1 1 allowed via spored-policy-v1
2c v0.161.0 (1558-b3) spored-policy + spored-policy-v1 0 / 1 allowed via spored-policy-v1 (the fix)
2d branch (1558-b4) spored-policy-v1 1 allowed via spored-policy-v1

2c, real call over SSM on 1558-b2 (the branch-launched instance, after the old CLI had rewritten spored-policy):

arn:aws:sts::435415984226:assumed-role/spored-instance-role/i-04ac73a1b2baa9be4
aws ec2 describe-spot-price-history --instance-types t4g.small --product-descriptions Linux/UNIX --max-items 1 --region us-east-1
-> {"SpotPriceHistory":[{"AvailabilityZone":"us-east-1f","InstanceType":"t4g.small","SpotPrice":"0.010300",...}]}  rc=0
negative control: aws iam list-users -> AccessDenied (no identity-based policy allows iam:ListUsers)

CloudTrail (spored-instance-role, all calls from the test session; no other principal touched the role during the run):

23:23:37 PutRolePolicy    spored-policy      (2a, v0.161.0)
23:24:24 PutRolePolicy    spored-policy-v1   (2b, branch)
23:24:24 DeleteRolePolicy spored-policy      (2b)
23:25:21 PutRolePolicy    spored-policy      (2c, v0.161.0; v1 untouched)
23:26:17 DeleteRolePolicy spored-policy      (2d, branch)
23:26:17 PutRolePolicy    spored-policy-v1   (2d)

CloudTrail eventTime has 1-second resolution, and each pair falls in the same second. lookup-events returns ties in arbitrary order: for 2b and 2d it listed them in the opposite order to the real one. So CloudTrail cannot show the ordering.

I measured it against real IAM with a scratch-only harness instead. It is a build-tagged test in an exported copy of 9e42dade, not committed. It wraps a real iam.Client with nanosecond-stamped recording and runs putVersionedRolePolicy on a throwaway ec2-trusted role, spawn-1558-order (since deleted):

-- A: role holds [spored-baseline-policy]                       (the 2b case)
23:32:04.944940 ListRolePolicies [spored-baseline-policy]
23:32:05.084109 PutRolePolicy    spored-baseline-policy-v1
23:32:05.196670 DeleteRolePolicy spored-baseline-policy        -> Put BEFORE Delete
-- B: role holds [spored-baseline-policy, spored-baseline-policy-v1]   (the 2d case)
23:32:05.431165 ListRolePolicies [...both...]
23:32:05.612766 DeleteRolePolicy spored-baseline-policy
23:32:05.740684 PutRolePolicy    spored-baseline-policy-v1     -> Delete first, by design (v1 already covers it; keeps <=2 copies)

Note for the plan: in 2d the legacy copy is deleted before the Put. That is correct, because -v1 is already on the role and covers it. The "Put before Delete" expectation applies only to the first new-CLI launch (2b).

3. --iam-policy s3:ReadOnly (new role spawn-instance-d83504c4): PASS

Simulate covered ec2:DescribeSpotPriceHistory and s3:GetObject.

step CLI policies (statements, chars) DescribeSpot s3:GetObject
3a v0.161.0 spawn-inline-policy (13, 2,195), spored-baseline-policy (12, 2,074) implicitDeny allowed
3b branch spawn-inline-policy (1 statement, 160 chars: only the s3 read), spored-baseline-policy-v1 (12, 2,105) allowed allowed
3c v0.161.0 spawn-inline-policy (13, back to the embedded baseline copy), spored-baseline-policy, spored-baseline-policy-v1 allowed (via v1) allowed

CloudTrail for 3b: PutRolePolicy spored-baseline-policy-v1, PutRolePolicy spawn-inline-policy, DeleteRolePolicy spored-baseline-policy, all ok. The role was deleted afterwards because this test created it.

4. Refuse-to-downgrade: PASS

  • I planted spored-policy-v2 as a copy of v1, then ran a branch launch (1558-c). It printed:

    ⚠️ IAM role spored-instance-role carries spored-policy-v2, written by a newer spawn (policy schema v2; this spawn writes v1). Leaving the role's grants as that version set them: they include this version's, so instances launched now get them. Upgrade spawn to stop this warning (#1558).

  • The policies stayed spored-policy-v1 + spored-policy-v2.
  • CloudTrail between the plant (23:27:41) and my manual delete of v2 (23:28:16) shows no Put or Delete from the launch.
  • The launch succeeded.

5. Reap and verify: PASS

Instances. All 9 instances (1558-a, b1–b4, c, d1–d3) are terminated. The account has no pending, running or stopped instances.

Independent leak check in us-east-1:

  • 0 open or active Spot requests;
  • 0 volumes;
  • 0 EIPs;
  • security groups and key pairs identical to the pre-run baseline;
  • no *1558* roles or instance profiles;
  • spawn-instance-d83504c4 deleted.

Snapshot diff for spored-instance-role. The only differences are:

  • inline name spored-policy → spored-policy-v1. The document is byte-identical, so DescribeSpotPriceHistory is still present.
  • RoleLastUsed.LastUsedDate.

The trust policy, the other two inline policies, the attached AmazonSSMManagedInstanceCore and the instance profile are unchanged. The role is in the end state the branch expects, so nothing was restored.

Cost: 9 t4g.small Spot instances, 4,189 instance-seconds in total, about 1.16 instance-hours (~$0.012 at $0.0103/h).

Not merged.

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

Labels

area:spored on-node agent: lifecycle, telemetry, readiness type:bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

spored-instance-role is shared and rewritten by whichever CLI version launches last; mixed-version accounts silently lose newer grants

1 participant