mailer: policy before the send, hygiene, rate, per-box cap, SES
Task 5 of the platform mail submission plan. POST /v1/send on the
mailer's socket (under Task 3's peer rule) takes the agent's stamped
request and, before any SES call, in the plan's order: the route is on
this box (provision.BoxServesRecord, the reconciler's own predicates),
the app sender exists and is switched, it is not paused, raw has exactly
one From: equal to from, the From domain is granted, lists the app and is
verified in CARLOS_MAIL_REGION, a slot of the per-box daily cap is
reserved durably, and a token of the per-sender bucket (2/s, burst 20,
G9) is taken. Bcc and every X-SES-* header are stripped, folded and
mixed-case forms included, and the message goes to SES v2 SendEmail with
raw content, the envelope as Destination, the domain's configuration
set, the tenant only with a TenantARN, and the three attribution tags.
SES errors map to REJECTED, RATE or MAILER_UNAVAILABLE, and a send SES
did not take gives its slot back. At most four sends run at once.
Every AWS config comes from rootaws.LoadStaticConfig over the newest key
in /etc/carlos-mailer/keys (0640 root:carlos-mailer, at most two keys),
with the two regions named explicitly (CARLOS_MAIL_REGION,
CARLOS_DEPLOYMENT_REGION, new host.env keys). The deployment store is
release.NewS3StoreFromConfig wrapped in absentOnDeniedStore, so a denied
read is absent and absent always refuses. A key file change rebuilds
both clients; one that stops loading refuses every send and fails
health. `carlos mailer serve` refuses to start, naming the key, without
the bucket, either region or its state directory.
Shared pieces: mailwire gains DomainView, TenantName, SenderAppID and
DefaultDailyCap (TierCap("") now reads it); host.BoxScopeFromEnv is
provisionTickConfig's scope rule, factored out; the release openers
scan covers NewS3StoreFromConfig.
Census: Task 5 claims added, overlay re-proposed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
39 files changed,
+2,813
−36
docs/superpowers/notes/census-claims-platform-mail-submission.tsv+8 −0docs/superpowers/notes/census-proposal-platform-mail-submission.md+10 −3internal/console/mailcounts.go+4 −1internal/console/mailcounts_test.go+12 −0internal/host/agent.go+26 −11internal/host/mailswitch.go+1 −1internal/hostenv/hostenv.go+7 −0internal/hostenv/hostenv_test.go+32 −0internal/mail/mailwire_domain_test.go+66 −0internal/mailer/counter.go+167 −0internal/mailer/counter_test.go+99 −0internal/mailer/fs_test.go+16 −0internal/mailer/harness_test.go+257 −0internal/mailer/hygiene.go+77 −0internal/mailer/hygiene_test.go+69 −0internal/mailer/keys.go+175 −0internal/mailer/keys_other.go+8 −0internal/mailer/keys_test.go+109 −0internal/mailer/keys_unix.go+16 −0internal/mailer/policy.go+278 −0internal/mailer/rate.go+56 −0internal/mailer/routes.go+69 −0internal/mailer/send.go+224 −0internal/mailer/send_test.go+446 −0internal/mailer/server.go+12 −4internal/mailer/server_test.go+1 −1internal/mailer/ses.go+104 −0internal/mailer/ses_test.go+63 −0internal/mailer/store.go+80 −0internal/mailwire/mailwire.go+36 −0internal/provision/boxserves_test.go+79 −0internal/provision/reconcile.go+20 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −1internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv+21 −6internal/release/openers_test.go+4 −2internal/release/store.go+16 −2internal/release/store_fromconfig_test.go+51 −0mailer_cli.go+63 −3mailer_cli_test.go+30 −1
CI cancelled — superseded by a newer push — run details
diff --git a/docs/superpowers/notes/census-claims-platform-mail-submission.tsv b/docs/superpowers/notes/census-claims-platform-mail-submission.tsv| index a59144507..da38ca9fa 100644 |
| --- a/docs/superpowers/notes/census-claims-platform-mail-submission.tsv |
| +++ b/docs/superpowers/notes/census-claims-platform-mail-submission.tsv |
| @@ -40,3 +40,11 @@ internal/mailsubmit/verb.go:Mount Task 4, new: POST /v1/mail on an instance's co |
| internal/mailsubmit/forward.go:SocketForwarder.Send Task 4, new: the agent's client to the mailer: one HTTP POST of /v1/send over a fresh dial of the constant /run/carlos-mailer/mailer.sock, 60 s timeout, answer read to at most 64 KiB and decoded. Runs in the agent, as carlos. The socket's directory is root's; the mailer at the other end is a separate uid. |
| internal/host/agent.go:runAgent Task 4: sets eb.Mail = mailsubmit.SocketForwarder{} on every box and, when a deploy store opens, eb.MailSwitch to a new mailSwitchCache's On, armed for the serial-move refresh (armedMailSwitch). One more openDeployStore call, as the fleet and coordinator wiring beside it already make. Agent, not root. |
| internal/host/agent.go:fastTick Task 4: on a serial move, after the schedule leg, starts the armed mail switch cache's Refresh on its own goroutine (each read bounded at 2 s, overlapping refreshes skipped). It re-reads the app sender records already cached, through the agent's deploy store. Agent, not root; the tick waits on nothing new. |
| +# |
| +# Task 5 (the mailer's send: policy, hygiene, rate, per-box cap, SES). |
| +internal/host/agent.go:provisionTickConfig Task 5: its region, pools and fleet label now come from BoxScopeFromEnv, which is the same three reads moved out unchanged (CARLOS_REGION trimmed, provision.ParseBoxPools(CARLOS_POOLS), and resolveFleetIdentity's label only when its fleet is the one the region places the box on), so the box-local mailer resolves "on this box" by the agent's rule. The ReconcileConfig it returns is field for field what it was. Agent, not root. |
| +internal/mailer/counter.go:OpenCounter Task 5, new: the mailer's per-box daily cap counter. Creates $STATE_DIRECTORY/counts (0700) and removes count files more than three days old by their date-shaped names. Runs as carlos-mailer in its own StateDirectory (0700 carlos-mailer), which no other uid can write; never root. |
| +internal/mailer/counter.go:Counter.loadLocked Task 5, new: reads the day's counts file from the mailer's own state directory; a body that does not decode is renamed aside, logged loudly, and the day restarts at zero (the per-box bound §4.1 (a) accepts). carlos-mailer only. |
| +internal/mailer/counter.go:Counter.writeLocked Task 5, new: writes the day's counts durably (temp file in the same directory, fsync, rename, directory fsync) before a send. carlos-mailer only, in its own state directory. |
| +internal/mailer/keys.go:loadKeys Task 5, new: reads /etc/carlos-mailer/keys (a constant path) as carlos-mailer: refuses anything but a regular 0640 file owned by root and group carlos-mailer, more than two keys, or a malformed line; errors never carry a secret. Root never reads it. The file is written by the operator by hand, in a 0750 root:carlos-mailer directory uid carlos cannot traverse. |
| +internal/mailer/keys.go:KeyFile.Changed Task 5, new: a stat of the same constant key path, compared with the loaded file's mtime, size and inode, so a rotation reloads with no restart. carlos-mailer only. |
diff --git a/docs/superpowers/notes/census-proposal-platform-mail-submission.md b/docs/superpowers/notes/census-proposal-platform-mail-submission.md| index 81c94a1ee..f59eb0586 100644 |
| --- a/docs/superpowers/notes/census-proposal-platform-mail-submission.md |
| +++ b/docs/superpowers/notes/census-proposal-platform-mail-submission.md |
| @@ -1,10 +1,11 @@ |
| # Census approval: platform-mail-submission |
| -Ruling `census-ruling-platform-mail-submission`. The independent reviewer approves or rejects every change below, 8 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| +Ruling `census-ruling-platform-mail-submission`. The independent reviewer approves or rejects every change below, 13 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| | unit | change | read sites | what changed | |
| |---|---|---|---| |
| | `internal/host/agent.go` `fastTick` | body | unchanged (1) | Task 4: on a serial move, after the schedule leg, starts the armed mail switch cache's Refresh on its own goroutine (each read bounded at 2 s, overlapping refreshes skipped). It re-reads the app sender records already cached, through the agent's deploy store. Agent, not root; the tick waits on nothing new. | |
| +| `internal/host/agent.go` `provisionTickConfig` | body | unchanged (2) | Task 5: its region, pools and fleet label now come from BoxScopeFromEnv, which is the same three reads moved out unchanged (CARLOS_REGION trimmed, provision.ParseBoxPools(CARLOS_POOLS), and resolveFleetIdentity's label only when its fleet is the one the region places the box on), so the box-local mailer resolves "on this box" by the agent's rule. The ReconcileConfig it returns is field for field what it was. Agent, not root. | |
| | `internal/host/agent.go` `runAgent` | body | unchanged (6) | Task 4: sets eb.Mail = mailsubmit.SocketForwarder{} on every box and, when a deploy store opens, eb.MailSwitch to a new mailSwitchCache's On, armed for the serial-move refresh (armedMailSwitch). One more openDeployStore call, as the fleet and coordinator wiring beside it already make. Agent, not root. | |
| | `internal/host/agent.go` `statusLoop` | body | unchanged (6) | Task 3 (plan gap G6 (b)): the status tick also fills Probes.MailerArmed from mailerArmed(mailwire.MailerSocket, 2s): a stat of /run/carlos-mailer/mailer.sock and, only when it is a socket, GET /v1/health on it. The agent (carlos-edge.service, user carlos), not root; reported in the private BoxMetrics block only. The same six sites; no store request, no read of /etc/carlos-mailer (which uid carlos cannot traverse). | |
| | `internal/host/bootstrap.go` `bootstrapWithGroup` | body | unchanged (3) | Task 3: the sysusers.d/carlos.conf it writes is now the constant sysusersConf, which adds "u carlos-mailer - \"CARLOS mailer\" - /usr/sbin/nologin" ahead of the existing "g carlos-sockets -" line, so the tmpfiles line naming group carlos-mailer resolves on a box whose confs arrive by a staged-tree refresh. Constant text, no input; no read added. | |
| @@ -26,13 +27,14 @@ Ruling `census-ruling-platform-mail-submission`. The independent reviewer approv |
| | `internal/activator/backend_exec.go` `ExecBackend.spawnChildFrom` | sites | -registry:Host ×3, +whole:Route | Task 4: the inline mount (Timers, UpdatesReader) is replaced by b.controlMount(rt, tokenReader, n): the same verbs under the same conditions, plus the mail verb when b.Mail is set. The three rt.Host reads move into controlMount; the route is passed whole. Agent, not root; nothing else changes. | |
| | `internal/activator/prepare.go` `ExecBackend.listenControl` | sites | -registry:Host ×3, +whole:Route | Task 4: the same replacement as spawnChildFrom, with gen as the write fence's generation, so the nested and rootfs listener mounts exactly what the flat one does. Agent, not root. | |
| -Envelopes re-pinned: `.`, `internal/activator`, `internal/host`, `internal/host/demo_units`, `internal/host/units`, `internal/instancectl`, `internal/mailer`, `internal/mailsubmit`, `internal/mailwire`, `internal/moves`, `internal/status`. |
| +Envelopes re-pinned: `.`, `internal/activator`, `internal/host`, `internal/host/demo_units`, `internal/host/units`, `internal/hostenv`, `internal/instancectl`, `internal/mailer`, `internal/mailsubmit`, `internal/mailwire`, `internal/moves`, `internal/provision`, `internal/release`, `internal/status`. |
| 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. |
| Recorded dispositions, which each change must still satisfy: |
| - `internal/host/agent.go` `fastTick`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=observes the change index before any pass (observeIndex), runs the backstop's requested full pass and a scoped pass for moved app scopes (indexTick), and arms the canary pointer gate on the sweep (canaryPointerGate) only on a tick whose own index observation succeeded; read site unchanged, offset moved;rev3=census-ruling-stateless-replicas-1;basis=Call coordinator Tick on the existing tick before convergence; client renews held terms only at the pinned interval. Existing registry read unchanged. Final review I3: signal the owned renewal worker instead of waiting for its sequential console HTTP calls. Existing convergence and record read unchanged.;rev3=census-ruling-region-ha-p3a;basis=Run the optional desired-role reader on the existing tick after observing the armed change index; no new root path or timer, nil reader is unchanged.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: signals the owned replica worker on the existing tick; coalesced asynchronous execution, no timer or bucket scan added. merge of origin/main 7920cccf: Retain main box-role reader pass on the existing tick alongside the replica worker signal; merge-only body change, unchanged read sites.;rev3=census-ruling-restart-new-box-gap;basis=calls the optional restartGain hook (restartGainSeed) once per existing tick before the serial read; no new root path, timer or read kind; nil hook is unchanged;rev3=census-ruling-agent-start-demo-3;basis=Refresh moved notices through the shared watch before normal convergence; no new per-box poll. Census read-site delta: unchanged (1).;rev3=census-ruling-stateless-replicas-4-task1;basis=Signals the owned replica swap worker (armedReplicaDeploy.tick) beside the placement worker on the existing tick; coalesced background pass, no timer, no bucket read. Its transitions go through the console's authenticated /deploy. |
| +- `internal/host/agent.go` `provisionTickConfig`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ha-p1a-433;basis=the agent (carlos-edge.service, user carlos) and the edges file loop's eligibility: the same CARLOS_POOLS read, now parsed by provision.ParseBoxPools (internal/provision, envelope re-pinned), the one parser boxPools also uses. "@shared" (provision.SharedPoolToken, never a valid pool name) is the shared "" pool; other tokens are literal as before; empty elements and repeats dropped. No read added.;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 4, rule 2): sets ReconcileConfig.FleetBox to the box's own fleet label from resolveFleetIdentity(getenv), only when the identity resolves and region == PlacementTarget(identity.Fleet); otherwise it stays "" (the box admits only unlabelled records). The same environment the fleet loops already read; read sites unchanged (2). Agent config, not root. |
| - `internal/host/agent.go` `runAgent`: authority, task B,C,D,F. Basis: rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added.;rev3=census-ruling-static-sweep-periodic;basis=in the edge-ready callback, publishes e.LargestStaticTree in staticTreeSource for the disk alert line (diskAlertFrac in the metrics loop); in-memory wiring only, no read added; read sites unchanged (9);rev3=census-ruling-edge-page-cache-1;basis=wires the exec backend's CurrentInputs into the edge cache (wireCurrentInputs) and, in the ready hook after armEdgeAssetCache (whose returned store it now keeps), calls armEdgePageCache, which does nothing unless CARLOS_PAGE_CACHE=1; read sites unchanged (9); no read added;rev3=census-ruling-gvisor-demos;basis=Capture sandbox resolution and refusal once; log errors once; gate route admission and BeforeExec before process launch. No new root read. Task 5: pass the once-captured sandbox effective mode/config error into ExecBackend, UnitBackend and the immutable Client expectation. Same startup environment/registry reads; swapArming declines gVisor before placement. Task 8: arm read-only status projection with the existing Client.SandboxStatus callback. Agent status now queries the existing root /ready endpoint; no new root authority or guest-file input. Merge2 e8a1ddde: retain main wireCurrentInputs and armEdgePageCache through the existing asset-store ready hook alongside branch once-captured sandbox mode, wake gates and root status wiring. No new direct read; main page-cache helpers retain their own census overlays.;rev3=census-ruling-region-ha-held-build;basis=wires the drain state: svc.SetDrainingSource(boxDrain.IsDraining), svc.SetPeerDrainView(e.PeerDraining), e.SetPeerDrainedHook(svc.DropHoldersNaming); in-memory only; no read added; region HA held-requests Task 5: on group members, starts the drain driver over the activator, the edge and boxDrain, and serves its root-only drain socket; no read added beyond the socket's own Branch review r1: the drain state follows the root start fence on group members (the fence reader is the existing fenceLocation.read, a root-owned fixed path); e.SetPeerUndrainedHook(svc.AllowHoldersNaming) beside the drained hook (memory only); the drain socket serves only the agent's own user. No read added.;rev3=census-ruling-security-review-mitigations;basis=Wire the cached operator flat-layout choice into the exec backend's new-resident refusal; no read source added, existing authority retained.;rev3=census-ruling-w6-ingress-drain;basis=agent (user carlos), not root. Builds the ingress drain (newIngressDrain) with arming read at ask time from os.Getenv (CARLOS_REGION_HA, CARLOS_INGRESS_TARGET_GROUPS, both from the root-owned host.env), the fixed admission and lease.CurrentSelf (existing IMDS identity); its reader is awstg.Load, the box role's credentials calling ELB DescribeTargetHealth/DescribeTargetGroupAttributes (new AWS reads, by the agent). Wires admission.closeStartsForIngressDrain, the lbhealth drain condition, ingress.setEdge, and ingress.shutdownStarted in WithShutdownStarted. The drain socket (/run/carlos/.ha-drain/drain.sock, agent-user only, existing) is now also served on a fixed box with the drain configured (was group members only), routing /v1/ingress/* to the ingress drain and the group drain verbs to 404 there. armHADepartures now takes fixtureDepartureGetenv() and MakeQueue fixtureDepartureQueue(), which in a production (non-rootrunner) build are os.Getenv and nil, as before. Read sites unchanged (9).;rev3=census-ruling-stateless-replicas-4-task1;basis=Arms the fleet-only replica swap worker next to the placement worker: same console URL and fleet token as the existing replicaCoordinatorAPI, the existing activator Service; stops and joins at shutdown. No new read site, credential or bucket reader.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: sets deployWorker.step to the rollout scheduler answer for the record permit (replicaStepOf over armedRollout), an in-memory callback; no read site, credential or bucket reader added.;rev3=census-ruling-stateless-replicas-4-task2-fix2;basis=Task 2 fix round 2: the swap worker step is armedReplicaStep, the same lazy scheduler lookup as before as a named function; no read site added.;rev3=census-ruling-stateless-replicas-4-merge-main;basis=Merge of main 5fac2ff1: both sides changed it. Main (01d6ca78, linked-deployments-slice1) starts linkLoop beside tunnelLoop; this branch keeps its replica coordinator wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-final;basis=#511 final wave item 2: wires the swap worker's drive (armedReplicaDrive, the armed rollout manager's DriveReplicaRelease); no read added;rev3=census-ruling-stateless-replicas-4-merge-main2;basis=Merge of main af871da0 (v0.34.49): both sides changed it. Main (178dcfe5, member-backups-2a) moves the inline duty-view closure into armDutyView/dutyView and starts verifyAssignLoop; its sites drop by registry:Host and whole:Route x2 as main recorded them. This branch keeps its replica coordinator, swap worker and drive wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-drill3;basis=drill 3 R24: makes one in-memory channel, closes it (once) inside the edge's existing shutdown-started callback after ingress.shutdownStarted, and passes it to tunnelLoop, which drains only a fleet channel name; no read added, same six sites; touches no admission, lease, ingress drain, listener or file; the agent process, no root decision;rev3=census-ruling-edge-ppv2;basis=Agent (uid carlos), not root. memwatchLoop now gets edgeProxyCounters(&demoEdge) (in-process counters, no read). The drain socket's driver is newAgentDrainSocket(ingress, e, os.Getenv), which attaches the edge trust handler only when CARLOS_INGRESS_PROXY_SOURCES in the agent's environment (from the root-owned host.env) parses to a non-empty list; the socket is served when drainSocketServed: a group member or a configured ingress drain (both as before), or a box armed for PROXY protocol (new). The socket's path and agent-user-only permissions are unchanged. Read sites unchanged (6). |
| - `internal/host/agent.go` `statusLoop`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the status tick's context carries the box's lifetime judge; read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 953b9fda (its later changes, regional box names and self-serve moves plan 1 among them, under main's own census rulings), where the tick fills rootfs_ready and rootfs_blocked from armedRootfs.Load().probe, which each tick runs NestedOK's checks and asks the control socket's GET /ready/rootfs (never the store); the same four direct sites;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 11 and #329 plan 3 Task 7: takes root's GET /egress reader and fills p.Egress = egressStatusProbe(egressStatus, routes, provision.PolicyReadStates()) and p.SizeCommittedMiB = sizeCommittedMiB(armedSizeSource.Load(), routes); the two added whole:Route sites are the tick's own registry list handed to those two units (decision rows), which read root's control socket and the activator's memory; no store request added; the four existing sites unchanged, offsets moved.;rev3=census-ruling-fleet-alerts-1;basis=the agent (carlos-edge.service, user carlos): the status tick passes os.Geteuid() to alertDeliveryProbe, which fills AlertDelivery.EngineBeat/EngineBeatWhy from engineBeatArmed (the env value and the euid only, no file access, root refused before the path is looked at), and fills Probes.DiskFullETAHours from diskETAProbe(&processDiskTrend, now), a Theil-Sen fit over the metrics loop's in-memory ring of disk readings; the same six sites, no read added, no store request added;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the status tick's Probes gain HeldStreams: heldStreamsState(), which calls the edge's in-memory counters function (nil until the edge is ready). No file, bucket or registry access added.;rev3=census-ruling-stateless-replicas-3;basis=Fix round 1 Q20: read the detached in-memory replica snapshot source into Probes.ReplicaCopies on the existing five-minute tick. Existing six direct read sites unchanged. No additional bucket request, changed cadence or app lifecycle action.;rev3=census-ruling-agent-start-demo-3;basis=Report moved capability only when the serving edge reports readiness; report claim-seed support only with CARLOS_DEMO_CLAIM=1. Reads the explicit capability flag from the process environment; no new filesystem or registry read.;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 fix round 1 (#511 R16 amendment): the status tick also fills Probes.ApplyFinished from systemApplyFinished(release.OptDir()), an Lstat of root's apply journal <opt>/system/router/journal.json in the root-owned, world-readable state directory: finished only when the journal is absent, any other answer unknown and so unfinished. Round 0: Probes.PrevRelease from prevReleaseOf (carlos.prev and carlos.prev.version, the files withMovesFields already reads). Reported in the private BoxMetrics block; no bucket request or cadence change. |
| - `internal/host/bootstrap.go` `bootstrapWithGroup`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move bootstrapWith body here, retaining host.env, embedded unit reads and tmpfiles execution. Group live caller holds root mutation guard; skip automatic update/recovery units, preserve Restart=no/nftables drop-in and masks, and write separate root-owned /run/carlos-group-maintenance tmpfiles rule outside service ownership walk. No agent receipt read.;rev3=census-ruling-gvisor-demos;basis=Create the rootfs parent at 0700 and runtime root at 0755. Existing host.env/unit reads unchanged; workload templates remain unarmed. |
| @@ -62,9 +64,14 @@ New dispositions, which census-propose wrote and the reviewer checks against the |
| - new `internal/host/units/carlos-mailer-arm.path:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| - new `internal/host/units/carlos-mailer.service:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| - new `internal/host/units/carlos-mailer.socket:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| +- new `internal/mailer/counter.go:Counter.loadLocked`: reads +file:ReadFile; written legacy, accepted-legacy, frozen |
| +- new `internal/mailer/counter.go:Counter.writeLocked`: reads +file:CreateTemp, +file:Open; written legacy, accepted-legacy, frozen |
| +- new `internal/mailer/counter.go:OpenCounter`: reads +file:ReadDir; written legacy, accepted-legacy, frozen |
| +- new `internal/mailer/keys.go:KeyFile.Changed`: reads +file:Stat; written legacy, accepted-legacy, frozen |
| +- new `internal/mailer/keys.go:loadKeys`: reads +file:Open, +file:ReadFrom, +file:Stat; written legacy, accepted-legacy, frozen |
| - new `internal/mailsubmit/forward.go:SocketForwarder.Send`: reads +file:ReadAll; written legacy, accepted-legacy, frozen |
| - new `internal/mailsubmit/verb.go:Mount`: reads +registry:App, +registry:Host, +whole:Route; written legacy, accepted-legacy, frozen |
| -Seal: `07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063` → `615b17f291546a3de0c068258e6b76e72fe06b14f809df308fa6ed018c00e5fd`. |
| +Seal: `07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063` → `e8d4820f40e9b6459ddcba3f3efb9926b742ccd5cce8b33fa713551152265d51`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/console/mailcounts.go b/internal/console/mailcounts.go| index cd0185576..109e422ef 100644 |
| --- a/internal/console/mailcounts.go |
| +++ b/internal/console/mailcounts.go |
| @@ -17,6 +17,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/mail" |
| + "github.com/carlosframework/platform/internal/mailwire" |
| ) |
| // MailCounts is one app's activity for one UTC day. |
| @@ -72,7 +73,9 @@ func TierCap(tier string) int { |
| case "starter": |
| return 1000 |
| default: |
| - return 50 |
| + // The mailer caps a grant with no DailyCap at the same number |
| + // (platform mail submission plan, Task 5): one constant. |
| + return mailwire.DefaultDailyCap |
| } |
| } |
diff --git a/internal/console/mailcounts_test.go b/internal/console/mailcounts_test.go| index f63d74f02..ab3d9b28b 100644 |
| --- a/internal/console/mailcounts_test.go |
| +++ b/internal/console/mailcounts_test.go |
| @@ -1061,3 +1061,15 @@ func TestEnforceKeepsAManualPauseTakenMeanwhile(t *testing.T) { |
| t.Fatalf("pause = %+v, want the manual (kind-less) pause kept", pz) |
| } |
| } |
| + |
| +// The mailer caps a grant with no DailyCap at mailwire.DefaultDailyCap |
| +// (platform mail submission plan, Task 5): the console's default tier cap |
| +// is the same constant, so the two cannot disagree. |
| +func TestTierDefaultCapShared(t *testing.T) { |
| + if got := TierCap(""); got != mailwire.DefaultDailyCap { |
| + t.Fatalf("TierCap(\"\") = %d, mailwire.DefaultDailyCap = %d", got, mailwire.DefaultDailyCap) |
| + } |
| + if TierCap("free") != mailwire.DefaultDailyCap { |
| + t.Fatalf("the free tier's cap moved off the shared default") |
| + } |
| +} |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index ce5d1ca27..0552659b1 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -3946,6 +3946,29 @@ func domainsTickConfig(getenv func(string) string, publicIP string) (domains.Con |
| return cfg, ips, nil |
| } |
| +// BoxScopeFromEnv is the part of provisionTickConfig that decides which |
| +// instance records are this box's: CARLOS_REGION, CARLOS_POOLS |
| +// (provision.ParseBoxPools) and the fleet label. The box-local mailer |
| +// reads its scope through it (platform mail submission design, decision |
| +// 4), so "on this box" is resolved by the agent's own rule. |
| +// |
| +// The fleet label is this box's own label in its fleet (managed fleets 1b, |
| +// rule 2), from the one identity every fleet loop resolves, and only when |
| +// that identity's fleet is the one this box's region places it on. An |
| +// identity that does not resolve, or names another fleet, leaves it empty: |
| +// a fleet box that cannot say which box it is admits only unlabelled |
| +// records, never another box's. |
| +func BoxScopeFromEnv(getenv func(string) string) provision.BoxScope { |
| + scope := provision.BoxScope{ |
| + Region: strings.TrimSpace(getenv("CARLOS_REGION")), |
| + Pools: provision.ParseBoxPools(getenv("CARLOS_POOLS")), |
| + } |
| + if identity, err := resolveFleetIdentity(getenv); err == nil && scope.Region == registry.PlacementTarget(identity.Fleet) { |
| + scope.FleetBox = identity.Label |
| + } |
| + return scope |
| +} |
| + |
| // provisionTickConfig builds one instances reconcile pass's Config from the |
| // environment — pure (getenv-injected), mirroring domainsTickConfig's shape. |
| // Unlike domainsTickConfig, there is no inert zero-Config case: an unset |
| @@ -3959,8 +3982,8 @@ func domainsTickConfig(getenv func(string) string, publicIP string) (domains.Con |
| // a declaration about what work THIS BOX will accept, independent of a |
| // record's own "no-inbound" placement request — see ReconcileConfig.Inbound. |
| func provisionTickConfig(getenv func(string) string) provision.ReconcileConfig { |
| - region := strings.TrimSpace(getenv("CARLOS_REGION")) |
| - pools := provision.ParseBoxPools(getenv("CARLOS_POOLS")) |
| + scope := BoxScopeFromEnv(getenv) |
| + region, pools := scope.Region, scope.Pools |
| dd := getenv("CARLOS_DATA_DIR") |
| if dd == "" { |
| dd = "/data" |
| @@ -3988,15 +4011,7 @@ func provisionTickConfig(getenv func(string) string) provision.ReconcileConfig { |
| // when none is armed (every test that does not arm one). |
| ConfigGate: configGate(), |
| } |
| - // This box's own label in its fleet (managed fleets 1b, rule 2), from |
| - // the one identity every fleet loop resolves, and only when that |
| - // identity's fleet is the one this box's region places it on. An |
| - // identity that does not resolve, or names another fleet, leaves it |
| - // empty: a fleet box that cannot say which box it is admits only |
| - // unlabelled records, never another box's. |
| - if identity, err := resolveFleetIdentity(getenv); err == nil && region == registry.PlacementTarget(identity.Fleet) { |
| - cfg.FleetBox = identity.Label |
| - } |
| + cfg.FleetBox = scope.FleetBox |
| // The root release public key, same source and same parser as adoptLoop's |
| // and domainsTickConfig's. It guards ONE decision in this pass: whether a |
| // trash marker may retire a production-flagged app's routes (#340). |
diff --git a/internal/host/mailswitch.go b/internal/host/mailswitch.go| index b0cd28355..3f0431b3a 100644 |
| --- a/internal/host/mailswitch.go |
| +++ b/internal/host/mailswitch.go |
| @@ -110,7 +110,7 @@ func (c *mailSwitchCache) Refresh(ctx context.Context) { |
| // absent record is off. A failed read or an undecodable body keeps the last |
| // good answer (or false), marked as an error so On asks again later. |
| func (c *mailSwitchCache) read(ctx context.Context, k mailSwitchKey) mailSwitchEntry { |
| - body, etag, err := c.store.Get(ctx, mailwire.SenderKey(k.acct, k.app, "app")) |
| + body, etag, err := c.store.Get(ctx, mailwire.SenderKey(k.acct, k.app, mailwire.SenderAppID)) |
| now := c.now() |
| var e mailSwitchEntry |
| switch { |
diff --git a/internal/hostenv/hostenv.go b/internal/hostenv/hostenv.go| index 195d23e9c..1178ce0c9 100644 |
| --- a/internal/hostenv/hostenv.go |
| +++ b/internal/hostenv/hostenv.go |
| @@ -73,6 +73,11 @@ var Required = []string{ |
| // marker, which do select, are cross-checked against the signed roster |
| // where the agent uses them (internal/host's mode selection). Adding a |
| // variable is a code change, reviewed. |
| +// |
| +// CARLOS_MAIL_REGION and CARLOS_DEPLOYMENT_REGION are the box-local |
| +// mailer's two AWS regions, SES's and the deployment bucket's (platform |
| +// mail submission plan, Task 5). They select no box authority: they name |
| +// the regions the mailer's own key is used in. |
| var Optional = []string{ |
| "CARLOS_ACME_DELEGATION_ZONE", |
| "CARLOS_ACME_DIRECTORY", |
| @@ -84,6 +89,7 @@ var Optional = []string{ |
| "CARLOS_CHANGE_INDEX", |
| "CARLOS_DEMO_API_CONSOLE_ORIGIN", |
| "CARLOS_DEMO_API_ORIGIN", |
| + "CARLOS_DEPLOYMENT_REGION", |
| "CARLOS_DEPLOYMENT_SINGLE_TENANT", |
| "CARLOS_DNS_PROVIDER", |
| "CARLOS_EDGE_GZIP", |
| @@ -98,6 +104,7 @@ var Optional = []string{ |
| "CARLOS_INGRESS_PROXY_SOURCES", |
| "CARLOS_INGRESS_TARGET_GROUPS", |
| "CARLOS_LAYOUT_DEFAULT", |
| + "CARLOS_MAIL_REGION", |
| "CARLOS_MOVES_PHASE1", |
| "CARLOS_MOVE_READY_DELTA_BYTES", |
| "CARLOS_PLAN_LIMITS", |
diff --git a/internal/hostenv/hostenv_test.go b/internal/hostenv/hostenv_test.go| index 243af5f94..6544260f8 100644 |
| --- a/internal/hostenv/hostenv_test.go |
| +++ b/internal/hostenv/hostenv_test.go |
| @@ -775,3 +775,35 @@ func TestProxySourcesInAGroupBoxHostEnv(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// The box-local mailer's two AWS regions (platform mail submission plan, |
| +// Task 5) pass both assembly paths: a fixed box's host.env and a group |
| +// box's. |
| +func TestHostEnvAllowsMailRegion(t *testing.T) { |
| + for _, k := range []string{"CARLOS_MAIL_REGION", "CARLOS_DEPLOYMENT_REGION"} { |
| + if !Allowed(k) { |
| + t.Fatalf("%s is not on the allowlist", k) |
| + } |
| + } |
| + env := today() |
| + env["CARLOS_MAIL_REGION"] = "eu-west-1" |
| + env["CARLOS_DEPLOYMENT_REGION"] = "us-east-1" |
| + shared, regional := Split(env) |
| + got, err := Assemble(shared, regional) |
| + if err != nil { |
| + t.Fatalf("Assemble: %v", err) |
| + } |
| + if got["CARLOS_MAIL_REGION"] != "eu-west-1" || got["CARLOS_DEPLOYMENT_REGION"] != "us-east-1" { |
| + t.Fatalf("Assemble dropped them: %v", got) |
| + } |
| + c, genv := groupEnvFixture() |
| + genv["CARLOS_MAIL_REGION"] = "eu-west-1" |
| + genv["CARLOS_DEPLOYMENT_REGION"] = "us-east-1" |
| + gg, err := AssembleGroup(nil, genv, c, "queue") |
| + if err != nil { |
| + t.Fatalf("AssembleGroup: %v", err) |
| + } |
| + if gg["CARLOS_MAIL_REGION"] != "eu-west-1" || gg["CARLOS_DEPLOYMENT_REGION"] != "us-east-1" { |
| + t.Fatalf("AssembleGroup dropped them: %v", gg) |
| + } |
| +} |
diff --git a/internal/mail/mailwire_domain_test.go b/internal/mail/mailwire_domain_test.go| new file mode 100644 |
| index 000000000..6e6056068 |
| --- /dev/null |
| +++ b/internal/mail/mailwire_domain_test.go |
| @@ -0,0 +1,66 @@ |
| +package mail |
| + |
| +import ( |
| + "encoding/json" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/mailwire" |
| +) |
| + |
| +// The mailer reads domain records through mailwire.DomainView (platform |
| +// mail submission plan, Task 5; round 1 P3): a fully populated |
| +// DomainRecord, marshalled and decoded as the view, keeps every field the |
| +// view names. This is the consumer pin for the domain record's shape. |
| +func TestDomainViewDecodesMailDomain(t *testing.T) { |
| + at := time.Date(2026, 11, 13, 8, 30, 0, 0, time.UTC) |
| + full := &DomainRecord{ |
| + Schema: 1, Domain: "docs.example.com", Kind: "custom", Apps: []string{"docs", "sheets"}, |
| + Regions: map[string]*RegionState{ |
| + "eu-west-1": {IdentityARN: "arn:aws:ses:eu-west-1:1:identity/docs.example.com", DKIMTokens: []string{"a", "b"}, |
| + MailFrom: "mail.docs.example.com", ConfigSet: "carlos-bab", Status: StatusVerified, CheckedAt: at, Adopted: true}, |
| + "us-east-1": {IdentityARN: "", ConfigSet: "", Status: StatusPending, CheckedAt: at}, |
| + }, |
| + CreatedAt: at, |
| + } |
| + body, err := json.Marshal(full) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var v mailwire.DomainView |
| + if err := json.Unmarshal(body, &v); err != nil { |
| + t.Fatal(err) |
| + } |
| + if v.Domain != full.Domain || len(v.Apps) != 2 || v.Apps[0] != "docs" || v.Apps[1] != "sheets" { |
| + t.Fatalf("view %+v", v) |
| + } |
| + if len(v.Regions) != len(full.Regions) { |
| + t.Fatalf("regions %v", v.Regions) |
| + } |
| + for r, st := range full.Regions { |
| + got := v.Regions[r] |
| + if got == nil || got.IdentityARN != st.IdentityARN || got.ConfigSet != st.ConfigSet || got.Status != st.Status { |
| + t.Errorf("region %s = %+v, want %+v", r, got, st) |
| + } |
| + } |
| + if mailwire.DomainStatusVerified != StatusVerified { |
| + t.Fatalf("mailwire's verified status %q != %q", mailwire.DomainStatusVerified, StatusVerified) |
| + } |
| +} |
| + |
| +// One app sender id: the agent and the mailer read the switch and send as |
| +// the record internal/mail calls the app sender. |
| +func TestMailwireSenderAppIDMatchesMail(t *testing.T) { |
| + if mailwire.SenderAppID != SenderAppID { |
| + t.Fatalf("mailwire.SenderAppID = %q, internal/mail's is %q", mailwire.SenderAppID, SenderAppID) |
| + } |
| +} |
| + |
| +// One tenant name: the mailer's TenantName is internal/mail's. |
| +func TestMailwireTenantNameMatchesMail(t *testing.T) { |
| + for _, acct := range []string{"bab", "abcxyz", "zzz"} { |
| + if got, want := mailwire.TenantName(acct), TenantName(acct); got != want { |
| + t.Errorf("mailwire.TenantName(%q) = %q, want %q", acct, got, want) |
| + } |
| + } |
| +} |
diff --git a/internal/mailer/counter.go b/internal/mailer/counter.go| new file mode 100644 |
| index 000000000..db1ced249 |
| --- /dev/null |
| +++ b/internal/mailer/counter.go |
| @@ -0,0 +1,167 @@ |
| +package mailer |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// counterKeep is how many days of count files the mailer keeps. |
| +const counterKeep = 3 * 24 * time.Hour |
| + |
| +// Counter is the per-box daily send counter (design decision 9, §4.1 (a), |
| +// ruled by Paul): one file per UTC day, $STATE_DIRECTORY/counts/<day>.json, |
| +// a map from "acct/app/sender" to the messages reserved that day. A slot is |
| +// reserved, and written durably (temp file, fsync, rename), before the |
| +// send, and released if SES did not take the message. The console still |
| +// counts every send from SES events and pauses at the cap fleet-wide; this |
| +// counter is the per-box brake before the send. |
| +type Counter struct { |
| + dir string |
| + logf func(string, ...any) |
| + |
| + mu sync.Mutex |
| + day string |
| + counts map[string]int |
| +} |
| + |
| +// OpenCounter opens dir/counts, creating it, and removes count files more |
| +// than three days old. |
| +func OpenCounter(stateDir string, now time.Time, logf func(string, ...any)) (*Counter, error) { |
| + if logf == nil { |
| + logf = func(string, ...any) {} |
| + } |
| + dir := filepath.Join(stateDir, "counts") |
| + if err := os.MkdirAll(dir, 0o700); err != nil { |
| + return nil, err |
| + } |
| + c := &Counter{dir: dir, logf: logf} |
| + entries, err := os.ReadDir(dir) |
| + if err != nil { |
| + return nil, err |
| + } |
| + for _, e := range entries { |
| + day, ok := strings.CutSuffix(e.Name(), ".json") |
| + if !ok { |
| + continue |
| + } |
| + if t, err := time.Parse(time.DateOnly, day); err == nil && now.Sub(t) > counterKeep { |
| + _ = os.Remove(filepath.Join(dir, e.Name())) |
| + } |
| + } |
| + return c, nil |
| +} |
| + |
| +// Day is the UTC day a count belongs to. |
| +func Day(now time.Time) string { return now.UTC().Format(time.DateOnly) } |
| + |
| +func (c *Counter) path(day string) string { return filepath.Join(c.dir, day+".json") } |
| + |
| +// loadLocked makes day's counts current. A file that does not decode is |
| +// moved aside and logged loudly, and the day restarts from zero: that is |
| +// the per-box bound §4.1 (a) accepts, and the console's event count still |
| +// holds the fleet-wide cap. c.mu is held. |
| +func (c *Counter) loadLocked(day string) error { |
| + if c.day == day && c.counts != nil { |
| + return nil |
| + } |
| + counts := map[string]int{} |
| + b, err := os.ReadFile(c.path(day)) |
| + switch { |
| + case errors.Is(err, os.ErrNotExist): |
| + case err != nil: |
| + return err |
| + default: |
| + if derr := json.Unmarshal(b, &counts); derr != nil { |
| + aside := fmt.Sprintf("%s.corrupt-%d", c.path(day), time.Now().UnixNano()) |
| + if rerr := os.Rename(c.path(day), aside); rerr != nil { |
| + return fmt.Errorf("mailer: count file %s is corrupt and cannot be moved aside: %w", c.path(day), rerr) |
| + } |
| + c.logf("mailer: ALERT: count file %s is corrupt (%v); moved to %s, and %s restarts from 0 on this box", c.path(day), derr, aside, day) |
| + counts = map[string]int{} |
| + } |
| + } |
| + c.day, c.counts = day, counts |
| + return nil |
| +} |
| + |
| +// writeLocked writes the current day durably. c.mu is held. |
| +func (c *Counter) writeLocked() error { |
| + b, err := json.Marshal(c.counts) |
| + if err != nil { |
| + return err |
| + } |
| + f, err := os.CreateTemp(c.dir, ".counts-*") |
| + if err != nil { |
| + return err |
| + } |
| + tmp := f.Name() |
| + defer os.Remove(tmp) |
| + if _, err := f.Write(b); err != nil { |
| + f.Close() |
| + return err |
| + } |
| + if err := f.Sync(); err != nil { |
| + f.Close() |
| + return err |
| + } |
| + if err := f.Close(); err != nil { |
| + return err |
| + } |
| + if err := os.Rename(tmp, c.path(c.day)); err != nil { |
| + return err |
| + } |
| + if d, err := os.Open(c.dir); err == nil { |
| + _ = d.Sync() |
| + d.Close() |
| + } |
| + return nil |
| +} |
| + |
| +// Reserve takes one of key's slots for day if fewer than limit are taken, |
| +// and writes the count before it returns true. A write that fails takes |
| +// nothing. |
| +func (c *Counter) Reserve(key, day string, limit int) (bool, error) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if err := c.loadLocked(day); err != nil { |
| + return false, err |
| + } |
| + if c.counts[key] >= limit { |
| + return false, nil |
| + } |
| + c.counts[key]++ |
| + if err := c.writeLocked(); err != nil { |
| + c.counts[key]-- |
| + return false, err |
| + } |
| + return true, nil |
| +} |
| + |
| +// Release gives back one of key's slots for day: a send SES did not take. |
| +func (c *Counter) Release(key, day string) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if err := c.loadLocked(day); err != nil || c.counts[key] == 0 { |
| + return |
| + } |
| + c.counts[key]-- |
| + if err := c.writeLocked(); err != nil { |
| + c.logf("mailer: release of a %s slot for %s not written: %v", day, key, err) |
| + } |
| +} |
| + |
| +// Count is key's reserved slots for day. |
| +func (c *Counter) Count(key, day string) int { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if err := c.loadLocked(day); err != nil { |
| + return 0 |
| + } |
| + return c.counts[key] |
| +} |
diff --git a/internal/mailer/counter_test.go b/internal/mailer/counter_test.go| new file mode 100644 |
| index 000000000..2c6a14bea |
| --- /dev/null |
| +++ b/internal/mailer/counter_test.go |
| @@ -0,0 +1,99 @@ |
| +package mailer |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "sort" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The per-box cap counter (§4.1 (a)) survives a restart: reservations are |
| +// written before the send, so a reopened counter refuses at the same |
| +// boundary. A refused send's slot is released. A corrupt file is moved |
| +// aside, logged loudly, and the day restarts from zero. |
| +func TestCounterDurableAcrossRestart(t *testing.T) { |
| + dir := t.TempDir() |
| + now := time.Date(2026, 11, 13, 12, 0, 0, 0, time.UTC) |
| + day := Day(now) |
| + const key = "abcxyz/docs/app" |
| + c, err := OpenCounter(dir, now, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := 0; i < 2; i++ { |
| + if ok, err := c.Reserve(key, day, 3); !ok || err != nil { |
| + t.Fatalf("reserve %d: %v %v", i, ok, err) |
| + } |
| + } |
| + c2, err := OpenCounter(dir, now, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if ok, _ := c2.Reserve(key, day, 3); !ok { |
| + t.Fatal("the third slot after a restart was refused") |
| + } |
| + if ok, _ := c2.Reserve(key, day, 3); ok { |
| + t.Fatal("the fourth slot after a restart was admitted") |
| + } |
| + // A send SES did not take gives its slot back, durably. |
| + c2.Release(key, day) |
| + c3, _ := OpenCounter(dir, now, nil) |
| + if n := c3.Count(key, day); n != 2 { |
| + t.Fatalf("after a release and a restart: %d, want 2", n) |
| + } |
| + // Another day is another count; other senders are their own. |
| + if ok, _ := c3.Reserve(key, Day(now.Add(24*time.Hour)), 3); !ok { |
| + t.Fatal("the next day refused") |
| + } |
| + if ok, _ := c3.Reserve("abcxyz/sheets/app", day, 1); !ok { |
| + t.Fatal("another sender refused") |
| + } |
| + |
| + // A corrupt file: moved aside, logged, restarted at zero. |
| + if err := os.WriteFile(filepath.Join(dir, "counts", day+".json"), []byte("{not json"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + var logs []string |
| + c4, err := OpenCounter(dir, now, func(f string, a ...any) { logs = append(logs, f) }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := c4.Count(key, day); n != 0 { |
| + t.Fatalf("a corrupt day counts %d, want 0", n) |
| + } |
| + if len(logs) != 1 || !strings.Contains(logs[0], "ALERT") { |
| + t.Fatalf("corrupt file not logged loudly: %q", logs) |
| + } |
| + aside := false |
| + for _, n := range c4.days() { |
| + aside = aside || strings.Contains(n, ".corrupt-") |
| + } |
| + if !aside { |
| + t.Fatalf("the corrupt file was not kept aside: %v", c4.days()) |
| + } |
| + |
| + // Files older than three days are removed at start. |
| + old := filepath.Join(dir, "counts", Day(now.Add(-5*24*time.Hour))+".json") |
| + if err := os.WriteFile(old, []byte("{}"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := OpenCounter(dir, now, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := os.Stat(old); !os.IsNotExist(err) { |
| + t.Fatalf("a five-day-old count file survived: %v", err) |
| + } |
| +} |
| + |
| +// days lists the count files present. |
| +func (c *Counter) days() []string { |
| + entries, _ := os.ReadDir(c.dir) |
| + var out []string |
| + for _, e := range entries { |
| + out = append(out, e.Name()) |
| + } |
| + sort.Strings(out) |
| + return out |
| +} |
diff --git a/internal/mailer/fs_test.go b/internal/mailer/fs_test.go| new file mode 100644 |
| index 000000000..019ae1f17 |
| --- /dev/null |
| +++ b/internal/mailer/fs_test.go |
| @@ -0,0 +1,16 @@ |
| +package mailer |
| + |
| +import ( |
| + "os" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func osChtimes(path string, t time.Time) error { return os.Chtimes(path, t, t) } |
| + |
| +func removeFile(t *testing.T, path string) { |
| + t.Helper() |
| + if err := os.Remove(path); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/mailer/harness_test.go b/internal/mailer/harness_test.go| new file mode 100644 |
| index 000000000..947b73c4c |
| --- /dev/null |
| +++ b/internal/mailer/harness_test.go |
| @@ -0,0 +1,257 @@ |
| +package mailer |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/sesv2" |
| + |
| + "github.com/carlosframework/platform/internal/mailsubmit" |
| + "github.com/carlosframework/platform/internal/mailwire" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +const ( |
| + tAcct = "abcxyz" |
| + tApp = "docs" |
| + tHost = "a.docs.example.com" |
| + tDomain = "docs.example.com" |
| + tFrom = "hello@docs.example.com" |
| + tRegion = "eu-west-1" |
| +) |
| + |
| +// fakeSES records every SendEmail and answers as told. |
| +type fakeSES struct { |
| + mu sync.Mutex |
| + calls []*sesv2.SendEmailInput |
| + err error |
| + block chan struct{} // when set, SendEmail waits on it |
| +} |
| + |
| +func (f *fakeSES) SendEmail(ctx context.Context, in *sesv2.SendEmailInput, _ ...func(*sesv2.Options)) (*sesv2.SendEmailOutput, error) { |
| + f.mu.Lock() |
| + f.calls = append(f.calls, in) |
| + n, err, block := len(f.calls), f.err, f.block |
| + f.mu.Unlock() |
| + if block != nil { |
| + <-block |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &sesv2.SendEmailOutput{MessageId: aws.String(fmt.Sprintf("ses-%d", n))}, nil |
| +} |
| + |
| +func (f *fakeSES) n() int { f.mu.Lock(); defer f.mu.Unlock(); return len(f.calls) } |
| + |
| +func (f *fakeSES) last() *sesv2.SendEmailInput { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.calls[len(f.calls)-1] |
| +} |
| + |
| +// harness is one mailer over a DirStore holding a route on this box, a |
| +// switched app sender and a verified domain, with a fake SES and a clock. |
| +type harness struct { |
| + t *testing.T |
| + store *release.DirStore |
| + wrapped release.Store // what the mailer is handed as its store, before the wrapper |
| + ses *fakeSES |
| + m *Mailer |
| + h http.Handler |
| + now time.Time |
| + keyPath string |
| + logs *logBuf |
| + builds []Key |
| +} |
| + |
| +type logBuf struct { |
| + mu sync.Mutex |
| + lines []string |
| +} |
| + |
| +func (l *logBuf) add(f string, a ...any) { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + l.lines = append(l.lines, fmt.Sprintf(f, a...)) |
| +} |
| + |
| +func (l *logBuf) has(sub string) bool { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + for _, s := range l.lines { |
| + if strings.Contains(s, sub) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// noOwnerCheck stands in for root:carlos-mailer, which a test cannot chown. |
| +func noOwnerCheck(t *testing.T) { |
| + t.Helper() |
| + prev := keyOwnerCheck |
| + keyOwnerCheck = func(os.FileInfo) error { return nil } |
| + t.Cleanup(func() { keyOwnerCheck = prev }) |
| +} |
| + |
| +func writeKeys(t *testing.T, path, body string) { |
| + t.Helper() |
| + if err := os.WriteFile(path, []byte(body), 0o640); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(path, 0o640); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +type harnessOpt func(*harnessCfg) |
| + |
| +type harnessCfg struct { |
| + scope provision.BoxScope |
| + record *provision.Record // nil: the default record |
| + sender map[string]any |
| + domain map[string]any |
| + extra map[string]map[string]any // more domain records, by domain |
| + store func(release.Store) release.Store |
| +} |
| + |
| +func defaultRecord() provision.Record { |
| + return provision.Record{Schema: 1, Host: tHost, Slug: "a", App: tApp, Account: tAcct, Region: "ie", Channel: "stable", |
| + CreatedAt: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)} |
| +} |
| + |
| +func defaultSender() map[string]any { |
| + return map[string]any{ |
| + "id": mailwire.SenderAppID, |
| + "declared": map[string]any{"from": tFrom}, |
| + "grant": map[string]any{"domains": []string{tDomain}, "daily_cap": 1000}, |
| + "submission": map[string]any{"on": true, "at": "2026-11-13T00:00:00Z"}, |
| + } |
| +} |
| + |
| +func defaultDomain() map[string]any { |
| + return map[string]any{ |
| + "domain": tDomain, "apps": []string{tApp}, |
| + "regions": map[string]any{tRegion: map[string]any{ |
| + "identity_arn": "arn:aws:ses:eu-west-1:1:identity/" + tDomain, "config_set": "carlos-" + tAcct, "status": "verified"}}, |
| + } |
| +} |
| + |
| +func putJSON(t *testing.T, s release.Store, key string, v any) { |
| + t.Helper() |
| + b, err := json.Marshal(v) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, etag, _ := s.Get(context.Background(), key) |
| + if _, err := s.Put(context.Background(), key, b, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func newHarness(t *testing.T, opts ...harnessOpt) *harness { |
| + t.Helper() |
| + noOwnerCheck(t) |
| + cfg := harnessCfg{scope: provision.BoxScope{Region: "ie"}, sender: defaultSender(), domain: defaultDomain()} |
| + for _, o := range opts { |
| + o(&cfg) |
| + } |
| + h := &harness{t: t, store: release.NewDirStore(t.TempDir()), ses: &fakeSES{}, |
| + now: time.Date(2026, 11, 13, 12, 0, 0, 0, time.UTC), logs: &logBuf{}} |
| + rec := defaultRecord() |
| + if cfg.record != nil { |
| + rec = *cfg.record |
| + } |
| + if rec.Host != "" { |
| + putJSON(t, h.store, provision.RecordKey(rec.Account, rec.App, tHost), rec) |
| + } |
| + if cfg.sender != nil { |
| + putJSON(t, h.store, mailwire.SenderKey(tAcct, tApp, mailwire.SenderAppID), cfg.sender) |
| + } |
| + if cfg.domain != nil { |
| + putJSON(t, h.store, mailwire.DomainKey(tAcct, tDomain), cfg.domain) |
| + } |
| + for d, rec := range cfg.extra { |
| + putJSON(t, h.store, mailwire.DomainKey(tAcct, d), rec) |
| + } |
| + h.wrapped = h.store |
| + if cfg.store != nil { |
| + h.wrapped = cfg.store(h.store) |
| + } |
| + h.keyPath = filepath.Join(t.TempDir(), "keys") |
| + writeKeys(t, h.keyPath, "AKIDOLD secret-old 2026-11-01T00:00:00Z\n") |
| + keys, err := OpenKeyFile(h.keyPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + counter, err := OpenCounter(t.TempDir(), h.now, h.logs.add) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + m, err := New(context.Background(), Options{ |
| + Scope: cfg.scope, MailRegion: tRegion, Keys: keys, Counter: counter, Logf: h.logs.add, |
| + Now: func() time.Time { return h.now }, |
| + Clients: func(_ context.Context, k Key) (SES, release.Store, error) { |
| + h.builds = append(h.builds, k) |
| + return h.ses, h.wrapped, nil |
| + }, |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h.m = m |
| + h.h = NewHandler(m, m.Healthy) |
| + return h |
| +} |
| + |
| +func message(from string) string { |
| + return "From: Docs <" + from + ">\r\nTo: Someone <x@example.org>\r\nSubject: hi\r\n\r\nbody\r\n" |
| +} |
| + |
| +func (h *harness) request(mut ...func(*mailsubmit.SendRequest)) mailsubmit.SendRequest { |
| + req := mailsubmit.SendRequest{Account: tAcct, App: tApp, Host: tHost, From: tFrom, To: []string{"x@example.org"}, Raw: []byte(message(tFrom))} |
| + for _, f := range mut { |
| + f(&req) |
| + } |
| + return req |
| +} |
| + |
| +type sent struct { |
| + status int |
| + ans mailsubmit.Answer |
| + retryAfter string |
| +} |
| + |
| +func (h *harness) send(req mailsubmit.SendRequest) sent { |
| + h.t.Helper() |
| + body, err := json.Marshal(req) |
| + if err != nil { |
| + h.t.Fatal(err) |
| + } |
| + r := httptest.NewRequest(http.MethodPost, "/v1/send", bytes.NewReader(body)) |
| + w := httptest.NewRecorder() |
| + h.h.ServeHTTP(w, r) |
| + var ans mailsubmit.Answer |
| + _ = json.Unmarshal(w.Body.Bytes(), &ans) |
| + return sent{status: w.Code, ans: ans, retryAfter: w.Header().Get("Retry-After")} |
| +} |
| + |
| +func (h *harness) want(got sent, status int, code string) { |
| + h.t.Helper() |
| + if got.status != status || got.ans.Code != code { |
| + h.t.Fatalf("got %d %+v (Retry-After %q), want %d %s", got.status, got.ans, got.retryAfter, status, code) |
| + } |
| +} |
diff --git a/internal/mailer/hygiene.go b/internal/mailer/hygiene.go| new file mode 100644 |
| index 000000000..20ed5e8da |
| --- /dev/null |
| +++ b/internal/mailer/hygiene.go |
| @@ -0,0 +1,77 @@ |
| +package mailer |
| + |
| +import ( |
| + "bytes" |
| + "errors" |
| + "strings" |
| +) |
| + |
| +// errNoSeparator is a message with no empty line between its header block |
| +// and its body. |
| +var errNoSeparator = errors.New("mailer: message has no header/body separator") |
| + |
| +// splitHeader is raw's header block and body: the header lines up to the |
| +// first empty line (CRLF or LF), and everything after that line, byte for |
| +// byte. ok is false when there is no empty line. |
| +func splitHeader(raw []byte) (header, body []byte, ok bool) { |
| + for i := 0; i <= len(raw); { |
| + j := bytes.IndexByte(raw[i:], '\n') |
| + if j < 0 { |
| + return nil, nil, false |
| + } |
| + line := raw[i : i+j] |
| + if len(line) == 0 || (len(line) == 1 && line[0] == '\r') { |
| + return raw[:i], raw[i+j+1:], true |
| + } |
| + i += j + 1 |
| + } |
| + return nil, nil, false |
| +} |
| + |
| +// strippedField reports whether a header field of this name never reaches |
| +// SES (design §5, Header hygiene): Bcc, and every X-SES-* field. SMTP |
| +// honours X-SES-TENANT, X-SES-CONFIGURATION-SET and X-SES-MESSAGE-TAGS, and |
| +// §9.0 found the v2 raw path honours the last two when the parameters are |
| +// absent; the mailer always passes the parameters and strips the headers |
| +// regardless. |
| +func strippedField(name string) bool { |
| + return strings.EqualFold(name, "Bcc") || (len(name) >= 6 && strings.EqualFold(name[:6], "X-SES-")) |
| +} |
| + |
| +// StripHeaders removes every header field named Bcc or starting X-SES-, |
| +// case-insensitively, together with its folded continuation lines. A |
| +// field's name is what precedes its colon, with any whitespace before the |
| +// colon ignored (RFC 5322's obsolete syntax allows it, and a reader that |
| +// honours "Bcc :" must not see one). Only the header block is touched: the |
| +// body, and the line separating it, are returned byte for byte, and so is |
| +// every other header line. A message with no separator is an error. |
| +func StripHeaders(raw []byte) ([]byte, error) { |
| + header, _, ok := splitHeader(raw) |
| + if !ok { |
| + return nil, errNoSeparator |
| + } |
| + out := make([]byte, 0, len(raw)) |
| + dropping := false |
| + for i := 0; i < len(header); { |
| + j := bytes.IndexByte(header[i:], '\n') |
| + line := header[i : i+j+1] // the header block ends in "\n" by construction |
| + i += j + 1 |
| + if line[0] == ' ' || line[0] == '\t' { |
| + // A continuation belongs to the field above it. |
| + if !dropping { |
| + out = append(out, line...) |
| + } |
| + continue |
| + } |
| + dropping = false |
| + if c := bytes.IndexByte(line, ':'); c > 0 { |
| + name := strings.TrimRight(string(line[:c]), " \t") |
| + if strippedField(name) { |
| + dropping = true |
| + continue |
| + } |
| + } |
| + out = append(out, line...) |
| + } |
| + return append(out, raw[len(header):]...), nil |
| +} |
diff --git a/internal/mailer/hygiene_test.go b/internal/mailer/hygiene_test.go| new file mode 100644 |
| index 000000000..58b0c1dcb |
| --- /dev/null |
| +++ b/internal/mailer/hygiene_test.go |
| @@ -0,0 +1,69 @@ |
| +package mailer |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// Test 8.6 (design §5, Header hygiene): Bcc and every X-SES-* field never |
| +// reach SES, in every spelling and folding; every other header line and the |
| +// body are byte-identical. |
| +func TestHygieneStripsHeaders(t *testing.T) { |
| + in := "From: Docs <hello@docs.example.com>\r\n" + |
| + "Bcc: a@example.org\r\n" + |
| + "To: x@example.org\r\n" + |
| + "BCC: b@example.org,\r\n" + |
| + "\tc@example.org\r\n" + |
| + "X-SES-TENANT: other\r\n" + |
| + "Subject: a subject\r\n" + |
| + " folded on two lines\r\n" + |
| + "X-SES-CONFIGURATION-SET: theirs\r\n" + |
| + "x-ses-message-tags: account=victim, app=x\r\n" + |
| + "Bcc : spaced@example.org\r\n" + |
| + "bCc:\r\n" + |
| + " d@example.org\r\n" + |
| + "X-Sesame: kept\r\n" + |
| + "\r\n" + |
| + "Bcc: this is the body, kept\r\n" + |
| + "X-SES-TENANT: so is this\r\n" |
| + want := "From: Docs <hello@docs.example.com>\r\n" + |
| + "To: x@example.org\r\n" + |
| + "Subject: a subject\r\n" + |
| + " folded on two lines\r\n" + |
| + "X-Sesame: kept\r\n" + |
| + "\r\n" + |
| + "Bcc: this is the body, kept\r\n" + |
| + "X-SES-TENANT: so is this\r\n" |
| + got, err := StripHeaders([]byte(in)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if string(got) != want { |
| + t.Fatalf("stripped:\n%q\nwant:\n%q", got, want) |
| + } |
| + for _, gone := range []string{"a@example.org", "b@example.org", "c@example.org", "d@example.org", "spaced@", "theirs", "victim", "other"} { |
| + if strings.Contains(string(got[:strings.Index(string(got), "\r\n\r\n")]), gone) { |
| + t.Errorf("%q survived in the header block", gone) |
| + } |
| + } |
| + |
| + // LF-only line ends work the same way. |
| + lf := strings.ReplaceAll(in, "\r\n", "\n") |
| + got, err = StripHeaders([]byte(lf)) |
| + if err != nil || string(got) != strings.ReplaceAll(want, "\r\n", "\n") { |
| + t.Fatalf("LF-only: %q %v", got, err) |
| + } |
| + |
| + // A message with no header/body separator is an error, not a guess. |
| + for _, bad := range []string{"From: a@b.example.com\r\nSubject: x", "From: a@b.example.com", ""} { |
| + if _, err := StripHeaders([]byte(bad)); err == nil { |
| + t.Errorf("no separator %q: accepted", bad) |
| + } |
| + } |
| + |
| + // Nothing to strip: byte for byte. |
| + clean := "From: a@b.example.com\r\n\r\n\x00binary\xff body\r\n" |
| + if got, err := StripHeaders([]byte(clean)); err != nil || string(got) != clean { |
| + t.Fatalf("clean message changed: %q %v", got, err) |
| + } |
| +} |
diff --git a/internal/mailer/keys.go b/internal/mailer/keys.go| new file mode 100644 |
| index 000000000..353b5a7b4 |
| --- /dev/null |
| +++ b/internal/mailer/keys.go |
| @@ -0,0 +1,175 @@ |
| +package mailer |
| + |
| +import ( |
| + "bufio" |
| + "bytes" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "os/user" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// KeyPath is the mailer's key file (design §5): written by an operator by |
| +// hand, 0640 root:carlos-mailer, under a 0750 root:carlos-mailer directory |
| +// that uid carlos cannot traverse. |
| +const KeyPath = "/etc/carlos-mailer/keys" |
| + |
| +// mailerGroup is the group the key file must carry. |
| +const mailerGroup = "carlos-mailer" |
| + |
| +// maxKeys is IAM's limit of access keys per user: rotation arms the second |
| +// key beside the first, then deletes the old one. |
| +const maxKeys = 2 |
| + |
| +// Key is one access key of the region's mailer IAM user. |
| +type Key struct { |
| + ID string |
| + Secret string |
| + Created time.Time |
| +} |
| + |
| +// keyOwnerCheck refuses a key file not owned by root and group |
| +// carlos-mailer. A test seam: tests cannot chown to root. |
| +var keyOwnerCheck = rootAndMailerGroup |
| + |
| +func rootAndMailerGroup(fi os.FileInfo) error { |
| + uid, gid, ok := fileOwner(fi) |
| + if !ok { |
| + return errors.New("cannot read the key file's owner on this system") |
| + } |
| + g, err := user.LookupGroup(mailerGroup) |
| + if err != nil { |
| + return fmt.Errorf("group %s: %w", mailerGroup, err) |
| + } |
| + want, err := strconv.Atoi(g.Gid) |
| + if err != nil { |
| + return fmt.Errorf("group %s gid %q: %w", mailerGroup, g.Gid, err) |
| + } |
| + if uid != 0 || gid != want { |
| + return fmt.Errorf("owned by %d:%d, want root:%s (0:%d)", uid, gid, mailerGroup, want) |
| + } |
| + return nil |
| +} |
| + |
| +// LoadKeys reads the key file: up to two lines of |
| +// "<access-key-id> <secret-access-key> <created RFC 3339>", with "#" |
| +// comments and blank lines skipped. It refuses a file that is not mode |
| +// 0640, not owned by root, or not group carlos-mailer; one with no key or |
| +// more than two; and any line it cannot read. The error never carries a |
| +// secret. |
| +func LoadKeys(path string) ([]Key, error) { |
| + keys, _, err := loadKeys(path) |
| + return keys, err |
| +} |
| + |
| +func loadKeys(path string) ([]Key, os.FileInfo, error) { |
| + f, err := os.Open(path) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + defer f.Close() |
| + fi, err := f.Stat() |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + if !fi.Mode().IsRegular() || fi.Mode().Perm() != 0o640 { |
| + return nil, nil, fmt.Errorf("%s: mode %v, want a regular file 0640", path, fi.Mode()) |
| + } |
| + if err := keyOwnerCheck(fi); err != nil { |
| + return nil, nil, fmt.Errorf("%s: %w", path, err) |
| + } |
| + var buf bytes.Buffer |
| + if _, err := buf.ReadFrom(f); err != nil { |
| + return nil, nil, err |
| + } |
| + var keys []Key |
| + sc := bufio.NewScanner(&buf) |
| + for n := 1; sc.Scan(); n++ { |
| + line := strings.TrimSpace(sc.Text()) |
| + if line == "" || strings.HasPrefix(line, "#") { |
| + continue |
| + } |
| + fields := strings.Fields(line) |
| + if len(fields) != 3 || fields[0] == "" || fields[1] == "" { |
| + return nil, nil, fmt.Errorf("%s:%d: want \"<key id> <secret> <created RFC 3339>\"", path, n) |
| + } |
| + created, err := time.Parse(time.RFC3339, fields[2]) |
| + if err != nil { |
| + return nil, nil, fmt.Errorf("%s:%d: created is not RFC 3339", path, n) |
| + } |
| + keys = append(keys, Key{ID: fields[0], Secret: fields[1], Created: created}) |
| + } |
| + if err := sc.Err(); err != nil { |
| + return nil, nil, err |
| + } |
| + switch { |
| + case len(keys) == 0: |
| + return nil, nil, fmt.Errorf("%s: no key", path) |
| + case len(keys) > maxKeys: |
| + return nil, nil, fmt.Errorf("%s: %d keys, at most %d (IAM allows two per user)", path, len(keys), maxKeys) |
| + } |
| + return keys, fi, nil |
| +} |
| + |
| +// KeyFile is the loaded key file, and how to tell it changed. The mailer |
| +// asks Changed before each send; a change reloads the file and rebuilds |
| +// both clients, so a rotation needs no restart (design §5, Rotation). |
| +type KeyFile struct { |
| + path string |
| + |
| + mu sync.Mutex |
| + keys []Key |
| + fi os.FileInfo |
| +} |
| + |
| +// OpenKeyFile loads path. |
| +func OpenKeyFile(path string) (*KeyFile, error) { |
| + keys, fi, err := loadKeys(path) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &KeyFile{path: path, keys: keys, fi: fi}, nil |
| +} |
| + |
| +// Newest is the key with the newest created time: the one the mailer |
| +// signs with. With two keys armed during a rotation, that is the new one. |
| +func (k *KeyFile) Newest() Key { |
| + k.mu.Lock() |
| + defer k.mu.Unlock() |
| + best := k.keys[0] |
| + for _, key := range k.keys[1:] { |
| + if key.Created.After(best.Created) { |
| + best = key |
| + } |
| + } |
| + return best |
| +} |
| + |
| +// Changed reports whether the file on disk is no longer the one loaded: |
| +// another modification time, size or inode, or gone. |
| +func (k *KeyFile) Changed() bool { |
| + fi, err := os.Stat(k.path) |
| + if err != nil { |
| + return true |
| + } |
| + k.mu.Lock() |
| + defer k.mu.Unlock() |
| + return !fi.ModTime().Equal(k.fi.ModTime()) || fi.Size() != k.fi.Size() || !os.SameFile(fi, k.fi) |
| +} |
| + |
| +// Reload reads the file again. On an error the loaded keys stay as they |
| +// were; the caller decides whether to keep sending with them. |
| +func (k *KeyFile) Reload() error { |
| + keys, fi, err := loadKeys(k.path) |
| + if err != nil { |
| + return err |
| + } |
| + k.mu.Lock() |
| + k.keys, k.fi = keys, fi |
| + k.mu.Unlock() |
| + return nil |
| +} |
diff --git a/internal/mailer/keys_other.go b/internal/mailer/keys_other.go| new file mode 100644 |
| index 000000000..fee26ec92 |
| --- /dev/null |
| +++ b/internal/mailer/keys_other.go |
| @@ -0,0 +1,8 @@ |
| +//go:build !unix |
| + |
| +package mailer |
| + |
| +import "os" |
| + |
| +// fileOwner cannot say who owns a file here, so every key file is refused. |
| +func fileOwner(os.FileInfo) (uid, gid int, ok bool) { return 0, 0, false } |
diff --git a/internal/mailer/keys_test.go b/internal/mailer/keys_test.go| new file mode 100644 |
| index 000000000..f2778f4cc |
| --- /dev/null |
| +++ b/internal/mailer/keys_test.go |
| @@ -0,0 +1,109 @@ |
| +package mailer |
| + |
| +import ( |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The key file (design §5, Its credential): 0640 root:carlos-mailer, at |
| +// most two keys (IAM's rotation pair), the newest used, and a change on |
| +// disk seen without a restart. |
| +func TestKeysFile(t *testing.T) { |
| + noOwnerCheck(t) |
| + dir := t.TempDir() |
| + path := filepath.Join(dir, "keys") |
| + |
| + writeKeys(t, path, "# a comment\n\nAKIDA secretA 2026-11-01T00:00:00Z\nAKIDB secretB 2026-11-13T00:00:00Z\n") |
| + kf, err := OpenKeyFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if k := kf.Newest(); k.ID != "AKIDB" || k.Secret != "secretB" { |
| + t.Fatalf("newest = %+v", k) |
| + } |
| + // The newest wins whatever the order in the file. |
| + writeKeys(t, path, "AKIDB secretB 2026-11-13T00:00:00Z\nAKIDA secretA 2026-11-01T00:00:00Z\n") |
| + if keys, err := LoadKeys(path); err != nil || len(keys) != 2 { |
| + t.Fatalf("reordered: %v %v", keys, err) |
| + } |
| + |
| + for name, body := range map[string]string{ |
| + "three keys": "A a 2026-11-01T00:00:00Z\nB b 2026-11-02T00:00:00Z\nC c 2026-11-03T00:00:00Z\n", |
| + "no key": "# nothing\n", |
| + "two fields": "AKIDA secretA\n", |
| + "bad created": "AKIDA secretA yesterday\n", |
| + "four fields": "AKIDA secretA 2026-11-01T00:00:00Z extra\n", |
| + } { |
| + writeKeys(t, path, body) |
| + if _, err := LoadKeys(path); err == nil { |
| + t.Errorf("%s: accepted", name) |
| + } else if strings.Contains(err.Error(), "secretA") { |
| + t.Errorf("%s: the error carries the secret: %v", name, err) |
| + } |
| + } |
| + |
| + // Mode other than 0640. |
| + writeKeys(t, path, "AKIDA secretA 2026-11-01T00:00:00Z\n") |
| + for _, mode := range []os.FileMode{0o600, 0o644, 0o660, 0o440} { |
| + if err := os.Chmod(path, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := LoadKeys(path); err == nil { |
| + t.Errorf("mode %o: accepted", mode) |
| + } |
| + } |
| + if err := os.Chmod(path, 0o640); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Not a regular file. |
| + if _, err := LoadKeys(dir); err == nil { |
| + t.Error("a directory: accepted") |
| + } |
| + // The owner check is consulted, and refuses. |
| + keyOwnerCheck = func(os.FileInfo) error { return errors.New("owned by 1000:1000") } |
| + if _, err := LoadKeys(path); err == nil || !strings.Contains(err.Error(), "owned by") { |
| + t.Errorf("a wrong owner: %v", err) |
| + } |
| + keyOwnerCheck = func(os.FileInfo) error { return nil } |
| + |
| + // The production owner check refuses a file this test user owns. |
| + if os.Geteuid() != 0 { |
| + fi, _ := os.Stat(path) |
| + if err := rootAndMailerGroup(fi); err == nil { |
| + t.Error("rootAndMailerGroup accepted a file not owned by root") |
| + } |
| + } |
| + |
| + // An mtime change is seen, and a reload picks up the new keys. |
| + kf, err = OpenKeyFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if kf.Changed() { |
| + t.Fatal("changed with nothing changed") |
| + } |
| + writeKeys(t, path, "AKIDA secretA 2026-11-01T00:00:00Z\nAKIDC secretC 2026-11-14T00:00:00Z\n") |
| + later := time.Now().Add(time.Minute) |
| + _ = os.Chtimes(path, later, later) |
| + if !kf.Changed() { |
| + t.Fatal("an mtime change was not seen") |
| + } |
| + if err := kf.Reload(); err != nil || kf.Newest().ID != "AKIDC" || kf.Changed() { |
| + t.Fatalf("reload: %v newest %s", err, kf.Newest().ID) |
| + } |
| + // A reload that fails keeps the loaded keys. |
| + writeKeys(t, path, "garbage\n") |
| + if err := kf.Reload(); err == nil || kf.Newest().ID != "AKIDC" { |
| + t.Fatalf("a failed reload: %v, newest %s", err, kf.Newest().ID) |
| + } |
| + if err := os.Remove(path); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !kf.Changed() { |
| + t.Fatal("a removed file is not a change") |
| + } |
| +} |
diff --git a/internal/mailer/keys_unix.go b/internal/mailer/keys_unix.go| new file mode 100644 |
| index 000000000..dd1b15cad |
| --- /dev/null |
| +++ b/internal/mailer/keys_unix.go |
| @@ -0,0 +1,16 @@ |
| +//go:build unix |
| + |
| +package mailer |
| + |
| +import ( |
| + "os" |
| + "syscall" |
| +) |
| + |
| +func fileOwner(fi os.FileInfo) (uid, gid int, ok bool) { |
| + st, ok := fi.Sys().(*syscall.Stat_t) |
| + if !ok { |
| + return 0, 0, false |
| + } |
| + return int(st.Uid), int(st.Gid), true |
| +} |
diff --git a/internal/mailer/policy.go b/internal/mailer/policy.go| new file mode 100644 |
| index 000000000..1b6e57610 |
| --- /dev/null |
| +++ b/internal/mailer/policy.go |
| @@ -0,0 +1,278 @@ |
| +package mailer |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "math" |
| + "net/http" |
| + "net/mail" |
| + "os" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/mailsubmit" |
| + "github.com/carlosframework/platform/internal/mailwire" |
| +) |
| + |
| +// senderTTL is how long a sender record is kept: a pause or a switch-off |
| +// the console writes is honoured within it. |
| +const senderTTL = 2 * time.Second |
| + |
| +// How long a domain record answer is kept. |
| +const ( |
| + domainTTL = 30 * time.Second |
| + domainAbsentTTL = 5 * time.Second |
| +) |
| + |
| +// decision is admit's answer: a refusal (status and code, with |
| +// Retry-After when it has one), or an admitted message with what the send |
| +// needs. An admitted message holds a counter slot, which the caller |
| +// releases if SES does not take it. |
| +type decision struct { |
| + status int |
| + code string |
| + retryAfter string |
| + |
| + sender *mailwire.SenderView |
| + from string // the bare From address |
| + configSet string |
| + counterKey string |
| + day string |
| +} |
| + |
| +func refuse(status int, code string) decision { return decision{status: status, code: code} } |
| + |
| +func (d decision) admitted() bool { return d.status == 0 } |
| + |
| +type cached[T any] struct { |
| + v *T |
| + at time.Time |
| +} |
| + |
| +type viewCache[T any] struct { |
| + mu sync.Mutex |
| + m map[string]cached[T] |
| +} |
| + |
| +func (c *viewCache[T]) get(k string, now time.Time, ttl, absentTTL time.Duration) (*T, bool) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + e, ok := c.m[k] |
| + if !ok { |
| + return nil, false |
| + } |
| + limit := ttl |
| + if e.v == nil { |
| + limit = absentTTL |
| + } |
| + if now.Sub(e.at) >= limit { |
| + return nil, false |
| + } |
| + return e.v, true |
| +} |
| + |
| +func (c *viewCache[T]) put(k string, v *T, now time.Time) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.m[k] = cached[T]{v: v, at: now} |
| +} |
| + |
| +// readJSON reads key through the mailer's store and decodes it into a new |
| +// T. An absent object (a denied read included) is nil and no error. |
| +func readJSON[T any](ctx context.Context, m *Mailer, key string) (*T, error) { |
| + body, _, err := m.storeNow().Get(ctx, key) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + v := new(T) |
| + if err := json.Unmarshal(body, v); err != nil { |
| + return nil, fmt.Errorf("mailer: %s: %w", key, err) |
| + } |
| + return v, nil |
| +} |
| + |
| +// admit applies the sender's policy to a stamped request before any SES |
| +// call, in the plan's order (Task 5, policy.go): |
| +// |
| +// 1. the route is on this box, else 403 ROUTE_NOT_ON_BOX; |
| +// 2. the app sender exists and is switched to submission, else 403 |
| +// SUBMISSION_OFF; |
| +// 3. it is not paused, else 429 PAUSED; |
| +// 4. raw has exactly one From: whose address is req.From, else 400; |
| +// 5. that address's domain is one the sender was granted, whose domain |
| +// record lists the app and is verified in the mail region, else 403 |
| +// FROM_NOT_ALLOWED; |
| +// 6. a slot of the sender's daily cap is reserved, else 429 CAP_REACHED; |
| +// 7. a token of the sender's rate is taken, else 429 RATE, and the slot |
| +// is given back. |
| +// |
| +// A store error at any step is 503 MAILER_UNAVAILABLE, never an admit. |
| +func (m *Mailer) admit(ctx context.Context, req mailsubmit.SendRequest) decision { |
| + now := m.now() |
| + unavailable := refuse(http.StatusServiceUnavailable, mailsubmit.CodeMailerUnavailable) |
| + |
| + // 1. Box-local routes only (decision 4, test 8.4). |
| + here, err := m.routeHere(ctx, req.Account, req.App, req.Host) |
| + if err != nil { |
| + m.logf("mailer: route %s/%s/%s: %v", req.Account, req.App, req.Host, err) |
| + return unavailable |
| + } |
| + if !here { |
| + return refuse(http.StatusForbidden, mailsubmit.CodeRouteNotOnBox) |
| + } |
| + |
| + // 2. The app sender, and its switch. |
| + sender, err := m.sender(ctx, req.Account, req.App, now) |
| + if err != nil { |
| + m.logf("mailer: sender %s/%s: %v", req.Account, req.App, err) |
| + return unavailable |
| + } |
| + if sender == nil || sender.Submission == nil || !sender.Submission.On { |
| + return refuse(http.StatusForbidden, mailsubmit.CodeSubmissionOff) |
| + } |
| + |
| + // 3. Pause, on the record (decision 8). |
| + if p := sender.EffectivePause(); p != nil { |
| + d := refuse(http.StatusTooManyRequests, mailsubmit.CodePaused) |
| + d.retryAfter = "3600" |
| + if p.LiftsAtDayRoll() { |
| + d.retryAfter = secondsToMidnight(now) |
| + } |
| + return d |
| + } |
| + |
| + // 4. from is the one From: header (§4). |
| + from, ok := oneFrom(req.Raw, req.From) |
| + if !ok { |
| + return refuse(http.StatusBadRequest, mailsubmit.CodeBadRequest) |
| + } |
| + |
| + // 5. The From domain, granted and verified in the mail region. |
| + at := strings.LastIndexByte(from, '@') |
| + domain := strings.ToLower(from[at+1:]) |
| + if sender.Grant == nil || !slices.Contains(sender.Grant.Domains, domain) { |
| + return refuse(http.StatusForbidden, mailsubmit.CodeFromNotAllowed) |
| + } |
| + dv, err := m.domain(ctx, req.Account, domain, now) |
| + if err != nil { |
| + m.logf("mailer: domain %s/%s: %v", req.Account, domain, err) |
| + return unavailable |
| + } |
| + if dv == nil || !slices.Contains(dv.Apps, req.App) { |
| + return refuse(http.StatusForbidden, mailsubmit.CodeFromNotAllowed) |
| + } |
| + region := dv.Regions[m.mailRegion] |
| + if region == nil || region.Status != mailwire.DomainStatusVerified || region.IdentityARN == "" { |
| + return refuse(http.StatusForbidden, mailsubmit.CodeFromNotAllowed) |
| + } |
| + |
| + // 6. The per-box daily cap (decision 9, §4.1 (a)): messages, not |
| + // recipients, as the console counts Send events. |
| + limit := sender.Grant.DailyCap |
| + if limit <= 0 { |
| + limit = mailwire.DefaultDailyCap |
| + } |
| + // The sender is the app sender, read from its own key (decision 5): |
| + // the key and the tag name it by that id, never by the body's. |
| + key := req.Account + "/" + req.App + "/" + mailwire.SenderAppID |
| + day := Day(now) |
| + reserved, err := m.counter.Reserve(key, day, limit) |
| + if err != nil { |
| + m.logf("mailer: cap counter for %s: %v", key, err) |
| + return unavailable |
| + } |
| + if !reserved { |
| + d := refuse(http.StatusTooManyRequests, mailsubmit.CodeCapReached) |
| + d.retryAfter = secondsToMidnight(now) |
| + return d |
| + } |
| + |
| + // 7. The per-sender rate (G9). A refused take gives the slot back. |
| + if ok, wait := m.buckets.Take(key, now); !ok { |
| + m.counter.Release(key, day) |
| + d := refuse(http.StatusTooManyRequests, mailsubmit.CodeRate) |
| + d.retryAfter = strconv.Itoa(max(1, int(math.Ceil(wait.Seconds())))) |
| + return d |
| + } |
| + return decision{sender: sender, from: from, configSet: region.ConfigSet, counterKey: key, day: day} |
| +} |
| + |
| +// sender is the app sender record, cached senderTTL. |
| +func (m *Mailer) sender(ctx context.Context, acct, app string, now time.Time) (*mailwire.SenderView, error) { |
| + key := mailwire.SenderKey(acct, app, mailwire.SenderAppID) |
| + if v, ok := m.senders.get(key, now, senderTTL, senderTTL); ok { |
| + return v, nil |
| + } |
| + v, err := readJSON[mailwire.SenderView](ctx, m, key) |
| + if err != nil { |
| + return nil, err |
| + } |
| + m.senders.put(key, v, now) |
| + return v, nil |
| +} |
| + |
| +// domain is one domain record, read by key (never listed), cached. |
| +func (m *Mailer) domain(ctx context.Context, acct, domain string, now time.Time) (*mailwire.DomainView, error) { |
| + key := mailwire.DomainKey(acct, domain) |
| + if v, ok := m.domains.get(key, now, domainTTL, domainAbsentTTL); ok { |
| + return v, nil |
| + } |
| + v, err := readJSON[mailwire.DomainView](ctx, m, key) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if v != nil && v.Domain != domain { |
| + // A body that disagrees with its key is no record of this domain. |
| + v = nil |
| + } |
| + m.domains.put(key, v, now) |
| + return v, nil |
| +} |
| + |
| +// oneFrom is the address of raw's From: header when there is exactly one |
| +// From: field naming exactly one address, and it equals envelopeFrom's |
| +// address case-insensitively. The header block must parse. |
| +func oneFrom(raw []byte, envelopeFrom string) (string, bool) { |
| + want, err := mail.ParseAddress(envelopeFrom) |
| + if err != nil || !strings.Contains(want.Address, "@") { |
| + return "", false |
| + } |
| + header, _, ok := splitHeader(raw) |
| + if !ok { |
| + return "", false |
| + } |
| + msg, err := mail.ReadMessage(bytes.NewReader(append(append([]byte(nil), header...), "\r\n"...))) |
| + if err != nil { |
| + return "", false |
| + } |
| + froms := msg.Header["From"] |
| + if len(froms) != 1 { |
| + return "", false |
| + } |
| + list, err := mail.ParseAddressList(froms[0]) |
| + if err != nil || len(list) != 1 || !strings.EqualFold(list[0].Address, want.Address) { |
| + return "", false |
| + } |
| + addr := list[0].Address |
| + at := strings.LastIndexByte(addr, '@') |
| + if at <= 0 || at == len(addr)-1 { |
| + return "", false |
| + } |
| + return addr, true |
| +} |
| + |
| +// secondsToMidnight is Retry-After to the next UTC midnight, at least 1. |
| +func secondsToMidnight(now time.Time) string { |
| + u := now.UTC() |
| + next := time.Date(u.Year(), u.Month(), u.Day()+1, 0, 0, 0, 0, time.UTC) |
| + return strconv.Itoa(max(1, int(math.Ceil(next.Sub(u).Seconds())))) |
| +} |
diff --git a/internal/mailer/rate.go b/internal/mailer/rate.go| new file mode 100644 |
| index 000000000..7ab2a77f0 |
| --- /dev/null |
| +++ b/internal/mailer/rate.go |
| @@ -0,0 +1,56 @@ |
| +package mailer |
| + |
| +import ( |
| + "math" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// The per-sender token bucket (design §5, Rate; plan gap G9): two messages |
| +// a second, a burst of twenty, per sender per box. Paul to confirm against |
| +// the deployment's SES send rate. |
| +const ( |
| + Rate = 2 |
| + Burst = 20 |
| +) |
| + |
| +// Buckets is one token bucket per (account, app, sender), in memory: a |
| +// restart refills every bucket, which is at most one burst. |
| +type Buckets struct { |
| + rate float64 |
| + burst float64 |
| + |
| + mu sync.Mutex |
| + buckets map[string]*bucket |
| +} |
| + |
| +type bucket struct { |
| + tokens float64 |
| + last time.Time |
| +} |
| + |
| +// NewBuckets is Rate per second with a burst of Burst. |
| +func NewBuckets() *Buckets { |
| + return &Buckets{rate: Rate, burst: Burst, buckets: map[string]*bucket{}} |
| +} |
| + |
| +// Take spends one token of key's bucket at now. When none is left it |
| +// spends nothing and reports how long until one is. |
| +func (b *Buckets) Take(key string, now time.Time) (ok bool, wait time.Duration) { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + bk, seen := b.buckets[key] |
| + if !seen { |
| + bk = &bucket{tokens: b.burst, last: now} |
| + b.buckets[key] = bk |
| + } |
| + if now.After(bk.last) { |
| + bk.tokens = math.Min(b.burst, bk.tokens+now.Sub(bk.last).Seconds()*b.rate) |
| + bk.last = now |
| + } |
| + if bk.tokens >= 1 { |
| + bk.tokens-- |
| + return true, 0 |
| + } |
| + return false, time.Duration((1 - bk.tokens) / b.rate * float64(time.Second)) |
| +} |
diff --git a/internal/mailer/routes.go b/internal/mailer/routes.go| new file mode 100644 |
| index 000000000..5f06f06ae |
| --- /dev/null |
| +++ b/internal/mailer/routes.go |
| @@ -0,0 +1,69 @@ |
| +package mailer |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +// How long a route answer is kept: a route that is here stays here for |
| +// 30 s; one that is not is asked again after 5 s, so a route that has just |
| +// been minted is not refused for long. |
| +const ( |
| + routeHereTTL = 30 * time.Second |
| + routeNotHereTTL = 5 * time.Second |
| +) |
| + |
| +type routeAnswer struct { |
| + here bool |
| + at time.Time |
| +} |
| + |
| +type routeCache struct { |
| + mu sync.Mutex |
| + answers map[[3]string]routeAnswer |
| +} |
| + |
| +// routeHere reports whether (acct, app, host) is a route of this box |
| +// (design decision 4): its instance record, read from the bucket through |
| +// provision.GetRecord (which refuses a body that disagrees with its key), |
| +// is one BoxServesRecord admits for this box's scope. An absent record |
| +// (a denied read included), a retired one, or a body that does not match |
| +// its key is not here. Only a store error that is none of these is an |
| +// error, for a 503. |
| +func (m *Mailer) routeHere(ctx context.Context, acct, app, host string) (bool, error) { |
| + k := [3]string{acct, app, host} |
| + now := m.now() |
| + m.routes.mu.Lock() |
| + if a, ok := m.routes.answers[k]; ok { |
| + ttl := routeNotHereTTL |
| + if a.here { |
| + ttl = routeHereTTL |
| + } |
| + if now.Sub(a.at) < ttl { |
| + m.routes.mu.Unlock() |
| + return a.here, nil |
| + } |
| + } |
| + m.routes.mu.Unlock() |
| + |
| + here := false |
| + rec, err := provision.GetRecord(ctx, m.storeNow(), acct, app, host) |
| + switch { |
| + case err == nil: |
| + here = provision.BoxServesRecord(m.scope, *rec) |
| + case errors.Is(err, os.ErrNotExist): |
| + case errors.Is(err, provision.ErrRecordCorrupt): |
| + m.logf("mailer: instance record %s/%s/%s refused: %v", acct, app, host, err) |
| + default: |
| + return false, err |
| + } |
| + m.routes.mu.Lock() |
| + m.routes.answers[k] = routeAnswer{here: here, at: now} |
| + m.routes.mu.Unlock() |
| + return here, nil |
| +} |
diff --git a/internal/mailer/send.go b/internal/mailer/send.go| new file mode 100644 |
| index 000000000..9f6b3de9a |
| --- /dev/null |
| +++ b/internal/mailer/send.go |
| @@ -0,0 +1,224 @@ |
| +package mailer |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/mail" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + |
| + "github.com/carlosframework/platform/internal/mailsubmit" |
| + "github.com/carlosframework/platform/internal/mailwire" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// maxInFlight is how many sends the mailer runs at once; above it the |
| +// answer is 503 MAILER_UNAVAILABLE at once, which the app retries. |
| +const maxInFlight = 4 |
| + |
| +// Options configure a Mailer. |
| +type Options struct { |
| + // Scope is this box's scope, by the agent's rule (host.BoxScopeFromEnv). |
| + Scope provision.BoxScope |
| + // MailRegion is CARLOS_MAIL_REGION: SES's region, and the region whose |
| + // identity status a From domain must have. |
| + MailRegion string |
| + // Keys is the loaded key file. |
| + Keys *KeyFile |
| + // Counter is the per-box daily counter. |
| + Counter *Counter |
| + // Clients builds the SES client and the deployment store over a key |
| + // (AWSClients in production). The store is wrapped in |
| + // absentOnDeniedStore here, whatever builds it. |
| + Clients func(context.Context, Key) (SES, release.Store, error) |
| + // Logf is the journal; nil discards. |
| + Logf func(string, ...any) |
| + // Now is the clock; nil is time.Now. |
| + Now func() time.Time |
| +} |
| + |
| +// Mailer is the send pipeline behind POST /v1/send. |
| +type Mailer struct { |
| + scope provision.BoxScope |
| + mailRegion string |
| + keys *KeyFile |
| + counter *Counter |
| + clients func(context.Context, Key) (SES, release.Store, error) |
| + logf func(string, ...any) |
| + now func() time.Time |
| + |
| + buckets *Buckets |
| + sem chan struct{} |
| + routes routeCache |
| + senders viewCache[mailwire.SenderView] |
| + domains viewCache[mailwire.DomainView] |
| + |
| + mu sync.Mutex |
| + ses SES |
| + store release.Store |
| + broken error // the key file changed and did not reload: refuse everything |
| +} |
| + |
| +// New builds a Mailer and its clients over the newest key. |
| +func New(ctx context.Context, o Options) (*Mailer, error) { |
| + if o.Keys == nil || o.Counter == nil || o.Clients == nil || o.MailRegion == "" { |
| + return nil, errors.New("mailer: keys, counter, clients and mail region are required") |
| + } |
| + m := &Mailer{scope: o.Scope, mailRegion: o.MailRegion, keys: o.Keys, counter: o.Counter, clients: o.Clients, |
| + logf: o.Logf, now: o.Now, buckets: NewBuckets(), sem: make(chan struct{}, maxInFlight)} |
| + if m.logf == nil { |
| + m.logf = func(string, ...any) {} |
| + } |
| + if m.now == nil { |
| + m.now = time.Now |
| + } |
| + m.routes.answers = map[[3]string]routeAnswer{} |
| + m.senders.m = map[string]cached[mailwire.SenderView]{} |
| + m.domains.m = map[string]cached[mailwire.DomainView]{} |
| + if err := m.buildClients(ctx); err != nil { |
| + return nil, err |
| + } |
| + return m, nil |
| +} |
| + |
| +// buildClients (re)builds both clients over the newest key. m.mu is not |
| +// held. |
| +func (m *Mailer) buildClients(ctx context.Context) error { |
| + ses, store, err := m.clients(ctx, m.keys.Newest()) |
| + if err != nil { |
| + return fmt.Errorf("mailer: build clients: %w", err) |
| + } |
| + m.mu.Lock() |
| + m.ses, m.store = ses, newAbsentOnDeniedStore(store, m.logf) |
| + m.mu.Unlock() |
| + return nil |
| +} |
| + |
| +func (m *Mailer) storeNow() release.Store { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + return m.store |
| +} |
| + |
| +func (m *Mailer) sesNow() SES { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + return m.ses |
| +} |
| + |
| +// refreshKeys reloads the key file and rebuilds both clients when it has |
| +// changed on disk (a rotation, design §5). A file that no longer loads (an |
| +// operator removing the key to disarm, or writing a bad one) leaves the |
| +// mailer refusing every send, and unhealthy, until it loads again. |
| +func (m *Mailer) refreshKeys(ctx context.Context) error { |
| + if !m.keys.Changed() { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + return m.broken |
| + } |
| + err := m.keys.Reload() |
| + if err == nil { |
| + err = m.buildClients(ctx) |
| + } |
| + m.mu.Lock() |
| + m.broken = err |
| + m.mu.Unlock() |
| + if err != nil { |
| + m.logf("mailer: ALERT: key file changed and did not load; refusing every send until it does: %v", err) |
| + return err |
| + } |
| + m.logf("mailer: key file changed; clients rebuilt over key %s", m.keys.Newest().ID) |
| + return nil |
| +} |
| + |
| +// Healthy is GET /v1/health's answer: the key file loads and the clients |
| +// are built. |
| +func (m *Mailer) Healthy() error { return m.refreshKeys(context.Background()) } |
| + |
| +// ServeHTTP is POST /v1/send: one stamped message from the agent, answered |
| +// synchronously with SES's result or the coded refusal (design §4). |
| +func (m *Mailer) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + select { |
| + case m.sem <- struct{}{}: |
| + defer func() { <-m.sem }() |
| + default: |
| + answer(w, http.StatusServiceUnavailable, mailsubmit.Answer{Code: mailsubmit.CodeMailerUnavailable}, "") |
| + return |
| + } |
| + var req mailsubmit.SendRequest |
| + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, mailsubmit.MaxBody)).Decode(&req); err != nil || !validRequest(req) { |
| + answer(w, http.StatusBadRequest, mailsubmit.Answer{Code: mailsubmit.CodeBadRequest}, "") |
| + return |
| + } |
| + ctx := r.Context() |
| + if err := m.refreshKeys(ctx); err != nil { |
| + answer(w, http.StatusServiceUnavailable, mailsubmit.Answer{Code: mailsubmit.CodeMailerUnavailable}, "") |
| + return |
| + } |
| + d := m.admit(ctx, req) |
| + if !d.admitted() { |
| + m.logf("mailer: %s/%s %s: %d %s", req.Account, req.App, req.Host, d.status, d.code) |
| + answer(w, d.status, mailsubmit.Answer{Code: d.code}, d.retryAfter) |
| + return |
| + } |
| + stripped, err := StripHeaders(req.Raw) |
| + if err != nil { |
| + m.counter.Release(d.counterKey, d.day) |
| + answer(w, http.StatusBadRequest, mailsubmit.Answer{Code: mailsubmit.CodeBadRequest}, "") |
| + return |
| + } |
| + out, err := m.sesNow().SendEmail(ctx, sendInput(req, d, stripped)) |
| + if err != nil { |
| + m.counter.Release(d.counterKey, d.day) |
| + status, code, retryAfter := sesRefusal(err) |
| + m.logf("mailer: %s/%s %s: SES refused: %d %s: %v", req.Account, req.App, req.Host, status, code, err) |
| + answer(w, status, mailsubmit.Answer{Code: code}, retryAfter) |
| + return |
| + } |
| + id := aws.ToString(out.MessageId) |
| + m.logf("mailer: %s/%s %s: sent %s to %d recipients", req.Account, req.App, req.Host, id, len(req.To)) |
| + answer(w, http.StatusOK, mailsubmit.Answer{MessageID: id}, "") |
| +} |
| + |
| +// validRequest is the stamped request's shape: names the bucket keys can |
| +// be built from, a from, 1 to 50 recipients that each parse as one |
| +// address, and a raw message within the limit. The agent checked most of |
| +// it; the mailer does not rely on that. |
| +func validRequest(req mailsubmit.SendRequest) bool { |
| + if !release.ValidAccount(req.Account) || !release.ValidApp(req.App) || !validHost(req.Host) { |
| + return false |
| + } |
| + if req.From == "" || len(req.To) == 0 || len(req.To) > mailsubmit.MaxRecipients || len(req.Raw) == 0 || len(req.Raw) > mailsubmit.MaxRaw { |
| + return false |
| + } |
| + for _, to := range req.To { |
| + a, err := mail.ParseAddress(to) |
| + if err != nil || a.Name != "" || !strings.Contains(a.Address, "@") { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// validHost is a hostname a record key may be built from: no path |
| +// separators, no traversal. |
| +func validHost(h string) bool { |
| + return h != "" && len(h) <= 253 && !strings.ContainsAny(h, "/\\ \t\r\n") && !strings.Contains(h, "..") |
| +} |
| + |
| +// answer writes the mailer's answer as JSON. |
| +func answer(w http.ResponseWriter, status int, ans mailsubmit.Answer, retryAfter string) { |
| + w.Header().Set("Content-Type", "application/json") |
| + if retryAfter != "" { |
| + w.Header().Set("Retry-After", retryAfter) |
| + } |
| + w.WriteHeader(status) |
| + _ = json.NewEncoder(w).Encode(ans) |
| +} |
diff --git a/internal/mailer/send_test.go b/internal/mailer/send_test.go| new file mode 100644 |
| index 000000000..c5a2df081 |
| --- /dev/null |
| +++ b/internal/mailer/send_test.go |
| @@ -0,0 +1,446 @@ |
| +package mailer |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + sesv2types "github.com/aws/aws-sdk-go-v2/service/sesv2/types" |
| + "github.com/aws/smithy-go" |
| + |
| + "github.com/carlosframework/platform/internal/mailsubmit" |
| + "github.com/carlosframework/platform/internal/mailwire" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// Test 8.4 (design decision 4): a stamp naming a route that is not on this |
| +// box is refused before any SES call. |
| +func TestMailerRefusesRouteNotOnBox(t *testing.T) { |
| + rec := func(f func(*provision.Record)) harnessOpt { |
| + return func(c *harnessCfg) { |
| + r := defaultRecord() |
| + f(&r) |
| + c.record = &r |
| + } |
| + } |
| + scope := func(s provision.BoxScope) harnessOpt { return func(c *harnessCfg) { c.scope = s } } |
| + for name, opts := range map[string][]harnessOpt{ |
| + "another region": {rec(func(r *provision.Record) { r.Region = "us" })}, |
| + "another pool": {rec(func(r *provision.Record) { r.Pool = "tito" })}, |
| + "labelled for another fleet box": {scope(provision.BoxScope{Region: "fleet/pi", FleetBox: "pi-1"}), |
| + rec(func(r *provision.Record) { r.Region, r.FleetBox = "fleet/pi", "pi-2" })}, |
| + "retired": {rec(func(r *provision.Record) { r.Retired = true })}, |
| + "absent": {rec(func(r *provision.Record) { r.Host = "" })}, |
| + "a body naming another host": {rec(func(r *provision.Record) { r.Host = "b.docs.example.com" })}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + h := newHarness(t, opts...) |
| + h.want(h.send(h.request()), http.StatusForbidden, mailsubmit.CodeRouteNotOnBox) |
| + if h.ses.n() != 0 { |
| + t.Fatalf("SES called %d times", h.ses.n()) |
| + } |
| + }) |
| + } |
| + // The same record on its own box is served; a fleet record labelled for |
| + // this box too. |
| + h := newHarness(t) |
| + if got := h.send(h.request()); got.status != http.StatusOK || got.ans.MessageID == "" { |
| + t.Fatalf("a route on this box: %+v", got) |
| + } |
| + h = newHarness(t, scope(provision.BoxScope{Region: "fleet/pi", FleetBox: "pi-1"}), |
| + rec(func(r *provision.Record) { r.Region, r.FleetBox = "fleet/pi", "pi-1" })) |
| + if got := h.send(h.request()); got.status != http.StatusOK { |
| + t.Fatalf("a fleet route labelled for this box: %+v", got) |
| + } |
| +} |
| + |
| +// Test 8.5: the sender's policy refuses before SES. Each refusing case runs |
| +// on its own mailer and SES sees nothing; the cap boundary sees exactly |
| +// the three sends it admits. |
| +func TestMailerPolicyRefusesBeforeSES(t *testing.T) { |
| + sender := func(f func(map[string]any)) harnessOpt { |
| + return func(c *harnessCfg) { |
| + s := defaultSender() |
| + f(s) |
| + c.sender = s |
| + } |
| + } |
| + domain := func(f func(map[string]any)) harnessOpt { |
| + return func(c *harnessCfg) { |
| + d := defaultDomain() |
| + f(d) |
| + c.domain = d |
| + } |
| + } |
| + refusals := []struct { |
| + name string |
| + opts []harnessOpt |
| + req func(*mailsubmit.SendRequest) |
| + status int |
| + code string |
| + }{ |
| + {"a From domain not granted", nil, func(r *mailsubmit.SendRequest) { |
| + r.From, r.Raw = "hello@other.example.com", []byte(message("hello@other.example.com")) |
| + }, 403, mailsubmit.CodeFromNotAllowed}, |
| + {"a verified domain of the app's that the sender was not granted", []harnessOpt{func(c *harnessCfg) { |
| + c.extra = map[string]map[string]any{"other.example.com": { |
| + "domain": "other.example.com", "apps": []string{tApp}, |
| + "regions": map[string]any{tRegion: map[string]any{"identity_arn": "arn:aws:ses:eu-west-1:1:identity/other.example.com", "status": "verified"}}, |
| + }} |
| + }}, func(r *mailsubmit.SendRequest) { |
| + r.From, r.Raw = "hello@other.example.com", []byte(message("hello@other.example.com")) |
| + }, 403, mailsubmit.CodeFromNotAllowed}, |
| + {"a subdomain of a granted domain", nil, func(r *mailsubmit.SendRequest) { |
| + r.From, r.Raw = "a@x.docs.example.com", []byte(message("a@x.docs.example.com")) |
| + }, 403, mailsubmit.CodeFromNotAllowed}, |
| + {"granted, but pending in the mail region", []harnessOpt{domain(func(d map[string]any) { |
| + d["regions"] = map[string]any{tRegion: map[string]any{"identity_arn": "arn:x", "status": "pending"}} |
| + })}, nil, 403, mailsubmit.CodeFromNotAllowed}, |
| + {"granted, verified only in another region", []harnessOpt{domain(func(d map[string]any) { |
| + d["regions"] = map[string]any{"us-east-1": map[string]any{"identity_arn": "arn:x", "status": "verified"}} |
| + })}, nil, 403, mailsubmit.CodeFromNotAllowed}, |
| + {"verified, but with no identity", []harnessOpt{domain(func(d map[string]any) { |
| + d["regions"] = map[string]any{tRegion: map[string]any{"status": "verified"}} |
| + })}, nil, 403, mailsubmit.CodeFromNotAllowed}, |
| + {"the domain does not list the app", []harnessOpt{domain(func(d map[string]any) { d["apps"] = []string{"sheets"} })}, nil, 403, mailsubmit.CodeFromNotAllowed}, |
| + {"no domain record", []harnessOpt{func(c *harnessCfg) { c.domain = nil }}, nil, 403, mailsubmit.CodeFromNotAllowed}, |
| + {"no grant", []harnessOpt{sender(func(s map[string]any) { delete(s, "grant") })}, nil, 403, mailsubmit.CodeFromNotAllowed}, |
| + {"From: is not from", nil, func(r *mailsubmit.SendRequest) { r.Raw = []byte(message("other@docs.example.com")) }, 400, mailsubmit.CodeBadRequest}, |
| + {"two From: fields", nil, func(r *mailsubmit.SendRequest) { |
| + r.Raw = []byte("From: " + tFrom + "\r\nFROM: evil@other.example.com\r\n\r\nbody\r\n") |
| + }, 400, mailsubmit.CodeBadRequest}, |
| + {"a From: with two addresses", nil, func(r *mailsubmit.SendRequest) { |
| + r.Raw = []byte("From: " + tFrom + ", evil@other.example.com\r\n\r\nbody\r\n") |
| + }, 400, mailsubmit.CodeBadRequest}, |
| + {"no From:", nil, func(r *mailsubmit.SendRequest) { r.Raw = []byte("Subject: x\r\n\r\nbody\r\n") }, 400, mailsubmit.CodeBadRequest}, |
| + {"switched off", []harnessOpt{sender(func(s map[string]any) { s["submission"] = map[string]any{"on": false} })}, nil, 403, mailsubmit.CodeSubmissionOff}, |
| + {"never switched", []harnessOpt{sender(func(s map[string]any) { delete(s, "submission") })}, nil, 403, mailsubmit.CodeSubmissionOff}, |
| + {"no sender record", []harnessOpt{func(c *harnessCfg) { c.sender = nil }}, nil, 403, mailsubmit.CodeSubmissionOff}, |
| + } |
| + for _, c := range refusals { |
| + t.Run(c.name, func(t *testing.T) { |
| + h := newHarness(t, c.opts...) |
| + var muts []func(*mailsubmit.SendRequest) |
| + if c.req != nil { |
| + muts = append(muts, c.req) |
| + } |
| + h.want(h.send(h.request(muts...)), c.status, c.code) |
| + if h.ses.n() != 0 { |
| + t.Fatalf("SES called %d times", h.ses.n()) |
| + } |
| + }) |
| + } |
| + |
| + // Paused, each kind: 429 PAUSED, Retry-After to the next UTC midnight |
| + // for the kinds that lift at the day roll, an hour otherwise. |
| + now := time.Date(2026, 11, 13, 12, 0, 0, 0, time.UTC) |
| + midnight := strconv.Itoa(int(time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC).Sub(now).Seconds())) |
| + for kind, wantRA := range map[string]string{ |
| + mailwire.PauseKindCap: midnight, mailwire.PauseKindPlan: midnight, |
| + mailwire.PauseKindRate: "3600", "": "3600", mailwire.PauseKindPerInstance: "3600", |
| + } { |
| + t.Run("paused "+kind, func(t *testing.T) { |
| + h := newHarness(t, sender(func(s map[string]any) { s["pause"] = map[string]any{"kind": kind, "at": "2026-11-13T01:00:00Z"} })) |
| + got := h.send(h.request()) |
| + h.want(got, 429, mailsubmit.CodePaused) |
| + if got.retryAfter != wantRA || h.ses.n() != 0 { |
| + t.Fatalf("Retry-After %q (want %q), SES %d", got.retryAfter, wantRA, h.ses.n()) |
| + } |
| + }) |
| + } |
| + t.Run("paused, legacy record", func(t *testing.T) { |
| + h := newHarness(t, sender(func(s map[string]any) { |
| + s["provisioned"] = map[string]any{"active": false, "pause_kind": "rate", "at": "2026-11-13T01:00:00Z"} |
| + })) |
| + h.want(h.send(h.request()), 429, mailsubmit.CodePaused) |
| + }) |
| + |
| + // The cap boundary: cap 3, sends 1-3 accepted, the 4th refused. |
| + h := newHarness(t, sender(func(s map[string]any) { s["grant"] = map[string]any{"domains": []string{tDomain}, "daily_cap": 3} })) |
| + for i := 1; i <= 3; i++ { |
| + if got := h.send(h.request()); got.status != http.StatusOK { |
| + t.Fatalf("send %d under the cap: %+v", i, got) |
| + } |
| + h.now = h.now.Add(time.Second) // keep the rate bucket out of it |
| + } |
| + got := h.send(h.request()) |
| + h.want(got, 429, mailsubmit.CodeCapReached) |
| + if n, err := strconv.Atoi(got.retryAfter); err != nil || n <= 0 || n > 86400 { |
| + t.Fatalf("CAP_REACHED Retry-After %q", got.retryAfter) |
| + } |
| + if h.ses.n() != 3 { |
| + t.Fatalf("SES saw %d calls, want exactly 3", h.ses.n()) |
| + } |
| + // A grant with no cap is capped at the shared default. |
| + h = newHarness(t, sender(func(s map[string]any) { s["grant"] = map[string]any{"domains": []string{tDomain}} })) |
| + for i := 0; i < mailwire.DefaultDailyCap; i++ { |
| + if got := h.send(h.request()); got.status != http.StatusOK { |
| + t.Fatalf("send %d under the default cap: %+v", i, got) |
| + } |
| + h.now = h.now.Add(time.Second) |
| + } |
| + h.want(h.send(h.request()), 429, mailsubmit.CodeCapReached) |
| +} |
| + |
| +// The exact SendEmail input (design §5, The send). |
| +func TestSendInputShape(t *testing.T) { |
| + h := newHarness(t) |
| + raw := "From: Docs <" + tFrom + ">\r\nTo: Header <header@example.org>\r\nBcc: hidden@example.org\r\nX-SES-TENANT: other\r\nSubject: hi\r\n\r\nbody\r\n" |
| + req := h.request(func(r *mailsubmit.SendRequest) { |
| + r.Raw = []byte(raw) |
| + r.To = []string{"env1@example.org", "env2@example.org"} |
| + }) |
| + if got := h.send(req); got.status != 200 || got.ans.MessageID != "ses-1" { |
| + t.Fatalf("send: %+v", got) |
| + } |
| + in := h.ses.last() |
| + if aws.ToString(in.FromEmailAddress) != tFrom { |
| + t.Errorf("FromEmailAddress %q", aws.ToString(in.FromEmailAddress)) |
| + } |
| + if in.Destination == nil || strings.Join(in.Destination.ToAddresses, ",") != "env1@example.org,env2@example.org" || |
| + len(in.Destination.CcAddresses) != 0 || len(in.Destination.BccAddresses) != 0 { |
| + t.Errorf("Destination %+v, want the envelope", in.Destination) |
| + } |
| + want := "From: Docs <" + tFrom + ">\r\nTo: Header <header@example.org>\r\nSubject: hi\r\n\r\nbody\r\n" |
| + if in.Content == nil || in.Content.Raw == nil || string(in.Content.Raw.Data) != want || in.Content.Simple != nil { |
| + t.Errorf("Content %+v", in.Content) |
| + } |
| + if aws.ToString(in.ConfigurationSetName) != "carlos-"+tAcct { |
| + t.Errorf("ConfigurationSetName %q", aws.ToString(in.ConfigurationSetName)) |
| + } |
| + if in.TenantName != nil { |
| + t.Errorf("TenantName %q with no TenantARN", aws.ToString(in.TenantName)) |
| + } |
| + tags := map[string]string{} |
| + for _, tg := range in.EmailTags { |
| + tags[aws.ToString(tg.Name)] = aws.ToString(tg.Value) |
| + } |
| + if len(in.EmailTags) != 3 || tags["account"] != tAcct || tags["app"] != tApp || tags["sender"] != mailwire.SenderAppID { |
| + t.Errorf("EmailTags %v", tags) |
| + } |
| + if in.ListManagementOptions != nil || in.ReplyToAddresses != nil || in.FeedbackForwardingEmailAddress != nil { |
| + t.Errorf("unexpected fields: %+v", in) |
| + } |
| + |
| + // The sender tag is the app sender's id, whatever the body's id says. |
| + h = newHarness(t, func(c *harnessCfg) { c.sender["id"] = "someone-else" }) |
| + if got := h.send(h.request()); got.status != 200 { |
| + t.Fatalf("send: %+v", got) |
| + } |
| + for _, tg := range h.ses.last().EmailTags { |
| + if aws.ToString(tg.Name) == "sender" && aws.ToString(tg.Value) != mailwire.SenderAppID { |
| + t.Fatalf("sender tag %q from the body", aws.ToString(tg.Value)) |
| + } |
| + } |
| + |
| + // With a TenantARN, the account's tenant; with no config set, none. |
| + h = newHarness(t, func(c *harnessCfg) { |
| + c.sender["tenant_arn"] = "arn:aws:ses:eu-west-1:1:tenant/carlos-abcxyz/x" |
| + c.domain["regions"] = map[string]any{tRegion: map[string]any{"identity_arn": "arn:x", "status": "verified"}} |
| + }) |
| + if got := h.send(h.request()); got.status != 200 { |
| + t.Fatalf("send: %+v", got) |
| + } |
| + in = h.ses.last() |
| + if aws.ToString(in.TenantName) != mailwire.TenantName(tAcct) || in.ConfigurationSetName != nil { |
| + t.Errorf("TenantName %q ConfigurationSetName %v", aws.ToString(in.TenantName), in.ConfigurationSetName) |
| + } |
| +} |
| + |
| +// The rate (G9): 20 in a burst, then 429 RATE with Retry-After 1, and one |
| +// more half a second later. The refused send gave its cap slot back. |
| +func TestRateBucket(t *testing.T) { |
| + h := newHarness(t) |
| + for i := 0; i < Burst; i++ { |
| + if got := h.send(h.request()); got.status != 200 { |
| + t.Fatalf("burst send %d: %+v", i, got) |
| + } |
| + } |
| + got := h.send(h.request()) |
| + h.want(got, 429, mailsubmit.CodeRate) |
| + if got.retryAfter != "1" { |
| + t.Fatalf("RATE Retry-After %q, want 1", got.retryAfter) |
| + } |
| + if c := h.m.counter.Count(tAcct+"/"+tApp+"/app", Day(h.now)); c != Burst { |
| + t.Fatalf("counter %d after a refused take, want %d", c, Burst) |
| + } |
| + h.now = h.now.Add(500 * time.Millisecond) |
| + if got := h.send(h.request()); got.status != 200 { |
| + t.Fatalf("after 500 ms: %+v", got) |
| + } |
| + // The bucket itself. |
| + b := NewBuckets() |
| + at := time.Unix(1_700_000_000, 0) |
| + for i := 0; i < Burst; i++ { |
| + if ok, _ := b.Take("k", at); !ok { |
| + t.Fatalf("take %d refused", i) |
| + } |
| + } |
| + if ok, wait := b.Take("k", at); ok || wait != 500*time.Millisecond { |
| + t.Fatalf("over the burst: ok %v wait %v", ok, wait) |
| + } |
| + if ok, _ := b.Take("other", at); !ok { |
| + t.Fatal("buckets are per sender") |
| + } |
| +} |
| + |
| +// SES's answers map onto the verb's codes, and a send SES did not take |
| +// gives its cap slot back. |
| +func TestMailerSESErrorsMap(t *testing.T) { |
| + key := tAcct + "/" + tApp + "/app" |
| + for name, c := range map[string]struct { |
| + err error |
| + status int |
| + code string |
| + ra string |
| + }{ |
| + "rejected": {&sesv2types.MessageRejected{Message: aws.String("x")}, 400, mailsubmit.CodeRejected, ""}, |
| + "too many": {&sesv2types.TooManyRequestsException{Message: aws.String("x")}, 429, mailsubmit.CodeRate, "1"}, |
| + "throttling": {&smithy.GenericAPIError{Code: "ThrottlingException"}, 429, mailsubmit.CodeRate, "1"}, |
| + "sending paused": {&sesv2types.SendingPausedException{Message: aws.String("x")}, 503, mailsubmit.CodeMailerUnavailable, ""}, |
| + "suspended": {&sesv2types.AccountSuspendedException{Message: aws.String("x")}, 503, mailsubmit.CodeMailerUnavailable, ""}, |
| + "anything else": {errors.New("connection reset"), 503, mailsubmit.CodeMailerUnavailable, ""}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + h := newHarness(t) |
| + h.ses.err = c.err |
| + got := h.send(h.request()) |
| + h.want(got, c.status, c.code) |
| + if got.retryAfter != c.ra { |
| + t.Fatalf("Retry-After %q, want %q", got.retryAfter, c.ra) |
| + } |
| + if n := h.m.counter.Count(key, Day(h.now)); n != 0 { |
| + t.Fatalf("the slot was not released: %d", n) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Plan round 1 P2-4: a denied read is absent, and absent always refuses; |
| +// any other store error is 503. None reaches SES, and each denial is |
| +// logged as one. The wrapper covers provision.GetRecord's read too. |
| +func TestMailerReadsAccessDeniedAsAbsent(t *testing.T) { |
| + denied := &smithy.GenericAPIError{Code: "AccessDenied", Message: "Access Denied"} |
| + for name, c := range map[string]struct { |
| + prefix string |
| + err error |
| + status int |
| + code string |
| + }{ |
| + "sender denied": {"apps/" + tAcct + "/" + tApp + "/email/senders/", denied, 403, mailsubmit.CodeSubmissionOff}, |
| + "instance record denied": {"apps/" + tAcct + "/" + tApp + "/instances/", denied, 403, mailsubmit.CodeRouteNotOnBox}, |
| + "domain denied": {"accounts/" + tAcct + "/email/domains/", denied, 403, mailsubmit.CodeFromNotAllowed}, |
| + "sender store down": {"apps/" + tAcct + "/" + tApp + "/email/senders/", errors.New("i/o timeout"), 503, mailsubmit.CodeMailerUnavailable}, |
| + "record store down": {"apps/" + tAcct + "/" + tApp + "/instances/", errors.New("i/o timeout"), 503, mailsubmit.CodeMailerUnavailable}, |
| + "domain store down": {"accounts/" + tAcct + "/email/domains/", errors.New("i/o timeout"), 503, mailsubmit.CodeMailerUnavailable}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + h := newHarness(t, func(cfg *harnessCfg) { |
| + cfg.store = func(s release.Store) release.Store { return &failingStore{Store: s, prefix: c.prefix, err: c.err} } |
| + }) |
| + h.want(h.send(h.request()), c.status, c.code) |
| + if h.ses.n() != 0 { |
| + t.Fatalf("SES called %d times", h.ses.n()) |
| + } |
| + if c.err == denied && !h.logs.has("denied, taken as absent") { |
| + t.Fatalf("the denial was not logged: %v", h.logs.lines) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// failingStore answers err for every key under prefix. |
| +type failingStore struct { |
| + release.Store |
| + prefix string |
| + err error |
| +} |
| + |
| +func (f *failingStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if strings.HasPrefix(key, f.prefix) { |
| + return nil, "", f.err |
| + } |
| + return f.Store.Get(ctx, key) |
| +} |
| + |
| +// At most four sends in flight; the fifth is 503 at once. |
| +func TestMailerConcurrencyLimit(t *testing.T) { |
| + h := newHarness(t) |
| + h.ses.block = make(chan struct{}) |
| + var wg sync.WaitGroup |
| + for i := 0; i < maxInFlight; i++ { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); h.send(h.request()) }() |
| + } |
| + deadline := time.Now().Add(5 * time.Second) |
| + for h.ses.n() < maxInFlight && time.Now().Before(deadline) { |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + if h.ses.n() != maxInFlight { |
| + t.Fatalf("%d sends in flight, want %d", h.ses.n(), maxInFlight) |
| + } |
| + h.want(h.send(h.request()), 503, mailsubmit.CodeMailerUnavailable) |
| + close(h.ses.block) |
| + wg.Wait() |
| +} |
| + |
| +// A rotation reloads the key file and rebuilds both clients over the |
| +// newest key with no restart; a key file that stops loading (disarmed) |
| +// refuses every send and fails health until it loads again. |
| +func TestMailerFollowsTheKeyFile(t *testing.T) { |
| + h := newHarness(t) |
| + if got := h.send(h.request()); got.status != 200 { |
| + t.Fatalf("send: %+v", got) |
| + } |
| + writeKeys(t, h.keyPath, "AKIDOLD secret-old 2026-11-01T00:00:00Z\nAKIDNEW secret-new 2026-11-13T00:00:00Z\n") |
| + future := time.Now().Add(time.Minute) |
| + _ = osChtimes(h.keyPath, future) |
| + if got := h.send(h.request()); got.status != 200 { |
| + t.Fatalf("send after rotation: %+v", got) |
| + } |
| + if len(h.builds) != 2 || h.builds[1].ID != "AKIDNEW" { |
| + t.Fatalf("client builds %v, want a rebuild over AKIDNEW", h.builds) |
| + } |
| + removeFile(t, h.keyPath) |
| + h.want(h.send(h.request()), 503, mailsubmit.CodeMailerUnavailable) |
| + if h.m.Healthy() == nil { |
| + t.Fatal("healthy with no key file") |
| + } |
| + writeKeys(t, h.keyPath, "AKIDNEW secret-new 2026-11-13T00:00:00Z\n") |
| + if got := h.send(h.request()); got.status != 200 || h.m.Healthy() != nil { |
| + t.Fatalf("after re-arming: %+v %v", got, h.m.Healthy()) |
| + } |
| +} |
| + |
| +// A malformed stamped request is 400 and reaches nothing. |
| +func TestMailerRefusesMalformedRequests(t *testing.T) { |
| + h := newHarness(t) |
| + for name, mut := range map[string]func(*mailsubmit.SendRequest){ |
| + "bad account": func(r *mailsubmit.SendRequest) { r.Account = "../x" }, |
| + "bad app": func(r *mailsubmit.SendRequest) { r.App = "Docs!" }, |
| + "host traversal": func(r *mailsubmit.SendRequest) { r.Host = "../../x" }, |
| + "host with slash": func(r *mailsubmit.SendRequest) { r.Host = "a/b" }, |
| + "no recipients": func(r *mailsubmit.SendRequest) { r.To = nil }, |
| + "51 recipients": func(r *mailsubmit.SendRequest) { r.To = make([]string, 51) }, |
| + "a bad recipient": func(r *mailsubmit.SendRequest) { r.To = []string{"x@example.org\r\nBcc: y@example.org"} }, |
| + "named recipient": func(r *mailsubmit.SendRequest) { r.To = []string{"X <x@example.org>"} }, |
| + "no from": func(r *mailsubmit.SendRequest) { r.From = "" }, |
| + "no raw": func(r *mailsubmit.SendRequest) { r.Raw = nil }, |
| + "no separator": func(r *mailsubmit.SendRequest) { r.Raw = []byte("From: " + tFrom + "\r\nSubject: x") }, |
| + } { |
| + got := h.send(h.request(mut)) |
| + if got.status != 400 || got.ans.Code != mailsubmit.CodeBadRequest { |
| + t.Errorf("%s: %+v", name, got) |
| + } |
| + } |
| + if h.ses.n() != 0 { |
| + t.Fatalf("SES called %d times", h.ses.n()) |
| + } |
| +} |
diff --git a/internal/mailer/server.go b/internal/mailer/server.go| index e74d56556..31a8b2cd6 100644 |
| --- a/internal/mailer/server.go |
| +++ b/internal/mailer/server.go |
| @@ -32,7 +32,7 @@ type Config struct { |
| // passes instancectl.EdgeMainPIDPeer(): uid carlos AND the MainPID of |
| // carlos-edge.service. Nil refuses every connection. |
| PeerOK func(net.Conn) error |
| - // Handler serves admitted connections. Nil serves NewHandler(nil). |
| + // Handler serves admitted connections. Nil serves NewHandler(nil, nil). |
| Handler http.Handler |
| // Logf is the journal; nil discards. |
| Logf func(string, ...any) |
| @@ -50,7 +50,7 @@ func Serve(ctx context.Context, cfg Config) error { |
| } |
| h := cfg.Handler |
| if h == nil { |
| - h = NewHandler(nil) |
| + h = NewHandler(nil, nil) |
| } |
| vetted := &vettedListener{Listener: cfg.Listener, ok: cfg.PeerOK, logf: logf, now: time.Now} |
| srv := &http.Server{ |
| @@ -77,11 +77,19 @@ func Serve(ctx context.Context, cfg Config) error { |
| } |
| // NewHandler is the mailer's routes: GET /v1/health, and POST /v1/send |
| -// when send is not nil. |
| -func NewHandler(send http.Handler) http.Handler { |
| +// when send is not nil. healthy, when set, decides the health answer: 503 |
| +// while it returns an error, which the box reports as not armed. |
| +func NewHandler(send http.Handler, healthy func() error) http.Handler { |
| mux := http.NewServeMux() |
| mux.HandleFunc("GET /v1/health", func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Content-Type", "application/json") |
| + if healthy != nil { |
| + if err := healthy(); err != nil { |
| + w.WriteHeader(http.StatusServiceUnavailable) |
| + _ = json.NewEncoder(w).Encode(map[string]bool{"ok": false}) |
| + return |
| + } |
| + } |
| _ = json.NewEncoder(w).Encode(map[string]bool{"ok": true}) |
| }) |
| if send != nil { |
diff --git a/internal/mailer/server_test.go b/internal/mailer/server_test.go| index 6cc4ec01f..baa407ec1 100644 |
| --- a/internal/mailer/server_test.go |
| +++ b/internal/mailer/server_test.go |
| @@ -63,7 +63,7 @@ func sockClient(sock string) *http.Client { |
| // countingHandler is NewHandler(nil) that counts the requests it saw. |
| func countingHandler(n *atomic.Int32) http.Handler { |
| - inner := NewHandler(nil) |
| + inner := NewHandler(nil, nil) |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| n.Add(1) |
| inner.ServeHTTP(w, r) |
diff --git a/internal/mailer/ses.go b/internal/mailer/ses.go| new file mode 100644 |
| index 000000000..a046f7731 |
| --- /dev/null |
| +++ b/internal/mailer/ses.go |
| @@ -0,0 +1,104 @@ |
| +package mailer |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "strings" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| + "github.com/aws/aws-sdk-go-v2/service/sesv2" |
| + sesv2types "github.com/aws/aws-sdk-go-v2/service/sesv2/types" |
| + "github.com/aws/smithy-go" |
| + |
| + "github.com/carlosframework/platform/internal/mailsubmit" |
| + "github.com/carlosframework/platform/internal/mailwire" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/rootaws" |
| +) |
| + |
| +// SES is the one SES v2 call the mailer makes (design §5, The send; §9.0: |
| +// its IAM action is ses:SendRawEmail). |
| +type SES interface { |
| + SendEmail(ctx context.Context, in *sesv2.SendEmailInput, opts ...func(*sesv2.Options)) (*sesv2.SendEmailOutput, error) |
| +} |
| + |
| +// awsConfigs builds the mailer's two AWS configs from one key: SES in the |
| +// mail region, S3 in the deployment bucket's region. Both come from |
| +// rootaws.LoadStaticConfig, which refuses AWS_PROFILE, empties the shared |
| +// config files and disables IMDS; the mailer never uses the default chain. |
| +func awsConfigs(ctx context.Context, k Key, mailRegion, deployRegion string) (sesCfg, s3Cfg aws.Config, err error) { |
| + sesCfg, err = rootaws.LoadStaticConfig(ctx, k.ID, k.Secret, awsconfig.WithRegion(mailRegion)) |
| + if err != nil { |
| + return aws.Config{}, aws.Config{}, err |
| + } |
| + s3Cfg, err = rootaws.LoadStaticConfig(ctx, k.ID, k.Secret, awsconfig.WithRegion(deployRegion)) |
| + if err != nil { |
| + return aws.Config{}, aws.Config{}, err |
| + } |
| + return sesCfg, s3Cfg, nil |
| +} |
| + |
| +// AWSClients is the production client builder: an SES v2 client in the |
| +// mail region and the deployment bucket's store in its region, both over |
| +// the key it is given. |
| +func AWSClients(mailRegion, deployRegion, bucket string) func(context.Context, Key) (SES, release.Store, error) { |
| + return func(ctx context.Context, k Key) (SES, release.Store, error) { |
| + sesCfg, s3Cfg, err := awsConfigs(ctx, k, mailRegion, deployRegion) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + return sesv2.NewFromConfig(sesCfg), release.NewS3StoreFromConfig(s3Cfg, bucket), nil |
| + } |
| +} |
| + |
| +// sendInput is the SendEmail call for an admitted, stripped message: the |
| +// raw content, the envelope as an explicit Destination (never the |
| +// headers), the domain's configuration set when it has one, the account's |
| +// tenant only when the sender has one, and the three attribution tags the |
| +// console believes from the mailer alone (decision 6). |
| +func sendInput(req mailsubmit.SendRequest, d decision, stripped []byte) *sesv2.SendEmailInput { |
| + in := &sesv2.SendEmailInput{ |
| + FromEmailAddress: aws.String(d.from), |
| + Destination: &sesv2types.Destination{ToAddresses: append([]string(nil), req.To...)}, |
| + Content: &sesv2types.EmailContent{Raw: &sesv2types.RawMessage{Data: stripped}}, |
| + EmailTags: []sesv2types.MessageTag{ |
| + {Name: aws.String(mailwire.TagAccount), Value: aws.String(req.Account)}, |
| + {Name: aws.String(mailwire.TagApp), Value: aws.String(req.App)}, |
| + {Name: aws.String(mailwire.TagSender), Value: aws.String(mailwire.SenderAppID)}, |
| + }, |
| + } |
| + if d.configSet != "" { |
| + in.ConfigurationSetName = aws.String(d.configSet) |
| + } |
| + if d.sender.TenantARN != "" { |
| + in.TenantName = aws.String(mailwire.TenantName(req.Account)) |
| + } |
| + return in |
| +} |
| + |
| +// sesRefusal maps an SES error to the verb's answer: a rejected message is |
| +// 400 REJECTED; throttling is 429 RATE, Retry-After 1; everything else, |
| +// sending paused and a suspended account among them, is 503 |
| +// MAILER_UNAVAILABLE. |
| +func sesRefusal(err error) (status int, code, retryAfter string) { |
| + var rejected *sesv2types.MessageRejected |
| + if errors.As(err, &rejected) { |
| + return http.StatusBadRequest, mailsubmit.CodeRejected, "" |
| + } |
| + var tooMany *sesv2types.TooManyRequestsException |
| + if errors.As(err, &tooMany) { |
| + return http.StatusTooManyRequests, mailsubmit.CodeRate, "1" |
| + } |
| + var apiErr smithy.APIError |
| + if errors.As(err, &apiErr) { |
| + switch c := apiErr.ErrorCode(); { |
| + case c == "MessageRejected": |
| + return http.StatusBadRequest, mailsubmit.CodeRejected, "" |
| + case strings.Contains(c, "TooManyRequests"), strings.Contains(c, "Throttl"): |
| + return http.StatusTooManyRequests, mailsubmit.CodeRate, "1" |
| + } |
| + } |
| + return http.StatusServiceUnavailable, mailsubmit.CodeMailerUnavailable, "" |
| +} |
diff --git a/internal/mailer/ses_test.go b/internal/mailer/ses_test.go| new file mode 100644 |
| index 000000000..ec1cdf1a9 |
| --- /dev/null |
| +++ b/internal/mailer/ses_test.go |
| @@ -0,0 +1,63 @@ |
| +package mailer |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "sync/atomic" |
| + "testing" |
| +) |
| + |
| +// The mailer never uses IMDS (design §5, decision 2; plan round 1 P2-3): |
| +// its configs come from its static key with the two named regions, and |
| +// building them, building the clients and retrieving credentials touch no |
| +// metadata endpoint, even one the environment points at and leaves on. |
| +func TestMailerNeverUsesIMDS(t *testing.T) { |
| + var hits atomic.Int32 |
| + imds := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + hits.Add(1) |
| + http.Error(w, "no", http.StatusNotFound) |
| + })) |
| + defer imds.Close() |
| + t.Setenv("AWS_EC2_METADATA_SERVICE_ENDPOINT", imds.URL) |
| + t.Setenv("AWS_EC2_METADATA_DISABLED", "false") |
| + t.Setenv("AWS_REGION", "ap-south-1") |
| + t.Setenv("AWS_DEFAULT_REGION", "ap-south-1") |
| + t.Setenv("AWS_ACCESS_KEY_ID", "AKIDFROMENV") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "envsecret") |
| + ctx := context.Background() |
| + k := Key{ID: "AKIDMAILER", Secret: "mailersecret"} |
| + |
| + sesCfg, s3Cfg, err := awsConfigs(ctx, k, "eu-west-1", "us-east-1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if sesCfg.Region != "eu-west-1" || s3Cfg.Region != "us-east-1" { |
| + t.Fatalf("regions %q and %q, want eu-west-1 and us-east-1", sesCfg.Region, s3Cfg.Region) |
| + } |
| + for _, cfg := range []struct { |
| + name string |
| + get func() (string, error) |
| + }{ |
| + {"ses", func() (string, error) { c, err := sesCfg.Credentials.Retrieve(ctx); return c.AccessKeyID, err }}, |
| + {"s3", func() (string, error) { c, err := s3Cfg.Credentials.Retrieve(ctx); return c.AccessKeyID, err }}, |
| + } { |
| + id, err := cfg.get() |
| + if err != nil || id != "AKIDMAILER" { |
| + t.Fatalf("%s credentials: %q %v, want the mailer's static key, never the environment's", cfg.name, id, err) |
| + } |
| + } |
| + ses, store, err := AWSClients("eu-west-1", "us-east-1", "bucket")(ctx, k) |
| + if err != nil || ses == nil || store == nil { |
| + t.Fatalf("AWSClients: %v", err) |
| + } |
| + if hits.Load() != 0 { |
| + t.Fatalf("the metadata endpoint was called %d times", hits.Load()) |
| + } |
| + |
| + // A profile in the environment is refused, not followed. |
| + t.Setenv("AWS_PROFILE", "someone") |
| + if _, _, err := AWSClients("eu-west-1", "us-east-1", "bucket")(ctx, k); err == nil { |
| + t.Fatal("AWS_PROFILE was followed") |
| + } |
| +} |
diff --git a/internal/mailer/store.go b/internal/mailer/store.go| new file mode 100644 |
| index 000000000..f2aada785 |
| --- /dev/null |
| +++ b/internal/mailer/store.go |
| @@ -0,0 +1,80 @@ |
| +package mailer |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "os" |
| + "path" |
| + "sync" |
| + "time" |
| + |
| + "github.com/aws/smithy-go" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// absentOnDeniedStore is the mailer's one store (plan Task 5, round 1 P2-4, |
| +// round 2 P3). The mailer's IAM user has s3:GetObject on three key |
| +// patterns and no s3:ListBucket, so S3 answers a missing key with 403 |
| +// AccessDenied, not 404. This wrapper reads that denial as absent |
| +// (os.ErrNotExist), and passes every other answer through. It wraps the |
| +// store itself, not one read, so provision.GetRecord's read of an instance |
| +// record is covered as well as the mailer's own sender and domain reads. |
| +// |
| +// Absent always refuses (SUBMISSION_OFF, ROUTE_NOT_ON_BOX or |
| +// FROM_NOT_ALLOWED), so the mapping cannot admit anything. A denial is |
| +// logged as one, at most once a minute per key prefix, so a broken policy |
| +// is visible rather than mistaken for a real absence. |
| +type absentOnDeniedStore struct { |
| + release.Store |
| + logf func(string, ...any) |
| + now func() time.Time |
| + |
| + mu sync.Mutex |
| + logged map[string]time.Time |
| +} |
| + |
| +func newAbsentOnDeniedStore(s release.Store, logf func(string, ...any)) *absentOnDeniedStore { |
| + if logf == nil { |
| + logf = func(string, ...any) {} |
| + } |
| + return &absentOnDeniedStore{Store: s, logf: logf, now: time.Now, logged: map[string]time.Time{}} |
| +} |
| + |
| +func (s *absentOnDeniedStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + body, etag, err := s.Store.Get(ctx, key) |
| + if err != nil && accessDenied(err) { |
| + s.noteDenied(key, err) |
| + return nil, "", fmt.Errorf("mailer: %s: access denied, read as absent: %w", key, os.ErrNotExist) |
| + } |
| + return body, etag, err |
| +} |
| + |
| +// accessDenied is S3's answer to a GET the caller may not make, or to a |
| +// missing key the caller may not list: the AccessDenied code, or a bare |
| +// 403 from an S3-compatible store. |
| +func accessDenied(err error) bool { |
| + var apiErr smithy.APIError |
| + if errors.As(err, &apiErr) && apiErr.ErrorCode() == "AccessDenied" { |
| + return true |
| + } |
| + var httpErr interface{ HTTPStatusCode() int } |
| + return errors.As(err, &httpErr) && httpErr.HTTPStatusCode() == http.StatusForbidden |
| +} |
| + |
| +func (s *absentOnDeniedStore) noteDenied(key string, err error) { |
| + prefix := path.Dir(key) |
| + now := s.now() |
| + s.mu.Lock() |
| + last, seen := s.logged[prefix] |
| + report := !seen || now.Sub(last) >= time.Minute |
| + if report { |
| + s.logged[prefix] = now |
| + } |
| + s.mu.Unlock() |
| + if report { |
| + s.logf("mailer: read of %s denied, taken as absent (a missing object answers 403 without s3:ListBucket; if this object exists, the mailer's policy is wrong): %v", key, err) |
| + } |
| +} |
diff --git a/internal/mailwire/mailwire.go b/internal/mailwire/mailwire.go| index 682577a5b..869e2e94c 100644 |
| --- a/internal/mailwire/mailwire.go |
| +++ b/internal/mailwire/mailwire.go |
| @@ -110,6 +110,11 @@ func (v *SenderView) EffectivePause() *Pause { |
| return nil |
| } |
| +// SenderAppID is the app sender's id, internal/mail's SenderAppID (a test |
| +// pins them equal). Every instance of a switched app sends as it (design |
| +// decision 5), and its record carries the app's submission switch. |
| +const SenderAppID = "app" |
| + |
| // SenderKey is the bucket key of one sender. It is the same string as |
| // internal/mail's SenderKey, which a test pins. |
| func SenderKey(acct, app, id string) string { |
| @@ -122,6 +127,37 @@ func DomainKey(acct, domain string) string { |
| return "accounts/" + acct + "/email/domains/" + domain + ".json" |
| } |
| +// DefaultDailyCap is a sender's daily cap when its grant names none (a |
| +// zero DailyCap): the console's TierCap("") and the mailer's cap read this |
| +// one constant, so the two cannot disagree. |
| +const DefaultDailyCap = 50 |
| + |
| +// TenantName is the SES tenant of an account, the same string as |
| +// internal/mail's TenantName, which a test pins. |
| +func TenantName(acct string) string { return "carlos-" + acct } |
| + |
| +// DomainRegionView is the part of one region's identity state the mailer |
| +// reads. |
| +type DomainRegionView struct { |
| + IdentityARN string `json:"identity_arn"` |
| + ConfigSet string `json:"config_set"` |
| + Status string `json:"status"` |
| +} |
| + |
| +// DomainView is accounts/<acct>/email/domains/<domain>.json as the mailer |
| +// reads it: the domain, the apps that may send from it, and each region's |
| +// identity state, under internal/mail's JSON names. Every other field is |
| +// ignored on decode. |
| +type DomainView struct { |
| + Domain string `json:"domain"` |
| + Apps []string `json:"apps"` |
| + Regions map[string]*DomainRegionView `json:"regions"` |
| +} |
| + |
| +// DomainStatusVerified is a region's identity status once SES has verified |
| +// it: the only status the mailer sends from. |
| +const DomainStatusVerified = "verified" |
| + |
| // MailerSocket is the box-local mailer's socket (carlos-mailer.socket). The |
| // agent dials it to forward a stamped message, and to report whether the |
| // box's mailer is armed. Its directory is root's and hidden from every |
diff --git a/internal/provision/boxserves_test.go b/internal/provision/boxserves_test.go| new file mode 100644 |
| index 000000000..f308b5082 |
| --- /dev/null |
| +++ b/internal/provision/boxserves_test.go |
| @@ -0,0 +1,79 @@ |
| +package provision |
| + |
| +import ( |
| + "testing" |
| +) |
| + |
| +// BoxServesRecord is the mailer's "on this box" (platform mail submission |
| +// design, decision 4). It must agree, record for record, with what a real |
| +// reconcile pass on that box mints: one store of records across regions, |
| +// pools, fleet labels and serving classes, one pass per box scope, and the |
| +// minted set compared with BoxServesRecord's answer for every record. |
| +func TestBoxServesRecordMatchesReconciler(t *testing.T) { |
| + s, sqid := shopSetup(t) |
| + recs := []Record{ |
| + fleetRecord(sqid, "fa.shop.example.com", ""), |
| + fleetRecord(sqid, "fb.shop.example.com", "pi-1"), |
| + fleetRecord(sqid, "fc.shop.example.com", "pi-2"), |
| + } |
| + ie := shopRecord(sqid) |
| + ie.Host, ie.Slug = "ie.shop.example.com", "ie" |
| + us := shopRecord(sqid) |
| + us.Host, us.Slug, us.Region = "us.shop.example.com", "us", "us" |
| + pooled := shopRecord(sqid) |
| + pooled.Host, pooled.Slug, pooled.Pool = "pool.shop.example.com", "pool", "tito" |
| + static := shopRecord(sqid) |
| + static.Host, static.Slug, static.Kind = "static.shop.example.com", "static", "static" |
| + labelled := shopRecord(sqid) |
| + labelled.Host, labelled.Slug, labelled.FleetBox = "stale.shop.example.com", "stale", "pi-2" |
| + recs = append(recs, ie, us, pooled, static, labelled) |
| + for _, rec := range recs { |
| + if err := CreateRecord(ctx, s, rec); err != nil { |
| + t.Fatalf("%s: %v", rec.Host, err) |
| + } |
| + } |
| + scopes := []BoxScope{ |
| + {Region: "ie"}, |
| + {Region: "us"}, |
| + {Region: "ie", Pools: []string{"tito"}}, |
| + {Region: "ie", Pools: []string{"", "tito"}}, |
| + {Region: "eu"}, |
| + {Region: "fleet/pi", FleetBox: "pi-1"}, |
| + {Region: "fleet/pi", FleetBox: "pi-2"}, |
| + {Region: "fleet/pi"}, |
| + {Region: "ie", FleetBox: "pi-1"}, |
| + } |
| + sawTrue, sawFalse := false, false |
| + for _, scope := range scopes { |
| + reg := regWith(t) |
| + if err := Reconcile(ctx, s, reg, ReconcileConfig{Region: scope.Region, Pools: scope.Pools, FleetBox: scope.FleetBox, DataDir: "/data"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, rec := range recs { |
| + got, err := GetRecord(ctx, s, rec.Account, rec.App, rec.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rt, err := reg.Get(rec.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + minted := rt != nil |
| + if serves := BoxServesRecord(scope, *got); serves != minted { |
| + t.Errorf("scope %+v, record %s (region %q pool %q label %q kind %q): BoxServesRecord %v, the reconciler minted %v", |
| + scope, rec.Host, got.Region, got.Pool, got.FleetBox, got.Kind, serves, minted) |
| + } |
| + sawTrue = sawTrue || minted |
| + sawFalse = sawFalse || !minted |
| + } |
| + } |
| + if !sawTrue || !sawFalse { |
| + t.Fatalf("the table never exercised both answers (minted %v, refused %v)", sawTrue, sawFalse) |
| + } |
| + // A retired record is no box's, even one whose scope matches. |
| + gone := ie |
| + gone.Retired = true |
| + if BoxServesRecord(BoxScope{Region: "ie"}, gone) { |
| + t.Fatal("a retired record is served") |
| + } |
| +} |
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go| index 72e988df7..023771b64 100644 |
| --- a/internal/provision/reconcile.go |
| +++ b/internal/provision/reconcile.go |
| @@ -556,6 +556,26 @@ func (cfg ReconcileConfig) ownsRecord(rec Record) bool { |
| return rec.FleetBox == "" || rec.FleetBox == cfg.FleetBox |
| } |
| +// BoxScope is the part of a box's ReconcileConfig that decides which |
| +// instance records are its own: its region, its pools and, on a fleet, its |
| +// label. |
| +type BoxScope struct { |
| + Region string |
| + Pools []string |
| + FleetBox string |
| +} |
| + |
| +// BoxServesRecord reports whether rec is a route of the box b describes, |
| +// by the reconciler's own predicates (inScope, everywhereClass, ownsRecord), |
| +// unchanged: so "on this box" means what a reconcile pass means by it. A |
| +// retired record is no box's. The box-local mailer asks it before it sends |
| +// for a route (platform mail submission design, decision 4): exact where a |
| +// fleet record names a box, region and pool otherwise. |
| +func BoxServesRecord(b BoxScope, rec Record) bool { |
| + cfg := ReconcileConfig{Region: b.Region, Pools: b.Pools, FleetBox: b.FleetBox} |
| + return cfg.inScope(rec.Region, rec.Pool, everywhereClass(rec)) && cfg.ownsRecord(rec) && !rec.Retired |
| +} |
| + |
| // RouteFor is the one answer to "what route does this record describe". The |
| // mint path builds from it and the adoption match test (design §4.2) |
| // compares against it — one function, so a shape the reconciler would mint |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 17deae282..d06086905 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -203,4 +203,4 @@ plan14-root-reads-edge-ppv2.tsv 44e5745a1d22ea2ddd6e73d775d87759afe7121666212b6e |
| plan14-root-reads-static-site-geo-962.tsv 5e8a72175700a3e60c1e283b133c1ee25e36f292e2e319f02a19138f15186376 |
| plan14-root-reads-member-backups-drill-nodb.tsv 07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063 |
| plan14-root-reads-spread-every-schedule-ticks.tsv 07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063 |
| -plan14-root-reads-platform-mail-submission.tsv 615b17f291546a3de0c068258e6b76e72fe06b14f809df308fa6ed018c00e5fd |
| +plan14-root-reads-platform-mail-submission.tsv e8d4820f40e9b6459ddcba3f3efb9926b742ccd5cce8b33fa713551152265d51 |
diff --git a/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv b/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv| index 8588a4278..fa691f423 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv |
| @@ -1,7 +1,8 @@ |
| # Census overlay platform-mail-submission, written by census-propose (#369). census-ruling-platform-mail-submission, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-platform-mail-submission.md. |
| -# 18 body, 3 sites, 11 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| -# 8 new dispositions: 0 reads re-frozen at their disposition with the claim, 8 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +# 19 body, 3 sites, 14 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 13 new dispositions: 0 reads re-frozen at their disposition with the claim, 13 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| @legacy 2d0d5c7d06f3d3299a7b17609928866ebb192d07468a1876e0ad9df56571ace8 internal/host/agent.go fastTick legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=observes the change index before any pass (observeIndex), runs the backstop's requested full pass and a scoped pass for moved app scopes (indexTick), and arms the canary pointer gate on the sweep (canaryPointerGate) only on a tick whose own index observation succeeded; read site unchanged, offset moved;rev3=census-ruling-stateless-replicas-1;basis=Call coordinator Tick on the existing tick before convergence; client renews held terms only at the pinned interval. Existing registry read unchanged. Final review I3: signal the owned renewal worker instead of waiting for its sequential console HTTP calls. Existing convergence and record read unchanged.;rev3=census-ruling-region-ha-p3a;basis=Run the optional desired-role reader on the existing tick after observing the armed change index; no new root path or timer, nil reader is unchanged.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: signals the owned replica worker on the existing tick; coalesced asynchronous execution, no timer or bucket scan added. merge of origin/main 7920cccf: Retain main box-role reader pass on the existing tick alongside the replica worker signal; merge-only body change, unchanged read sites.;rev3=census-ruling-restart-new-box-gap;basis=calls the optional restartGain hook (restartGainSeed) once per existing tick before the serial read; no new root path, timer or read kind; nil hook is unchanged;rev3=census-ruling-agent-start-demo-3;basis=Refresh moved notices through the shared watch before normal convergence; no new per-box poll. Census read-site delta: unchanged (1).;rev3=census-ruling-stateless-replicas-4-task1;basis=Signals the owned replica swap worker (armedReplicaDeploy.tick) beside the placement worker on the existing tick; coalesced background pass, no timer, no bucket read. Its transitions go through the console's authenticated /deploy.;rev3=census-ruling-platform-mail-submission;basis=Task 4: on a serial move, after the schedule leg, starts the armed mail switch cache's Refresh on its own goroutine (each read bounded at 2 s, overlapping refreshes skipped). It re-reads the app sender records already cached, through the agent's deploy store. Agent, not root; the tick waits on nothing new. registry:Host@5822 a1cd273f24047c63670f8c32c000a84f1a3861d058da38c5318551929f312390 |
| +@legacy 562d26b51dcbce93d68fabfe933e074c2b2933fcded74156fd88f559407862da internal/host/agent.go provisionTickConfig legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ha-p1a-433;basis=the agent (carlos-edge.service, user carlos) and the edges file loop's eligibility: the same CARLOS_POOLS read, now parsed by provision.ParseBoxPools (internal/provision, envelope re-pinned), the one parser boxPools also uses. "@shared" (provision.SharedPoolToken, never a valid pool name) is the shared "" pool; other tokens are literal as before; empty elements and repeats dropped. No read added.;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 4, rule 2): sets ReconcileConfig.FleetBox to the box's own fleet label from resolveFleetIdentity(getenv), only when the identity resolves and region == PlacementTarget(identity.Fleet); otherwise it stays "" (the box admits only unlabelled records). The same environment the fleet loops already read; read sites unchanged (2). Agent config, not root.;rev3=census-ruling-platform-mail-submission;basis=Task 5: its region, pools and fleet label now come from BoxScopeFromEnv, which is the same three reads moved out unchanged (CARLOS_REGION trimmed, provision.ParseBoxPools(CARLOS_POOLS), and resolveFleetIdentity's label only when its fleet is the one the region places the box on), so the box-local mailer resolves "on this box" by the agent's rule. The ReconcileConfig it returns is field for field what it was. Agent, not root. data-literal@173,data-literal@214 cabe3cb9662118eb82ddbc77dbbdb80b6718494caea097c8ffb894ccc4903fe3 |
| @legacy 589908d713736c8e6a9e3ff35f04288a44aa15643b899bdd3ec8e0b97d43d808 internal/host/agent.go statusLoop legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the status tick's context carries the box's lifetime judge; read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 953b9fda (its later changes, regional box names and self-serve moves plan 1 among them, under main's own census rulings), where the tick fills rootfs_ready and rootfs_blocked from armedRootfs.Load().probe, which each tick runs NestedOK's checks and asks the control socket's GET /ready/rootfs (never the store); the same four direct sites;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 11 and #329 plan 3 Task 7: takes root's GET /egress reader and fills p.Egress = egressStatusProbe(egressStatus, routes, provision.PolicyReadStates()) and p.SizeCommittedMiB = sizeCommittedMiB(armedSizeSource.Load(), routes); the two added whole:Route sites are the tick's own registry list handed to those two units (decision rows), which read root's control socket and the activator's memory; no store request added; the four existing sites unchanged, offsets moved.;rev3=census-ruling-fleet-alerts-1;basis=the agent (carlos-edge.service, user carlos): the status tick passes os.Geteuid() to alertDeliveryProbe, which fills AlertDelivery.EngineBeat/EngineBeatWhy from engineBeatArmed (the env value and the euid only, no file access, root refused before the path is looked at), and fills Probes.DiskFullETAHours from diskETAProbe(&processDiskTrend, now), a Theil-Sen fit over the metrics loop's in-memory ring of disk readings; the same six sites, no read added, no store request added;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the status tick's Probes gain HeldStreams: heldStreamsState(), which calls the edge's in-memory counters function (nil until the edge is ready). No file, bucket or registry access added.;rev3=census-ruling-stateless-replicas-3;basis=Fix round 1 Q20: read the detached in-memory replica snapshot source into Probes.ReplicaCopies on the existing five-minute tick. Existing six direct read sites unchanged. No additional bucket request, changed cadence or app lifecycle action.;rev3=census-ruling-agent-start-demo-3;basis=Report moved capability only when the serving edge reports readiness; report claim-seed support only with CARLOS_DEMO_CLAIM=1. Reads the explicit capability flag from the process environment; no new filesystem or registry read.;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 fix round 1 (#511 R16 amendment): the status tick also fills Probes.ApplyFinished from systemApplyFinished(release.OptDir()), an Lstat of root's apply journal <opt>/system/router/journal.json in the root-owned, world-readable state directory: finished only when the journal is absent, any other answer unknown and so unfinished. Round 0: Probes.PrevRelease from prevReleaseOf (carlos.prev and carlos.prev.version, the files withMovesFields already reads). Reported in the private BoxMetrics block; no bucket request or cadence change.;rev3=census-ruling-platform-mail-submission;basis=Task 3 (plan gap G6 (b)): the status tick also fills Probes.MailerArmed from mailerArmed(mailwire.MailerSocket, 2s): a stat of /run/carlos-mailer/mailer.sock and, only when it is a socket, GET /v1/health on it. The agent (carlos-edge.service, user carlos), not root; reported in the private BoxMetrics block only. The same six sites; no store request, no read of /etc/carlos-mailer (which uid carlos cannot traverse). whole:Route@10554,whole:Route@12628,whole:Route@12909,whole:Route@6583,whole:Route@6610,whole:Route@7918 4dd7407a53e445f78e63f160bee068d835b26d5d8fd3300d389ba5dbcab26d5a |
| @legacy 722920e1d095fe935962342d131ef5e8d5c97481b52b7ddc38dc214bf84ee9a5 internal/host/bootstrap.go bootstrapWithGroup legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move bootstrapWith body here, retaining host.env, embedded unit reads and tmpfiles execution. Group live caller holds root mutation guard; skip automatic update/recovery units, preserve Restart=no/nftables drop-in and masks, and write separate root-owned /run/carlos-group-maintenance tmpfiles rule outside service ownership walk. No agent receipt read.;rev3=census-ruling-gvisor-demos;basis=Create the rootfs parent at 0700 and runtime root at 0755. Existing host.env/unit reads unchanged; workload templates remain unarmed.;rev3=census-ruling-platform-mail-submission;basis=Task 3: the sysusers.d/carlos.conf it writes is now the constant sysusersConf, which adds "u carlos-mailer - \"CARLOS mailer\" - /usr/sbin/nologin" ahead of the existing "g carlos-sockets -" line, so the tmpfiles line naming group carlos-mailer resolves on a box whose confs arrive by a staged-tree refresh. Constant text, no input; no read added. file:Command@12045,file:ReadFile@564,file:ReadFile@7111 62fa76ad0fa812a0effc7c6add43ddcf54313450c13f20fbb2fee9d004488588 |
| @legacy aea72efedb3cc995ae9c791962e3e80f7dfe0b54d87da8c3ca13616baf7a433b internal/host/bootstrap.go privilegedPlan legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-platform-mail-submission;basis=Task 3: one more constant argv, useradd --system --user-group --no-create-home --shell /usr/sbin/nologin carlos-mailer, right after carlos's, behind runPrivileged's existing guard (user.Lookup of the argv's own last word). No input; no read added. data-literal@382 4f353dc38a329ff88fdec4bc2611c44b7ac483eee308b73f58100abc539707cc |
| @@ -22,12 +23,18 @@ |
| @legacy 85d678c6a608ff70b7a60141d0efde911544f4b7aa9a7d9508f0e13cf2b7e724 internal/host/units/carlos-mailer-arm.path external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: [Path] PathExists=/etc/carlos-mailer/keys, Unit=carlos-mailer.socket, WantedBy=multi-user.target; enabled and armed by bootstrap like every .path. PID 1 watches a path in a root-owned 0750 root:carlos-mailer directory only root (the operator) writes; it starts a socket unit and reads nothing. file:external@0 6b28c6282ee930560f859f20c752c65f0e550412b9c6ffb1fc10c292a3941a2a |
| @legacy f99b76edb6264d669d69dee1931907a85d99256a5f891eda8be179f49c658492 internal/host/units/carlos-mailer.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: runs /opt/carlos/carlos mailer serve as the static user carlos-mailer (never root), socket-activated, ConditionPathExists=/etc/carlos-mailer/keys, EnvironmentFile=-/etc/carlos/host.env (read by PID 1, as every carlos service's) with UnsetEnvironment=CARLOS_SECRETS_KEY, AWS_EC2_METADATA_DISABLED=true, IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128, StateDirectory=carlos-mailer 0700, and the relay's hardening block with no ReadWritePaths. No root process reads anything new; the mailer reads its own key file and state. file:external@0 3f9bd1c2d6e1a4d5d1c72d0c24b000e122cc95290cca8b0d2e62d86576e2dd5f |
| @legacy 486f70ac08ac5f675d91dc3b7bddf949c908db227e4596af5706df846c4fb32f internal/host/units/carlos-mailer.socket external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: ConditionPathExists=/etc/carlos-mailer/keys, ListenStream=/run/carlos-mailer/mailer.sock, SocketUser=carlos, SocketGroup=carlos, SocketMode=0600, Accept=no; not enabled, started only by the arming path. PID 1 binds a socket in a root-owned directory, as carlos-instance-control.socket does in /run/carlos-control. No read added. file:external@0 275aae364c39e89bdf3d76d7e66aea9cf65b398ac0c16c087db353cfd5140c34 |
| +@legacy 6124a227150c2055499a081f370c0d3211decfc51a16ff34a0449493b2a94cb3 internal/mailer/counter.go Counter.loadLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: reads the day's counts file from the mailer's own state directory; a body that does not decode is renamed aside, logged loudly, and the day restarts at zero (the per-box bound §4.1 (a) accepts). carlos-mailer only. file:ReadFile@142 a317a61e58c996133e1ae96045932c927052cb5f44720fb90193ae45abbe2d1b |
| +@legacy 66171fc9229872bbf17d3f26e75389dbacb7171bbd7ff08f5c820b60140e2ebf internal/mailer/counter.go Counter.writeLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: writes the day's counts durably (temp file in the same directory, fsync, rename, directory fsync) before a send. carlos-mailer only, in its own state directory. file:CreateTemp@118,file:Open@489 40cb38a8252e6c90bd21efdfafc7bbcb9b66b04a10bf9c2154f5796e1bff4820 |
| +@legacy 12c73222310be848185adfe95bbddc07be71e26b630125da84c9e2e8700f961e internal/mailer/counter.go OpenCounter legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: the mailer's per-box daily cap counter. Creates $STATE_DIRECTORY/counts (0700) and removes count files more than three days old by their date-shaped names. Runs as carlos-mailer in its own StateDirectory (0700 carlos-mailer), which no other uid can write; never root. file:ReadDir@316 86a48b081bc3c509a70c882d07bf045a9dcd2a9e7ca6643db7fbec83cb35b9f1 |
| +@legacy 09ddb6ec28ddc32798b2afd4909d661e9da73e8a6cf48c6b8a73f9fa00bb0cba internal/mailer/keys.go KeyFile.Changed legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: a stat of the same constant key path, compared with the loaded file's mtime, size and inode, so a rotation reloads with no restart. carlos-mailer only. file:Stat@47 1e4714c15a0cde077167358d786eaa3b33d6a9f3330a5d282dbba59beb1a3299 |
| +@legacy c577b1c36d95d7616e46d796828771d5e9a7d2b7229d0c6b3353c3ec4c313bf7 internal/mailer/keys.go loadKeys legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: reads /etc/carlos-mailer/keys (a constant path) as carlos-mailer: refuses anything but a regular 0640 file owned by root and group carlos-mailer, more than two keys, or a malformed line; errors never carry a secret. Root never reads it. The file is written by the operator by hand, in a 0750 root:carlos-mailer directory uid carlos cannot traverse. file:Open@68,file:ReadFrom@488,file:Stat@154 c86150ed82395d1051892825ea4893a289e2eda699372974c4373845794d707d |
| @legacy 92d90fe8f4ae11810f6e85c8df7ceb2a4024c8da10e42c8788ee154f5b8a60ce internal/mailsubmit/forward.go SocketForwarder.Send legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 4, new: the agent's client to the mailer: one HTTP POST of /v1/send over a fresh dial of the constant /run/carlos-mailer/mailer.sock, 60 s timeout, answer read to at most 64 KiB and decoded. Runs in the agent, as carlos. The socket's directory is root's; the mailer at the other end is a separate uid. file:ReadAll@885 b1c14436f42f60c4157ad0dffb1b998931a58b3a2ebf545578ff6d2e243dcd58 |
| @legacy dcfde0fc6cf86e118ad58646b43a41481c115f7eae91a5bb137f4d00e079d607 internal/mailsubmit/verb.go Mount legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 4, new: POST /v1/mail on an instance's control socket. The bearer by the existing verbs' rule (empty or unreadable token refuses everything; SHA-256 constant-time compare); MaxBytesReader(14 MiB), the JSON envelope, base64 raw of at most 10 MiB, 1 to 50 non-empty recipients, a non-empty from, else 400 BAD_REQUEST. Stamps account, app and host from the route the socket was bound for, never from the body, and forwards; a transport error or an answer outside 200/400/403/429/503 is 503 MAILER_UNAVAILABLE. Runs in the agent, as carlos; the body is a tenant's and is only decoded and forwarded, never used to name a path, route or account. registry:App@152,registry:Host@160,whole:Route@147 170951db97d14dc471251211b1526d2a640a0c7aba3f5eec1e6c12bc0ae81d2c |
| @legacy 9d438dcdbaabed1854fa668aa67b6b86f60ede58d5d3d2ba3c3dcb410a9f1976 internal/activator/backend_exec.go ExecBackend.agentOwnedVars legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Use the verified generation/launch mode to remove CARLOS_DB after environment merges and omit the binary --db argument where applicable. Existing runtime, layout, secrets and exec gates remain; route reads are mode projection only.;rev3=census-ruling-platform-mail-submission;basis=Task 4: also decides CARLOS_MAIL through mailSubmits: set to "submit" only when the control socket bound, the verb is mounted, the app sender's switch is on and the route is Provisioned; stripped otherwise, a tenant-supplied value from fileEnv included. agentOwnedNames and moves.AgentOwnedVars gain it as a pinned pair. Only narrows what a tenant's files can set. Agent, not root. registry:Host@1209,whole:Route@1171,whole:Route@631 7cc1bcb0b415ee478350a0519799542e0b1e5419c94121519c6e1b349d613c10 |
| @legacy efaa7c1113d4186ab422cb6350f2a53d99468bb7e8d5e71bf22b1f11612a7687 internal/activator/backend_exec.go ExecBackend.spawnChildFrom legacy accepted-legacy accepted-legacy;rev3=census-ruling-zddr3;basis=Census ruling zddr3: changed legacy row (comment-only change describing the shim placement); the same class as the accepted-legacy Manager.startIn and placementLive under fix1-merge-review (existing agent delegated-cgroup management remains legacy); no root decision; no registry, /data, release or claim reads. Boundary: the agent's own delegated cgroup subtree (including its scratch probe child), /proc/self, and pipes to and from its own parent, running as carlos.;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos (the flat start body): the same change as seedChild: ensureAdminTokenFor(ctx, rt, paths) for the token (the same flat path), the key's producer carrying the HA mint decision, and launchEnvLayer(ctx, rt) for the env and key layer the replica gate reads; a non-HA host's token, key and env are produced and read as before; +whole:Route; only adds refusals for HA hosts;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Use the verified generation/launch mode to remove CARLOS_DB after environment merges and omit the binary --db argument where applicable. Existing runtime, layout, secrets and exec gates remain; route reads are mode projection only.;rev3=census-ruling-edge-page-cache-1;basis=the control listener is now built with the whole route (edge.ListenControl(controlSocket, rt, ...)), the +whole:Route site; it computes the launch inputs once from the build it execs by path (a staged exe's caller-named build, or the gate-resolved pinned version; "" for an unpinned live link) and fileEnv it already read, keeps them on the childProc, and for a live-link spawn publishes them to the in-memory cache (NoteProcessInputs) beside the existing purge; no new file read;rev3=census-ruling-gvisor-demos;basis=Task 5: gate launch using startup-captured mode and existing route/role/layout before preparation or execution; migrate structured root start identity and reject mismatches. Unsupported gVisor paths refuse; native behavior and existing root authority checks retained. No new root read source. Merge2 e8a1ddde: retain main build parameter, pinned live identity, launchInputs from captured build/environment, and current-process input publication. edge.ListenControl now receives the whole Route as main requires (+whole:Route); no new filesystem or storage input. Branch sandboxLaunch remains before preparation and spawn; existing direct primitive gate unchanged.;rev3=census-ruling-security-review-mitigations;basis=Enforce the unchanged never-served resident refusal once at the shared flat/foreign primary binary spawn sink, before placement, live-link/token/env/control preparation or execution. Covers plain, generation and staged Service wakes; existing served/explicit-flat exemptions and other gates retained. No new filesystem/store source.;rev3=census-ruling-platform-mail-submission;basis=Task 4: the inline mount (Timers, UpdatesReader) is replaced by b.controlMount(rt, tokenReader, n): the same verbs under the same conditions, plus the mail verb when b.Mail is set. The three rt.Host reads move into controlMount; the route is passed whole. Agent, not root; nothing else changes. file:Command@11030,registry:Host@12313,registry:Host@12674,registry:Host@12768,registry:Host@258,registry:Host@4236,registry:Stateless@10961,whole:Route@10853,whole:Route@11002,whole:Route@11410,whole:Route@13065,whole:Route@13157,whole:Route@1527,whole:Route@189,whole:Route@1944,whole:Route@2305,whole:Route@287,whole:Route@4091,whole:Route@4119,whole:Route@4430,whole:Route@476,whole:Route@6501,whole:Route@8766 dacd2d37b38491f11ba1be34795d5fe40915aa044d6732ccf2bae467c733f80e |
| @legacy fa76f66ed1ce2b9e9b96dd442f08e32b99d090fa72055b83bb9c2fa35a4907db internal/activator/prepare.go ExecBackend.listenControl legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-edge-page-cache-1;basis=passes the whole route to edge.ListenControl instead of rt.Host (the -registry:Host +whole:Route change); nothing else;rev3=census-ruling-platform-mail-submission;basis=Task 4: the same replacement as spawnChildFrom, with gen as the write fence's generation, so the nested and rootfs listener mounts exactly what the flat one does. Agent, not root. registry:Host@508,whole:Route@361,whole:Route@389 f6534861cdbeef80dbcfaf6b07df685e4ac2f2a86650db54f174871526a50aff |
| internal/host/agent.go fastTick legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=observes the change index before any pass (observeIndex), runs the backstop's requested full pass and a scoped pass for moved app scopes (indexTick), and arms the canary pointer gate on the sweep (canaryPointerGate) only on a tick whose own index observation succeeded; read site unchanged, offset moved;rev3=census-ruling-stateless-replicas-1;basis=Call coordinator Tick on the existing tick before convergence; client renews held terms only at the pinned interval. Existing registry read unchanged. Final review I3: signal the owned renewal worker instead of waiting for its sequential console HTTP calls. Existing convergence and record read unchanged.;rev3=census-ruling-region-ha-p3a;basis=Run the optional desired-role reader on the existing tick after observing the armed change index; no new root path or timer, nil reader is unchanged.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: signals the owned replica worker on the existing tick; coalesced asynchronous execution, no timer or bucket scan added. merge of origin/main 7920cccf: Retain main box-role reader pass on the existing tick alongside the replica worker signal; merge-only body change, unchanged read sites.;rev3=census-ruling-restart-new-box-gap;basis=calls the optional restartGain hook (restartGainSeed) once per existing tick before the serial read; no new root path, timer or read kind; nil hook is unchanged;rev3=census-ruling-agent-start-demo-3;basis=Refresh moved notices through the shared watch before normal convergence; no new per-box poll. Census read-site delta: unchanged (1).;rev3=census-ruling-stateless-replicas-4-task1;basis=Signals the owned replica swap worker (armedReplicaDeploy.tick) beside the placement worker on the existing tick; coalesced background pass, no timer, no bucket read. Its transitions go through the console's authenticated /deploy.;rev3=census-ruling-platform-mail-submission;basis=Task 4: on a serial move, after the schedule leg, starts the armed mail switch cache's Refresh on its own goroutine (each read bounded at 2 s, overlapping refreshes skipped). It re-reads the app sender records already cached, through the agent's deploy store. Agent, not root; the tick waits on nothing new. registry:Host@5822 a1cd273f24047c63670f8c32c000a84f1a3861d058da38c5318551929f312390 |
| +internal/host/agent.go provisionTickConfig legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ha-p1a-433;basis=the agent (carlos-edge.service, user carlos) and the edges file loop's eligibility: the same CARLOS_POOLS read, now parsed by provision.ParseBoxPools (internal/provision, envelope re-pinned), the one parser boxPools also uses. "@shared" (provision.SharedPoolToken, never a valid pool name) is the shared "" pool; other tokens are literal as before; empty elements and repeats dropped. No read added.;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 4, rule 2): sets ReconcileConfig.FleetBox to the box's own fleet label from resolveFleetIdentity(getenv), only when the identity resolves and region == PlacementTarget(identity.Fleet); otherwise it stays "" (the box admits only unlabelled records). The same environment the fleet loops already read; read sites unchanged (2). Agent config, not root.;rev3=census-ruling-platform-mail-submission;basis=Task 5: its region, pools and fleet label now come from BoxScopeFromEnv, which is the same three reads moved out unchanged (CARLOS_REGION trimmed, provision.ParseBoxPools(CARLOS_POOLS), and resolveFleetIdentity's label only when its fleet is the one the region places the box on), so the box-local mailer resolves "on this box" by the agent's rule. The ReconcileConfig it returns is field for field what it was. Agent, not root. data-literal@173,data-literal@214 cabe3cb9662118eb82ddbc77dbbdb80b6718494caea097c8ffb894ccc4903fe3 |
| internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added.;rev3=census-ruling-static-sweep-periodic;basis=in the edge-ready callback, publishes e.LargestStaticTree in staticTreeSource for the disk alert line (diskAlertFrac in the metrics loop); in-memory wiring only, no read added; read sites unchanged (9);rev3=census-ruling-edge-page-cache-1;basis=wires the exec backend's CurrentInputs into the edge cache (wireCurrentInputs) and, in the ready hook after armEdgeAssetCache (whose returned store it now keeps), calls armEdgePageCache, which does nothing unless CARLOS_PAGE_CACHE=1; read sites unchanged (9); no read added;rev3=census-ruling-gvisor-demos;basis=Capture sandbox resolution and refusal once; log errors once; gate route admission and BeforeExec before process launch. No new root read. Task 5: pass the once-captured sandbox effective mode/config error into ExecBackend, UnitBackend and the immutable Client expectation. Same startup environment/registry reads; swapArming declines gVisor before placement. Task 8: arm read-only status projection with the existing Client.SandboxStatus callback. Agent status now queries the existing root /ready endpoint; no new root authority or guest-file input. Merge2 e8a1ddde: retain main wireCurrentInputs and armEdgePageCache through the existing asset-store ready hook alongside branch once-captured sandbox mode, wake gates and root status wiring. No new direct read; main page-cache helpers retain their own census overlays.;rev3=census-ruling-region-ha-held-build;basis=wires the drain state: svc.SetDrainingSource(boxDrain.IsDraining), svc.SetPeerDrainView(e.PeerDraining), e.SetPeerDrainedHook(svc.DropHoldersNaming); in-memory only; no read added; region HA held-requests Task 5: on group members, starts the drain driver over the activator, the edge and boxDrain, and serves its root-only drain socket; no read added beyond the socket's own Branch review r1: the drain state follows the root start fence on group members (the fence reader is the existing fenceLocation.read, a root-owned fixed path); e.SetPeerUndrainedHook(svc.AllowHoldersNaming) beside the drained hook (memory only); the drain socket serves only the agent's own user. No read added.;rev3=census-ruling-security-review-mitigations;basis=Wire the cached operator flat-layout choice into the exec backend's new-resident refusal; no read source added, existing authority retained.;rev3=census-ruling-w6-ingress-drain;basis=agent (user carlos), not root. Builds the ingress drain (newIngressDrain) with arming read at ask time from os.Getenv (CARLOS_REGION_HA, CARLOS_INGRESS_TARGET_GROUPS, both from the root-owned host.env), the fixed admission and lease.CurrentSelf (existing IMDS identity); its reader is awstg.Load, the box role's credentials calling ELB DescribeTargetHealth/DescribeTargetGroupAttributes (new AWS reads, by the agent). Wires admission.closeStartsForIngressDrain, the lbhealth drain condition, ingress.setEdge, and ingress.shutdownStarted in WithShutdownStarted. The drain socket (/run/carlos/.ha-drain/drain.sock, agent-user only, existing) is now also served on a fixed box with the drain configured (was group members only), routing /v1/ingress/* to the ingress drain and the group drain verbs to 404 there. armHADepartures now takes fixtureDepartureGetenv() and MakeQueue fixtureDepartureQueue(), which in a production (non-rootrunner) build are os.Getenv and nil, as before. Read sites unchanged (9).;rev3=census-ruling-stateless-replicas-4-task1;basis=Arms the fleet-only replica swap worker next to the placement worker: same console URL and fleet token as the existing replicaCoordinatorAPI, the existing activator Service; stops and joins at shutdown. No new read site, credential or bucket reader.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: sets deployWorker.step to the rollout scheduler answer for the record permit (replicaStepOf over armedRollout), an in-memory callback; no read site, credential or bucket reader added.;rev3=census-ruling-stateless-replicas-4-task2-fix2;basis=Task 2 fix round 2: the swap worker step is armedReplicaStep, the same lazy scheduler lookup as before as a named function; no read site added.;rev3=census-ruling-stateless-replicas-4-merge-main;basis=Merge of main 5fac2ff1: both sides changed it. Main (01d6ca78, linked-deployments-slice1) starts linkLoop beside tunnelLoop; this branch keeps its replica coordinator wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-final;basis=#511 final wave item 2: wires the swap worker's drive (armedReplicaDrive, the armed rollout manager's DriveReplicaRelease); no read added;rev3=census-ruling-stateless-replicas-4-merge-main2;basis=Merge of main af871da0 (v0.34.49): both sides changed it. Main (178dcfe5, member-backups-2a) moves the inline duty-view closure into armDutyView/dutyView and starts verifyAssignLoop; its sites drop by registry:Host and whole:Route x2 as main recorded them. This branch keeps its replica coordinator, swap worker and drive wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-drill3;basis=drill 3 R24: makes one in-memory channel, closes it (once) inside the edge's existing shutdown-started callback after ingress.shutdownStarted, and passes it to tunnelLoop, which drains only a fleet channel name; no read added, same six sites; touches no admission, lease, ingress drain, listener or file; the agent process, no root decision;rev3=census-ruling-edge-ppv2;basis=Agent (uid carlos), not root. memwatchLoop now gets edgeProxyCounters(&demoEdge) (in-process counters, no read). The drain socket's driver is newAgentDrainSocket(ingress, e, os.Getenv), which attaches the edge trust handler only when CARLOS_INGRESS_PROXY_SOURCES in the agent's environment (from the root-owned host.env) parses to a non-empty list; the socket is served when drainSocketServed: a group member or a configured ingress drain (both as before), or a box armed for PROXY protocol (new). The socket's path and agent-user-only permissions are unchanged. Read sites unchanged (6).;rev3=census-ruling-platform-mail-submission;basis=Task 4: sets eb.Mail = mailsubmit.SocketForwarder{} on every box and, when a deploy store opens, eb.MailSwitch to a new mailSwitchCache's On, armed for the serial-move refresh (armedMailSwitch). One more openDeployStore call, as the fleet and coordinator wiring beside it already make. Agent, not root. file:Exec@21141,file:Open@2191,file:Statfs@56665,registry:App@13287,whole:Route@13279,whole:Route@50143 8c29c4f2bb4562560e304a5ab66a3be6f8a354949819cb19a22d9005d06d5a39 |
| internal/host/agent.go statusLoop legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the status tick's context carries the box's lifetime judge; read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 953b9fda (its later changes, regional box names and self-serve moves plan 1 among them, under main's own census rulings), where the tick fills rootfs_ready and rootfs_blocked from armedRootfs.Load().probe, which each tick runs NestedOK's checks and asks the control socket's GET /ready/rootfs (never the store); the same four direct sites;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 11 and #329 plan 3 Task 7: takes root's GET /egress reader and fills p.Egress = egressStatusProbe(egressStatus, routes, provision.PolicyReadStates()) and p.SizeCommittedMiB = sizeCommittedMiB(armedSizeSource.Load(), routes); the two added whole:Route sites are the tick's own registry list handed to those two units (decision rows), which read root's control socket and the activator's memory; no store request added; the four existing sites unchanged, offsets moved.;rev3=census-ruling-fleet-alerts-1;basis=the agent (carlos-edge.service, user carlos): the status tick passes os.Geteuid() to alertDeliveryProbe, which fills AlertDelivery.EngineBeat/EngineBeatWhy from engineBeatArmed (the env value and the euid only, no file access, root refused before the path is looked at), and fills Probes.DiskFullETAHours from diskETAProbe(&processDiskTrend, now), a Theil-Sen fit over the metrics loop's in-memory ring of disk readings; the same six sites, no read added, no store request added;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the status tick's Probes gain HeldStreams: heldStreamsState(), which calls the edge's in-memory counters function (nil until the edge is ready). No file, bucket or registry access added.;rev3=census-ruling-stateless-replicas-3;basis=Fix round 1 Q20: read the detached in-memory replica snapshot source into Probes.ReplicaCopies on the existing five-minute tick. Existing six direct read sites unchanged. No additional bucket request, changed cadence or app lifecycle action.;rev3=census-ruling-agent-start-demo-3;basis=Report moved capability only when the serving edge reports readiness; report claim-seed support only with CARLOS_DEMO_CLAIM=1. Reads the explicit capability flag from the process environment; no new filesystem or registry read.;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 fix round 1 (#511 R16 amendment): the status tick also fills Probes.ApplyFinished from systemApplyFinished(release.OptDir()), an Lstat of root's apply journal <opt>/system/router/journal.json in the root-owned, world-readable state directory: finished only when the journal is absent, any other answer unknown and so unfinished. Round 0: Probes.PrevRelease from prevReleaseOf (carlos.prev and carlos.prev.version, the files withMovesFields already reads). Reported in the private BoxMetrics block; no bucket request or cadence change.;rev3=census-ruling-platform-mail-submission;basis=Task 3 (plan gap G6 (b)): the status tick also fills Probes.MailerArmed from mailerArmed(mailwire.MailerSocket, 2s): a stat of /run/carlos-mailer/mailer.sock and, only when it is a socket, GET /v1/health on it. The agent (carlos-edge.service, user carlos), not root; reported in the private BoxMetrics block only. The same six sites; no store request, no read of /etc/carlos-mailer (which uid carlos cannot traverse). whole:Route@10554,whole:Route@12628,whole:Route@12909,whole:Route@6583,whole:Route@6610,whole:Route@7918 4dd7407a53e445f78e63f160bee068d835b26d5d8fd3300d389ba5dbcab26d5a |
| internal/host/bootstrap.go bootstrapWithGroup legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move bootstrapWith body here, retaining host.env, embedded unit reads and tmpfiles execution. Group live caller holds root mutation guard; skip automatic update/recovery units, preserve Restart=no/nftables drop-in and masks, and write separate root-owned /run/carlos-group-maintenance tmpfiles rule outside service ownership walk. No agent receipt read.;rev3=census-ruling-gvisor-demos;basis=Create the rootfs parent at 0700 and runtime root at 0755. Existing host.env/unit reads unchanged; workload templates remain unarmed.;rev3=census-ruling-platform-mail-submission;basis=Task 3: the sysusers.d/carlos.conf it writes is now the constant sysusersConf, which adds "u carlos-mailer - \"CARLOS mailer\" - /usr/sbin/nologin" ahead of the existing "g carlos-sockets -" line, so the tmpfiles line naming group carlos-mailer resolves on a box whose confs arrive by a staged-tree refresh. Constant text, no input; no read added. file:Command@12045,file:ReadFile@564,file:ReadFile@7111 62fa76ad0fa812a0effc7c6add43ddcf54313450c13f20fbb2fee9d004488588 |
| @@ -51,19 +58,27 @@ internal/host/mailerreport.go mailerArmed legacy accepted-legacy accepted-legacy |
| internal/host/units/carlos-mailer-arm.path external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: [Path] PathExists=/etc/carlos-mailer/keys, Unit=carlos-mailer.socket, WantedBy=multi-user.target; enabled and armed by bootstrap like every .path. PID 1 watches a path in a root-owned 0750 root:carlos-mailer directory only root (the operator) writes; it starts a socket unit and reads nothing. file:external@0 6b28c6282ee930560f859f20c752c65f0e550412b9c6ffb1fc10c292a3941a2a |
| internal/host/units/carlos-mailer.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: runs /opt/carlos/carlos mailer serve as the static user carlos-mailer (never root), socket-activated, ConditionPathExists=/etc/carlos-mailer/keys, EnvironmentFile=-/etc/carlos/host.env (read by PID 1, as every carlos service's) with UnsetEnvironment=CARLOS_SECRETS_KEY, AWS_EC2_METADATA_DISABLED=true, IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128, StateDirectory=carlos-mailer 0700, and the relay's hardening block with no ReadWritePaths. No root process reads anything new; the mailer reads its own key file and state. file:external@0 3f9bd1c2d6e1a4d5d1c72d0c24b000e122cc95290cca8b0d2e62d86576e2dd5f |
| internal/host/units/carlos-mailer.socket external legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 3, new: ConditionPathExists=/etc/carlos-mailer/keys, ListenStream=/run/carlos-mailer/mailer.sock, SocketUser=carlos, SocketGroup=carlos, SocketMode=0600, Accept=no; not enabled, started only by the arming path. PID 1 binds a socket in a root-owned directory, as carlos-instance-control.socket does in /run/carlos-control. No read added. file:external@0 275aae364c39e89bdf3d76d7e66aea9cf65b398ac0c16c087db353cfd5140c34 |
| +internal/mailer/counter.go Counter.loadLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: reads the day's counts file from the mailer's own state directory; a body that does not decode is renamed aside, logged loudly, and the day restarts at zero (the per-box bound §4.1 (a) accepts). carlos-mailer only. file:ReadFile@142 a317a61e58c996133e1ae96045932c927052cb5f44720fb90193ae45abbe2d1b |
| +internal/mailer/counter.go Counter.writeLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: writes the day's counts durably (temp file in the same directory, fsync, rename, directory fsync) before a send. carlos-mailer only, in its own state directory. file:CreateTemp@118,file:Open@489 40cb38a8252e6c90bd21efdfafc7bbcb9b66b04a10bf9c2154f5796e1bff4820 |
| +internal/mailer/counter.go OpenCounter legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: the mailer's per-box daily cap counter. Creates $STATE_DIRECTORY/counts (0700) and removes count files more than three days old by their date-shaped names. Runs as carlos-mailer in its own StateDirectory (0700 carlos-mailer), which no other uid can write; never root. file:ReadDir@316 86a48b081bc3c509a70c882d07bf045a9dcd2a9e7ca6643db7fbec83cb35b9f1 |
| +internal/mailer/keys.go KeyFile.Changed legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: a stat of the same constant key path, compared with the loaded file's mtime, size and inode, so a rotation reloads with no restart. carlos-mailer only. file:Stat@47 1e4714c15a0cde077167358d786eaa3b33d6a9f3330a5d282dbba59beb1a3299 |
| +internal/mailer/keys.go loadKeys legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 5, new: reads /etc/carlos-mailer/keys (a constant path) as carlos-mailer: refuses anything but a regular 0640 file owned by root and group carlos-mailer, more than two keys, or a malformed line; errors never carry a secret. Root never reads it. The file is written by the operator by hand, in a 0750 root:carlos-mailer directory uid carlos cannot traverse. file:Open@68,file:ReadFrom@488,file:Stat@154 c86150ed82395d1051892825ea4893a289e2eda699372974c4373845794d707d |
| internal/mailsubmit/forward.go SocketForwarder.Send legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 4, new: the agent's client to the mailer: one HTTP POST of /v1/send over a fresh dial of the constant /run/carlos-mailer/mailer.sock, 60 s timeout, answer read to at most 64 KiB and decoded. Runs in the agent, as carlos. The socket's directory is root's; the mailer at the other end is a separate uid. file:ReadAll@885 b1c14436f42f60c4157ad0dffb1b998931a58b3a2ebf545578ff6d2e243dcd58 |
| internal/mailsubmit/verb.go Mount legacy accepted-legacy accepted-legacy;rev3=census-ruling-platform-mail-submission;basis=Task 4, new: POST /v1/mail on an instance's control socket. The bearer by the existing verbs' rule (empty or unreadable token refuses everything; SHA-256 constant-time compare); MaxBytesReader(14 MiB), the JSON envelope, base64 raw of at most 10 MiB, 1 to 50 non-empty recipients, a non-empty from, else 400 BAD_REQUEST. Stamps account, app and host from the route the socket was bound for, never from the body, and forwards; a transport error or an answer outside 200/400/403/429/503 is 503 MAILER_UNAVAILABLE. Runs in the agent, as carlos; the body is a tenant's and is only decoded and forwarded, never used to name a path, route or account. registry:App@152,registry:Host@160,whole:Route@147 170951db97d14dc471251211b1526d2a640a0c7aba3f5eec1e6c12bc0ae81d2c |
| internal/activator/backend_exec.go ExecBackend.agentOwnedVars legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Use the verified generation/launch mode to remove CARLOS_DB after environment merges and omit the binary --db argument where applicable. Existing runtime, layout, secrets and exec gates remain; route reads are mode projection only.;rev3=census-ruling-platform-mail-submission;basis=Task 4: also decides CARLOS_MAIL through mailSubmits: set to "submit" only when the control socket bound, the verb is mounted, the app sender's switch is on and the route is Provisioned; stripped otherwise, a tenant-supplied value from fileEnv included. agentOwnedNames and moves.AgentOwnedVars gain it as a pinned pair. Only narrows what a tenant's files can set. Agent, not root. registry:Host@1209,whole:Route@1171,whole:Route@631 7cc1bcb0b415ee478350a0519799542e0b1e5419c94121519c6e1b349d613c10 |
| internal/activator/backend_exec.go ExecBackend.spawnChildFrom legacy accepted-legacy accepted-legacy;rev3=census-ruling-zddr3;basis=Census ruling zddr3: changed legacy row (comment-only change describing the shim placement); the same class as the accepted-legacy Manager.startIn and placementLive under fix1-merge-review (existing agent delegated-cgroup management remains legacy); no root decision; no registry, /data, release or claim reads. Boundary: the agent's own delegated cgroup subtree (including its scratch probe child), /proc/self, and pipes to and from its own parent, running as carlos.;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos (the flat start body): the same change as seedChild: ensureAdminTokenFor(ctx, rt, paths) for the token (the same flat path), the key's producer carrying the HA mint decision, and launchEnvLayer(ctx, rt) for the env and key layer the replica gate reads; a non-HA host's token, key and env are produced and read as before; +whole:Route; only adds refusals for HA hosts;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Use the verified generation/launch mode to remove CARLOS_DB after environment merges and omit the binary --db argument where applicable. Existing runtime, layout, secrets and exec gates remain; route reads are mode projection only.;rev3=census-ruling-edge-page-cache-1;basis=the control listener is now built with the whole route (edge.ListenControl(controlSocket, rt, ...)), the +whole:Route site; it computes the launch inputs once from the build it execs by path (a staged exe's caller-named build, or the gate-resolved pinned version; "" for an unpinned live link) and fileEnv it already read, keeps them on the childProc, and for a live-link spawn publishes them to the in-memory cache (NoteProcessInputs) beside the existing purge; no new file read;rev3=census-ruling-gvisor-demos;basis=Task 5: gate launch using startup-captured mode and existing route/role/layout before preparation or execution; migrate structured root start identity and reject mismatches. Unsupported gVisor paths refuse; native behavior and existing root authority checks retained. No new root read source. Merge2 e8a1ddde: retain main build parameter, pinned live identity, launchInputs from captured build/environment, and current-process input publication. edge.ListenControl now receives the whole Route as main requires (+whole:Route); no new filesystem or storage input. Branch sandboxLaunch remains before preparation and spawn; existing direct primitive gate unchanged.;rev3=census-ruling-security-review-mitigations;basis=Enforce the unchanged never-served resident refusal once at the shared flat/foreign primary binary spawn sink, before placement, live-link/token/env/control preparation or execution. Covers plain, generation and staged Service wakes; existing served/explicit-flat exemptions and other gates retained. No new filesystem/store source.;rev3=census-ruling-platform-mail-submission;basis=Task 4: the inline mount (Timers, UpdatesReader) is replaced by b.controlMount(rt, tokenReader, n): the same verbs under the same conditions, plus the mail verb when b.Mail is set. The three rt.Host reads move into controlMount; the route is passed whole. Agent, not root; nothing else changes. file:Command@11030,registry:Host@12313,registry:Host@12674,registry:Host@12768,registry:Host@258,registry:Host@4236,registry:Stateless@10961,whole:Route@10853,whole:Route@11002,whole:Route@11410,whole:Route@13065,whole:Route@13157,whole:Route@1527,whole:Route@189,whole:Route@1944,whole:Route@2305,whole:Route@287,whole:Route@4091,whole:Route@4119,whole:Route@4430,whole:Route@476,whole:Route@6501,whole:Route@8766 dacd2d37b38491f11ba1be34795d5fe40915aa044d6732ccf2bae467c733f80e |
| internal/activator/prepare.go ExecBackend.listenControl legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-edge-page-cache-1;basis=passes the whole route to edge.ListenControl instead of rt.Host (the -registry:Host +whole:Route change); nothing else;rev3=census-ruling-platform-mail-submission;basis=Task 4: the same replacement as spawnChildFrom, with gen as the write fence's generation, so the nested and rootfs listener mounts exactly what the flat one does. Agent, not root. registry:Host@508,whole:Route@361,whole:Route@389 f6534861cdbeef80dbcfaf6b07df685e4ac2f2a86650db54f174871526a50aff |
| -@coverage . 90e9af87273bc6003300b0ae91d6e615c0c9c900518c03837f34e9038a7bfec5 |
| +@coverage . a6e82ded2b08718479bb8d6bdad426b33238044b5fa5224256168f5016b76af5 |
| @coverage internal/activator 2fe6860f1b7ef4f5644e17f59fe3cf75759ec2ffe597994c1478edd0512cbc38 |
| -@coverage internal/host 80665fe1e921b049292c71a9e4c4e102c3d72b525cb4ed1d3a46d681fadcf2ad |
| +@coverage internal/host c0ad562284905411f38c76f5d8aefe76eada13927a4629884e46bff52ccf0b30 |
| @coverage internal/host/demo_units 3a34238356068c6176879f3ee189c81af8e08bfcc0246c5feba80d7169f7af6a |
| @coverage internal/host/units 460478599582ed846a1b6c2d5273c8b2460dc40dcb2e82807a4d404d64c7a330 |
| +@coverage internal/hostenv 6c96c4abe8548fe3cf12d3a220de3e2917c3edfa5320b1662ea76bdf364d24b5 |
| @coverage internal/instancectl 50d4d80f1f1a86bbed67676f4e439eb79a08bb546ea85ff01a3b433925b9d984 |
| -@coverage internal/mailer 3a1c42f8892a49d986a12078be8b5b8c7e69f066b265928b72eaaf3b6a19910d |
| +@coverage internal/mailer 985199bf5324887938514750668eaa8eb099b1b3be0734c7de77c7fddd4230b1 |
| @coverage internal/mailsubmit 56f6a85fb8ec114b259da26d7bbc7e5a605fc2013693f19012facc248e10b3d8 |
| -@coverage internal/mailwire 63e4ea297d1030ee6dc397f0a2a107f58b3ecff029513199b8e64489b2c454c1 |
| +@coverage internal/mailwire 58b9cbb8a003ed11feb1c0352c5c23992fe532da895471ec76045528ab12e077 |
| @coverage internal/moves 9390702695d308a327f5572f4ff5967718141c5d385dff7671ff1e2c825ef407 |
| +@coverage internal/provision 81eee86d7ee3819434031945c3f54d864c6122b50ee03f9a6162f26453287c08 |
| +@coverage internal/release 6a35b2b7512a396c5803d5976dfc23af48c2de9736a52ff9338e10740b4c44b5 |
| @coverage internal/status 7cdc110ec7df53cc754816f7333a90f665fb27a55caa7d2f4988fb7b02f8263f |
diff --git a/internal/release/openers_test.go b/internal/release/openers_test.go| index fb9405401..2156ba9b9 100644 |
| --- a/internal/release/openers_test.go |
| +++ b/internal/release/openers_test.go |
| @@ -18,7 +18,8 @@ import ( |
| // until EnableChangeIndex, so the way a deployment-bucket writer goes missing |
| // is a new call site that opens the bucket with the plain constructor. This |
| // test finds every place the module builds a store over a bucket or a |
| -// directory (NewS3Store, NewS3StoreIn, an S3Store literal, NewDirStore) and |
| +// directory (NewS3Store, NewS3StoreIn, NewS3StoreFromConfig, an S3Store |
| +// literal, NewDirStore) and |
| // makes each one say which kind it is for: |
| // |
| // - an S3 deployment bucket (apps/, accounts/, control/): the site calls |
| @@ -54,6 +55,7 @@ var otherBucketOpeners = map[string]openerEntry{ |
| "internal/lease/execution_store.go:ExecutionStore": {"execution/build state: the hibernate and claim data bucket, keyed by host prefix", 1}, |
| "internal/lease/endpoint.go:NewFilesStore": {"per-instance files store: the data/hibernate bucket, a host's published files under its hibernate prefix (files/0/), not the deployment bucket", 1}, |
| "internal/status/dryrun.go:DryRun": {"status dry run: a throwaway scratch directory, not a deployment", 1}, |
| + "internal/mailer/ses.go:AWSClients": {"the box-local mailer's read-only deployment store over its own key: GetObject on sender, domain and instance records only, never a write, so no change-index bump is needed", 1}, |
| "internal/grouprollaws/objects.go:read": {"carlos system group's read-only operator store (edges files, locks, router pointers in the deployment and data buckets) over each bucket's own region endpoint, never a configured one; its Put and Delete refuse, so no change-index bump is needed", 1}, |
| } |
| @@ -132,7 +134,7 @@ func scanOpenerSites(fset *token.FileSet, f *ast.File, rel string, inReleasePkg |
| if sel, ok := x.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "EnableChangeIndex" { |
| enables++ |
| } |
| - for _, name := range []string{"NewS3Store", "NewS3StoreIn"} { |
| + for _, name := range []string{"NewS3Store", "NewS3StoreIn", "NewS3StoreFromConfig"} { |
| if isRelease(x.Fun, name) { |
| found = append(found, openerSite{key: rel + ":" + fn, line: fset.Position(x.Pos()).Line, what: "call to " + name, kind: "s3call"}) |
| } |
diff --git a/internal/release/store.go b/internal/release/store.go| index cb34f9ce7..0e9198d6d 100644 |
| --- a/internal/release/store.go |
| +++ b/internal/release/store.go |
| @@ -870,7 +870,22 @@ func newS3Store(ctx context.Context, bucket string, opts ...func(*awsconfig.Load |
| if err != nil { |
| return nil, fmt.Errorf("s3store: load aws config: %w", err) |
| } |
| - client := awss3.NewFromConfig(cfg, s3compat.Options(), func(o *awss3.Options) { |
| + return &S3Store{Client: newS3Client(cfg), Bucket: bucket}, nil |
| +} |
| + |
| +// NewS3StoreFromConfig is an S3Store over a config the caller built, with |
| +// the same client options as every other store here (newS3Client). The |
| +// box-local mailer builds its config from its own static key with |
| +// rootaws.LoadStaticConfig and an explicit region, and never from the |
| +// default chain (platform mail submission plan, Task 5). |
| +func NewS3StoreFromConfig(cfg aws.Config, bucket string) *S3Store { |
| + return &S3Store{Client: newS3Client(cfg), Bucket: bucket} |
| +} |
| + |
| +// newS3Client is the store's S3 client over cfg: s3compat's options, which |
| +// honour CARLOS_S3_ENDPOINT and CARLOS_S3_QUIRKS, and the checksum settings. |
| +func newS3Client(cfg aws.Config) *awss3.Client { |
| + return awss3.NewFromConfig(cfg, s3compat.Options(), func(o *awss3.Options) { |
| // s3compat sets these too, but only under a custom endpoint. This |
| // store has always set them on EVERY client including stock AWS, and |
| // the flagship runs on stock AWS — so the unconditional form stays |
| @@ -879,7 +894,6 @@ func newS3Store(ctx context.Context, bucket string, opts ...func(*awsconfig.Load |
| o.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired |
| o.ResponseChecksumValidation = aws.ResponseChecksumValidationWhenRequired |
| }) |
| - return &S3Store{Client: client, Bucket: bucket}, nil |
| } |
| // s3NotFound folds the shapes a missing object answers with (NoSuchKey on |
diff --git a/internal/release/store_fromconfig_test.go b/internal/release/store_fromconfig_test.go| new file mode 100644 |
| index 000000000..66bcdf8de |
| --- /dev/null |
| +++ b/internal/release/store_fromconfig_test.go |
| @@ -0,0 +1,51 @@ |
| +package release |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| +) |
| + |
| +// NewS3StoreFromConfig builds the store over a caller's config with the |
| +// same client options as every other store (newS3Client): it honours |
| +// CARLOS_S3_ENDPOINT through s3compat, reads by key, and folds a missing |
| +// key into os.ErrNotExist exactly as NewS3Store's store does. |
| +func TestNewS3StoreFromConfig(t *testing.T) { |
| + var gets atomic.Int32 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gets.Add(1) |
| + if r.Method != http.MethodGet { |
| + http.Error(w, "no", http.StatusMethodNotAllowed) |
| + return |
| + } |
| + if strings.HasSuffix(r.URL.Path, "/b/present.json") { |
| + w.Header().Set("ETag", `"e1"`) |
| + _, _ = io.WriteString(w, `{"ok":true}`) |
| + return |
| + } |
| + w.Header().Set("Content-Type", "application/xml") |
| + w.WriteHeader(http.StatusNotFound) |
| + _, _ = io.WriteString(w, `<Error><Code>NoSuchKey</Code><Message>no</Message></Error>`) |
| + })) |
| + defer srv.Close() |
| + t.Setenv("CARLOS_S3_ENDPOINT", srv.URL) |
| + cfg := aws.Config{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider("AKID", "SECRET", "")} |
| + s := NewS3StoreFromConfig(cfg, "b") |
| + body, etag, err := s.Get(context.Background(), "present.json") |
| + if err != nil || string(body) != `{"ok":true}` || etag != `"e1"` { |
| + t.Fatalf("Get = %q %q %v", body, etag, err) |
| + } |
| + if _, _, err := s.Get(context.Background(), "absent.json"); err == nil || !strings.Contains(err.Error(), "file does not exist") { |
| + t.Fatalf("missing key = %v, want os.ErrNotExist", err) |
| + } |
| + if gets.Load() != 2 { |
| + t.Fatalf("%d requests reached the endpoint, want 2", gets.Load()) |
| + } |
| +} |
diff --git a/mailer_cli.go b/mailer_cli.go| index 480192bb5..8fcbc21fa 100644 |
| --- a/mailer_cli.go |
| +++ b/mailer_cli.go |
| @@ -2,13 +2,17 @@ package main |
| import ( |
| "context" |
| + "errors" |
| "fmt" |
| "log" |
| "os" |
| "os/signal" |
| + "strings" |
| "syscall" |
| + "time" |
| "github.com/carlosframework/platform/internal/clireg" |
| + "github.com/carlosframework/platform/internal/host" |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/mailer" |
| ) |
| @@ -44,8 +48,11 @@ func mailerCommand() *clireg.Node { |
| } |
| // runMailerServe is carlos-mailer.service's ExecStart. It refuses to start, |
| -// with one line, when systemd passed no socket: the mailer never binds the |
| -// path itself. |
| +// with one line, without the deployment bucket, either AWS region, its |
| +// state directory, a socket from systemd, or a loadable key. The unit |
| +// restarts it every 5 s and the socket stays up, so the agent's dial is |
| +// answered 503 MAILER_UNAVAILABLE and the box reports the mailer not |
| +// armed until the cause is fixed (plan Task 5). |
| func runMailerServe(_ []string) { |
| ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) |
| defer stop() |
| @@ -55,15 +62,68 @@ func runMailerServe(_ []string) { |
| } |
| } |
| +// mailerEnv is the mailer's configuration from host.env, through the |
| +// unit's EnvironmentFile=: the bucket, and the two AWS regions named |
| +// explicitly (round 1 P2-3). CARLOS_REGION is a placement label, used only |
| +// for "on this box", never as an AWS region. |
| +type mailerEnv struct { |
| + bucket, mailRegion, deployRegion, stateDir string |
| +} |
| + |
| +func readMailerEnv(getenv func(string) string) (mailerEnv, error) { |
| + e := mailerEnv{ |
| + bucket: strings.TrimSpace(getenv("CARLOS_DEPLOYMENT_BUCKET")), |
| + mailRegion: strings.TrimSpace(getenv("CARLOS_MAIL_REGION")), |
| + deployRegion: strings.TrimSpace(getenv("CARLOS_DEPLOYMENT_REGION")), |
| + stateDir: strings.TrimSpace(getenv("STATE_DIRECTORY")), |
| + } |
| + for _, need := range []struct{ name, val string }{ |
| + {"CARLOS_DEPLOYMENT_BUCKET", e.bucket}, |
| + {"CARLOS_MAIL_REGION", e.mailRegion}, |
| + {"CARLOS_DEPLOYMENT_REGION", e.deployRegion}, |
| + } { |
| + if need.val == "" { |
| + return e, fmt.Errorf("%s is not set; add it to /etc/carlos/host.env, then restart carlos-mailer.service", need.name) |
| + } |
| + } |
| + if e.stateDir == "" { |
| + return e, errors.New("STATE_DIRECTORY is not set; carlos-mailer.service's StateDirectory= sets it") |
| + } |
| + return e, nil |
| +} |
| + |
| func mailerServe(ctx context.Context, getenv func(string) string, pid int) error { |
| + env, err := readMailerEnv(getenv) |
| + if err != nil { |
| + return err |
| + } |
| ln, err := mailer.ActivatedListener(getenv, pid) |
| if err != nil { |
| return err |
| } |
| + keys, err := mailer.OpenKeyFile(mailer.KeyPath) |
| + if err != nil { |
| + return err |
| + } |
| + counter, err := mailer.OpenCounter(env.stateDir, time.Now(), log.Printf) |
| + if err != nil { |
| + return err |
| + } |
| + m, err := mailer.New(ctx, mailer.Options{ |
| + Scope: host.BoxScopeFromEnv(getenv), |
| + MailRegion: env.mailRegion, |
| + Keys: keys, |
| + Counter: counter, |
| + Clients: mailer.AWSClients(env.mailRegion, env.deployRegion, env.bucket), |
| + Logf: log.Printf, |
| + }) |
| + if err != nil { |
| + return err |
| + } |
| return mailer.Serve(ctx, mailer.Config{ |
| Listener: ln, |
| PeerOK: instancectl.EdgeMainPIDPeer(), |
| - Handler: mailer.NewHandler(nil), |
| + Handler: mailer.NewHandler(m, m.Healthy), |
| Logf: log.Printf, |
| }) |
| } |
diff --git a/mailer_cli_test.go b/mailer_cli_test.go| index 5e4e07d38..c8051440f 100644 |
| --- a/mailer_cli_test.go |
| +++ b/mailer_cli_test.go |
| @@ -25,10 +25,13 @@ func runMailerServeBinary(t *testing.T, env ...string) (int, string) { |
| return cmd.ProcessState.ExitCode(), stderr.String() |
| } |
| +// mailerBaseEnv is everything carlos mailer serve reads before the socket. |
| +var mailerBaseEnv = []string{"CARLOS_DEPLOYMENT_BUCKET=b", "CARLOS_MAIL_REGION=eu-west-1", "CARLOS_DEPLOYMENT_REGION=eu-west-1", "STATE_DIRECTORY=/nonexistent"} |
| + |
| // With no socket from systemd the mailer refuses to start, with one line, |
| // rather than binding the path itself. |
| func TestMailerServeRefusesWithoutSocket(t *testing.T) { |
| - code, stderr := runMailerServeBinary(t) |
| + code, stderr := runMailerServeBinary(t, mailerBaseEnv...) |
| if code == 0 { |
| t.Fatal("mailer serve with no socket exited 0") |
| } |
| @@ -37,3 +40,29 @@ func TestMailerServeRefusesWithoutSocket(t *testing.T) { |
| t.Fatalf("stderr = %q, want one line naming the missing socket", stderr) |
| } |
| } |
| + |
| +// Plan round 1 P2-3: the mailer names its AWS regions explicitly, and |
| +// refuses to start without either, naming the missing key, before it |
| +// serves anything (it never reaches the socket). |
| +func TestMailerRefusesWithoutRegion(t *testing.T) { |
| + for _, missing := range []string{"CARLOS_MAIL_REGION", "CARLOS_DEPLOYMENT_REGION", "CARLOS_DEPLOYMENT_BUCKET"} { |
| + var env []string |
| + for _, kv := range mailerBaseEnv { |
| + if strings.HasPrefix(kv, missing+"=") { |
| + kv = missing + "=" |
| + } |
| + env = append(env, kv) |
| + } |
| + code, stderr := runMailerServeBinary(t, env...) |
| + lines := strings.Split(strings.TrimSpace(stderr), "\n") |
| + if code == 0 || len(lines) != 1 || !strings.Contains(lines[0], missing) || strings.Contains(stderr, "LISTEN_PID") { |
| + t.Errorf("without %s: exit %d, stderr %q; want one line naming it", missing, code, stderr) |
| + } |
| + } |
| + // CARLOS_REGION is a placement label, never the AWS region: it does |
| + // not stand in for either. |
| + code, stderr := runMailerServeBinary(t, "CARLOS_REGION=eu-west-1", "CARLOS_DEPLOYMENT_BUCKET=b", "STATE_DIRECTORY=/x") |
| + if code == 0 || !strings.Contains(stderr, "CARLOS_MAIL_REGION") { |
| + t.Errorf("CARLOS_REGION alone: exit %d, stderr %q", code, stderr) |
| + } |
| +} |