carlos / platform Public

mailsubmit: refuse an unswitched app before its body; bound in-flight sends

The verb reads the app's switch after the bearer check and answers
403 SUBMISSION_OFF before reading the body. A global bound of
MaxInFlight (8) across every socket answers 503. Command one-shots
strip CARLOS_MAIL: they have no control socket, so they can't send.

Fable P2-9, P3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 1091ea9dbed55fe3e0e2f25414ebe6e766e20edd parent b0aba39
7 files changed, +100 −9
  • internal/activator/backend_exec.go +1 −1
  • internal/activator/cmdunit.go +4 −2
  • internal/activator/cmdunit_test.go +3 −0
  • internal/activator/mailverb_test.go +2 −2
  • internal/mailsubmit/proto.go +5 −0
  • internal/mailsubmit/verb.go +22 −3
  • internal/mailsubmit/verb_test.go +63 −1
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 2555d9cc3..dc30b2b62 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -2794,7 +2794,7 @@ func (b *ExecBackend) controlMount(rt registry.Route, tokenReader func() (string
instanceupdates.Mount(mux, rt.Host, tokenReader, b.UpdatesReader)
}
if b.Mail != nil {
- mailsubmit.Mount(mux, rt, tokenReader, b.Mail)
+ mailsubmit.Mount(mux, rt, tokenReader, b.Mail, b.MailSwitch)
}
}
}
diff --git a/internal/activator/cmdunit.go b/internal/activator/cmdunit.go
index 223004538..b7cd3f891 100644
--- a/internal/activator/cmdunit.go
+++ b/internal/activator/cmdunit.go
@@ -211,11 +211,13 @@ var _ CmdBackend = (*ExecBackend)(nil)
// environment carries CARLOS_INSTANCE_KEY and CARLOS_ADMIN_TOKEN through:
// the command runs as the instance, on the instance's sealed data, with
// the key the serving generation holds and never one of its own. Over it:
-// the control-channel variables stripped as seedVars strips them,
+// the control-channel variables stripped as seedVars strips them
+// (CARLOS_MAIL among them: a one-shot has no control socket, so it cannot
+// submit mail, and must not be told it can),
// CARLOS_REGION set or removed from the backend's region as agentOwnedVars
// does, CARLOS_HOST from the row, and the three run variables.
func (b *ExecBackend) cmdVars(rt registry.Route, fileEnv map[string]string, dbPath, runID, runDir string) map[string]string {
- v := withoutVars(fileEnv, "CARLOS_CONTROL_SOCKET", "CARLOS_PURGE")
+ v := withoutVars(fileEnv, "CARLOS_CONTROL_SOCKET", "CARLOS_PURGE", "CARLOS_MAIL")
if b.Region != "" {
v = withVar(v, "CARLOS_REGION", b.Region)
} else {
diff --git a/internal/activator/cmdunit_test.go b/internal/activator/cmdunit_test.go
index 55a271952..822cd804d 100644
--- a/internal/activator/cmdunit_test.go
+++ b/internal/activator/cmdunit_test.go
@@ -37,6 +37,9 @@ func TestCmdVarsComposeTheRunEnvironment(t *testing.T) {
file := map[string]string{
"APP_KEY": "k", "CARLOS_ADMIN_TOKEN": "tok", "CARLOS_CONTROL_SOCKET": "/x", "CARLOS_PURGE": "header",
"CARLOS_REGION": "us", "CARLOS_HOST": "liar.example.com", "CARLOS_RUN_ID": "planted",
+ // A one-shot has no control socket, so it cannot submit mail
+ // (Fable P3): the serving generation's CARLOS_MAIL is stripped.
+ "CARLOS_MAIL": "submit",
}
got := b.cmdVars(rt, file, "/data/instances/h.example.com/app.db", "run_a", "/data/instances/h.example.com/.carlos-run/run_a")
want := map[string]string{
diff --git a/internal/activator/mailverb_test.go b/internal/activator/mailverb_test.go
index 680582d3f..9bae0e6de 100644
--- a/internal/activator/mailverb_test.go
+++ b/internal/activator/mailverb_test.go
@@ -72,7 +72,7 @@ func TestMailVerbMountedAtBothBindSites(t *testing.T) {
t.Run("flat, mounted", func(t *testing.T) {
b := testExecBackend(t) // Timers and UpdatesReader nil
rec := &mailRecorder{}
- b.Mail = rec
+ b.Mail, b.MailSwitch = rec, func(string, string) bool { return true }
ctl, token, stop := startAndReachControlSocket(t, b, "flatmail.example.com")
defer stop()
if code := mailPost(t, ctl, token); code != http.StatusOK {
@@ -96,7 +96,7 @@ func TestMailVerbMountedAtBothBindSites(t *testing.T) {
nested := func(t *testing.T, mail mailsubmit.Forwarder) (string, string, func()) {
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
b.GenContainment = true
- b.Mail = mail
+ b.Mail, b.MailSwitch = mail, func(string, string) bool { return true }
p0 := b.pathsFor(rt)
if err := os.MkdirAll(p0.runDir, 0o750); err != nil {
t.Fatal(err)
diff --git a/internal/mailsubmit/proto.go b/internal/mailsubmit/proto.go
index e1e449b0d..f80b3a499 100644
--- a/internal/mailsubmit/proto.go
+++ b/internal/mailsubmit/proto.go
@@ -66,6 +66,11 @@ const (
// MaxBody in memory, and one instance must not tie up the agent. The
// next is answered 429 RATE with Retry-After 1.
MaxInFlightPerSocket = 2
+ // MaxInFlight is how many messages every control socket of the agent
+ // together may have in it at once (Fable P2-9): each holds up to
+ // MaxBody, so this bounds the agent's memory whatever the number of
+ // instances. The next is answered 503 MAILER_UNAVAILABLE.
+ MaxInFlight = 8
)
// MailerSocket is the mailer's socket.
diff --git a/internal/mailsubmit/verb.go b/internal/mailsubmit/verb.go
index 772bc946a..0dde4a482 100644
--- a/internal/mailsubmit/verb.go
+++ b/internal/mailsubmit/verb.go
@@ -27,12 +27,18 @@ var passThrough = map[int]bool{
http.StatusTooManyRequests: true, http.StatusServiceUnavailable: true,
}
+// globalInflight bounds the messages in the agent across every socket
+// (MaxInFlight).
+var globalInflight = make(chan struct{}, MaxInFlight)
+
// Mount adds POST /v1/mail. rt is the route that owns this control socket:
// it is fixed here, and the request is stamped with it, never with anything
// the body says. tokenReader is read on every request (the env file can
// change under a running instance); an empty or unreadable token refuses
-// everything.
-func Mount(mux *http.ServeMux, rt registry.Route, tokenReader func() (string, error), fwd Forwarder) {
+// everything. switched is the agent's read of the route's app's switch
+// (nil: off): an app that is not switched is answered 403 SUBMISSION_OFF
+// before its body is read (Fable P2-9), as the mailer would answer it.
+func Mount(mux *http.ServeMux, rt registry.Route, tokenReader func() (string, error), fwd Forwarder, switched func(account, app string) bool) {
account, app, host := release.RouteAccount(rt), rt.App, rt.Host
inflight := make(chan struct{}, MaxInFlightPerSocket)
mux.HandleFunc("POST /v1/mail", func(w http.ResponseWriter, r *http.Request) {
@@ -50,8 +56,14 @@ func Mount(mux *http.ServeMux, rt registry.Route, tokenReader func() (string, er
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
+ // An app that is not switched sends nothing through here: say so
+ // before the body is read.
+ if switched == nil || !switched(account, app) {
+ answer(w, http.StatusForbidden, Answer{Code: CodeSubmissionOff}, "")
+ return
+ }
// At most MaxInFlightPerSocket messages from this socket at once,
- // the body read included.
+ // and MaxInFlight from every socket, the body read included.
select {
case inflight <- struct{}{}:
defer func() { <-inflight }()
@@ -59,6 +71,13 @@ func Mount(mux *http.ServeMux, rt registry.Route, tokenReader func() (string, er
answer(w, http.StatusTooManyRequests, Answer{Code: CodeRate}, "1")
return
}
+ select {
+ case globalInflight <- struct{}{}:
+ defer func() { <-globalInflight }()
+ default:
+ answer(w, http.StatusServiceUnavailable, Answer{Code: CodeMailerUnavailable}, "")
+ return
+ }
// 2. The envelope's shape and size.
env, raw, ok := readEnvelope(w, r)
if !ok {
diff --git a/internal/mailsubmit/verb_test.go b/internal/mailsubmit/verb_test.go
index 147164cf2..02a3c3ec4 100644
--- a/internal/mailsubmit/verb_test.go
+++ b/internal/mailsubmit/verb_test.go
@@ -5,6 +5,7 @@ import (
"encoding/base64"
"encoding/json"
"errors"
+ "io"
"net/http"
"net/http/httptest"
"strings"
@@ -46,7 +47,7 @@ const goodRaw = "From: Docs <hello@docs.example.com>\r\nTo: x@example.org\r\nSub
func mux(t *testing.T, rt registry.Route, token func() (string, error), fwd Forwarder) *http.ServeMux {
t.Helper()
m := http.NewServeMux()
- Mount(m, rt, token, fwd)
+ Mount(m, rt, token, fwd, func(string, string) bool { return true })
return m
}
@@ -311,3 +312,64 @@ func TestMailVerbBoundsInFlightPerSocket(t *testing.T) {
t.Fatalf("after the in-flight sends finished: %d", w.Code)
}
}
+
+// readCounter is a request body that counts the bytes read from it.
+type readCounter struct {
+ io.Reader
+ n int
+}
+
+func (r *readCounter) Read(p []byte) (int, error) {
+ n, err := r.Reader.Read(p)
+ r.n += n
+ return n, err
+}
+
+// Fable P2-9: an app that is not switched is answered 403 SUBMISSION_OFF
+// before a byte of its body is read, and the mailer is never asked.
+func TestVerbRefusesAnUnswitchedAppBeforeTheBody(t *testing.T) {
+ fwd := &recorder{status: 200, ans: Answer{MessageID: "m"}}
+ for name, switched := range map[string]func(string, string) bool{
+ "off": func(string, string) bool { return false },
+ "no switch": nil,
+ } {
+ m := http.NewServeMux()
+ Mount(m, routeA, staticToken("tok"), fwd, switched)
+ body := &readCounter{Reader: strings.NewReader(envelope("hello@docs.example.com", []string{"x@example.org"}, goodRaw))}
+ req := httptest.NewRequest(http.MethodPost, "/v1/mail", body)
+ req.Header.Set("Authorization", "Bearer tok")
+ w := httptest.NewRecorder()
+ m.ServeHTTP(w, req)
+ var ans Answer
+ _ = json.Unmarshal(w.Body.Bytes(), &ans)
+ if w.Code != http.StatusForbidden || ans.Code != CodeSubmissionOff {
+ t.Errorf("%s: %d %s, want 403 SUBMISSION_OFF", name, w.Code, w.Body.String())
+ }
+ if body.n != 0 {
+ t.Errorf("%s: %d body bytes read", name, body.n)
+ }
+ }
+ if fwd.n() != 0 {
+ t.Fatalf("the mailer was asked %d times", fwd.n())
+ }
+}
+
+// Fable P2-9: at most MaxInFlight messages in the agent from every socket
+// together; the next is 503 MAILER_UNAVAILABLE.
+func TestVerbGlobalInFlightBound(t *testing.T) {
+ for i := 0; i < MaxInFlight; i++ {
+ globalInflight <- struct{}{}
+ }
+ defer func() {
+ for i := 0; i < MaxInFlight; i++ {
+ <-globalInflight
+ }
+ }()
+ fwd := &recorder{status: 200, ans: Answer{MessageID: "m"}}
+ w := post(mux(t, routeA, staticToken("tok"), fwd), "tok", envelope("hello@docs.example.com", []string{"x@example.org"}, goodRaw))
+ var ans Answer
+ _ = json.Unmarshal(w.Body.Bytes(), &ans)
+ if w.Code != http.StatusServiceUnavailable || ans.Code != CodeMailerUnavailable || fwd.n() != 0 {
+ t.Fatalf("with the agent full: %d %s, %d sends", w.Code, w.Body.String(), fwd.n())
+ }
+}