mail: instance sender fields, strict inventory, tag decode
Slice 1 Task 2 (#148): Sender gains Reserving/Releasing/Removing/ InstancesPause and GrantBlock.Addresses; CanSend is true for a live instance sender; SenderOfCaller decodes the encoded sender tag from the mailer; ListSendersStrict fails on an unreadable sender.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+330
−3
internal/console/sesevents_instance_test.go+80 −0internal/mail/mail.go+4 −0internal/mail/sender.go+24 −3internal/mail/sender_instance_test.go+152 −0internal/mail/senders_strict.go+70 −0
CI cancelled — superseded by a newer push — run details
diff --git a/internal/console/sesevents_instance_test.go b/internal/console/sesevents_instance_test.go| new file mode 100644 |
| index 000000000..2eb79926a |
| --- /dev/null |
| +++ b/internal/console/sesevents_instance_test.go |
| @@ -0,0 +1,80 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/mail" |
| + "github.com/carlosframework/platform/internal/mailwire" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// Instance senders decision 10: the mailer's events, tagged with an |
| +// instance sender's encoded id, are counted against that sender alone, and |
| +// its bounce rate pauses it and not its sibling. The same events from a |
| +// non-mailer caller are never charged to the tagged instance. |
| +func TestEventsChargeOnlyTheTaggedInstance(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "bill@tito.io", now.Add(-time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + app := &mail.Sender{ID: mail.SenderAppID, Scope: mail.ScopeApp, Source: mail.SourceDomain, |
| + Grant: &mail.GrantBlock{Domains: []string{"lgc.li"}}, Submission: &mailwire.Submission{On: true, At: now.Add(-time.Hour)}} |
| + if _, err := mail.PutSender(ctx, fx.rel, release.OpsAccount, "shop", app, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, id := range []string{"a.shop.example", "b.shop.example"} { |
| + sn := &mail.Sender{ID: id, Scope: mail.ScopeInstance, Host: id, Source: mail.SourceDomain, |
| + Grant: &mail.GrantBlock{DailyCap: 1000, Addresses: []string{"x@lgc.li"}}} |
| + if _, err := mail.PutSender(ctx, fx.rel, release.OpsAccount, "shop", sn, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + tags := map[string]string{"account": release.OpsAccount, "app": "shop", "sender": mailwire.SenderTag("a.shop.example")} |
| + day := now.UTC().Format("2006-01-02") |
| + |
| + // A non-mailer caller carrying A's tags is not charged to A. |
| + forged := bounceTo("eve@example.com", "m-forged", now) |
| + forged.Caller = mail.UserName(release.OpsAccount, "elsewhere") |
| + forged.Tags = tags |
| + fx.srv.recordAndEnforceMail(ctx, forged, "sns-forged") |
| + if c, _ := fx.st.MailCounts(ctx, release.OpsAccount, "shop", "a.shop.example", day); c.Bounces != 0 { |
| + t.Fatalf("A charged for a non-mailer caller's event: %+v", c) |
| + } |
| + |
| + for i := 0; i < MinSendsForRates; i++ { |
| + ev := mail.Event{Type: mail.EventSend, Domain: "lgc.li", MessageID: fmt.Sprintf("m-send-%d", i), At: now, |
| + Caller: "carlos-mailer-eu-west-1", Tags: tags} |
| + fx.srv.recordAndEnforceMail(ctx, ev, fmt.Sprintf("sns-send-%d", i)) |
| + } |
| + for i := 0; i < 3; i++ { |
| + ev := bounceTo(fmt.Sprintf("r%d@example.com", i), fmt.Sprintf("m-bounce-%d", i), now) |
| + ev.Caller = "carlos-mailer-eu-west-1" |
| + ev.Tags = tags |
| + fx.srv.recordAndEnforceMail(ctx, ev, fmt.Sprintf("sns-bounce-%d", i)) |
| + } |
| + if c, _ := fx.st.MailCounts(ctx, release.OpsAccount, "shop", "a.shop.example", day); c.Sends != MinSendsForRates || c.Bounces != 3 { |
| + t.Fatalf("A counts %+v", c) |
| + } |
| + if c, _ := fx.st.MailCounts(ctx, release.OpsAccount, "shop", "b.shop.example", day); c.Sends != 0 || c.Bounces != 0 { |
| + t.Fatalf("B charged: %+v", c) |
| + } |
| + a, _, err := mail.GetSender(ctx, fx.rel, release.OpsAccount, "shop", "a.shop.example") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if pz := mail.EffectivePause(a); pz == nil || pz.Kind != mail.PauseKindRate { |
| + t.Fatalf("A pause = %+v, want a rate pause", pz) |
| + } |
| + b, _, err := mail.GetSender(ctx, fx.rel, release.OpsAccount, "shop", "b.shop.example") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if pz := mail.EffectivePause(b); pz != nil { |
| + t.Fatalf("B paused by A's bounces: %+v", pz) |
| + } |
| +} |
diff --git a/internal/mail/mail.go b/internal/mail/mail.go| index 9fe71cde1..5e4d568f3 100644 |
| --- a/internal/mail/mail.go |
| +++ b/internal/mail/mail.go |
| @@ -52,6 +52,10 @@ type GrantBlock struct { |
| Source string `json:"source"` |
| At time.Time `json:"at"` |
| By string `json:"by"` |
| + // Addresses is an instance sender's exact address grants, canonical |
| + // (mailwire.CanonicalAddress), written only through the address |
| + // reservation functions (addresses.go). Additive. |
| + Addresses []string `json:"addresses,omitempty"` |
| } |
| // Provisioned is the walk's half. KeyID is the SMTP USERNAME and is not a |
diff --git a/internal/mail/sender.go b/internal/mail/sender.go| index 163ade925..7df34dd34 100644 |
| --- a/internal/mail/sender.go |
| +++ b/internal/mail/sender.go |
| @@ -103,6 +103,19 @@ type Sender struct { |
| // by the reap (sweep.go). Additive. |
| Submission *mailwire.Submission `json:"submission,omitempty"` |
| + // The instance-sender fields (instance senders design, decisions 3, |
| + // 15 and 16). Additive. Reserving and Releasing are an address grant's |
| + // pending transitions (mail.SetAddress's invariant: every address key a |
| + // sender owns is named on its record until the key is gone); Removing |
| + // marks a sender whose removal has begun, which the mailer refuses and |
| + // CanSend reads as unable to send. InstancesPause is written only on an |
| + // app sender in per-instance mode: the account plan pause over every |
| + // instance sender of the app, read by the mailer. |
| + Reserving []string `json:"reserving,omitempty"` |
| + Releasing []string `json:"releasing,omitempty"` |
| + Removing *time.Time `json:"removing,omitempty"` |
| + InstancesPause *mailwire.Pause `json:"instances_pause,omitempty"` |
| + |
| // Salt disambiguates a slug collision. The slug is 40 bits of a hash, so |
| // two senders can in principle want the same IAM user name; the caller |
| // index detects that and ResolveSenderNames recomputes the slug with a |
| @@ -139,8 +152,13 @@ func Switched(sn *Sender) bool { |
| // CanSend reports whether anything can send as this sender at all: it has |
| // an IAM credential (Provisioned), or its app is switched to the submit |
| // transport. A sender that can send is one a pause means something for. |
| +// |
| +// An instance sender can send while it is not being removed: one exists |
| +// only in an app switched to submission (instance senders decision 1), and |
| +// it has no switch of its own (decision 10). |
| func CanSend(sn *Sender) bool { |
| - return sn != nil && (sn.Provisioned != nil || Switched(sn)) |
| + return sn != nil && (sn.Provisioned != nil || Switched(sn) || |
| + (sn.Scope == ScopeInstance && sn.Removing == nil)) |
| } |
| // SendersPrefix is where an app's senders live. Inside apps/<acct>/<app>/ on |
| @@ -510,8 +528,11 @@ func claimUnserializedResolveSenderNames(ctx context.Context, s release.Store, a |
| func SenderOfCaller(ctx context.Context, s release.Store, caller string, tags map[string]string) (string, string, string, bool) { |
| // Decision 6's guard. Nothing above it, and nothing below it reads tags. |
| if mailwire.IsMailerCaller(caller) { |
| - acct, app, sender := tags[mailwire.TagAccount], tags[mailwire.TagApp], tags[mailwire.TagSender] |
| - if release.ValidAccount(acct) && release.ValidApp(app) && ValidSenderID(sender) { |
| + // The sender tag is SES-safe-encoded (instance senders decision 11): |
| + // "app", or "i-" and the base32 of an instance sender's id. |
| + acct, app := tags[mailwire.TagAccount], tags[mailwire.TagApp] |
| + sender, decoded := mailwire.SenderFromTag(tags[mailwire.TagSender]) |
| + if decoded && release.ValidAccount(acct) && release.ValidApp(app) && ValidSenderID(sender) { |
| return acct, app, sender, true |
| } |
| logMailerUntagged(caller, time.Now()) |
diff --git a/internal/mail/sender_instance_test.go b/internal/mail/sender_instance_test.go| new file mode 100644 |
| index 000000000..040cd7337 |
| --- /dev/null |
| +++ b/internal/mail/sender_instance_test.go |
| @@ -0,0 +1,152 @@ |
| +package mail |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/mailwire" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func TestCanSendInstanceSender(t *testing.T) { |
| + now := time.Now() |
| + if !CanSend(&Sender{ID: "a.x.example", Scope: ScopeInstance}) { |
| + t.Error("a live instance sender cannot send") |
| + } |
| + if CanSend(&Sender{ID: "a.x.example", Scope: ScopeInstance, Removing: &now}) { |
| + t.Error("a removing instance sender can send") |
| + } |
| + if CanSend(&Sender{ID: SenderAppID, Scope: ScopeApp}) { |
| + t.Error("an app sender with no credential and no switch can send") |
| + } |
| + if !CanSend(&Sender{ID: SenderAppID, Scope: ScopeApp, Provisioned: &Provisioned{}}) { |
| + t.Error("a provisioned app sender cannot send") |
| + } |
| + if CanSend(nil) { |
| + t.Error("nil can send") |
| + } |
| +} |
| + |
| +func TestSenderOfCallerDecodesInstanceTag(t *testing.T) { |
| + ctx := context.Background() |
| + s := release.NewDirStore(t.TempDir()) |
| + const mailer = "carlos-mailer-eu-west-1" |
| + tags := map[string]string{mailwire.TagAccount: "bab", mailwire.TagApp: "shop", mailwire.TagSender: mailwire.SenderTag("a.x.example")} |
| + acct, app, sender, ok := SenderOfCaller(ctx, s, mailer, tags) |
| + if !ok || acct != "bab" || app != "shop" || sender != "a.x.example" { |
| + t.Fatalf("SenderOfCaller = %q %q %q %v", acct, app, sender, ok) |
| + } |
| + raw := map[string]string{mailwire.TagAccount: "bab", mailwire.TagApp: "shop", mailwire.TagSender: "a.x.example"} |
| + if _, _, _, ok := SenderOfCaller(ctx, s, mailer, raw); ok { |
| + t.Error("an undecoded sender tag was believed") |
| + } |
| + appTags := map[string]string{mailwire.TagAccount: "bab", mailwire.TagApp: "shop", mailwire.TagSender: "app"} |
| + if _, _, sender, ok := SenderOfCaller(ctx, s, mailer, appTags); !ok || sender != SenderAppID { |
| + t.Errorf("app tag: %q %v", sender, ok) |
| + } |
| + // A non-mailer caller's tags are never read: today's parse result. |
| + acct, app, sender, ok = SenderOfCaller(ctx, s, UserName("bab", "other"), tags) |
| + if !ok || acct != "bab" || app != "other" || sender != SenderAppID { |
| + t.Errorf("non-mailer caller = %q %q %q %v", acct, app, sender, ok) |
| + } |
| +} |
| + |
| +// failGetStore fails Get for one key. |
| +type failGetStore struct { |
| + release.Store |
| + key string |
| +} |
| + |
| +func (f failGetStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == f.key { |
| + return nil, "", errors.New("injected read failure") |
| + } |
| + return f.Store.Get(ctx, key) |
| +} |
| + |
| +func putSenderJSON(t *testing.T, s release.Store, acct, app string, sn *Sender) { |
| + t.Helper() |
| + if _, err := claimUnserializedPutSender(context.Background(), s, acct, app, sn, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestListSendersStrictFailsOnUnreadable(t *testing.T) { |
| + ctx := context.Background() |
| + base := release.NewDirStore(t.TempDir()) |
| + putSenderJSON(t, base, "bab", "shop", &Sender{ID: SenderAppID, Scope: ScopeApp, Source: SourceDomain}) |
| + putSenderJSON(t, base, "bab", "shop", &Sender{ID: "b.x.example", Scope: ScopeInstance, Host: "b.x.example"}) |
| + putSenderJSON(t, base, "bab", "shop", &Sender{ID: "a.x.example", Scope: ScopeInstance, Host: "a.x.example"}) |
| + |
| + all, err := ListSendersStrict(ctx, base, "bab", "shop") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var ids []string |
| + for _, sn := range all { |
| + ids = append(ids, sn.ID) |
| + } |
| + if strings.Join(ids, ",") != "app,a.x.example,b.x.example" { |
| + t.Fatalf("order %v", ids) |
| + } |
| + if got := InstanceSenders(all); len(got) != 2 || got[0].ID != "a.x.example" { |
| + t.Fatalf("InstanceSenders = %v", got) |
| + } |
| + |
| + bad := failGetStore{Store: base, key: SenderKey("bab", "shop", "b.x.example")} |
| + if _, err := ListSendersStrict(ctx, bad, "bab", "shop"); !errors.Is(err, ErrSenderInventory) { |
| + t.Fatalf("unreadable: %v, want ErrSenderInventory", err) |
| + } |
| + if _, err := base.Put(ctx, SenderKey("bab", "shop", "c.x.example"), []byte("{not json"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := ListSendersStrict(ctx, base, "bab", "shop"); !errors.Is(err, ErrSenderInventory) { |
| + t.Fatalf("malformed: %v, want ErrSenderInventory", err) |
| + } |
| + if err := base.Delete(ctx, SenderKey("bab", "shop", "c.x.example")); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// The mailer reads instance senders through mailwire.SenderView: every |
| +// field the view names survives the round trip, and the copied rules equal |
| +// this package's. |
| +func TestSenderViewDecodesInstanceSender(t *testing.T) { |
| + at := time.Date(2026, 11, 30, 9, 0, 0, 0, time.UTC) |
| + sn := &Sender{ |
| + Schema: 1, ID: "a.x.example", Scope: ScopeInstance, Host: "a.x.example", Source: SourceDomain, |
| + Grant: &GrantBlock{Domains: []string{}, DailyCap: 40, Addresses: []string{"paul@x.example"}}, |
| + Pause: &mailwire.Pause{Kind: mailwire.PauseKindCap, At: at}, |
| + Reserving: []string{"r@x.example"}, |
| + Releasing: []string{"q@x.example"}, |
| + Removing: &at, |
| + InstancesPause: &mailwire.Pause{Kind: mailwire.PauseKindPlan, At: at}, |
| + } |
| + body, err := json.Marshal(sn) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var v mailwire.SenderView |
| + if err := json.Unmarshal(body, &v); err != nil { |
| + t.Fatal(err) |
| + } |
| + if v.Scope != ScopeInstance || v.Host != "a.x.example" || v.Removing == nil || !v.Removing.Equal(at) || |
| + v.InstancesPause == nil || v.InstancesPause.Kind != mailwire.PauseKindPlan || |
| + v.Grant == nil || len(v.Grant.Addresses) != 1 || v.Grant.Addresses[0] != "paul@x.example" || v.Grant.DailyCap != 40 { |
| + t.Fatalf("view %+v grant %+v", v, v.Grant) |
| + } |
| + if ScopeInstance != mailwire.ScopeInstance { |
| + t.Error("ScopeInstance differs from mailwire's") |
| + } |
| + if domainRe.String() != mailwire.AddressDomainPattern() { |
| + t.Error("mailwire's address domain rule differs from domainRe") |
| + } |
| + if senderIDRe.String() != mailwire.SenderIDPattern() { |
| + t.Error("mailwire's sender id rule differs from senderIDRe") |
| + } |
| +} |
diff --git a/internal/mail/senders_strict.go b/internal/mail/senders_strict.go| new file mode 100644 |
| index 000000000..7d0f360c2 |
| --- /dev/null |
| +++ b/internal/mail/senders_strict.go |
| @@ -0,0 +1,70 @@ |
| +package mail |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "sort" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// ErrSenderInventory is ListSendersStrict's refusal: a sender key exists but |
| +// could not be read or decoded, so "these are all the app's senders" cannot |
| +// be answered (instance senders decision 16 (b)). |
| +var ErrSenderInventory = errors.New("mail: could not read every sender of the app") |
| + |
| +// ListSendersStrict is ListSenders for the decisions that must rest on a |
| +// complete inventory: whether any instance sender exists (the mode |
| +// switches, submission off) and whether every one was removed (teardown). |
| +// ListSenders skips a sibling it cannot read, which is right for a status |
| +// reply and wrong for these. Same order: app sender first, the rest by id. |
| +// It has no legacy fallback: an app with no app sender record has none. |
| +func ListSendersStrict(ctx context.Context, s release.Store, acct, app string) ([]*Sender, error) { |
| + if !release.ValidAccount(acct) || !release.ValidApp(app) { |
| + return nil, fmt.Errorf("mail: invalid account or app %q/%q", acct, app) |
| + } |
| + keys, err := s.List(ctx, SendersPrefix(acct, app)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var appSender *Sender |
| + var rest []*Sender |
| + for _, k := range keys { |
| + if !strings.HasSuffix(k, ".json") { |
| + continue |
| + } |
| + raw, _, err := s.Get(ctx, k) |
| + if err != nil { |
| + return nil, fmt.Errorf("%w: %s: %v", ErrSenderInventory, k, err) |
| + } |
| + var sn Sender |
| + if err := json.Unmarshal(raw, &sn); err != nil { |
| + return nil, fmt.Errorf("%w: %s: %v", ErrSenderInventory, k, err) |
| + } |
| + if sn.ID == SenderAppID { |
| + appSender = &sn |
| + continue |
| + } |
| + rest = append(rest, &sn) |
| + } |
| + sort.Slice(rest, func(i, j int) bool { return rest[i].ID < rest[j].ID }) |
| + out := make([]*Sender, 0, len(rest)+1) |
| + if appSender != nil { |
| + out = append(out, appSender) |
| + } |
| + return append(out, rest...), nil |
| +} |
| + |
| +// InstanceSenders is the instance senders among all. |
| +func InstanceSenders(all []*Sender) []*Sender { |
| + var out []*Sender |
| + for _, sn := range all { |
| + if sn != nil && sn.Scope == ScopeInstance { |
| + out = append(out, sn) |
| + } |
| + } |
| + return out |
| +} |