carlos / platform Public

docs: plan 2b-1 review round 1 fixes

Four-tag IAM scope for terminate and console output, no wildcard
boundary without app storage, delivered-key set, unconditioned
ListBucket, tagged bucket creation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c0db57801a48bf4b1df2762f6d6260b7db6f267e parent cde7f69
1 file changed, +120 −50
  • docs/superpowers/plans/2026-11-08-managed-fleets-2b1-console-aws.md +120 −50
diff --git a/docs/superpowers/plans/2026-11-08-managed-fleets-2b1-console-aws.md b/docs/superpowers/plans/2026-11-08-managed-fleets-2b1-console-aws.md
index 93de419e9..ca9efdad2 100644
--- a/docs/superpowers/plans/2026-11-08-managed-fleets-2b1-console-aws.md
+++ b/docs/superpowers/plans/2026-11-08-managed-fleets-2b1-console-aws.md
@@ -63,8 +63,8 @@ The following constraints apply to this slice and supersede 2a's phase-specific
1. Reusing a ClientToken with changed parameters must not become proof that no instance exists. Task 3 `TestAWSComputeClientTokenConflict`, composed with Task 2 `TestManagedRejectedAfterAmbiguity`, owns the quota invariant.
2. A later DescribeInstances page can contain the instance or fail. Task 3 `TestAWSComputeDescribeComplete` requires complete pagination or an error with no usable partial result; no partial absence can trigger relaunch or cleanup.
3. An existing IAM user may have the expected name but the wrong path, account, boundary or policies. Task 4 `TestAWSFleetExistingUserDrift` refuses it before any key creation or deletion; Task 5 pins the boundary condition in rendered IAM.
-4. Two lost rotations followed by a third mint must retain the delivered key. Task 4 `TestAWSFleetCredentialsDoubleLostRotation` verifies the exact kept ID, orphan reaping before mint, pagination and crash recovery.
-5. Fleet credentials must not reach a sibling fleet or deployment bucket through another Allow, version operation or copy source. Tasks 4–5 `TestAWSFleetDataPolicyIsolation` and `TestManagedFleetRenderedPolicyIsolation` evaluate the exact inline policy and boundary together.
+4. Every delivered key remains protected after seal loss. Tasks 2/4 `TestManagedDeliveredKeySet` and `TestAWSFleetCredentialsDoubleLostRotation` require refusal before any reap/mint when a delivered ID other than keep remains live, with a durable needs-operator reason and enrolment refusal.
+5. Fleet credentials must not reach a sibling fleet or deployment bucket through another Allow, version operation or copy source. Tasks 4–5 `TestAWSFleetDataPolicyIsolation` and `TestManagedFleetRenderedPolicyIsolation` pin exact inline/boundary fixtures and structural isolation assertions; they do not simulate IAM.
---
@@ -73,7 +73,7 @@ The following constraints apply to this slice and supersede 2a's phase-specific
| Task | Files / responsibility |
|---|---|
| 1 | Console admission, preparation, enrolment; bounded registry snapshot reads |
-| 2 | Console worker/recovery/readiness; ambiguous launch and publication authority |
+| 2 | Console worker/recovery/readiness; delivered-key set, ambiguity and publication authority |
| 3 | New `internal/awsmanaged/{compute,clients,diagnostics}.go`; compute adapter |
| 4 | New `internal/awsmanaged/{storage,credentials,policy}.go`; fleet bucket/user/key lifecycle |
| 5 | `infra/modules/region-host/managed_fleets.tf`, module variables/boundary/tests; opt-in console authority |
@@ -143,7 +143,7 @@ TestManagedPreparedErrorCleared: prepared=1 plus managed_preparation_failed => c
later worker pass and completed show have no stale failure; unrelated errors survive;
canceled pass after successful preparation cannot leave that transient error forever.
TestManagedRegistryOutsideTransaction: park GetFleetContext/ListFleetBoxesContext;
- unrelated SELECT completes before releasing the registry fake; snapshot expires at 30s;
+ unrelated SELECT completes before releasing the registry fake; context times out at 30 s;
canceled remote call returns; no helper goroutine remains blocked; no partial reservation.
TestManagedRegistrySnapshotAllocation: labels box-8 plus retained box-9 => next box-10;
registry failure/foreign owner/BYO => no reserve; quota remains one SQL transaction;
@@ -169,7 +169,7 @@ Resolve already-stored account/request IDs before the cap, quota, config, plan a
Retain all accepted aliases after closure; do not prune away the promise that a lost request can replay.
An existing database already over 64 keeps its rows but admits no new aliases for that operation.
Use an indexed op_id count; add `managed_request_aliases_op` idempotently in migrateManaged.
-Choose the cap option from N1; matching joins need not consume the daily new-operation budget.
+Matching joins need not consume the daily new-operation budget.
Mark the cap refusal as COPY; existing identical-retry messages and response codes remain unchanged.
- [ ] **Step 4: Move bounded registry reads outside SQL transactions.**
@@ -178,7 +178,8 @@ Resolve known aliases before registry access, then obtain a detached snapshot wi
For deferred allocation, read the operation identity first, fetch its snapshot, then re-read the operation inside BEGIN IMMEDIATE.
Inside the transaction re-resolve requests/open state, preparation, ownership recorded in SQL, retained labels and both quotas.
Combine snapshot labels with all retained managed labels; do not infer the next number solely from the snapshot.
-The server's existing managed admission lock covers snapshot plus allocation; add the same lock around the worker's deferred-allocation call in managedworker.go.
+The server's existing `lockFleet` (`fleetbox.go:209`) covers snapshot plus allocation; take it around the worker's deferred-allocation call too.
+It serializes only one fleet. Cross-fleet account quota is serialized only by the BEGIN IMMEDIATE re-check (`managedstore.go:101`).
Managed BYO growth remains refused.
Keep one serving console/managed worker per database as in 2a; do not claim a new distributed registry transaction.
The context-aware registry variants preserve freshFleetsConn and every existing field; cancel the real remote call, not a goroutine around an uncancellable call.
@@ -202,7 +203,8 @@ Commit subject: `fix: bound managed admission and preserve retry status`.
### Task 2: Preserve lifecycle authority across ambiguity and slow calls
**Files:**
-- Modify: `internal/console/{managedworker,managedready,managedstore}.go`.
+- Modify: `internal/console/{managedworker,managedready,managedstore,managedhistory,managedenrol,managedview}.go` and credential/view tests.
+- Modify: `internal/fleetstore/{provisioner,fake}.go`, `fake_test.go` and the console storage spy/callers.
- Modify: `internal/compute/{provisioner,fake}.go` and `fake_test.go`.
- Create: `internal/console/managedrecovery_test.go`; extend `managedready_test.go`, `managedbudget_test.go`.
@@ -216,6 +218,9 @@ Commit subject: `fix: bound managed admission and preserve retry status`.
- New `(*Server).refreshManagedPublication(ctx context.Context, b managedBox, now time.Time) (managedBox, bool, error)`; bool means all six current checks authorize a new PUT.
- New `const managedPublicationFreshFor = time.Minute`; LastHeartbeatAt remains the persisted observation-attempt time.
- Add `ReadinessCheckedAt time.Time` with JSON `readiness_checked_at` to managedBox; it dates completed checks, while ReadyAt remains immutable. Missing legacy values require refresh.
+- Change fleetstore rotation to `RotateFleetCredentials(ctx context.Context, fleet, keep string, delivered []string) (Credentials, error)`; add sentinel `ErrDeliveredKeyStillLive`.
+- New durable `managed_fleet_delivered_keys(fleet, account, key_id)` set, unique on all three; migrate the nonempty legacy delivered_key_id into it.
+- Add `credential_state`/`credential_reason` columns (default empty) to managed_fleet_storage and matching additive fleetShowReply fields; expose `needs-operator` without secrets.
**Census/review:** Termination, token revocation and ready publication need independent risk review plus authority/write inventory updates. Compute may enter root scope through the console store imports; census-card decides actual membership.
@@ -240,13 +245,18 @@ TestManagedDelayedPublicationFreshness: absent object after >=60s => six fresh c
matching existing object => ready even if fresh checks would fail; no termination;
mismatch/unreadable object => no PUT/revoke/terminate; postdeadline hourly schedule;
absent + fresh checks not passing at deadline => proven-unpublished cleanup.
+TestManagedDeliveredKeySet: K1 delivered -> seal lost -> K2 minted and delivered -> seal lost;
+ restart retains {K1,K2}; rotation refuses before any reap/mint, K1 survives;
+ durable needs-operator reason names another delivered key still live; show exposes it;
+ new enrolments refuse before token claim/delivery until resolved; failure to record delivery
+ returns no credentials; legacy migration and lost-response delivery retain protected IDs.
TestManagedPublicationRefreshBudget: absent delayed publication reads heartbeat once/60s;
one stable pointer per due pass, owner only after other five pass; zero LIST;
matching-object recovery and settled boxes => zero readiness reads;
crash after attempt stamp/before observation => old passes cannot authorize a PUT.
```
-- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console ./internal/compute -run 'TestManaged(RejectedAfterAmbiguity|FreshRejectedLaunch|ProviderOutsideFleetLock|DeadlineBeforeBackoff|DelayedPublicationFreshness|PublicationRefreshBudget)|TestFakeClientToken' -count=1`; expect FAIL.**
+- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/console ./internal/compute ./internal/fleetstore -run 'TestManaged(RejectedAfterAmbiguity|FreshRejectedLaunch|ProviderOutsideFleetLock|DeadlineBeforeBackoff|DelayedPublicationFreshness|PublicationRefreshBudget|DeliveredKeySet)|TestFakeClientToken|TestFleetCredentials' -count=1`; expect FAIL.**
- [ ] **Step 3: Separate first dispatch proof from later rejection.**
@@ -283,7 +293,18 @@ If fresh checks pass and the original ReadyAt was before launch+20m, issue the o
Never reset ReadyAt or the launch deadline; immediate near-deadline publication keeps 2a's same-step behavior.
Preserve C08 on every post-PUT result, including a response lost after the box consumed the object.
-- [ ] **Step 6: Repeat Step 2 to PASS, run the existing C08/deadline witnesses once and commit.**
+- [ ] **Step 6: Persist every delivered key and stop unsafe recovery.**
+
+At managedhistory.go:294/360, add the delivered ID to the durable set before any credential reply; never replace the set with the latest ID.
+Keep the legacy delivered_key_id only as the last-delivered `keep` selector; update it and insert into the set in one transaction before replying.
+Pass the complete set to rotation under lockFleet; do not prune delivery history when a seal is lost or a key disappears.
+Update fleetstore's fake and every caller/spy to enforce the same guard before any reap/mint; Task 4 implements it against complete IAM pages.
+On ErrDeliveredKeyStillLive, persist `needs-operator` with reason `delivered_key_other_than_keep_still_live` (COPY); do not clear it as a transient preparation error.
+Check this state before enrolment's token CAS (managedenrol.go:114); refuse new enrolments until explicit recovery verifies the condition is resolved.
+Do not automatically delete delivered keys to resolve it; existing ready boxes and their credentials keep working. No background key polling.
+Read status from SQL in managedFleetView (managedview.go:139), including when no open operation exists; no AWS calls on show.
+
+- [ ] **Step 7: Repeat Step 2 to PASS, run the existing C08/deadline witnesses once and commit.**
Select `TestManagedPublishDeadline`, `TestManagedPublicationNearDeadline`, `TestManagedAcceptedTerminateAbsent` and `TestManagedPublicationUncertaintyResolves`.
Commit subject: `fix: preserve managed lifecycle authority across retries`.
@@ -292,7 +313,7 @@ Commit subject: `fix: preserve managed lifecycle authority across retries`.
**Files:**
- Create: `internal/awsmanaged/{clients,compute,diagnostics}.go`.
-- Create tests: `internal/awsmanaged/{compute,diagnostics}_test.go`.
+- Create tests: `internal/awsmanaged/{compute,diagnostics}_test.go` and `export_test.go`.
- Retain the boundary witness in `internal/compute/imports_test.go`; no SDK import in console managed*.go.
**Interfaces:**
@@ -310,7 +331,7 @@ ConsoleOutput(ctx context.Context, region, cloudID string) (string, error)
- New `type ComputeConfig struct { Deployment, AccountID string; Regions []string }` and `type Compute struct` implementing that interface.
- New `NewCompute(ctx context.Context, cfg ComputeConfig) (*Compute, error)`; load each explicit region through rootaws, with no implicit-region fallback.
-- New `type HTTPClient interface { Do(*http.Request) (*http.Response, error) }` and `NewComputeWith(ctx context.Context, cfg ComputeConfig, transport HTTPClient) (*Compute, error)` for explicit transport injection through rootaws load options.
+- Test-only `type HTTPClient interface { Do(*http.Request) (*http.Response, error) }` and `NewComputeWith(ctx context.Context, cfg ComputeConfig, transport HTTPClient) (*Compute, error)` in `export_test.go` inject transport through rootaws load options; no production With export.
- New unexported `newCompute(cfg ComputeConfig, clients map[string]ec2API) (*Compute, error)` for mocks; deep-copy configuration.
- New ec2API contains RunInstances, DescribeInstances, DescribeImages, TerminateInstances and GetConsoleOutput only.
- Each SDK method has `(context.Context, *ec2.XInput, ...func(*ec2.Options)) (*ec2.XOutput, error)`; GetConsoleOutput's result type is `*ec2.GetConsoleOutputOutput`.
@@ -337,7 +358,11 @@ TestAWSComputeAbsence: empty filtered Find != proof of termination; exact-ID Not
stopped/stopping/shutting-down remain nonterminal; terminated remains discoverable.
TestAWSComputeTerminateIdentity: mismatch/missing/duplicate tag for EACH identity component,
wrong region/deployment or invalid ID => zero TerminateInstances calls;
+ pre-lookup NotFound => ambiguity error, neither nil nor os.ErrNotExist, zero terminate calls;
exact lookup match => exactly one ID terminated; acceptance is not a termination observation.
+TestAWSComputeManagedTags: deployment+region-only host is excluded from ListDeployment;
+ each missing identity tag is excluded; Terminate and ConsoleOutput refuse the region host
+ without TerminateInstances or GetConsoleOutput calls.
TestAWSComputeConsoleOutput: bounded base64 decode; recognized breadcrumb codes only;
sentinels for enrol/tunnel/access/private secrets, shell trace, unknown lines absent from output/errors.
```
@@ -362,10 +387,12 @@ Return only safe typed classifications; never wrap an AWS response containing Us
- [ ] **Step 4: Implement complete discovery and conservative absence.**
-Find filters all four identity tags in the explicit region; ListDeployment filters only the deployment tag.
+Find filters all four identity tags in the explicit region; ListDeployment filters deployment, then drops every instance missing any of the four identity tags.
+The deployment+region-only host fixture follows `infra/modules/region-host/group.tf:21/:267` at the baseline; it is never a managed instance.
Consume every page under the caller's deadline; detect repeated tokens, malformed reservations and conflicting duplicate IDs as errors.
Lookup addresses exactly one cloud ID with no identity-tag filters; validate the response region/client binding and ID.
-An AWS exact `InvalidInstanceID.NotFound` is the only not-found service code mapped to os.ErrNotExist; an empty success is ambiguity.
+Lookup maps only exact `InvalidInstanceID.NotFound` to os.ErrNotExist; an empty success is ambiguity.
+Terminate converts its own pre-lookup NotFound into an ambiguity error, never nil or os.ErrNotExist; it has sent no termination request.
The adapter does not assert that a recent launch is gone: only the worker's recorded exact-ID termination attempt permits absence to release quota.
For Launch, the initial no-side-effect rejection allowlist is InvalidAMIID.Malformed, InvalidSubnetID.NotFound, InvalidGroup.NotFound, InvalidParameterValue, Unsupported, UnauthorizedOperation, InsufficientInstanceCapacity and InstanceLimitExceeded.
Classify these as ErrLaunchRejected; the worker still requires firstDispatch proof to release quota. Unknown codes are ambiguous.
@@ -375,7 +402,7 @@ IAM in Task 5 prevents this role from retagging existing instances; do not claim
- [ ] **Step 5: Bound console output and keep diagnostics private.**
-Describe the exact instance first and require the configured deployment tag before GetConsoleOutput.
+Describe the exact instance first and require the configured deployment plus nonempty fleet/label/operation tags before GetConsoleOutput.
Limit the encoded input to 128 KiB and decoded input to 64 KiB; malformed encoding returns a safe error.
Recognize only full lines `CARLOS_BOOT:<code>` where code is one of `seed_verified`, `enrol_pending`, `enrol_failed`, `stable_verified`, `joining`, `bootstrap_failed`.
Return at most 32 recognized codes, joined by newlines; unknown lines and arbitrary suffixes are dropped.
@@ -396,10 +423,10 @@ Commit subject: `feat: add managed fleet AWS compute adapter`.
**Interfaces:**
- Existing `fleetstore.Credentials { ID string; Secret []byte }`, JSON `id`/`secret`, and `FleetStorage { Bucket, Region string }` (`fleetstore/provisioner.go:5`).
-- Implements existing `EnsureFleetStorage(ctx context.Context, fleet, region string) (fleetstore.FleetStorage, error)`, `FleetCredentials(ctx context.Context, fleet string) (fleetstore.Credentials, error)`, `RotateFleetCredentials(ctx context.Context, fleet, keep string) (fleetstore.Credentials, error)`.
+- Implements existing EnsureFleetStorage/FleetCredentials and Task 2's revised `RotateFleetCredentials(ctx context.Context, fleet, keep string, delivered []string) (fleetstore.Credentials, error)` contract.
- New `type StorageConfig struct { Deployment, AccountID, IAMRegion, BucketPrefix, UserPath, BoundaryARN string; Regions []string }` and `type Storage struct`.
- New `NewStorage(ctx context.Context, cfg StorageConfig) (*Storage, error)` and unexported `newStorage(cfg StorageConfig, buckets map[string]s3API, users iamAPI) (*Storage, error)`.
-- New `NewStorageWith(ctx context.Context, cfg StorageConfig, transport HTTPClient) (*Storage, error)` applies the injected transport to both S3 and IAM through rootaws; no unmocked secondary client.
+- Test-only `NewStorageWith(ctx context.Context, cfg StorageConfig, transport HTTPClient) (*Storage, error)` in `export_test.go` applies transport to both S3 and IAM through rootaws; no production With export or unmocked secondary client.
- New `fleetResourceNames(cfg StorageConfig, fleet string) (bucket, user string, err error)`; deterministic deployment+fleet names.
- New `fleetDataPolicy(bucketARN string) (string, error)`; JSON document for one bucket only.
- New `(*Storage).verifyFleetUser(ctx context.Context, fleet string) (string, error)` returns verified IAM user name, never a key.
@@ -413,7 +440,8 @@ Commit subject: `feat: add managed fleet AWS compute adapter`.
TestAWSFleetBucketContract: deterministic name, versioning Enabled, AES256, four public blocks;
lifecycle NoncurrentDays=7, AbortIncompleteMultipartUpload.DaysAfterInitiation=7;
no current expiration; region mismatch/foreign owner/mismatched tags => no mutation;
- us-east-1 omits LocationConstraint; other regions set it; same-fleet retry converges.
+ CreateBucketConfiguration.Tags contains both identity tags in the initial request;
+ us-east-1 omits LocationConstraint but retains Tags; other regions set both; retry converges.
TestAWSFleetBucketPartialFailure: fail after each creation/configuration/readback call;
retry verifies ownership before repair; untagged pre-existing bucket fails closed;
failed readback cannot return prepared storage or mint credentials.
@@ -424,13 +452,20 @@ TestAWSFleetExistingUserDrift: existing name with wrong ARN/account/path/boundar
TestAWSFleetCredentialsDoubleLostRotation: delivered K1; mint K2 but lose secret/seal;
next rotation keeps K1, reaps K2, mints K3; lose again then keep K1 and reap K3;
<=2 keys after each mint, K1 never deleted; KEEP on page 2 survives; missing keep => no deletion/mint.
+ Separately: K1 delivered -> seal lost -> K2 minted+delivered -> seal lost again;
+ delivered={K1,K2}, keep=K2 => ErrDeliveredKeyStillLive, no deletion/mint;
+ delivered non-keep on page 2 also refuses; console composition records needs-operator.
TestAWSFleetKeyFailures: failed deletion => no mint; lost mint response => later list/reap;
inactive kept key => refuse; same-fleet concurrent rotations serialized; other fleet untouched;
FleetCredentials never returns secret; no sealed key recovery by an AWS Get operation.
-TestAWSFleetDataPolicyIsolation: own lease/replica/files/restore requests allowed;
- sibling bucket and deployment bucket denied for read/write/list/version/copy source;
- own private-key Get/Put allowed, delete/version-delete denied; IAM/EC2/bucket-admin denied;
- list/version operations use bucket ARNs, object actions use exact allowed object ARNs.
+TestAWSFleetDataPolicyIsolation: exact JSON fixture plus structural assertions for
+ lease/replica/files/restore grants; cross-bucket NotResource Deny present;
+ no wildcard Allow action or unbounded bucket ARN; bucket/object ARNs disjoint;
+ private-key Put has StringEquals s3:if-none-match="*"; no alternate unconditional grant;
+ ListBucket on exact bucket has no prefix condition; ListBucketVersions and
+ ListBucketMultipartUploads retain prefix conditions; no IAM/EC2/bucket-admin grants.
+TestAWSFleetMissingKey: mocked GET with fleet credentials maps missing key to 404 semantics;
+ policy fixture pins unconditioned ListBucket; mock is not proof of live IAM enforcement.
```
- [ ] **Step 2: Run `GOFLAGS=-buildvcs=false go test ./internal/awsmanaged -run 'TestAWSFleet' -count=1`; expect FAIL.**
@@ -441,14 +476,17 @@ Hash `Deployment + "/" + fleet` with SHA-256, use the first 24 lowercase hex cha
Bucket is BucketPrefix+suffix; IAM user is `managed-fleet-`+suffix under the exact configured UserPath.
Require a safe nonempty deployment, valid fleet name, 12-digit account, valid bounded bucket name and non-root IAM path.
Refuse prefixes matching configured protected deployment/data buckets in the module and disallow overlaps with the app-store namespace.
-On CreateBucket success, stamp `carlos:deployment` and `carlos:fleet`; subsequent retries require exact tags and expected account/region before any configuration writes.
+Send `carlos:deployment` and `carlos:fleet` in CreateBucketConfiguration.Tags on the initial CreateBucket; retain the configuration with Tags even in us-east-1.
+The pinned S3 v1.105.0 SDK `types/types.go:925–938` has this field and names `s3:TagResource` for general-purpose buckets; Task 5 grants it.
+Reference: [https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucketConfiguration.html](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucketConfiguration.html).
+Subsequent retries require exact tags and expected account/region before any configuration writes.
Use ExpectedBucketOwner on supported calls; BucketAlreadyExists, access denied and unowned collisions are refusal, never adoption.
-BucketAlreadyOwnedByYou alone is insufficient: inspect region and tags. A crash before initial tagging leaves an explicit operator-reconciliation case; never relabel an unknown bucket.
+BucketAlreadyOwnedByYou alone is insufficient: inspect region and tags. Lost creation replies recover through those tags; never relabel an unknown or untagged pre-existing bucket.
Configure versioning, AES256 encryption, public blocking and the two seven-day rules, then read back each before returning FleetStorage.
EnsureFleetStorage returns success only after Step 4's user and inline policy checks also succeed; a bucket alone is not prepared fleet storage.
Missing/incorrect settings on a verified owned bucket may be repaired; unknown lifecycle rules or foreign tags cause refusal rather than destructive replacement.
Never disable versioning, expire current objects, empty/delete a bucket or grant bucket-policy administration in this slice.
-S3 operations: CreateBucket, GetBucketLocation, Get/PutBucketTagging, Get/PutBucketVersioning, Get/PutBucketEncryption, Get/PutPublicAccessBlock, Get/PutBucketLifecycleConfiguration.
+S3 operations: CreateBucket (with Tags), GetBucketLocation, GetBucketTagging, Get/PutBucketVersioning, Get/PutBucketEncryption, Get/PutPublicAccessBlock, Get/PutBucketLifecycleConfiguration.
Only preparation invokes these operations; FleetCredentials and enrolment do not reconfigure S3.
- [ ] **Step 4: Verify IAM identity and install a separate fleet-data policy.**
@@ -466,31 +504,37 @@ The fleet-data policy has the following action/resource contract:
| Consumer | Actions | Resource scope |
|---|---|---|
-| Bucket region / data discovery | GetBucketLocation; ListBucket, ListBucketVersions | Exact bucket; list prefixes restricted to the data/probe/key paths below |
+| Bucket region / missing-key semantics | GetBucketLocation, ListBucket | Exact bucket; ListBucket has no prefix condition so missing-key GET returns 404 |
+| Version discovery | ListBucketVersions | Exact bucket; prefixes restricted to the data/probe/key paths below |
| Lease, replica and files | GetObject, PutObject, DeleteObject | `instances/*` in the exact bucket |
| Restore and move staging | GetObject, PutObject, DeleteObject, GetObjectVersion | `instances/*`, `moves/*`, `move-snapshots/*` in the exact bucket |
-| Multipart data uploads | AbortMultipartUpload, ListMultipartUploadParts | Same data object prefixes; ListBucketMultipartUploads only on the exact bucket |
-| First-box key and later recovery | GetObject, PutObject | Exact `system/fleet-secrets-key.json`; writer/format deferred to 2b-2 |
+| Multipart data uploads | AbortMultipartUpload, ListMultipartUploadParts | Same data object prefixes; ListBucketMultipartUploads on exact bucket with prefix conditions |
+| First-box key and later recovery | GetObject; conditional PutObject | Exact `system/fleet-secrets-key.json`; separate Put Allow requires StringEquals `s3:if-none-match = "*"` for first writer wins; 2b-2 consumes it |
| Storage challenge | GetObject, PutObject, DeleteObject | `_carlos/probes/*`; challenge implementation deferred to 2b-2 |
Use the `s3:` prefix for these actions. There is no DeleteObjectVersion grant: claim-free lease release deletes a bare lock key; destructive versioned claim paths remain refused.
Read-version/list-version grants cover versioned restore; any later need for permanent version deletion must identify its production consumer and receive a separate policy review.
No wildcard action Allow, object tagging, bucket administration, IAM, EC2, deployment-bucket or other-fleet resource enters the document.
Add an explicit `s3:*` Deny with NotResource equal to this bucket and its objects, so another resource-policy Allow cannot grant cross-bucket access.
-Fixture requests include cross-bucket CopyObject sources as well as destinations; a valid destination does not authorize reading a foreign source.
+Structural fixtures check CopyObject source GetObject and destination PutObject scopes separately; neither grant reaches a foreign bucket.
+Keep the key PutObject condition in both inline and boundary fixtures; no broader statement may grant unconditional writes to that path.
Inspect `internal/lease/{lease,endpoint,versioned}.go` consumers; VersionedStore's existence alone does not justify granting every method's destructive permission.
-- [ ] **Step 5: Implement rotation that preserves the delivered key.**
+- [ ] **Step 5: Implement rotation that preserves every delivered key.**
Credentials.ID is the AWS access-key ID; Secret is the UTF-8 secret-access-key bytes, with JSON base64 supplied by the existing []byte encoding.
Bucket/region remain FleetStorage metadata; do not hide JSON credentials or bucket selectors inside Secret.
FleetCredentials lists fully and returns the newest active ID (CreateDate then ID tie-break), with empty Secret; it is advisory and never selects keep for rotation.
-Under an adapter fleet mutex, verify the user, list every key page, and confirm a nonempty keep exists and is active before deleting anything.
-Reap every ID except keep, confirm deletions with a complete list, then mint exactly one key; stop on ambiguity at any step.
-With empty keep, all existing keys are undelivered orphans by the core contract; reap them before the first usable mint.
+Under an adapter fleet mutex, verify the user and list every key page before inspecting delivered IDs or changing keys.
+Before any delete/mint, intersect the complete live key inventory with the durable delivered set; any delivered ID other than keep returns ErrDeliveredKeyStillLive.
+Treat any still-existing delivered key, including inactive keys, as protected; unknown or incomplete inventory refuses mutation.
+Then confirm a nonempty keep exists and is active before deleting anything.
+Only after this guard, reap undelivered IDs except keep, confirm deletions with a complete list, then mint exactly one key; stop on ambiguity.
+With empty keep, the same guard applies: only proven undelivered orphans may be reaped before the first usable mint.
Use MaxAttempts=1 on CreateAccessKey; a lost response is recovered by listing and reaping the orphan on the next explicit rotation.
Return the new secret only from that mint; never persist it in the adapter or put it in errors/logs.
-The console still seals before delivery and persists delivered_key_id before replying; losing a seal never changes the keep argument.
+Task 2 seals before delivery and adds each delivered ID to the durable set before replying; seal loss never erases that history.
+A newly delivered key becomes keep without unprotecting older delivered keys; the adapter refuses and the console records needs-operator when another remains live.
Two serving consoles with different databases remain unsupported; an in-process mutex is not presented as distributed rotation exclusion.
- [ ] **Step 6: Repeat Step 2 to PASS and commit.**
@@ -512,9 +556,9 @@ Commit subject: `feat: provision managed fleet buckets and bounded credentials`.
- New `managed_fleet_bucket_prefix` string default empty and `managed_fleet_user_path` string default `/carlos-managed-fleet/`.
- New `aws_iam_role_policy.host_managed_fleets`, attached only to existing aws_iam_role.host when enabled.
- Reuse the existing `aws_iam_policy.store_user_boundary` ARN/mechanism; create it when app storage OR managed provisioning needs it.
-- Add opt-in fleet-prefix statements to that boundary without altering its existing app-store statements; no new per-fleet role/profile.
+- Include existing app-store statements only when store_bucket_prefix is nonempty; append fleet-prefix statements only when managed is enabled. No new per-fleet role/profile.
- New outputs `managed_fleet_user_boundary_arn`, `managed_fleet_user_path`, `managed_fleet_bucket_prefix`; null while off.
-- New test helper `effectiveFleetAccess(inline, boundary []byte, action, resource string, context map[string][]string) (bool, error)` in `_test.go` only.
+- Tests compare exact rendered JSON fixtures and assert structure; no hand-written IAM evaluator.
**Census/review:** Every non-Markdown infra file is root census scope. IAM grants require independent security review of the complete policy union; rendered fixtures are evidence of intent, not an AWS live-policy verdict.
@@ -523,17 +567,21 @@ Commit subject: `feat: provision managed fleet buckets and bounded credentials`.
```text
off_by_default: zero host_managed_fleets resources; existing store policy/boundary unchanged;
store disabled + managed disabled => no new boundary; outputs null.
+store_off_managed_on: boundary has fleet statements only; no resource anywhere equals
+ arn:aws:s3:::* or arn:aws:s3:::*/*; app-store statements are absent.
enabled_shape: one host policy, existing boundary mechanism, approved concrete region/image/subnet/SG/type;
RunInstances requires deployment/fleet/label/operation tags; CreateTags only at RunInstances;
- Terminate/GetConsoleOutput require deployment resource tag; no CreateRole/PassRole/profile/SSM.
+ Terminate/GetConsoleOutput require exact deployment and Null=false on all four identity tags;
+ deployment+region-only region host fails required-tag fixture; no CreateRole/PassRole/profile/SSM.
+ CreateBucket tagging grant includes s3:TagResource on the managed prefix.
existing_user_boundary: CreateUser and PutUserPolicy require exact iam:PermissionsBoundary;
IAM resource is account + managed path; no boundary editing/AttachUserPolicy/UpdateUser.
bad_config: empty/wildcard identity/network, root or overlapping IAM path, region mismatch,
protected or overlapping bucket prefixes => plan failure before resources.
-TestManagedFleetRenderedPolicyIsolation: exact inline AND rendered boundary allows own data;
- foreign fleet/deployment bucket, foreign account/path, wrong/missing boundary denied;
- app-store credential with unchanged app inline gains no fleet or version capability;
- deliberately broadened sibling Allow cannot override inline cross-bucket explicit Deny.
+TestManagedFleetRenderedPolicyIsolation: exact-diff inline/boundary/host-policy fixtures;
+ structural asserts pin own-data grants, explicit cross-bucket Deny, disjoint ARNs,
+ exact account/path/boundary conditions and required identity tags; no unbounded bucket
+ resource or wildcard Allow action; unchanged app inline contains no fleet/version grants.
```
- [ ] **Step 2: Run local failing checks against mocked fixtures.**
@@ -550,7 +598,9 @@ Image ARN uses the EC2 image ARN form; never substitute an account-owned instanc
Require the deployment request tag and nonempty fleet/label/operation tags on created instances/volumes; restrict tag keys to the four identity keys.
Constrain instance type, IMDSv2/hop limit and absent instance profile in the statement for the resource types supporting those keys.
CreateTags permits only launch-time tags with `ec2:CreateAction=RunInstances`; do not grant DeleteTags or post-launch retagging.
-TerminateInstances and GetConsoleOutput use exact configured deployment resource-tag conditions and configured-region resources.
+TerminateInstances and GetConsoleOutput use StringEquals on aws:ResourceTag/carlos:deployment and configured-region resources.
+Both also require Null=false for aws:ResourceTag/carlos:deployment, aws:ResourceTag/carlos:fleet, aws:ResourceTag/carlos:label and aws:ResourceTag/carlos:operation.
+Pin a region-host fixture carrying only deployment+region (group.tf:21/:267): both actions lack the required tags and ListDeployment excludes it.
DescribeInstances/DescribeImages use Resource `*` where required, restricted to configured requested regions in this new grant.
The existing host inventory policy already grants broad DescribeInstances: report that effective read scope honestly; adding a narrow Allow does not reduce it.
Do not add compute permissions to group runtime roles or create an SG, subnet, VPC, instance profile or SSM access path.
@@ -560,14 +610,17 @@ AWS reference: [https://docs.aws.amazon.com/service-authorization/latest/referen
- [ ] **Step 4: Render bounded IAM/S3 grants and boundary intersection.**
Grant Task 4's exact IAM operations only under the configured account's managed-fleet user path.
-Keep CreateUser and PutUserPolicy conditioned on the existing exact boundary ARN; scoped DeleteUser/DeleteUserPolicy are allowed for the later approved cleanup path, without adding a runtime deletion method now.
+Keep CreateUser and PutUserPolicy conditioned on the exact boundary ARN; scoped DeleteUser remains for the later approved cleanup path without a runtime method now.
+Do not grant iam:DeleteUserPolicy in 2b-1; it belongs to 2d.
No CreateRole, PassRole, AttachUserPolicy, group mutation, login profile, boundary mutation or IAM policy-version edit grant.
-Read-only policy/group membership APIs are necessary to reject existing-resource drift and stay on the same user resource scope.
+Required drift-check reads are GetUser, GetUserPolicy, ListUserPolicies, ListAttachedUserPolicies and ListGroupsForUser; ListAccessKeys inventories keys. All stay on the same user resource scope.
Scope CreateBucket/configure/readback actions to the exact managed prefix; use the IAM action names corresponding to the SDK operations, including s3:PutLifecycleConfiguration.
-The exact S3 grant is CreateBucket, GetBucketLocation, Get/PutBucketTagging, Get/PutBucketVersioning, Get/PutEncryptionConfiguration, Get/PutBucketPublicAccessBlock and Get/PutLifecycleConfiguration, all prefixed `s3:`.
+The exact S3 grant is CreateBucket, TagResource, GetBucketLocation, GetBucketTagging, Get/PutBucketVersioning, Get/PutEncryptionConfiguration, Get/PutBucketPublicAccessBlock and Get/PutLifecycleConfiguration, all prefixed `s3:`.
+TagResource is required for CreateBucketConfiguration.Tags; a later PutBucketTagging grant is not a substitute.
Protect deployment/data buckets with explicit Denies on the new bucket creation/configuration actions, even if an operator chooses an overlapping prefix.
Do not add a console-role DeleteObject Deny on deployment/data buckets: existing lease release depends on it.
-Add only Task 4's fleet-data actions to the existing boundary under the distinct managed prefix; retain app-store effective access unchanged.
+Build boundary Statement by conditional concatenation: app statements only when store_bucket_prefix != "", fleet statements only when managed is enabled.
+Add only Task 4's fleet-data actions under the distinct managed prefix; retain enabled app-store effective access unchanged (main.tf:694–711).
Require disjoint app/managed IAM paths and bucket prefixes when both features are enabled; no wildcard or empty prefix accepted.
The boundary limits delegated authority; each user's exact inline policy narrows it to that fleet and explicitly denies cross-bucket access.
AWS boundary reference: [https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html).
@@ -576,8 +629,8 @@ AWS boundary reference: [https://docs.aws.amazon.com/IAM/latest/UserGuide/access
The HCL tests compare jsondecode of actual resource.policy values with the checked-in JSON fixtures for fixed mock inputs.
Task 4's Go renderer likewise compares with fleet-data-policy.json; testing a hand-copied policy alone is insufficient.
-The test-only evaluator implements only the operators present in these fixtures and errors on every unsupported construct; it is not a general IAM simulator.
-Evaluate explicit Deny before Allow, then intersect boundary and inline; enumerate bucket and object ARNs separately and both CopyObject permissions.
+Use exact-diff fixtures plus structural assertions: no wildcard Allow actions or unbounded bucket resources, explicit cross-bucket Deny present, disjoint resource ARNs and required conditions intact.
+Check bucket/object ARN classes and CopyObject source/destination grants separately. Do not implement an IAM evaluator or claim these checks prove live authorization.
Assert the complete host policy union contains no new write bypass through an older wildcard grant; distinguish pre-existing inventory reads from new mutation authority.
Mark variable descriptions, errors and output descriptions COPY for the controller's review.
Shipping later requires a platform release tag and deployment repository ref bump, followed by an inspected plan and Paul's scoped apply approval.
@@ -642,7 +695,7 @@ Do not run the full edge suite between tasks.
- No production assignment to Config.ManagedCompute/ManagedStorage and no enabled configuration change.
**Interfaces:**
-- Consume Tasks 3–4 public With constructors with a mock HTTP transport and explicit dummy credentials; all network destinations, including IAM, are intercepted.
+- Consume Tasks 3–4 test-only With constructors exported through `export_test.go` with mock transport and dummy credentials; all destinations, including IAM, are intercepted.
- Consume real console HTTP handlers, SQLite persistence and RunManagedFleetsPass in existing console tests with fakes.
- Keep AWS adapter imports out of managed*.go, including tests; adapter/worker composition uses exported compute/fleetstore contracts.
- Retain the existing TestManagedCoreImports direct-import boundary and compile-time Provisioner implementation assertions.
@@ -725,10 +778,10 @@ Finish line: one merged console-side slice, production still off, no live resour
| §5 provider-neutral core and rootaws | Tasks 3/4 adapters, Task 7 import/constructor witnesses |
| Decision 1 no profile/SSM, dedicated egress-only SG | Task 3 request and Task 5 grants; real network verification 2b-2 |
| Decision 2 versioning/SSE/public blocking/7-day rules | Task 4 bucket contract/readback; no 30-day deletion job |
-| Addendum P1 per-fleet IAM user, boundary, enrol-only delivery | Tasks 4/5; existing console seal/delivered-ID mechanism retained |
+| Addendum P1 per-fleet IAM user, boundary, enrol-only delivery | Tasks 2/4/5; sealed delivery, durable delivered-ID set and needs-operator guard |
| Existing-resource IAM/boundary drift | Tasks 4/5 user/path/account/boundary/policy checks and denied fixture |
| Addendum P2 fleet-private key in own bucket | Task 4 exact reserved policy path; mint/write/public registration 2b-2 |
-| §8.4 sibling/deployment credential isolation | Tasks 4/5 offline effective-policy/copy/version cases; live proof 2b-2 |
+| §8.4 sibling/deployment credential isolation | Tasks 4/5 exact fixtures and structural copy/version scopes; live proof 2b-2 |
| ready.json console-only authority | Task 6 PUT/DELETE denial plus Task 4 direct-S3 isolation |
| Decision 6 console authority opt-in/default off | Task 5 region/image/subnet/SG/tag/path/prefix scopes; no role creation |
| Existing broad inventory Allow | Task 5 reports actual union; no false claim of narrower effective Describe |
@@ -763,3 +816,20 @@ Plan-only self-review is complete; it is not an independent risk/census review o
- Release/tag and deployment module ref bump; inspected local plan followed by separately approved apply. Run the first real box, cross-bucket denial and serving proof only inside that approval.
- Subsequent phases stay separate: 2c later-box key consumption/many-box acceptance; 2d removal, 30-day retention/revival and hourly regional orphan sweep; phase 3 billing and VPC peering.
- Carry N2 and the other accepted 2a minors as follow-ups, together with the closed review history; neither this file nor the 2b split restarts that history.
+
+## Review history
+
+Round 1: all findings accepted; three P1s fixed in this plan. This revision does not reset the round count or reopen 2a's closed rounds.
+
+- P1-1 — Fixed (managed-instance identity): Tasks 3/5 require all four tags; deployment+region-only hosts are excluded from discovery and denied termination/output.
+- P1-2 — Fixed (boundary namespace isolation): Task 5 omits empty-prefix app statements and pins store-off/managed-on rendering without wildcard bucket resources.
+- P1-3 — Fixed (delivered-key preservation): Tasks 2/4 persist the delivered set, refuse before reap/mint on another live delivered key, and expose needs-operator with enrolment refusal.
+- P2-4 — Fixed (missing-key semantics): Task 4 grants unconditioned exact-bucket ListBucket; version/multipart list prefixes remain restricted; fixture and mocked GET cover 404.
+- P2-5 — Fixed (termination evidence): Task 3 converts pre-lookup NotFound to ambiguity and adds the TerminateIdentity assertion.
+- P2-6 — Fixed (creation identity): Task 4 tags at CreateBucket via the pinned SDK field; Task 5 grants s3:TagResource.
+- P2-7 — Fixed (quota serialization): Task 1 names lockFleet and reserves cross-fleet account serialization to the BEGIN IMMEDIATE re-check.
+- P3-8 — Fixed (least authority): Task 5 drops DeleteUserPolicy until 2d and names required drift-check reads.
+- P3-9 — Fixed (first-writer key authority): Task 4 conditions private-key PutObject on s3:if-none-match="*"; 2b-2 consumes it.
+- P3-10 — Fixed (admission clarity): Task 1 fixes the cap at 64 and states that the context times out at 30 s.
+- P3-11 — Fixed (test-only injection): Tasks 3/4/7 move With constructors to export_test.go.
+- P3-12 — Fixed (policy evidence): Tasks 4/5 use exact-diff fixtures and structural assertions; the hand-written IAM evaluator is removed.