email: the mail role, instance sender doors and CLI (Tasks 7-8)
Slice 1 Tasks 7-8 (#148, spec §5, decisions 12-13): svcrole mail, bound to one app; five instance-sender doors behind it and Admin's per-instance switch; instance delete refused while a sender exists; operator pause --host for one sender (pause and cap); instance state in the email status reply. CLI: carlos email instance create|status|rm, addresses add|rm, per-instance on|off, pause/resume --host; services help names the role; cli.md and parity rows. Copy approved by Paul in copy review (2026-11-30), applied verbatim. Claim-invariant fixtures and a read probe for the six routes; linkedRefuse for linked apps. Census re-proposed (root package envelope).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
25 files changed,
+1,449
−14
docs/parity.md+8 −2docs/site/cli.md+14 −0docs/superpowers/notes/census-proposal-instance-senders-1.md+1 −1internal/console/apiinstances.go+3 −0internal/console/apiinstancesender.go+442 −0internal/console/apiinstancesender_test.go+249 −0internal/console/apimail.go+36 −2internal/console/apiservices.go+3 −0internal/console/claim_invariant_fixtures_test.go+124 −0internal/console/claim_invariant_probes_read_test.go+2 −0internal/console/linkedpolicy.go+8 −0internal/console/mailinstance_copy.go+34 −0internal/console/routedecls.go+10 −0internal/console/svcpage.go+3 −0internal/console/svcprincipal.go+14 −0internal/console/testdata/claim-routes.txt+6 −0internal/mail/addresses.go+20 −1internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv+2 −1mail_cli.go+66 −4mail_instance_cli.go+296 −0mail_instance_cli_test.go+71 −0mail_instance_copy.go+23 −0parity/cli.tsv+7 −0parity/parity.tsv+3 −0services.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-FEK61b .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 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 golang.org/x/sys v0.49.0 go: downloading golang.org/x/mod v0.41.0 go: downloading github.com/pion/logging v0.2.4 go: downloading github.com/pion/stun/v3 v3.1.5 go: downloading github.com/pierrec/lz4/v4 v4.1.22 go: downloading github.com/pion/turn/v4 v4.1.4 go: downloading github.com/lmittmann/tint v1.1.3 go: downloading github.com/cespare/xxhash/v2 v2.3.0 go: downloading github.com/beorn7/perks v1.0.1 go: downloading github.com/prometheus/client_model v0.5.0 go: downloading github.com/prometheus/common v0.45.0 go: downloading google.golang.org/protobuf v1.36.10 go: downloading github.com/prometheus/procfs v0.12.0 go: downloading github.com/klauspost/compress v1.20.2 go: downloading github.com/pion/dtls/v3 v3.1.4 go: downloading github.com/pion/transport/v4 v4.0.2 go: downloading github.com/pion/randutil v0.1.0 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 modernc.org/sqlite v1.55.0 go: downloading github.com/klauspost/compress v1.20.2 go: downloading github.com/pierrec/lz4/v4 v4.1.22 go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0 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 github.com/google/uuid v1.6.0 go: downloading modernc.org/mathutil v1.7.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/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec amadan: job cancelled — a newer push superseded it
diff --git a/docs/parity.md b/docs/parity.md| index 9866b1c63..fcbf1561d 100644 |
| --- a/docs/parity.md |
| +++ b/docs/parity.md |
| @@ -12,10 +12,10 @@ CLI rows are checked against the command registry (`parity/cli.tsv`). |
| |---|---:| |
| | both | 48 | |
| | partial | 9 | |
| -| gap | 70 | |
| +| gap | 73 | |
| | cli-only | 21 | |
| | console-only | 19 | |
| -| Total | 167 | |
| +| Total | 170 | |
| ## account |
| @@ -131,6 +131,9 @@ CLI rows are checked against the command registry (`parity/cli.tsv`). |
| | email-credentials | partial | `email credentials create`<br>`email credentials list`<br>`email credentials revoke` | `GET /a/{sqid}/apps/{app}/settings/{section}` | | The console lists credentials read-only; it cannot create or revoke them. | |
| | email-rotate | gap | `email rotate` | | [wp-email-storage](#wp-email-storage) | | |
| | email-submission | gap | `email submission on`<br>`email submission off` | | [wp-email-storage](#wp-email-storage) | Switches an app to sending through the box: no SMTP credential in its instances. | |
| +| email-instance | gap | `email instance create`<br>`email instance status`<br>`email instance rm` | | [wp-email-storage](#wp-email-storage) | Gives one instance of an app its own email sender, shows it, or removes it. | |
| +| email-addresses | gap | `email addresses add`<br>`email addresses rm` | | [wp-email-storage](#wp-email-storage) | Lets one instance send as one exact address on the app's domain, or stops it. | |
| +| email-per-instance | gap | `email per-instance on`<br>`email per-instance off` | | [wp-email-storage](#wp-email-storage) | Makes every instance of an app send only as its own sender. | |
| ## fleets |
| @@ -346,6 +349,9 @@ Discussion #737. |
| - `email-events` (email), CLI has `email events`, `email events push` |
| - `email-rotate` (email), CLI has `email rotate` |
| - `email-submission` (email), CLI has `email submission on`, `email submission off` |
| +- `email-instance` (email), CLI has `email instance create`, `email instance status`, `email instance rm` |
| +- `email-addresses` (email), CLI has `email addresses add`, `email addresses rm` |
| +- `email-per-instance` (email), CLI has `email per-instance on`, `email per-instance off` |
| <a id="wp-cli-verbs"></a> |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 6bf87787a..bf702ca08 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -2823,6 +2823,20 @@ or pinning a build without `--mail submit` is refused. The app-level SMTP |
| user goes a week after its key stops being used. `submission off` delivers |
| the SMTP credential again. Both restart the app's instances. |
| +`carlos email instance create --app <a> --host <h>` gives one instance of an app its own email sender, with its own daily cap, pause and counts. `--address` grants it addresses as it is created. `status` shows the instance's sender and today's counts, and `rm` removes it, revoking every address. An instance can't be deleted while it has a sender. The app must send through the platform's mailer first (`carlos email submission on`). A backend can run these with a `mail` service credential. |
| + |
| +`carlos email addresses add --app <a> --host <h> <address>` lets one instance send as one exact address on a domain the app sends from, and `rm` stops it. Each address belongs to one instance. The domain must be the app's alone: an address can't be given out on a domain another app shares, and another app can't add the domain while addresses use it. |
| + |
| +`carlos email per-instance on --app <a>` makes every instance of the app send only as its own sender: as the addresses granted to it, within its own cap. An instance with no sender can't send at all. It needs the app's old SMTP credential retired first, about a week after `carlos email submission on`. `off` is refused while any instance sender exists. |
| + |
| +`--host <h>` on `carlos email pause` and `resume` pauses, resumes or changes the cap of that one instance's sender, leaving the rest of the app alone. |
| + |
| +```sh |
| +carlos email instance create --app shop --host a.shop.example --address paul@shop.example |
| +carlos email addresses add --app shop --host a.shop.example sales@shop.example |
| +carlos email per-instance on --app shop |
| +``` |
| + |
| ### carlos ledger |
| Append-only hash-chained ledgers an app can publish. `append` adds one JSON |
diff --git a/docs/superpowers/notes/census-proposal-instance-senders-1.md b/docs/superpowers/notes/census-proposal-instance-senders-1.md| index 305dd6c43..f3a1af414 100644 |
| --- a/docs/superpowers/notes/census-proposal-instance-senders-1.md |
| +++ b/docs/superpowers/notes/census-proposal-instance-senders-1.md |
| @@ -2,7 +2,7 @@ |
| Ruling `census-ruling-instance-senders-1`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| -Envelopes re-pinned: `internal/mailer`, `internal/mailsubmit`, `internal/mailwire`, `internal/svcrole`. |
| +Envelopes re-pinned: `.`, `internal/mailer`, `internal/mailsubmit`, `internal/mailwire`, `internal/svcrole`. |
| Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index 9466c8379..e7c77270e 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -3483,6 +3483,9 @@ func (s *Server) handleAPIInstanceDelete(w http.ResponseWriter, r *http.Request) |
| jsonError(w, http.StatusBadRequest, "invalid host") |
| return |
| } |
| + if s.refuseInstanceDeleteWithSender(ctx, w, acct.Sqid, app, host) { |
| + return |
| + } |
| // Admitted on, a hostname whose create, retirement or migration is |
| // still settling is refused up front (lifetimes.go); the delete itself |
| // is a retirement (importDeleteRule, lifetimes_retire.go), which admits |
diff --git a/internal/console/apiinstancesender.go b/internal/console/apiinstancesender.go| new file mode 100644 |
| index 000000000..8055a1bef |
| --- /dev/null |
| +++ b/internal/console/apiinstancesender.go |
| @@ -0,0 +1,442 @@ |
| +package console |
| + |
| +// The instance-sender doors (instance senders design §5, decision 12): an |
| +// app's backend, holding a `mail` service credential, gives one instance |
| +// of the app its own email sender and exact addresses. Every door is |
| +// Allow(svcrole.Mail) (Admin reaches them through the union). Per-instance |
| +// mode is Admin's own door. All mutations go through internal/mail, which |
| +// serializes them per app (applock.go) and decides every refusal before |
| +// its first write. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "slices" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/mail" |
| + "github.com/carlosframework/platform/internal/mailwire" |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +// instanceSenderTimeout bounds one door's store work. |
| +const instanceSenderTimeout = 30 * time.Second |
| + |
| +// apiInstanceSenderReply is one instance sender, as the doors and the |
| +// status reply's sender entries show it. |
| +type apiInstanceSenderReply struct { |
| + Host string `json:"host"` |
| + ID string `json:"id"` |
| + Addresses []string `json:"addresses"` |
| + Pending []string `json:"pending,omitempty"` |
| + Removing *time.Time `json:"removing,omitempty"` |
| + State string `json:"state"` |
| + Pause *mailwire.Pause `json:"pause,omitempty"` |
| + DailyCap int `json:"daily_cap"` |
| + Counts map[string]int `json:"counts"` |
| +} |
| + |
| +// The instance-sender states (CLI renders them). |
| +const ( |
| + instanceStateSending = "sending" |
| + instanceStatePaused = "paused" |
| + instanceStateHeld = "held" |
| + instanceStateRemoving = "removing" |
| +) |
| + |
| +// instanceSenderState is one sender's state: removing, its own pause, the |
| +// app sender's hold over every instance, or sending. |
| +func instanceSenderState(sn, appSender *mail.Sender) (string, *mailwire.Pause) { |
| + if sn.Removing != nil { |
| + return instanceStateRemoving, nil |
| + } |
| + if pz := mail.EffectivePause(sn); pz != nil { |
| + return instanceStatePaused, pz |
| + } |
| + if appSender != nil && appSender.InstancesPause != nil { |
| + return instanceStateHeld, appSender.InstancesPause |
| + } |
| + return instanceStateSending, nil |
| +} |
| + |
| +// instanceSenderReply builds the reply for one sender, with today's counts. |
| +func (s *Server) instanceSenderReply(ctx context.Context, acct, app string, sn, appSender *mail.Sender, now time.Time) (apiInstanceSenderReply, error) { |
| + c, err := s.store.MailCounts(ctx, acct, app, sn.ID, now.UTC().Format("2006-01-02")) |
| + if err != nil { |
| + return apiInstanceSenderReply{}, err |
| + } |
| + state, pz := instanceSenderState(sn, appSender) |
| + out := apiInstanceSenderReply{ |
| + Host: sn.Host, ID: sn.ID, Addresses: []string{}, Removing: sn.Removing, State: state, Pause: pz, |
| + DailyCap: mailCapFor(sn.Grant), |
| + Counts: map[string]int{"sends": int(c.Sends), "bounces": int(c.Bounces), "complaints": int(c.Complaints), |
| + "rejects": int(c.Rejects), "deliveries": int(c.Deliveries)}, |
| + } |
| + if sn.Grant != nil { |
| + out.Addresses = append(out.Addresses, sn.Grant.Addresses...) |
| + } |
| + out.Pending = append(slices.Clone(sn.Reserving), sn.Releasing...) |
| + return out, nil |
| +} |
| + |
| +// mailDoorGates is the instance-sender doors' shared front: the principal |
| +// and app (apiAccountApp's resolution, including a service credential's |
| +// app binding), the write budget of the principal's kind, and the mail |
| +// backend. read skips the budget. |
| +func (s *Server) mailDoorGates(w http.ResponseWriter, r *http.Request, write bool) (*Account, string, bool) { |
| + _, acct, app, ok := s.apiAccountApp(w, r) |
| + if !ok { |
| + return nil, "", false |
| + } |
| + if write { |
| + p, _ := principalFrom(r.Context()) |
| + if !s.allowWrite(p, time.Now()) { |
| + jsonError(w, http.StatusTooManyRequests, "too many requests — wait a minute and try again") |
| + return nil, "", false |
| + } |
| + } |
| + if !s.mailAvailable(w) { |
| + return nil, "", false |
| + } |
| + return acct, app, true |
| +} |
| + |
| +// instanceSenderHost validates {host} by shape (never by today's manifest, so |
| +// status and removal outlive it, as instance delete does). |
| +func instanceSenderHost(w http.ResponseWriter, r *http.Request) (string, bool) { |
| + host := r.PathValue("host") |
| + if !provision.ValidHostShape(host) { |
| + jsonError(w, http.StatusBadRequest, mailInstanceCopy.InvalidHost) |
| + return "", false |
| + } |
| + return host, true |
| +} |
| + |
| +// writeInstanceSenderError maps internal/mail's refusals to answers. |
| +func (s *Server) writeInstanceSenderError(w http.ResponseWriter, app, host string, err error) { |
| + var inUse *mail.AddressesInUseError |
| + switch { |
| + case errors.Is(err, mailwire.ErrAddressSyntax): |
| + jsonError(w, http.StatusBadRequest, fmt.Sprintf(mailInstanceCopy.AddressSyntax, addressOf(err))) |
| + case errors.Is(err, mailwire.ErrAddressNotASCII): |
| + jsonError(w, http.StatusBadRequest, fmt.Sprintf(mailInstanceCopy.AddressNotASCII, addressOf(err))) |
| + case errors.Is(err, mailwire.ErrAddressTooLong): |
| + jsonError(w, http.StatusBadRequest, fmt.Sprintf(mailInstanceCopy.AddressTooLong, addressOf(err))) |
| + case errors.Is(err, mailwire.ErrAddressDomain): |
| + jsonError(w, http.StatusBadRequest, fmt.Sprintf(mailInstanceCopy.AddressDomain, addressOf(err))) |
| + case errors.Is(err, mail.ErrInvalidHost): |
| + jsonError(w, http.StatusBadRequest, mailInstanceCopy.InvalidHost) |
| + case errors.Is(err, mail.ErrAddressTaken): |
| + jsonError(w, http.StatusConflict, mailInstanceCopy.AddressTaken) |
| + case errors.Is(err, mail.ErrAddressDomainShared): |
| + jsonError(w, http.StatusConflict, fmt.Sprintf(mailInstanceCopy.DomainShared, refusalDomainOf(err))) |
| + case errors.Is(err, mail.ErrAddressDomainNotApp): |
| + d := refusalDomainOf(err) |
| + jsonError(w, http.StatusConflict, fmt.Sprintf(mailInstanceCopy.DomainNotApp, d, app, d)) |
| + case errors.Is(err, mail.ErrTooManyAddresses): |
| + jsonError(w, http.StatusConflict, mailInstanceCopy.TooMany) |
| + case errors.Is(err, mail.ErrSenderRemoving): |
| + jsonError(w, http.StatusConflict, mailInstanceCopy.SenderRemoving) |
| + case errors.Is(err, mail.ErrAddressPending): |
| + jsonError(w, http.StatusConflict, mailInstanceCopy.AddressPending) |
| + case errors.Is(err, mail.ErrSubmissionOff): |
| + jsonError(w, http.StatusConflict, fmt.Sprintf(mailInstanceCopy.SubmissionOff, app)) |
| + case errors.Is(err, mail.ErrInstanceSendersExist): |
| + jsonError(w, http.StatusConflict, mailInstanceCopy.InstanceSendersExist) |
| + case errors.Is(err, mail.ErrAppUserNotReaped): |
| + jsonError(w, http.StatusConflict, mailInstanceCopy.AppUserNotReaped) |
| + case errors.As(err, &inUse): |
| + jsonError(w, http.StatusConflict, domainInUseMessage(inUse)) |
| + case errors.Is(err, mail.ErrSenderInventory): |
| + jsonError(w, http.StatusBadGateway, mailInstanceCopy.SenderInventory) |
| + case errors.Is(err, mail.ErrNoSuchSender): |
| + http.Error(w, "404 page not found", http.StatusNotFound) |
| + default: |
| + if mail.IsAddressConcurrent(err) { |
| + jsonError(w, http.StatusConflict, mailInstanceCopy.AddressConcurrent) |
| + return |
| + } |
| + log.Printf("console: instance sender %s/%s: %v", app, host, err) |
| + jsonError(w, http.StatusBadGateway, mailInstanceCopy.WriteFailed) |
| + } |
| +} |
| + |
| +// domainInUseMessage names the count, or the pin when nothing is counted. |
| +func domainInUseMessage(e *mail.AddressesInUseError) string { |
| + if e.Count <= 0 { |
| + return fmt.Sprintf(mailInstanceCopy.DomainHeld, e.Domain) |
| + } |
| + return fmt.Sprintf(mailInstanceCopy.DomainInUse, e.Count, e.Domain) |
| +} |
| + |
| +// addressOf and domainOf read the subject internal/mail puts first in its |
| +// wrapped refusals ("<subject>: <reason>"), for the message. |
| +func addressOf(err error) string { return mail.RefusalSubject(err) } |
| +func refusalDomainOf(err error) string { |
| + sub := mail.RefusalSubject(err) |
| + if at := lastAt(sub); at >= 0 { |
| + return sub[at+1:] |
| + } |
| + return sub |
| +} |
| + |
| +func lastAt(s string) int { |
| + for i := len(s) - 1; i >= 0; i-- { |
| + if s[i] == '@' { |
| + return i |
| + } |
| + } |
| + return -1 |
| +} |
| + |
| +// handleAPIInstanceSenderCreate answers POST .../instances/{host}/email |
| +// {"addresses": [...]}: create (or return) the instance's sender. |
| +func (s *Server) handleAPIInstanceSenderCreate(w http.ResponseWriter, r *http.Request) { |
| + acct, app, ok := s.mailDoorGates(w, r, true) |
| + if !ok { |
| + return |
| + } |
| + host, ok := instanceSenderHost(w, r) |
| + if !ok { |
| + return |
| + } |
| + var req struct { |
| + Addresses []string `json:"addresses"` |
| + } |
| + if !readJSONAllowEmpty(w, r, &req) { |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), instanceSenderTimeout) |
| + defer cancel() |
| + rec, err := provision.GetRecord(ctx, s.cfg.Releases, acct.Sqid, app, host) |
| + if err != nil { |
| + log.Printf("console: instance sender create %s/%s: record: %v", app, host, err) |
| + jsonError(w, http.StatusBadGateway, mailInstanceCopy.WriteFailed) |
| + return |
| + } |
| + if rec == nil { |
| + jsonError(w, http.StatusNotFound, fmt.Sprintf(mailInstanceCopy.NoInstance, host)) |
| + return |
| + } |
| + p, _ := principalFrom(r.Context()) |
| + sn, err := mail.CreateInstanceSender(ctx, s.claimMailStore(), acct.Sqid, app, host, req.Addresses, principalKey(p), time.Now()) |
| + if err != nil { |
| + s.writeInstanceSenderError(w, app, host, err) |
| + return |
| + } |
| + s.answerInstanceSender(ctx, w, acct.Sqid, app, sn) |
| +} |
| + |
| +func (s *Server) answerInstanceSender(ctx context.Context, w http.ResponseWriter, acct, app string, sn *mail.Sender) { |
| + appSender, _, err := mail.GetSender(ctx, s.cfg.Releases, acct, app, mail.SenderAppID) |
| + if err != nil { |
| + log.Printf("console: instance sender %s/%s: app sender: %v", app, sn.Host, err) |
| + } |
| + out, err := s.instanceSenderReply(ctx, acct, app, sn, appSender, time.Now()) |
| + if err != nil { |
| + log.Printf("console: instance sender %s/%s: counts: %v", app, sn.Host, err) |
| + jsonError(w, http.StatusBadGateway, mailInstanceCopy.WriteFailed) |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, out) |
| +} |
| + |
| +// handleAPIInstanceSenderStatus answers GET .../instances/{host}/email. |
| +func (s *Server) handleAPIInstanceSenderStatus(w http.ResponseWriter, r *http.Request) { |
| + acct, app, ok := s.mailDoorGates(w, r, false) |
| + if !ok { |
| + return |
| + } |
| + host, ok := instanceSenderHost(w, r) |
| + if !ok { |
| + return |
| + } |
| + id, err := mail.InstanceSenderID(host) |
| + if err != nil { |
| + jsonError(w, http.StatusBadRequest, mailInstanceCopy.InvalidHost) |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), instanceSenderTimeout) |
| + defer cancel() |
| + sn, _, err := mail.GetSender(ctx, s.cfg.Releases, acct.Sqid, app, id) |
| + if err != nil { |
| + s.writeInstanceSenderError(w, app, host, err) |
| + return |
| + } |
| + if sn == nil || sn.Scope != mail.ScopeInstance { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + s.answerInstanceSender(ctx, w, acct.Sqid, app, sn) |
| +} |
| + |
| +// handleAPIInstanceSenderRemove answers DELETE .../instances/{host}/email. |
| +func (s *Server) handleAPIInstanceSenderRemove(w http.ResponseWriter, r *http.Request) { |
| + acct, app, ok := s.mailDoorGates(w, r, true) |
| + if !ok { |
| + return |
| + } |
| + host, ok := instanceSenderHost(w, r) |
| + if !ok { |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), instanceSenderTimeout) |
| + defer cancel() |
| + if err := mail.RemoveInstanceSender(ctx, s.claimMailStore(), acct.Sqid, app, host, time.Now()); err != nil { |
| + s.writeInstanceSenderError(w, app, host, err) |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, map[string]any{"host": host, "removed": true}) |
| +} |
| + |
| +// handleAPIInstanceAddressGrant answers PUT |
| +// .../instances/{host}/email/addresses/{address}. |
| +func (s *Server) handleAPIInstanceAddressGrant(w http.ResponseWriter, r *http.Request) { |
| + s.instanceAddressChange(w, r, true) |
| +} |
| + |
| +// handleAPIInstanceAddressRevoke answers DELETE |
| +// .../instances/{host}/email/addresses/{address}. |
| +func (s *Server) handleAPIInstanceAddressRevoke(w http.ResponseWriter, r *http.Request) { |
| + s.instanceAddressChange(w, r, false) |
| +} |
| + |
| +func (s *Server) instanceAddressChange(w http.ResponseWriter, r *http.Request, grant bool) { |
| + acct, app, ok := s.mailDoorGates(w, r, true) |
| + if !ok { |
| + return |
| + } |
| + host, ok := instanceSenderHost(w, r) |
| + if !ok { |
| + return |
| + } |
| + // Canonicalised before anything else reads it (decision 6). |
| + address, err := mailwire.CanonicalAddress(r.PathValue("address")) |
| + if err != nil { |
| + s.writeInstanceSenderError(w, app, host, fmt.Errorf("%s: %w", r.PathValue("address"), err)) |
| + return |
| + } |
| + id, err := mail.InstanceSenderID(host) |
| + if err != nil { |
| + jsonError(w, http.StatusBadRequest, mailInstanceCopy.InvalidHost) |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), instanceSenderTimeout) |
| + defer cancel() |
| + var sn *mail.Sender |
| + if grant { |
| + sn, err = mail.GrantAddress(ctx, s.claimMailStore(), acct.Sqid, app, id, address, time.Now()) |
| + } else { |
| + sn, err = mail.RevokeAddress(ctx, s.claimMailStore(), acct.Sqid, app, id, address, time.Now()) |
| + } |
| + if err != nil { |
| + s.writeInstanceSenderError(w, app, host, err) |
| + return |
| + } |
| + if sn == nil { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + s.answerInstanceSender(ctx, w, acct.Sqid, app, sn) |
| +} |
| + |
| +// handleAPIEmailPerInstance answers POST .../email/per-instance {"on": |
| +// bool}: Admin only (decision 2). |
| +func (s *Server) handleAPIEmailPerInstance(w http.ResponseWriter, r *http.Request) { |
| + acct, app, ok := s.mailDoorGates(w, r, true) |
| + if !ok { |
| + return |
| + } |
| + var req struct { |
| + On *bool `json:"on"` |
| + } |
| + if !readJSON(w, r, &req) { |
| + return |
| + } |
| + if req.On == nil { |
| + jsonError(w, http.StatusBadRequest, submissionCopy.SayOnOrOff) |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), instanceSenderTimeout) |
| + defer cancel() |
| + p, _ := principalFrom(r.Context()) |
| + sn, err := mail.SetPerInstance(ctx, s.claimMailStore(), acct.Sqid, app, *req.On, principalKey(p), time.Now()) |
| + if err != nil { |
| + s.writeInstanceSenderError(w, app, "", err) |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, map[string]any{"app": app, "per_instance": sn.PerInstance}) |
| +} |
| + |
| +// refuseInstanceDeleteWithSender is instance delete's refusal while the |
| +// instance still has an email sender (decision 13). True when it answered. |
| +func (s *Server) refuseInstanceDeleteWithSender(ctx context.Context, w http.ResponseWriter, acct, app, host string) bool { |
| + if s.cfg.Releases == nil { |
| + return false |
| + } |
| + has, err := mail.HasInstanceSender(ctx, s.cfg.Releases, acct, app, host) |
| + if errors.Is(err, mail.ErrInvalidHost) { |
| + return false |
| + } |
| + if err != nil { |
| + log.Printf("console: instance delete %s/%s: email sender: %v", app, host, err) |
| + jsonError(w, http.StatusBadGateway, mailInstanceCopy.SenderInventory) |
| + return true |
| + } |
| + if has { |
| + jsonError(w, http.StatusConflict, fmt.Sprintf(mailInstanceCopy.InstanceDeleteHasSender, app, host)) |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +// pauseInstanceSender is the operator pause door's --host form: pause, |
| +// resume and/or set the cap of one instance's sender, leaving the app |
| +// sender and every sibling as they are. |
| +func (s *Server) pauseInstanceSender(ctx context.Context, w http.ResponseWriter, acct *Account, app, addr, host string, paused *bool, dailyCap int) { |
| + id, err := mail.InstanceSenderID(host) |
| + if err != nil { |
| + jsonError(w, http.StatusBadRequest, mailInstanceCopy.InvalidHost) |
| + return |
| + } |
| + var sn *mail.Sender |
| + if dailyCap > 0 { |
| + if sn, err = mail.SetInstanceSenderCap(ctx, s.claimMailStore(), acct.Sqid, app, host, dailyCap, addr, time.Now()); err != nil { |
| + s.writeInstanceSenderError(w, app, host, err) |
| + return |
| + } |
| + } |
| + if paused != nil { |
| + if sn, err = mail.SetSenderPaused(ctx, s.claimMailStore(), s.cfg.MailProvisioner, acct.Sqid, app, id, *paused, "", time.Now()); err != nil { |
| + s.writeInstanceSenderError(w, app, host, err) |
| + return |
| + } |
| + } |
| + if sn == nil || sn.Scope != mail.ScopeInstance { |
| + http.Error(w, "404 page not found", http.StatusNotFound) |
| + return |
| + } |
| + var detail []string |
| + if paused != nil { |
| + detail = append(detail, map[bool]string{true: "email paused", false: "email resumed"}[*paused]) |
| + } |
| + if dailyCap > 0 { |
| + detail = append(detail, fmt.Sprintf("daily cap set to %d", dailyCap)) |
| + } |
| + s.audit(acct, app, addr, "email-pause", fmt.Sprintf("%s: %s (cli)", host, joinSemi(detail))) |
| + s.answerInstanceSender(ctx, w, acct.Sqid, app, sn) |
| +} |
| + |
| +func joinSemi(parts []string) string { |
| + out := "" |
| + for i, p := range parts { |
| + if i > 0 { |
| + out += "; " |
| + } |
| + out += p |
| + } |
| + return out |
| +} |
diff --git a/internal/console/apiinstancesender_test.go b/internal/console/apiinstancesender_test.go| new file mode 100644 |
| index 000000000..8c2925365 |
| --- /dev/null |
| +++ b/internal/console/apiinstancesender_test.go |
| @@ -0,0 +1,249 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "slices" |
| + "sort" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hostops" |
| + "github.com/carlosframework/platform/internal/mail" |
| + "github.com/carlosframework/platform/internal/mailwire" |
| + "github.com/carlosframework/platform/internal/svcrole" |
| +) |
| + |
| +const ( |
| + isHost = "acme.go.tito.io" |
| + isDomain = "go.tito.io" |
| +) |
| + |
| +// mailInstanceDoors is the intent list for the mail role (instance senders |
| +// decision 12): exactly the instance-sender doors. |
| +var mailInstanceDoors = []string{ |
| + "DELETE /api/cli/apps/{account}/{app}/instances/{host}/email", |
| + "DELETE /api/cli/apps/{account}/{app}/instances/{host}/email/addresses/{address}", |
| + "GET /api/cli/apps/{account}/{app}/instances/{host}/email", |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/email", |
| + "PUT /api/cli/apps/{account}/{app}/instances/{host}/email/addresses/{address}", |
| +} |
| + |
| +func TestMailRoleReachesOnlyTheInstanceSenderDoors(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + var reach []string |
| + for pattern, set := range fx.srv.cliRoles { |
| + if set.Permits(svcrole.Mail) { |
| + reach = append(reach, pattern) |
| + } |
| + } |
| + sort.Strings(reach) |
| + if !slices.Equal(reach, mailInstanceDoors) { |
| + t.Errorf("the mail role reaches %q, want exactly %q", reach, mailInstanceDoors) |
| + } |
| + for _, pattern := range mailInstanceDoors { |
| + set := fx.srv.cliRoles[pattern] |
| + for _, r := range []svcrole.Role{svcrole.Instance, svcrole.Operate, svcrole.Publish, svcrole.Deploy, svcrole.Service} { |
| + if set.Permits(r) { |
| + t.Errorf("%s admits %s", pattern, r) |
| + } |
| + } |
| + if !set.Permits(svcrole.Admin) { |
| + t.Errorf("%s refuses Admin", pattern) |
| + } |
| + } |
| + for _, closed := range []string{ |
| + "POST /api/cli/apps/{account}/{app}/email/pause", |
| + "POST /api/cli/apps/{account}/{app}/email/per-instance", |
| + "GET /api/cli/apps/{account}/{app}/email/events", |
| + "POST /api/cli/apps/{account}/{app}/email/credentials", |
| + "POST /api/cli/apps/{account}/{app}/email/submission", |
| + } { |
| + if fx.srv.cliRoles[closed].Permits(svcrole.Mail) { |
| + t.Errorf("mail reaches %s", closed) |
| + } |
| + } |
| +} |
| + |
| +// instanceSenderFixture: titogo with one instance, switched to submission, |
| +// its app sender granted go.tito.io (verified, titogo's alone), and a mail |
| +// credential bound to titogo. |
| +func instanceSenderFixture(t *testing.T) (*consoleFixture, string, string) { |
| + fx, mailTok, u, _ := instanceSenderFixtureOwner(t) |
| + return fx, mailTok, u |
| +} |
| + |
| +func instanceSenderFixtureOwner(t *testing.T) (*consoleFixture, string, string, string) { |
| + t.Helper() |
| + fx, token := instanceFixture(t, "code-inst-sender") |
| + enableInstances(t, fx, "titogo", titoManifest()) |
| + u := instancesURL(fx, "bab", "titogo") |
| + if status, _, out := rawReq(t, http.MethodPost, u, token, `{"host":"`+isHost+`","region":"ie"}`); status != http.StatusCreated { |
| + t.Fatalf("create instance = %d %s", status, out) |
| + } |
| + fx.srv.cfg.MailProvisioner = mail.NewMemProvisioner("1") |
| + ctx := context.Background() |
| + now := time.Now() |
| + app := &mail.Sender{ID: mail.SenderAppID, Scope: mail.ScopeApp, Source: mail.SourceDomain, |
| + Grant: &mail.GrantBlock{Domains: []string{isDomain}}, Submission: &mailwire.Submission{On: true, At: now}} |
| + if _, err := mail.PutSender(ctx, fx.rel, "bab", "titogo", app, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := mail.PutDomain(ctx, fx.rel, "bab", &mail.DomainRecord{Domain: isDomain, Kind: mail.KindCustom, Apps: []string{"titogo"}, |
| + Regions: map[string]*mail.RegionState{"eu-west-1": {IdentityARN: "arn:aws:ses:eu-west-1:1:identity/" + isDomain, Status: mail.StatusVerified}}, CreatedAt: now}, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + mailTok := serviceToken(t, fx.st, OpsAccountID, "onboard", "titogo", svcrole.Mail) |
| + return fx, mailTok, u, token |
| +} |
| + |
| +func TestInstanceSenderDoors(t *testing.T) { |
| + fx, tok, u := instanceSenderFixture(t) |
| + base := u + "/" + isHost + "/email" |
| + status, _, out := rawReq(t, http.MethodPost, base, tok, `{"addresses":["Paul@Go.Tito.io"]}`) |
| + if status != http.StatusOK { |
| + t.Fatalf("create = %d %s", status, out) |
| + } |
| + var got apiInstanceSenderReply |
| + if err := json.Unmarshal([]byte(out), &got); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !slices.Equal(got.Addresses, []string{"paul@go.tito.io"}) || got.State != instanceStateSending { |
| + t.Fatalf("create reply %+v", got) |
| + } |
| + if status, _, out := rawReq(t, http.MethodPut, base+"/addresses/p%C3%A5l@go.tito.io", tok, ""); status != http.StatusBadRequest || |
| + !strings.Contains(out, "ASCII") { |
| + t.Fatalf("non-ASCII = %d %s", status, out) |
| + } |
| + if status, _, out := rawReq(t, http.MethodPut, base+"/addresses/dana@go.tito.io", tok, ""); status != http.StatusOK { |
| + t.Fatalf("grant = %d %s", status, out) |
| + } |
| + if status, _, out := rawReq(t, http.MethodGet, base, tok, ""); status != http.StatusOK || !strings.Contains(out, "dana@go.tito.io") { |
| + t.Fatalf("status = %d %s", status, out) |
| + } |
| + if status, _, out := rawReq(t, http.MethodDelete, base+"/addresses/dana@go.tito.io", tok, ""); status != http.StatusOK || |
| + strings.Contains(out, "dana@") { |
| + t.Fatalf("revoke = %d %s", status, out) |
| + } |
| + // Taken by another instance: the neutral refusal. |
| + if _, err := mail.CreateInstanceSender(context.Background(), fx.rel, "bab", "titogo", "other.go.tito.io", []string{"taken@go.tito.io"}, "t", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status, _, out := rawReq(t, http.MethodPut, base+"/addresses/taken@go.tito.io", tok, ""); status != http.StatusConflict || |
| + !strings.Contains(out, jsonQuote(mailInstanceCopy.AddressTaken)) { |
| + t.Fatalf("taken = %d %s", status, out) |
| + } |
| + if status, _, out := rawReq(t, http.MethodDelete, base, tok, ""); status != http.StatusOK { |
| + t.Fatalf("remove = %d %s", status, out) |
| + } |
| + if status, _, _ := rawReq(t, http.MethodGet, base, tok, ""); status != http.StatusNotFound { |
| + t.Fatalf("status after remove = %d, want 404", status) |
| + } |
| +} |
| + |
| +func jsonQuote(s string) string { |
| + b, _ := json.Marshal(s) |
| + return strings.Trim(string(b), `"`) |
| +} |
| + |
| +func TestInstanceDeleteRefusedWithSender(t *testing.T) { |
| + _, tok, u, ownerTok := instanceSenderFixtureOwner(t) |
| + if status, _, out := rawReq(t, http.MethodPost, u+"/"+isHost+"/email", tok, `{}`); status != http.StatusOK { |
| + t.Fatalf("create sender = %d %s", status, out) |
| + } |
| + status, _, out := rawReq(t, http.MethodDelete, u+"/"+isHost, ownerTok, "") |
| + if status != http.StatusConflict || !strings.Contains(out, jsonQuote(fmt.Sprintf(mailInstanceCopy.InstanceDeleteHasSender, "titogo", isHost))) { |
| + t.Fatalf("delete with a sender = %d %s", status, out) |
| + } |
| + if status, _, out := rawReq(t, http.MethodDelete, u+"/"+isHost+"/email", tok, ""); status != http.StatusOK { |
| + t.Fatalf("remove sender = %d %s", status, out) |
| + } |
| + if status, _, out := rawReq(t, http.MethodDelete, u+"/"+isHost, ownerTok, ""); status != http.StatusOK { |
| + t.Fatalf("delete after removal = %d %s", status, out) |
| + } |
| +} |
| + |
| +func TestMailCredentialNeedsAnApp(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + if _, err := fx.st.NewServicePrincipal(OpsAccountID, "onboard", "", svcrole.Mail, "paul@keymail.dev", time.Now()); err == nil { |
| + t.Fatal("an account-wide mail credential was minted") |
| + } |
| +} |
| + |
| +func TestEmailPauseHost(t *testing.T) { |
| + fx, tok, u := instanceSenderFixture(t) |
| + ctx := context.Background() |
| + for _, h := range []string{isHost, "b.go.tito.io"} { |
| + if _, err := mail.CreateInstanceSender(ctx, fx.rel, "bab", "titogo", h, nil, "t", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + read := func(id string) string { |
| + raw, _, err := fx.rel.Get(ctx, mail.SenderKey("bab", "titogo", id)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(raw) |
| + } |
| + appBefore, sibBefore := read(mail.SenderAppID), read("b.go.tito.io") |
| + sn, err := mail.SetInstanceSenderCap(ctx, fx.rel, "bab", "titogo", isHost, 77, "op", time.Now()) |
| + if err != nil || sn.Grant.DailyCap != 77 { |
| + t.Fatalf("cap: %v %+v", err, sn) |
| + } |
| + if _, err := mail.SetSenderPaused(ctx, fx.rel, fx.srv.cfg.MailProvisioner, "bab", "titogo", isHost, true, "", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if read(mail.SenderAppID) != appBefore || read("b.go.tito.io") != sibBefore { |
| + t.Fatal("pausing one instance changed the app sender or a sibling") |
| + } |
| + _ = tok |
| + _ = u |
| +} |
| + |
| +func TestEmailStatusInstanceEntries(t *testing.T) { |
| + fx, _, _ := instanceSenderFixture(t) |
| + ctx := context.Background() |
| + if _, err := mail.CreateInstanceSender(ctx, fx.rel, "bab", "titogo", isHost, []string{"p@go.tito.io"}, "t", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + acct, _ := fx.st.AccountBySqid("bab") |
| + rec, _, err := mail.Get(ctx, fx.rel, "bab", "titogo") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out, err := fx.srv.emailReply(ctx, acct, "titogo", rec) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, e := range out["senders"].([]map[string]any) { |
| + if e["scope"] != mail.ScopeInstance { |
| + continue |
| + } |
| + if e["active"] != true || e["state"] != instanceStateSending { |
| + t.Fatalf("an unpaused instance sender reads %v/%v", e["active"], e["state"]) |
| + } |
| + } |
| +} |
| + |
| +// Every bucket write the instance-sender work makes classifies to exactly |
| +// this app (spec test 8.11, address half). |
| +func TestInstanceSenderWritesClassifyToApp(t *testing.T) { |
| + fx, _, _ := instanceSenderFixture(t) |
| + ctx := context.Background() |
| + keys := []string{ |
| + mail.SenderKey("bab", "titogo", isHost), |
| + mail.AddressKey("bab", "titogo", "p@go.tito.io"), |
| + } |
| + for _, k := range keys { |
| + c, err := hostops.ClassifyMutation(ctx, fx.rel, nil, hostops.MutationTarget{Key: k, Method: "Put", After: []byte(`{}`)}) |
| + if err != nil { |
| + t.Fatalf("%s: %v", k, err) |
| + } |
| + if len(c.Scopes) != 1 || c.Scopes[0] != (hostops.AppScope{Account: "bab", App: "titogo"}) { |
| + t.Fatalf("%s classifies to %+v", k, c.Scopes) |
| + } |
| + } |
| +} |
diff --git a/internal/console/apimail.go b/internal/console/apimail.go| index 8034aad08..134d279d4 100644 |
| --- a/internal/console/apimail.go |
| +++ b/internal/console/apimail.go |
| @@ -475,6 +475,33 @@ func (s *Server) emailReply(ctx context.Context, acct *Account, app string, rec |
| entry["pause_kind"] = pz.Kind |
| } |
| } |
| + // An instance sender holds no credential, so today's "active" rule |
| + // (a credential, not paused) would read every one as paused; its |
| + // entry says its state instead (instance senders §5). Additive. |
| + if sn.Scope == mail.ScopeInstance { |
| + var appSender *mail.Sender |
| + if len(all) > 0 && all[0].ID == mail.SenderAppID { |
| + appSender = all[0] |
| + } |
| + state, hold := instanceSenderState(sn, appSender) |
| + entry["state"] = state |
| + entry["active"] = state == instanceStateSending |
| + addrs := []string{} |
| + if sn.Grant != nil { |
| + addrs = append(addrs, sn.Grant.Addresses...) |
| + } |
| + entry["addresses"] = addrs |
| + if pending := append(append([]string(nil), sn.Reserving...), sn.Releasing...); len(pending) > 0 { |
| + entry["pending"] = pending |
| + } |
| + if sn.Removing != nil { |
| + entry["removing"] = sn.Removing |
| + } |
| + if state == instanceStateHeld { |
| + entry["pause"] = hold |
| + entry["pause_kind"] = hold.Kind |
| + } |
| + } |
| senders = append(senders, entry) |
| } |
| appPause := rec.EffectivePause() |
| @@ -1591,8 +1618,9 @@ func (s *Server) handleAPIEmailPause(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| var req struct { |
| - Paused *bool `json:"paused"` |
| - DailyCap int `json:"daily_cap"` |
| + Paused *bool `json:"paused"` |
| + DailyCap int `json:"daily_cap"` |
| + Host string `json:"host"` |
| } |
| if !readJSON(w, r, &req) { |
| return |
| @@ -1604,6 +1632,12 @@ func (s *Server) handleAPIEmailPause(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), mailPauseTimeout) |
| defer cancel() |
| + // One instance's sender only (instance senders §5): its pause and its |
| + // cap, nothing of the app sender's or a sibling's. |
| + if req.Host != "" { |
| + s.pauseInstanceSender(ctx, w, acct, app, addr, req.Host, req.Paused, req.DailyCap) |
| + return |
| + } |
| if req.DailyCap > 0 { |
| domains, err := s.mailAppDomains(ctx, acct, app) |
diff --git a/internal/console/apiservices.go b/internal/console/apiservices.go| index fd056e1b9..83fabd44d 100644 |
| --- a/internal/console/apiservices.go |
| +++ b/internal/console/apiservices.go |
| @@ -375,6 +375,9 @@ func (s *Server) handleAPIServiceCreate(w http.ResponseWriter, r *http.Request) |
| case errors.Is(err, ErrAccountScopedUsage): |
| jsonError(w, http.StatusBadRequest, usageCopyNoApp) |
| return |
| + case errors.Is(err, ErrAccountScopedMail): |
| + jsonError(w, http.StatusBadRequest, mailInstanceCopy.MailNoApp) |
| + return |
| case errors.Is(err, ErrAppScopedPlatform): |
| jsonError(w, http.StatusBadRequest, platformCopy["svc.platform_app"]) |
| return |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 5186ddc38..e39414b5c 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -26,6 +26,7 @@ import ( |
| "net/http" |
| "net/http/httptest" |
| "net/url" |
| + "slices" |
| "strconv" |
| "strings" |
| "testing" |
| @@ -414,6 +415,69 @@ func (cx *claimCase) emailDomainEnsured(t *testing.T) { |
| ensureEmailDomain(t, cx.consoleFixture, cx.bearer, "titogo", claimMailDomain) |
| } |
| +// instanceSenderWorld: titogo switched to submission on its platform mail |
| +// domain, instance acme.go.tito.io, and, with sender, that instance's own |
| +// sender holding p@<domain>. |
| +func (cx *claimCase) instanceSenderWorld(t *testing.T, sender bool) { |
| + t.Helper() |
| + cx.instanceWorld(t) |
| + cx.instance(t, `{"host":"acme.go.tito.io","region":"ie"}`) |
| + cx.emailProvisioned(t) |
| + if _, err := mail.SwitchOn(context.Background(), cx.srv.claimMailStore(), cx.srv.cfg.MailProvisioner, |
| + "bab", "titogo", nil, "setup@example.com", time.Now()); err != nil { |
| + t.Fatalf("switch on: %v", err) |
| + } |
| + if sender { |
| + if _, err := mail.CreateInstanceSender(context.Background(), cx.srv.claimMailStore(), "bab", "titogo", "acme.go.tito.io", |
| + []string{"p@" + claimMailDomain}, "setup@example.com", time.Now()); err != nil { |
| + t.Fatalf("create instance sender: %v", err) |
| + } |
| + } |
| +} |
| + |
| +// perInstanceOn stamps the app-level user as reaped (submission §7.4) |
| +// and switches per-instance mode on. |
| +func (cx *claimCase) perInstanceOn(t *testing.T) { |
| + t.Helper() |
| + ctx := context.Background() |
| + sn, etag, err := mail.GetSender(ctx, cx.rel, "bab", "titogo", mail.SenderAppID) |
| + if err != nil || sn == nil { |
| + t.Fatalf("app sender: %v", err) |
| + } |
| + now := time.Now() |
| + sn.Provisioned = nil |
| + sn.Submission.AppUserReapedAt = &now |
| + if _, err := mail.PutSender(ctx, cx.srv.claimMailStore(), "bab", "titogo", sn, etag); err != nil { |
| + t.Fatalf("stamp reaped: %v", err) |
| + } |
| + if _, err := mail.SetPerInstance(ctx, cx.srv.claimMailStore(), "bab", "titogo", true, "setup", now); err != nil { |
| + t.Fatalf("per-instance on: %v", err) |
| + } |
| +} |
| + |
| +func (cx *claimCase) senderExists(want bool) string { |
| + has, err := mail.HasInstanceSender(context.Background(), cx.rel, "bab", "titogo", "acme.go.tito.io") |
| + if err != nil { |
| + return err.Error() |
| + } |
| + if has != want { |
| + return fmt.Sprintf("instance sender exists = %v, want %v", has, want) |
| + } |
| + return "" |
| +} |
| + |
| +func (cx *claimCase) senderHolds(address string, want bool) string { |
| + sn, _, err := mail.GetSender(context.Background(), cx.rel, "bab", "titogo", "acme.go.tito.io") |
| + if err != nil { |
| + return err.Error() |
| + } |
| + held := sn != nil && sn.Grant != nil && slices.Contains(sn.Grant.Addresses, address) |
| + if held != want { |
| + return fmt.Sprintf("%s granted = %v, want %v", address, held, want) |
| + } |
| + return "" |
| +} |
| + |
| func (cx *claimCase) emailProvisioned(t *testing.T) { |
| t.Helper() |
| provisionEmail(t, cx.consoleFixture, cx.mailFake, cx.bearer, "titogo", claimMailDomain, "hello@"+claimMailDomain) |
| @@ -1831,6 +1895,66 @@ var claimFixtures = map[string]claimFixture{ |
| }, |
| do: claimAPI(http.MethodPost, "/api/cli/apps/bab/titogo/email/rotate", `{}`), |
| }}, |
| + // The instance-sender doors (instance senders §5). The world has titogo |
| + // switched to submission on its platform mail domain, with instance |
| + // acme.go.tito.io; each door's check reads the sender it changes. |
| + "route POST /api/cli/apps/{account}/{app}/instances/{host}/email": {door: &claimDoor{ |
| + apps: claimRefs("bab/titogo"), |
| + setup: func(t *testing.T, cx *claimCase) { cx.instanceSenderWorld(t, false) }, |
| + do: claimAPI(http.MethodPost, "/api/cli/apps/bab/titogo/instances/acme.go.tito.io/email", |
| + `{"addresses":["p@`+claimMailDomain+`"]}`), |
| + check: func(t *testing.T, cx *claimCase, open bool) string { |
| + return cx.senderExists(open) |
| + }, |
| + }}, |
| + "route GET /api/cli/apps/{account}/{app}/instances/{host}/email": claimRead("reads one instance's email sender and today's counts"), |
| + "route DELETE /api/cli/apps/{account}/{app}/instances/{host}/email": {door: &claimDoor{ |
| + apps: claimRefs("bab/titogo"), |
| + setup: func(t *testing.T, cx *claimCase) { cx.instanceSenderWorld(t, true) }, |
| + do: claimAPI(http.MethodDelete, "/api/cli/apps/bab/titogo/instances/acme.go.tito.io/email", ""), |
| + check: func(t *testing.T, cx *claimCase, open bool) string { |
| + return cx.senderExists(!open) |
| + }, |
| + }}, |
| + "route PUT /api/cli/apps/{account}/{app}/instances/{host}/email/addresses/{address}": {door: &claimDoor{ |
| + apps: claimRefs("bab/titogo"), |
| + setup: func(t *testing.T, cx *claimCase) { cx.instanceSenderWorld(t, true) }, |
| + do: claimAPI(http.MethodPut, "/api/cli/apps/bab/titogo/instances/acme.go.tito.io/email/addresses/q@"+claimMailDomain, ""), |
| + check: func(t *testing.T, cx *claimCase, open bool) string { |
| + return cx.senderHolds("q@"+claimMailDomain, open) |
| + }, |
| + }}, |
| + "route DELETE /api/cli/apps/{account}/{app}/instances/{host}/email/addresses/{address}": {door: &claimDoor{ |
| + apps: claimRefs("bab/titogo"), |
| + setup: func(t *testing.T, cx *claimCase) { cx.instanceSenderWorld(t, true) }, |
| + do: claimAPI(http.MethodDelete, "/api/cli/apps/bab/titogo/instances/acme.go.tito.io/email/addresses/p@"+claimMailDomain, ""), |
| + check: func(t *testing.T, cx *claimCase, open bool) string { |
| + return cx.senderHolds("p@"+claimMailDomain, !open) |
| + }, |
| + }}, |
| + // Per-instance mode switches off here: on needs the app-level user |
| + // reaped, which setup stamps directly before switching on. |
| + "route POST /api/cli/apps/{account}/{app}/email/per-instance": {door: &claimDoor{ |
| + apps: claimRefs("bab/titogo"), |
| + setup: func(t *testing.T, cx *claimCase) { |
| + cx.instanceSenderWorld(t, false) |
| + cx.perInstanceOn(t) |
| + }, |
| + do: claimAPI(http.MethodPost, "/api/cli/apps/bab/titogo/email/per-instance", `{"on":false}`), |
| + check: func(t *testing.T, cx *claimCase, open bool) string { |
| + sn, _, err := mail.GetSender(context.Background(), cx.rel, "bab", "titogo", mail.SenderAppID) |
| + if err != nil { |
| + return err.Error() |
| + } |
| + switch { |
| + case open && sn.PerInstance: |
| + return "the open run did not switch per-instance mode off" |
| + case !open && !sn.PerInstance: |
| + return "a refused run switched per-instance mode off" |
| + } |
| + return "" |
| + }, |
| + }}, |
| // The submission switch (platform mail submission Task 6). The door |
| // switches off: on needs fresh box reports, records and declared |
| // builds this world does not stage, and both directions write the same |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index 2a3343bd2..1dd088605 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -293,6 +293,8 @@ var claimReadProbes = map[string]claimProbe{ |
| "route GET /api/cli/apps/{account}/{app}/policy": claimAPIRead(claimWorldPolicy, "/api/cli/apps/bab/titogo/policy", `"default_size":"small"`), |
| "route GET /api/cli/apps/{account}/{app}/email": claimAPIRead(func(t *testing.T, cx *claimCase) { cx.emailDeclared(t) }, |
| "/api/cli/apps/bab/titogo/email", claimMailDomain), |
| + "route GET /api/cli/apps/{account}/{app}/instances/{host}/email": claimAPIRead(func(t *testing.T, cx *claimCase) { cx.instanceSenderWorld(t, true) }, |
| + "/api/cli/apps/bab/titogo/instances/acme.go.tito.io/email", "p@"+claimMailDomain), |
| "route GET /api/cli/apps/{account}/{app}/email/events": claimAPIRead(func(t *testing.T, cx *claimCase) { cx.emailProvisioned(t) }, |
| "/api/cli/apps/bab/titogo/email/events", `"events"`), |
| "route GET /api/cli/apps/{account}/{app}/email/events/push": claimAPIRead(func(t *testing.T, cx *claimCase) { cx.emailPush(t) }, |
diff --git a/internal/console/linkedpolicy.go b/internal/console/linkedpolicy.go| index 930bf871b..083d415c6 100644 |
| --- a/internal/console/linkedpolicy.go |
| +++ b/internal/console/linkedpolicy.go |
| @@ -310,6 +310,14 @@ var linkedPolicies = map[string]linkedPolicy{ |
| "POST /api/cli/apps/{account}/{app}/email/domains": linkedRefuse, |
| "POST /api/cli/apps/{account}/{app}/email/domains/{domain}/verify": linkedRefuse, |
| "DELETE /api/cli/apps/{account}/{app}/email/domains/{domain}": linkedRefuse, |
| + // Instance senders (instance senders §5): a linked app's instances and |
| + // their senders live at home. |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/email": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/instances/{host}/email": linkedRefuse, |
| + "DELETE /api/cli/apps/{account}/{app}/instances/{host}/email": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/instances/{host}/email/addresses/{address}": linkedRefuse, |
| + "DELETE /api/cli/apps/{account}/{app}/instances/{host}/email/addresses/{address}": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/email/per-instance": linkedRefuse, |
| // The box doors: a linked app has no instance records for them to name. |
| "POST /api/fleet/replicas/{account}/{app}/{host}/coordinator": linkedRefuse, |
diff --git a/internal/console/mailinstance_copy.go b/internal/console/mailinstance_copy.go| new file mode 100644 |
| index 000000000..ad691e89d |
| --- /dev/null |
| +++ b/internal/console/mailinstance_copy.go |
| @@ -0,0 +1,34 @@ |
| +package console |
| + |
| +// mailInstanceCopy is every user-facing string of the instance-sender doors |
| +// (instance senders design §5), as approved in copy review. |
| +var mailInstanceCopy = struct { |
| + InvalidHost, NoInstance, AddressSyntax, AddressNotASCII, AddressTooLong, AddressDomain string |
| + AddressTaken, DomainShared, DomainNotApp, TooMany, SenderRemoving, AddressPending string |
| + AddressConcurrent, SubmissionOff, InstanceSendersExist, AppUserNotReaped string |
| + SenderInventory, WriteFailed, InstanceDeleteHasSender, DomainInUse, DomainHeld string |
| + MailNoApp string |
| +}{ |
| + InvalidHost: "That host name can't name an instance.", |
| + NoInstance: "This app has no instance at %s.", |
| + AddressSyntax: "%s isn't a single email address. Give just the address, like paul@example.com, with no name or angle brackets.", |
| + AddressNotASCII: "%s has characters outside plain ASCII, which these addresses can't use.", |
| + AddressTooLong: "%s is longer than 254 characters.", |
| + AddressDomain: "%s doesn't end in a valid domain name.", |
| + AddressTaken: "That address is already in use by another instance.", |
| + DomainShared: "%s is shared with another app, so its addresses can't be given to one instance.", |
| + DomainNotApp: "This app doesn't send from %s. Add the domain to the app first: carlos email domains add --app %s %s", |
| + TooMany: "An instance can have at most 50 addresses.", |
| + SenderRemoving: "This instance's email sender is being removed. Run carlos email instance rm again to finish, then try again.", |
| + AddressPending: "That address is still being released. Try again in a moment.", |
| + AddressConcurrent: "That address changed while this was running. Try again.", |
| + SubmissionOff: "This app doesn't send through the platform's mailer yet. Turn that on first: carlos email submission on --app %s", |
| + InstanceSendersExist: "This app still has instance senders. Remove them first with carlos email instance rm.", |
| + AppUserNotReaped: "This app's SMTP credential hasn't been retired yet. Per-instance mode can start a week after submission went on, once that credential is gone.", |
| + SenderInventory: "Couldn't read every sender of this app. Try again.", |
| + WriteFailed: "Couldn't change this instance's email. Try again.", |
| + InstanceDeleteHasSender: "This instance still has an email sender. Remove it first: carlos email instance rm --app %s --host %s", |
| + DomainInUse: "%d instance addresses use %s. Revoke them first with carlos email addresses rm.", |
| + DomainHeld: "%s is held for one app's instance addresses, so another app can't share it.", |
| + MailNoApp: "A mail credential works for one app. Name it with --app.", |
| +} |
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go| index c94e1648a..e86f527f1 100644 |
| --- a/internal/console/routedecls.go |
| +++ b/internal/console/routedecls.go |
| @@ -1429,6 +1429,16 @@ var routeDecls = []routeDecl{ |
| {Pattern: "POST /api/cli/apps/{account}/{app}/email/credentials", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIEmailCredentialsCreate}, |
| {Pattern: "DELETE /api/cli/apps/{account}/{app}/email/credentials/{name}", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIEmailCredentialsRevoke}, |
| {Pattern: "POST /api/cli/apps/{account}/{app}/email/pause", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIEmailPause}, |
| + // The instance-sender doors (instance senders design §5, decision 12): |
| + // the mail role, which an app's backend holds to onboard its |
| + // instances' senders and addresses without Admin (which can deploy). |
| + // Per-instance mode changes how every instance sends, so it is Admin's. |
| + {Pattern: "POST /api/cli/apps/{account}/{app}/instances/{host}/email", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Mail), Handler: (*Server).handleAPIInstanceSenderCreate}, |
| + {Pattern: "GET /api/cli/apps/{account}/{app}/instances/{host}/email", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Mail), Handler: (*Server).handleAPIInstanceSenderStatus}, |
| + {Pattern: "DELETE /api/cli/apps/{account}/{app}/instances/{host}/email", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Mail), Handler: (*Server).handleAPIInstanceSenderRemove}, |
| + {Pattern: "PUT /api/cli/apps/{account}/{app}/instances/{host}/email/addresses/{address}", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Mail), Handler: (*Server).handleAPIInstanceAddressGrant}, |
| + {Pattern: "DELETE /api/cli/apps/{account}/{app}/instances/{host}/email/addresses/{address}", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Mail), Handler: (*Server).handleAPIInstanceAddressRevoke}, |
| + {Pattern: "POST /api/cli/apps/{account}/{app}/email/per-instance", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIEmailPerInstance}, |
| } |
| // registerDecls is THE loop: every declaration match accepts and whose gate |
diff --git a/internal/console/svcpage.go b/internal/console/svcpage.go| index 640508878..744d1a948 100644 |
| --- a/internal/console/svcpage.go |
| +++ b/internal/console/svcpage.go |
| @@ -415,6 +415,9 @@ func (s *Server) handleServiceCreatePage(w http.ResponseWriter, r *http.Request) |
| case errors.Is(err, ErrAccountScopedUsage): |
| back("err", usageCopyNoApp) |
| return |
| + case errors.Is(err, ErrAccountScopedMail): |
| + back("err", mailInstanceCopy.MailNoApp) |
| + return |
| case errors.Is(err, ErrAccountScopedDeploy): |
| back("err", "A deploy credential must name one app. Nothing was minted.") |
| return |
diff --git a/internal/console/svcprincipal.go b/internal/console/svcprincipal.go| index b02770f96..a5409f2f1 100644 |
| --- a/internal/console/svcprincipal.go |
| +++ b/internal/console/svcprincipal.go |
| @@ -242,6 +242,12 @@ FROM cli_tokens WHERE token_hash = ?`, hash). |
| if r == svcrole.Usage && app == "" { |
| return Principal{}, false |
| } |
| + // A mail credential is minted bound to one app (instance senders |
| + // decision 12), so one with no app is a row this console did not |
| + // write, never a credential onboarding every app's instances. |
| + if r == svcrole.Mail && app == "" { |
| + return Principal{}, false |
| + } |
| p = Principal{Kind: PrincipalService, Address: addr, AccountID: accountID, App: app, Role: r, Name: name, Rungs: scope, |
| CredentialID: credID, Commands: granted, Scope: teamScope} |
| // A platform credential is its own account's, bound to no app, |
| @@ -305,6 +311,9 @@ const ( |
| // store refuses it, so neither mint door can forget it. |
| var ErrAccountScopedUsage = errors.New(usageCopyNoApp) |
| +// ErrAccountScopedMail is a mail credential minted without an app. |
| +var ErrAccountScopedMail = errors.New(mailInstanceCopy.MailNoApp) |
| + |
| // ErrUsageOff is a usage credential minted while CONSOLE_INSTANCE_USAGE is |
| // off. The store has no config, so this one is the server's |
| // (usageMintRefusal), checked by both mint doors before the store. |
| @@ -519,6 +528,11 @@ func (s *Store) claimRawNewServicePrincipalScoped(accountID int64, name, app str |
| if role == svcrole.Usage && app == "" { |
| return "", ErrAccountScopedUsage |
| } |
| + // A mail credential onboards one app's instances (instance senders |
| + // decision 12), so it names that app. |
| + if role == svcrole.Mail && app == "" { |
| + return "", ErrAccountScopedMail |
| + } |
| canon, err := canonicalRungs(rungs) |
| if err != nil { |
| return "", err |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 0c476a429..caa0a0c6c 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -23,6 +23,8 @@ route DELETE /api/cli/apps/{account}/{app}/email/credentials/{name} |
| route DELETE /api/cli/apps/{account}/{app}/email/domains/{domain} |
| route DELETE /api/cli/apps/{account}/{app}/email/events/push |
| route DELETE /api/cli/apps/{account}/{app}/instances/{host} |
| +route DELETE /api/cli/apps/{account}/{app}/instances/{host}/email |
| +route DELETE /api/cli/apps/{account}/{app}/instances/{host}/email/addresses/{address} |
| route DELETE /api/cli/apps/{account}/{app}/instances/{host}/move |
| route DELETE /api/cli/apps/{account}/{app}/sidecars/{name} |
| route DELETE /api/cli/link |
| @@ -105,6 +107,7 @@ route GET /api/cli/apps/{account}/{app}/geo |
| route GET /api/cli/apps/{account}/{app}/instances |
| route GET /api/cli/apps/{account}/{app}/instances/{host} |
| route GET /api/cli/apps/{account}/{app}/instances/{host}/backups |
| +route GET /api/cli/apps/{account}/{app}/instances/{host}/email |
| route GET /api/cli/apps/{account}/{app}/instances/{host}/interactive |
| route GET /api/cli/apps/{account}/{app}/instances/{host}/move |
| route GET /api/cli/apps/{account}/{app}/instances/{host}/move/offline |
| @@ -294,6 +297,7 @@ route POST /api/cli/apps/{account}/{app}/email/domains |
| route POST /api/cli/apps/{account}/{app}/email/domains/{domain}/verify |
| route POST /api/cli/apps/{account}/{app}/email/enable |
| route POST /api/cli/apps/{account}/{app}/email/pause |
| +route POST /api/cli/apps/{account}/{app}/email/per-instance |
| route POST /api/cli/apps/{account}/{app}/email/rotate |
| route POST /api/cli/apps/{account}/{app}/email/submission |
| route POST /api/cli/apps/{account}/{app}/environments/fork |
| @@ -303,6 +307,7 @@ route POST /api/cli/apps/{account}/{app}/features |
| route POST /api/cli/apps/{account}/{app}/instance-token |
| route POST /api/cli/apps/{account}/{app}/instances |
| route POST /api/cli/apps/{account}/{app}/instances/{host}/channel |
| +route POST /api/cli/apps/{account}/{app}/instances/{host}/email |
| route POST /api/cli/apps/{account}/{app}/instances/{host}/gate-pass |
| route POST /api/cli/apps/{account}/{app}/instances/{host}/import/abort |
| route POST /api/cli/apps/{account}/{app}/instances/{host}/import/commit |
| @@ -436,6 +441,7 @@ route PUT /api/cli/apps/{account}/{app}/domains/{host}/paths |
| route PUT /api/cli/apps/{account}/{app}/domains/{host}/placements |
| route PUT /api/cli/apps/{account}/{app}/email/events/push |
| route PUT /api/cli/apps/{account}/{app}/instances-manifest |
| +route PUT /api/cli/apps/{account}/{app}/instances/{host}/email/addresses/{address} |
| route PUT /api/cli/apps/{account}/{app}/instances/{host}/import |
| route PUT /api/cli/apps/{account}/{app}/instances/{host}/updates |
| route PUT /api/cli/apps/{account}/{app}/interactive |
diff --git a/internal/mail/addresses.go b/internal/mail/addresses.go| index eb39dcc01..fae9aa7da 100644 |
| --- a/internal/mail/addresses.go |
| +++ b/internal/mail/addresses.go |
| @@ -350,7 +350,7 @@ func canonicalAll(addresses []string) ([]string, error) { |
| for _, a := range addresses { |
| c, err := mailwire.CanonicalAddress(a) |
| if err != nil { |
| - return nil, fmt.Errorf("%q: %w", a, err) |
| + return nil, fmt.Errorf("%s: %w", a, err) |
| } |
| if !slices.Contains(out, c) { |
| out = append(out, c) |
| @@ -801,3 +801,22 @@ func RevokeAddress(ctx context.Context, s release.Store, acct, app, id, address |
| }) |
| return out, err |
| } |
| + |
| +// IsAddressConcurrent reports a grant that a concurrent call finished or |
| +// revoked first (only without the app lock, which the exported functions |
| +// hold; kept for callers that map every outcome). |
| +func IsAddressConcurrent(err error) bool { return errors.Is(err, errAddressConcurrent) } |
| + |
| +// RefusalSubject is the subject a refusal of this package names first |
| +// ("<address or domain>: <reason>"), for a door's message; "" when it |
| +// names none. |
| +func RefusalSubject(err error) string { |
| + if err == nil { |
| + return "" |
| + } |
| + msg := err.Error() |
| + if i := strings.Index(msg, ": "); i > 0 && !strings.HasPrefix(msg, "mail:") { |
| + return msg[:i] |
| + } |
| + return "" |
| +} |
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 02260a4c2..03f27f3de 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv |
| @@ -1,5 +1,6 @@ |
| # Census overlay instance-senders-1, written by census-propose (#369). census-ruling-instance-senders-1, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-instance-senders-1.md. |
| -# 0 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 0 body, 0 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage . ab9b3e4b011a4dfa36e85d6a8302e8cb7b88e7cdcd6e20b3e329af8d2e4ca210 |
| @coverage internal/mailer 7faad983d368293409cd67c257a99faf7814075cc0bf9dad034955ce849dce26 |
| @coverage internal/mailsubmit 293b1864d19aa444237d4976d8e4d5bcffbed8b268c9c4fd7fade244d0b0f604 |
| @coverage internal/mailwire a080b525495cc7762aa536a015ce961f6263c3e89d69bb115adb5a64978d84d6 |
diff --git a/mail_cli.go b/mail_cli.go| index 64c322e47..747ae8d10 100644 |
| --- a/mail_cli.go |
| +++ b/mail_cli.go |
| @@ -62,7 +62,7 @@ import ( |
| "github.com/carlosframework/platform/internal/clireg" |
| ) |
| -const emailUsage = `usage: carlos email <enable|domains|status|test|credentials|submission|rotate|pause|resume> [flags] |
| +const emailUsage = `usage: carlos email <enable|domains|status|test|credentials|submission|instance|addresses|per-instance|rotate|pause|resume> [flags] |
| enable --app <a> [--env-prefix <PREFIX>] [--from <addr>] [--domain <d>] [--timeout <dur>] |
| declare, ensure a sending domain, wait for it to |
| @@ -129,10 +129,20 @@ const emailUsage = `usage: carlos email <enable|domains|status|test|credentials| |
| submission on|off --app <a> |
| send through the box, with no SMTP credential in |
| the app (on), or deliver the credential again (off). |
| + instance create|status|rm --app <a> --host <h> [--address <addr>]... |
| + give one instance of an app its own email sender, show |
| + it, or remove it. Create can grant addresses at once. |
| + addresses add|rm --app <a> --host <h> <address> |
| + let an instance send as one exact address on the app's |
| + domain, or stop it. |
| + per-instance on|off --app <a> |
| + make every instance send only as its own sender. An |
| + instance with no sender can't send at all. |
| rotate --app <a> [--finish] |
| mint a fresh delivered credential, leaving the old |
| one live until --finish deletes it. |
| - pause --app <a> stop this app's sending — operator only. |
| + pause --app <a> [--host <h>] |
| + stop this app's sending — operator only. |
| resume --app <a> resume it — operator only. this lifts a plan's |
| email hold too, until the app's next send while its |
| limit is still used up |
| @@ -205,6 +215,36 @@ func emailCommand() *clireg.Node { |
| Fallback: usage, |
| }, |
| raw("rotate", cust, runEmailRotate), |
| + // One instance's own sender and its addresses (instance senders |
| + // design §5), and the app switch that makes them the only way out. |
| + { |
| + Name: "instance", |
| + Audience: cust, |
| + Children: []*clireg.Node{ |
| + rawErr("create", cust, runEmailInstanceCreate), |
| + rawErr("status", cust, runEmailInstanceStatus), |
| + rawErr("rm", cust, runEmailInstanceRm), |
| + }, |
| + Fallback: usage, |
| + }, |
| + { |
| + Name: "addresses", |
| + Audience: cust, |
| + Children: []*clireg.Node{ |
| + rawErr("add", cust, func(args []string) error { return runEmailAddresses(args, true) }), |
| + rawErr("rm", cust, func(args []string) error { return runEmailAddresses(args, false) }), |
| + }, |
| + Fallback: usage, |
| + }, |
| + { |
| + Name: "per-instance", |
| + Audience: cust, |
| + Children: []*clireg.Node{ |
| + rawErr("on", cust, func(args []string) error { return runEmailPerInstance(args, true) }), |
| + rawErr("off", cust, func(args []string) error { return runEmailPerInstance(args, false) }), |
| + }, |
| + Fallback: usage, |
| + }, |
| raw("pause", op, func(args []string) { runEmailPause(args, true) }), |
| raw("resume", op, func(args []string) { runEmailPause(args, false) }), |
| }, |
| @@ -323,6 +363,11 @@ type apiEmailSender struct { |
| DailyCap int `json:"daily_cap"` |
| KeyID string `json:"key_id,omitempty"` |
| Counts apiEmailCounts `json:"counts"` |
| + // Instance senders only (instance senders §5); absent from an older |
| + // console, which then renders as before. |
| + Addresses []string `json:"addresses,omitempty"` |
| + Pending []string `json:"pending,omitempty"` |
| + State string `json:"state,omitempty"` |
| } |
| // apiEmailReply is the shape every declare/status/enable/rotate/pause door |
| @@ -1601,6 +1646,12 @@ func printEmailStatus(w io.Writer, res apiEmailReply) { |
| if len(res.Senders) > 1 { |
| fmt.Fprintln(w, " senders:") |
| for _, sn := range res.Senders { |
| + if sn.Scope == "instance" && sn.State != "" { |
| + w2 := &prefixWriter{w: w, prefix: " "} |
| + printInstanceSender(w2, apiInstanceSender{Host: sn.Host, ID: sn.ID, Addresses: sn.Addresses, Pending: sn.Pending, |
| + State: sn.State, Pause: sn.Pause, DailyCap: sn.DailyCap, Counts: sn.Counts}) |
| + continue |
| + } |
| what := sn.ID |
| if sn.Host != "" { |
| what = sn.Host |
| @@ -2047,12 +2098,13 @@ func runEmailPause(args []string, paused bool) { |
| } |
| fs := flag.NewFlagSet("email "+verb, flag.ExitOnError) |
| app := appFlag(fs, "app to "+verb) |
| + host := fs.String("host", "", "pause or resume only this instance's own sender") |
| acctRaw, acctIDRaw, _ := accountFlags(fs) |
| consoleFlag := consoleOption(fs, "console origin (API mode only; default: the only logged-in one)") |
| fs.Usage = flagUsage(fs, "") |
| fs.Parse(args) |
| name := strings.TrimSpace(*app) |
| - usage := fmt.Sprintf("usage: carlos email %s --app <a> [--account <sqid-or-name>] [--account-id <sqid>] [--console <origin>]", verb) |
| + usage := fmt.Sprintf("usage: carlos email %s --app <a> [--host <h>] [--account <sqid-or-name>] [--account-id <sqid>] [--console <origin>]", verb) |
| if name != "" { |
| if err := validAppName(name); err != nil { |
| log.Fatalf("email %s: %v", verb, err) |
| @@ -2063,10 +2115,20 @@ func runEmailPause(args []string, paused bool) { |
| printUsing(stdout, sess) |
| acct := resolvedAccount(sess, acctRaw, acctIDRaw) |
| name = resolvedApp(sess, acct, name, usage) |
| - res, err := sess.emailPause(context.Background(), acct, name, paused) |
| + var res apiEmailReply |
| + var err error |
| + h := strings.TrimSpace(*host) |
| + if h != "" { |
| + err = pauseInstanceSender(sess, acct, name, h, paused) |
| + } else { |
| + res, err = sess.emailPause(context.Background(), acct, name, paused) |
| + } |
| if err != nil { |
| log.Fatalf("email %s: %v", verb, err) |
| } |
| + if h != "" { |
| + return // pauseInstanceSender printed the instance's line |
| + } |
| c := colorFor(stdout) |
| fmt.Fprintf(stdout, "%s %s\n", c.ok(verb+"d email for"), res.App) |
| } |
diff --git a/mail_instance_cli.go b/mail_instance_cli.go| new file mode 100644 |
| index 000000000..47fdbc02b |
| --- /dev/null |
| +++ b/mail_instance_cli.go |
| @@ -0,0 +1,296 @@ |
| +package main |
| + |
| +// mail_instance_cli.go is `carlos email instance`, `carlos email addresses` |
| +// and `carlos email per-instance` (instance senders design §5): give one |
| +// instance of an app its own email sender and exact addresses, and switch |
| +// the app to sending only through them. Every run function returns an |
| +// error (AGENTS.md "Writing Go here"); the dispatcher prints it. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "flag" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// apiInstanceSender decodes the console's apiInstanceSenderReply. |
| +type apiInstanceSender struct { |
| + Host string `json:"host"` |
| + ID string `json:"id"` |
| + Addresses []string `json:"addresses"` |
| + Pending []string `json:"pending,omitempty"` |
| + Removing *time.Time `json:"removing,omitempty"` |
| + State string `json:"state"` |
| + Pause *apiEmailPause `json:"pause,omitempty"` |
| + DailyCap int `json:"daily_cap"` |
| + Counts apiEmailCounts `json:"counts"` |
| +} |
| + |
| +// instanceStateWord is the state, as the status line leads with it. |
| +func instanceStateWord(state string, pz *apiEmailPause) string { |
| + kind := "" |
| + if pz != nil { |
| + kind = pz.Kind |
| + } |
| + switch state { |
| + case "paused": |
| + return fmt.Sprintf(instanceCLICopy.Paused, orManual(kind)) |
| + case "held": |
| + return fmt.Sprintf(instanceCLICopy.Held, orManual(kind)) |
| + case "removing": |
| + return instanceCLICopy.Removing |
| + default: |
| + return instanceCLICopy.Sending |
| + } |
| +} |
| + |
| +func orManual(kind string) string { |
| + if kind == "" { |
| + return "manual" |
| + } |
| + return kind |
| +} |
| + |
| +// printInstanceSender is one instance's line, state first, then its |
| +// pending addresses on a second line when there are any. |
| +func printInstanceSender(w io.Writer, s apiInstanceSender) { |
| + addrs := instanceCLICopy.NoAddresses |
| + if len(s.Addresses) > 0 { |
| + addrs = strings.Join(s.Addresses, ", ") |
| + } |
| + fmt.Fprintf(w, instanceCLICopy.Line+"\n", s.Host, instanceStateWord(s.State, s.Pause), addrs, |
| + s.Counts.Sends, s.DailyCap, s.Counts.Bounces) |
| + if len(s.Pending) > 0 { |
| + fmt.Fprintf(w, " "+instanceCLICopy.Pending+"\n", strings.Join(s.Pending, ", ")) |
| + } |
| +} |
| + |
| +// instanceFlags parses --app, --host and the account/console flags shared |
| +// by every instance verb. |
| +type instanceArgs struct { |
| + app, host, console string |
| + acctRaw, acctID *string |
| + addresses multiFlag |
| + rest []string |
| +} |
| + |
| +func parseInstanceArgs(verb string, args []string, withAddress bool) (*instanceArgs, error) { |
| + fs := flag.NewFlagSet(verb, flag.ContinueOnError) |
| + fs.SetOutput(io.Discard) |
| + out := &instanceArgs{} |
| + app := appFlag(fs, "app the instance belongs to") |
| + host := fs.String("host", "", "the instance's host name") |
| + out.acctRaw, out.acctID, _ = accountFlags(fs) |
| + consoleFlag := consoleOption(fs, "console origin (API mode only; default: the only logged-in one)") |
| + if withAddress { |
| + fs.Var(&out.addresses, "address", "an address to grant as the sender is created (repeat for more)") |
| + } |
| + if err := fs.Parse(args); err != nil { |
| + return nil, fmt.Errorf("%s: %w", verb, err) |
| + } |
| + out.app, out.host, out.console, out.rest = strings.TrimSpace(*app), strings.TrimSpace(*host), *consoleFlag, fs.Args() |
| + if out.app == "" || out.host == "" { |
| + return nil, fmt.Errorf("usage: carlos %s --app <a> --host <h>", verb) |
| + } |
| + if err := validAppName(out.app); err != nil { |
| + return nil, fmt.Errorf("%s: %w", verb, err) |
| + } |
| + return out, nil |
| +} |
| + |
| +func (a *instanceArgs) session() (*apiSession, apiAcct) { |
| + sess := requireMailAPISession(a.console) |
| + printUsing(stdout, sess) |
| + return sess, resolvedAccount(sess, a.acctRaw, a.acctID) |
| +} |
| + |
| +func instanceSenderPath(a apiAcct, app, host, tail string) string { |
| + return apiPath(a, app, "/instances/"+url.PathEscape(host)+"/email"+tail) |
| +} |
| + |
| +func decodeInstanceSender(status int, body []byte, ok int) (apiInstanceSender, error) { |
| + if status != ok { |
| + return apiInstanceSender{}, mailAPIError(status, body) |
| + } |
| + var out apiInstanceSender |
| + if err := json.Unmarshal(body, &out); err != nil { |
| + return apiInstanceSender{}, fmt.Errorf("unreadable response: %w", err) |
| + } |
| + return out, nil |
| +} |
| + |
| +func runEmailInstanceCreate(args []string) error { |
| + a, err := parseInstanceArgs("email instance create", args, true) |
| + if err != nil { |
| + return err |
| + } |
| + sess, acct := a.session() |
| + status, body, err := sess.postJSON(context.Background(), instanceSenderPath(acct, a.app, a.host, ""), |
| + struct { |
| + Addresses []string `json:"addresses"` |
| + }{a.addresses}) |
| + if err != nil { |
| + return err |
| + } |
| + s, err := decodeInstanceSender(status, body, http.StatusOK) |
| + if err != nil { |
| + return fmt.Errorf("email instance create: %w", err) |
| + } |
| + fmt.Fprintf(stdout, instanceCLICopy.Created+"\n", s.Host) |
| + printInstanceSender(stdout, s) |
| + return nil |
| +} |
| + |
| +func runEmailInstanceStatus(args []string) error { |
| + a, err := parseInstanceArgs("email instance status", args, false) |
| + if err != nil { |
| + return err |
| + } |
| + sess, acct := a.session() |
| + status, body, err := sess.getJSON(context.Background(), instanceSenderPath(acct, a.app, a.host, "")) |
| + if err != nil { |
| + return err |
| + } |
| + s, err := decodeInstanceSender(status, body, http.StatusOK) |
| + if err != nil { |
| + return fmt.Errorf("email instance status: %w", err) |
| + } |
| + printInstanceSender(stdout, s) |
| + return nil |
| +} |
| + |
| +func runEmailInstanceRm(args []string) error { |
| + a, err := parseInstanceArgs("email instance rm", args, false) |
| + if err != nil { |
| + return err |
| + } |
| + sess, acct := a.session() |
| + status, body, err := sess.deleteJSON(context.Background(), instanceSenderPath(acct, a.app, a.host, "")) |
| + if err != nil { |
| + return err |
| + } |
| + if status != http.StatusOK { |
| + return fmt.Errorf("email instance rm: %w", mailAPIError(status, body)) |
| + } |
| + fmt.Fprintf(stdout, instanceCLICopy.Removed+"\n", a.host) |
| + return nil |
| +} |
| + |
| +func runEmailAddresses(args []string, add bool) error { |
| + verb := "email addresses rm" |
| + if add { |
| + verb = "email addresses add" |
| + } |
| + a, err := parseInstanceArgs(verb, args, false) |
| + if err != nil { |
| + return err |
| + } |
| + if len(a.rest) != 1 { |
| + return fmt.Errorf("usage: carlos %s --app <a> --host <h> <address>", verb) |
| + } |
| + address := a.rest[0] |
| + sess, acct := a.session() |
| + path := instanceSenderPath(acct, a.app, a.host, "/addresses/"+url.PathEscape(address)) |
| + var status int |
| + var body []byte |
| + if add { |
| + status, body, err = sess.putJSON(context.Background(), path, struct{}{}) |
| + } else { |
| + status, body, err = sess.deleteJSON(context.Background(), path) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + s, err := decodeInstanceSender(status, body, http.StatusOK) |
| + if err != nil { |
| + return fmt.Errorf("%s: %w", verb, err) |
| + } |
| + if add { |
| + fmt.Fprintf(stdout, instanceCLICopy.AddressAdded+"\n", s.Host, strings.ToLower(address)) |
| + } else { |
| + fmt.Fprintf(stdout, instanceCLICopy.AddressRemoved+"\n", s.Host, strings.ToLower(address)) |
| + } |
| + return nil |
| +} |
| + |
| +func runEmailPerInstance(args []string, on bool) error { |
| + verb := "email per-instance off" |
| + if on { |
| + verb = "email per-instance on" |
| + } |
| + fs := flag.NewFlagSet(verb, flag.ContinueOnError) |
| + fs.SetOutput(io.Discard) |
| + app := appFlag(fs, "app to switch") |
| + acctRaw, acctIDRaw, _ := accountFlags(fs) |
| + consoleFlag := consoleOption(fs, "console origin (API mode only; default: the only logged-in one)") |
| + if err := fs.Parse(args); err != nil { |
| + return fmt.Errorf("%s: %w", verb, err) |
| + } |
| + name := strings.TrimSpace(*app) |
| + if name == "" { |
| + return fmt.Errorf("usage: carlos %s --app <a>", verb) |
| + } |
| + if err := validAppName(name); err != nil { |
| + return fmt.Errorf("%s: %w", verb, err) |
| + } |
| + sess := requireMailAPISession(*consoleFlag) |
| + printUsing(stdout, sess) |
| + acct := resolvedAccount(sess, acctRaw, acctIDRaw) |
| + status, body, err := sess.postJSON(context.Background(), apiPath(acct, name, "/email/per-instance"), struct { |
| + On bool `json:"on"` |
| + }{on}) |
| + if err != nil { |
| + return err |
| + } |
| + if status != http.StatusOK { |
| + return fmt.Errorf("%s: %w", verb, mailAPIError(status, body)) |
| + } |
| + if on { |
| + fmt.Fprintf(stdout, instanceCLICopy.PerInstanceOn+"\n", name) |
| + } else { |
| + fmt.Fprintf(stdout, instanceCLICopy.PerInstanceOff+"\n", name) |
| + } |
| + return nil |
| +} |
| + |
| +// pauseInstanceSender is `carlos email pause|resume --host`: one instance's |
| +// own sender, through the operator pause door's host field. |
| +func pauseInstanceSender(sess *apiSession, acct apiAcct, app, host string, paused bool) error { |
| + status, body, err := sess.postJSON(context.Background(), apiPath(acct, app, "/email/pause"), struct { |
| + Paused *bool `json:"paused"` |
| + Host string `json:"host"` |
| + }{&paused, host}) |
| + if err != nil { |
| + return err |
| + } |
| + s, err := decodeInstanceSender(status, body, http.StatusOK) |
| + if err != nil { |
| + return err |
| + } |
| + printInstanceSender(stdout, s) |
| + return nil |
| +} |
| + |
| +// prefixWriter indents every line written through it. |
| +type prefixWriter struct { |
| + w io.Writer |
| + prefix string |
| +} |
| + |
| +func (p *prefixWriter) Write(b []byte) (int, error) { |
| + lines := strings.SplitAfter(string(b), "\n") |
| + for _, l := range lines { |
| + if l == "" { |
| + continue |
| + } |
| + if _, err := io.WriteString(p.w, p.prefix+l); err != nil { |
| + return 0, err |
| + } |
| + } |
| + return len(b), nil |
| +} |
diff --git a/mail_instance_cli_test.go b/mail_instance_cli_test.go| new file mode 100644 |
| index 000000000..d043e291a |
| --- /dev/null |
| +++ b/mail_instance_cli_test.go |
| @@ -0,0 +1,71 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "fmt" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestPrintInstanceSenderStates(t *testing.T) { |
| + base := apiInstanceSender{Host: "a.shop.example", Addresses: []string{"paul@shop.example"}, DailyCap: 50, |
| + Counts: apiEmailCounts{Sends: 3, Bounces: 1}} |
| + cases := []struct { |
| + state string |
| + pause *apiEmailPause |
| + word string |
| + }{ |
| + {"sending", nil, instanceCLICopy.Sending}, |
| + {"paused", &apiEmailPause{Kind: "cap"}, fmt.Sprintf(instanceCLICopy.Paused, "cap")}, |
| + {"paused", &apiEmailPause{}, fmt.Sprintf(instanceCLICopy.Paused, "manual")}, |
| + {"held", &apiEmailPause{Kind: "plan"}, fmt.Sprintf(instanceCLICopy.Held, "plan")}, |
| + {"removing", nil, instanceCLICopy.Removing}, |
| + {"", nil, instanceCLICopy.Sending}, // an older console sends no state |
| + } |
| + for _, c := range cases { |
| + s := base |
| + s.State, s.Pause = c.state, c.pause |
| + var b bytes.Buffer |
| + printInstanceSender(&b, s) |
| + want := fmt.Sprintf(instanceCLICopy.Line, "a.shop.example", c.word, "paul@shop.example", 3, 50, 1) + "\n" |
| + if b.String() != want { |
| + t.Errorf("%s: got %q, want %q", c.state, b.String(), want) |
| + } |
| + } |
| + var b bytes.Buffer |
| + none := base |
| + none.Addresses, none.Pending = nil, []string{"q@shop.example"} |
| + printInstanceSender(&b, none) |
| + if !strings.Contains(b.String(), instanceCLICopy.NoAddresses) || !strings.Contains(b.String(), fmt.Sprintf(instanceCLICopy.Pending, "q@shop.example")) { |
| + t.Errorf("no addresses / pending: %q", b.String()) |
| + } |
| +} |
| + |
| +// An unpaused instance sender in carlos email status prints its state, |
| +// not the "paused" today's credential rule would read for it. |
| +func TestEmailStatusRendersInstanceSenderState(t *testing.T) { |
| + res := apiEmailReply{App: "shop", Senders: []apiEmailSender{ |
| + {ID: "app", Scope: "app", Active: true}, |
| + {ID: "a.shop.example", Scope: "instance", Host: "a.shop.example", Active: true, State: "sending", |
| + Addresses: []string{"paul@shop.example"}, DailyCap: 50}, |
| + }} |
| + var b bytes.Buffer |
| + printEmailStatus(&b, res) |
| + out := b.String() |
| + if !strings.Contains(out, "a.shop.example: "+instanceCLICopy.Sending) || strings.Contains(out, "instance a.shop.example: paused") { |
| + t.Errorf("status:\n%s", out) |
| + } |
| +} |
| + |
| +func TestParseInstanceArgs(t *testing.T) { |
| + if _, err := parseInstanceArgs("email instance status", []string{"--app", "shop"}, false); err == nil { |
| + t.Error("--host missing accepted") |
| + } |
| + a, err := parseInstanceArgs("email instance create", []string{"--app", "shop", "--host", "a.shop.example", "--address", "p@x.example", "--address", "q@x.example"}, true) |
| + if err != nil || len(a.addresses) != 2 { |
| + t.Fatalf("%v %+v", err, a) |
| + } |
| + if err := runEmailAddresses([]string{"--app", "shop", "--host", "a.shop.example"}, true); err == nil || !strings.Contains(err.Error(), "<address>") { |
| + t.Errorf("address missing: %v", err) |
| + } |
| +} |
diff --git a/mail_instance_copy.go b/mail_instance_copy.go| new file mode 100644 |
| index 000000000..109009ba0 |
| --- /dev/null |
| +++ b/mail_instance_copy.go |
| @@ -0,0 +1,23 @@ |
| +package main |
| + |
| +// instanceCLICopy is the CLI output of the instance verbs (instance senders |
| +// design §5), as approved in copy review. |
| +var instanceCLICopy = struct { |
| + Sending, Paused, Held, Removing, Line, NoAddresses, Pending string |
| + Created, Removed, AddressAdded, AddressRemoved string |
| + PerInstanceOn, PerInstanceOff string |
| +}{ |
| + Sending: "sending", |
| + Paused: "paused (%s)", |
| + Held: "held (%s)", |
| + Removing: "removing", |
| + Line: "%s: %s \u2014 %s; today %d/%d sent, %d bounced", |
| + NoAddresses: "no addresses", |
| + Pending: "pending: %s", |
| + Created: "email sender ready for %s", |
| + Removed: "email sender removed for %s", |
| + AddressAdded: "%s can now send as %s", |
| + AddressRemoved: "%s can no longer send as %s", |
| + PerInstanceOn: "per-instance mode on for %s: each instance sends only as its own sender", |
| + PerInstanceOff: "per-instance mode off for %s", |
| +} |
diff --git a/parity/cli.tsv b/parity/cli.tsv| index 74c1eff71..d1dfd615d 100644 |
| --- a/parity/cli.tsv |
| +++ b/parity/cli.tsv |
| @@ -84,6 +84,8 @@ domains verify customer - - - - - |
| economics backhaul operator - - - - - |
| economics bill operator - - - - - |
| edge box-local - - - - - |
| +email addresses add customer - - - - - |
| +email addresses rm customer - - - - - |
| email credentials create customer - - - - - |
| email credentials list customer - - - - - |
| email credentials revoke customer - - - - - |
| @@ -92,7 +94,12 @@ email domains rm customer - - - - - |
| email enable customer - - - - - |
| email events customer - - - - - |
| email events push customer - - - - - |
| +email instance create customer - - - - - |
| +email instance rm customer - - - - - |
| +email instance status customer - - - - - |
| email pause operator - - - - - |
| +email per-instance off customer - - - - - |
| +email per-instance on customer - - - - - |
| email resume operator - - - - - |
| email rotate customer - - - - - |
| email status customer - - - - - |
diff --git a/parity/parity.tsv b/parity/parity.tsv| index 083e3e273..1f442afbe 100644 |
| --- a/parity/parity.tsv |
| +++ b/parity/parity.tsv |
| @@ -150,6 +150,9 @@ email-events email gap email events ; email events push wp-email-storage |
| email-credentials email partial email credentials create ; email credentials list ; email credentials revoke GET /a/{sqid}/apps/{app}/settings/{section} The console lists credentials read-only; it cannot create or revoke them. |
| email-rotate email gap email rotate wp-email-storage |
| email-submission email gap email submission on ; email submission off wp-email-storage Switches an app to sending through the box: no SMTP credential in its instances. |
| +email-instance email gap email instance create ; email instance status ; email instance rm wp-email-storage Gives one instance of an app its own email sender, shows it, or removes it. |
| +email-addresses email gap email addresses add ; email addresses rm wp-email-storage Lets one instance send as one exact address on the app's domain, or stops it. |
| +email-per-instance email gap email per-instance on ; email per-instance off wp-email-storage Makes every instance of an app send only as its own sender. |
| email-pause email operator email pause ; email resume Operator only: pause and resume need a console operator on the mail-operator allowlist (CARLOS_MAIL_OPERATORS). |
| # relay |
diff --git a/services.go b/services.go| index 93ad40c8e..1ec1f37bf 100644 |
| --- a/services.go |
| +++ b/services.go |
| @@ -34,7 +34,7 @@ import ( |
| const servicesUsage = `usage: carlos services <create|ls|rotate|revoke> [flags] |
| - create --role <publish|deploy|instance|operate|service|run|usage|admin> [--app <app>] [--account <sqid|name>] [--json] <name> |
| + create --role <publish|deploy|instance|operate|service|mail|run|usage|admin> [--app <app>] [--account <sqid|name>] [--json] <name> |
| mint a credential a SERVER holds, bound to this account — |
| not to you. Unlike your own CLI token, its reach is fixed |
| at mint: adding you to another account later does not widen |
| @@ -49,6 +49,7 @@ const servicesUsage = `usage: carlos services <create|ls|rotate|revoke> [flags] |
| apps. Omit --app for an account-scoped credential. |
| --role run needs --app and --commands, the command |
| prefixes it may run: --commands "import classic,import sync". |
| + mail: give an app's instances their own email senders and addresses. Can't deploy, pause, raise a cap or read who was emailed. |
| Words are matched exactly, from the start of the command. |
| --json prints one JSON object and nothing else, the bare |
| secret in its "secret" field: carlos services create |
| @@ -172,8 +173,8 @@ func validServiceHandle(handle string) error { |
| // help and create's usage line, at package level so a test can read the |
| // role lists they name (TestServicesHelpNamesEveryRole). |
| const ( |
| - servicesCreateRoleHelp = "role: publish, deploy, instance, operate, service, run, team, usage or admin (required)" |
| - servicesCreateUsage = "usage: carlos services create --role <publish|deploy|instance|operate|service|run|team|usage|admin> [--app <app>] " + |
| + servicesCreateRoleHelp = "role: publish, deploy, instance, operate, service, mail, run, team, usage or admin (required)" |
| + servicesCreateUsage = "usage: carlos services create --role <publish|deploy|instance|operate|service|mail|run|team|usage|admin> [--app <app>] " + |
| "[--rungs <list>] [--commands <list>] [--scope <name>] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>] [--json] <name>" |
| ) |