carlos / platform Public

mail: one stated address invariant, enforced in one place (Task 3 R2)

Astra round 2 on Task 3 found a second ownership P1 (an old grant could
recreate a key after recover and revoke), so stopping rule 2 applies:
rather than a third patch, the record is now the authority and the key
an index. A key blocks only while the sender it names lists the address
(a stale key is taken over by CAS); every key write carries a fresh
nonce, and a sender grants only while the key carries its own nonce. So
no two records grant one address, gate or no gate. Domain sharing is
pinned on the domain record (AddressApp) by CAS and refused in
EnsureDomain's own CAS'd write. Concurrent simulation on the bare store
plus the reviewer's schedules. Round 1 and 2 findings committed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 7fdd2ffcf2c393f850ca025bdcec74e5b7b1f4ae parent d21ea91
8 files changed, +497 −132
  • docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-T3-R1.md +31 −0
  • docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-T3-R2.md +48 −0
  • internal/mail/addresses.go +276 −107
  • internal/mail/addresses_guard_test.go +69 −22
  • internal/mail/addresses_interleave_test.go +54 −0
  • internal/mail/domain.go +7 −0
  • internal/mail/walk.go +8 −0
  • internal/provision/instance_senders_1_census_test.go +4 −3

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-mA0R74
.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/sns v1.43.0
go: downloading golang.org/x/crypto v0.58.0
go: downloading github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.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/route53 v1.64.1
go: downloading golang.org/x/sys v0.49.0
go: downloading github.com/pion/stun/v3 v3.1.5
go: downloading github.com/pion/turn/v4 v4.1.4
go: downloading github.com/pierrec/lz4/v4 v4.1.22
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/pion/transport/v4 v4.0.2
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading github.com/pion/randutil v0.1.0
go: downloading github.com/wlynxg/anet v0.0.5
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 github.com/google/uuid v1.6.0
go: downloading modernc.org/mathutil v1.7.1
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/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-T3-R1.md b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-T3-R1.md
new file mode 100644
index 000000000..cce3eb84d
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-T3-R1.md
@@ -0,0 +1,31 @@
+# Task 3 review, round 1 (Astra, gpt-6-astra, on eb615f8fe)
+
+1. **P1 — Recovery can orphan an address key when `HostClaim` is off.**
+
+ **Evidence:** [addresses.go:483](/home/paulca/amadan.net/carlos/platform-instance-senders-1/internal/mail/addresses.go:483) and `:508` run recovery and grants without serialization for unmarked stores. This is a supported console path: [claim_mail_admitter.go:224](/home/paulca/amadan.net/carlos/platform-instance-senders-1/internal/console/claim_mail_admitter.go:224) returns the bare store when `HostClaim` is false.
+
+ **Failure scenario:** A grant writes `Reserving`, then pauses before creating the key. Concurrent recovery sees no key and removes the reservation ([addresses.go:329](/home/paulca/amadan.net/carlos/platform-instance-senders-1/internal/mail/addresses.go:329), `:359`). The grant resumes and creates the key at `:262`; its final update skips the address because the reservation is gone (`:269`). Both calls succeed, leaving a key that its sender no longer names. Subsequent recovery cannot discover it.
+
+ The same missing serialization permits domain sharing to race with grant preflight: both checks can pass before either operation writes.
+
+ **Invariant broken:** Decision 15’s record-to-key ownership invariant; decision 6’s exclusive-domain condition.
+
+ **Fix:** Enforce shared serialization for address transitions and domain membership changes in every supported mode, or refuse instance-address operations before any write when that serialization is unavailable. Sender-record CAS alone does not protect this multi-object transition.
+
+2. **P2 — The guard never exercises overlapping operations.**
+
+ **Evidence:** [addresses_guard_test.go:143](/home/paulca/amadan.net/carlos/platform-instance-senders-1/internal/mail/addresses_guard_test.go:143) completes each operation before starting the next. The failure wrapper returns an error before the selected write; it never pauses an operation while another runs.
+
+ **Failure scenario:** The grant/recovery overlap above cannot occur in this test, regardless of seed or iteration count. The guard can pass while the required invariant is broken.
+
+ **Invariant broken:** Decision 15’s guard must cover interleavings of grant, revoke and recovery.
+
+ **Fix:** Add deterministic, channel-controlled schedules around reservation, key creation/deletion and final record updates. Include the flag-off production store path and the grant/recovery schedule above; use signals, not sleeps.
+
+No P3 findings.
+
+Within the serialized path, I found no additional issue with refusal ordering, canonical uniqueness, separator rejection or domain-hook placement. The changed census classifications are appropriate: `putAddressClaim` writes an address key rather than an instance record; the `mailwire` change tightens validation and adds no root reads.
+
+Targeted tests could not start: the read-only sandbox prevented Go from creating its build directory. Census tests were therefore not executed. No files were edited.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-T3-R2.md b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-T3-R2.md
new file mode 100644
index 000000000..64ae99e35
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-T3-R2.md
@@ -0,0 +1,48 @@
+# Task 3 review, round 2 (Astra, gpt-6-astra, on d21ea91ae)
+
+Round-1 P1: **Partly resolved.** The original two-call schedule is fixed, but grant/recover/revoke can still orphan a key; domain sharing remains unserialized.
+Round-1 P2: **Partly resolved.** Signal-controlled tests now cover overlaps, but omit the schedule below and bypass public recovery in the revoke/grant test.
+
+1. **P1 — Recovery can finish a reservation while its original writer remains able to recreate the key.**
+
+ **Evidence:** Recovery now creates the key at [addresses.go:368](/home/paulca/amadan.net/carlos/platform-instance-senders-1/internal/mail/addresses.go:368) and moves the reservation into grants at line 386. The original grant still writes its saved `todo` at line 293, then silently skips an absent reservation at line 300.
+
+ **Failure scenario, with HostClaim off:**
+ - Grant reserves address A, then pauses before its key write.
+ - Recovery creates A’s key and moves A into `Grant.Addresses`.
+ - `RevokeAddress` completes: it deletes the key and removes A from the record.
+ - The paused grant resumes, recreates the key, finds no reservation, and returns success.
+
+ The key now names a sender whose record no longer names A. Further recovery sees no pending transition and cannot repair it. This uses the public operations and requires no failed storage operation.
+
+ **Invariant:** Decision 15, every owned key remains named until deletion.
+
+ **Fix:** Require shared serialization for these transitions, or refuse them before writes when serialization is unavailable. Rolling reservations forward does not fence an older writer.
+
+2. **P2 — The new interleaving tests miss the remaining ownership failure.**
+
+ **Evidence:** [addresses_interleave_test.go:109](/home/paulca/amadan.net/carlos/platform-instance-senders-1/internal/mail/addresses_interleave_test.go:109) completes recovery and immediately resumes the grant. At line 153, the revoke/grant test calls the internal grant step specifically to bypass public recovery.
+
+ **Failure scenario:** All added schedules can pass while the P1 schedule above leaves an orphan.
+
+ **Invariant:** Decision 15’s guard must exercise grant/revoke/recovery interleavings.
+
+ **Fix:** Extend the existing paused-grant schedule with a completed public revoke before resuming. Exercise public `GrantAddress` during a paused revoke too, and check the invariant at intermediate boundaries.
+
+3. **P2 — Send-time rejection does not implement the required domain-change refusal.**
+
+ **Evidence:** The replacement justification at [addresses.go:28](/home/paulca/amadan.net/carlos/platform-instance-senders-1/internal/mail/addresses.go:28) relies on [instance.go:154](/home/paulca/amadan.net/carlos/platform-instance-senders-1/internal/mailwire/instance.go:154). The sharing inventory check remains separate from subsequent writes at [walk.go:190](/home/paulca/amadan.net/carlos/platform-instance-senders-1/internal/mail/walk.go:190).
+
+ **Failure scenario:** With HostClaim off, another app passes the empty-inventory check and pauses. A grant completes against the still-exclusive domain. The joining app resumes and shares it. Both operations succeed; the new mailwire check subsequently rejects the instance’s sends.
+
+ **Invariant:** Decision 6 requires sharing to be refused up front while addresses depend on the domain. Rejecting subsequent mail does not satisfy that requirement.
+
+ **Fix:** Serialize domain membership changes with address transitions, or refuse address operations without that protection.
+
+No P3 findings. The mailwire change tightens authorization and adds no root reads; its envelope re-pin is appropriate. I found no new canonicalization or gated refusal-ordering defect.
+
+Focused tests could not start: Go attempted to update `go.mod`, which the read-only sandbox rejected. No files were edited.
+
+This is the second round in the same ownership-invariant fault family, so stopping rule 2 applies. Choose refusal without serialization, removal of that unsupported mode, or one centrally enforced invariant with a guard. I recommend refusal without serialization.
+
+**NOT READY**
\ No newline at end of file
diff --git a/internal/mail/addresses.go b/internal/mail/addresses.go
index 436de8c9e..64b146c7c 100644
--- a/internal/mail/addresses.go
+++ b/internal/mail/addresses.go
@@ -3,35 +3,45 @@ package mail
// Instance senders' address grants (instance senders design, decisions 6
// and 15, docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md).
//
-// THE INVARIANT: every address key a sender owns is named on its record
-// (Grant.Addresses, Reserving or Releasing) until the key is gone. This
-// file is the only writer of those three lists and of the keys. A grant
-// moves an address Reserving → key written → Grant.Addresses; a revoke
-// moves it Grant.Addresses → Releasing → key deleted → gone. A crash at
-// any point leaves the address named on the record, so RecoverAddresses
-// can always finish the step, and a key whose body names another sender is
-// never deleted. The mailer honours only Grant.Addresses.
+// THE INVARIANT, enforced in one place (claimAddressKey and the grant's
+// final step): NO TWO SENDER RECORDS EVER GRANT ONE ADDRESS. The sender
+// record is the authority; the address key is an index that makes the
+// check cheap, under two rules:
+//
+// 1. A key blocks a grant only while the sender it names LISTS the
+// address (Grant.Addresses, Reserving or Releasing). A key whose sender
+// lists nothing is stale, and a new holder takes it over by CAS on its
+// etag. A stale key is therefore garbage, never authority.
+// 2. Every write of a key carries a fresh nonce, so its etag always
+// changes, and a sender moves an address from Reserving into
+// Grant.Addresses only after re-reading the key and finding its own
+// latest nonce. Two senders racing one address are serialized by the
+// key's etag; the loser re-reads, finds the winner listing it, and is
+// refused.
+//
+// A grant moves an address Reserving → key claimed → Grant.Addresses; a
+// revoke moves it Grant.Addresses → Releasing → own key deleted → gone; a
+// grant refuses an address still Releasing (ErrAddressPending), so a
+// release never deletes a key under a fresh grant. Recovery finishes every
+// pending step forward. None of this rests on the mail claim gate, which a
+// console without HostClaim does not have (claimMailStore returns the bare
+// store): each rule holds under any interleaving. The mailer honours only
+// Grant.Addresses.
//
// Every refusal is decided READ-ONLY before the first write of its
-// admitted call: the mail claim gate retains itself when an admitted call
-// 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.
+// admitted call: under the gate, an admitted call that fails after any
+// write retains the gate (claim_gate.go:425-427). 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.
+// Domain sharing (decision 6) is pinned on the domain record itself:
+// AddressApp is set by CAS before an address is reserved, and EnsureDomain
+// refuses another app in the same CAS'd write that would add it. The
+// mailer also sends an address only from a domain its app holds alone.
import (
"context"
+ "crypto/rand"
+ "encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -73,10 +83,14 @@ var (
// 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.
- errAddressClaimMismatch = errors.New("mail: address key changed under the gate")
+ // errAddressClaimMismatch is an address another live sender claimed
+ // between the read-only check and the write. Only possible without the
+ // mail claim gate; under it, it is an inconsistency and correctly
+ // retains the gate.
+ errAddressClaimMismatch = fmt.Errorf("mail: claimed by another sender meanwhile: %w", ErrAddressTaken)
+ // errAddressConcurrent is a grant whose address a concurrent call
+ // finished or revoked first. Only possible without the gate.
+ errAddressConcurrent = errors.New("mail: address changed by a concurrent call")
)
// AddressesInUseError is ErrAddressesInUse with what a door names: the
@@ -87,6 +101,9 @@ type AddressesInUseError struct {
}
func (e *AddressesInUseError) Error() string {
+ if e.Count <= 0 {
+ return fmt.Sprintf("mail: %s is held for one app's instance addresses", e.Domain)
+ }
return fmt.Sprintf("mail: %d instance address(es) use %s", e.Count, e.Domain)
}
@@ -96,6 +113,8 @@ func (e *AddressesInUseError) Is(target error) bool { return target == ErrAddres
// addressClaim is the body at AddressKey.
type addressClaim struct {
Sender string `json:"sender"`
+ // Nonce changes on every write, so the key's etag always does (rule 2).
+ Nonce string `json:"nonce,omitempty"`
}
// AddressKey is the uniqueness key of one canonical address in one app.
@@ -122,6 +141,127 @@ func readAddressClaim(ctx context.Context, s release.Store, key string) (sender,
return c.Sender, etag, true, nil
}
+// readAddressClaimFull is readAddressClaim with the key's nonce.
+func readAddressClaimFull(ctx context.Context, s release.Store, key string) (addressClaim, string, bool, error) {
+ raw, etag, err := s.Get(ctx, key)
+ if errors.Is(err, os.ErrNotExist) {
+ return addressClaim{}, "", false, nil
+ }
+ if err != nil {
+ return addressClaim{}, "", false, err
+ }
+ var c addressClaim
+ if err := json.Unmarshal(raw, &c); err != nil {
+ return addressClaim{}, "", false, fmt.Errorf("mail: %s: %w", key, err)
+ }
+ return c, etag, true, nil
+}
+
+// lists reports whether a sender record names the address anywhere.
+func lists(sn *Sender, c string) bool {
+ return sn != nil && (slices.Contains(sn.Reserving, c) || slices.Contains(sn.Releasing, c) ||
+ (sn.Grant != nil && slices.Contains(sn.Grant.Addresses, c)))
+}
+
+// liveHolder reports whether the key's sender (other than id) still lists
+// the address, which is what makes its key block (rule 1).
+func liveHolder(ctx context.Context, s release.Store, acct, app, holder, c string) (bool, error) {
+ if holder == "" || !ValidSenderID(holder) {
+ return false, nil
+ }
+ sn, _, err := GetSender(ctx, s, acct, app, holder)
+ if err != nil {
+ return false, err
+ }
+ return lists(sn, c), nil
+}
+
+func newNonce() (string, error) {
+ var b [12]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(b[:]), nil
+}
+
+// claimAddressKey is the ONE writer of address keys: it makes the key name
+// id with a fresh nonce, creating it, rewriting this sender's own key, or
+// taking over a stale one, each by CAS. It returns the nonce written, or
+// errAddressClaimMismatch when another sender that still lists the
+// address holds the key.
+func claimAddressKey(ctx context.Context, s release.Store, acct, app, id, c string) (string, error) {
+ key := AddressKey(acct, app, c)
+ for attempt := 0; attempt < 8; attempt++ {
+ cur, etag, exists, err := readAddressClaimFull(ctx, s, key)
+ if err != nil {
+ return "", err
+ }
+ if exists && cur.Sender != id {
+ live, err := liveHolder(ctx, s, acct, app, cur.Sender, c)
+ if err != nil {
+ return "", err
+ }
+ if live {
+ return "", fmt.Errorf("%s: %w", c, errAddressClaimMismatch)
+ }
+ }
+ nonce, err := newNonce()
+ if err != nil {
+ return "", err
+ }
+ body, err := json.Marshal(addressClaim{Sender: id, Nonce: nonce})
+ if err != nil {
+ return "", err
+ }
+ if _, err := s.Put(ctx, key, body, etag); err != nil {
+ if errors.Is(err, release.ErrCASConflict) {
+ continue
+ }
+ return "", err
+ }
+ return nonce, nil
+ }
+ return "", fmt.Errorf("mail: %s: address key kept changing: %w", c, release.ErrCASConflict)
+}
+
+// keyCarries reports whether the key still carries this sender's nonce.
+func keyCarries(ctx context.Context, s release.Store, acct, app, id, c, nonce string) (bool, error) {
+ cur, _, exists, err := readAddressClaimFull(ctx, s, AddressKey(acct, app, c))
+ if err != nil {
+ return false, err
+ }
+ return exists && cur.Sender == id && cur.Nonce == nonce, nil
+}
+
+// pinDomainForAddresses sets the domain record's AddressApp to app by CAS,
+// refusing a domain any other app holds or is pinned to (decision 6).
+func pinDomainForAddresses(ctx context.Context, s release.Store, acct, app, domain string) error {
+ for attempt := 0; attempt < 8; attempt++ {
+ rec, etag, err := GetDomain(ctx, s, acct, domain)
+ if err != nil {
+ return err
+ }
+ if rec == nil {
+ return fmt.Errorf("%s: %w", domain, ErrAddressDomainNotApp)
+ }
+ if len(rec.Apps) != 1 || rec.Apps[0] != app || (rec.AddressApp != "" && rec.AddressApp != app) {
+ return fmt.Errorf("%s: %w", domain, ErrAddressDomainShared)
+ }
+ if rec.AddressApp == app {
+ return nil
+ }
+ rec.AddressApp = app
+ if _, err := claimUnserializedPutDomain(ctx, s, acct, rec, etag); err != nil {
+ if errors.Is(err, release.ErrCASConflict) {
+ continue
+ }
+ return err
+ }
+ return nil
+ }
+ return fmt.Errorf("mail: %s: domain record kept changing: %w", domain, release.ErrCASConflict)
+}
+
// getInstanceSender reads an instance sender; nil with no error when absent.
func getInstanceSender(ctx context.Context, s release.Store, acct, app, id string) (*Sender, string, error) {
sn, etag, err := GetSender(ctx, s, acct, app, id)
@@ -233,7 +373,7 @@ func preflightGrants(ctx context.Context, s release.Store, acct, app, id string,
if rec == nil {
return fmt.Errorf("%s: %w", c, ErrAddressDomainNotApp)
}
- if len(rec.Apps) != 1 || rec.Apps[0] != app {
+ if len(rec.Apps) != 1 || rec.Apps[0] != app || (rec.AddressApp != "" && rec.AddressApp != app) {
return fmt.Errorf("%s: %w", c, ErrAddressDomainShared)
}
holder, _, exists, err := readAddressClaim(ctx, s, AddressKey(acct, app, c))
@@ -241,7 +381,13 @@ func preflightGrants(ctx context.Context, s release.Store, acct, app, id string,
return err
}
if exists && holder != id {
- return fmt.Errorf("%s: %w", c, ErrAddressTaken)
+ live, err := liveHolder(ctx, s, acct, app, holder, c)
+ if err != nil {
+ return err
+ }
+ if live {
+ return fmt.Errorf("%s: %w", c, ErrAddressTaken)
+ }
}
}
return nil
@@ -252,11 +398,21 @@ func preflightGrants(ctx context.Context, s release.Store, acct, app, id string,
// that turns out to name another sender here changed under the gate and is
// 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 domains []string
+ for _, c := range canonical {
+ if d := addressDomain(c); !slices.Contains(domains, d) {
+ domains = append(domains, d)
+ }
+ }
+ for _, d := range domains {
+ if err := pinDomainForAddresses(ctx, s, acct, app, d); err != nil {
+ return nil, err
+ }
+ }
var todo []string
var pending error
- sn, err := mutateSender(ctx, s, acct, app, id, func(sn *Sender) bool {
- todo = todo[:0]
- pending = nil
+ if _, err := mutateSender(ctx, s, acct, app, id, func(sn *Sender) bool {
+ todo, pending = todo[:0], nil
changed := false
for _, c := range canonical {
if sn.Grant != nil && slices.Contains(sn.Grant.Addresses, c) {
@@ -275,28 +431,53 @@ func grantPreflighted(ctx context.Context, s release.Store, acct, app, id string
todo = append(todo, c)
}
return changed
- })
- if err != nil {
+ }); err != nil {
return nil, err
}
if pending != nil {
return nil, pending
}
- if len(todo) == 0 {
- return sn, nil
- }
- body, err := json.Marshal(addressClaim{Sender: id})
- if err != nil {
- return nil, err
- }
+ return finishReservations(ctx, s, acct, app, id, todo)
+}
+
+// finishReservations claims each reserved address's key, then, in one
+// CAS, grants the ones whose key still carries this sender's own nonce and
+// drops the ones another live sender holds. It is the grant's and
+// recovery's shared last step: rule 2 lives here. A key that names this
+// sender with another nonce means a concurrent call of the same sender
+// (recovery, or a retry) is finishing it: the address is left reserved for
+// that call. An address granted by the end is success, however it got
+// there; one lost to another sender is errAddressClaimMismatch; one still
+// pending or gone is errAddressConcurrent.
+func finishReservations(ctx context.Context, s release.Store, acct, app, id string, todo []string) (*Sender, error) {
+ won := map[string]string{}
+ var lost []string
for _, c := range todo {
- if err := putAddressClaim(ctx, s, acct, app, id, c, body); err != nil {
+ nonce, err := claimAddressKey(ctx, s, acct, app, id, c)
+ switch {
+ case err == nil:
+ won[c] = nonce
+ case errors.Is(err, errAddressClaimMismatch):
+ lost = append(lost, c)
+ default:
return nil, err
}
}
- return mutateSender(ctx, s, acct, app, id, func(sn *Sender) bool {
+ // Re-read every won key just before the CAS. While the address stays in
+ // Reserving, no other sender can take the key (rule 1), so a key that no
+ // longer carries this nonce was rewritten by this same sender.
+ for c, nonce := range won {
+ ok, err := keyCarries(ctx, s, acct, app, id, c, nonce)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ delete(won, c)
+ }
+ }
+ sn, err := mutateSender(ctx, s, acct, app, id, func(sn *Sender) bool {
changed := false
- for _, c := range todo {
+ for c := range won {
if !slices.Contains(sn.Reserving, c) {
continue
}
@@ -309,27 +490,30 @@ func grantPreflighted(ctx context.Context, s release.Store, acct, app, id string
}
changed = true
}
+ for _, c := range lost {
+ if slices.Contains(sn.Reserving, c) {
+ sn.Reserving = without(sn.Reserving, c)
+ changed = true
+ }
+ }
return changed
})
-}
-
-// putAddressClaim creates the key; an existing key naming this sender is
-// success.
-func putAddressClaim(ctx context.Context, s release.Store, acct, app, id, c string, body []byte) error {
- key := AddressKey(acct, app, c)
- if _, err := s.Put(ctx, key, body, ""); err == nil {
- return nil
- } else if !errors.Is(err, release.ErrCASConflict) {
- return err
- }
- holder, _, exists, err := readAddressClaim(ctx, s, key)
if err != nil {
- return err
+ return nil, err
}
- if !exists || holder != id {
- return fmt.Errorf("%s: %w", c, errAddressClaimMismatch)
+ var notGranted []string
+ for _, c := range todo {
+ if (sn.Grant == nil || !slices.Contains(sn.Grant.Addresses, c)) && !slices.Contains(lost, c) {
+ notGranted = append(notGranted, c)
+ }
}
- return nil
+ if len(lost) > 0 {
+ return sn, fmt.Errorf("%s: %w", strings.Join(lost, ", "), errAddressClaimMismatch)
+ }
+ if len(notGranted) > 0 {
+ return sn, fmt.Errorf("%s: %w", strings.Join(notGranted, ", "), errAddressConcurrent)
+ }
+ return sn, nil
}
// deleteOwnAddressClaim deletes the key only when it names this sender, by
@@ -344,13 +528,9 @@ func deleteOwnAddressClaim(ctx context.Context, s release.Store, acct, app, id,
}
// 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.
+// forward: each Reserving address goes through finishReservations (its key
+// claimed, then granted or dropped), and each Releasing address has its own
+// key deleted and is dropped. 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 {
@@ -359,55 +539,37 @@ func claimUnserializedRecoverAddresses(ctx context.Context, s release.Store, acc
if len(sn.Reserving) == 0 && len(sn.Releasing) == 0 {
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 {
- switch err := putAddressClaim(ctx, s, acct, app, id, c, body); {
- case err == nil:
- grant = append(grant, c)
- case errors.Is(err, errAddressClaimMismatch):
- drop = append(drop, c)
- default:
- return nil, err
- }
- }
releasing := slices.Clone(sn.Releasing)
for _, c := range releasing {
if err := deleteOwnAddressClaim(ctx, s, acct, app, id, c); err != nil {
return nil, err
}
}
- return mutateSender(ctx, s, acct, app, id, func(sn *Sender) bool {
- changed := false
- for _, c := range grant {
- if slices.Contains(sn.Reserving, c) {
- sn.Reserving = without(sn.Reserving, c)
- if sn.Grant == nil {
- sn.Grant = &GrantBlock{}
+ if len(releasing) > 0 {
+ if sn, err = mutateSender(ctx, s, acct, app, id, func(sn *Sender) bool {
+ changed := false
+ for _, c := range releasing {
+ if slices.Contains(sn.Releasing, c) {
+ sn.Releasing = without(sn.Releasing, c)
+ changed = true
}
- if !slices.Contains(sn.Grant.Addresses, c) {
- sn.Grant.Addresses = append(sn.Grant.Addresses, c)
- }
- changed = true
- }
- }
- for _, c := range drop {
- if slices.Contains(sn.Reserving, c) {
- sn.Reserving = without(sn.Reserving, c)
- changed = true
- }
- }
- for _, c := range releasing {
- if slices.Contains(sn.Releasing, c) {
- sn.Releasing = without(sn.Releasing, c)
- changed = true
}
+ return changed
+ }); err != nil {
+ return nil, err
}
- return changed
- })
+ }
+ if len(sn.Reserving) == 0 {
+ return sn, nil
+ }
+ out, err := finishReservations(ctx, s, acct, app, id, slices.Clone(sn.Reserving))
+ // Recovery's job is done when nothing is pending: losing an address to
+ // another sender, or finding it finished by a concurrent call, is the
+ // outcome, not a failure.
+ if errors.Is(err, errAddressClaimMismatch) || errors.Is(err, errAddressConcurrent) {
+ return out, nil
+ }
+ return out, err
}
// claimUnserializedGrantAddresses grants a batch to an existing sender:
@@ -491,6 +653,13 @@ func refuseDomainShareWhileAddressesUse(ctx context.Context, s release.Store, ac
if err != nil || rec == nil || slices.Contains(rec.Apps, app) {
return err
}
+ if rec.AddressApp != "" && rec.AddressApp != app {
+ n, err := addressesUseDomain(ctx, s, acct, rec.AddressApp, domain)
+ if err != nil {
+ return err
+ }
+ return &AddressesInUseError{Domain: domain, Count: n}
+ }
for _, other := range rec.Apps {
n, err := addressesUseDomain(ctx, s, acct, other, domain)
if err != nil {
diff --git a/internal/mail/addresses_guard_test.go b/internal/mail/addresses_guard_test.go
index 0ee988744..cd46970ed 100644
--- a/internal/mail/addresses_guard_test.go
+++ b/internal/mail/addresses_guard_test.go
@@ -67,22 +67,20 @@ var guardOps = map[string]guardOp{
},
}
-// checkAddressInvariant: every address key names a sender whose record
-// lists the address (granted, reserving or releasing), or is absent; no
-// address is granted to two senders.
+// checkAddressInvariant is decision 15's invariant as enforced: no address
+// is granted to two records, and every granted address's key names its
+// holder (so no other sender can take it over). A key naming a sender that
+// lists nothing is stale and allowed: it never blocks (checked by
+// checkStaleKeysDoNotBlock).
func checkAddressInvariant(t *testing.T, s release.Store, ids, addrs []string, trace string) {
t.Helper()
ctx := context.Background()
- recs := map[string]*Sender{}
+ grantedBy := map[string]string{}
for _, id := range ids {
sn, _, err := GetSender(ctx, s, tAcct, tApp, id)
if err != nil {
t.Fatalf("%s: read %s: %v", trace, id, err)
}
- recs[id] = sn
- }
- grantedBy := map[string]string{}
- for id, sn := range recs {
if sn == nil || sn.Grant == nil {
continue
}
@@ -94,24 +92,16 @@ func checkAddressInvariant(t *testing.T, s release.Store, ids, addrs []string, t
}
}
for _, a := range addrs {
+ id, granted := grantedBy[a]
+ if !granted {
+ continue
+ }
holder, _, exists, err := readAddressClaim(ctx, s, AddressKey(tAcct, tApp, a))
if err != nil {
t.Fatalf("%s: %v", trace, err)
}
- if !exists {
- if id, ok := grantedBy[a]; ok {
- t.Fatalf("%s: %s granted to %s with no key", trace, a, id)
- }
- continue
- }
- sn := recs[holder]
- if sn == nil {
- t.Fatalf("%s: key %s names %s, which has no record", trace, a, holder)
- }
- named := slices.Contains(sn.Reserving, a) || slices.Contains(sn.Releasing, a) ||
- (sn.Grant != nil && slices.Contains(sn.Grant.Addresses, a))
- if !named {
- t.Fatalf("%s: key %s names %s, whose record does not list it: %+v", trace, a, holder, sn)
+ if !exists || holder != id {
+ t.Fatalf("%s: %s granted to %s but its key names %q (exists %v)", trace, a, id, holder, exists)
}
}
}
@@ -170,3 +160,60 @@ func errString(err error) string {
}
func itoa(n int) string { return strconv.Itoa(n) }
+
+// TestAddressConcurrentSimulation is decision 15's randomized simulation on
+// the bare store (no mail claim gate, as a console without HostClaim runs):
+// goroutines race grant, revoke and recover over two senders and two
+// addresses. At quiescence, after recovery, the invariant holds, nothing is
+// pending, and a stale key never blocks: each ungranted address can be
+// granted to either sender.
+func TestAddressConcurrentSimulation(t *testing.T) {
+ seed := time.Now().UnixNano()
+ t.Logf("seed %d", seed)
+ ids := []string{"a.shop.example", "b.shop.example"}
+ addrs := []string{"p@x.example", "q@x.example"}
+ names := []string{"grant", "grant", "revoke", "recover"}
+ for round := 0; round < 30; round++ {
+ base := release.NewDirStore(t.TempDir())
+ addrFixture(t, base)
+ var wg sync.WaitGroup
+ for w := 0; w < 4; w++ {
+ rng := rand.New(rand.NewSource(seed + int64(round*10+w)))
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 6; i++ {
+ _ = guardOps[names[rng.Intn(len(names))]](context.Background(), base, ids[rng.Intn(2)], addrs[rng.Intn(2)])
+ }
+ }()
+ }
+ wg.Wait()
+ trace := "round " + strconv.Itoa(round)
+ checkAddressInvariant(t, base, ids, addrs, trace)
+ for _, id := range ids {
+ sn, err := RecoverAddresses(context.Background(), base, tAcct, tApp, id)
+ if err != nil {
+ t.Fatalf("%s: recover %s: %v", trace, id, err)
+ }
+ if len(sn.Reserving) != 0 || len(sn.Releasing) != 0 {
+ t.Fatalf("%s: %s still pending after recovery: %+v", trace, id, sn)
+ }
+ }
+ checkAddressInvariant(t, base, ids, addrs, trace+" recovered")
+ for _, a := range addrs {
+ granted := false
+ for _, id := range ids {
+ if sn := senderOf(t, base, id); sn.Grant != nil && slices.Contains(sn.Grant.Addresses, a) {
+ granted = true
+ }
+ }
+ if granted {
+ continue
+ }
+ if _, err := GrantAddress(context.Background(), base, tAcct, tApp, ids[round%2], a, time.Now()); err != nil {
+ t.Fatalf("%s: free address %s blocked: %v", trace, a, err)
+ }
+ }
+ checkAddressInvariant(t, base, ids, addrs, trace+" free addresses granted")
+ }
+}
diff --git a/internal/mail/addresses_interleave_test.go b/internal/mail/addresses_interleave_test.go
index aac00345d..6f0122a29 100644
--- a/internal/mail/addresses_interleave_test.go
+++ b/internal/mail/addresses_interleave_test.go
@@ -188,3 +188,57 @@ func TestInterleaveTwoSendersRace(t *testing.T) {
t.Fatalf("loser a: %+v", sn)
}
}
+
+// Round 2's P1 schedule: a grant paused before its key write; recovery
+// grants the address; a revoke completes; the old grant resumes and writes
+// a key naming a sender that lists nothing. That key is stale: it must not
+// block another sender, and nothing is granted twice.
+func TestInterleaveOldGrantAfterRecoverAndRevoke(t *testing.T) {
+ ctx := context.Background()
+ 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(ctx, base, tAcct, tApp, "a.shop.example"); err != nil {
+ t.Fatal(err)
+ }
+ checkAddressInvariant(t, base, ilIDs, ilAddrs, "after recover")
+ if _, err := RevokeAddress(ctx, base, tAcct, tApp, "a.shop.example", "p@x.example", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ checkAddressInvariant(t, base, ilIDs, ilAddrs, "after revoke")
+ _ = finish(t, p, done) // its outcome is not the point; the state is
+ checkAddressInvariant(t, base, ilIDs, ilAddrs, "after the old grant resumed")
+ if sn := senderOf(t, base, "a.shop.example"); sn.Grant != nil && len(sn.Grant.Addresses) != 0 {
+ t.Fatalf("the revoked address came back: %+v", sn.Grant)
+ }
+ // Whatever key the old grant left, it does not block b.
+ if _, err := GrantAddress(ctx, base, tAcct, tApp, "b.shop.example", "p@x.example", time.Now()); err != nil {
+ t.Fatalf("b blocked by a stale key: %v", err)
+ }
+ checkAddressInvariant(t, base, ilIDs, ilAddrs, "b granted")
+}
+
+// The public GrantAddress during a paused revoke: its recovery finishes the
+// release first, then it grants; the revoke's late delete cannot remove the
+// new key (its etag changed), and the invariant holds at every boundary.
+func TestInterleavePublicGrantDuringPausedRevoke(t *testing.T) {
+ ctx := context.Background()
+ base := release.NewDirStore(t.TempDir())
+ addrFixture(t, base)
+ if _, err := GrantAddress(ctx, 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(ctx, s, tAcct, tApp, "a.shop.example", "p@x.example", time.Now())
+ return err
+ })
+ checkAddressInvariant(t, base, ilIDs, ilAddrs, "revoke parked")
+ if _, err := GrantAddress(ctx, base, tAcct, tApp, "a.shop.example", "p@x.example", time.Now()); err != nil {
+ t.Fatalf("grant during a paused revoke: %v", err)
+ }
+ checkAddressInvariant(t, base, ilIDs, ilAddrs, "re-granted")
+ _ = finish(t, p, done)
+ checkAddressInvariant(t, base, ilIDs, ilAddrs, "revoke resumed")
+}
diff --git a/internal/mail/domain.go b/internal/mail/domain.go
index 754468b71..58ad424ee 100644
--- a/internal/mail/domain.go
+++ b/internal/mail/domain.go
@@ -67,6 +67,13 @@ type DomainRecord struct {
Apps []string `json:"apps"`
Regions map[string]*RegionState `json:"regions"`
CreatedAt time.Time `json:"created_at"`
+ // AddressApp pins the domain to the one app whose instance senders hold
+ // address grants on it (instance senders decision 6). Set by CAS on this
+ // record before an address is reserved, and read by EnsureDomain in the
+ // same CAS'd read-modify-write that adds an app, so a domain can never
+ // become shared under address grants, gate or no gate. Sticky: it clears
+ // only with the record. Additive.
+ AddressApp string `json:"address_app,omitempty"`
}
func DomainsPrefix(acct string) string { return "accounts/" + acct + "/email/domains/" }
diff --git a/internal/mail/walk.go b/internal/mail/walk.go
index 0c81e3eaa..74375a247 100644
--- a/internal/mail/walk.go
+++ b/internal/mail/walk.go
@@ -223,6 +223,14 @@ func claimUnserializedEnsureDomain(ctx context.Context, s release.Store, p Provi
if rec.Regions == nil {
rec.Regions = map[string]*RegionState{}
}
+ // The share refusal, in the CAS'd read-modify-write itself (instance
+ // senders decision 6): a domain pinned to another app's instance
+ // addresses is never joined. The read-only check above answers the
+ // serialized case before any write; this answers a race without the
+ // mail claim gate, where PutDomain's etag makes it atomic.
+ if rec.AddressApp != "" && rec.AddressApp != app {
+ return nil, nil, &AddressesInUseError{Domain: domain}
+ }
rec.AddApp(app)
// WHOSE IDENTITY IS IT (#216). SES identities are per AWS account, and
diff --git a/internal/provision/instance_senders_1_census_test.go b/internal/provision/instance_senders_1_census_test.go
index 0e08a421d..e927ad7a4 100644
--- a/internal/provision/instance_senders_1_census_test.go
+++ b/internal/provision/instance_senders_1_census_test.go
@@ -12,10 +12,11 @@ package provision
func instanceSenders1WriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), instanceUsageWriteCensusInventory()...)
reviewed := []censusEntry{
- // The address uniqueness key: one create-only Put of
+ // The address uniqueness key: claimAddressKey's one Put of
// apps/<account>/<app>/email/addresses/<canonical>.json
- // (mail.AddressKey). Not a record key.
- {"internal/mail/addresses.go", "putAddressClaim", "nonrecord", "sel:Put", "36a56ac3be1e5bc7cb1cbf4061f6e9a303017233815dcccfb7a50938bf522dcd"},
+ // (mail.AddressKey), conditional on the etag it read (create-only
+ // when absent). Not a record key.
+ {"internal/mail/addresses.go", "claimAddressKey", "nonrecord", "sel:Put", "3fe6cf3dcebeba663fd5d3f4925baa8c15240ac29572b09a57d271611f655a15"},
}
for _, r := range reviewed {
replaced := false