mail: address reservations with a stated invariant and guard
Slice 1 Task 3 (#148, decisions 6 and 15): GrantAddress, RevokeAddress and RecoverAddresses keep every address key named on its sender's record until the key is gone; refusals are decided read-only before any write; EnsureDomain and RemoveDomain refuse while instance addresses use the domain. CanonicalAddress also refuses "/" and quoted local parts (the address becomes a key segment). Randomized failure-injection guard. Record-write census entry for the address key.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+1,056
−3
internal/mail/addresses.go+544 −0internal/mail/addresses_guard_test.go+172 −0internal/mail/addresses_test.go+284 −0internal/mail/walk.go+10 −0internal/mailwire/instance.go+7 −1internal/mailwire/instance_test.go+4 −0internal/provision/instance_senders_1_census_test.go+33 −0internal/provision/plan9_b8_census_test.go+1 −1internal/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-JuwjjA .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/smithy-go v1.28.1 go: downloading github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5 go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e go: downloading golang.org/x/net v0.62.0 go: downloading github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0 go: downloading modernc.org/sqlite v1.55.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/acm v1.45.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/resourcegroupstaggingapi v1.37.0 go: downloading golang.org/x/sys v0.49.0 go: downloading github.com/oschwald/maxminddb-golang v1.13.1 go: downloading github.com/pion/logging v0.2.4 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/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/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14 go: downloading github.com/pion/dtls/v3 v3.1.4 go: downloading github.com/pion/transport/v4 v4.0.2 go: downloading github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 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 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 amadan: job cancelled — a newer push superseded it
diff --git a/internal/mail/addresses.go b/internal/mail/addresses.go| new file mode 100644 |
| index 000000000..58cd8e704 |
| --- /dev/null |
| +++ b/internal/mail/addresses.go |
| @@ -0,0 +1,544 @@ |
| +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. |
| +// |
| +// 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. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "slices" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/mailwire" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// MaxSenderAddresses bounds one instance sender's address grants |
| +// (decision 12). |
| +const MaxSenderAddresses = 50 |
| + |
| +var ( |
| + // ErrAddressTaken is a grant of an address another sender of the app |
| + // holds. Deliberately neutral: it never names the holder. |
| + ErrAddressTaken = errors.New("mail: that address is already in use") |
| + // ErrAddressDomainShared is a grant on a domain whose record lists any |
| + // app but this one (decision 6, refused up front). |
| + ErrAddressDomainShared = errors.New("mail: the address's domain is shared with another app") |
| + // ErrAddressDomainNotApp is a grant on a domain the app sender is not |
| + // granted, or that has no domain record. |
| + ErrAddressDomainNotApp = errors.New("mail: the address's domain is not one this app sends from") |
| + // ErrTooManyAddresses is a grant past MaxSenderAddresses. |
| + ErrTooManyAddresses = errors.New("mail: too many addresses on one sender") |
| + // ErrAddressesInUse is the refusal of a domain change while instance |
| + // address grants depend on the domain; AddressesInUseError carries the |
| + // count. |
| + ErrAddressesInUse = errors.New("mail: instance addresses use this domain") |
| + // ErrSenderRemoving is a grant to, or a create of, a sender whose |
| + // removal has begun. Revoke and recover stay allowed: removal needs them. |
| + ErrSenderRemoving = errors.New("mail: the sender is being removed") |
| + // ErrNoSuchSender is an address change on an instance sender that does |
| + // not exist. |
| + ErrNoSuchSender = errors.New("mail: no such instance sender") |
| + // 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") |
| +) |
| + |
| +// AddressesInUseError is ErrAddressesInUse with what a door names: the |
| +// domain and how many grants, reservations and releases use it. |
| +type AddressesInUseError struct { |
| + Domain string |
| + Count int |
| +} |
| + |
| +func (e *AddressesInUseError) Error() string { |
| + return fmt.Sprintf("mail: %d instance address(es) use %s", e.Count, e.Domain) |
| +} |
| + |
| +// Is makes errors.Is(err, ErrAddressesInUse) hold. |
| +func (e *AddressesInUseError) Is(target error) bool { return target == ErrAddressesInUse } |
| + |
| +// addressClaim is the body at AddressKey. |
| +type addressClaim struct { |
| + Sender string `json:"sender"` |
| +} |
| + |
| +// AddressKey is the uniqueness key of one canonical address in one app. |
| +// Inside the app prefix, so release.PurgeApp sweeps it (decision 6). The |
| +// caller passes a canonical address (mailwire.CanonicalAddress), which can |
| +// contain no "/". |
| +func AddressKey(acct, app, canonical string) string { |
| + return release.AppPrefix(acct, app) + "email/addresses/" + canonical + ".json" |
| +} |
| + |
| +// readAddressClaim reads one address key. exists is false for an absent key. |
| +func readAddressClaim(ctx context.Context, s release.Store, key string) (sender, etag string, exists bool, err error) { |
| + raw, etag, err := s.Get(ctx, key) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return "", "", false, nil |
| + } |
| + if err != nil { |
| + return "", "", false, err |
| + } |
| + var c addressClaim |
| + if err := json.Unmarshal(raw, &c); err != nil { |
| + return "", "", false, fmt.Errorf("mail: %s: %w", key, err) |
| + } |
| + return c.Sender, etag, true, nil |
| +} |
| + |
| +// 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) |
| + if err != nil || sn == nil { |
| + return nil, "", err |
| + } |
| + if sn.Scope != ScopeInstance { |
| + return nil, "", fmt.Errorf("mail: %s/%s/%s is not an instance sender: %w", acct, app, id, ErrNoSuchSender) |
| + } |
| + return sn, etag, nil |
| +} |
| + |
| +// mutateSender applies edit to the instance sender under CAS, re-reading on |
| +// a conflict. edit reports whether it changed anything; nothing is written |
| +// when it did not. |
| +func mutateSender(ctx context.Context, s release.Store, acct, app, id string, edit func(*Sender) bool) (*Sender, error) { |
| + for attempt := 0; attempt < 8; attempt++ { |
| + sn, etag, err := getInstanceSender(ctx, s, acct, app, id) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if sn == nil { |
| + return nil, ErrNoSuchSender |
| + } |
| + if !edit(sn) { |
| + return sn, nil |
| + } |
| + if _, err := claimUnserializedPutSender(ctx, s, acct, app, sn, etag); err != nil { |
| + if errors.Is(err, release.ErrCASConflict) { |
| + continue |
| + } |
| + return nil, err |
| + } |
| + return sn, nil |
| + } |
| + return nil, fmt.Errorf("mail: %s/%s/%s: sender kept changing: %w", acct, app, id, release.ErrCASConflict) |
| +} |
| + |
| +func without(list []string, v string) []string { |
| + return slices.DeleteFunc(slices.Clone(list), func(x string) bool { return x == v }) |
| +} |
| + |
| +func addressDomain(canonical string) string { |
| + return canonical[strings.LastIndexByte(canonical, '@')+1:] |
| +} |
| + |
| +// canonicalAll canonicalises and de-duplicates a batch, in order. |
| +func canonicalAll(addresses []string) ([]string, error) { |
| + var out []string |
| + for _, a := range addresses { |
| + c, err := mailwire.CanonicalAddress(a) |
| + if err != nil { |
| + return nil, fmt.Errorf("%q: %w", a, err) |
| + } |
| + if !slices.Contains(out, c) { |
| + out = append(out, c) |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +// preflightGrants makes every refusal of a batch grant, read-only: the |
| +// sender (absent is allowed: a create is about to write it) is not being |
| +// removed; the batch fits the limit; each address's domain is granted to |
| +// the app sender and held by this app alone; no key names another sender. |
| +// An address already granted to this sender is not counted again. |
| +func preflightGrants(ctx context.Context, s release.Store, acct, app, id string, canonical []string) error { |
| + sn, _, err := getInstanceSender(ctx, s, acct, app, id) |
| + if err != nil { |
| + return err |
| + } |
| + var held []string |
| + if sn != nil { |
| + if sn.Removing != nil { |
| + return ErrSenderRemoving |
| + } |
| + if sn.Grant != nil { |
| + held = append(held, sn.Grant.Addresses...) |
| + } |
| + held = append(held, sn.Reserving...) |
| + } |
| + total := len(held) |
| + for _, c := range canonical { |
| + if !slices.Contains(held, c) { |
| + total++ |
| + } |
| + } |
| + if total > MaxSenderAddresses { |
| + return ErrTooManyAddresses |
| + } |
| + appSender, _, err := GetSender(ctx, s, acct, app, SenderAppID) |
| + if err != nil { |
| + return err |
| + } |
| + for _, c := range canonical { |
| + domain := addressDomain(c) |
| + if appSender == nil || appSender.Grant == nil || !slices.Contains(appSender.Grant.Domains, domain) { |
| + return fmt.Errorf("%s: %w", c, ErrAddressDomainNotApp) |
| + } |
| + rec, _, err := GetDomain(ctx, s, acct, domain) |
| + if err != nil { |
| + return err |
| + } |
| + if rec == nil { |
| + return fmt.Errorf("%s: %w", c, ErrAddressDomainNotApp) |
| + } |
| + if len(rec.Apps) != 1 || rec.Apps[0] != app { |
| + return fmt.Errorf("%s: %w", c, ErrAddressDomainShared) |
| + } |
| + holder, _, exists, err := readAddressClaim(ctx, s, AddressKey(acct, app, c)) |
| + if err != nil { |
| + return err |
| + } |
| + if exists && holder != id { |
| + return fmt.Errorf("%s: %w", c, ErrAddressTaken) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// grantPreflighted writes a batch that preflightGrants accepted, under the |
| +// same admitted call: reserve all, write each key, then grant all. A key |
| +// 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 todo []string |
| + sn, err := mutateSender(ctx, s, acct, app, id, func(sn *Sender) bool { |
| + todo = todo[:0] |
| + changed := false |
| + for _, c := range canonical { |
| + if sn.Grant != nil && slices.Contains(sn.Grant.Addresses, c) { |
| + continue |
| + } |
| + if !slices.Contains(sn.Reserving, c) { |
| + sn.Reserving = append(sn.Reserving, c) |
| + changed = true |
| + } |
| + todo = append(todo, c) |
| + } |
| + return changed |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if len(todo) == 0 { |
| + return sn, nil |
| + } |
| + body, err := json.Marshal(addressClaim{Sender: id}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + for _, c := range todo { |
| + if err := putAddressClaim(ctx, s, acct, app, id, c, body); err != nil { |
| + return nil, err |
| + } |
| + } |
| + return mutateSender(ctx, s, acct, app, id, func(sn *Sender) bool { |
| + changed := false |
| + for _, c := range todo { |
| + if !slices.Contains(sn.Reserving, c) { |
| + continue |
| + } |
| + sn.Reserving = without(sn.Reserving, c) |
| + if sn.Grant == nil { |
| + sn.Grant = &GrantBlock{} |
| + } |
| + if !slices.Contains(sn.Grant.Addresses, c) { |
| + sn.Grant.Addresses = append(sn.Grant.Addresses, 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 |
| + } |
| + if !exists || holder != id { |
| + return fmt.Errorf("%s: %w", c, errAddressClaimMismatch) |
| + } |
| + return nil |
| +} |
| + |
| +// deleteOwnAddressClaim deletes the key only when it names this sender, by |
| +// its read etag. |
| +func deleteOwnAddressClaim(ctx context.Context, s release.Store, acct, app, id, c string) error { |
| + key := AddressKey(acct, app, c) |
| + holder, etag, exists, err := readAddressClaim(ctx, s, key) |
| + if err != nil || !exists || holder != id { |
| + return err |
| + } |
| + 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. |
| +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 { |
| + return sn, err |
| + } |
| + if len(sn.Reserving) == 0 && len(sn.Releasing) == 0 { |
| + return sn, nil |
| + } |
| + var grant, drop []string |
| + 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 { |
| + grant = append(grant, c) |
| + } else { |
| + drop = append(drop, c) |
| + } |
| + } |
| + 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 !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 |
| + }) |
| +} |
| + |
| +// claimUnserializedGrantAddresses grants a batch to an existing sender: |
| +// read-only refusals first, then the writes. |
| +func claimUnserializedGrantAddresses(ctx context.Context, s release.Store, acct, app, id string, canonical []string) (*Sender, error) { |
| + sn, _, err := getInstanceSender(ctx, s, acct, app, id) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if sn == nil { |
| + return nil, ErrNoSuchSender |
| + } |
| + if err := preflightGrants(ctx, s, acct, app, id, canonical); err != nil { |
| + return nil, err |
| + } |
| + return grantPreflighted(ctx, s, acct, app, id, canonical) |
| +} |
| + |
| +// claimUnserializedRevokeAddress revokes one canonical address: into |
| +// Releasing, its own key deleted, out of Releasing. Revoking an address the |
| +// sender does not hold is success. |
| +func claimUnserializedRevokeAddress(ctx context.Context, s release.Store, acct, app, id, c string) (*Sender, error) { |
| + sn, err := mutateSender(ctx, s, acct, app, id, func(sn *Sender) bool { |
| + if sn.Grant == nil || !slices.Contains(sn.Grant.Addresses, c) { |
| + return false |
| + } |
| + sn.Grant.Addresses = without(sn.Grant.Addresses, c) |
| + if !slices.Contains(sn.Releasing, c) { |
| + sn.Releasing = append(sn.Releasing, c) |
| + } |
| + return true |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if !slices.Contains(sn.Releasing, c) { |
| + return sn, nil |
| + } |
| + 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 { |
| + if !slices.Contains(sn.Releasing, c) { |
| + return false |
| + } |
| + sn.Releasing = without(sn.Releasing, c) |
| + return true |
| + }) |
| +} |
| + |
| +// addressesUseDomain counts this app's instance senders' grants, |
| +// reservations and releases on domain, from a strict inventory. |
| +func addressesUseDomain(ctx context.Context, s release.Store, acct, app, domain string) (int, error) { |
| + all, err := ListSendersStrict(ctx, s, acct, app) |
| + if err != nil { |
| + return 0, err |
| + } |
| + n := 0 |
| + for _, sn := range InstanceSenders(all) { |
| + var lists [][]string |
| + if sn.Grant != nil { |
| + lists = append(lists, sn.Grant.Addresses) |
| + } |
| + lists = append(lists, sn.Reserving, sn.Releasing) |
| + for _, l := range lists { |
| + for _, c := range l { |
| + if addressDomain(c) == domain { |
| + n++ |
| + } |
| + } |
| + } |
| + } |
| + return n, nil |
| +} |
| + |
| +// refuseDomainShareWhileAddressesUse is EnsureDomain's read-only gate: app |
| +// may not join a domain another app's instance addresses depend on, since |
| +// that would make the domain shared under them (decision 6). |
| +func refuseDomainShareWhileAddressesUse(ctx context.Context, s release.Store, acct, app, domain string) error { |
| + rec, _, err := GetDomain(ctx, s, acct, domain) |
| + if err != nil || rec == nil || slices.Contains(rec.Apps, app) { |
| + return err |
| + } |
| + for _, other := range rec.Apps { |
| + n, err := addressesUseDomain(ctx, s, acct, other, domain) |
| + if err != nil { |
| + return err |
| + } |
| + if n > 0 { |
| + return &AddressesInUseError{Domain: domain, Count: n} |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// refuseDomainRemoveWhileAddressesUse is RemoveDomain's read-only gate. |
| +func refuseDomainRemoveWhileAddressesUse(ctx context.Context, s release.Store, acct, app, domain string) error { |
| + n, err := addressesUseDomain(ctx, s, acct, app, domain) |
| + if err != nil { |
| + return err |
| + } |
| + if n > 0 { |
| + return &AddressesInUseError{Domain: domain, Count: n} |
| + } |
| + return nil |
| +} |
| + |
| +// RecoverAddresses finishes any pending grant or release of one instance |
| +// sender, as its own admitted call. |
| +func RecoverAddresses(ctx context.Context, s release.Store, acct, app, id string) (*Sender, error) { |
| + if _, enabled := s.(ClaimMailStore); !enabled { |
| + return claimUnserializedRecoverAddresses(ctx, s, acct, app, id) |
| + } |
| + var out *Sender |
| + err := WithClaimMailResource(ctx, s, func(ctx context.Context) error { |
| + return claimMailAdmitted(ctx, s, acct, claimMailPlan{Apps: []string{app}}, func(ctx context.Context) error { |
| + var err error |
| + out, err = claimUnserializedRecoverAddresses(ctx, s, acct, app, id) |
| + return err |
| + }) |
| + }) |
| + return out, err |
| +} |
| + |
| +// GrantAddress grants one address to an existing instance sender. The |
| +// address is canonicalised first; recovery runs as its own admitted call; |
| +// every refusal is decided before the grant call's first write. |
| +func GrantAddress(ctx context.Context, s release.Store, acct, app, id, address string, _ time.Time) (*Sender, error) { |
| + c, err := mailwire.CanonicalAddress(address) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if _, err := RecoverAddresses(ctx, s, acct, app, id); err != nil { |
| + return nil, err |
| + } |
| + if _, enabled := s.(ClaimMailStore); !enabled { |
| + return claimUnserializedGrantAddresses(ctx, s, acct, app, id, []string{c}) |
| + } |
| + var out *Sender |
| + err = WithClaimMailResource(ctx, s, func(ctx context.Context) error { |
| + return claimMailAdmitted(ctx, s, acct, claimMailPlan{Apps: []string{app}}, func(ctx context.Context) error { |
| + var err error |
| + out, err = claimUnserializedGrantAddresses(ctx, s, acct, app, id, []string{c}) |
| + return err |
| + }) |
| + }) |
| + return out, err |
| +} |
| + |
| +// RevokeAddress revokes one address from an instance sender. Allowed while |
| +// the sender is being removed. |
| +func RevokeAddress(ctx context.Context, s release.Store, acct, app, id, address string, _ time.Time) (*Sender, error) { |
| + c, err := mailwire.CanonicalAddress(address) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if _, err := RecoverAddresses(ctx, s, acct, app, id); err != nil { |
| + return nil, err |
| + } |
| + if _, enabled := s.(ClaimMailStore); !enabled { |
| + return claimUnserializedRevokeAddress(ctx, s, acct, app, id, c) |
| + } |
| + var out *Sender |
| + err = WithClaimMailResource(ctx, s, func(ctx context.Context) error { |
| + return claimMailAdmitted(ctx, s, acct, claimMailPlan{Apps: []string{app}}, func(ctx context.Context) error { |
| + var err error |
| + out, err = claimUnserializedRevokeAddress(ctx, s, acct, app, id, c) |
| + return err |
| + }) |
| + }) |
| + return out, err |
| +} |
diff --git a/internal/mail/addresses_guard_test.go b/internal/mail/addresses_guard_test.go| new file mode 100644 |
| index 000000000..0ee988744 |
| --- /dev/null |
| +++ b/internal/mail/addresses_guard_test.go |
| @@ -0,0 +1,172 @@ |
| +package mail |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "math/rand" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// failNthStore fails the nth write (Put, Delete, DeleteIfMatch) from now on, |
| +// once, then lets everything through. n <= 0 never fails. |
| +type failNthStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + n, cur int |
| +} |
| + |
| +var errInjected = errors.New("injected write failure") |
| + |
| +func (f *failNthStore) fail() bool { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.cur++ |
| + return f.n > 0 && f.cur == f.n |
| +} |
| +func (f *failNthStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + if f.fail() { |
| + return "", errInjected |
| + } |
| + return f.Store.Put(ctx, key, body, ifMatch) |
| +} |
| +func (f *failNthStore) Delete(ctx context.Context, key string) error { |
| + if f.fail() { |
| + return errInjected |
| + } |
| + return f.Store.Delete(ctx, key) |
| +} |
| +func (f *failNthStore) DeleteIfMatch(ctx context.Context, key, etag string) error { |
| + if f.fail() { |
| + return errInjected |
| + } |
| + return release.DeleteIfMatch(ctx, f.Store, key, etag) |
| +} |
| + |
| +// guardOps is the operation set the guard draws from. Task 4 adds removal. |
| +type guardOp func(ctx context.Context, s release.Store, id, addr string) error |
| + |
| +var guardOps = map[string]guardOp{ |
| + "grant": func(ctx context.Context, s release.Store, id, addr string) error { |
| + _, err := GrantAddress(ctx, s, tAcct, tApp, id, addr, time.Now()) |
| + return err |
| + }, |
| + "revoke": func(ctx context.Context, s release.Store, id, addr string) error { |
| + _, err := RevokeAddress(ctx, s, tAcct, tApp, id, addr, time.Now()) |
| + return err |
| + }, |
| + "recover": func(ctx context.Context, s release.Store, id, _ string) error { |
| + _, err := RecoverAddresses(ctx, s, tAcct, tApp, id) |
| + return err |
| + }, |
| +} |
| + |
| +// 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. |
| +func checkAddressInvariant(t *testing.T, s release.Store, ids, addrs []string, trace string) { |
| + t.Helper() |
| + ctx := context.Background() |
| + recs := map[string]*Sender{} |
| + 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 |
| + } |
| + for _, a := range sn.Grant.Addresses { |
| + if other, ok := grantedBy[a]; ok { |
| + t.Fatalf("%s: %s granted to %s and %s", trace, a, other, id) |
| + } |
| + grantedBy[a] = id |
| + } |
| + } |
| + for _, a := range addrs { |
| + 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) |
| + } |
| + } |
| +} |
| + |
| +func TestAddressReservationInvariant(t *testing.T) { |
| + seed := time.Now().UnixNano() |
| + t.Logf("seed %d", seed) |
| + rng := rand.New(rand.NewSource(seed)) |
| + ids := []string{"a.shop.example", "b.shop.example"} |
| + addrs := []string{"p@x.example", "q@x.example", "r@x.example"} |
| + names := []string{"grant", "revoke", "recover"} |
| + for run := 0; run < 15; run++ { |
| + type step struct{ op, id, addr string } |
| + seq := make([]step, 3+rng.Intn(4)) |
| + for i := range seq { |
| + seq[i] = step{names[rng.Intn(len(names))], ids[rng.Intn(2)], addrs[rng.Intn(3)]} |
| + } |
| + // Count the sequence's writes once, then fail each one in turn. |
| + probe := &countingStore{Store: release.NewDirStore(t.TempDir())} |
| + addrFixture(t, probe.Store) |
| + for _, st := range seq { |
| + _ = guardOps[st.op](context.Background(), probe, st.id, st.addr) |
| + } |
| + for n := 1; n <= probe.count(); n++ { |
| + base := release.NewDirStore(t.TempDir()) |
| + addrFixture(t, base) |
| + s := &failNthStore{Store: base, n: n} |
| + var trace []string |
| + for _, st := range seq { |
| + err := guardOps[st.op](context.Background(), s, st.id, st.addr) |
| + trace = append(trace, st.op+"("+st.id+","+st.addr+")="+errString(err)) |
| + checkAddressInvariant(t, base, ids, addrs, strings.Join(trace, " ")+" fail@"+itoa(n)) |
| + } |
| + for _, id := range ids { |
| + sn, err := RecoverAddresses(context.Background(), base, tAcct, tApp, id) |
| + if err != nil { |
| + t.Fatalf("recover %s: %v", id, err) |
| + } |
| + if len(sn.Reserving) != 0 || len(sn.Releasing) != 0 { |
| + t.Fatalf("%s after recovery still pending: %+v (%s fail@%d)", id, sn, strings.Join(trace, " "), n) |
| + } |
| + } |
| + checkAddressInvariant(t, base, ids, addrs, strings.Join(trace, " ")+" recovered") |
| + } |
| + } |
| +} |
| + |
| +func errString(err error) string { |
| + if err == nil { |
| + return "ok" |
| + } |
| + if errors.Is(err, errInjected) { |
| + return "injected" |
| + } |
| + return "refused" |
| +} |
| + |
| +func itoa(n int) string { return strconv.Itoa(n) } |
diff --git a/internal/mail/addresses_test.go b/internal/mail/addresses_test.go| new file mode 100644 |
| index 000000000..e006d8348 |
| --- /dev/null |
| +++ b/internal/mail/addresses_test.go |
| @@ -0,0 +1,284 @@ |
| +package mail |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/mailwire" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// countingStore counts writes (Put, Delete, DeleteIfMatch). |
| +type countingStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + writes int |
| +} |
| + |
| +func (c *countingStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + c.mu.Lock() |
| + c.writes++ |
| + c.mu.Unlock() |
| + return c.Store.Put(ctx, key, body, ifMatch) |
| +} |
| +func (c *countingStore) Delete(ctx context.Context, key string) error { |
| + c.mu.Lock() |
| + c.writes++ |
| + c.mu.Unlock() |
| + return c.Store.Delete(ctx, key) |
| +} |
| +func (c *countingStore) DeleteIfMatch(ctx context.Context, key, etag string) error { |
| + c.mu.Lock() |
| + c.writes++ |
| + c.mu.Unlock() |
| + return release.DeleteIfMatch(ctx, c.Store, key, etag) |
| +} |
| +func (c *countingStore) count() int { c.mu.Lock(); defer c.mu.Unlock(); return c.writes } |
| + |
| +const ( |
| + tAcct = "bab" |
| + tApp = "shop" |
| + tDom = "x.example" |
| +) |
| + |
| +// addrFixture: app "shop" switched, its app sender granted x.example, whose |
| +// record lists only shop; instance senders a and b. |
| +func addrFixture(t *testing.T, s release.Store) { |
| + t.Helper() |
| + ctx := context.Background() |
| + now := time.Now() |
| + putSenderJSON(t, s, tAcct, tApp, &Sender{ID: SenderAppID, Scope: ScopeApp, Source: SourceDomain, |
| + Grant: &GrantBlock{Domains: []string{tDom, "shared.example"}}, Submission: &mailwire.Submission{On: true, At: now}}) |
| + for _, d := range []struct { |
| + name string |
| + apps []string |
| + }{{tDom, []string{tApp}}, {"shared.example", []string{tApp, "other"}}} { |
| + if _, err := claimUnserializedPutDomain(ctx, s, tAcct, &DomainRecord{Domain: d.name, Kind: KindCustom, Apps: d.apps, |
| + Regions: map[string]*RegionState{"eu-west-1": {IdentityARN: "arn:" + d.name, Status: StatusVerified}}, CreatedAt: now}, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, id := range []string{"a.shop.example", "b.shop.example"} { |
| + putSenderJSON(t, s, tAcct, tApp, &Sender{ID: id, Scope: ScopeInstance, Host: id, Source: SourceDomain}) |
| + } |
| +} |
| + |
| +func senderOf(t *testing.T, s release.Store, id string) *Sender { |
| + t.Helper() |
| + sn, _, err := GetSender(context.Background(), s, tAcct, tApp, id) |
| + if err != nil || sn == nil { |
| + t.Fatalf("sender %s: %v %v", id, sn, err) |
| + } |
| + return sn |
| +} |
| + |
| +func keyHolder(t *testing.T, s release.Store, c string) (string, bool) { |
| + t.Helper() |
| + h, _, ok, err := readAddressClaim(context.Background(), s, AddressKey(tAcct, tApp, c)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return h, ok |
| +} |
| + |
| +func TestGrantCanonical(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + addrFixture(t, s) |
| + sn, err := GrantAddress(context.Background(), s, tAcct, tApp, "a.shop.example", "Paul@X.Example", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(sn.Grant.Addresses) != 1 || sn.Grant.Addresses[0] != "paul@x.example" || len(sn.Reserving) != 0 { |
| + t.Fatalf("sender %+v grant %+v", sn, sn.Grant) |
| + } |
| + raw, _, err := s.Get(context.Background(), AddressKey(tAcct, tApp, "paul@x.example")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var c addressClaim |
| + if json.Unmarshal(raw, &c) != nil || c.Sender != "a.shop.example" { |
| + t.Fatalf("key body %s", raw) |
| + } |
| + // Idempotent: granting again writes nothing. |
| + cs := &countingStore{Store: s} |
| + if _, err := GrantAddress(context.Background(), cs, tAcct, tApp, "a.shop.example", "paul@x.example", time.Now()); err != nil || cs.count() != 0 { |
| + t.Fatalf("re-grant: %v, %d writes", err, cs.count()) |
| + } |
| +} |
| + |
| +func TestGrantTakenRefusedBeforeWrite(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + addrFixture(t, s) |
| + if _, err := GrantAddress(context.Background(), s, tAcct, tApp, "a.shop.example", "paul@x.example", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + cs := &countingStore{Store: s} |
| + for _, addr := range []string{"paul@x.example", "PAUL@x.example"} { |
| + if _, err := GrantAddress(context.Background(), cs, tAcct, tApp, "b.shop.example", addr, time.Now()); !errors.Is(err, ErrAddressTaken) { |
| + t.Fatalf("%s: %v, want ErrAddressTaken", addr, err) |
| + } |
| + } |
| + if cs.count() != 0 { |
| + t.Fatalf("refused grants wrote %d times", cs.count()) |
| + } |
| + if h, _ := keyHolder(t, s, "paul@x.example"); h != "a.shop.example" { |
| + t.Fatalf("key holder %q", h) |
| + } |
| +} |
| + |
| +func TestGrantRefusalsBeforeWrite(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + addrFixture(t, s) |
| + cs := &countingStore{Store: s} |
| + ctx := context.Background() |
| + if _, err := GrantAddress(ctx, cs, tAcct, tApp, "a.shop.example", "p@shared.example", time.Now()); !errors.Is(err, ErrAddressDomainShared) { |
| + t.Errorf("shared: %v", err) |
| + } |
| + if _, err := GrantAddress(ctx, cs, tAcct, tApp, "a.shop.example", "p@nope.example", time.Now()); !errors.Is(err, ErrAddressDomainNotApp) { |
| + t.Errorf("not the app's: %v", err) |
| + } |
| + if _, err := GrantAddress(ctx, cs, tAcct, tApp, "a.shop.example", "pål@x.example", time.Now()); !errors.Is(err, mailwire.ErrAddressNotASCII) { |
| + t.Errorf("not ascii: %v", err) |
| + } |
| + if _, err := GrantAddress(ctx, cs, tAcct, tApp, "nobody.shop.example", "p@x.example", time.Now()); !errors.Is(err, ErrNoSuchSender) { |
| + t.Errorf("no sender: %v", err) |
| + } |
| + if cs.count() != 0 { |
| + t.Fatalf("refusals wrote %d times", cs.count()) |
| + } |
| + // The limit counts the batch with what is held. |
| + for i := 0; i < MaxSenderAddresses; i++ { |
| + if _, err := GrantAddress(ctx, s, tAcct, tApp, "a.shop.example", string(rune('a'+i%26))+string(rune('a'+i/26))+"@x.example", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + cs = &countingStore{Store: s} |
| + if _, err := GrantAddress(ctx, cs, tAcct, tApp, "a.shop.example", "one-more@x.example", time.Now()); !errors.Is(err, ErrTooManyAddresses) || cs.count() != 0 { |
| + t.Errorf("limit: %v, %d writes", err, cs.count()) |
| + } |
| + now := time.Now() |
| + if _, err := mutateSender(ctx, s, tAcct, tApp, "b.shop.example", func(sn *Sender) bool { sn.Removing = &now; return true }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := GrantAddress(ctx, cs, tAcct, tApp, "b.shop.example", "b@x.example", time.Now()); !errors.Is(err, ErrSenderRemoving) || cs.count() != 0 { |
| + t.Errorf("removing: %v, %d writes", err, cs.count()) |
| + } |
| +} |
| + |
| +// Through the production ClaimMailStore wrapper: a refused grant releases |
| +// the gate, so the next gated mutation succeeds. |
| +func TestGateReleasedAfterRefusal(t *testing.T) { |
| + ctx := t.Context() |
| + gate, admitter := &fixGate{}, &fixAdmitter{} |
| + base := release.NewDirStore(t.TempDir()) |
| + addrFixture(t, base) |
| + s, err := NewClaimMailStore(base, gate, admitter, ClaimMailOwner{Console: "c", Enrollment: "e", Controller: "k"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := GrantAddress(ctx, s, tAcct, tApp, "a.shop.example", "paul@x.example", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := GrantAddress(ctx, s, tAcct, tApp, "b.shop.example", "paul@x.example", time.Now()); !errors.Is(err, ErrAddressTaken) { |
| + t.Fatalf("refusal: %v", err) |
| + } |
| + if gate.held { |
| + t.Fatal("the gate is held after an expected refusal") |
| + } |
| + if _, err := GrantAddress(ctx, s, tAcct, tApp, "b.shop.example", "dana@x.example", time.Now()); err != nil { |
| + t.Fatalf("next gated mutation: %v", err) |
| + } |
| +} |
| + |
| +func TestRevokeDeletesOnlyOwnKey(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + addrFixture(t, s) |
| + ctx := context.Background() |
| + if _, err := GrantAddress(ctx, s, tAcct, tApp, "a.shop.example", "paul@x.example", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + sn, err := RevokeAddress(ctx, s, tAcct, tApp, "a.shop.example", "Paul@x.example", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(sn.Grant.Addresses) != 0 || len(sn.Releasing) != 0 { |
| + t.Fatalf("after revoke %+v", sn) |
| + } |
| + if _, ok := keyHolder(t, s, "paul@x.example"); ok { |
| + t.Fatal("key survived the revoke") |
| + } |
| + // A key naming another sender is never deleted by this sender's revoke |
| + // or recovery. |
| + body, _ := json.Marshal(addressClaim{Sender: "b.shop.example"}) |
| + if _, err := s.Put(ctx, AddressKey(tAcct, tApp, "dana@x.example"), body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := mutateSender(ctx, s, tAcct, tApp, "a.shop.example", func(sn *Sender) bool { |
| + sn.Releasing = append(sn.Releasing, "dana@x.example") |
| + return true |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := RecoverAddresses(ctx, s, tAcct, tApp, "a.shop.example"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if h, ok := keyHolder(t, s, "dana@x.example"); !ok || h != "b.shop.example" { |
| + t.Fatalf("another sender's key: %q %v", h, ok) |
| + } |
| +} |
| + |
| +func TestDomainChangesRefusedWhileAddressesUse(t *testing.T) { |
| + ctx := context.Background() |
| + for _, state := range []string{"granted", "reserving", "releasing"} { |
| + s := release.NewDirStore(t.TempDir()) |
| + addrFixture(t, s) |
| + if _, err := mutateSender(ctx, s, tAcct, tApp, "a.shop.example", func(sn *Sender) bool { |
| + switch state { |
| + case "granted": |
| + sn.Grant = &GrantBlock{Addresses: []string{"paul@x.example"}} |
| + case "reserving": |
| + sn.Reserving = []string{"paul@x.example"} |
| + case "releasing": |
| + sn.Releasing = []string{"paul@x.example"} |
| + } |
| + return true |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + cs := &countingStore{Store: s} |
| + var inUse *AddressesInUseError |
| + if err := refuseDomainShareWhileAddressesUse(ctx, cs, tAcct, "other", tDom); !errors.As(err, &inUse) || inUse.Count != 1 || !errors.Is(err, ErrAddressesInUse) { |
| + t.Errorf("%s: share: %v", state, err) |
| + } |
| + if err := refuseDomainRemoveWhileAddressesUse(ctx, cs, tAcct, tApp, tDom); !errors.Is(err, ErrAddressesInUse) { |
| + t.Errorf("%s: remove: %v", state, err) |
| + } |
| + if err := refuseDomainShareWhileAddressesUse(ctx, cs, tAcct, tApp, tDom); err != nil { |
| + t.Errorf("%s: the holding app re-ensuring its own domain: %v", state, err) |
| + } |
| + if cs.count() != 0 { |
| + t.Errorf("%s: refusals wrote %d times", state, cs.count()) |
| + } |
| + } |
| + // Through the real walks: EnsureDomain by another app and RemoveDomain |
| + // by the holder both refuse before anything is written. |
| + s := release.NewDirStore(t.TempDir()) |
| + addrFixture(t, s) |
| + if _, err := GrantAddress(ctx, s, tAcct, tApp, "a.shop.example", "paul@x.example", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + cs := &countingStore{Store: s} |
| + if _, _, err := EnsureDomain(ctx, cs, nil, nil, Deployment{Region: "eu-west-1"}, tAcct, "other", tDom, time.Now()); !errors.Is(err, ErrAddressesInUse) { |
| + t.Errorf("EnsureDomain: %v", err) |
| + } |
| + if _, err := RemoveDomain(ctx, cs, nil, nil, Deployment{Region: "eu-west-1"}, tAcct, tApp, tDom); !errors.Is(err, ErrAddressesInUse) { |
| + t.Errorf("RemoveDomain: %v", err) |
| + } |
| + if cs.count() != 0 { |
| + t.Errorf("walk refusals wrote %d times", cs.count()) |
| + } |
| +} |
diff --git a/internal/mail/walk.go b/internal/mail/walk.go| index b59bac665..0c81e3eaa 100644 |
| --- a/internal/mail/walk.go |
| +++ b/internal/mail/walk.go |
| @@ -185,6 +185,11 @@ func claimUnserializedEnsureDomain(ctx context.Context, s release.Store, p Provi |
| if DomainKindFor(d, domain) == KindPlatform && !platformNameOwnedBy(d, domain, acct) { |
| return nil, nil, fmt.Errorf("mail: %q is not %s's platform name: %w", domain, acct, ErrNotOwnPlatformName) |
| } |
| + // Read-only, before the claim's write: joining a domain another app's |
| + // instance addresses depend on would share it under them (addresses.go). |
| + if err := refuseDomainShareWhileAddressesUse(ctx, s, acct, app, domain); err != nil { |
| + return nil, nil, err |
| + } |
| err := claimDomain(ctx, s, domain, acct, app, now) |
| if errors.Is(err, ErrDomainClaimed) { |
| err = takeLapsedClaim(ctx, s, p, d.Region, domain, acct, app, now) |
| @@ -2013,6 +2018,11 @@ func claimUnserializedRemoveDomain(ctx context.Context, s release.Store, p Provi |
| } |
| } |
| + // Read-only too: instance address grants still depend on it. |
| + if err := refuseDomainRemoveWhileAddressesUse(ctx, s, acct, app, domain); err != nil { |
| + return nil, err |
| + } |
| + |
| cur, curEtag, err := GetDomain(ctx, s, acct, domain) |
| if err != nil { |
| return nil, err |
diff --git a/internal/mailwire/instance.go b/internal/mailwire/instance.go| index e672d15df..b8a39edd5 100644 |
| --- a/internal/mailwire/instance.go |
| +++ b/internal/mailwire/instance.go |
| @@ -36,6 +36,12 @@ const MaxAddressLen = 254 |
| // may not import that one; a test in internal/mail pins the two equal. |
| var addressDomainRe = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$`) |
| +// localPartRe is a dot-atom local part without "/" or "\x60": the address |
| +// becomes a bucket key segment (addresses.go's AddressKey), so a separator |
| +// can never reach it, and a quoted local part is refused rather than |
| +// normalised. |
| +var localPartRe = regexp.MustCompile("^[a-z0-9!#$%&'*+=?^_{|}~-]+(\\.[a-z0-9!#$%&'*+=?^_{|}~-]+)*$") |
| + |
| // AddressDomainPattern is addressDomainRe's source, for that pin. |
| func AddressDomainPattern() string { return addressDomainRe.String() } |
| @@ -62,7 +68,7 @@ func CanonicalAddress(s string) (string, error) { |
| } |
| addr := strings.ToLower(a.Address) |
| at := strings.LastIndexByte(addr, '@') |
| - if at <= 0 || at == len(addr)-1 { |
| + if at <= 0 || at == len(addr)-1 || !localPartRe.MatchString(addr[:at]) { |
| return "", ErrAddressSyntax |
| } |
| if d := addr[at+1:]; len(d) > 253 || !addressDomainRe.MatchString(d) { |
diff --git a/internal/mailwire/instance_test.go b/internal/mailwire/instance_test.go| index fd8da82d5..d37a9731b 100644 |
| --- a/internal/mailwire/instance_test.go |
| +++ b/internal/mailwire/instance_test.go |
| @@ -30,6 +30,10 @@ func TestCanonicalAddress(t *testing.T) { |
| "paul@": ErrAddressSyntax, |
| "a, b@c.example": ErrAddressSyntax, |
| "": ErrAddressSyntax, |
| + "a/b@x.example": ErrAddressSyntax, |
| + `"a b"@x.example`: ErrAddressSyntax, |
| + "a..b@x.example": ErrAddressSyntax, |
| + "`a`@x.example": ErrAddressSyntax, |
| "pål@x.example": ErrAddressNotASCII, |
| "paul@x": ErrAddressDomain, |
| "paul@-x.example": ErrAddressDomain, |
diff --git a/internal/provision/instance_senders_1_census_test.go b/internal/provision/instance_senders_1_census_test.go| new file mode 100644 |
| index 000000000..0e08a421d |
| --- /dev/null |
| +++ b/internal/provision/instance_senders_1_census_test.go |
| @@ -0,0 +1,33 @@ |
| +package provision |
| + |
| +// instanceSenders1WriteCensusInventory is the instance senders slice 1 |
| +// review of the record-write census (design |
| +// 2026-11-30-instance-senders-on-submission, plan |
| +// 2026-11-30-instance-senders-1-own-address). The slice adds instance |
| +// senders' address grants: create-only keys under |
| +// apps/<account>/<app>/email/addresses/ (mail.AddressKey), beside the sender |
| +// records under email/senders/. Neither is an instance record |
| +// (apps/<account>/<app>/instances/); none of it builds a record key, calls a |
| +// record writer or writes a record. |
| +func instanceSenders1WriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), instanceUsageWriteCensusInventory()...) |
| + reviewed := []censusEntry{ |
| + // The address uniqueness key: one create-only Put of |
| + // apps/<account>/<app>/email/addresses/<canonical>.json |
| + // (mail.AddressKey). Not a record key. |
| + {"internal/mail/addresses.go", "putAddressClaim", "nonrecord", "sel:Put", "36a56ac3be1e5bc7cb1cbf4061f6e9a303017233815dcccfb7a50938bf522dcd"}, |
| + } |
| + for _, r := range reviewed { |
| + replaced := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + entries[i], replaced = r, true |
| + break |
| + } |
| + } |
| + if !replaced { |
| + entries = append(entries, r) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index dcd64b8c9..125f8325a 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := instanceUsageWriteCensusInventory() |
| + inventory := instanceSenders1WriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
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 14d542723..212139ad8 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 85dc6783c8ab6142e874c2504e1af7bd73b2be43132378df4f7ed74c72337956 |
| +@coverage internal/mailwire a5e1c8d6bf3514d49be52aa27d8bec42450657e3c6f4673f1645dc01395454d2 |