Merge origin/main (4a9a47c0) into certwarm-wake; census re-proposed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
40 files changed,
+1,483
−43
docs/site/plans.md+8 −1docs/superpowers/notes/census-proposal-plans-4b-after-grace.md+11 −0docs/superpowers/notes/plans-4b-ledger.md+20 −0docs/superpowers/plans/2026-10-25-plans-4b-email-and-storage-stages.md+223 −0docs/superpowers/specs/CODEX-FINDINGS-PLANS-4B-CODE.md+34 −0docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-4B-CODE.md+38 −0docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-4B.md+32 −0docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4B.md+10 −0internal/console/claim_app_mutation_test.go+1 −1internal/console/claim_backend_recorders_test.go+2 −2internal/console/claim_backends.go+2 −2internal/console/claim_purge_backend.go+1 −1internal/console/claim_store_effects.go+2 −2internal/console/deletion_test.go+1 −1internal/console/mailcounts.go+25 −2internal/console/plancaps_copy.go+6 −0internal/console/plangrace_cli_test.go+18 −1internal/console/plangrace_test.go+2 −2internal/console/plangrace_view_test.go+33 −2internal/console/plangracepass.go+52 −5internal/console/planmail.go+116 −0internal/console/planmail_test.go+252 −0internal/console/planstorage.go+118 −0internal/console/planstorage_test.go+203 −0internal/mail/mail.go+3 −0internal/mail/pauseif_test.go+40 −0internal/mail/walk.go+24 −3internal/objstore/aws.go+13 −3internal/objstore/aws_test.go+4 −4internal/objstore/enforce_test.go+4 −4internal/objstore/memprovisioner.go+2 −2internal/objstore/memprovisioner_test.go+1 −1internal/objstore/objstore.go+15 −0internal/objstore/provisioner.go+3 −1internal/objstore/walk.go+1 −1internal/objstore/walk_test.go+2 −2internal/objstore/writesdenied.go+46 −0internal/objstore/writesdenied_test.go+109 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-plans-4b-after-grace.tsv+5 −0
CI failed — run details
diff --git a/docs/site/plans.md b/docs/site/plans.md| index ba4d9aa81..b52239fa3 100644 |
| --- a/docs/site/plans.md |
| +++ b/docs/site/plans.md |
| @@ -79,4 +79,11 @@ Going over the limit starts a grace period: |
| While an account is over, its owners get one reminder a day, saying when grace ends and how to get back under: buy a pack, move to a bigger plan, or clean up. |
| -Nothing is refused, slowed or stopped yet. The console only warns and keeps the clock. It also records when an owner actually received notice: an email that was accepted for delivery, an owner viewing an account page with the banner, or an owner's CLI printing the warning. Whatever acts after grace starts only once grace has ended and an owner received notice at least 3 days earlier, so an account nobody has heard from is never cut off. |
| +After grace, only the capped action is refused, and each refusal lifts by itself: |
| + |
| +- **Email.** When an account has sent twice its daily limit, every sender of every app is paused until midnight UTC. This does not wait for notice, because sending reputation is shared by every tenant. The catalog's email ceiling caps it. |
| +- **Storage.** New uploads to the account's stores are refused once grace has ended and an owner has had notice for 3 days, or straight away at twice the limit. Downloads, listing and deletes keep working, so the account can clean up. Uploads come back once usage is under the limit or the limit is raised. |
| + |
| +The account banner and the CLI warning line say which stage is in force. Bandwidth and awake hours only warn for now. |
| + |
| +The console also records when an owner actually received notice: an email that was accepted for delivery, an owner viewing an account page with the banner, or an owner's CLI printing the warning. Apart from the two ceilings above (email at twice its limit, storage at twice its limit), whatever acts after grace starts only once grace has ended and an owner received notice at least 3 days earlier. So an account nobody has heard from is never cut off for anything short of a ceiling. |
diff --git a/docs/superpowers/notes/census-proposal-plans-4b-after-grace.md b/docs/superpowers/notes/census-proposal-plans-4b-after-grace.md| new file mode 100644 |
| index 000000000..03138f7fa |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-plans-4b-after-grace.md |
| @@ -0,0 +1,11 @@ |
| +# Census approval: plans-4b-after-grace |
| + |
| +Ruling `census-ruling-plans-4b-after-grace`. Every change below keeps the disposition it already has, so it needs an approval, not a decision. |
| + |
| +Envelopes re-pinned: `internal/console`, `internal/mail`, `internal/objstore`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Escalate if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. An escalation goes to the census owner as a decision. |
| + |
| +Seal: `0c4eabfe38e12b098285bdeb5ceb0b16e5333928f5b02e160a6b16b5fd9ce1e0` → `0c4eabfe38e12b098285bdeb5ceb0b16e5333928f5b02e160a6b16b5fd9ce1e0`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-plans-4b-after-grace.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/plans-4b-ledger.md b/docs/superpowers/notes/plans-4b-ledger.md| new file mode 100644 |
| index 000000000..30e35e6b4 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/plans-4b-ledger.md |
| @@ -0,0 +1,20 @@ |
| +# SDD ledger — plan: docs/superpowers/plans/2026-10-25-plans-4b-email-and-storage-stages.md |
| +Pre-flight: T1 produces planMailPauseAt, T4 consumes (match); T2 produces SetWritesDenied/EnsureUser(denyWrites)/Record.WritesDenied, T3 consumes (match); T3 produces storageDenyDue, T4 consumes (match). T4 changes planNoticesOf signature (4a callers updated in T4). |
| +Task 1: Ruling: enforceAccountMail runs from a defer at the top of enforceMailLimits, so it follows every per-sender outcome (including an already-paused sender) — the plan said 'after the per-sender checks' — cost if wrong: none. |
| +Task 1: complete (commits 4944c8b..9c76cd7, tests: go test ./internal/console/ -run 'PlanMailPauseAt|AccountMail|PlanMailPause|PlanResume|SESEvent|Enforce|MailCount|ResumeStale' → ok github.com/carlosframework/platform/internal/console 21.530s) |
| +Task 2: complete (commits 9c76cd7..c5b0081, tests: go test ./internal/objstore/ -run 'StorePolicy|GrantWritesTheWriteDeny|SetWritesDenied|Grant|Enforce' → ok github.com/carlosframework/platform/internal/objstore (cached)) |
| +Task 3: Ruling: the storage regrant runs under claimAppCall action 'plan-storage-regrant' (added to TestClaimAppMutationGate's door list), the scan-regrant precedent; the audit actor is 'plan' — cost if wrong: an action rename. |
| +Task 3: complete (commits c5b0081..a089ae0, tests: go test ./internal/console/ -run 'StorageDeny|ClaimAppMutationGate|GracePass' → ok github.com/carlosframework/platform/internal/console (cached)) |
| +Task 4: Ruling: planNoticesOf takes a stage func(capState) string (nil allowed) instead of limits and ceilings — the banner and CLI pass s.planStage(acct, now), the email pass passes nil — same effect, one fewer threaded value — cost if wrong: none. |
| +Task 4: Ruling: 4a's test fixture moved from 2x to 1.5x storage, because 2x is now the hard-ceiling stage (Paul's 2026-10-25 call) and correctly shows the storage-denied text — cost if wrong: none (fixture). |
| +Task 4: note: the email-paused banner reads the hourly-measured row, so it can lag the event-driven pause by up to an hour. |
| +Task 4: complete (commits a089ae0..6081376, tests: go test ./internal/console/ -run 'BannerSays|CLIWarning|Banner|GracePass|ExpiredPeriod' → ok github.com/carlosframework/platform/internal/console (cached)) |
| +Task 5: Ruling: no record-write census layer — TestPlan9B8RecordWriteCensus names no site (SetWritesDenied writes through objstore.PutIn, an existing writer) — cost if wrong: CI names it. |
| +Final: fixed (1) failed storage regrant never retried — TestStorageDenyRetriesAFailedRegrant RED→GREEN (Record.WritesDenyApplied, set after a successful grant) |
| +Final: fixed (2) concurrent pause could be overwritten — TestSetSenderPausedIfChecksTheRereadSender, TestPlanResumeRereadsTheSender RED→GREEN (mail.SetSenderPausedIf asks eligibility of the sender read inside the mutation) |
| +Final: fixed (3) delayed SES event re-paused — TestDelayedSESEventDoesNotRepause RED→GREEN (account check measures today) |
| +Final: fixed (4) one broken app blocked the rest — TestAccountMailContinuesPastABrokenApp RED→GREEN (loops aggregate errors; storage too) |
| +Final: fixed (5) removed storage limit kept the deny — TestStorageDenyClearedWhenLimitRemoved RED→GREEN (clearStorageDeny when the plan offers no storage cap) |
| +Final: minor (deferred): the email-paused banner derives from the measured row and the current threshold, so an upgrade mid-day hides it while senders stay paused until the day rolls |
| +Final: minor (deferred): the live MinIO contract run does not exercise the write deny (JSON and MemProvisioner tests only) |
| +Final: Ruling: objstore helper named updateStore, not updateRecord — the record-write census matches the name as a key site; the writes go through objstore.PutIn, an existing inventoried writer — cost if wrong: none. |
diff --git a/docs/superpowers/plans/2026-10-25-plans-4b-email-and-storage-stages.md b/docs/superpowers/plans/2026-10-25-plans-4b-email-and-storage-stages.md| new file mode 100644 |
| index 000000000..281b611aa |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-25-plans-4b-email-and-storage-stages.md |
| @@ -0,0 +1,223 @@ |
| +# Plans 4b: Email and Storage After-Grace Stages Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** The two console-side after-grace stages. |
| +- An account that sends twice its daily email limit has every sender paused until the UTC day rolls. |
| +- An account over its storage cap, past grace and past notice, has new uploads refused on every one of its stores. Reads and deletes keep working. |
| +- Both undo themselves: email at the UTC day roll, storage once usage is back under the cap or the cap is raised. |
| + |
| +**Architecture:** |
| +- **Email:** an account-wide check joins `enforceMailLimits`, which runs on every SES event. It pauses senders with a new pause kind, `plan`. The hourly grace pass resumes those senders after the day rolls, because a paused sender sends nothing, so no event arrives to resume it. |
| +- **Storage:** `objstore.Record` gains `WritesDenied`, and the store policy gains an unconditional `Deny s3:PutObject` while it is set. The hourly grace pass converges each store's record and re-runs the grant, which rewrites the policy (the `regrantForScanning` precedent). |
| + |
| +**Tech Stack:** Go; `internal/console`, `internal/mail`, `internal/objstore`. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md`: |
| +- §5.6 (email: "warn at 80%, allow up to 2x the cap, pause at 2x"; the 10,000 hard ceiling); |
| +- §5.5 (storage: after grace, `Deny s3:PutObject`, reads and deletes keep working); |
| +- §6 (stages; the notice rule; "two things do not wait for notice: hard ceilings…"). |
| + |
| +The plan builds on Plan 4a, merged as 9623e47: `plan_cap_state`, `afterGraceDue`, `planGracePass`, `measureCaps`. |
| + |
| +## Scope split (rest of Plan 4) |
| + |
| +- **4b (this plan):** email pause and storage write deny, both console-side. |
| +- **4c:** the box-side throttle for bandwidth and awake hours: |
| + - throttle state in the limits record; |
| + - edge throttling; |
| + - open WebSockets closed and new upgrades refused; |
| + - the 15-minute continuous-awake ceiling for instances. |
| +- **4d:** the lapse lifecycle (§9.2), including disabling running things over the cap, newest first. Nothing in the code can disable an app or instance today, and that mechanism serves lapse. |
| + |
| +## Calls for Paul (both CONFIRMED by Paul, 2026-10-25) |
| + |
| +1. **The email pause does not wait for notice.** Email's grace is "the rest of the day up to 2x" (§6), so its after-grace moment is 2x, inside one day. The 72-hour notice rule could therefore never be met. Sending reputation is shared by every tenant (§5.6), the reason §6 gives for hard ceilings skipping notice. So the pause at 2x is treated as a ceiling. Owners already get the 80% and over emails that day from Plan 4a. |
| +2. **Storage at 2x the cap is a hard ceiling too** (table 4.2, "2x cap"). It denies writes without waiting for grace or notice. Below 2x, writes are denied only once `afterGraceDue` holds. |
| + |
| +## Global Constraints |
| + |
| +- **No catalog, no change:** |
| + - every new check returns at once when `EffectiveLimits(acct)` is nil; |
| + - no pause, no policy change, no record field written; |
| + - existing per-sender caps, rate pauses and scanning denies behave exactly as today. |
| +- **Email pause point:** `min(2*EmailPerDay, Ceilings.EmailPerDay)`, where a ceiling of 0 means none. It applies to the account's `AccountSends` for the UTC day. |
| +- **Storage deny when** `afterGraceDue(st, now) || st.Used >= 2*st.Limit`. It is cleared when neither holds (back under, or a bigger limit). A storage measurement that can't be read leaves every store as it is. |
| +- **Only the capped action is refused.** |
| + - Email: senders paused. Apps keep serving. |
| + - Storage: `s3:PutObject` denied. `Get`, `List` and `Delete` stay allowed, so the customer can clean up. |
| +- **Per-instance senders are left alone.** `SetSenderPaused` cannot resume them (`ErrPerInstance`), and pausing one deactivates every instance's key. They are logged once per day roll. An operator's per-sender `DailyCap` still governs them. |
| +- **Every pause, resume, deny and clear is audited** on the account, with the figures behind it (the `mail.paused` precedent, `mailcounts.go:222`). |
| +- **Copy:** new strings join `planNoticeCopy`, and the Luna pass reviews them (Paul, 2026-10-25). |
| +- **Census:** the console envelope is re-pinned. A new objstore record writer needs a record-write census layer. Astra approves the census card, and only decisions go to Paul. |
| +- **Tests:** touched packages only, with `-run`; CI runs the full suite. Use `planNow` and inject `now`. |
| + |
| +## Review Focus |
| + |
| +1. **A sender paused for the plan comes back the next UTC day** even though it sends nothing, and only `plan` pauses come back. Rate and manual pauses never do. Pinned in Task 1 (`TestPlanMailPauseResumesOnDayRoll`, `TestPlanResumeLeavesOtherPausesAlone`). |
| +2. **Writes denied, reads and deletes allowed:** the policy keeps List, Get and Delete, keeps both anti-forgery denies and the scanning deny, and adds only the write deny. Pinned in Task 2 (`TestStorePolicyDeniesWritesOnly`). |
| +3. **A deny lifts by itself** when usage falls under the cap or the plan grows. Pinned in Task 3 (`TestStorageDenyClearsWhenBackUnder`). |
| +4. **Unknown is not over.** An unreadable storage sweep neither sets nor clears a deny. Pinned in Task 3 (`TestStorageDenyUnchangedWhenUnmeasured`). |
| +5. **The banner says why.** While a stage is active the account banner and CLI line say what is refused and until when. Pinned in Task 4 (`TestBannerSaysEmailPaused`, `TestBannerSaysStorageWritesDenied`). |
| + |
| +--- |
| + |
| +### Task 1: Account-wide email pause and day-roll resume |
| + |
| +**Files:** |
| +- Modify: `internal/mail/mail.go:84` (add `PauseKindPlan = "plan"`). |
| +- Modify: `internal/console/mailcounts.go`: |
| + - `enforceMailLimits` (:222) calls `s.enforceAccountMail` after its per-sender checks; |
| + - `resumeStaleCapPause` (:176) also resumes `PauseKindPlan`. |
| +- Create: `internal/console/planmail.go`. |
| +- Modify: `internal/console/plangracepass.go`: `planGraceAccount` calls `s.resumePlanMail(ctx, acct, now)`. |
| +- Test: `internal/console/planmail_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: `AccountSends` (`mailcounts.go:325`), `mail.ListSenders` (`mail.go:288`), `mail.SetSenderPaused` (`walk.go:2006`), `s.store.AppsIn`, `EffectiveLimits`, `cfg.PlanCatalog.Ceilings`. |
| +- Produces: |
| + ```go |
| + func planMailPauseAt(l *plans.Limits, ceilings plans.Limits) int64 // 0 when the plan sets no email limit |
| + func (s *Server) enforceAccountMail(ctx context.Context, acct string, now time.Time) (bool, error) // pauses every active, non-per-instance sender of every app of acct when AccountSends >= planMailPauseAt; audits "mail.paused" once per sender with "plan: <n> of <limit> emails today" |
| + func (s *Server) resumePlanMail(ctx context.Context, acct *Account, now time.Time) error // calls resumeStaleCapPause for every sender of every app (it resumes only plan/cap pauses from an earlier UTC day) |
| + ``` |
| + |
| +- [ ] **Step 1: Write the failing tests** (fixture: `mailFixture` / `seedCounts` from `mailcounts_test.go`, `examplePlanCatalog`, free plan `email_per_day: 50`) |
| + ```go |
| + func TestPlanMailPauseAt(t *testing.T) // limit 50, ceiling 10000 -> 100; limit 8000 -> 10000; ceiling 0 -> 2x; no email limit -> 0 |
| + func TestAccountMailPausesEverySenderAt2x(t *testing.T) // two apps, two senders; 100 sends today: every sender Active=false, PauseKind "plan"; audit mail.paused |
| + func TestAccountMailBelow2xLeavesSenders(t *testing.T) // 99 sends: all active |
| + func TestAccountMailWithoutACatalogUnchanged(t *testing.T) // 500 sends, no catalog: all active (per-sender caps aside) |
| + func TestAccountMailSkipsPerInstanceSenders(t *testing.T) |
| + func TestPlanMailPauseResumesOnDayRoll(t *testing.T) // paused at planNow; resumePlanMail at planNow+1 UTC day: active again, audit mail.resumed; same day: still paused |
| + func TestPlanResumeLeavesOtherPausesAlone(t *testing.T) // a rate pause and a manual pause from yesterday stay paused |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'PlanMailPauseAt|AccountMail|PlanMailPause|PlanResume'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** In `enforceMailLimits`, call `enforceAccountMail` after the per-sender pause decision, whether or not this sender paused. Errors are logged and don't stop the per-sender result. |
| +- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Enforce|MailCount|ResumeStale'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `console: account-wide email pause at twice the plan (plans 4b)`. |
| + |
| +### Task 2: Store write deny in the policy |
| + |
| +**Files:** |
| +- Modify: `internal/objstore/objstore.go:140` (`Record` gains `WritesDenied *WritesDenied`). |
| +- Modify: `internal/objstore/aws.go:180` (`storePolicyJSON`) and `:391` (`EnsureUser`). |
| +- Modify: `internal/objstore/provisioner.go:21` (the interface). |
| +- Modify: `internal/objstore/memprovisioner.go:79`. |
| +- Modify: `internal/objstore/walk.go:297` (`claimRawGrantIn` passes the flag). |
| +- Modify: the console wrappers at `internal/console/claim_backends.go:205`, `claim_store_effects.go:67` and `claim_purge_backend.go:45`, plus every test fake the compiler names. |
| +- Test: `internal/objstore/aws_policy_test.go` (or beside the existing `storePolicyJSON` tests), `internal/objstore/walk_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: |
| + ```go |
| + type WritesDenied struct { Reason string `json:"reason"`; At time.Time `json:"at"` } // on Record as `json:"writes_denied,omitempty"` |
| + func storePolicyJSON(bucketARN string, deny *DenyTag, denyWrites bool) string // denyWrites adds {"Effect":"Deny","Action":"s3:PutObject","Resource":"<bucketARN>/*"} |
| + // Provisioner: |
| + EnsureUser(ctx context.Context, name, path, bucketARN string, deny *DenyTag, denyWrites bool) (arn string, err error) |
| + func SetWritesDenied(ctx context.Context, s release.Store, acct, app, env string, wd *WritesDenied) (*Record, error) // CAS write of the record's field only; nil clears; a missing record is os.ErrNotExist |
| + ``` |
| + `claimRawGrantIn` passes `rec.WritesDenied != nil`. |
| + |
| +- [ ] **Step 1: Write the failing tests** |
| + ```go |
| + func TestStorePolicyDeniesWritesOnly(t *testing.T) // denyWrites: the PutObject deny is present; Allow still has List/Get/Put/Delete/GetObjectTagging; both anti-forgery denies present; with a DenyTag the infected GetObject deny is still present |
| + func TestStorePolicyUnchangedWithoutDeny(t *testing.T) // denyWrites false: byte-identical to today's output for the same inputs |
| + func TestGrantWritesTheWriteDeny(t *testing.T) // record with WritesDenied, GrantIn on MemProvisioner: PolicyFor(user) holds the deny; cleared and re-granted: gone |
| + func TestSetWritesDeniedRoundTrip(t *testing.T) // set then Get: field equal; nil clears; missing record: os.ErrNotExist |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/objstore/ -run 'StorePolicy|GrantWritesTheWriteDeny|SetWritesDenied'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** again, plus `go test ./internal/objstore/ ./internal/console/ -run 'Store|Grant|Scan|Purge'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `objstore: a store policy that refuses new uploads (plans 4b)`. |
| + |
| +### Task 3: Storage stage in the grace pass |
| + |
| +**Files:** |
| +- Create: `internal/console/planstorage.go`. |
| +- Modify: `internal/console/plangracepass.go`: `planGraceAccount` calls `s.convergeStorageDeny(ctx, acct, st, measured, now)` after storing the storage row. |
| +- Test: `internal/console/planstorage_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: `afterGraceDue`; `objstore.StoreEnvironments`, `objstore.GetIn`, `objstore.SetWritesDenied`, `objstore.GrantIn`; `claimAppCall` (the `regrantForScanning` precedent, `apiscan.go:624`); `appconfig.ParsePublicKey(s.cfg.SecretsPub, "CARLOS_SECRETS_PUBKEY")`. |
| +- Produces: |
| + ```go |
| + func storageDenyDue(st capState, now time.Time) bool // afterGraceDue(st, now) || (st.Level.over() && st.Used >= 2*st.Limit) |
| + func (s *Server) convergeStorageDeny(ctx context.Context, acct *Account, st capState, measured bool, now time.Time) error |
| + ``` |
| + `convergeStorageDeny` does nothing when `measured` is false. Otherwise, for each provisioned store of every app (the default store and every environment), it compares `rec.WritesDenied != nil` with `storageDenyDue(st, now)`. When they differ it: |
| + - writes the field (`Reason`: `"plan storage: <used> of <limit> bytes"`); |
| + - re-runs the grant with the record's own grant source, as `regrantForScanning` does; |
| + - audits `store.writes_denied` or `store.writes_allowed`. |
| + |
| + With no secrets key configured, it logs once and returns. |
| + |
| +- [ ] **Step 1: Write the failing tests** (`privateStorageFixture` or the `apistore` fixtures with `*objstore.MemProvisioner`; a storage day file through `putStorageDay`) |
| + ```go |
| + func TestStorageDenyDue(t *testing.T) // in grace: false; grace over + notice 72h: true; 2x without notice: true |
| + func TestStorageDenySetAfterGrace(t *testing.T) // over row, grace ended, notice 72h old: record WritesDenied set, policy holds the deny, audit store.writes_denied |
| + func TestStorageDenyClearsWhenBackUnder(t *testing.T) // then usage under the cap: field cleared, deny gone, audit store.writes_allowed |
| + func TestStorageDenyUnchangedWhenUnmeasured(t *testing.T) // denied store, sweep unreadable: still denied |
| + func TestStorageDenyWithoutACatalogUnchanged(t *testing.T) |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'StorageDeny'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** again. Expected: PASS. |
| +- [ ] **Step 5: Commit** `console: refuse new uploads past storage grace (plans 4b)`. |
| + |
| +### Task 4: The banner and CLI say why |
| + |
| +**Files:** |
| +- Modify: `internal/console/plancaps_copy.go` (keys `banner.email_paused`, `cli.email_paused`, `banner.storage_denied`, `cli.storage_denied`). |
| +- Modify: `internal/console/plangracepass.go`: `planNoticeText`, and `planNotice` gains `Stage string` (`""`, `"email_paused"`, `"storage_denied"`). |
| +- Test: `internal/console/plangrace_view_test.go`, `plangrace_cli_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: `planNoticesOf` sets `Stage`: |
| + - `"email_paused"` for an `email` row whose `Used >= planMailPauseAt`. It needs the limits, so `planNoticesOf(states, now, l *plans.Limits, ceilings plans.Limits)`. Callers pass `EffectiveLimits` and the catalog's ceilings. |
| + - `"storage_denied"` for a `storage` row where `storageDenyDue`. |
| + |
| + `planNoticeText` uses the stage key when `Stage != ""`. Draft copy: |
| + - email paused: "Email is paused until midnight UTC: this account sent %s." / cli: "email is paused until midnight utc: this account sent %s". |
| + - storage denied: "New uploads to this account's storage are refused: %s. Downloads and deletes still work." / cli: "new uploads are refused: %s. downloads and deletes still work". |
| + |
| +- [ ] **Step 1: Write the failing tests** |
| + ```go |
| + func TestBannerSaysEmailPaused(t *testing.T) // email row at 2x: banner contains "Email is paused until midnight UTC" |
| + func TestBannerSaysStorageWritesDenied(t *testing.T) // storage row past grace with notice: banner contains "New uploads to this account's storage are refused" |
| + func TestCLIWarningSaysStorageWritesDenied(t *testing.T) |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'BannerSays|CLIWarningSays'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** Update every `planNoticesOf` caller. |
| +- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Banner|CLIWarning|GracePass'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `console: banner and CLI say which plan stage is active (plans 4b)`. |
| + |
| +### Task 5: Docs, Luna, census and gates |
| + |
| +- [ ] Run a Luna copy pass on the four new strings: a committed brief carrying the house rules and example renderings. Apply its changes and show Paul only what it flags. |
| +- [ ] Extend `docs/site/plans.md` "Warnings and grace" with what happens after grace for email and storage, and how each lifts. |
| +- [ ] Census: |
| + - run `make census-card`, add hand decision rows if a new unit appears, then `make census-propose NAME=plans-4b-after-grace CLAIMS=<file>`; |
| + - add a record-write census layer for `objstore.SetWritesDenied`; |
| + - Astra approves the card, and decisions go to Paul. |
| +- [ ] Merge main, push, wait for green CI, then Astra's whole-branch review. |
| + |
| +## Done when |
| + |
| +Every task's tests pass and Review Focus 1–5 are pinned. The census card is approved. CI is green after merging current main, and Astra's whole-branch review has no open Critical or Important finding. |
| + |
| +## Astra review (2026-10-25) |
| + |
| +Findings in `docs/superpowers/specs/CODEX-FINDINGS-PLANS-4B-CODE.md`: five Important (all fixed, each test-first) and two Minor (deferred). |
| + |
| +1. **A failed storage regrant was never retried.** The record now carries `WritesDenyApplied`, which is set only after a successful grant, and the pass retries while it disagrees. |
| +2. **Concurrent pauses could be overwritten.** `mail.SetSenderPausedIf` checks eligibility against the sender as reread inside the mutation, for both the plan pause and the day-roll resume. |
| +3. **A delayed SES event could re-pause.** The account check measures the current UTC day. Sender counters keep the event's day. |
| +4. **One broken app blocked the rest.** The account loops carry on past a failure and report every error together. |
| +5. **A removed storage limit kept its deny.** `clearStorageDeny` runs when the plan sets no storage cap. |
| + |
| +Deferred Minors: |
| +- The email-paused banner can disappear after a mid-day upgrade while senders stay paused until the day rolls. |
| +- The live MinIO contract does not exercise the write deny. |
| + |
| +Census: Astra approved all three envelopes (`internal/console`, `internal/mail`, `internal/objstore`). |
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-PLANS-4B-CODE.md b/docs/superpowers/specs/CODEX-FINDINGS-PLANS-4B-CODE.md| new file mode 100644 |
| index 000000000..e7be4e769 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-FINDINGS-PLANS-4B-CODE.md |
| @@ -0,0 +1,34 @@ |
| +Reviewed HEAD `daf34151639d840551d227609f58b3c514ab3664`. No Critical findings. |
| + |
| +1. **Important — failed storage rewrites never retry.** [planstorage.go:54](/home/paulca/.cache/tmp/claude-1001/plans-4b-after-grace/internal/console/planstorage.go:54) |
| + `SetWritesDenied` commits before `GrantIn` rewrites the policy. If IAM fails—or claim admission refuses the regrant—the next pass sees the desired record value and skips it permanently. Setting can leave uploads allowed above the ceiling; clearing can leave uploads refused after cleanup or upgrade. Track successful policy application separately or retry the regrant until it succeeds. |
| + |
| +2. **Important — concurrent pauses can erase a rate or manual pause.** [planmail.go:65](/home/paulca/.cache/tmp/claude-1001/plans-4b-after-grace/internal/console/planmail.go:65) |
| + The active/per-instance checks use the earlier listing. Between that check and `SetSenderPaused`, another event or operator can pause the sender. `SetSenderPaused` rereads it but unconditionally replaces its pause kind with `plan`, so tomorrow’s sweep resumes a sender that must remain paused. Claim-mode serialization does not protect the preceding eligibility check. The new resume sweep has the corresponding stale-snapshot risk. Check eligibility inside the serialized mutation, before changing keys. |
| + |
| +3. **Important — delayed SES events reapply yesterday’s account pause.** [mailcounts.go:227](/home/paulca/.cache/tmp/claude-1001/plans-4b-after-grace/internal/console/mailcounts.go:227) |
| + This forwards `now`, which the SES caller supplies from the original message’s `SentAt`. After Monday’s capped account resumes on Tuesday, a delayed delivery or bounce for Monday reads Monday’s over-limit count and pauses every active sender again, including siblings with no Tuesday usage. Preserve event-day attribution for counters, but enforce the account’s daily ceiling against the current UTC day. |
| + |
| +4. **Important — one broken app prevents unrelated apps from converging.** [planmail.go:72](/home/paulca/.cache/tmp/claude-1001/plans-4b-after-grace/internal/console/planmail.go:72), [planmail.go:97](/home/paulca/.cache/tmp/claude-1001/plans-4b-after-grace/internal/console/planmail.go:97), [planstorage.go:41](/home/paulca/.cache/tmp/claude-1001/plans-4b-after-grace/internal/console/planstorage.go:41) |
| + These account-wide loops stop at the first failure. Apps are ordered alphabetically: an unreadable record or persistently failing credential in app `a` prevents app `z` from pausing, resuming, or changing its storage policy on every subsequent pass. Continue across independent senders/stores and aggregate failures. |
| + |
| +5. **Important — removing a storage limit leaves its existing deny indefinitely.** [plangracepass.go:86](/home/paulca/.cache/tmp/claude-1001/plans-4b-after-grace/internal/console/plangracepass.go:86) |
| + With the catalog still enabled, moving an account to a plan with `StorageBytes == 0` stops storage measurement. The pass deletes the cap-state row without running storage convergence, leaving `WritesDenied` and the IAM deny intact forever. Handle removal of this individual cap explicitly; distinguish it from an unreadable measurement and from disabling plans entirely. |
| + |
| +6. **Minor — the displayed email stage can disagree with the actual pause.** [plangracepass.go:342](/home/paulca/.cache/tmp/claude-1001/plans-4b-after-grace/internal/console/plangracepass.go:342) |
| + After a free account pauses at 100 sends, upgrading its limit to 1,000 immediately removes the `email_paused` stage because the calculated threshold changes. Its credentials remain paused until the next UTC day. This discrepancy persists beyond the acknowledged hourly measurement lag. Derive the displayed stage from applied enforcement state. |
| + |
| +7. **Minor — the MinIO contract never exercises the new deny.** [writesdenied_test.go:32](/home/paulca/.cache/tmp/claude-1001/plans-4b-after-grace/internal/objstore/writesdenied_test.go:32) |
| + The new tests inspect JSON and the memory provisioner. The live fixture still installs only the existing writable policy at [.amadan/ci.d/30-minio-contract:298](/home/paulca/.cache/tmp/claude-1001/plans-4b-after-grace/.amadan/ci.d/30-minio-contract:298). A green contract run therefore does not establish that the new stage refuses uploads while preserving downloads, listing, and deletion, or that clearing restores uploads. |
| + |
| +Static checks confirmed that the policy preserves both anti-forgery denies and the scanning deny; environment stores are enumerated; unreadable storage measurements leave enforcement unchanged; and catalog-off entry points skip new enforcement. The hourly mail sweep lists every live app and reads its senders each hour. |
| + |
| +Targeted tests were attempted with `GOFLAGS=-buildvcs=false`, but Go could not create its build directory in the read-only sandbox. No tests ran. HEAD and the working tree remain unchanged. |
| + |
| +**Census verdicts**, limited to the card’s root-read question: |
| + |
| +- **`internal/console`: approve.** Reviewed the changed enforcement, notification, and adapter functions and their downstream calls. Existing claim authorization remains in [claim_backends.go:205](/home/paulca/.cache/tmp/claude-1001/plans-4b-after-grace/internal/console/claim_backends.go:205); purge still refuses provisioning. No new root filesystem or execution authority was identified. |
| +- **`internal/mail`: approve.** [mail.go:83](/home/paulca/.cache/tmp/claude-1001/plans-4b-after-grace/internal/mail/mail.go:83) adds a pause-kind constant only. |
| +- **`internal/objstore`: approve.** [writesdenied.go:16](/home/paulca/.cache/tmp/claude-1001/plans-4b-after-grace/internal/objstore/writesdenied.go:16) uses existing validated record reads and CAS writes through `PutIn`; policy generation adds a deny without changing resource selection, existing validation, or root read targets. |
| + |
| +**Verdict: changes required.** |
| \ No newline at end of file |
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-4B-CODE.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-4B-CODE.md| new file mode 100644 |
| index 000000000..68b4e1799 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-4B-CODE.md |
| @@ -0,0 +1,38 @@ |
| +# Whole-branch code review brief: Plans 4b (email and storage after-grace stages) |
| + |
| +You are a senior Go reviewer on the carlos platform, and the census's |
| +cross-model reviewer for this branch. Review branch `plans-4b-after-grace` |
| +(`git diff c3a34e32f9b13d60456f22bafd756abb3a97a026..HEAD` is the branch's own change). Read-only: do not |
| +modify the working tree, index, HEAD or branches. You may run `go test` |
| +with GOFLAGS=-buildvcs=false, targeted with -run. |
| + |
| +Requirements: the spec docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md |
| +§5.5, §5.6 and §6; the plan docs/superpowers/plans/2026-10-25-plans-4b-email-and-storage-stages.md, |
| +including its Global Constraints, Review Focus and the two calls Paul |
| +CONFIRMED (the email pause at 2x skips the notice wait; storage at 2x is a |
| +hard ceiling); the executor's `Ruling:` lines in |
| +docs/superpowers/notes/plans-4b-ledger.md. Plan 4a (merged) is the base: |
| +plan_cap_state, afterGraceDue, the grace pass. |
| + |
| +Grade by effect. Check each Review Focus line deliberately, and also: |
| +- plans off changes nothing: no pause, no policy change, no record field; |
| + existing per-sender caps, rate pauses, manual pauses and scanning |
| + denies behave exactly as before; |
| +- the account pause: races between SES events, an account with many apps, |
| + per-instance senders, a sender paused for another reason; |
| +- resume: only plan and cap pauses from an earlier UTC day, never rate or |
| + manual; the hourly sweep cost; |
| +- the storage policy: reads, lists and deletes still allowed; the |
| + anti-forgery and scanning denies intact; MinIO uses the same policy; |
| +- convergence: set and clear idempotent; a regrant failure halfway (record |
| + marked, policy not rewritten); env stores; claim mode (claimAppCall); |
| +- the banner and CLI stage lines match what enforcement does. |
| + |
| +Census: answer the card's review question for every re-pinned envelope in |
| +docs/superpowers/notes/census-proposal-plans-4b-after-grace.md. Give |
| +approve or escalate per envelope. |
| + |
| +Answer: findings graded Critical / Important / Minor, each with file:line |
| +and a concrete failure scenario; then the census verdicts; then a verdict: |
| +accept, accept with fixes, or changes required. Do not review the |
| +wording (Luna-approved copy in plancaps_copy.go). |
diff --git a/docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-4B.md b/docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-4B.md| new file mode 100644 |
| index 000000000..bb22dd039 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-4B.md |
| @@ -0,0 +1,32 @@ |
| +# Copy pass brief: plan stage notices (plans 4b) |
| + |
| +You are reviewing user-facing strings for a hosting console (the carlos platform). Paul, the owner, delegated this review to you. Apply his house rules and return improved strings. |
| + |
| +## House rules |
| + |
| +- No em dashes or en dashes used as dashes. Where you would use one, end the sentence with a full stop and start a new one. |
| +- Plain words, short sentences, no jargon, no marketing tone, no exclamation marks. |
| +- CLI strings (keys starting `cli.`) are entirely lower case, with no full stop at the very end. Banner strings use normal sentence case. |
| +- Keep the one `%s` placeholder in each string. |
| +- Do not name the product. |
| +- Facts that must stay true: email for the whole account is paused because it sent twice its plan's daily limit, and it resumes at midnight UTC; for storage, new uploads are refused but downloads and deletes still work; storage writes come back once usage is under the plan's limit. |
| + |
| +## How the strings combine |
| + |
| +`%s` is a usage phrase. Examples: `100 of 50 emails today`, `3 GB of 1 GB object storage`. |
| + |
| +- banner, email: Email is paused until midnight UTC: this account sent 100 of 50 emails today. |
| +- banner, storage: New uploads to this account's storage are refused: 3 GB of 1 GB object storage. Downloads and deletes still work. |
| + |
| +## Strings |
| + |
| +| key | current | |
| +|---|---| |
| +| `banner.email_paused` | Email is paused until midnight UTC: this account sent %s. | |
| +| `cli.email_paused` | email is paused until midnight utc: this account sent %s | |
| +| `banner.storage_denied` | New uploads to this account's storage are refused: %s. Downloads and deletes still work. | |
| +| `cli.storage_denied` | new uploads are refused: %s. downloads and deletes still work | |
| + |
| +## Answer |
| + |
| +Return a Markdown table with columns `key`, `new`, `why` for every key, `new` equal to `current` where no change is needed. Then a section `Flags` for anything Paul must decide. Do not edit any files. |
diff --git a/docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4B.md b/docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4B.md| new file mode 100644 |
| index 000000000..23aa9a9ca |
| --- /dev/null |
| +++ b/docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4B.md |
| @@ -0,0 +1,10 @@ |
| +| key | new | why | |
| +|---|---|---| |
| +| `banner.email_paused` | Email is paused until midnight UTC: this account sent %s. | Clear and matches the required account-wide pause and reset time. | |
| +| `cli.email_paused` | email is paused until midnight utc: this account sent %s | Lower case with no final full stop. | |
| +| `banner.storage_denied` | New uploads to this account's storage are refused: %s. Downloads and deletes still work. | Clear and preserves the storage behavior. | |
| +| `cli.storage_denied` | new uploads to this account's storage are refused: %s. downloads and deletes still work | Adds the missing storage context, stays lower case, and has no final full stop. | |
| + |
| +## Flags |
| + |
| +None. No files were edited. |
| \ No newline at end of file |
diff --git a/internal/console/claim_app_mutation_test.go b/internal/console/claim_app_mutation_test.go| index 4e1d34cc5..bce2b01af 100644 |
| --- a/internal/console/claim_app_mutation_test.go |
| +++ b/internal/console/claim_app_mutation_test.go |
| @@ -42,7 +42,7 @@ func TestClaimAppMutationGate(t *testing.T) { |
| base := func() hostops.AppAdmission { |
| return hostops.AppAdmission{V: 1, AppID: "app", Revision: 1, Epoch: 1, State: "open", Registrations: map[string]hostops.Registration{}, Effects: map[string]hostops.Effect{}} |
| } |
| - for _, door := range []string{"restore", "protection", "store-grant", "store-provision", "store-rotate", "store-rotate-finish", "store-destroy", "scan-regrant", "store-declare"} { |
| + for _, door := range []string{"restore", "protection", "store-grant", "store-provision", "store-rotate", "store-rotate-finish", "store-destroy", "scan-regrant", "store-declare", "plan-storage-regrant"} { |
| t.Run(door, func(t *testing.T) { |
| ctx := context.Background() |
| begin := func(a hostops.AppAdmission, id string) (*hostops.OperationHandle, error, *hostops.ControlWriter) { |
diff --git a/internal/console/claim_backend_recorders_test.go b/internal/console/claim_backend_recorders_test.go| index 5fa134071..a611a25c6 100644 |
| --- a/internal/console/claim_backend_recorders_test.go |
| +++ b/internal/console/claim_backend_recorders_test.go |
| @@ -35,7 +35,7 @@ func (w *StoreProvisionerBoundary) EnsureBucket(ctx context.Context, name string |
| } |
| return w.raw.EnsureBucket(ctx, name) |
| } |
| -func (w *StoreProvisionerBoundary) EnsureUser(ctx context.Context, name string, path string, bucketARN string, deny *objstore.DenyTag) (string, error) { |
| +func (w *StoreProvisionerBoundary) EnsureUser(ctx context.Context, name string, path string, bucketARN string, deny *objstore.DenyTag, denyWrites bool) (string, error) { |
| body, err := json.Marshal(map[string]any{"name": name, "path": path, "bucketARN": bucketARN, "deny": deny}) |
| if err != nil { |
| return "", err |
| @@ -44,7 +44,7 @@ func (w *StoreProvisionerBoundary) EnsureUser(ctx context.Context, name string, |
| if err != nil { |
| return "", err |
| } |
| - return w.raw.EnsureUser(ctx, name, path, bucketARN, deny) |
| + return w.raw.EnsureUser(ctx, name, path, bucketARN, deny, denyWrites) |
| } |
| func (w *StoreProvisionerBoundary) MintKey(ctx context.Context, user string) (string, string, error) { |
| body, err := json.Marshal(map[string]any{"user": user}) |
diff --git a/internal/console/claim_backends.go b/internal/console/claim_backends.go| index 99066e190..bbcae9421 100644 |
| --- a/internal/console/claim_backends.go |
| +++ b/internal/console/claim_backends.go |
| @@ -202,11 +202,11 @@ func (p claimStoreProvisioner) EnsureBucket(ctx context.Context, name string) (s |
| } |
| return p.raw.EnsureBucket(ctx, name) |
| } |
| -func (p claimStoreProvisioner) EnsureUser(ctx context.Context, name, path, bucketARN string, deny *objstore.DenyTag) (string, error) { |
| +func (p claimStoreProvisioner) EnsureUser(ctx context.Context, name, path, bucketARN string, deny *objstore.DenyTag, denyWrites bool) (string, error) { |
| if err := p.userPolicy(ctx, name, bucketARN); err != nil { |
| return "", err |
| } |
| - return p.raw.EnsureUser(ctx, name, path, bucketARN, deny) |
| + return p.raw.EnsureUser(ctx, name, path, bucketARN, deny, denyWrites) |
| } |
| func (p claimStoreProvisioner) MintKey(ctx context.Context, user string) (string, string, error) { |
| if err := p.user(ctx, "MintKey", user); err != nil { |
diff --git a/internal/console/claim_purge_backend.go b/internal/console/claim_purge_backend.go| index 034281991..b2c76474d 100644 |
| --- a/internal/console/claim_purge_backend.go |
| +++ b/internal/console/claim_purge_backend.go |
| @@ -42,7 +42,7 @@ var _ objstore.Provisioner = claimPurgeStore{} |
| func (p claimPurgeStore) EnsureBucket(context.Context, string) (string, error) { |
| return "", hostops.ErrContract |
| } |
| -func (p claimPurgeStore) EnsureUser(context.Context, string, string, string, *objstore.DenyTag) (string, error) { |
| +func (p claimPurgeStore) EnsureUser(context.Context, string, string, string, *objstore.DenyTag, bool) (string, error) { |
| return "", hostops.ErrContract |
| } |
| func (p claimPurgeStore) MintKey(context.Context, string) (string, string, error) { |
diff --git a/internal/console/claim_store_effects.go b/internal/console/claim_store_effects.go| index 72fb98dfc..3e867afc8 100644 |
| --- a/internal/console/claim_store_effects.go |
| +++ b/internal/console/claim_store_effects.go |
| @@ -64,9 +64,9 @@ func (p claimEffectProvisioner) mutation(ctx context.Context, resource, action s |
| func (p claimEffectProvisioner) EnsureBucket(ctx context.Context, name string) (string, error) { |
| return p.effects.run(ctx, "bucket:"+name, "ensure-bucket", name, func(ctx context.Context) (string, error) { return p.base.EnsureBucket(ctx, name) }) |
| } |
| -func (p claimEffectProvisioner) EnsureUser(ctx context.Context, name, path, arn string, deny *objstore.DenyTag) (string, error) { |
| +func (p claimEffectProvisioner) EnsureUser(ctx context.Context, name, path, arn string, deny *objstore.DenyTag, denyWrites bool) (string, error) { |
| return p.effects.run(ctx, "iam-user:"+name, "ensure-user", []any{name, path, arn, deny}, func(ctx context.Context) (string, error) { |
| - return p.base.EnsureUser(ctx, name, path, arn, deny) |
| + return p.base.EnsureUser(ctx, name, path, arn, deny, denyWrites) |
| }) |
| } |
| func (p claimEffectProvisioner) MintKey(ctx context.Context, user string) (string, string, error) { |
diff --git a/internal/console/deletion_test.go b/internal/console/deletion_test.go| index 77bced1de..ea0d33e33 100644 |
| --- a/internal/console/deletion_test.go |
| +++ b/internal/console/deletion_test.go |
| @@ -521,7 +521,7 @@ func seedStore(t *testing.T, fx *consoleFixture, fake *objstore.MemProvisioner, |
| } |
| fake.Buckets[bucket]["customer/data.bin"] = []byte("the customer's objects") |
| user := objstore.UserName(fx.sqid, app) |
| - arn, err := fake.EnsureUser(ctx, user, objstore.UserPath, "arn:aws:s3:::"+bucket, nil) |
| + arn, err := fake.EnsureUser(ctx, user, objstore.UserPath, "arn:aws:s3:::"+bucket, nil, false) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/mailcounts.go b/internal/console/mailcounts.go| index 25e9e6c47..cd81069f7 100644 |
| --- a/internal/console/mailcounts.go |
| +++ b/internal/console/mailcounts.go |
| @@ -11,6 +11,7 @@ package console |
| import ( |
| "context" |
| + "errors" |
| "fmt" |
| "log" |
| "time" |
| @@ -181,7 +182,7 @@ func (s *Server) resumeStaleCapPause(ctx context.Context, acct, app, sender stri |
| // untouched. The first two never auto-resume by design; the third must |
| // not, because resuming reactivates every key including the standalones |
| // and the app credential every instance still holds. |
| - if sn.Provisioned.PauseKind != mail.PauseKindCap || sn.PerInstance { |
| + if (sn.Provisioned.PauseKind != mail.PauseKindCap && sn.Provisioned.PauseKind != mail.PauseKindPlan) || sn.PerInstance { |
| return sn, false, nil |
| } |
| pausedDay := sn.Provisioned.At.UTC().Format("2006-01-02") |
| @@ -191,7 +192,18 @@ func (s *Server) resumeStaleCapPause(ctx context.Context, acct, app, sender stri |
| // future) — not a day roll yet. |
| return sn, false, nil |
| } |
| - if _, err := mail.SetSenderPaused(ctx, s.claimMailStore(), s.cfg.MailProvisioner, acct, app, sender, false, "", now); err != nil { |
| + // Asked again of the sender as read inside the mutation: sn may be a |
| + // stale listing, and a pause taken since (manual, rate) must stay |
| + // (Astra plans-4b finding 2). |
| + stillStale := func(cur *mail.Sender) bool { |
| + return cur.Provisioned != nil && !cur.Provisioned.Active && !cur.PerInstance && |
| + (cur.Provisioned.PauseKind == mail.PauseKindCap || cur.Provisioned.PauseKind == mail.PauseKindPlan) && |
| + cur.Provisioned.At.UTC().Format("2006-01-02") < today |
| + } |
| + if _, err := mail.SetSenderPausedIf(ctx, s.claimMailStore(), s.cfg.MailProvisioner, acct, app, sender, false, "", now, stillStale); err != nil { |
| + if errors.Is(err, mail.ErrNotEligible) { |
| + return sn, false, nil |
| + } |
| return nil, false, err |
| } |
| if a, err := s.store.AccountBySqid(acct); err != nil { |
| @@ -220,6 +232,17 @@ func (s *Server) resumeStaleCapPause(ctx context.Context, acct, app, sender stri |
| // presents to the member as "email stopped working", which is the failure |
| // this whole mechanism is supposed to prevent someone else's tenant causing. |
| func (s *Server) enforceMailLimits(ctx context.Context, acct, app, sender string, now time.Time) (bool, string, error) { |
| + // The account-wide plan pause (plans 4b) runs after the sender's own |
| + // checks, whatever they decided: one sender's event can carry the |
| + // account past twice its daily limit. |
| + // It measures TODAY, not the event's day: a delayed event for an |
| + // earlier day must not pause an account that has since resumed (Astra |
| + // plans-4b finding 3). The sender's own counters keep the event's day. |
| + defer func() { |
| + if _, err := s.enforceAccountMail(ctx, acct, time.Now()); err != nil { |
| + log.Printf("console: plan mail %s: %v", acct, err) |
| + } |
| + }() |
| sn, _, err := mail.GetSender(ctx, s.cfg.Releases, acct, app, sender) |
| if err != nil { |
| return false, "", err |
diff --git a/internal/console/plancaps_copy.go b/internal/console/plancaps_copy.go| index 1282ea191..0552ab413 100644 |
| --- a/internal/console/plancaps_copy.go |
| +++ b/internal/console/plancaps_copy.go |
| @@ -43,4 +43,10 @@ var planNoticeCopy = map[string]string{ |
| "email.warn": "- %s.", |
| "email.over": "- %s, over the limit. Nothing changes until %s.", |
| "email.ways_out": "To stay within the plan, buy a pack, move to a bigger plan, or clean up.\n\nAccount settings:\n%s", |
| + // Plans 4b: an after-grace stage in force. Approved by delegation (Luna, |
| + // docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4B.md). |
| + "banner.email_paused": "Email is paused until midnight UTC: this account sent %s.", |
| + "cli.email_paused": "email is paused until midnight utc: this account sent %s", |
| + "banner.storage_denied": "New uploads to this account's storage are refused: %s. Downloads and deletes still work.", |
| + "cli.storage_denied": "new uploads to this account's storage are refused: %s. downloads and deletes still work", |
| } |
diff --git a/internal/console/plangrace_cli_test.go b/internal/console/plangrace_cli_test.go| index 105b1a4ca..3804a024c 100644 |
| --- a/internal/console/plangrace_cli_test.go |
| +++ b/internal/console/plangrace_cli_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "net/http" |
| "strings" |
| "testing" |
| + "time" |
| "github.com/carlosframework/platform/internal/svcrole" |
| ) |
| @@ -36,7 +37,7 @@ func TestCLIWarningHeaderUnderAPlan(t *testing.T) { |
| overRow(t, fx) |
| token := cliToken(t, fx, "paul@keymail.dev", "code-cli-warn") |
| got := cliWarnings(t, fx, token, true) |
| - if len(got) != 1 || !strings.HasPrefix(got[0], "this account is over its plan: 2 GB of 1 GB object storage") { |
| + if len(got) != 1 || !strings.HasPrefix(got[0], "this account is over its plan: 1.5 GB of 1 GB object storage") { |
| t.Fatalf("warning header = %q", got) |
| } |
| } |
| @@ -98,3 +99,19 @@ func TestCLIWarningOnAppScopedDoors(t *testing.T) { |
| t.Fatalf("app door = %d, warnings %q", resp.StatusCode, got) |
| } |
| } |
| + |
| +func TestCLIWarningSaysStorageWritesDenied(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + st := evaluateCap(nil, capStorage, 3_000_000_000, 1_000_000_000, time.Now().Add(-time.Hour)) |
| + st.AccountID = acct.ID |
| + if err := fx.st.PutCapState(st); err != nil { |
| + t.Fatal(err) |
| + } |
| + token := cliToken(t, fx, "paul@keymail.dev", "code-cli-stage") |
| + got := cliWarnings(t, fx, token, true) |
| + if len(got) != 1 || !strings.HasPrefix(got[0], "new uploads to this account's storage are refused") { |
| + t.Fatalf("warning = %q", got) |
| + } |
| +} |
diff --git a/internal/console/plangrace_test.go b/internal/console/plangrace_test.go| index 4243c0082..c9f2c4b99 100644 |
| --- a/internal/console/plangrace_test.go |
| +++ b/internal/console/plangrace_test.go |
| @@ -231,10 +231,10 @@ func TestExpiredPeriodIsNotDueOrShown(t *testing.T) { |
| if afterGraceDue(st, nov) { |
| t.Error("October's bandwidth row is due in November") |
| } |
| - if got := planNoticesOf([]capState{st}, nov); len(got) != 0 { |
| + if got := planNoticesOf([]capState{st}, nov, nil); len(got) != 0 { |
| t.Errorf("October's row shown in November: %v", got) |
| } |
| - if got := planNoticesOf([]capState{st}, oct.Add(time.Hour)); len(got) != 1 { |
| + if got := planNoticesOf([]capState{st}, oct.Add(time.Hour), nil); len(got) != 1 { |
| t.Errorf("current row not shown: %v", got) |
| } |
| } |
diff --git a/internal/console/plangrace_view_test.go b/internal/console/plangrace_view_test.go| index c35342f57..be2fbb535 100644 |
| --- a/internal/console/plangrace_view_test.go |
| +++ b/internal/console/plangrace_view_test.go |
| @@ -16,7 +16,7 @@ func overRow(t *testing.T, fx *consoleFixture) *Account { |
| acct, _ := fx.st.AccountBySqid(fx.sqid) |
| // The real clock: page views and CLI requests record notice at |
| // time.Now(), which must not fall before the first over. |
| - st := evaluateCap(nil, capStorage, 2_000_000_000, 1_000_000_000, time.Now().Add(-time.Hour)) |
| + st := evaluateCap(nil, capStorage, 1_500_000_000, 1_000_000_000, time.Now().Add(-time.Hour)) |
| st.AccountID = acct.ID |
| if err := fx.st.PutCapState(st); err != nil { |
| t.Fatal(err) |
| @@ -29,7 +29,7 @@ func TestBannerShowsPlanNotices(t *testing.T) { |
| overRow(t, fx) |
| c := signInPaul(t, fx) |
| _, _, body := get(t, c, fx.u("/")) |
| - if !strings.Contains(body, "This account is over its plan: 2 GB of 1 GB object storage") { |
| + if !strings.Contains(body, "This account is over its plan: 1.5 GB of 1 GB object storage") { |
| t.Fatalf("account page has no plan banner:\n%s", body) |
| } |
| } |
| @@ -88,3 +88,34 @@ func TestBannerNoticeOnlyWhenRendered(t *testing.T) { |
| t.Fatal("a rendered banner recorded no notice") |
| } |
| } |
| + |
| +// Plans 4b: while a stage is active the banner says what is refused. |
| +func TestBannerSaysEmailPaused(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + st := evaluateCap(nil, capEmail, 100, 50, time.Now()) // free: 50 a day, paused at 100 |
| + st.AccountID = acct.ID |
| + if err := fx.st.PutCapState(st); err != nil { |
| + t.Fatal(err) |
| + } |
| + c := signInPaul(t, fx) |
| + if _, _, body := get(t, c, fx.u("/")); !strings.Contains(body, "Email is paused until midnight UTC") { |
| + t.Fatalf("no email-paused banner:\n%s", body) |
| + } |
| +} |
| + |
| +func TestBannerSaysStorageWritesDenied(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + st := evaluateCap(nil, capStorage, 3_000_000_000, 1_000_000_000, time.Now().Add(-time.Hour)) // 3x: the hard ceiling |
| + st.AccountID = acct.ID |
| + if err := fx.st.PutCapState(st); err != nil { |
| + t.Fatal(err) |
| + } |
| + c := signInPaul(t, fx) |
| + if _, _, body := get(t, c, fx.u("/")); !strings.Contains(body, "New uploads to this account's storage are refused") { |
| + t.Fatalf("no storage-denied banner:\n%s", body) |
| + } |
| +} |
diff --git a/internal/console/plangracepass.go b/internal/console/plangracepass.go| index 9e126ab88..3fc5ebd19 100644 |
| --- a/internal/console/plangracepass.go |
| +++ b/internal/console/plangracepass.go |
| @@ -83,6 +83,11 @@ func (s *Server) planGraceAccount(ctx context.Context, acct *Account, now time.T |
| return err |
| } |
| states = append(states, st) |
| + if c == capStorage { |
| + if err := s.convergeStorageDeny(ctx, acct, st, true, now); err != nil { |
| + log.Printf("console: plan grace %s: storage stage: %v", acct.Sqid, err) |
| + } |
| + } |
| case errs[c] != nil: |
| log.Printf("console: plan grace %s: %s: %v (row kept)", acct.Sqid, c, errs[c]) |
| if p := byCap[c]; p != nil { |
| @@ -94,6 +99,17 @@ func (s *Server) planGraceAccount(ctx context.Context, acct *Account, now time.T |
| } |
| } |
| } |
| + if _, measured := measures[capStorage]; !measured && errs[capStorage] == nil { |
| + // The plan sets no storage limit: nothing can be over it. |
| + if err := s.clearStorageDeny(ctx, acct, now); err != nil { |
| + log.Printf("console: plan grace %s: storage clear: %v", acct.Sqid, err) |
| + } |
| + } |
| + if s.cfg.MailProvisioner != nil { |
| + if err := s.resumePlanMail(ctx, acct, now); err != nil { |
| + log.Printf("console: plan grace %s: mail resume: %v", acct.Sqid, err) |
| + } |
| + } |
| return s.notifyPlanOwners(ctx, acct, states, now) |
| } |
| @@ -160,7 +176,7 @@ func (s *Server) notifyPlanOwners(ctx context.Context, acct *Account, states []c |
| func (s *Server) planNoticeEmail(acct *Account, due []capState) (string, string) { |
| lines := []string{fmt.Sprintf(planNoticeCopy["email.intro"], acct.Sqid), ""} |
| - for _, n := range planNoticesOf(due, time.Now()) { |
| + for _, n := range planNoticesOf(due, time.Now(), nil) { |
| lines = append(lines, planNoticeText(n, "email")) |
| } |
| settings := s.cfg.Origin + "/a/" + url.PathEscape(acct.Sqid) + "/settings" |
| @@ -174,16 +190,24 @@ type planNotice struct { |
| Level capLevel |
| Used, Limit int64 |
| GraceEnds time.Time |
| + // Stage names an after-grace stage in force (plans 4b): "email_paused" |
| + // or "storage_denied"; "" when none. |
| + Stage string |
| } |
| // planNoticesOf is the caps at warn or over in the current period, in |
| // capOrder. A row left from an ended day or month is not shown. |
| -func planNoticesOf(states []capState, now time.Time) []planNotice { |
| +// stage, when not nil, names the after-grace stage in force for a row. |
| +func planNoticesOf(states []capState, now time.Time, stage func(capState) string) []planNotice { |
| var out []planNotice |
| for _, c := range capOrder { |
| for _, st := range states { |
| if st.Cap == c && st.Period == capPeriod(c, now) && (st.Level == levelWarn || st.Level.over()) { |
| - out = append(out, planNotice{Cap: st.Cap, Level: st.Level, Used: st.Used, Limit: st.Limit, GraceEnds: st.GraceEnds}) |
| + n := planNotice{Cap: st.Cap, Level: st.Level, Used: st.Used, Limit: st.Limit, GraceEnds: st.GraceEnds} |
| + if stage != nil { |
| + n.Stage = stage(st) |
| + } |
| + out = append(out, n) |
| } |
| } |
| } |
| @@ -194,6 +218,9 @@ func planNoticesOf(states []capState, now time.Time) []planNotice { |
| // "email". |
| func planNoticeText(n planNotice, surface string) string { |
| use := usagePhrase(n) |
| + if f, ok := planNoticeCopy[surface+"."+n.Stage]; ok && n.Stage != "" { |
| + return fmt.Sprintf(f, use) |
| + } |
| if n.Level.over() { |
| return fmt.Sprintf(planNoticeCopy[surface+".over"], use, n.GraceEnds.UTC().Format("2 January 2006")) |
| } |
| @@ -231,7 +258,7 @@ func (s *Server) planBanner(acct *Account, role string, now time.Time) ([]string |
| return nil, nil |
| } |
| var lines []string |
| - for _, n := range planNoticesOf(states, now) { |
| + for _, n := range planNoticesOf(states, now, s.planStage(acct, now)) { |
| lines = append(lines, planNoticeText(n, "banner")) |
| } |
| if role != RoleOwner || len(lines) == 0 { |
| @@ -283,7 +310,7 @@ func (s *Server) writePlanWarnings(w http.ResponseWriter, r *http.Request, p Pri |
| return |
| } |
| now := time.Now() |
| - for _, n := range planNoticesOf(states, now) { |
| + for _, n := range planNoticesOf(states, now, s.planStage(acct, now)) { |
| w.Header().Add(planWarningHeader, planNoticeText(n, "cli")) |
| } |
| seen := shownStates(states, now) |
| @@ -309,3 +336,23 @@ func (s *Server) isOwner(acct *Account, addr string) bool { |
| } |
| return false |
| } |
| + |
| +// planStage names the after-grace stage in force for a cap row, for the |
| +// banner and CLI line (plans 4b): the same predicates enforcement uses. |
| +// nil when the account's limits cannot be read. |
| +func (s *Server) planStage(acct *Account, now time.Time) func(capState) string { |
| + l, err := s.EffectiveLimits(acct) |
| + if err != nil || l == nil { |
| + return nil |
| + } |
| + pauseAt := planMailPauseAt(l, s.cfg.PlanCatalog.Ceilings) |
| + return func(st capState) string { |
| + switch { |
| + case st.Cap == capEmail && pauseAt > 0 && st.Used >= pauseAt: |
| + return "email_paused" |
| + case st.Cap == capStorage && storageDenyDue(st, now): |
| + return "storage_denied" |
| + } |
| + return "" |
| + } |
| +} |
diff --git a/internal/console/planmail.go b/internal/console/planmail.go| new file mode 100644 |
| index 000000000..e412c812d |
| --- /dev/null |
| +++ b/internal/console/planmail.go |
| @@ -0,0 +1,116 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/mail" |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +// planMailPauseAt is the day's send count at which the account's mail is |
| +// paused (plans 4b, spec §5.6): twice the plan's daily limit, never above |
| +// the catalog's email ceiling. 0 means the plan sets no email limit. |
| +func planMailPauseAt(l *plans.Limits, ceilings plans.Limits) int64 { |
| + if l == nil || l.EmailPerDay <= 0 { |
| + return 0 |
| + } |
| + at := 2 * int64(l.EmailPerDay) |
| + if c := int64(ceilings.EmailPerDay); c > 0 && at > c { |
| + at = c |
| + } |
| + return at |
| +} |
| + |
| +// enforceAccountMail pauses every sender of the account once its sends for |
| +// the UTC day reach planMailPauseAt. The pause does not wait for notice: |
| +// email's grace ends at 2x within the day, and sending reputation is |
| +// shared by every tenant (Paul, 2026-10-25). An app sender in per-instance |
| +// mode is left alone: it cannot be resumed automatically, and pausing it |
| +// would deactivate every instance's key. |
| +func (s *Server) enforceAccountMail(ctx context.Context, acct string, now time.Time) (bool, error) { |
| + if s.cfg.PlanCatalog == nil { |
| + return false, nil |
| + } |
| + a, err := s.store.AccountBySqid(acct) |
| + if err != nil || a == nil { |
| + return false, err |
| + } |
| + l, err := s.EffectiveLimits(a) |
| + if err != nil || l == nil { |
| + return false, err |
| + } |
| + at := planMailPauseAt(l, s.cfg.PlanCatalog.Ceilings) |
| + if at == 0 { |
| + return false, nil |
| + } |
| + sent, err := s.store.AccountSends(ctx, acct, usage.DayOf(now)) |
| + if err != nil || sent < at { |
| + return false, err |
| + } |
| + apps, err := s.store.AppsIn(a.ID) |
| + if err != nil { |
| + return false, err |
| + } |
| + // Every app and sender is tried; one that fails does not hold the rest |
| + // back (Astra plans-4b finding 4). |
| + paused := false |
| + var errs []error |
| + eligible := func(cur *mail.Sender) bool { |
| + return cur.Provisioned != nil && cur.Provisioned.Active && !cur.PerInstance |
| + } |
| + for _, app := range apps { |
| + senders, err := mail.ListSenders(ctx, s.cfg.Releases, acct, app) |
| + if err != nil { |
| + errs = append(errs, fmt.Errorf("%s: %w", app, err)) |
| + continue |
| + } |
| + for _, sn := range senders { |
| + if sn.Provisioned == nil || !sn.Provisioned.Active { |
| + continue |
| + } |
| + if sn.PerInstance { |
| + log.Printf("console: plan mail %s: %s/%s is per-instance; left to its own cap", acct, app, sn.ID) |
| + continue |
| + } |
| + if _, err := mail.SetSenderPausedIf(ctx, s.claimMailStore(), s.cfg.MailProvisioner, acct, app, sn.ID, true, mail.PauseKindPlan, now, eligible); err != nil { |
| + if !errors.Is(err, mail.ErrNotEligible) { |
| + errs = append(errs, fmt.Errorf("%s/%s: %w", app, sn.ID, err)) |
| + } |
| + continue |
| + } |
| + paused = true |
| + s.audit(a, app, "ses", "mail.paused", fmt.Sprintf("%s: plan: %d of %d emails today, paused at twice the limit until the UTC day rolls", |
| + mailAuditSubject(app, sn.ID), sent, l.EmailPerDay)) |
| + } |
| + } |
| + return paused, errors.Join(errs...) |
| +} |
| + |
| +// resumePlanMail lifts plan and cap pauses from an earlier UTC day on every |
| +// sender of the account. A paused sender sends nothing, so no SES event |
| +// would ever resume it; the hourly grace pass does. |
| +func (s *Server) resumePlanMail(ctx context.Context, acct *Account, now time.Time) error { |
| + apps, err := s.store.AppsIn(acct.ID) |
| + if err != nil { |
| + return err |
| + } |
| + var errs []error |
| + for _, app := range apps { |
| + senders, err := mail.ListSenders(ctx, s.cfg.Releases, acct.Sqid, app) |
| + if err != nil { |
| + errs = append(errs, fmt.Errorf("%s: %w", app, err)) |
| + continue |
| + } |
| + for _, sn := range senders { |
| + if _, _, err := s.resumeStaleCapPause(ctx, acct.Sqid, app, sn.ID, sn, now); err != nil { |
| + errs = append(errs, fmt.Errorf("%s/%s: %w", app, sn.ID, err)) |
| + } |
| + } |
| + } |
| + return errors.Join(errs...) |
| +} |
diff --git a/internal/console/planmail_test.go b/internal/console/planmail_test.go| new file mode 100644 |
| index 000000000..9a774e97f |
| --- /dev/null |
| +++ b/internal/console/planmail_test.go |
| @@ -0,0 +1,252 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/mail" |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +var planMailNow = time.Date(2026, 8, 19, 12, 0, 0, 0, time.UTC) |
| + |
| +// addMailApp gives the ops account an app with a provisioned, active app |
| +// sender whose own daily cap (1000) is well above the plan's. |
| +func addMailApp(t *testing.T, fx *consoleFixture, app string) { |
| + t.Helper() |
| + ctx := context.Background() |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, app, "paul@keymail.dev", planMailNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := mail.Declare(ctx, fx.rel, release.OpsAccount, app, strings.ToUpper(app)+"_SMTP", "noreply@x.com", "owner@example.test", planMailNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := mail.ApplyGrant(ctx, fx.rel, release.OpsAccount, app, []string{"x.com"}, 1000, "tier:free", "tier", planMailNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec, etag, _ := mail.Get(ctx, fx.rel, release.OpsAccount, app) |
| + rec.Provisioned = &mail.Provisioned{IAMUser: "u-" + app, KeyID: "AKIA" + app, Active: true, At: planMailNow} |
| + if _, err := mail.Put(ctx, fx.rel, release.OpsAccount, app, rec, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + p := fx.srv.cfg.MailProvisioner.(*mail.MemProvisioner) |
| + p.EnsureUser(ctx, "u-"+app, mail.UserPath, []string{"arn:aws:ses:eu-west-1:1:identity/x.com"}, nil, []string{"x.com"}) |
| +} |
| + |
| +// planMailFixture: plans on (free: 50 emails a day), two mail apps. |
| +func planMailFixture(t *testing.T) *consoleFixture { |
| + t.Helper() |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.MailProvisioner = mail.NewMemProvisioner("1") |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + addMailApp(t, fx, "blog") |
| + addMailApp(t, fx, "shop") |
| + return fx |
| +} |
| + |
| +func sends(t *testing.T, fx *consoleFixture, app string, n int, day time.Time) { |
| + t.Helper() |
| + for i := 0; i < n; i++ { |
| + if err := fx.st.RecordMailEvent(context.Background(), release.OpsAccount, app, mail.SenderAppID, day.UTC().Format("2006-01-02"), mail.EventSend); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +func senderState(t *testing.T, fx *consoleFixture, app string) *mail.Provisioned { |
| + t.Helper() |
| + rec, _, err := mail.Get(context.Background(), fx.rel, release.OpsAccount, app) |
| + if err != nil || rec == nil || rec.Provisioned == nil { |
| + t.Fatalf("mail record %s: %v", app, err) |
| + } |
| + return rec.Provisioned |
| +} |
| + |
| +func TestPlanMailPauseAt(t *testing.T) { |
| + for _, c := range []struct { |
| + limit, ceiling int |
| + want int64 |
| + }{{50, 10000, 100}, {8000, 10000, 10000}, {50, 0, 100}, {0, 10000, 0}} { |
| + if got := planMailPauseAt(&plans.Limits{EmailPerDay: c.limit}, plans.Limits{EmailPerDay: c.ceiling}); got != c.want { |
| + t.Errorf("limit %d ceiling %d = %d, want %d", c.limit, c.ceiling, got, c.want) |
| + } |
| + } |
| +} |
| + |
| +func TestAccountMailPausesEverySenderAt2x(t *testing.T) { |
| + fx := planMailFixture(t) |
| + sends(t, fx, "blog", 60, planMailNow) |
| + sends(t, fx, "shop", 40, planMailNow) |
| + paused, err := fx.srv.enforceAccountMail(context.Background(), release.OpsAccount, planMailNow) |
| + if err != nil || !paused { |
| + t.Fatalf("enforceAccountMail = %v, %v, want a pause", paused, err) |
| + } |
| + for _, app := range []string{"blog", "shop"} { |
| + if p := senderState(t, fx, app); p.Active || p.PauseKind != mail.PauseKindPlan { |
| + t.Errorf("%s sender = active %v kind %q, want paused for the plan", app, p.Active, p.PauseKind) |
| + } |
| + } |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + events, _ := fx.st.Events(acct.ID, "blog", 10) |
| + found := false |
| + for _, e := range events { |
| + if e.Action == "mail.paused" && strings.Contains(e.Message+e.Detail, "100 of 50") { |
| + found = true |
| + } |
| + } |
| + if !found { |
| + t.Errorf("no mail.paused audit naming the figures: %+v", events) |
| + } |
| +} |
| + |
| +func TestAccountMailBelow2xLeavesSenders(t *testing.T) { |
| + fx := planMailFixture(t) |
| + sends(t, fx, "blog", 99, planMailNow) |
| + if paused, err := fx.srv.enforceAccountMail(context.Background(), release.OpsAccount, planMailNow); err != nil || paused { |
| + t.Fatalf("enforceAccountMail at 99 = %v, %v", paused, err) |
| + } |
| + if !senderState(t, fx, "blog").Active { |
| + t.Fatal("paused below 2x") |
| + } |
| +} |
| + |
| +func TestAccountMailWithoutACatalogUnchanged(t *testing.T) { |
| + fx := planMailFixture(t) |
| + fx.srv.cfg.PlanCatalog = nil |
| + sends(t, fx, "blog", 500, planMailNow) |
| + if paused, _ := fx.srv.enforceAccountMail(context.Background(), release.OpsAccount, planMailNow); paused { |
| + t.Fatal("paused with plans off") |
| + } |
| + if !senderState(t, fx, "shop").Active { |
| + t.Fatal("a sender paused with plans off") |
| + } |
| +} |
| + |
| +func TestAccountMailSkipsPerInstanceSenders(t *testing.T) { |
| + fx := planMailFixture(t) |
| + ctx := context.Background() |
| + sn, etag, err := mail.GetSender(ctx, fx.rel, release.OpsAccount, "shop", mail.SenderAppID) |
| + if err != nil || sn == nil { |
| + t.Fatalf("sender: %v", err) |
| + } |
| + sn.PerInstance = true |
| + if _, err := mail.PutSender(ctx, fx.rel, release.OpsAccount, "shop", sn, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + sends(t, fx, "blog", 100, planMailNow) |
| + fx.srv.enforceAccountMail(ctx, release.OpsAccount, planMailNow) |
| + if !senderState(t, fx, "shop").Active { |
| + t.Fatal("a per-instance sender was paused") |
| + } |
| + if senderState(t, fx, "blog").Active { |
| + t.Fatal("the app sender was not paused") |
| + } |
| +} |
| + |
| +func TestPlanMailPauseResumesOnDayRoll(t *testing.T) { |
| + fx := planMailFixture(t) |
| + ctx := context.Background() |
| + sends(t, fx, "blog", 100, planMailNow) |
| + fx.srv.enforceAccountMail(ctx, release.OpsAccount, planMailNow) |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + if err := fx.srv.resumePlanMail(ctx, acct, planMailNow.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if senderState(t, fx, "blog").Active { |
| + t.Fatal("resumed the same day") |
| + } |
| + if err := fx.srv.resumePlanMail(ctx, acct, planMailNow.Add(13*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !senderState(t, fx, "blog").Active || !senderState(t, fx, "shop").Active { |
| + t.Fatal("plan pause not lifted on the UTC day roll") |
| + } |
| +} |
| + |
| +func TestPlanResumeLeavesOtherPausesAlone(t *testing.T) { |
| + fx := planMailFixture(t) |
| + ctx := context.Background() |
| + if _, err := mail.SetSenderPaused(ctx, fx.rel, fx.srv.cfg.MailProvisioner, release.OpsAccount, "blog", mail.SenderAppID, true, mail.PauseKindRate, planMailNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := mail.SetSenderPaused(ctx, fx.rel, fx.srv.cfg.MailProvisioner, release.OpsAccount, "shop", mail.SenderAppID, true, "", planMailNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + if err := fx.srv.resumePlanMail(ctx, acct, planMailNow.Add(48*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if senderState(t, fx, "blog").Active || senderState(t, fx, "shop").Active { |
| + t.Fatal("a rate or manual pause was lifted by the plan resume") |
| + } |
| +} |
| + |
| +// The SES event path runs the account check: one sender's event pauses |
| +// every sender of the account. |
| +func TestSESEventTriggersAccountPause(t *testing.T) { |
| + fx := planMailFixture(t) |
| + now := time.Now().UTC() |
| + sends(t, fx, "blog", 100, now) |
| + if _, _, err := fx.srv.enforceMailLimits(context.Background(), release.OpsAccount, "blog", mail.SenderAppID, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if senderState(t, fx, "shop").Active { |
| + t.Fatal("an SES event at 2x left a sibling sender sending") |
| + } |
| +} |
| + |
| +// Finding 2, resume side: a stale snapshot saying "plan pause from |
| +// yesterday" must not lift what is now a manual pause. |
| +func TestPlanResumeRereadsTheSender(t *testing.T) { |
| + fx := planMailFixture(t) |
| + ctx := context.Background() |
| + if _, err := mail.SetSenderPaused(ctx, fx.rel, fx.srv.cfg.MailProvisioner, release.OpsAccount, "blog", mail.SenderAppID, true, mail.PauseKindPlan, planMailNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + stale, _, _ := mail.GetSender(ctx, fx.rel, release.OpsAccount, "blog", mail.SenderAppID) |
| + if _, err := mail.SetSenderPaused(ctx, fx.rel, fx.srv.cfg.MailProvisioner, release.OpsAccount, "blog", mail.SenderAppID, true, "", planMailNow.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, _, err := fx.srv.resumeStaleCapPause(ctx, release.OpsAccount, "blog", mail.SenderAppID, stale, planMailNow.Add(48*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if senderState(t, fx, "blog").Active { |
| + t.Fatal("a manual pause was lifted from a stale plan-pause snapshot") |
| + } |
| +} |
| + |
| +// Finding 3: a delayed event for yesterday must not pause today. |
| +func TestDelayedSESEventDoesNotRepause(t *testing.T) { |
| + fx := planMailFixture(t) |
| + yesterday := time.Now().UTC().AddDate(0, 0, -1) |
| + sends(t, fx, "blog", 100, yesterday) |
| + if _, _, err := fx.srv.enforceMailLimits(context.Background(), release.OpsAccount, "blog", mail.SenderAppID, yesterday); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !senderState(t, fx, "shop").Active { |
| + t.Fatal("yesterday's late event paused the account today") |
| + } |
| +} |
| + |
| +// Finding 4: one unreadable app does not stop the rest of the account. |
| +func TestAccountMailContinuesPastABrokenApp(t *testing.T) { |
| + fx := planMailFixture(t) |
| + ctx := context.Background() |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "aaa", "paul@keymail.dev", planMailNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.rel.Put(ctx, mail.SenderKey(release.OpsAccount, "aaa", mail.SenderAppID), []byte("{broken"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + now := time.Now().UTC() |
| + sends(t, fx, "blog", 100, now) |
| + if _, err := fx.srv.enforceAccountMail(ctx, release.OpsAccount, now); err == nil { |
| + t.Error("the broken app's error was swallowed") |
| + } |
| + if senderState(t, fx, "shop").Active || senderState(t, fx, "blog").Active { |
| + t.Fatal("an unreadable app stopped the others pausing") |
| + } |
| +} |
diff --git a/internal/console/planstorage.go b/internal/console/planstorage.go| new file mode 100644 |
| index 000000000..81ca30891 |
| --- /dev/null |
| +++ b/internal/console/planstorage.go |
| @@ -0,0 +1,118 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/objstore" |
| +) |
| + |
| +// storageDenyDue is whether the account's stores should refuse new uploads |
| +// (plans 4b, spec §5.5): past grace with notice received, or at twice the |
| +// cap, the table's hard ceiling, which does not wait for notice (Paul, |
| +// 2026-10-25). |
| +func storageDenyDue(st capState, now time.Time) bool { |
| + return afterGraceDue(st, now) || (st.Level.over() && st.Limit > 0 && st.Used >= 2*st.Limit) |
| +} |
| + |
| +// convergeStorageDeny brings every provisioned store of the account in line |
| +// with storageDenyDue: it marks or clears each record's WritesDenied and |
| +// re-runs the grant, which rewrites the policy (the regrantForScanning |
| +// precedent). An unmeasured storage cap changes nothing: unknown is not |
| +// over, and not under either. |
| +func (s *Server) convergeStorageDeny(ctx context.Context, acct *Account, st capState, measured bool, now time.Time) error { |
| + if !measured { |
| + return nil |
| + } |
| + return s.convergeStores(ctx, acct, storageDenyDue(st, now), st, now) |
| +} |
| + |
| +// clearStorageDeny lifts the deny from every store of an account whose |
| +// plan no longer limits storage (Astra plans-4b finding 5): with no cap |
| +// there is nothing to be over. |
| +func (s *Server) clearStorageDeny(ctx context.Context, acct *Account, now time.Time) error { |
| + return s.convergeStores(ctx, acct, false, capState{}, now) |
| +} |
| + |
| +// convergeStores applies want to every provisioned store of the account. |
| +// Each store is tried; one that fails does not hold the others back |
| +// (Astra plans-4b finding 4). |
| +func (s *Server) convergeStores(ctx context.Context, acct *Account, want bool, st capState, now time.Time) error { |
| + if s.cfg.PlanCatalog == nil || s.cfg.StoreProvisioner == nil { |
| + return nil |
| + } |
| + apps, err := s.store.AppsIn(acct.ID) |
| + if err != nil { |
| + return err |
| + } |
| + var errs []error |
| + for _, app := range apps { |
| + envs, err := objstore.StoreEnvironments(ctx, s.cfg.Releases, acct.Sqid, app) |
| + if err != nil { |
| + errs = append(errs, fmt.Errorf("%s: %w", app, err)) |
| + continue |
| + } |
| + for _, env := range append([]string{""}, envs...) { |
| + if err := s.convergeStoreDeny(ctx, acct, app, env, st, want, now); err != nil { |
| + errs = append(errs, fmt.Errorf("%s/%s: %w", app, env, err)) |
| + } |
| + } |
| + } |
| + return errors.Join(errs...) |
| +} |
| + |
| +// convergeStoreDeny brings one store to want: the record's WritesDenied |
| +// first, then the policy through the grant, then WritesDenyApplied once |
| +// the grant succeeded. A store whose grant failed is retried on the next |
| +// pass, because WritesDenyApplied still disagrees. |
| +func (s *Server) convergeStoreDeny(ctx context.Context, acct *Account, app, env string, st capState, want bool, now time.Time) error { |
| + rec, _, err := objstore.GetIn(ctx, s.cfg.Releases, acct.Sqid, app, env) |
| + if err != nil { |
| + return err |
| + } |
| + if rec == nil || rec.Provisioned == nil { |
| + return nil |
| + } |
| + have := rec.WritesDenied != nil |
| + applied := rec.WritesDenyApplied != nil && *rec.WritesDenyApplied |
| + if have == want && applied == want { |
| + return nil |
| + } |
| + pub, err := appconfig.ParsePublicKey(s.cfg.SecretsPub, "CARLOS_SECRETS_PUBKEY") |
| + if err != nil { |
| + log.Printf("console: plan storage %s: no secrets key, store policies left as they are: %v", acct.Sqid, err) |
| + return nil |
| + } |
| + action, detail := "store.writes_allowed", fmt.Sprintf("plan storage: %d of %d bytes; new uploads allowed again", st.Used, st.Limit) |
| + if want { |
| + action, detail = "store.writes_denied", fmt.Sprintf("plan storage: %d of %d bytes; new uploads refused, downloads and deletes still work", st.Used, st.Limit) |
| + } |
| + if have != want { |
| + var wd *objstore.WritesDenied |
| + if want { |
| + wd = &objstore.WritesDenied{Reason: fmt.Sprintf("plan storage: %d of %d bytes", st.Used, st.Limit), At: now} |
| + } |
| + if _, err := objstore.SetWritesDenied(ctx, s.cfg.Releases, acct.Sqid, app, env, wd); err != nil { |
| + return err |
| + } |
| + } |
| + source := objstore.GrantSourceOperator |
| + if rec.Grant != nil && rec.Grant.Source != "" { |
| + source = rec.Grant.Source |
| + } |
| + if _, err := claimAppCall(s, ctx, acct, app, "plan-storage-regrant", func(ctx context.Context) (*objstore.Record, error) { |
| + return objstore.GrantIn(ctx, s.cfg.Releases, s.cfg.StoreProvisioner, s.cfg.StoreDeployment, |
| + pub, acct.Sqid, app, env, "plan", source, "", now) |
| + }); err != nil { |
| + return err |
| + } |
| + if _, err := objstore.SetWritesDenyApplied(ctx, s.cfg.Releases, acct.Sqid, app, env, want); err != nil { |
| + return err |
| + } |
| + s.audit(acct, app, "plan", action, detail) |
| + return nil |
| +} |
diff --git a/internal/console/planstorage_test.go b/internal/console/planstorage_test.go| new file mode 100644 |
| index 000000000..313098b86 |
| --- /dev/null |
| +++ b/internal/console/planstorage_test.go |
| @@ -0,0 +1,203 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/objstore" |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// deniedStoreFixture: plans on, titogo's own store granted on a fake |
| +// provisioner. |
| +func deniedStoreFixture(t *testing.T, code string) (*consoleFixture, *objstore.MemProvisioner, *Account) { |
| + t.Helper() |
| + fx, fake, token, _ := storeArmed(t, code) |
| + grantStore(t, fx, token) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + return fx, fake, acct |
| +} |
| + |
| +func storageRow(acct *Account, used, limit int64, firstOver time.Time) capState { |
| + st := evaluateCap(nil, capStorage, used, limit, firstOver) |
| + st.AccountID = acct.ID |
| + return st |
| +} |
| + |
| +func titogoStore(t *testing.T, fx *consoleFixture) *objstore.Record { |
| + t.Helper() |
| + rec, _, err := objstore.Get(context.Background(), fx.rel, release.OpsAccount, "titogo") |
| + if err != nil || rec == nil { |
| + t.Fatalf("titogo store: %+v, %v", rec, err) |
| + } |
| + return rec |
| +} |
| + |
| +func hasWriteDeny(t *testing.T, policy string) bool { |
| + t.Helper() |
| + var doc struct { |
| + Statement []struct { |
| + Effect string |
| + Action []string |
| + Condition map[string]any |
| + } |
| + } |
| + if err := json.Unmarshal([]byte(policy), &doc); err != nil { |
| + t.Fatalf("policy: %v\n%s", err, policy) |
| + } |
| + for _, st := range doc.Statement { |
| + if st.Effect == "Deny" && len(st.Action) == 1 && st.Action[0] == "s3:PutObject" && st.Condition == nil { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func TestStorageDenyDue(t *testing.T) { |
| + acct := &Account{ID: 1} |
| + st := storageRow(acct, 150, 100, planNow) |
| + if storageDenyDue(st, planNow.Add(time.Hour)) { |
| + t.Error("due in grace") |
| + } |
| + st.NoticeAt = planNow |
| + if !storageDenyDue(st, planNow.Add(7*24*time.Hour)) { |
| + t.Error("not due with grace over and notice 7 days old") |
| + } |
| + ceiling := storageRow(acct, 200, 100, planNow) |
| + if !storageDenyDue(ceiling, planNow.Add(time.Minute)) { |
| + t.Error("not due at twice the cap") |
| + } |
| +} |
| + |
| +func TestStorageDenySetAfterGrace(t *testing.T) { |
| + fx, fake, acct := deniedStoreFixture(t, "code-plan-store-deny") |
| + st := storageRow(acct, 2_000_000_000, 1_500_000_000, planNow.Add(-10*24*time.Hour)) |
| + st.NoticeAt = planNow.Add(-9 * 24 * time.Hour) |
| + if err := fx.srv.convergeStorageDeny(context.Background(), acct, st, true, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := titogoStore(t, fx) |
| + if rec.WritesDenied == nil { |
| + t.Fatal("record not marked") |
| + } |
| + if !hasWriteDeny(t, fake.PolicyFor(rec.Provisioned.IAMUser)) { |
| + t.Fatalf("policy has no write deny:\n%s", fake.PolicyFor(rec.Provisioned.IAMUser)) |
| + } |
| + events, _ := fx.st.Events(acct.ID, "titogo", 10) |
| + found := false |
| + for _, e := range events { |
| + found = found || e.Action == "store.writes_denied" |
| + } |
| + if !found { |
| + t.Errorf("no store.writes_denied audit: %+v", events) |
| + } |
| +} |
| + |
| +func TestStorageDenyClearsWhenBackUnder(t *testing.T) { |
| + fx, fake, acct := deniedStoreFixture(t, "code-plan-store-clear") |
| + st := storageRow(acct, 3_000_000_000, 1_000_000_000, planNow) |
| + if err := fx.srv.convergeStorageDeny(context.Background(), acct, st, true, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + under := storageRow(acct, 500_000_000, 1_000_000_000, planNow) |
| + if err := fx.srv.convergeStorageDeny(context.Background(), acct, under, true, planNow.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := titogoStore(t, fx) |
| + if rec.WritesDenied != nil || hasWriteDeny(t, fake.PolicyFor(rec.Provisioned.IAMUser)) { |
| + t.Fatal("deny not lifted when usage fell under the cap") |
| + } |
| + events, _ := fx.st.Events(acct.ID, "titogo", 10) |
| + found := false |
| + for _, e := range events { |
| + found = found || e.Action == "store.writes_allowed" |
| + } |
| + if !found { |
| + t.Errorf("no store.writes_allowed audit") |
| + } |
| +} |
| + |
| +func TestStorageDenyUnchangedWhenUnmeasured(t *testing.T) { |
| + fx, _, acct := deniedStoreFixture(t, "code-plan-store-unknown") |
| + if err := fx.srv.convergeStorageDeny(context.Background(), acct, storageRow(acct, 3_000_000_000, 1_000_000_000, planNow), true, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.srv.convergeStorageDeny(context.Background(), acct, capState{}, false, planNow.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if titogoStore(t, fx).WritesDenied == nil { |
| + t.Fatal("an unmeasured pass cleared the deny") |
| + } |
| +} |
| + |
| +func TestStorageDenyWithoutACatalogUnchanged(t *testing.T) { |
| + fx, _, acct := deniedStoreFixture(t, "code-plan-store-off") |
| + fx.srv.cfg.PlanCatalog = nil |
| + if err := fx.srv.convergeStorageDeny(context.Background(), acct, storageRow(acct, 3_000_000_000, 1_000_000_000, planNow), true, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if titogoStore(t, fx).WritesDenied != nil { |
| + t.Fatal("denied with plans off") |
| + } |
| +} |
| + |
| +// failingStore fails EnsureUser while fail is set. |
| +type failingStore struct { |
| + *objstore.MemProvisioner |
| + fail bool |
| +} |
| + |
| +func (f *failingStore) EnsureUser(ctx context.Context, name, path, bucketARN string, deny *objstore.DenyTag, denyWrites bool) (string, error) { |
| + if f.fail { |
| + return "", errors.New("iam down") |
| + } |
| + return f.MemProvisioner.EnsureUser(ctx, name, path, bucketARN, deny, denyWrites) |
| +} |
| + |
| +// Finding 1: a regrant that failed is retried on the next pass. |
| +func TestStorageDenyRetriesAFailedRegrant(t *testing.T) { |
| + fx, fake, acct := deniedStoreFixture(t, "code-plan-store-retry") |
| + flaky := &failingStore{MemProvisioner: fake, fail: true} |
| + fx.srv.cfg.StoreProvisioner = flaky |
| + st := storageRow(acct, 3_000_000_000, 1_000_000_000, planNow) |
| + if err := fx.srv.convergeStorageDeny(context.Background(), acct, st, true, planNow); err == nil { |
| + t.Fatal("a failed regrant reported success") |
| + } |
| + flaky.fail = false |
| + if err := fx.srv.convergeStorageDeny(context.Background(), acct, st, true, planNow.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := titogoStore(t, fx) |
| + if !hasWriteDeny(t, fake.PolicyFor(rec.Provisioned.IAMUser)) { |
| + t.Fatal("the deny never reached the policy after the regrant failed once") |
| + } |
| +} |
| + |
| +// Finding 5: a plan without a storage limit lifts an existing deny. |
| +func TestStorageDenyClearedWhenLimitRemoved(t *testing.T) { |
| + fx, fake, acct := deniedStoreFixture(t, "code-plan-store-nolimit") |
| + if err := fx.srv.convergeStorageDeny(context.Background(), acct, storageRow(acct, 3_000_000_000, 1_000_000_000, planNow), true, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + b, err := os.ReadFile(exampleCatalogPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c, err := plans.ParseCatalog([]byte(strings.Replace(string(b), `"storage_bytes": 1073741824,`, `"storage_bytes": 0,`, 1))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.srv.cfg.PlanCatalog = c |
| + fx.srv.planGracePass(context.Background(), planNow.Add(time.Hour)) |
| + rec := titogoStore(t, fx) |
| + if rec.WritesDenied != nil || hasWriteDeny(t, fake.PolicyFor(rec.Provisioned.IAMUser)) { |
| + t.Fatal("removing the storage limit left the deny in place") |
| + } |
| +} |
diff --git a/internal/mail/mail.go b/internal/mail/mail.go| index b3919b835..b2453833e 100644 |
| --- a/internal/mail/mail.go |
| +++ b/internal/mail/mail.go |
| @@ -83,6 +83,9 @@ type Provisioned struct { |
| const ( |
| PauseKindCap = "cap" |
| PauseKindRate = "rate" |
| + // PauseKindPlan is the account-wide pause at twice the plan's daily |
| + // email limit (plans 4b). Like a cap pause it lifts on the UTC day roll. |
| + PauseKindPlan = "plan" |
| ) |
| // Standalone is a displayed credential for something not running on CARLOS. |
diff --git a/internal/mail/pauseif_test.go b/internal/mail/pauseif_test.go| new file mode 100644 |
| index 000000000..43c7be896 |
| --- /dev/null |
| +++ b/internal/mail/pauseif_test.go |
| @@ -0,0 +1,40 @@ |
| +package mail |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// Astra plans-4b finding 2: the eligibility check runs on the sender as |
| +// reread inside the mutation, so a pause taken meanwhile is never replaced. |
| +func TestSetSenderPausedIfChecksTheRereadSender(t *testing.T) { |
| + ctx := context.Background() |
| + s := release.NewDirStore(t.TempDir()) |
| + p := NewMemProvisioner("1") |
| + now := time.Date(2026, 8, 19, 12, 0, 0, 0, time.UTC) |
| + if _, err := Declare(ctx, s, "bab", "blog", "BLOG_SMTP", "noreply@x.com", "o@example.test", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec, etag, _ := Get(ctx, s, "bab", "blog") |
| + rec.Provisioned = &Provisioned{IAMUser: "u", KeyID: "K1", Active: true, At: now} |
| + if _, err := Put(ctx, s, "bab", "blog", rec, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + p.EnsureUser(ctx, "u", UserPath, []string{"arn:aws:ses:eu-west-1:1:identity/x.com"}, nil, []string{"x.com"}) |
| + // An operator's rate pause lands after the caller's listing said active. |
| + if _, err := SetSenderPaused(ctx, s, p, "bab", "blog", SenderAppID, true, PauseKindRate, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + active := func(sn *Sender) bool { return sn.Provisioned != nil && sn.Provisioned.Active } |
| + if _, err := SetSenderPausedIf(ctx, s, p, "bab", "blog", SenderAppID, true, PauseKindPlan, now, active); !errors.Is(err, ErrNotEligible) { |
| + t.Fatalf("pause of a sender no longer active = %v, want ErrNotEligible", err) |
| + } |
| + sn, _, _ := GetSender(ctx, s, "bab", "blog", SenderAppID) |
| + if sn.Provisioned.PauseKind != PauseKindRate { |
| + t.Fatalf("pause kind = %q, want the rate pause kept", sn.Provisioned.PauseKind) |
| + } |
| +} |
diff --git a/internal/mail/walk.go b/internal/mail/walk.go| index 7c23692b6..679f91c65 100644 |
| --- a/internal/mail/walk.go |
| +++ b/internal/mail/walk.go |
| @@ -1118,7 +1118,7 @@ func claimUnserializedSetPaused(ctx context.Context, s release.Store, p Provisio |
| // hold this credential, and re-arming it is exactly what per-instance mode |
| // exists to prevent. A pause is always allowed. |
| func claimUnserializedSetSenderPaused(ctx context.Context, s release.Store, p Provisioner, |
| - acct, app, sender string, paused bool, kind string, now time.Time) (*Sender, error) { |
| + acct, app, sender string, paused bool, kind string, now time.Time, eligible func(*Sender) bool) (*Sender, error) { |
| sn, etag, err := GetSender(ctx, s, acct, app, sender) |
| if err != nil { |
| @@ -1127,6 +1127,13 @@ func claimUnserializedSetSenderPaused(ctx context.Context, s release.Store, p Pr |
| if sn == nil || sn.Provisioned == nil { |
| return nil, ErrNotProvisioned |
| } |
| + // The caller's condition is asked of the sender as read HERE, inside |
| + // the mutation, not of an earlier listing: a pause taken in between |
| + // must never be overwritten by an automatic one (Astra plans-4b |
| + // finding 2). The PutSender below is conditional on this read. |
| + if eligible != nil && !eligible(sn) { |
| + return nil, ErrNotEligible |
| + } |
| if !paused && sn.PerInstance { |
| return nil, fmt.Errorf("mail: %s/%s: resume its instance senders instead: %w", acct, app, ErrPerInstance) |
| } |
| @@ -2005,8 +2012,22 @@ func SetPaused(ctx context.Context, s release.Store, p Provisioner, |
| func SetSenderPaused(ctx context.Context, s release.Store, p Provisioner, |
| acct, app, sender string, paused bool, kind string, now time.Time) (*Sender, error) { |
| + return SetSenderPausedIf(ctx, s, p, acct, app, sender, paused, kind, now, nil) |
| +} |
| + |
| +// ErrNotEligible is SetSenderPausedIf's answer when the sender, as read |
| +// inside the mutation, no longer meets the caller's condition. Nothing was |
| +// changed. |
| +var ErrNotEligible = errors.New("mail: sender no longer eligible for this change") |
| + |
| +// SetSenderPausedIf is SetSenderPaused that first asks eligible of the |
| +// sender as read inside the mutation (nil: always). Automatic pauses and |
| +// resumes use it so that their decision rests on current state, not on a |
| +// listing taken earlier. |
| +func SetSenderPausedIf(ctx context.Context, s release.Store, p Provisioner, |
| + acct, app, sender string, paused bool, kind string, now time.Time, eligible func(*Sender) bool) (*Sender, error) { |
| if _, enabled := s.(ClaimMailStore); !enabled { |
| - return claimUnserializedSetSenderPaused(ctx, s, p, acct, app, sender, paused, kind, now) |
| + return claimUnserializedSetSenderPaused(ctx, s, p, acct, app, sender, paused, kind, now, eligible) |
| } |
| var claimResult0 *Sender |
| claimErr := WithClaimMailResource(ctx, s, func(ctx context.Context) error { |
| @@ -2015,7 +2036,7 @@ func SetSenderPaused(ctx context.Context, s release.Store, p Provisioner, |
| p = claimMarkedProvisioner{raw: p} |
| } |
| var err error |
| - claimResult0, err = claimUnserializedSetSenderPaused(ctx, s, p, acct, app, sender, paused, kind, now) |
| + claimResult0, err = claimUnserializedSetSenderPaused(ctx, s, p, acct, app, sender, paused, kind, now, eligible) |
| return err |
| }) |
| }) |
diff --git a/internal/objstore/aws.go b/internal/objstore/aws.go| index fc765c665..bd46ea76e 100644 |
| --- a/internal/objstore/aws.go |
| +++ b/internal/objstore/aws.go |
| @@ -177,7 +177,7 @@ type policyDocument struct { |
| // stay readable. That is the right trade when the goal is evidence rather |
| // than enforcement, but anyone quoting it in a compliance answer needs to |
| // know which of the two they have. |
| -func storePolicyJSON(bucketARN string, deny *DenyTag) string { |
| +func storePolicyJSON(bucketARN string, deny *DenyTag, denyWrites bool) string { |
| doc := policyDocument{ |
| Version: "2012-10-17", |
| Statement: []policyStatement{ |
| @@ -223,6 +223,16 @@ func storePolicyJSON(bucketARN string, deny *DenyTag) string { |
| }, |
| }) |
| } |
| + if denyWrites { |
| + // Plans 4b: a store past its plan's storage grace refuses new |
| + // uploads. Unconditional, and on PutObject only: reads, lists and |
| + // deletes stay allowed so the customer can clean up. |
| + doc.Statement = append(doc.Statement, policyStatement{ |
| + Effect: "Deny", |
| + Action: []string{"s3:PutObject"}, |
| + Resource: bucketARN + "/*", |
| + }) |
| + } |
| b, err := json.Marshal(doc) |
| if err != nil { |
| // doc is a static struct of strings/string-slices; Marshal cannot fail. |
| @@ -388,7 +398,7 @@ func (p *awsProvisioner) DeleteBucket(ctx context.Context, name string) error { |
| // An empty boundary is legal here only because MemProvisioner and the |
| // contract tests construct provisioners with no IAM at all. Every real |
| // console refuses to boot without one (cmd/console/main.go, storeBackend). |
| -func (p *awsProvisioner) EnsureUser(ctx context.Context, name, path, bucketARN string, deny *DenyTag) (string, error) { |
| +func (p *awsProvisioner) EnsureUser(ctx context.Context, name, path, bucketARN string, deny *DenyTag, denyWrites bool) (string, error) { |
| var arn string |
| in := &iam.CreateUserInput{ |
| UserName: aws.String(name), |
| @@ -415,7 +425,7 @@ func (p *awsProvisioner) EnsureUser(ctx context.Context, name, path, bucketARN s |
| _, err = p.iam.PutUserPolicy(ctx, &iam.PutUserPolicyInput{ |
| UserName: aws.String(name), |
| PolicyName: aws.String(policyName), |
| - PolicyDocument: aws.String(storePolicyJSON(bucketARN, deny)), |
| + PolicyDocument: aws.String(storePolicyJSON(bucketARN, deny, denyWrites)), |
| }) |
| if err != nil { |
| return "", fmt.Errorf("objstore: put policy for user %q: %w", name, err) |
diff --git a/internal/objstore/aws_test.go b/internal/objstore/aws_test.go| index 3ccc4d63e..073c835f9 100644 |
| --- a/internal/objstore/aws_test.go |
| +++ b/internal/objstore/aws_test.go |
| @@ -479,7 +479,7 @@ func TestEnsureUserAlreadyExists(t *testing.T) { |
| return &iam.PutUserPolicyOutput{}, nil |
| }, |
| }} |
| - arn, err := p.EnsureUser(context.Background(), "u1", UserPath, "arn:aws:s3:::b1", nil) |
| + arn, err := p.EnsureUser(context.Background(), "u1", UserPath, "arn:aws:s3:::b1", nil, false) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -512,7 +512,7 @@ func TestEnsureUserFresh(t *testing.T) { |
| return &iam.PutUserPolicyOutput{}, nil |
| }, |
| }} |
| - arn, err := p.EnsureUser(context.Background(), "u1", UserPath, "arn:aws:s3:::b1", nil) |
| + arn, err := p.EnsureUser(context.Background(), "u1", UserPath, "arn:aws:s3:::b1", nil, false) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -607,7 +607,7 @@ func TestEnsureUserStampsThePermissionsBoundary(t *testing.T) { |
| }, |
| } |
| p := &awsProvisioner{iam: iamStub, region: "eu-west-1", boundary: boundary} |
| - if _, err := p.EnsureUser(context.Background(), "carlos-store-bab-titogo", UserPath, "arn:aws:s3:::carlos-bab-titogo", nil); err != nil { |
| + if _, err := p.EnsureUser(context.Background(), "carlos-store-bab-titogo", UserPath, "arn:aws:s3:::carlos-bab-titogo", nil, false); err != nil { |
| t.Fatalf("EnsureUser: %v", err) |
| } |
| if seen == nil { |
| @@ -634,7 +634,7 @@ func TestEnsureUserOmitsAnEmptyBoundary(t *testing.T) { |
| }, |
| } |
| p := &awsProvisioner{iam: iamStub, region: "eu-west-1"} |
| - if _, err := p.EnsureUser(context.Background(), "u", UserPath, "arn:aws:s3:::b", nil); err != nil { |
| + if _, err := p.EnsureUser(context.Background(), "u", UserPath, "arn:aws:s3:::b", nil, false); err != nil { |
| t.Fatalf("EnsureUser: %v", err) |
| } |
| if sent { |
diff --git a/internal/objstore/enforce_test.go b/internal/objstore/enforce_test.go| index a8a810682..68f7e85a6 100644 |
| --- a/internal/objstore/enforce_test.go |
| +++ b/internal/objstore/enforce_test.go |
| @@ -18,7 +18,7 @@ import ( |
| // object, which changes the bytes by definition. Every store's policy is |
| // rewritten once on its next grant re-walk, deliberately. |
| func TestStorePolicyJSONShapeWithoutDeny(t *testing.T) { |
| - doc := storePolicyJSON("arn:aws:s3:::b", nil) |
| + doc := storePolicyJSON("arn:aws:s3:::b", nil, false) |
| var parsed policyDocument |
| if err := json.Unmarshal([]byte(doc), &parsed); err != nil { |
| @@ -46,7 +46,7 @@ func TestStorePolicyJSONShapeWithoutDeny(t *testing.T) { |
| // tag. |
| func TestStorePolicyJSONWithDeny(t *testing.T) { |
| doc := storePolicyJSON("arn:aws:s3:::b", |
| - &DenyTag{Key: TagVerdict, Value: string(VerdictInfected)}) |
| + &DenyTag{Key: TagVerdict, Value: string(VerdictInfected)}, false) |
| var parsed policyDocument |
| if err := json.Unmarshal([]byte(doc), &parsed); err != nil { |
| @@ -120,7 +120,7 @@ func TestMemProvisionerRewritesPolicyForExistingUser(t *testing.T) { |
| ctx := context.Background() |
| p := NewMemProvisioner("eu-west-1") |
| - if _, err := p.EnsureUser(ctx, "u", UserPath, "arn:aws:s3:::b", nil); err != nil { |
| + if _, err := p.EnsureUser(ctx, "u", UserPath, "arn:aws:s3:::b", nil, false); err != nil { |
| t.Fatal(err) |
| } |
| // The ENFORCEMENT deny, specifically: the anti-forgery Denys are in every |
| @@ -129,7 +129,7 @@ func TestMemProvisionerRewritesPolicyForExistingUser(t *testing.T) { |
| t.Fatal("no enforcement deny was asked for") |
| } |
| if _, err := p.EnsureUser(ctx, "u", UserPath, "arn:aws:s3:::b", |
| - &DenyTag{Key: TagVerdict, Value: string(VerdictInfected)}); err != nil { |
| + &DenyTag{Key: TagVerdict, Value: string(VerdictInfected)}, false); err != nil { |
| t.Fatal(err) |
| } |
| if !strings.Contains(p.PolicyFor("u"), "s3:ExistingObjectTag") { |
diff --git a/internal/objstore/memprovisioner.go b/internal/objstore/memprovisioner.go| index 8b393d06c..233e3b18a 100644 |
| --- a/internal/objstore/memprovisioner.go |
| +++ b/internal/objstore/memprovisioner.go |
| @@ -76,13 +76,13 @@ func (p *MemProvisioner) EnsureBucket(ctx context.Context, name string) (string, |
| return p.region, nil |
| } |
| -func (p *MemProvisioner) EnsureUser(ctx context.Context, name, path, bucketARN string, deny *DenyTag) (string, error) { |
| +func (p *MemProvisioner) EnsureUser(ctx context.Context, name, path, bucketARN string, deny *DenyTag, denyWrites bool) (string, error) { |
| p.mu.Lock() |
| defer p.mu.Unlock() |
| if err := p.takeFailure("EnsureUser"); err != nil { |
| return "", err |
| } |
| - policy := storePolicyJSON(bucketARN, deny) |
| + policy := storePolicyJSON(bucketARN, deny, denyWrites) |
| if u, ok := p.Users[name]; ok { |
| // The policy is rewritten for an existing principal too, mirroring |
| // PutUserPolicy running unconditionally on both of awsProvisioner's |
diff --git a/internal/objstore/memprovisioner_test.go b/internal/objstore/memprovisioner_test.go| index 2e5b1d1a6..056dafac8 100644 |
| --- a/internal/objstore/memprovisioner_test.go |
| +++ b/internal/objstore/memprovisioner_test.go |
| @@ -13,7 +13,7 @@ func TestMemProvisionerIdempotence(t *testing.T) { |
| if region, err := p.EnsureBucket(ctx, "b1"); err != nil || region != "eu-west-1" { |
| t.Fatalf("EnsureBucket #%d: %q %v", i, region, err) |
| } |
| - if arn, err := p.EnsureUser(ctx, "u1", "/carlos-store/", "arn:aws:s3:::b1", nil); err != nil || arn == "" { |
| + if arn, err := p.EnsureUser(ctx, "u1", "/carlos-store/", "arn:aws:s3:::b1", nil, false); err != nil || arn == "" { |
| t.Fatalf("EnsureUser #%d: %v", i, err) |
| } |
| } |
diff --git a/internal/objstore/objstore.go b/internal/objstore/objstore.go| index ee4571960..8126cf90d 100644 |
| --- a/internal/objstore/objstore.go |
| +++ b/internal/objstore/objstore.go |
| @@ -153,6 +153,21 @@ type Record struct { |
| Grant *GrantBlock `json:"grant,omitempty"` |
| Provisioned *Provisioned `json:"provisioned,omitempty"` |
| Scanning *ScanBlock `json:"scanning,omitempty"` |
| + // WritesDenied, when set, makes the store's policy refuse new uploads |
| + // (plans 4b): the account is past its plan's storage grace. The grant |
| + // walk reads it on every run, as it reads Scanning.Enforce. |
| + WritesDenied *WritesDenied `json:"writes_denied,omitempty"` |
| + // WritesDenyApplied is what the last successful grant wrote into the |
| + // policy for WritesDenied (nil: never written, the same as false). It |
| + // lets a regrant that failed after the record changed be retried |
| + // (Astra plans-4b finding 1). |
| + WritesDenyApplied *bool `json:"writes_deny_applied,omitempty"` |
| +} |
| + |
| +// WritesDenied says why a store refuses uploads, and since when. |
| +type WritesDenied struct { |
| + Reason string `json:"reason"` |
| + At time.Time `json:"at"` |
| } |
| // Key is the app's own store — KeyIn(acct, app, "") by another name, kept |
diff --git a/internal/objstore/provisioner.go b/internal/objstore/provisioner.go| index d96d02272..d5b0b8da5 100644 |
| --- a/internal/objstore/provisioner.go |
| +++ b/internal/objstore/provisioner.go |
| @@ -18,7 +18,9 @@ type Provisioner interface { |
| // It is threaded from the RECORD rather than asked of a Scanner, so a |
| // repair walk on a deployment with no engine built can still write the |
| // policy the record asks for instead of silently dropping enforcement. |
| - EnsureUser(ctx context.Context, name, path, bucketARN string, deny *DenyTag) (arn string, err error) |
| + // denyWrites adds an unconditional Deny on s3:PutObject (plans 4b: a |
| + // store past its plan's storage grace), threaded from the record. |
| + EnsureUser(ctx context.Context, name, path, bucketARN string, deny *DenyTag, denyWrites bool) (arn string, err error) |
| MintKey(ctx context.Context, user string) (id, secret string, err error) |
| DeleteKey(ctx context.Context, user, id string) error |
| // ReapKeys deletes every access key of user NOT named in keep. The grant |
diff --git a/internal/objstore/walk.go b/internal/objstore/walk.go| index 15e8619c5..801fde0fb 100644 |
| --- a/internal/objstore/walk.go |
| +++ b/internal/objstore/walk.go |
| @@ -294,7 +294,7 @@ func claimRawGrantIn(ctx context.Context, s release.Store, p Provisioner, d Depl |
| if rec.Scanning != nil { |
| deny = rec.Scanning.Enforce |
| } |
| - arn, err := p.EnsureUser(ctx, user, UserPath, "arn:aws:s3:::"+bucket, deny) |
| + arn, err := p.EnsureUser(ctx, user, UserPath, "arn:aws:s3:::"+bucket, deny, rec.WritesDenied != nil) |
| if err != nil { |
| return nil, fmt.Errorf("objstore: ensure user %s: %w", user, err) |
| } |
diff --git a/internal/objstore/walk_test.go b/internal/objstore/walk_test.go| index 028edb304..ae143283c 100644 |
| --- a/internal/objstore/walk_test.go |
| +++ b/internal/objstore/walk_test.go |
| @@ -1154,7 +1154,7 @@ func TestTeardownConfigObjectAbsent(t *testing.T) { |
| if _, err := p.EnsureBucket(ctx, "carlos-store-tito-bab-titogo"); err != nil { |
| t.Fatal(err) |
| } |
| - arn, err := p.EnsureUser(ctx, "carlos-store-bab-titogo", UserPath, "arn:aws:s3:::carlos-store-tito-bab-titogo", nil) |
| + arn, err := p.EnsureUser(ctx, "carlos-store-bab-titogo", UserPath, "arn:aws:s3:::carlos-store-tito-bab-titogo", nil, false) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -1194,7 +1194,7 @@ func crashedGrant(t *testing.T, s release.Store, p *MemProvisioner) (bucket, use |
| if _, err := p.EnsureBucket(ctx, bucket); err != nil { |
| t.Fatal(err) |
| } |
| - if _, err := p.EnsureUser(ctx, user, UserPath, "arn:aws:s3:::"+bucket, nil); err != nil { |
| + if _, err := p.EnsureUser(ctx, user, UserPath, "arn:aws:s3:::"+bucket, nil, false); err != nil { |
| t.Fatal(err) |
| } |
| id, _, err := p.MintKey(ctx, user) |
diff --git a/internal/objstore/writesdenied.go b/internal/objstore/writesdenied.go| new file mode 100644 |
| index 000000000..bbe9f7a14 |
| --- /dev/null |
| +++ b/internal/objstore/writesdenied.go |
| @@ -0,0 +1,46 @@ |
| +package objstore |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// SetWritesDenied sets (wd non-nil) or clears (nil) one store's |
| +// WritesDenied, leaving every other field as it is (plans 4b). It writes |
| +// the record only; the policy changes on the next grant walk, which the |
| +// caller runs. A missing record is os.ErrNotExist. |
| +func SetWritesDenied(ctx context.Context, s release.Store, acct, app, env string, wd *WritesDenied) (*Record, error) { |
| + return updateStore(ctx, s, acct, app, env, func(rec *Record) { rec.WritesDenied = wd }) |
| +} |
| + |
| +// SetWritesDenyApplied records what the last successful grant wrote for |
| +// WritesDenied. |
| +func SetWritesDenyApplied(ctx context.Context, s release.Store, acct, app, env string, applied bool) (*Record, error) { |
| + return updateStore(ctx, s, acct, app, env, func(rec *Record) { rec.WritesDenyApplied = &applied }) |
| +} |
| + |
| +// updateStore applies change to one store's record under CAS, three tries. |
| +func updateStore(ctx context.Context, s release.Store, acct, app, env string, change func(*Record)) (*Record, error) { |
| + for attempt := 0; attempt < 3; attempt++ { |
| + rec, etag, err := GetIn(ctx, s, acct, app, env) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if rec == nil { |
| + return nil, os.ErrNotExist |
| + } |
| + change(rec) |
| + if _, err := PutIn(ctx, s, acct, app, env, rec, etag); err != nil { |
| + if errors.Is(err, release.ErrCASConflict) { |
| + continue |
| + } |
| + return nil, err |
| + } |
| + return rec, nil |
| + } |
| + return nil, fmt.Errorf("objstore: %s: lost the write race three times", KeyIn(acct, app, env)) |
| +} |
diff --git a/internal/objstore/writesdenied_test.go b/internal/objstore/writesdenied_test.go| new file mode 100644 |
| index 000000000..ce953be2d |
| --- /dev/null |
| +++ b/internal/objstore/writesdenied_test.go |
| @@ -0,0 +1,109 @@ |
| +package objstore |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// writeDenyOf finds the unconditional PutObject deny (plans 4b), not the |
| +// conditional anti-forgery one. |
| +func writeDenyOf(t *testing.T, doc string) *policyStatement { |
| + t.Helper() |
| + var parsed policyDocument |
| + if err := json.Unmarshal([]byte(doc), &parsed); err != nil { |
| + t.Fatalf("not valid JSON: %v\n%s", err, doc) |
| + } |
| + for i, st := range parsed.Statement { |
| + if st.Effect == "Deny" && len(st.Action) == 1 && st.Action[0] == "s3:PutObject" && st.Condition == nil { |
| + return &parsed.Statement[i] |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +func TestStorePolicyDeniesWritesOnly(t *testing.T) { |
| + doc := storePolicyJSON("arn:aws:s3:::b", &DenyTag{Key: TagVerdict, Value: string(VerdictInfected)}, true) |
| + if d := writeDenyOf(t, doc); d == nil || d.Resource != "arn:aws:s3:::b/*" { |
| + t.Fatalf("no unconditional PutObject deny on the bucket's objects:\n%s", doc) |
| + } |
| + for _, want := range []string{"s3:ListBucket", "s3:GetObject", "s3:DeleteObject", "s3:GetObjectTagging", |
| + "s3:PutObjectTagging", "s3:RequestObjectTagKeys", "s3:ExistingObjectTag"} { |
| + if !strings.Contains(doc, want) { |
| + t.Errorf("policy lost %s:\n%s", want, doc) |
| + } |
| + } |
| + var parsed policyDocument |
| + json.Unmarshal([]byte(doc), &parsed) |
| + if len(parsed.Statement) != 6 { |
| + t.Fatalf("want the five statements of a scanning store plus the write deny, got %d:\n%s", len(parsed.Statement), doc) |
| + } |
| +} |
| + |
| +func TestStorePolicyUnchangedWithoutDeny(t *testing.T) { |
| + for _, deny := range []*DenyTag{nil, {Key: TagVerdict, Value: string(VerdictInfected)}} { |
| + doc := storePolicyJSON("arn:aws:s3:::b", deny, false) |
| + if writeDenyOf(t, doc) != nil { |
| + t.Fatalf("write deny without being asked:\n%s", doc) |
| + } |
| + } |
| +} |
| + |
| +func TestGrantWritesTheWriteDeny(t *testing.T) { |
| + ctx := context.Background() |
| + s := release.NewDirStore(t.TempDir()) |
| + _, pub := testSealKeypair(t) |
| + p := NewMemProvisioner("eu-west-1") |
| + rotateFixture(t, s, pub, p) |
| + user := UserName("bab", "titogo") |
| + if _, err := SetWritesDenied(ctx, s, "bab", "titogo", "", &WritesDenied{Reason: "plan storage", At: time.Now().UTC()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := Grant(ctx, s, p, testDeployment(), pub, "bab", "titogo", "op@example.com", GrantSourceOperator, "", time.Now().UTC()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if writeDenyOf(t, p.PolicyFor(user)) == nil { |
| + t.Fatalf("re-granting a store with WritesDenied wrote no write deny:\n%s", p.PolicyFor(user)) |
| + } |
| + if _, err := SetWritesDenied(ctx, s, "bab", "titogo", "", nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := Grant(ctx, s, p, testDeployment(), pub, "bab", "titogo", "op@example.com", GrantSourceOperator, "", time.Now().UTC()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if writeDenyOf(t, p.PolicyFor(user)) != nil { |
| + t.Fatalf("cleared WritesDenied left the write deny:\n%s", p.PolicyFor(user)) |
| + } |
| +} |
| + |
| +func TestSetWritesDeniedRoundTrip(t *testing.T) { |
| + ctx := context.Background() |
| + s := release.NewDirStore(t.TempDir()) |
| + _, pub := testSealKeypair(t) |
| + p := NewMemProvisioner("eu-west-1") |
| + rotateFixture(t, s, pub, p) |
| + at := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC) |
| + rec, err := SetWritesDenied(ctx, s, "bab", "titogo", "", &WritesDenied{Reason: "r", At: at}) |
| + if err != nil || rec.WritesDenied == nil { |
| + t.Fatalf("set = %+v, %v", rec, err) |
| + } |
| + got, _, _ := Get(ctx, s, "bab", "titogo") |
| + if got.WritesDenied == nil || got.WritesDenied.Reason != "r" || !got.WritesDenied.At.Equal(at) || got.Provisioned == nil { |
| + t.Fatalf("stored = %+v", got) |
| + } |
| + if _, err := SetWritesDenied(ctx, s, "bab", "titogo", "", nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, _, _ := Get(ctx, s, "bab", "titogo"); got.WritesDenied != nil { |
| + t.Fatal("nil did not clear") |
| + } |
| + if _, err := SetWritesDenied(ctx, s, "bab", "nostore", "", nil); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("missing record = %v, want os.ErrNotExist", err) |
| + } |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 8463969ab..57f37ea6e 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -23,4 +23,5 @@ plan14-root-reads-plans-4a-store.tsv 72dc835c04caf5b2b49cc6ecbfd865bb3123b997ee9 |
| plan14-root-reads-plans-4-notices-grace.tsv 43e430a3b3edf9333bfe2c64f24ca9e4c04475dc45ae4983d4e8bcab6a9c0bc4 |
| plan14-root-reads-design-edge-rate-limit-358-decisions.tsv a067dcd9e32e6be2b7dd9c6a8256d1252ac4c737fd058c430823e382add340c4 |
| plan14-root-reads-design-edge-rate-limit-358.tsv 0c4eabfe38e12b098285bdeb5ceb0b16e5333928f5b02e160a6b16b5fd9ce1e0 |
| +plan14-root-reads-plans-4b-after-grace.tsv 0c4eabfe38e12b098285bdeb5ceb0b16e5333928f5b02e160a6b16b5fd9ce1e0 |
| plan14-root-reads-certwarm-wake.tsv 91204fcbc484343c03bd5ae69e3084055bc519a5b317e2ae3dc49880080764e2 |
diff --git a/internal/provision/testdata/plan14-root-reads-plans-4b-after-grace.tsv b/internal/provision/testdata/plan14-root-reads-plans-4b-after-grace.tsv| new file mode 100644 |
| index 000000000..d1b3c855d |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-plans-4b-after-grace.tsv |
| @@ -0,0 +1,5 @@ |
| +# Census overlay plans-4b-after-grace, written by census-propose (#369). census-ruling-plans-4b-after-grace, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-plans-4b-after-grace.md. |
| +# 0 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage internal/console 8a40b10ae28da7dc179120d2642ceb2f5b4b11af56d2f63fbeac72564ac04f40 |
| +@coverage internal/mail 05a47dcae9895be45f129a564dd4749920ffda2bbec6cf733689c17a8c130f15 |
| +@coverage internal/objstore 00ab61b5784339ab8ab911ecfabc006a64275676c48138903f5d68fafd225305 |