mail: address reservations safe without the claim gate (Task 3 R1)
Astra round 1 on Task 3: P1, recovery could orphan a key when HostClaim is off; P2, the guard never interleaved. Recovery now rolls a reservation forward (writes the key create-only), a grant refuses an address still being released (ErrAddressPending), and the mailer's address rule sends only from a domain its app holds alone, so a share racing a grant fails closed. Channel-controlled interleaving tests on the bare store.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+252
−13
internal/mail/addresses.go+48 −10internal/mail/addresses_interleave_test.go+190 −0internal/mailwire/instance.go+11 −2internal/mailwire/instance_test.go+2 −0internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv+1 −1
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-VCyDUi .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 golang.org/x/sys v0.49.0 go: downloading modernc.org/sqlite v1.55.0 go: downloading golang.org/x/crypto v0.58.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/ec2 v1.324.0 go: downloading github.com/aws/smithy-go v1.28.1 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/s3 v1.105.0 go: downloading github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5 go: downloading github.com/lmittmann/tint v1.1.3 go: downloading github.com/pierrec/lz4/v4 v4.1.22 go: downloading golang.org/x/net v0.62.0 go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e go: downloading github.com/aws/aws-sdk-go-v2/service/sesv2 v1.66.6 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/klauspost/compress v1.20.2 go: downloading github.com/wlynxg/anet v0.0.5 go: downloading github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 go: downloading golang.org/x/text v0.43.0 go: downloading modernc.org/sqlite v1.55.0 go: downloading github.com/klauspost/compress v1.20.2 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 github.com/dustin/go-humanize v1.0.1 go: downloading modernc.org/mathutil v1.7.1 go: downloading github.com/google/uuid v1.6.0 go: downloading github.com/dustin/go-humanize v1.0.1 go: downloading modernc.org/memory v1.11.0 go: downloading modernc.org/mathutil v1.7.1 go: downloading github.com/google/uuid v1.6.0 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/internal/mail/addresses.go b/internal/mail/addresses.go| index 58cd8e704..436de8c9e 100644 |
| --- a/internal/mail/addresses.go |
| +++ b/internal/mail/addresses.go |
| @@ -17,6 +17,18 @@ package mail |
| // fails after any write (claim_gate.go:425-427), so a business refusal |
| // after a write would strand it. Recovery runs as its own admitted call, |
| // before the call that may refuse. |
| +// |
| +// The invariant does NOT rest on the gate. A console without HostClaim |
| +// runs these unserialized (claimMailStore returns the bare store), so every |
| +// step is safe under any interleaving on its own: recovery ROLLS A |
| +// RESERVATION FORWARD (it writes the key itself, create-only) rather than |
| +// dropping it, so a grant paused between its reservation and its key can |
| +// never be left holding a key its record no longer names; and a grant |
| +// refuses an address still being released (ErrAddressPending), so a |
| +// release can never delete the key under a fresh grant. Domain sharing is |
| +// re-checked where it matters, at the mailer (mailwire.CheckInstanceFrom |
| +// sends an address only from a domain held by its app alone), so a share |
| +// racing a grant fails closed at send time. |
| import ( |
| "context" |
| @@ -58,6 +70,9 @@ var ( |
| // ErrNoSuchSender is an address change on an instance sender that does |
| // not exist. |
| ErrNoSuchSender = errors.New("mail: no such instance sender") |
| + // ErrAddressPending is a grant of an address the sender is still |
| + // releasing; recovery finishes the release, then the grant may run. |
| + ErrAddressPending = errors.New("mail: that address is still being released") |
| // errAddressClaimMismatch is an address key that appeared under the gate |
| // between the read-only check and the write: an inconsistency, returned |
| // as an error (which correctly retains the gate), never a refusal. |
| @@ -187,6 +202,11 @@ func preflightGrants(ctx context.Context, s release.Store, acct, app, id string, |
| held = append(held, sn.Grant.Addresses...) |
| } |
| held = append(held, sn.Reserving...) |
| + for _, c := range canonical { |
| + if slices.Contains(sn.Releasing, c) { |
| + return fmt.Errorf("%s: %w", c, ErrAddressPending) |
| + } |
| + } |
| } |
| total := len(held) |
| for _, c := range canonical { |
| @@ -233,13 +253,21 @@ func preflightGrants(ctx context.Context, s release.Store, acct, app, id string, |
| // an error (the gate stays retained, as an uncertain effect should). |
| func grantPreflighted(ctx context.Context, s release.Store, acct, app, id string, canonical []string) (*Sender, error) { |
| var todo []string |
| + var pending error |
| sn, err := mutateSender(ctx, s, acct, app, id, func(sn *Sender) bool { |
| todo = todo[:0] |
| + pending = nil |
| changed := false |
| for _, c := range canonical { |
| if sn.Grant != nil && slices.Contains(sn.Grant.Addresses, c) { |
| continue |
| } |
| + if slices.Contains(sn.Releasing, c) { |
| + // A release began since the preflight read (only possible |
| + // unserialized): reserve nothing, write nothing. |
| + pending = fmt.Errorf("%s: %w", c, ErrAddressPending) |
| + return false |
| + } |
| if !slices.Contains(sn.Reserving, c) { |
| sn.Reserving = append(sn.Reserving, c) |
| changed = true |
| @@ -251,6 +279,9 @@ func grantPreflighted(ctx context.Context, s release.Store, acct, app, id string |
| if err != nil { |
| return nil, err |
| } |
| + if pending != nil { |
| + return nil, pending |
| + } |
| if len(todo) == 0 { |
| return sn, nil |
| } |
| @@ -312,10 +343,14 @@ func deleteOwnAddressClaim(ctx context.Context, s release.Store, acct, app, id, |
| return release.DeleteIfMatch(ctx, s, key, etag) |
| } |
| -// claimUnserializedRecoverAddresses finishes every pending transition: a |
| -// Reserving address whose key names this sender is granted, one whose key |
| -// does not is dropped; a Releasing address's own key is deleted and the |
| -// address dropped. An absent sender is nothing to recover. |
| +// claimUnserializedRecoverAddresses finishes every pending transition, |
| +// always forward: a Reserving address's key is written if absent |
| +// (create-only), then the address is granted when the key names this |
| +// sender and dropped when it names another; a Releasing address's own key |
| +// is deleted and the address dropped. Rolling a reservation forward rather |
| +// than back is what keeps a concurrent grant, paused between its |
| +// reservation and its key, from leaving an orphaned key. An absent sender |
| +// is nothing to recover. |
| func claimUnserializedRecoverAddresses(ctx context.Context, s release.Store, acct, app, id string) (*Sender, error) { |
| sn, _, err := getInstanceSender(ctx, s, acct, app, id) |
| if err != nil || sn == nil { |
| @@ -325,15 +360,18 @@ func claimUnserializedRecoverAddresses(ctx context.Context, s release.Store, acc |
| return sn, nil |
| } |
| var grant, drop []string |
| + body, err := json.Marshal(addressClaim{Sender: id}) |
| + if err != nil { |
| + return nil, err |
| + } |
| for _, c := range sn.Reserving { |
| - holder, _, exists, err := readAddressClaim(ctx, s, AddressKey(acct, app, c)) |
| - if err != nil { |
| - return nil, err |
| - } |
| - if exists && holder == id { |
| + switch err := putAddressClaim(ctx, s, acct, app, id, c, body); { |
| + case err == nil: |
| grant = append(grant, c) |
| - } else { |
| + case errors.Is(err, errAddressClaimMismatch): |
| drop = append(drop, c) |
| + default: |
| + return nil, err |
| } |
| } |
| releasing := slices.Clone(sn.Releasing) |
diff --git a/internal/mail/addresses_interleave_test.go b/internal/mail/addresses_interleave_test.go| new file mode 100644 |
| index 000000000..aac00345d |
| --- /dev/null |
| +++ b/internal/mail/addresses_interleave_test.go |
| @@ -0,0 +1,190 @@ |
| +package mail |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// pausingStore parks the first write whose op and key match, before or |
| +// after it reaches the store, until the test releases it. Everything else |
| +// passes straight through. This is the unserialized (HostClaim off) |
| +// production shape: the bare store, no mail claim gate. |
| +type pausingStore struct { |
| + release.Store |
| + op, keyPart string |
| + after bool |
| + once sync.Once |
| + arrived chan struct{} |
| + release chan struct{} |
| +} |
| + |
| +func newPausing(base release.Store, op, keyPart string, after bool) *pausingStore { |
| + return &pausingStore{Store: base, op: op, keyPart: keyPart, after: after, |
| + arrived: make(chan struct{}), release: make(chan struct{})} |
| +} |
| + |
| +func (p *pausingStore) park(op, key string) { |
| + if op != p.op || !strings.Contains(key, p.keyPart) { |
| + return |
| + } |
| + p.once.Do(func() { |
| + close(p.arrived) |
| + <-p.release |
| + }) |
| +} |
| + |
| +func (p *pausingStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + if !p.after { |
| + p.park("Put", key) |
| + } |
| + etag, err := p.Store.Put(ctx, key, body, ifMatch) |
| + if p.after { |
| + p.park("Put", key) |
| + } |
| + return etag, err |
| +} |
| + |
| +func (p *pausingStore) DeleteIfMatch(ctx context.Context, key, etag string) error { |
| + if !p.after { |
| + p.park("DeleteIfMatch", key) |
| + } |
| + err := release.DeleteIfMatch(ctx, p.Store, key, etag) |
| + if p.after { |
| + p.park("DeleteIfMatch", key) |
| + } |
| + return err |
| +} |
| + |
| +// run starts op on s in the background and waits for it to park. |
| +func runParked(t *testing.T, p *pausingStore, op func(release.Store) error) chan error { |
| + t.Helper() |
| + done := make(chan error, 1) |
| + go func() { done <- op(p) }() |
| + select { |
| + case <-p.arrived: |
| + case err := <-done: |
| + t.Fatalf("operation finished without reaching its pause: %v", err) |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("operation never reached its pause") |
| + } |
| + return done |
| +} |
| + |
| +func finish(t *testing.T, p *pausingStore, done chan error) error { |
| + t.Helper() |
| + close(p.release) |
| + select { |
| + case err := <-done: |
| + return err |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("parked operation never finished") |
| + return nil |
| + } |
| +} |
| + |
| +var ilIDs = []string{"a.shop.example", "b.shop.example"} |
| +var ilAddrs = []string{"p@x.example"} |
| + |
| +func grantOn(id string) func(release.Store) error { |
| + return func(s release.Store) error { |
| + _, err := GrantAddress(context.Background(), s, tAcct, tApp, id, "p@x.example", time.Now()) |
| + return err |
| + } |
| +} |
| + |
| +// A grant paused between its reservation and its key, while recovery runs: |
| +// recovery rolls the reservation forward, the grant's key write finds its |
| +// own key, and nothing is orphaned (round 1 P1). |
| +func TestInterleaveGrantPausedBeforeKeyWhileRecover(t *testing.T) { |
| + base := release.NewDirStore(t.TempDir()) |
| + addrFixture(t, base) |
| + p := newPausing(base, "Put", "/email/addresses/", false) |
| + done := runParked(t, p, grantOn("a.shop.example")) |
| + if _, err := RecoverAddresses(context.Background(), base, tAcct, tApp, "a.shop.example"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := finish(t, p, done); err != nil { |
| + t.Fatalf("grant: %v", err) |
| + } |
| + checkAddressInvariant(t, base, ilIDs, ilAddrs, "grant-before-key/recover") |
| + if sn := senderOf(t, base, "a.shop.example"); len(sn.Grant.Addresses) != 1 || len(sn.Reserving) != 0 { |
| + t.Fatalf("a: %+v", sn) |
| + } |
| +} |
| + |
| +// A grant paused after its key, before its final update, while recovery |
| +// runs: recovery grants it, the grant's final update has nothing to do. |
| +func TestInterleaveGrantPausedAfterKeyWhileRecover(t *testing.T) { |
| + base := release.NewDirStore(t.TempDir()) |
| + addrFixture(t, base) |
| + p := newPausing(base, "Put", "/email/addresses/", true) |
| + done := runParked(t, p, grantOn("a.shop.example")) |
| + if _, err := RecoverAddresses(context.Background(), base, tAcct, tApp, "a.shop.example"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := finish(t, p, done); err != nil { |
| + t.Fatalf("grant: %v", err) |
| + } |
| + checkAddressInvariant(t, base, ilIDs, ilAddrs, "grant-after-key/recover") |
| +} |
| + |
| +// A revoke paused before deleting its key, while the same sender grants |
| +// the address again: the grant is refused (still being released), and the |
| +// revoke completes; nothing is granted without a key. |
| +func TestInterleaveRevokePausedWhileGrant(t *testing.T) { |
| + base := release.NewDirStore(t.TempDir()) |
| + addrFixture(t, base) |
| + if _, err := GrantAddress(context.Background(), base, tAcct, tApp, "a.shop.example", "p@x.example", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + p := newPausing(base, "DeleteIfMatch", "/email/addresses/", false) |
| + done := runParked(t, p, func(s release.Store) error { |
| + _, err := RevokeAddress(context.Background(), s, tAcct, tApp, "a.shop.example", "p@x.example", time.Now()) |
| + return err |
| + }) |
| + // The direct grant would run recovery first, which would finish the |
| + // release (a second, real delete): exercise the grant step itself. |
| + if _, err := claimUnserializedGrantAddresses(context.Background(), base, tAcct, tApp, "a.shop.example", []string{"p@x.example"}); !errors.Is(err, ErrAddressPending) { |
| + t.Fatalf("grant during release: %v, want ErrAddressPending", err) |
| + } |
| + if err := finish(t, p, done); err != nil { |
| + t.Fatalf("revoke: %v", err) |
| + } |
| + checkAddressInvariant(t, base, ilIDs, ilAddrs, "revoke/grant") |
| + if _, ok := keyHolder(t, base, "p@x.example"); ok { |
| + t.Fatal("key survived the revoke") |
| + } |
| +} |
| + |
| +// Two senders racing one address: one wins the key; the loser's grant |
| +// fails and its reservation is dropped by recovery, never granted. |
| +func TestInterleaveTwoSendersRace(t *testing.T) { |
| + base := release.NewDirStore(t.TempDir()) |
| + addrFixture(t, base) |
| + p := newPausing(base, "Put", "/email/addresses/", false) |
| + done := runParked(t, p, grantOn("a.shop.example")) |
| + // b's direct step (its preflight read happens now, a's key not yet written). |
| + if _, err := claimUnserializedGrantAddresses(context.Background(), base, tAcct, tApp, "b.shop.example", []string{"p@x.example"}); err != nil { |
| + t.Fatalf("b: %v", err) |
| + } |
| + aErr := finish(t, p, done) |
| + if aErr == nil { |
| + t.Fatal("both senders' grants succeeded") |
| + } |
| + if _, err := RecoverAddresses(context.Background(), base, tAcct, tApp, "a.shop.example"); err != nil { |
| + t.Fatal(err) |
| + } |
| + checkAddressInvariant(t, base, ilIDs, ilAddrs, "race") |
| + if h, _ := keyHolder(t, base, "p@x.example"); h != "b.shop.example" { |
| + t.Fatalf("holder %q", h) |
| + } |
| + if sn := senderOf(t, base, "a.shop.example"); len(sn.Reserving) != 0 || (sn.Grant != nil && len(sn.Grant.Addresses) != 0) { |
| + t.Fatalf("loser a: %+v", sn) |
| + } |
| +} |
diff --git a/internal/mailwire/instance.go b/internal/mailwire/instance.go| index b8a39edd5..8fabbe04e 100644 |
| --- a/internal/mailwire/instance.go |
| +++ b/internal/mailwire/instance.go |
| @@ -134,7 +134,8 @@ func SenderFromTag(tag string) (string, bool) { |
| // grants (decision 8, address half): from, canonicalised, is one of sn's |
| // granted addresses (never a reservation or a release, which the view does |
| // not carry), and its domain is sendable by the app sender under |
| -// CheckFromDomain. dv is the record of from's domain (nil when absent). |
| +// CheckFromDomain, and held by app alone. dv is the record of from's domain |
| +// (nil when absent). |
| // The owned-domain half arrives with slice 2. |
| func CheckInstanceFrom(sn, appSender *SenderView, from, app, region string, dv *DomainView) FromVerdict { |
| addr, err := CanonicalAddress(from) |
| @@ -145,5 +146,13 @@ func CheckInstanceFrom(sn, appSender *SenderView, from, app, region string, dv * |
| if appSender != nil && appSender.Grant != nil { |
| granted = appSender.Grant.Domains |
| } |
| - return CheckFromDomain(granted, addr[strings.LastIndexByte(addr, '@')+1:], app, region, dv) |
| + v := CheckFromDomain(granted, addr[strings.LastIndexByte(addr, '@')+1:], app, region, dv) |
| + // An address grant's domain is held by its app ALONE (decision 6). The |
| + // console refuses to share such a domain, and this refuses to send from |
| + // one that became shared anyway (a race on a console without the mail |
| + // claim gate): the address rule fails closed at the enforcement point. |
| + if v == FromSendable && (len(dv.Apps) != 1 || dv.Apps[0] != app) { |
| + return FromAppNotListed |
| + } |
| + return v |
| } |
diff --git a/internal/mailwire/instance_test.go b/internal/mailwire/instance_test.go| index d37a9731b..c064285c9 100644 |
| --- a/internal/mailwire/instance_test.go |
| +++ b/internal/mailwire/instance_test.go |
| @@ -99,6 +99,7 @@ func TestCheckInstanceFrom(t *testing.T) { |
| "eu-west-1": {IdentityARN: "arn:x", ConfigSet: "carlos-acct", Status: "pending"}}} |
| noSet := &DomainView{Domain: "x.example", Apps: []string{"shop"}, Regions: map[string]*DomainRegionView{ |
| "eu-west-1": {IdentityARN: "arn:x", Status: DomainStatusVerified}}} |
| + shared := &DomainView{Domain: "x.example", Apps: []string{"shop", "other"}, Regions: verified.Regions} |
| noDomainApp := &SenderView{ID: SenderAppID, Grant: &GrantView{Domains: []string{"other.example"}}} |
| pendingOnly := &SenderView{ID: "a.x.example", Scope: ScopeInstance, Grant: &GrantView{}} |
| @@ -119,6 +120,7 @@ func TestCheckInstanceFrom(t *testing.T) { |
| {"no configuration set", inst, appSender, "paul@x.example", noSet, FromNoConfigSet}, |
| {"no record", inst, appSender, "paul@x.example", nil, FromNoDomainRecord}, |
| {"malformed from", inst, appSender, "paul", verified, FromNotGranted}, |
| + {"domain became shared", inst, appSender, "paul@x.example", shared, FromAppNotListed}, |
| } { |
| if got := CheckInstanceFrom(c.sn, c.app, c.from, "shop", "eu-west-1", c.dv); got != c.want { |
| t.Errorf("%s: CheckInstanceFrom = %v, want %v", c.name, got, c.want) |
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 212139ad8..c3046f558 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv |
| @@ -1,3 +1,3 @@ |
| # 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, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| -@coverage internal/mailwire a5e1c8d6bf3514d49be52aa27d8bec42450657e3c6f4673f1645dc01395454d2 |
| +@coverage internal/mailwire a080b525495cc7762aa536a015ce961f6263c3e89d69bb115adb5a64978d84d6 |