Skip to content

feat(reaper): self-hosted reaper plans its own removal when the account is idle (report mode) (#1655) - #1668

Merged
scttfrdmn merged 1 commit into
mainfrom
feat/1655-selfhosted-reaper-removal
Nov 20, 2026
Merged

scttfrdmn merged 1 commit into
mainfrom
feat/1655-selfhosted-reaper-removal

Conversation

@scttfrdmn

Copy link
Copy Markdown
Contributor

Part of #1655 (leave-no-trace, spore-host/spore-host#752). Draft, report mode only: nothing is created or deleted. The reap flip is #1657.

What it does

The reaper spawn reaper deploy made (spawn-ttl-reaper-selfscan, scanning only its own account) now plans its own removal once the account-idle sweep (#1665) has, in one run, claimed, re-checked and reported every scope it judges (each scanned region and global), and its artifact bucket holds only ttl-reaper/ objects. The plan is made under the global scope's lease and logged; nothing is executed.

The plan, in execution order (offsets from the plan)

# how offset what target
1 direct 0 create group spawn-reaper-teardown (tagged spore-host:managed-by=spawn) scheduler:CreateScheduleGroup
2 one-shot spawn-reaper-teardown-function +2m delete the function aws-sdk:lambda:deleteFunction
3 one-shot spawn-reaper-teardown-role-inline +4m delete inline spawn-ttl-reaper-selfscan-policy aws-sdk:iam:deleteRolePolicy
4 one-shot spawn-reaper-teardown-role-managed +4m detach AWSLambdaBasicExecutionRole aws-sdk:iam:detachRolePolicy
5 one-shot spawn-reaper-teardown-role +5m delete spawn-ttl-reaper-selfscan-role aws-sdk:iam:deleteRole
6 one-shot spawn-reaper-teardown-log-group +15m delete /aws/lambda/spawn-ttl-reaper-selfscan aws-sdk:cloudwatchlogs:deleteLogGroup
7 direct 0 empty + delete the artifact bucket, only if tagged spawn:managed=true and holding only ttl-reaper/ (untagged: kept; anything else: no plan at all) s3:DeleteBucket
8-13 direct 0 for both rules (schedule, instance-terminated): remove target, delete rule, remove invoke permission events:RemoveTargets, events:DeleteRule, lambda:RemovePermission

Jobs: fixed names, ActionAfterCompletion=DELETE, FlexibleTimeWindow=OFF, run as spawn-reaper-teardown-invoke (never the reaper's own role); ConflictException on the group or a job counts as success, so a crashed run resumes. Steps 3-5 are dropped (role kept, logged) when another enabled region has a spawn-ttl-reaper-selfscan function (the role is account-wide) or that can't be checked.

Order differs from the issue's listing on purpose: jobs first, triggers last, as in lagotto#335. If the jobs can't be created the rules still fire and the next run retries with the same names; deleting the rules first would leave a reaper that never runs again. Role policies at +4m and role at +5m (not both at +5m), because DeleteRole refuses a role that still has policies.

Log lines: reaper-selfremoval REPORT step=<i>/<n> action=<what> how=<direct|one-shot|kept> offset=+<d> target=<api> resource=<arn> [name= group= at= input=] [reason=], then reaper-selfremoval REPORT account=… region=… steps=13 one_shots=5 direct=8 kept=0 group=spawn-reaper-teardown invoke_role=… role_kept=….

Mode

REAPER_SELF_REMOVAL=off|report|reap (default report; spawn reaper deploy --self-removal). effectiveSelfRemovalMode maps reap to report until #1657, pinned by TestSelfRemovalReapStillReports. The CreateOneShots call is already in the code behind that mapping, so the IAM coverage gate checks the scheduler grants against a real call site.

Keeping scopes in phase

Each report releases its lease, which restarts that scope's grace, so scopes reported in different runs would never be reported in the same run again. A regional-only lease mark (most launches) causes exactly that. So, for the self-hosted reaper only, when nothing is active or unreadable and some scope is still inside its grace, a scope that is already past the grace is held (logged, account_idle_held) until every scope is past it. If anything is active, the per-scope reports run as in #1665. A scope no creator has marked doesn't block, as long as nothing in it is active.

The invoke role (created at spawn reaper deploy, never at idle time)

spawn-reaper-teardown-invoke, tagged like the rest of the reaper (spore-host:managed-by=spawn, spore-host:component=ttl-reaper, no spore-host:role).

Trust:

{"Effect":"Allow","Principal":{"Service":"scheduler.amazonaws.com"},"Action":"sts:AssumeRole","Condition":{"StringEquals":{"aws:SourceAccount":"<acct>"}}}

Inline spawn-reaper-teardown-invoke-policy:

  • Allow lambda:DeleteFunction on arn:aws:lambda:*:<acct>:function:spawn-ttl-reaper-selfscan
  • Allow logs:DeleteLogGroup on arn:aws:logs:*:<acct>:log-group:/aws/lambda/spawn-ttl-reaper-selfscan and …:*
  • Allow iam:DeleteRolePolicy, iam:DeleteRole on arn:aws:iam::<acct>:role/spawn-ttl-reaper-selfscan-role
  • Allow iam:DetachRolePolicy on that role, if ArnEquals iam:PolicyARN = arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
  • Deny * on * if aws:ResourceTag/spore-host:role = service
  • Deny iam:Create*|Delete*|Put*|Set*|Tag*|Untag*|Update*|Attach*|Detach* on arn:aws:iam::<acct>:policy/spore-host/spawn-instance-boundary

The reaper's own role (one inline policy, reaperdeploy.PolicyDocument = reaperiam scan-self + own-account + these) gains:

  • lambda:GetFunction on arn:aws:lambda:*:<acct>:function:spawn-ttl-reaper-selfscan (its own tags, other regions)
  • s3:ListBucket, s3:GetBucketTagging on arn:aws:s3:::spawn-reaper-artifacts-<acct>-* (+ the --bucket one if custom)
  • scheduler:CreateSchedule on arn:aws:scheduler:*:<acct>:schedule/spawn-reaper-teardown/*
  • scheduler:CreateScheduleGroup, scheduler:TagResource on arn:aws:scheduler:*:<acct>:schedule-group/spawn-reaper-teardown
  • iam:PassRole on arn:aws:iam::<acct>:role/spawn-reaper-teardown-invoke if StringEquals iam:PassedToService = scheduler.amazonaws.com

These are not in reaperiam.ScanSelfStatements, so the cross-account member role and the SAM template are unchanged. The operated reaper never removes itself.

Not yet verified against real IAM. There's no AWS access here. Both documents need a real PutRolePolicy on a throwaway role, and simulation, before this merges.

Human path

spawn reaper teardown works as before, and now also deletes the spawn-reaper-teardown group and the invoke role (needs scheduler:DeleteScheduleGroup and scheduler:DeleteSchedule; see docs/reference/cli-iam-actions.md). --if-idle-for is unchanged (#1665).

Gates / tests

  • internal/iamcoverage: new principal ttl-reaper self-removal (root (*reaper).removeSelf, variant = PolicyDocument, passes the invoke role to Scheduler); the ttl-reaper principal cuts it. Implied rules added from the SAR: CreateScheduleGroup + Tags → scheduler:TagResource; DeleteScheduleGroup → scheduler:DeleteSchedule.
  • pkg/reaperiam drift gates cut the same entry; pkg/reaperdeploy TestSelfRemovalCallsAreGranted holds that subtree to the self-hosted policy in both directions.
  • Policy reach is checked with a test-local evaluator: TestTheTeardownInvokeRoleCanDeleteOnlyTheReaper, TestTheReaperCannotDeleteItself, TestSelfRemovalStatementsReach; size TestThePolicyFitsAnInlinePolicy.
  • Builder: offsets, fixed names, inputs, ConflictException resume, stop on error and on a lost lease.
  • Lambda: idle vs active, every-scope-reported, hold, unmarked region, off / other account, repurposed bucket, shared role, self-hosted detection, report makes zero writes (one fake implementing every Deployer API), reap still reports.
  • Each gate was watched failing against a revert that compiles.

…ccount is idle (report mode) (#1655)

Part of #1655 (leave-no-trace, spore-host/spore-host#752). Report mode only:
nothing is created or deleted; reap reports until #1657.

- lambda/ttl-reaper: when `spawn reaper deploy`'s reaper (spawn-ttl-reaper-
  selfscan, scanning only its own account) has, in one run, reported every
  account-idle scope and its artifact bucket holds only ttl-reaper/ objects,
  it plans its removal under the global lease and logs every step
  (`reaper-selfremoval REPORT step=... offset=... target=... resource=...`)
  and a summary. REAPER_SELF_REMOVAL=off|report|reap, default report;
  effectiveSelfRemovalMode maps reap to report (pinned). A due scope is held
  while another is inside its grace and nothing is active, so every scope
  comes due in one run (each report restarts its own grace).
- pkg/reaperdeploy: the plan (one-shot jobs in spawn-reaper-teardown: the
  function at +2m, role policies at +4m, the role at +5m unless another
  region's reaper shares it, the log group at +15m; then the bucket, only when
  tagged spawn:managed; then the rules, targets and permissions), the one-shot
  builder (fixed names, ConflictException resumes), the
  spawn-reaper-teardown-invoke role created at deploy (Scheduler trust for
  this account only; may delete only the reaper's function, log group and
  role; Denies on role=service and the boundary), the reaper role's added
  grants, and teardown removing the group and the invoke role.
- IAM gates: a self-removal principal in internal/iamcoverage, cut from the
  shared reaper inventory; SAR implied rules for CreateScheduleGroup tags and
  DeleteScheduleGroup; a policy evaluator test for both roles' reach.
- spawn reaper deploy --self-removal.
@scttfrdmn

Copy link
Copy Markdown
Contributor Author

IAM verification (dev 435415984226, 2026-11-20)

The documents were generated from this branch (TeardownInvokeTrustPolicy, TeardownInvokePolicyDocument, PolicyDocument) and applied for real to throwaway roles. The trust policy and both PutRolePolicy calls were accepted. Simulation:

Teardown invoke role

Check Result
lambda:DeleteFunction selfscan, logs:DeleteLogGroup its group, iam:DeleteRole the reaper role, iam:DetachRolePolicy with AWSLambdaBasicExecutionRole allowed
DeleteFunction on spawn-dashboard-api, DeleteRole on itself, Detach AdministratorAccess implicitDeny
DeletePolicy on the boundary explicitDeny
DeleteFunction on a resource tagged role=service explicitDeny

Reaper role

Check Result
CreateSchedule in spawn-reaper-teardown, CreateScheduleGroup on it, PassRole of the invoke role to scheduler.amazonaws.com allowed
DeleteFunction on itself, PassRole to lambda.amazonaws.com, CreateSchedule in default implicitDeny

The test roles were deleted.

@scttfrdmn
scttfrdmn marked this pull request as ready for review November 20, 2026 17:21
@codecov

codecov Bot commented Nov 20, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.23729% with 17 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
pkg/reaperdeploy/selfremoval.go 94.11% 16 Missing ⚠️
pkg/reaperdeploy/deployer.go 95.23% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn
scttfrdmn merged commit 7337bb2 into main Nov 20, 2026
9 checks passed
@scttfrdmn
scttfrdmn deleted the feat/1655-selfhosted-reaper-removal branch November 20, 2026 17:46
scttfrdmn added a commit that referenced this pull request Nov 20, 2026
After a command succeeds, the root command's post-run hook runs
libs/lastmile (v0.55.0) for spawn: it reports a stale teardown lease (with
its plan re-checked by pkg/teardown's report-only deleter), the self-hosted
reaper's teardown residue (the spawn-reaper-teardown-invoke role and each
region's spawn-reaper-teardown schedule group, #1668) once no spawn
lifecycle item is left, and an empty spore-host-lifecycle table.

Report only and never in the way: nothing on stdout, nothing at all
without --verbose (then debug: lines on stderr), the exit status is
untouched, the hook stops waiting after the 30 s budget, between 6-hourly
checks it makes no AWS call, and a cut-off check waits an hour. The
account comes from the command's own GetCallerIdentity, observed
passively through an inert pkg/config seam that only cmd.Execute sets.
The lifecycle client refuses every write and the Deleter every delete.
Skipped after completion, help, version, footprint, teardown, doctor,
cleanup, every reaper subcommand and hidden plumbing commands, and in the
infra account; SPORE_LASTMILE=off turns it off.

FullVisibility is false: the account-idle verdict is package main of
lambda/ttl-reaper and not reusable from cmd. The decision (an activity
reader AND readable infra-account tables) is encoded and tested both ways.

The wiring is in cmd/lastmile.go; the AWS-touching pieces are in the new
pkg/lastmilespawn (cmd may not import SDK services, #326/#327). libs is
bumped to v0.55.0 in the root, ttl-reaper and sweep-orchestrator modules.

Part of spore-host/libs#78.
scttfrdmn added a commit that referenced this pull request Nov 20, 2026
After a command succeeds, the root command's post-run hook runs
libs/lastmile (v0.55.0) for spawn: it reports a stale teardown lease (with
its plan re-checked by pkg/teardown's report-only deleter), the self-hosted
reaper's teardown residue (the spawn-reaper-teardown-invoke role and each
region's spawn-reaper-teardown schedule group, #1668) once no spawn
lifecycle item is left, and an empty spore-host-lifecycle table.

Report only and never in the way: nothing on stdout, nothing at all
without --verbose (then debug: lines on stderr), the exit status is
untouched, the hook stops waiting after the 30 s budget, between 6-hourly
checks it makes no AWS call, and a cut-off check waits an hour. The
account comes from the command's own GetCallerIdentity, observed
passively through an inert pkg/config seam that only cmd.Execute sets.
The lifecycle client refuses every write and the Deleter every delete.
Skipped after completion, help, version, footprint, teardown, doctor,
cleanup, every reaper subcommand and hidden plumbing commands, and in the
infra account; SPORE_LASTMILE=off turns it off.

FullVisibility is false: the account-idle verdict is package main of
lambda/ttl-reaper and not reusable from cmd. The decision (an activity
reader AND readable infra-account tables) is encoded and tested both ways.

The wiring is in cmd/lastmile.go; the AWS-touching pieces are in the new
pkg/lastmilespawn (cmd may not import SDK services, #326/#327). libs is
bumped to v0.55.0 in the root, ttl-reaper and sweep-orchestrator modules.

Part of spore-host/libs#78.
scttfrdmn added a commit that referenced this pull request Nov 20, 2026
* feat: the lazy CLI last mile, report mode (libs#78)

After a command succeeds, the root command's post-run hook runs
libs/lastmile (v0.55.0) for spawn: it reports a stale teardown lease (with
its plan re-checked by pkg/teardown's report-only deleter), the self-hosted
reaper's teardown residue (the spawn-reaper-teardown-invoke role and each
region's spawn-reaper-teardown schedule group, #1668) once no spawn
lifecycle item is left, and an empty spore-host-lifecycle table.

Report only and never in the way: nothing on stdout, nothing at all
without --verbose (then debug: lines on stderr), the exit status is
untouched, the hook stops waiting after the 30 s budget, between 6-hourly
checks it makes no AWS call, and a cut-off check waits an hour. The
account comes from the command's own GetCallerIdentity, observed
passively through an inert pkg/config seam that only cmd.Execute sets.
The lifecycle client refuses every write and the Deleter every delete.
Skipped after completion, help, version, footprint, teardown, doctor,
cleanup, every reaper subcommand and hidden plumbing commands, and in the
infra account; SPORE_LASTMILE=off turns it off.

FullVisibility is false: the account-idle verdict is package main of
lambda/ttl-reaper and not reusable from cmd. The decision (an activity
reader AND readable infra-account tables) is encoded and tested both ways.

The wiring is in cmd/lastmile.go; the AWS-touching pieces are in the new
pkg/lastmilespawn (cmd may not import SDK services, #326/#327). libs is
bumped to v0.55.0 in the root, ttl-reaper and sweep-orchestrator modules.

Part of spore-host/libs#78.

* test: the no-budget-left case is already past its deadline (Windows clock)

A 1 ns budget can still read as positive under Windows' coarse clock, so
lastmile.Run ran. A negative budget is past its deadline everywhere.

Part of spore-host/libs#78.

* CHANGELOG: keep [0.168.0] as tagged; last-mile entries under [Unreleased]

---------

Co-authored-by: spore-host release <[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.

1 participant