carlos / platform Public

email: Tasks 7-8 review fixes (R1 P2s)

Astra round 1 on Tasks 7-8: READY AFTER FIXES, census APPROVE for the
root package, svcrole, mailer, mailsubmit and mailwire. Its six P2s:
the domain doors answer instance-address dependencies with 409 and the
count; pause --host is 404 for a missing sender and 409 for a removing
one; an unreadable app sender is 502, never "sending"; the new verbs
resolve their session and account without exiting; HTTP witnesses for
the pause/cap matrix, the domain 409 and every captured write's
classification; pause/resume gain --cap (cli.md promised it) and the
three verbs get cli.md headings.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5b70b8f7c2a59c17c6f417b9647f90c413123073 parent 4ad0bb3
8 files changed, +269 −44
  • docs/site/cli.md +6 −0
  • docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-T7-R1.md +47 −0
  • internal/console/apiinstancesender.go +18 −1
  • internal/console/apiinstancesender_test.go +128 −22
  • internal/console/apimail.go +12 −0
  • internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv +1 −1
  • mail_cli.go +10 −6
  • mail_instance_cli.go +47 −14

CI cancelled — superseded by a newer push — run details

CI log
=== gate ===
go: downloading go1.26.10 (linux/arm64)
go version go1.26.10 linux/arm64
opentofu: arm64, tofu 1.13.9, aws 6.73.0, archive 2.8.1
  tofu: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/tofu_1.13.9_linux_arm64.tar.gz
  tofu: downloaded, digest verified
  aws: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-aws_6.73.0_linux_arm64.zip
  aws: downloaded, digest verified
  archive: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-archive_2.8.1_linux_arm64.zip
  archive: downloaded, digest verified
  installed in /tmp/carlos-opentofu-yOZSu9
.amadan/test-gate.sh
go: downloading github.com/aws/aws-sdk-go-v2 v1.44.0
go: downloading github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0
go: downloading github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5
go: downloading github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0
go: downloading github.com/aws/smithy-go v1.28.1
go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e
go: downloading golang.org/x/net v0.62.0
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/prometheus/client_golang v1.17.0
go: downloading github.com/aws/aws-sdk-go-v2/service/acm v1.45.0
go: downloading github.com/aws/aws-sdk-go-v2/service/iam v1.58.2
go: downloading github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.37.0
go: downloading github.com/aws/aws-sdk-go-v2/service/route53 v1.64.1
go: downloading github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0
go: downloading golang.org/x/sys v0.49.0
go: downloading golang.org/x/mod v0.41.0
go: downloading golang.org/x/crypto v0.58.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/aws/aws-sdk-go-v2/service/sesv2 v1.66.6
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading github.com/pion/transport/v4 v4.0.2
go: downloading github.com/beorn7/perks v1.0.1
go: downloading github.com/cespare/xxhash/v2 v2.3.0
go: downloading github.com/prometheus/client_model v0.5.0
go: downloading github.com/prometheus/common v0.45.0
go: downloading github.com/prometheus/procfs v0.12.0
go: downloading google.golang.org/protobuf v1.36.10
go: downloading github.com/pion/randutil v0.1.0
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/wlynxg/anet v0.0.5
go: downloading golang.org/x/text v0.43.0
go: downloading github.com/klauspost/compress v1.20.2
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading modernc.org/libc v1.74.1
go: downloading modernc.org/libc v1.74.1
go: downloading modernc.org/memory v1.11.0
go: downloading modernc.org/mathutil v1.7.1
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading github.com/google/uuid v1.6.0
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading github.com/google/uuid v1.6.0
go: downloading modernc.org/mathutil v1.7.1
go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec
go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec

amadan: job cancelled — a newer push superseded it
diff --git a/docs/site/cli.md b/docs/site/cli.md
index bf702ca08..2e300bc38 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -2823,10 +2823,16 @@ or pinning a build without `--mail submit` is refused. The app-level SMTP
user goes a week after its key stops being used. `submission off` delivers
the SMTP credential again. Both restart the app's instances.
+#### carlos email instance
+
`carlos email instance create --app <a> --host <h>` gives one instance of an app its own email sender, with its own daily cap, pause and counts. `--address` grants it addresses as it is created. `status` shows the instance's sender and today's counts, and `rm` removes it, revoking every address. An instance can't be deleted while it has a sender. The app must send through the platform's mailer first (`carlos email submission on`). A backend can run these with a `mail` service credential.
+#### carlos email addresses
+
`carlos email addresses add --app <a> --host <h> <address>` lets one instance send as one exact address on a domain the app sends from, and `rm` stops it. Each address belongs to one instance. The domain must be the app's alone: an address can't be given out on a domain another app shares, and another app can't add the domain while addresses use it.
+#### carlos email per-instance
+
`carlos email per-instance on --app <a>` makes every instance of the app send only as its own sender: as the addresses granted to it, within its own cap. An instance with no sender can't send at all. It needs the app's old SMTP credential retired first, about a week after `carlos email submission on`. `off` is refused while any instance sender exists.
`--host <h>` on `carlos email pause` and `resume` pauses, resumes or changes the cap of that one instance's sender, leaving the rest of the app alone.
diff --git a/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-T7-R1.md b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-T7-R1.md
new file mode 100644
index 000000000..db44ea518
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-T7-R1.md
@@ -0,0 +1,47 @@
+# Tasks 7-8 review, round 1 (Astra, gpt-6-astra, on 4ad0bb3d8)
+
+Reviewed `7dc39e668..4ad0bb3d85ae3752841324b26ce68ed03fe42859`. **No P1 findings; six P2 findings.** Static review only; no files changed or tests run.
+
+1. **P2 — Domain conflicts never reach the required 409 response.**
+ [apimail.go:1074](internal/console/apimail.go:1074) and [apimail.go:1233](internal/console/apimail.go:1233) do not handle `AddressesInUseError`. Removing a domain used by an instance address, or adding it to another app, falls through to generic 502 advice to retry. The new mapping in `writeInstanceSenderError` is never called by these handlers.
+ **Fix:** map this error in both domain handlers to 409 with the approved count/pin message; test grants, reservations and releases through HTTP.
+ **Invariant:** persistent address dependencies produce an actionable conflict, not a transient backend failure.
+
+2. **P2 — Pausing a nonexistent sender returns 502 instead of 404.**
+ [apiinstancesender.go:413](internal/console/apiinstancesender.go:413) calls `SetSenderPaused`, which returns `ErrNotProvisioned` for a missing sender ([walk.go:1368](internal/mail/walk.go:1368)). The error mapper does not handle it, so the later nil-sender 404 is unreachable. A removing sender also takes this generic failure path.
+ **Fix:** distinguish missing and removing senders inside the mutation path and map them to 404 and 409 respectively.
+ **Invariant:** sender lifecycle refusals retain their documented HTTP meaning.
+
+3. **P2 — Failed hold-state reads can report “sending.”**
+ [apiinstancesender.go:234](internal/console/apiinstancesender.go:234) logs an app-sender read failure and continues. If that record carries `InstancesPause`, the response omits the hold and reports `sending` for an otherwise unpaused sender. This affects status and mutation replies.
+ **Fix:** return 502 when the app sender cannot be read; add a read-failure witness with an existing plan hold.
+ **Invariant:** unknown enforcement state must not be reported as permission to send.
+
+4. **P2 — New error-returning CLI verbs still terminate the process during setup.**
+ [mail_instance_cli.go:106](mail_instance_cli.go:106) and [mail_instance_cli.go:241](mail_instance_cli.go:241) call `requireMailAPISession`, whose failure paths call `log.Fatal` ([mail_cli.go:259](mail_cli.go:259)). For example, invoking a new verb in direct-bucket mode exits instead of returning its error to the dispatcher.
+ **Fix:** use error-returning session/account resolution and propagate setup failures through the new verbs.
+ **Invariant:** new commands return errors; the dispatcher owns process termination.
+
+5. **P2 — Required boundary witnesses are replaced by lower-level checks.**
+ [apiinstancesender_test.go:176](internal/console/apiinstancesender_test.go:176) tests pause/cap functions directly, never the `host` HTTP routing or its three request shapes. [apiinstancesender_test.go:233](internal/console/apiinstancesender_test.go:233) classifies two invented keys with `{}` bodies rather than capturing actual create/grant/revoke/remove writes through `ClaimMailStore`. These tests can pass despite a broken handler or an additional incorrectly scoped write.
+ **Fix:** implement the planned HTTP pause/cap matrix and capture/classify every actual mutation from all four operations.
+ **Invariant:** witnesses exercise the production authority boundary and complete write set.
+
+6. **P2 — CLI documentation promises a cap operation the CLI cannot perform.**
+ [cli.md:2832](docs/site/cli.md:2832) says `pause`/`resume --host` changes the cap. Neither command accepts a cap flag, and its request contains only `paused` and `host`. The three explicitly planned command headings are also absent; their text was appended under the existing email section.
+ **Fix:** correct the behavioral claim or implement the cap flag, and add the `email instance`, `email addresses`, and `email per-instance` headings.
+ **Invariant:** documented commands expose the behavior they promise.
+
+The inspected role registrations admit `mail` to exactly the five sender doors, with Admin included. Mint and resolve reject account-wide mail rows. App binding precedes existence checks; writes select the principal-kind budget. The six claim fixtures, read probe and six `linkedRefuse` entries are present.
+
+Census verdicts, including earlier-slice changes against local `origin/main`:
+
+- **`.` — APPROVE:** CLI dispatch, requests and rendering; no new root-local authority. Reviewed `mail_cli.go:2098`, `mail_instance_cli.go:106`, and `services.go:175`.
+- **`internal/svcrole` — APPROVE:** catalogue addition preserves explicit door admission and Admin’s union (`svcrole.go:90`).
+- **`internal/mailer` — APPROVE:** sender lookup derives from the stamped host and validates ID, scope, host and removal; tenant remains app-derived (`policy.go:150`, `policy.go:277`, `ses.go:80`).
+- **`internal/mailsubmit` — APPROVE:** additive refusal code only (`proto.go:54`).
+- **`internal/mailwire` — APPROVE:** additive projections, canonical address checks, reversible tag validation and app-exclusive domain enforcement (`instance.go:49`, `instance.go:115`, `instance.go:138`, `mailwire.go:108`).
+
+Round 1 has no P1: apply the P2 fixes without reopening review, retaining the required census and changed-security checks.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/internal/console/apiinstancesender.go b/internal/console/apiinstancesender.go
index 8055a1bef..b15f32997 100644
--- a/internal/console/apiinstancesender.go
+++ b/internal/console/apiinstancesender.go
@@ -152,7 +152,7 @@ func (s *Server) writeInstanceSenderError(w http.ResponseWriter, app, host strin
jsonError(w, http.StatusConflict, domainInUseMessage(inUse))
case errors.Is(err, mail.ErrSenderInventory):
jsonError(w, http.StatusBadGateway, mailInstanceCopy.SenderInventory)
- case errors.Is(err, mail.ErrNoSuchSender):
+ case errors.Is(err, mail.ErrNoSuchSender), errors.Is(err, mail.ErrNotProvisioned):
http.Error(w, "404 page not found", http.StatusNotFound)
default:
if mail.IsAddressConcurrent(err) {
@@ -231,9 +231,13 @@ func (s *Server) handleAPIInstanceSenderCreate(w http.ResponseWriter, r *http.Re
}
func (s *Server) answerInstanceSender(ctx context.Context, w http.ResponseWriter, acct, app string, sn *mail.Sender) {
+ // The app sender carries the hold over every instance: without it the
+ // state cannot be known, and "sending" must never stand in for unknown.
appSender, _, err := mail.GetSender(ctx, s.cfg.Releases, acct, app, mail.SenderAppID)
if err != nil {
log.Printf("console: instance sender %s/%s: app sender: %v", app, sn.Host, err)
+ jsonError(w, http.StatusBadGateway, mailInstanceCopy.SenderInventory)
+ return
}
out, err := s.instanceSenderReply(ctx, acct, app, sn, appSender, time.Now())
if err != nil {
@@ -402,6 +406,19 @@ func (s *Server) pauseInstanceSender(ctx context.Context, w http.ResponseWriter,
jsonError(w, http.StatusBadRequest, mailInstanceCopy.InvalidHost)
return
}
+ cur, _, err := mail.GetSender(ctx, s.cfg.Releases, acct.Sqid, app, id)
+ switch {
+ case err != nil:
+ log.Printf("console: instance sender pause %s/%s: %v", app, host, err)
+ jsonError(w, http.StatusBadGateway, mailInstanceCopy.SenderInventory)
+ return
+ case cur == nil || cur.Scope != mail.ScopeInstance:
+ http.Error(w, "404 page not found", http.StatusNotFound)
+ return
+ case cur.Removing != nil:
+ jsonError(w, http.StatusConflict, mailInstanceCopy.SenderRemoving)
+ return
+ }
var sn *mail.Sender
if dailyCap > 0 {
if sn, err = mail.SetInstanceSenderCap(ctx, s.claimMailStore(), acct.Sqid, app, host, dailyCap, addr, time.Now()); err != nil {
diff --git a/internal/console/apiinstancesender_test.go b/internal/console/apiinstancesender_test.go
index 8c2925365..cc41cf1c2 100644
--- a/internal/console/apiinstancesender_test.go
+++ b/internal/console/apiinstancesender_test.go
@@ -8,12 +8,14 @@ import (
"slices"
"sort"
"strings"
+ "sync"
"testing"
"time"
"github.com/carlosframework/platform/internal/hostops"
"github.com/carlosframework/platform/internal/mail"
"github.com/carlosframework/platform/internal/mailwire"
+ "github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/svcrole"
)
@@ -72,10 +74,22 @@ func TestMailRoleReachesOnlyTheInstanceSenderDoors(t *testing.T) {
// its app sender granted go.tito.io (verified, titogo's alone), and a mail
// credential bound to titogo.
func instanceSenderFixture(t *testing.T) (*consoleFixture, string, string) {
- fx, mailTok, u, _ := instanceSenderFixtureOwner(t)
+ fx, mailTok, u, owner := instanceSenderFixtureOwner(t)
+ instanceOwnerTokens.Store(fx, owner)
return fx, mailTok, u
}
+var instanceOwnerTokens sync.Map
+
+func instanceFixtureOwnerToken(t *testing.T, fx *consoleFixture) (*consoleFixture, string) {
+ t.Helper()
+ v, ok := instanceOwnerTokens.Load(fx)
+ if !ok {
+ t.Fatal("no owner token for this fixture")
+ }
+ return fx, v.(string)
+}
+
func instanceSenderFixtureOwner(t *testing.T) (*consoleFixture, string, string, string) {
t.Helper()
fx, token := instanceFixture(t, "code-inst-sender")
@@ -173,9 +187,14 @@ func TestMailCredentialNeedsAnApp(t *testing.T) {
}
}
+// The operator pause door's host field, through HTTP: pause-only,
+// cap-only and pause plus cap each change only that instance sender; a
+// missing sender is 404 and a removing one 409.
func TestEmailPauseHost(t *testing.T) {
- fx, tok, u := instanceSenderFixture(t)
+ fx, _, u := instanceSenderFixture(t)
ctx := context.Background()
+ fx.srv.cfg.MailOperators = []string{"ops@keymail.dev"}
+ op := emailOperatorToken(t, fx, "code-inst-pause-op")
for _, h := range []string{isHost, "b.go.tito.io"} {
if _, err := mail.CreateInstanceSender(ctx, fx.rel, "bab", "titogo", h, nil, "t", time.Now()); err != nil {
t.Fatal(err)
@@ -188,19 +207,63 @@ func TestEmailPauseHost(t *testing.T) {
}
return string(raw)
}
- appBefore, sibBefore := read(mail.SenderAppID), read("b.go.tito.io")
- sn, err := mail.SetInstanceSenderCap(ctx, fx.rel, "bab", "titogo", isHost, 77, "op", time.Now())
- if err != nil || sn.Grant.DailyCap != 77 {
- t.Fatalf("cap: %v %+v", err, sn)
+ pauseURL := strings.TrimSuffix(u, "/instances") + "/email/pause"
+ for _, c := range []struct {
+ name, body string
+ paused bool
+ cap int
+ }{
+ {"pause only", `{"paused":true,"host":"` + isHost + `"}`, true, 0},
+ {"cap only", `{"daily_cap":77,"host":"` + isHost + `"}`, true, 77},
+ {"resume and cap", `{"paused":false,"daily_cap":88,"host":"` + isHost + `"}`, false, 88},
+ } {
+ appBefore, sibBefore := read(mail.SenderAppID), read("b.go.tito.io")
+ status, _, out := rawReq(t, http.MethodPost, pauseURL, op, c.body)
+ if status != http.StatusOK {
+ t.Fatalf("%s: %d %s", c.name, status, out)
+ }
+ sn, _, err := mail.GetSender(ctx, fx.rel, "bab", "titogo", isHost)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := mail.EffectivePause(sn) != nil; got != c.paused {
+ t.Errorf("%s: paused = %v, want %v", c.name, got, c.paused)
+ }
+ if c.cap > 0 && sn.Grant.DailyCap != c.cap {
+ t.Errorf("%s: cap = %d, want %d", c.name, sn.Grant.DailyCap, c.cap)
+ }
+ if read(mail.SenderAppID) != appBefore || read("b.go.tito.io") != sibBefore {
+ t.Fatalf("%s: the app sender or a sibling changed", c.name)
+ }
+ }
+ if status, _, out := rawReq(t, http.MethodPost, pauseURL, op, `{"paused":true,"host":"none.go.tito.io"}`); status != http.StatusNotFound {
+ t.Fatalf("missing sender = %d %s, want 404", status, out)
}
- if _, err := mail.SetSenderPaused(ctx, fx.rel, fx.srv.cfg.MailProvisioner, "bab", "titogo", isHost, true, "", time.Now()); err != nil {
+ now := time.Now()
+ sn, etag, _ := mail.GetSender(ctx, fx.rel, "bab", "titogo", "b.go.tito.io")
+ sn.Removing = &now
+ if _, err := mail.PutSender(ctx, fx.rel, "bab", "titogo", sn, etag); err != nil {
t.Fatal(err)
}
- if read(mail.SenderAppID) != appBefore || read("b.go.tito.io") != sibBefore {
- t.Fatal("pausing one instance changed the app sender or a sibling")
+ if status, _, out := rawReq(t, http.MethodPost, pauseURL, op, `{"paused":true,"host":"b.go.tito.io"}`); status != http.StatusConflict {
+ t.Fatalf("removing sender = %d %s, want 409", status, out)
+ }
+}
+
+// The domain doors answer a dependency on instance addresses with 409 and
+// the count (decision 13), not a retryable 502.
+func TestDomainRemoveRefusedForInstanceAddresses(t *testing.T) {
+ fx, tok, u := instanceSenderFixture(t)
+ if status, _, out := rawReq(t, http.MethodPost, u+"/"+isHost+"/email", tok, `{"addresses":["p@`+isDomain+`"]}`); status != http.StatusOK {
+ t.Fatalf("create = %d %s", status, out)
+ }
+ _, owner := instanceFixtureOwnerToken(t, fx)
+ domURL := strings.TrimSuffix(u, "/instances") + "/email/domains/" + isDomain
+ status, _, out := rawReq(t, http.MethodDelete, domURL, owner, "")
+ want := jsonQuote(fmt.Sprintf(mailInstanceCopy.DomainInUse, 1, isDomain))
+ if status != http.StatusConflict || !strings.Contains(out, want) {
+ t.Fatalf("domains rm = %d %s, want 409 %q", status, out, want)
}
- _ = tok
- _ = u
}
func TestEmailStatusInstanceEntries(t *testing.T) {
@@ -228,22 +291,65 @@ func TestEmailStatusInstanceEntries(t *testing.T) {
}
}
-// Every bucket write the instance-sender work makes classifies to exactly
-// this app (spec test 8.11, address half).
+// recordingStore records every write's key, method and bodies.
+type recordingStore struct {
+ release.Store
+ mu sync.Mutex
+ targets []hostops.MutationTarget
+}
+
+func (r *recordingStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ before, _, _ := r.Store.Get(ctx, key)
+ r.mu.Lock()
+ r.targets = append(r.targets, hostops.MutationTarget{Method: "Put", Key: key, Before: before, After: body})
+ r.mu.Unlock()
+ return r.Store.Put(ctx, key, body, ifMatch)
+}
+
+func (r *recordingStore) Delete(ctx context.Context, key string) error {
+ before, _, _ := r.Store.Get(ctx, key)
+ r.mu.Lock()
+ r.targets = append(r.targets, hostops.MutationTarget{Method: "Delete", Key: key, Before: before})
+ r.mu.Unlock()
+ return r.Store.Delete(ctx, key)
+}
+
+func (r *recordingStore) DeleteIfMatch(ctx context.Context, key, etag string) error {
+ before, _, _ := r.Store.Get(ctx, key)
+ r.mu.Lock()
+ r.targets = append(r.targets, hostops.MutationTarget{Method: "Delete", Key: key, Before: before})
+ r.mu.Unlock()
+ return release.DeleteIfMatch(ctx, r.Store, key, etag)
+}
+
+// Every bucket write the four instance-sender operations actually make,
+// captured through the production doors, classifies to exactly this app
+// (spec test 8.11, address half).
func TestInstanceSenderWritesClassifyToApp(t *testing.T) {
- fx, _, _ := instanceSenderFixture(t)
- ctx := context.Background()
- keys := []string{
- mail.SenderKey("bab", "titogo", isHost),
- mail.AddressKey("bab", "titogo", "p@go.tito.io"),
+ fx, tok, u := instanceSenderFixture(t)
+ rec := &recordingStore{Store: fx.srv.cfg.Releases}
+ fx.srv.cfg.Releases = rec
+ base := u + "/" + isHost + "/email"
+ for _, step := range []struct{ method, url, body string }{
+ {http.MethodPost, base, `{"addresses":["p@` + isDomain + `"]}`},
+ {http.MethodPut, base + "/addresses/q@" + isDomain, ""},
+ {http.MethodDelete, base + "/addresses/p@" + isDomain, ""},
+ {http.MethodDelete, base, ""},
+ } {
+ if status, _, out := rawReq(t, step.method, step.url, tok, step.body); status != http.StatusOK {
+ t.Fatalf("%s %s = %d %s", step.method, step.url, status, out)
+ }
+ }
+ if len(rec.targets) == 0 {
+ t.Fatal("no writes captured")
}
- for _, k := range keys {
- c, err := hostops.ClassifyMutation(ctx, fx.rel, nil, hostops.MutationTarget{Key: k, Method: "Put", After: []byte(`{}`)})
+ for _, target := range rec.targets {
+ c, err := hostops.ClassifyMutation(context.Background(), rec.Store, nil, target)
if err != nil {
- t.Fatalf("%s: %v", k, err)
+ t.Fatalf("%s %s: %v", target.Method, target.Key, err)
}
if len(c.Scopes) != 1 || c.Scopes[0] != (hostops.AppScope{Account: "bab", App: "titogo"}) {
- t.Fatalf("%s classifies to %+v", k, c.Scopes)
+ t.Fatalf("%s %s classifies to %+v", target.Method, target.Key, c.Scopes)
}
}
}
diff --git a/internal/console/apimail.go b/internal/console/apimail.go
index 134d279d4..2bb40abbc 100644
--- a/internal/console/apimail.go
+++ b/internal/console/apimail.go
@@ -1086,6 +1086,13 @@ func (s *Server) handleAPIEmailDomainEnsure(w http.ResponseWriter, r *http.Reque
jsonError(w, http.StatusConflict, mailDomainUnavailableMsg)
return
}
+ // Another app's instance addresses depend on this domain (instance
+ // senders decision 6): a conflict the caller can clear.
+ var inUse *mail.AddressesInUseError
+ if errors.As(err, &inUse) {
+ jsonError(w, http.StatusConflict, domainInUseMessage(inUse))
+ return
+ }
// ErrIdentityNotOwned (#216): SES already has an identity for this
// domain that this account's claim did not create. The member is
// told exactly how to prove control, because the proof is the only
@@ -1240,6 +1247,11 @@ func (s *Server) handleAPIEmailDomainRemove(w http.ResponseWriter, r *http.Reque
jsonError(w, http.StatusConflict, s.mailFromConflictMessage(ctx, acct, app, domain))
return
}
+ var inUse *mail.AddressesInUseError
+ if errors.As(err, &inUse) {
+ jsonError(w, http.StatusConflict, domainInUseMessage(inUse))
+ return
+ }
// 404 covers both "this app does not use that domain" and "that
// domain's claim belongs to another account", deliberately in the
// same words — see mail.ErrDomainNotReferenced.
diff --git a/internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv b/internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv
index 03f27f3de..3194f4427 100644
--- a/internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv
+++ b/internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv
@@ -1,6 +1,6 @@
# Census overlay instance-senders-1, written by census-propose (#369). census-ruling-instance-senders-1, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-instance-senders-1.md.
# 0 body, 0 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
-@coverage . ab9b3e4b011a4dfa36e85d6a8302e8cb7b88e7cdcd6e20b3e329af8d2e4ca210
+@coverage . 8fc50b771fdab063318e8fd13562f88cddbf35082f818eba9f07c27ecac777bb
@coverage internal/mailer 7faad983d368293409cd67c257a99faf7814075cc0bf9dad034955ce849dce26
@coverage internal/mailsubmit 293b1864d19aa444237d4976d8e4d5bcffbed8b268c9c4fd7fade244d0b0f604
@coverage internal/mailwire a080b525495cc7762aa536a015ce961f6263c3e89d69bb115adb5a64978d84d6
diff --git a/mail_cli.go b/mail_cli.go
index 747ae8d10..fd7cfb69d 100644
--- a/mail_cli.go
+++ b/mail_cli.go
@@ -262,15 +262,18 @@ func requireMailAPISession(consoleFlag string) *apiSession {
log.Fatal(err)
}
if sess == nil {
- log.Fatal("carlos email works through a console, and this shell is in direct bucket mode\n" +
- "(CARLOS_DEPLOYMENT_BUCKET/CARLOS_DEPLOYMENT_DIR is set). email is a member/operator verb with\n" +
- "no direct-bucket equivalent — the record lives in the console's deployment bucket, and enabling\n" +
- "or adding a domain calls out to the deployment's own SES estate, an authority only the console\n" +
- "can exercise. Unset the store env and run: carlos auth login --console <url>.")
+ log.Fatal(mailDirectModeRefusal)
}
return sess
}
+// mailDirectModeRefusal is the answer to an email verb in direct bucket mode.
+const mailDirectModeRefusal = "carlos email works through a console, and this shell is in direct bucket mode\n" +
+ "(CARLOS_DEPLOYMENT_BUCKET/CARLOS_DEPLOYMENT_DIR is set). email is a member/operator verb with\n" +
+ "no direct-bucket equivalent — the record lives in the console's deployment bucket, and enabling\n" +
+ "or adding a domain calls out to the deployment's own SES estate, an authority only the console\n" +
+ "can exercise. Unset the store env and run: carlos auth login --console <url>."
+
// ---- wire types --------------------------------------------------------------
type apiEmailDeclared struct {
@@ -2099,6 +2102,7 @@ func runEmailPause(args []string, paused bool) {
fs := flag.NewFlagSet("email "+verb, flag.ExitOnError)
app := appFlag(fs, "app to "+verb)
host := fs.String("host", "", "pause or resume only this instance's own sender")
+ capFlag := fs.Int("cap", 0, "with --host: also set that instance sender's daily cap")
acctRaw, acctIDRaw, _ := accountFlags(fs)
consoleFlag := consoleOption(fs, "console origin (API mode only; default: the only logged-in one)")
fs.Usage = flagUsage(fs, "")
@@ -2119,7 +2123,7 @@ func runEmailPause(args []string, paused bool) {
var err error
h := strings.TrimSpace(*host)
if h != "" {
- err = pauseInstanceSender(sess, acct, name, h, paused)
+ err = pauseInstanceSender(sess, acct, name, h, paused, *capFlag)
} else {
res, err = sess.emailPause(context.Background(), acct, name, paused)
}
diff --git a/mail_instance_cli.go b/mail_instance_cli.go
index 47fdbc02b..bd9e7bccd 100644
--- a/mail_instance_cli.go
+++ b/mail_instance_cli.go
@@ -9,6 +9,7 @@ package main
import (
"context"
"encoding/json"
+ "errors"
"flag"
"fmt"
"io"
@@ -103,10 +104,28 @@ func parseInstanceArgs(verb string, args []string, withAddress bool) (*instanceA
return out, nil
}
-func (a *instanceArgs) session() (*apiSession, apiAcct) {
- sess := requireMailAPISession(a.console)
+func (a *instanceArgs) session() (*apiSession, apiAcct, error) {
+ return mailSessionE(a.console, a.acctRaw, a.acctID)
+}
+
+// mailSessionE is requireMailAPISession plus resolvedAccount, returning
+// their refusals instead of exiting (AGENTS.md "Writing Go here").
+func mailSessionE(consoleFlag string, acctRaw, acctID *string) (*apiSession, apiAcct, error) {
+ sess, err := resolveMode(consoleFlag)
+ if err != nil {
+ return nil, apiAcct{}, err
+ }
+ if sess == nil {
+ return nil, apiAcct{}, errors.New(mailDirectModeRefusal)
+ }
printUsing(stdout, sess)
- return sess, resolvedAccount(sess, a.acctRaw, a.acctID)
+ acct := apiAccount(acctRaw, acctID)
+ if acct.Seg == "" {
+ if acct, err = sess.defaultAccount(context.Background()); err != nil {
+ return nil, apiAcct{}, err
+ }
+ }
+ return sess, acct, nil
}
func instanceSenderPath(a apiAcct, app, host, tail string) string {
@@ -129,7 +148,10 @@ func runEmailInstanceCreate(args []string) error {
if err != nil {
return err
}
- sess, acct := a.session()
+ sess, acct, err := a.session()
+ if err != nil {
+ return err
+ }
status, body, err := sess.postJSON(context.Background(), instanceSenderPath(acct, a.app, a.host, ""),
struct {
Addresses []string `json:"addresses"`
@@ -151,7 +173,10 @@ func runEmailInstanceStatus(args []string) error {
if err != nil {
return err
}
- sess, acct := a.session()
+ sess, acct, err := a.session()
+ if err != nil {
+ return err
+ }
status, body, err := sess.getJSON(context.Background(), instanceSenderPath(acct, a.app, a.host, ""))
if err != nil {
return err
@@ -169,7 +194,10 @@ func runEmailInstanceRm(args []string) error {
if err != nil {
return err
}
- sess, acct := a.session()
+ sess, acct, err := a.session()
+ if err != nil {
+ return err
+ }
status, body, err := sess.deleteJSON(context.Background(), instanceSenderPath(acct, a.app, a.host, ""))
if err != nil {
return err
@@ -194,7 +222,10 @@ func runEmailAddresses(args []string, add bool) error {
return fmt.Errorf("usage: carlos %s --app <a> --host <h> <address>", verb)
}
address := a.rest[0]
- sess, acct := a.session()
+ sess, acct, err := a.session()
+ if err != nil {
+ return err
+ }
path := instanceSenderPath(acct, a.app, a.host, "/addresses/"+url.PathEscape(address))
var status int
var body []byte
@@ -238,9 +269,10 @@ func runEmailPerInstance(args []string, on bool) error {
if err := validAppName(name); err != nil {
return fmt.Errorf("%s: %w", verb, err)
}
- sess := requireMailAPISession(*consoleFlag)
- printUsing(stdout, sess)
- acct := resolvedAccount(sess, acctRaw, acctIDRaw)
+ sess, acct, err := mailSessionE(*consoleFlag, acctRaw, acctIDRaw)
+ if err != nil {
+ return err
+ }
status, body, err := sess.postJSON(context.Background(), apiPath(acct, name, "/email/per-instance"), struct {
On bool `json:"on"`
}{on})
@@ -260,11 +292,12 @@ func runEmailPerInstance(args []string, on bool) error {
// pauseInstanceSender is `carlos email pause|resume --host`: one instance's
// own sender, through the operator pause door's host field.
-func pauseInstanceSender(sess *apiSession, acct apiAcct, app, host string, paused bool) error {
+func pauseInstanceSender(sess *apiSession, acct apiAcct, app, host string, paused bool, dailyCap int) error {
status, body, err := sess.postJSON(context.Background(), apiPath(acct, app, "/email/pause"), struct {
- Paused *bool `json:"paused"`
- Host string `json:"host"`
- }{&paused, host})
+ Paused *bool `json:"paused"`
+ Host string `json:"host"`
+ DailyCap int `json:"daily_cap,omitempty"`
+ }{&paused, host, dailyCap})
if err != nil {
return err
}