carlos / platform Public

Fleet public routes Task 4: the hub serves an eligible forward row through the tunnel, with no gate or cache work

- edge.FleetServeEligible (internal/edge/fleetforward.go): spec §4.4's one
  tenancy rule. A forward row is eligible only on the hub, inert,
  fleet-placed on a fleet in the hub's fleets table, its raw account
  non-empty and the owner. Any other fleet-placed row on the fleet arm:
  accountless is served and logged; a non-empty account that fails
  ValidAccount is refused before RouteAccount (controller ruling,
  preflight 4.1, written into spec §4.4); otherwise it must own the fleet.
- edge.HubArmed: the one hub test; internal/host's hubArmed calls it.
- Reload reads FleetChannelAuth and ListFleets before the routes loop, adds
  a first dispatch case for forward rows (eligible: fleetProxy, viaTunnel;
  refused: no map entry, throttled log, never a later arm), asks the
  predicate in the existing fleet case, and folds no path rows for a
  forward host.
- ServeHTTP: a forward host is never a login POST at the hub and is never
  cacheable; localAssetCatch refuses a forward row.
- Spec §7: Task 4's census card reconciled (FleetServeEligible lives in
  fleetforward.go; HubArmed has no read site).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 253f533cb4a422c027cefb9004bafa9c5c0327b3 parent 1d7c10e
6 files changed, +942 −43
  • docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md +13 −4
  • internal/edge/assetcatch.go +5 −2
  • internal/edge/edge.go +101 −33
  • internal/edge/fleetforward.go +87 −0
  • internal/edge/fleetforward_test.go +730 −0
  • internal/host/hub.go +6 −4

Intent

Human

<task-notification> <task-id>bqlzwb5al</task-id> <tool-use-id>toolu_01TTBU5ZtZj6FA3HwqSSbB2K</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bqlzwb5al.output</output-file> <status>completed</status> <summary>Background command "Wait for CI on rootfs-worker-exit" completed (exit code 0)</summary> </task-notification>

diff --git a/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md b/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md
index 7669c2c4a..3ae4e1aef 100644
--- a/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md
+++ b/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md
@@ -421,10 +421,19 @@ rule is written:
`rt.Account` is non-empty and equals the owner;
- any other fleet-placed row that would take the fleet arm (no `Tunnel`,
`hub` true): when the raw `rt.Account` is empty, eligible (the approved
- pre-account compatibility case, logged); otherwise eligible only when
- `release.RouteAccount(rt)` equals the owner (R1-12: the raw field is
- checked for empty BEFORE `RouteAccount`, which turns an empty account
- into `OpsAccount`, `adopt.go:1363`);
+ pre-account compatibility case, logged); when the raw `rt.Account` is
+ non-empty and fails `release.ValidAccount`, refused; otherwise eligible
+ only when `release.RouteAccount(rt)` equals the owner, and a fleet not in
+ `owners` is refused (R1-12: the raw field is checked BEFORE
+ `RouteAccount`, which turns an empty or invalid account into
+ `OpsAccount`, `adopt.go:1363`, so an invalid account is never mapped to
+ `bab` and passed on the ops account's own fleet; controller ruling,
+ preflight 4.1, Task 4). The `hub` argument gates forward rows only:
+ whether a non-forward row reaches the fleet arm is the caller's dispatch
+ (`Reload`: tunnels enabled, as today), and wherever it does, this account
+ rule holds (Task 4: Reload passes `e.tunnels != nil &&
+ edge.HubArmed(os.Getenv)`, the one hub test, which `internal/host`'s
+ `hubArmed` now calls);
- any row that does not take the fleet arm: not this predicate's
business (unchanged dispatch, including a hand row's socket fallback on
a box with no hub).
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go
index d082efa33..f9489fd31 100644
--- a/internal/edge/assetcatch.go
+++ b/internal/edge/assetcatch.go
@@ -263,8 +263,11 @@ func (e *Edge) localAssetCatch(r *http.Request, host string, up upstream) (HostA
}
// The policy refuses these routes outright; the route snapshot is
// checked too, so a policy that lags a gate or an import never serves a
- // stored body past it.
- if up.route.Kind == "status" || up.route.Gate != "" || up.route.ImportGate != "" {
+ // stored body past it. A forward row is refused too (fleet public routes
+ // spec §4.8): its gate is on the fleet edge, out of this box's sight, so
+ // nothing here may answer for it from storage. The hop fill
+ // (serveAssetFillForHop) goes through this check as well.
+ if up.route.Kind == "status" || up.route.Gate != "" || up.route.ImportGate != "" || up.route.IsForward() {
return HostAssets{}, false
}
a, ok := st.local.For(host)
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 0a8cb6e54..4f1c112d0 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -731,6 +731,49 @@ func (e *Edge) Reload() error {
// absent from it have their probers stopped, exactly as RetireExcept
// retires activator children for hosts absent from `managed`.
probeSpecs := make(map[string]probeSpec)
+ // Fleet channel auth and the fleets table, read BEFORE the routes loop
+ // (fleet public routes spec §4.4): the loop's fleet arm asks
+ // FleetServeEligible, which needs each fleet's owning account. Both are
+ // registry-backed, so they refresh on the SAME poll that rebuilds routes:
+ // Task 1's Fingerprint moves on every fleet mutation (including token
+ // rotation), and the edge's existing 2s Watch->Reload loop (below, Watch)
+ // is the whole convergence bound for a rotated or detached box. No hub
+ // configured (e.tunnels == nil, the vast majority of boxes today) means no
+ // fleet channels either: same nil-means-disabled convention as
+ // act/cache/staticStore. Errors here abort the WHOLE reload (routes
+ // included), matching e.reg.List() above: a transient registry read
+ // failure must leave both tables exactly as they were, not blank out
+ // fleet auth while routes move on. Both are applied after the loop and
+ // the folds, at the point they always were.
+ //
+ // The store door's tenancy map comes from the SAME pass: a box's
+ // credentials and the account its reads are scoped to must never come
+ // from two different reads of the registry. ListFleets goes over a fresh
+ // connection (like FleetChannelAuth), so a fleet the console created
+ // moments ago is visible here rather than stuck behind a stale WAL
+ // snapshot on the long-lived handle. The same map is the owners map the
+ // eligibility rule reads.
+ //
+ // hub is the one hub test (HubArmed, shared with the agent's bindings
+ // pass and the edges-file writer) on a box whose tunnels are enabled.
+ var fleetAuth map[string]string
+ var owners map[string]string
+ hub := false
+ if e.tunnels != nil {
+ fleetAuth, err = e.reg.FleetChannelAuth()
+ if err != nil {
+ return err
+ }
+ fleets, err := e.reg.ListFleets()
+ if err != nil {
+ return err
+ }
+ owners = make(map[string]string, len(fleets))
+ for _, f := range fleets {
+ owners[f.Name] = f.Account
+ }
+ hub = HubArmed(os.Getenv)
+ }
for _, t := range routes {
// A sidecar is a member that serves nothing: it binds no socket, and
// nothing — inside the box or outside it — may ever dial it. Refused
@@ -765,6 +808,25 @@ func (e *Edge) Reload() error {
genManaged := false
fleet, isFleetPlaced := registry.FleetPlacement(t.Region)
switch {
+ // A forward row (fleet public routes spec §4.2) is the hub's row for
+ // an app placed on a fleet: it runs nothing here, and the only way it
+ // is ever served is through its fleet's tunnel. FIRST, ahead of the
+ // Tunnel, socket and addr arms, so a forward row that carries a stray
+ // backend column can never reach one of them: an eligible row takes
+ // fleetProxy, an ineligible one gets no map entry (so Allowed is false
+ // and no certificate is ordered for it) and never falls through.
+ // Eligibility is FleetServeEligible, the one rule: the hub only, inert,
+ // on a fleet in this box's fleets table, its raw account the fleet's
+ // owner.
+ case t.IsForward():
+ if ok, why := FleetServeEligible(t, hub, owners); !ok {
+ e.logThrottled("forward-refused "+t.Host, fmt.Sprintf("route %s is not served: %s", t.Host, why))
+ continue
+ }
+ p := fleetProxy(fleet, t.FleetBox, e.tunnels)
+ p.ModifyResponse = e.responseModifier(t)
+ proxy = p
+ viaTunnel = true
// Both reverse proxies get the Carlos-Purge response hook
// (purge_header.go): the app declares its own cache invalidations on
// the response it is already returning, and the edge applies them and
@@ -817,7 +879,19 @@ func (e *Edge) Reload() error {
// config gap that isn't its fault. viaTunnel is shared with the Tunnel
// case on purpose — a fleet-served instance is exactly as un-wakeable
// locally as a `-tunnel`-bound one; see the hibernation comment below.
+ //
+ // The tenancy rule is FleetServeEligible's: a row whose raw account is
+ // not the fleet's owner (or is not a valid account) is refused, no map
+ // entry, rather than degraded to its socket, because the hub is where
+ // its traffic would go. An accountless row is the pre-account
+ // compatibility case: served, and logged.
case isFleetPlaced && e.tunnels != nil:
+ if ok, why := FleetServeEligible(t, hub, owners); !ok {
+ e.logThrottled("fleet-refused "+t.Host, fmt.Sprintf("route %s is not served: %s", t.Host, why))
+ continue
+ } else if why != "" {
+ e.logThrottled("fleet-accountless "+t.Host, fmt.Sprintf("route %s: %s", t.Host, why))
+ }
p := fleetProxy(fleet, t.FleetBox, e.tunnels)
p.ModifyResponse = e.responseModifier(t)
proxy = p
@@ -1024,6 +1098,13 @@ func (e *Edge) Reload() error {
// should not have produced this row; nothing to attach it to.
continue
}
+ // A forward host has no path map here (spec §4.4): every path of it
+ // is the forward row's, and the fleet edge, which holds the app's
+ // own paths, routes inside it. The gate's login POST relies on this
+ // (§4.8): it is never re-resolved at the hub.
+ if up.route.IsForward() {
+ continue
+ }
if up.paths == nil {
up.paths = make(map[string]string)
}
@@ -1099,38 +1180,11 @@ func (e *Edge) Reload() error {
return err
}
e.foldRegional(m, routes, regionalRows)
- // Fleet channel auth: registry-backed, so this refreshes on the SAME poll
- // that rebuilds routes — Task 1's Fingerprint moves on every fleet
- // mutation (including token rotation), and the edge's existing 2s
- // Watch->Reload loop (below, Watch) is the whole convergence bound for a
- // rotated or detached box. No hub configured (e.tunnels == nil, the vast
- // majority of boxes today) means no fleet channels either — same
- // nil-means-disabled convention as act/cache/staticStore. Errors here
- // abort the WHOLE reload (routes included), matching e.reg.List() above:
- // a transient registry read failure must leave both tables exactly as
- // they were, not blank out fleet auth while routes move on.
+ // Fleet channel auth and the door's tenancy map, read before the routes
+ // loop (above), applied here as they always were.
if e.tunnels != nil {
- auth, err := e.reg.FleetChannelAuth()
- if err != nil {
- return err
- }
- e.tunnels.SetDynamicAuth(auth)
- // The store door's tenancy map, from the SAME pass: a box's
- // credentials and the account its reads are scoped to must never come
- // from two different reads of the registry. ListFleets goes over a
- // fresh connection (like FleetChannelAuth above), so a fleet the
- // console created moments ago is visible here rather than stuck
- // behind a stale WAL snapshot on the long-lived handle. Same
- // all-or-nothing error contract as everything else in Reload.
- fleets, err := e.reg.ListFleets()
- if err != nil {
- return err
- }
- accounts := make(map[string]string, len(fleets))
- for _, f := range fleets {
- accounts[f.Name] = f.Account
- }
- e.fleetAccounts.Store(&accounts)
+ e.tunnels.SetDynamicAuth(fleetAuth)
+ e.fleetAccounts.Store(&owners)
}
// Probers BEFORE the map swap — the opposite order to RetireExcept below,
// and deliberately so. multiProxy answers 503 + Retry-After when the
@@ -1795,7 +1849,16 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// answered 413 here and never reaches Admit, so it spends no limiter
// token and no bcrypt comparison. Refusing junk must not cost a real
// visitor their attempts.
- loginPost := r.Method == http.MethodPost && r.URL.Path == gate.LoginPath
+ //
+ // A forward host is never a login POST here (fleet public routes spec
+ // §4.8): the hub does no gate work for it. Its row has no gate; the fleet
+ // edge holds the app's gate on its own row, renders the form and judges
+ // the password. So the body is not bounded, parsed or drained, the
+ // upstream is not re-resolved by `next` (a forward host has no path map
+ // here anyway), and the ungated-route 404 below does not fire: the POST
+ // reaches the fleet edge with its body and Content-Length intact.
+ loginPost := r.Method == http.MethodPost && r.URL.Path == gate.LoginPath &&
+ !up.route.IsForward()
if loginPost {
r.Body = http.MaxBytesReader(w, r.Body, gate.MaxFormBody)
if err := r.ParseForm(); err != nil {
@@ -2080,8 +2143,13 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !e.planThrottleAdmit(w, r, up) {
return
}
+ // A forward row is never cached here (fleet public routes spec §4.8): the
+ // hub cannot see the fleet edge's gate, so a gated page stored here would
+ // be served without the cookie, and an app's Carlos-Purge stops at its
+ // own box.
cacheable := e.cache != nil && (r.Method == http.MethodGet || r.Method == http.MethodHead) &&
- up.route.Kind != "status" && up.route.Kind != "static" && up.route.ImportGate == ""
+ up.route.Kind != "status" && up.route.Kind != "static" && up.route.ImportGate == "" &&
+ !up.route.IsForward()
var key CacheKey
if cacheable {
key = CacheKey{Host: host, Method: r.Method, Path: r.URL.Path, RawQuery: r.URL.RawQuery}
diff --git a/internal/edge/fleetforward.go b/internal/edge/fleetforward.go
new file mode 100644
index 000000000..dc67b361f
--- /dev/null
+++ b/internal/edge/fleetforward.go
@@ -0,0 +1,87 @@
+package edge
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// HubArmed reports whether this box is the hub (fleet public routes spec
+// §4.4, the plan's Global Constraints): CARLOS_TUNNEL_HOST set, trimmed, and
+// CARLOS_FLEET unset. The one definition of "hub": the edge's Reload, the
+// agent's bindings pass (internal/host hubArmed) and the edges-file writer
+// all read it here, so serving and publishing cannot disagree about which box
+// holds the forward rows.
+func HubArmed(getenv func(string) string) bool {
+ return strings.TrimSpace(getenv("CARLOS_TUNNEL_HOST")) != "" && getenv("CARLOS_FLEET") == ""
+}
+
+// FleetServeEligible decides whether rt may take the fleet arm: be served
+// through a fleet's tunnel (spec §4.4, with the controller's ruling on
+// invalid accounts). It is the one place the rule is written; Reload asks it
+// for every forward row and for every other row that reaches the fleet arm,
+// and the edges-file writer asks it the same question. owners maps a fleet's
+// name to its owning account, from this box's own fleets table; hub is
+// HubArmed on a box whose tunnels are enabled. why is a log fragment: the
+// reason for a refusal, or the note that an accountless row was served.
+//
+// - A forward row is eligible only on the hub, only inert (every
+// ForwardForbidden field zero), only fleet-placed on a fleet in owners,
+// and only when its raw Account is non-empty and equals the owner.
+// - Any other row that is fleet-placed and has no Tunnel (a Tunnel binding
+// takes its own arm first and is not this rule's business): an empty raw
+// Account is the approved pre-account compatibility case, served and
+// logged; a non-empty raw Account that fails release.ValidAccount is
+// refused, never mapped to OpsAccount by release.RouteAccount and passed
+// on the ops account's own fleet; otherwise RouteAccount must equal the
+// fleet's owner, and a fleet missing from owners is refused. hub does not
+// enter: whether such a row reaches the fleet arm is the caller's
+// dispatch (Reload: tunnels enabled), and wherever it does, the account
+// rule holds.
+// - Any other row is not this rule's business: eligible, nothing to log.
+//
+// The raw Account is read before RouteAccount, which turns an empty or
+// invalid account into OpsAccount.
+func FleetServeEligible(rt registry.Route, hub bool, owners map[string]string) (ok bool, why string) {
+ fleet, placed := registry.FleetPlacement(rt.Region)
+ if rt.IsForward() {
+ if !hub {
+ return false, "forward row on a box that is not the hub"
+ }
+ if !rt.InertForward() {
+ return false, "forward row carries a forbidden column"
+ }
+ if !placed {
+ return false, fmt.Sprintf("forward row is not fleet-placed (region %q)", rt.Region)
+ }
+ owner, known := owners[fleet]
+ switch {
+ case !known:
+ return false, fmt.Sprintf("fleet %q is not in this hub's fleets table", fleet)
+ case rt.Account == "":
+ return false, "forward row has no account"
+ case rt.Account != owner:
+ return false, fmt.Sprintf("account %q does not own fleet %q", rt.Account, fleet)
+ }
+ return true, ""
+ }
+ if !placed || rt.Tunnel != "" {
+ return true, ""
+ }
+ if rt.Account == "" {
+ return true, fmt.Sprintf("fleet-placed row has no account; served on fleet %q as before accounts", fleet)
+ }
+ if !release.ValidAccount(rt.Account) {
+ return false, fmt.Sprintf("fleet-placed row's account %q is not a valid account", rt.Account)
+ }
+ owner, known := owners[fleet]
+ switch {
+ case !known:
+ return false, fmt.Sprintf("fleet %q is not in this box's fleets table", fleet)
+ case release.RouteAccount(rt) != owner:
+ return false, fmt.Sprintf("account %q does not own fleet %q", rt.Account, fleet)
+ }
+ return true, ""
+}
diff --git a/internal/edge/fleetforward_test.go b/internal/edge/fleetforward_test.go
new file mode 100644
index 000000000..62876a26a
--- /dev/null
+++ b/internal/edge/fleetforward_test.go
@@ -0,0 +1,730 @@
+package edge
+
+// Fleet public routes, Task 4 (spec §4.4, §4.8, §4.12, §8 tests 5, 6, 9 tail
+// and 12): the hub serves a forward row through the fleet tunnel only when
+// FleetServeEligible says so, and does no gate, login or cache work for it.
+//
+// Accounts: the fleets' owner is "bah" and the second account "baj" (valid,
+// non-ops sqids, domains.Sqid(7) and Sqid(8)). Neither "bab" (OpsAccount) nor
+// the invalid "k3x" owns a fleet here, except in the one table case that
+// exists to show an invalid account is not mapped to OpsAccount and passed
+// on the ops account's own fleet (preflight 4.1).
+
+import (
+ "bytes"
+ "database/sql"
+ "fmt"
+ "io"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "reflect"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "golang.org/x/crypto/bcrypt"
+
+ "github.com/carlosframework/platform/internal/gate"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const (
+ fwdOwner = "bah" // owns fleets home and away
+ fwdOther = "baj" // owns no fleet
+ fwdBox1Tok = "box-1-token"
+ fwdBox2Tok = "box-2-token"
+ fwdT1Tok = "t1-token"
+)
+
+// forwardRow is an eligible forward row's declared fields for host on fleet.
+func forwardRow(host, fleet, account string) registry.Route {
+ return registry.Route{
+ Host: host, Kind: registry.KindForward, Slug: "shop", App: "shop",
+ Account: account, Region: registry.PlacementTarget(fleet), Channel: "production",
+ }
+}
+
+// forwardHubAndBox is the two-edge fixture. The hub is an Edge on its own
+// registry holding fleets home and away (both owned by fwdOwner) with active
+// boxes home/box-1 and away/box-2, and hubRows: forward rows written with
+// PutForward (Upsert refuses them), every other row with Upsert. Its tunnels
+// are armed as fleetTestEdge arms them, with one static client "t1" (so a
+// forward row whose tunnel column was corrupted to "t1" has a live channel to
+// leak to), and the process environment says this box is the hub
+// (CARLOS_TUNNEL_HOST set, CARLOS_FLEET empty), which Reload reads through
+// HubArmed.
+//
+// The box is a second Edge on a second registry holding boxRows, dialed in to
+// the hub as home/box-1 by the real tunnelclient loop (startFakeRemoteHost),
+// serving the box Edge itself, or boxHandler when it is non-nil.
+func forwardHubAndBox(t *testing.T, hubRows, boxRows []registry.Route, boxHandler http.Handler) (hubURL string, hub, box *Edge) {
+ t.Helper()
+ hubReg := openReg(t)
+ for _, f := range []string{"home", "away"} {
+ if err := hubReg.UpsertFleet(registry.Fleet{Name: f, Account: fwdOwner, Bucket: f + "-data"}); err != nil {
+ t.Fatalf("UpsertFleet(%s): %v", f, err)
+ }
+ }
+ for _, b := range []registry.FleetBox{
+ {Fleet: "home", Label: "box-1", TokenHash: sha256Hex(fwdBox1Tok), Status: "active"},
+ {Fleet: "away", Label: "box-2", TokenHash: sha256Hex(fwdBox2Tok), Status: "active"},
+ } {
+ if err := hubReg.AddFleetBox(b); err != nil {
+ t.Fatalf("AddFleetBox(%s/%s): %v", b.Fleet, b.Label, err)
+ }
+ }
+ for _, rt := range hubRows {
+ put := hubReg.Upsert
+ if rt.IsForward() {
+ put = hubReg.PutForward
+ }
+ if err := put(rt); err != nil {
+ t.Fatalf("hub row %s: %v", rt.Host, err)
+ }
+ }
+ hub, err := New(hubReg, nil)
+ if err != nil {
+ t.Fatalf("New(hub): %v", err)
+ }
+ t.Cleanup(hub.probers.Stop)
+ srv := httptest.NewServer(hub)
+ t.Cleanup(srv.Close)
+ u, err := url.Parse(srv.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("CARLOS_TUNNEL_HOST", u.Hostname())
+ t.Setenv("CARLOS_FLEET", "")
+ hub.EnableTunnels(NewTunnelHub(u.Hostname(), map[string]string{"t1": fwdT1Tok}))
+ if err := hub.Reload(); err != nil {
+ t.Fatalf("Reload(hub): %v", err)
+ }
+
+ boxReg := openReg(t)
+ for _, rt := range boxRows {
+ if err := boxReg.Upsert(rt); err != nil {
+ t.Fatalf("box row %s: %v", rt.Host, err)
+ }
+ }
+ box, err = New(boxReg, nil)
+ if err != nil {
+ t.Fatalf("New(box): %v", err)
+ }
+ t.Cleanup(box.probers.Stop)
+ var h http.Handler = box
+ if boxHandler != nil {
+ h = boxHandler
+ }
+ stop := startFakeRemoteHost(t, srv.URL, "home/box-1", fwdBox1Tok, h)
+ t.Cleanup(stop)
+ waitForTunnelState(t, hub.tunnels, "home/box-1", "connected", e2eReconnectBound)
+ return srv.URL, hub, box
+}
+
+// corruptRow writes value into host's routes column by raw SQL, behind every
+// registry writer (a hand edit, a bad migration, a future writer), asserts it
+// hit exactly one row, then reads the row back through a fresh
+// registry.Open(...).Get to prove the value persisted: the field the column
+// maps to (registry.ForwardForbidden) is no longer zero.
+func corruptRow(t *testing.T, regPath, host, column string, value any) {
+ t.Helper()
+ field := ""
+ for _, c := range registry.ForwardForbidden {
+ if c.Column == column {
+ field = c.Field
+ }
+ }
+ if field == "" {
+ t.Fatalf("corruptRow: %q is not a ForwardForbidden column", column)
+ }
+ db, err := sql.Open("sqlite", regPath)
+ if err != nil {
+ t.Fatalf("corruptRow: open: %v", err)
+ }
+ res, err := db.Exec(`UPDATE routes SET `+column+` = ? WHERE host = ?`, value, host)
+ if err != nil {
+ db.Close()
+ t.Fatalf("corruptRow(%s, %s): %v", host, column, err)
+ }
+ n, err := res.RowsAffected()
+ db.Close()
+ if err != nil || n != 1 {
+ t.Fatalf("corruptRow(%s, %s): %d rows affected (%v), want 1", host, column, n, err)
+ }
+ reg, err := registry.Open(regPath)
+ if err != nil {
+ t.Fatalf("corruptRow: reopen: %v", err)
+ }
+ defer reg.Close()
+ rt, err := reg.Get(host)
+ if err != nil || rt == nil {
+ t.Fatalf("corruptRow: Get(%s) = %v, %v", host, rt, err)
+ }
+ if reflect.ValueOf(*rt).FieldByName(field).IsZero() {
+ t.Fatalf("corruptRow: %s.%s (%s) reads back zero after the write", host, field, column)
+ }
+}
+
+// corruptValue is the value corruptRow writes for a column of type typ.
+func corruptValue(typ string) any {
+ if typ == "INTEGER" {
+ return 1
+ }
+ return "x"
+}
+
+// fwdDo sends one request to the hub with Host host and returns the response
+// with its body read. Redirects are not followed.
+func fwdDo(t *testing.T, hubURL, method, host, path, contentType string, body []byte) (*http.Response, []byte) {
+ t.Helper()
+ var rd io.Reader
+ if body != nil {
+ rd = bytes.NewReader(body)
+ }
+ req, err := http.NewRequest(method, hubURL+path, rd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = host
+ if contentType != "" {
+ req.Header.Set("Content-Type", contentType)
+ }
+ c := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+ resp, err := c.Do(req)
+ if err != nil {
+ t.Fatalf("%s %s%s (host %s): %v", method, hubURL, path, host, err)
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatalf("read body: %v", err)
+ }
+ return resp, b
+}
+
+// setStray sets the field named f of rt to a non-zero value of its type.
+func setStray(t *testing.T, rt *registry.Route, f string) {
+ t.Helper()
+ v := reflect.ValueOf(rt).Elem().FieldByName(f)
+ if !v.IsValid() {
+ t.Fatalf("Route has no field %s", f)
+ }
+ switch v.Kind() {
+ case reflect.String:
+ v.SetString("x")
+ case reflect.Bool:
+ v.SetBool(true)
+ case reflect.Int, reflect.Int64, reflect.Int32:
+ v.SetInt(1)
+ case reflect.Uint64, reflect.Uint32, reflect.Uint:
+ v.SetUint(1)
+ default:
+ t.Fatalf("setStray: field %s has kind %s", f, v.Kind())
+ }
+}
+
+func TestFleetServeEligible(t *testing.T) {
+ owners := map[string]string{"home": fwdOwner}
+ fwd := func(mut func(*registry.Route)) registry.Route {
+ rt := forwardRow("shop.example.com", "home", fwdOwner)
+ rt.Status, rt.Provisioned = "ready", true
+ if mut != nil {
+ mut(&rt)
+ }
+ return rt
+ }
+ hand := func(fleet, account string) registry.Route {
+ return registry.Route{Host: "hand.example.com", Kind: "instance", Status: "ready",
+ Region: registry.PlacementTarget(fleet), Account: account}
+ }
+ cases := []struct {
+ name string
+ rt registry.Route
+ hub bool
+ owners map[string]string
+ want bool
+ wantWhy bool // a log fragment is expected
+ }{
+ {"forward: eligible", fwd(nil), true, owners, true, false},
+ {"forward: hub off", fwd(nil), false, owners, false, true},
+ {"forward: owner mismatch", fwd(func(r *registry.Route) { r.Account = fwdOther }), true, owners, false, true},
+ {"forward: unknown fleet", fwd(func(r *registry.Route) { r.Region = registry.PlacementTarget("nowhere") }), true, owners, false, true},
+ {"forward: empty raw account", fwd(func(r *registry.Route) { r.Account = "" }), true, owners, false, true},
+ {"forward: empty raw account, fleet owned by empty account", fwd(func(r *registry.Route) { r.Account = "" }), true, map[string]string{"home": ""}, false, true},
+ {"forward: not fleet-placed", fwd(func(r *registry.Route) { r.Region = "" }), true, owners, false, true},
+ {"hand: empty raw account is served and logged", hand("home", ""), true, owners, true, true},
+ {"hand: the owner's account", hand("home", fwdOwner), true, owners, true, false},
+ {"hand: another valid account", hand("home", fwdOther), true, owners, false, true},
+ {"hand: invalid account k3x", hand("home", "k3x"), true, owners, false, true},
+ {"hand: invalid account on the ops account's fleet is not OpsAccount'd into a pass",
+ hand("ops", "!!"), true, map[string]string{"ops": release.OpsAccount}, false, true},
+ {"hand: owner's account, unknown fleet", hand("nowhere", fwdOwner), true, owners, false, true},
+ {"hand: explicit tunnel is not the fleet arm", func() registry.Route {
+ r := hand("home", fwdOther)
+ r.Tunnel = "t1"
+ return r
+ }(), true, owners, true, false},
+ }
+ for _, c := range cases {
+ ok, why := FleetServeEligible(c.rt, c.hub, c.owners)
+ if ok != c.want || (why != "") != c.wantWhy {
+ t.Errorf("%s: FleetServeEligible = (%v, %q), want ok=%v, why non-empty=%v", c.name, ok, why, c.want, c.wantWhy)
+ }
+ }
+ // One stray forbidden field, each in turn.
+ for _, f := range registry.ForwardForbidden {
+ rt := fwd(nil)
+ setStray(t, &rt, f.Field)
+ if ok, why := FleetServeEligible(rt, true, owners); ok || why == "" {
+ t.Errorf("forward with stray %s: FleetServeEligible = (%v, %q), want refused", f.Field, ok, why)
+ }
+ }
+}
+
+func TestReloadServesOnlyEligibleForwardRows(t *testing.T) {
+ hubURL, hub, _ := forwardHubAndBox(t, []registry.Route{
+ forwardRow("a.example.com", "home", fwdOwner),
+ forwardRow("b.example.com", "home", fwdOther),
+ forwardRow("c.example.com", "home", fwdOwner),
+ }, nil, namedHandler("box-1"))
+
+ var t1Hits sync.Map
+ stopT1 := startFakeRemoteHost(t, hubURL, "t1", fwdT1Tok, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ t1Hits.Store(r.Host, true)
+ io.WriteString(w, "t1")
+ }))
+ t.Cleanup(stopT1)
+ waitForTunnelState(t, hub.tunnels, "t1", "connected", e2eReconnectBound)
+
+ corruptRow(t, hub.reg.Path(), "c.example.com", "tunnel", "t1")
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if !hub.Allowed("a.example.com") {
+ t.Error("Allowed(a) = false, want true (eligible forward row)")
+ }
+ if hub.Allowed("b.example.com") {
+ t.Error("Allowed(b) = true, want false (its account does not own fleet home)")
+ }
+ if hub.Allowed("c.example.com") {
+ t.Error("Allowed(c) = true, want false (a stray tunnel column)")
+ }
+ if resp, body := fwdDo(t, hubURL, "GET", "a.example.com", "/", "", nil); resp.StatusCode != 200 || string(body) != "box-1" {
+ t.Errorf("GET a = %d %q, want 200 from box-1", resp.StatusCode, body)
+ }
+ fwdDo(t, hubURL, "GET", "c.example.com", "/", "", nil)
+ fwdDo(t, hubURL, "GET", "b.example.com", "/", "", nil)
+ t1Hits.Range(func(k, _ any) bool {
+ t.Errorf("static tunnel client t1 received a request for %v", k)
+ return true
+ })
+
+ // The hub test is the environment's, read on every Reload: a box that
+ // is a fleet box, or has no tunnel host, serves no forward row.
+ t.Setenv("CARLOS_FLEET", "home")
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if hub.Allowed("a.example.com") {
+ t.Error("Allowed(a) with CARLOS_FLEET set = true, want false (not the hub)")
+ }
+ t.Setenv("CARLOS_FLEET", "")
+ t.Setenv("CARLOS_TUNNEL_HOST", " ")
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if hub.Allowed("a.example.com") {
+ t.Error("Allowed(a) with a blank CARLOS_TUNNEL_HOST = true, want false (not the hub)")
+ }
+}
+
+func TestForwardServingRefusesEachForbiddenColumn(t *testing.T) {
+ hostOf := func(c registry.ForwardColumn) string {
+ return strings.ReplaceAll(c.Column, "_", "-") + ".example.com"
+ }
+ rows := []registry.Route{forwardRow("clean.example.com", "home", fwdOwner)}
+ for _, c := range registry.ForwardForbidden {
+ rows = append(rows, forwardRow(hostOf(c), "home", fwdOwner))
+ }
+ hubURL, hub, _ := forwardHubAndBox(t, rows, nil, namedHandler("box-1"))
+ for _, c := range registry.ForwardForbidden {
+ corruptRow(t, hub.reg.Path(), hostOf(c), c.Column, corruptValue(c.Type))
+ }
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if !hub.Allowed("clean.example.com") {
+ t.Fatal("the uncorrupted control row is not served")
+ }
+ unknown, unknownBody := fwdDo(t, hubURL, "GET", "never-registered.example.com", "/", "", nil)
+ for _, c := range registry.ForwardForbidden {
+ h := hostOf(c)
+ if hub.Allowed(h) {
+ t.Errorf("%s: Allowed = true with %s set, want false", c.Field, c.Column)
+ }
+ resp, body := fwdDo(t, hubURL, "GET", h, "/", "", nil)
+ if resp.StatusCode != unknown.StatusCode || string(body) != string(unknownBody) {
+ t.Errorf("%s: GET = %d %q, want the unknown-host answer %d %q", c.Field, resp.StatusCode, body, unknown.StatusCode, unknownBody)
+ }
+ }
+}
+
+// TestForwardResponseCarriesTheBoxVersionOnce is a pin: today's fleet arm
+// already forwards without stamping, because a forward row has no Version.
+// Shown failing by mutation (dropping the t.Version != "" guard on the
+// version stamp in Reload), not before the code.
+func TestForwardResponseCarriesTheBoxVersionOnce(t *testing.T) {
+ hubURL, _, _ := forwardHubAndBox(t, []registry.Route{forwardRow("shop.example.com", "home", fwdOwner)}, nil,
+ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Carlos-Version", "v1")
+ io.WriteString(w, "ok")
+ }))
+ resp, _ := fwdDo(t, hubURL, "GET", "shop.example.com", "/up", "", nil)
+ if got := resp.Header.Values("X-Carlos-Version"); !reflect.DeepEqual(got, []string{"v1"}) {
+ t.Fatalf("X-Carlos-Version = %q, want [v1]", got)
+ }
+}
+
+// countingBox answers every request cacheably and counts requests per host.
+type countingBox struct {
+ mu sync.Mutex
+ n map[string]int
+}
+
+func (b *countingBox) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ b.mu.Lock()
+ if b.n == nil {
+ b.n = map[string]int{}
+ }
+ b.n[r.Host]++
+ n := b.n[r.Host]
+ b.mu.Unlock()
+ w.Header().Set("Cache-Control", "public, max-age=300")
+ w.Header().Set("Content-Type", "text/plain")
+ fmt.Fprintf(w, "call %d", n)
+}
+
+func (b *countingBox) count(host string) int {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.n[host]
+}
+
+func TestForwardRowsAreNeverCached(t *testing.T) {
+ cb := &countingBox{}
+ // The positive control: a fleet-placed hand row (no account), served
+ // through the same tunnel to the same box, whose answer the hub DOES
+ // store, proving the cache is armed and the answer is cacheable.
+ hubURL, hub, _ := forwardHubAndBox(t, []registry.Route{
+ forwardRow("shop.example.com", "home", fwdOwner),
+ {Host: "hand.example.com", Kind: "instance", Status: "ready", Region: registry.PlacementTarget("home")},
+ }, nil, cb)
+ hub.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))
+ for i := 0; i < 2; i++ {
+ fwdDo(t, hubURL, "GET", "shop.example.com", "/page", "", nil)
+ fwdDo(t, hubURL, "GET", "hand.example.com", "/page", "", nil)
+ }
+ if n := cb.count("hand.example.com"); n != 1 {
+ t.Fatalf("control: the box saw %d requests for the hand row, want 1 (the cache must be armed and storing)", n)
+ }
+ if n := cb.count("shop.example.com"); n != 2 {
+ t.Fatalf("the box saw %d requests for the forward row, want 2 (never answered from the hub's cache)", n)
+ }
+}
+
+func TestForwardRowsSkipTheAssetCache(t *testing.T) {
+ _, hub, _ := forwardHubAndBox(t, []registry.Route{
+ forwardRow("shop.example.com", "home", fwdOwner),
+ {Host: "plain.example.com", Kind: "instance", Status: "ready", Addr: "127.0.0.1:1", Account: fwdOwner, App: "plain"},
+ }, nil, namedHandler("box-1"))
+ policy := HostAssets{Account: fwdOwner, App: "shop", Paths: []string{"/assets/"}, Gen: "g1", At: time.Now()}
+ local := &fakeLocalAssets{hosts: map[string]HostAssets{"shop.example.com": policy, "plain.example.com": policy}, builds: map[string]bool{}}
+ hub.assets.Store(&assetState{store: openLAStore(t), local: local, now: time.Now})
+ req := httptest.NewRequest(http.MethodGet, "/assets/app.js", nil)
+ m := hub.current()
+ if _, ok := hub.localAssetCatch(req, "plain.example.com", m["plain.example.com"]); !ok {
+ t.Fatal("control: the armed policy does not catch /assets/ for a non-forward row")
+ }
+ up, ok := m["shop.example.com"]
+ if !ok {
+ t.Fatal("the forward row is not served")
+ }
+ if _, ok := hub.localAssetCatch(req, "shop.example.com", up); ok {
+ t.Fatal("localAssetCatch = true for a forward row, want false")
+ }
+}
+
+// loginRecorder is a box that records what a login POST delivered.
+type loginRecorder struct {
+ mu sync.Mutex
+ got []loginSeen
+ page string
+}
+
+type loginSeen struct {
+ path, contentType string
+ length int64
+ body []byte
+}
+
+func (l *loginRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ l.mu.Lock()
+ l.got = append(l.got, loginSeen{path: r.URL.Path, contentType: r.Header.Get("Content-Type"), length: r.ContentLength, body: b})
+ l.mu.Unlock()
+ io.WriteString(w, "box")
+}
+
+func (l *loginRecorder) take() []loginSeen {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ out := l.got
+ l.got = nil
+ return out
+}
+
+func multipartLogin(t *testing.T, password, next string) ([]byte, string) {
+ t.Helper()
+ var buf bytes.Buffer
+ mw := multipart.NewWriter(&buf)
+ if err := mw.WriteField("password", password); err != nil {
+ t.Fatal(err)
+ }
+ if err := mw.WriteField("next", next); err != nil {
+ t.Fatal(err)
+ }
+ if err := mw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes(), mw.FormDataContentType()
+}
+
+func TestForwardLoginBodyReachesTheFleetEdge(t *testing.T) {
+ other, _ := hostEchoBackend(t, "other app")
+ rec := &loginRecorder{}
+ hubURL, hub, _ := forwardHubAndBox(t, []registry.Route{
+ forwardRow("shop.example.com", "home", fwdOwner),
+ {Host: "other.example.com", Kind: "instance", Status: "ready", Addr: other.Listener.Addr().String(), Account: fwdOwner, App: "other"},
+ }, nil, rec)
+
+ const form = "application/x-www-form-urlencoded"
+ mp, mpType := multipartLogin(t, "right", "/up")
+ for _, c := range []struct {
+ name, contentType string
+ body []byte
+ }{
+ {"urlencoded, right", form, []byte("password=right&next=%2Fup")},
+ {"urlencoded, wrong", form, []byte("password=wrong&next=%2Fup")},
+ {"multipart", mpType, mp},
+ } {
+ resp, body := fwdDo(t, hubURL, http.MethodPost, "shop.example.com", gate.LoginPath, c.contentType, c.body)
+ if resp.StatusCode != 200 || string(body) != "box" {
+ t.Errorf("%s: hub answered %d %q, want the box's 200 %q", c.name, resp.StatusCode, body, "box")
+ }
+ seen := rec.take()
+ if len(seen) != 1 {
+ t.Errorf("%s: the box saw %d requests, want 1", c.name, len(seen))
+ continue
+ }
+ s := seen[0]
+ if s.path != gate.LoginPath || s.contentType != c.contentType || !bytes.Equal(s.body, c.body) || s.length != int64(len(c.body)) {
+ t.Errorf("%s: the box received path %q, type %q, Content-Length %d, body %q; want %q, %q, %d, %q",
+ c.name, s.path, s.contentType, s.length, s.body, gate.LoginPath, c.contentType, len(c.body), c.body)
+ }
+ }
+
+ // A path row at the hub for the forward host's /shop prefix is not
+ // folded: the login POST whose next names it, and a GET under it, both
+ // reach the box (the fleet edge holds the app's own paths).
+ if err := hub.reg.UpsertPath(registry.RoutePath{Host: "shop.example.com", Prefix: "shop", Target: "other.example.com", Account: fwdOwner, App: "other"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ body := []byte("password=right&next=%2Fshop%2Fx")
+ if resp, got := fwdDo(t, hubURL, http.MethodPost, "shop.example.com", gate.LoginPath, form, body); resp.StatusCode != 200 || string(got) != "box" {
+ t.Errorf("login POST with next=/shop/x: hub answered %d %q, want the box", resp.StatusCode, got)
+ }
+ if seen := rec.take(); len(seen) != 1 || !bytes.Equal(seen[0].body, body) {
+ t.Errorf("login POST with next=/shop/x: the box saw %+v, want the body byte for byte", seen)
+ }
+ if resp, got := fwdDo(t, hubURL, http.MethodGet, "shop.example.com", "/shop/x", "", nil); resp.StatusCode != 200 || string(got) != "box" {
+ t.Errorf("GET /shop/x: hub answered %d %q, want the box (no path map at the hub for a forward host)", resp.StatusCode, got)
+ }
+ rec.take()
+}
+
+func TestForwardLoginThroughTheRealFleetGate(t *testing.T) {
+ hashB, err := bcrypt.GenerateFromPassword([]byte("right"), bcrypt.MinCost)
+ if err != nil {
+ t.Fatal(err)
+ }
+ hash := string(hashB)
+ app, _ := hostEchoBackend(t, "the app")
+ hubURL, hub, box := forwardHubAndBox(t,
+ []registry.Route{
+ forwardRow("shop.example.com", "home", fwdOwner),
+ // The comparison: a platform-hosted gated row the hub serves itself.
+ {Host: "gated.example.com", Kind: "instance", Status: "ready", Addr: app.Listener.Addr().String(), Account: fwdOwner, App: "gated", Gate: hash},
+ },
+ []registry.Route{{Host: "shop.example.com", Kind: "instance", Status: "ready", Addr: app.Listener.Addr().String(), Account: fwdOwner, App: "shop"}},
+ nil)
+ if err := box.reg.SetGate("shop.example.com", hash); err != nil {
+ t.Fatal(err)
+ }
+ if err := box.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if got := hub.current()["shop.example.com"].route.Gate; got != "" {
+ t.Fatalf("the hub's forward row carries a gate %q", got)
+ }
+ gateCookie := func(resp *http.Response) string {
+ for _, c := range resp.Cookies() {
+ if c.Name == gate.CookieName {
+ return c.Value
+ }
+ }
+ return ""
+ }
+ const form = "application/x-www-form-urlencoded"
+
+ // Without a cookie: the fleet edge's form, through the hub.
+ if resp, _ := fwdDo(t, hubURL, "GET", "shop.example.com", "/up", "", nil); resp.StatusCode != http.StatusUnauthorized {
+ t.Fatalf("GET /up without a cookie = %d, want the fleet edge's 401 form", resp.StatusCode)
+ }
+
+ resp, _ := fwdDo(t, hubURL, http.MethodPost, "shop.example.com", gate.LoginPath, form, []byte("password=right&next=%2Fup"))
+ if resp.StatusCode != http.StatusSeeOther || resp.Header.Get("Location") != "/up" {
+ t.Fatalf("right password: %d -> %q, want 303 -> /up", resp.StatusCode, resp.Header.Get("Location"))
+ }
+ c := gateCookie(resp)
+ if c == "" || !gate.Verify(c, "shop.example.com", hash, time.Now()) {
+ t.Fatalf("right password: cookie %q does not verify for the box's row", c)
+ }
+ // The hub passes the cookie through untouched, and the fleet edge admits it.
+ req, err := http.NewRequest("GET", hubURL+"/up", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = "shop.example.com"
+ req.AddCookie(&http.Cookie{Name: gate.CookieName, Value: c})
+ got, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ gotBody, _ := io.ReadAll(got.Body)
+ got.Body.Close()
+ if got.StatusCode != 200 || string(gotBody) != "the app" {
+ t.Fatalf("GET /up with the cookie = %d %q, want 200 from the app", got.StatusCode, gotBody)
+ }
+
+ // The wrong password and the multipart form, each compared with what the
+ // hub's own gated row answers the same request (the host name is the one
+ // difference in the page).
+ norm := func(b []byte, host string) string { return strings.ReplaceAll(string(b), host, "HOST") }
+ mp, mpType := multipartLogin(t, "right", "/up")
+ for _, c := range []struct {
+ name, contentType string
+ body []byte
+ }{
+ {"wrong password", form, []byte("password=wrong&next=%2Fup")},
+ {"multipart, right password", mpType, mp},
+ } {
+ fr, fb := fwdDo(t, hubURL, http.MethodPost, "shop.example.com", gate.LoginPath, c.contentType, c.body)
+ pr, pb := fwdDo(t, hubURL, http.MethodPost, "gated.example.com", gate.LoginPath, c.contentType, c.body)
+ if fr.StatusCode != http.StatusUnauthorized || gateCookie(fr) != "" {
+ t.Errorf("%s through the hub: %d, cookie %q; want 401 and no cookie", c.name, fr.StatusCode, gateCookie(fr))
+ }
+ if fr.StatusCode != pr.StatusCode || gateCookie(pr) != "" || norm(fb, "shop.example.com") != norm(pb, "gated.example.com") {
+ t.Errorf("%s: forward answer %d %q differs from the platform-hosted gated route's %d %q", c.name, fr.StatusCode, fb, pr.StatusCode, pb)
+ }
+ }
+}
+
+func TestUngatedLoginPostStill404s(t *testing.T) {
+ backend, seen := hostEchoBackend(t, "ungated app")
+ hubURL, _, _ := forwardHubAndBox(t, []registry.Route{
+ {Host: "plain.example.com", Kind: "instance", Status: "ready", Addr: backend.Listener.Addr().String(), Account: fwdOwner, App: "plain"},
+ }, nil, namedHandler("box-1"))
+ resp, _ := fwdDo(t, hubURL, http.MethodPost, "plain.example.com", gate.LoginPath, "application/x-www-form-urlencoded", []byte("password=right&next=%2Fup"))
+ if resp.StatusCode != http.StatusNotFound {
+ t.Fatalf("login POST to an ungated non-forward row = %d, want 404", resp.StatusCode)
+ }
+ if *seen != "" {
+ t.Fatal("the ungated app received the login POST")
+ }
+}
+
+// TestForwardRowMovedToAnotherFleetGoesToThatFleetsBox is spec §8 test 9's
+// tail (preflight 4.6): a forward row moved home -> away (same account)
+// while home's binding still names box-1 goes to away's box, not home's.
+func TestForwardRowMovedToAnotherFleetGoesToThatFleetsBox(t *testing.T) {
+ hubURL, hub, _ := forwardHubAndBox(t, []registry.Route{forwardRow("shop.example.com", "home", fwdOwner)}, nil, namedHandler("box-1"))
+ stop2 := startFakeRemoteHost(t, hubURL, "away/box-2", fwdBox2Tok, namedHandler("box-2"))
+ t.Cleanup(stop2)
+ waitForTunnelState(t, hub.tunnels, "away/box-2", "connected", e2eReconnectBound)
+
+ if changed, err := hub.reg.SetFleetBoxIf("shop.example.com", "home", "box-1"); err != nil || !changed {
+ t.Fatalf("bind to home/box-1: changed=%v err=%v", changed, err)
+ }
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if resp, body := fwdDo(t, hubURL, "GET", "shop.example.com", "/", "", nil); resp.StatusCode != 200 || string(body) != "box-1" {
+ t.Fatalf("before the move: %d %q, want box-1", resp.StatusCode, body)
+ }
+
+ if err := hub.reg.PutForward(forwardRow("shop.example.com", "away", fwdOwner)); err != nil {
+ t.Fatal(err)
+ }
+ // The bindings pass resumes with home's unchanged binding.
+ if changed, err := hub.reg.SetFleetBoxIf("shop.example.com", "home", "box-1"); err != nil || changed {
+ t.Fatalf("home's binding after the move: changed=%v err=%v, want no row changed", changed, err)
+ }
+ if rt, err := hub.reg.Get("shop.example.com"); err != nil || rt == nil || rt.FleetBox != "" {
+ t.Fatalf("stored row after the move: %+v, %v; want an empty FleetBox", rt, err)
+ }
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if resp, body := fwdDo(t, hubURL, "GET", "shop.example.com", "/", "", nil); resp.StatusCode != 200 || string(body) != "box-2" {
+ t.Fatalf("after the move: %d %q, want away's box-2", resp.StatusCode, body)
+ }
+}
+
+// TestReloadRefusesAHandFleetRowOfAnotherAccount: a non-forward fleet-placed
+// row (a hand row) takes the fleet arm only when FleetServeEligible admits
+// it: accountless (served, as before accounts), or its raw account owns the
+// fleet. Another account's row, or an invalid account's, gets no map entry
+// rather than a proxy into a fleet it does not own. Intended (spec §4.4);
+// Task 14 inventories such rows before the roll (preflight 1.22).
+func TestReloadRefusesAHandFleetRowOfAnotherAccount(t *testing.T) {
+ hand := func(host, account string) registry.Route {
+ return registry.Route{Host: host, Kind: "instance", Status: "ready", Region: registry.PlacementTarget("home"), Account: account}
+ }
+ hubURL, hub, _ := forwardHubAndBox(t, []registry.Route{
+ hand("accountless.example.com", ""),
+ hand("owner.example.com", fwdOwner),
+ hand("other.example.com", fwdOther),
+ hand("invalid.example.com", "k3x"),
+ }, nil, namedHandler("box-1"))
+ for host, want := range map[string]bool{
+ "accountless.example.com": true,
+ "owner.example.com": true,
+ "other.example.com": false,
+ "invalid.example.com": false,
+ } {
+ if got := hub.Allowed(host); got != want {
+ t.Errorf("Allowed(%s) = %v, want %v", host, got, want)
+ }
+ resp, body := fwdDo(t, hubURL, "GET", host, "/", "", nil)
+ if served := resp.StatusCode == 200 && string(body) == "box-1"; served != want {
+ t.Errorf("GET %s = %d %q, served through the fleet = %v, want %v", host, resp.StatusCode, body, served, want)
+ }
+ }
+}
diff --git a/internal/host/hub.go b/internal/host/hub.go
index bdc7f36cf..9edeca39f 100644
--- a/internal/host/hub.go
+++ b/internal/host/hub.go
@@ -1,6 +1,6 @@
package host
-import "strings"
+import "github.com/carlosframework/platform/internal/edge"
// hubArmed reports whether this box is the hub: the box that holds the
// tunnel's reserved hostname (CARLOS_TUNNEL_HOST set) and is not itself a
@@ -8,6 +8,8 @@ import "strings"
// fleet arm serves, so only the hub runs the bindings pass (fleet public
// routes spec §4.5 step 4); every other platform box reading every fleet's
// bindings was work with nothing to apply.
-func hubArmed(getenv func(string) string) bool {
- return strings.TrimSpace(getenv("CARLOS_TUNNEL_HOST")) != "" && getenv("CARLOS_FLEET") == ""
-}
+//
+// The test itself is edge.HubArmed, the one definition the edge's Reload
+// and the edges-file writer read too, so the box that serves forward rows,
+// the box that publishes them and the box that binds them are one box.
+func hubArmed(getenv func(string) string) bool { return edge.HubArmed(getenv) }