carlos / platform Public

Fleet public routes Task 13: the production-wired witness

TestFleetAppServesThroughTheHub assembles a real console, a real hub
(edge.New on the console's registry, provisioned through
host.BoxProvisionConfig) and a real fleet box (its own edge and registry,
its pass over the fleetapi store door, its release staged by
release.Pass) connected by tunnelclient.Loop, with every member step
through the built carlos CLI and no hand rows or fabricated records.

It proves a fleet-placed app serves at its public name through the
hub's TLS listener: the box's password gate, X-Carlos-Version once, a
429 from the hub only, an instance catch-all name, 503 while the box is
detached and 200 after it is added back, the row retired and the name
refused once the app is trashed, and a second real account's record on
the fleet judged and refused by the owner rule.

The instance runs a test-only tiny server, built in the test and shipped
through the console, started from the staged path with its socket on
fd 3; it is served by address because provision.SocketDir is
/run/carlos.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 12eeecee299ce1be5ab27ced2d013188ca9adeb0 parent 409d43d
1 file changed, +756 −0
  • fleet_public_routes_e2e_test.go +756 −0

Intent

Human

<task-notification> <task-id>a001a99eeac2e5ee4</task-id> <tool-use-id>toolu_01Eai11RYvz1c4ZvdcJxAKCb</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a001a99eeac2e5ee4.output</output-file> <status>completed</status> <summary>Agent "Implement Task 12: switch on" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE_WITH_CONCERNS (scope notes only; nothing is failing) Commit: `409d43d6` on design-fleet-public-routes (base f68b4fae). Not pushed. Tests: the ruled `-run` set passes (6 tests and 3 budget subtests), and the wider `internal/host` and `internal/provision` targeted runs pass. The red state was a compile failure (`undefined: BoxProvisionConfig`), as ruling #18 asked. The rename alone then failed both new tests on behaviour. Seven mutations each made a test fail. Build, vet, gofmt and the darwin, windows and linux/arm64 cross-builds are clean. - **Switch-on:** on the hub, `BoxProvisionConfig` sets `FleetOwners` from `hubFleetOwners(reg)`, which reads the fleets table on every call. Other boxes leave it nil and keep retiring forward rows. Both loops call `BoxProvisionConfig(reg, os.Getenv, judge, configure)`. The source pins and the four test callers are migrated. - **Same owners as the edge:** `fleetArmInputs` now gets its owners from `hubFleetOwners`, so the forward phase and the edge's verdict read one map. A parity assertion checks this. - **Request budget:** the steady-state difference matches §6 exactly, so §6 needed no change. - One fleet app: one trash-marker GET, two telemetry GETs (index off) and one limits GET. No manifest, seed, policy, retention, channel-pointer or record reads for it, and nothing else differs. - With an instance catch-all: exactly one more List of `apps/bah/shop/instances/`. - With two instances sharing a label: a record GET and a slot GET more for each host. - The edges file gets one extra PUT when the forward row appears, and nothing is written in steady state. - **Census:** two units are this task's. `fastConvergeLoop` changed body only (read sites unchanged, keeps authority); reverting its one call takes it off the card. `hubFleetOwners` is new and carries the reads Task 6 listed under `fleetArmInputs`, which leaves the card. Neither `BoxProvisionConfig` nor `instancesLoop` shows; the seal is unchanged. Spec §7 now has a "Task 12's card" entry. Concerns: 1. Telemetry was measured with the change index off. The index-armed row of §6 is not exercised. 2. "Before" is today's hub with the forward phase off, over an identical bucket, so the fleet app's records are in both. A world with no `shop` record at all would add one record-body GET, which every platform box already pays. 3. `edge.Reload` still builds its owner map inline from the same `ListFleets`. The two agree because they read one table, but they are not one function. Sharing it would touch `internal/edge` and `Edge.Reload`'s census entry, so I left it for the whole-branch review. 4. Policy reads are one GET per in-scope app per pass on both hubs, because the test has no armed policy cache. The fleet app gets none. Scratch files are removed and nothing is left running. The full report is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-public-routes/.superpowers/sdd/2026-10-30-fleet-public-routes/task-12-report.md`.</result> <usage><subagent_tokens>213778</subagent_tokens><tool_uses>94</tool_uses><duration_ms>1107237</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a5b7de8c197baf926</task-id> <tool-use-id>toolu_01P5pVMUhRYP6JXy6XC1e6sw</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a5b7de8c197baf926.output</output-file> <status>failed</status> <summary>Agent "Review Task 12: switch on" failed: Agent terminated early due to an API error: You've hit your 5-hour limit · resets 4:20pm (Europe/Dublin) (error type rate_limit, HTTP 429, request id req_011CgYgnEqThs22ivzzYNPrK, model sent to the API: claude-opus-5-5)</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once. This agent's work so far is saved. The limit resets at 4:20pm (Europe/Dublin). Once its requests are accepted again, send the agent a message (SendMessage) to let it continue from where it stopped instead of starting a new agent.</note> </task-notification>

Human

continue

Human

continue

Attributed to this commit: 26.5 g CO₂e (3,342,609 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-fleet-public-routes, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/fleet_public_routes_e2e_test.go b/fleet_public_routes_e2e_test.go
new file mode 100644
index 000000000..66ff7935f
--- /dev/null
+++ b/fleet_public_routes_e2e_test.go
@@ -0,0 +1,756 @@
+// The production-wired witness for fleet public routes (spec
+// docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md §8, plan
+// Task 13): a fleet-placed app serves at its public name through the hub,
+// end to end, with no hand-written registry row and no fabricated record.
+//
+// Everything in it is a production constructor or a production verb:
+//
+// - the console is console.NewServer over a temp registry and a DirStore,
+// as deploy_region_e2e_test.go runs it, and every member action is the
+// built carlos binary (buildCarlos) speaking to it as a signed-in person;
+// - the hub is edge.New on the console's own registry file, armed with
+// EnableStatic and EnableTunnels the way enableTunnelsFromEnv arms it,
+// and its provisioning pass is provision.Reconcile with
+// host.BoxProvisionConfig, the function both of the agent's provisioning
+// loops call;
+// - the fleet box is a second edge.New on its own registry, whose pass is
+// the same Reconcile and BoxProvisionConfig over a fleetapi.New store
+// (the store door, with the token `carlos fleets add-box` printed), whose
+// release is staged and stamped by release.Pass (the root adopt pass),
+// and which dials the hub with tunnelclient.Loop.
+//
+// It runs in one process rather than as subprocesses of the agents because
+// an unprivileged agent cannot stage a release (the stage is relayed to
+// root, internal/host/stagerelay.go) or run an instance unit; a harness of
+// the real agents would have to fake root.
+//
+// The hub's and the box's passes share the process's globals that
+// BoxProvisionConfig wires (armedPolicyCache, boxLifetimes and
+// noteSizeChanged, internal/host/agent.go): in production each box is its
+// own process. Accepted (preflight 1.16): nothing in this test reads the
+// lifetime index, and both passes run on this goroutine, one after the
+// other.
+//
+// Where the test stands in for something production does:
+//
+// - TLS admission. Production admits a name through issuerHostPolicy ->
+// deploymentHost inside edge.Run's TLS chain, which is unexported. With
+// one hub and no other box's edges file, deploymentHost gives Allowed's
+// answer, so the hub's listener here is an httptest TLS server whose
+// GetCertificate refuses every SNI name hub.Allowed refuses.
+// - The instance's process. provision.SocketDir is the constant
+// /run/carlos, which an unprivileged test cannot bind, so the instance
+// is created with --addr (an upstream address on loopback) and the test
+// starts the staged binary itself, handing it the listening socket on
+// fd 3 as a systemd socket unit would. The binary is a test-only fixture
+// (fprTinyServer), built here and shipped through the console like any
+// release. Pointing an instance at an address is an operator's act, so
+// the member holds the operator bit, granted with the store call the
+// console box's `console operator grant` makes.
+// - The box's tunnel and store door. They dial the hub's plain listener
+// (the same edge), because the tunnel client checks the hub's
+// certificate against the system roots; every public request goes
+// through the TLS listener.
+//
+// WebSockets do not cross the fleet tunnel today (amadan #471), so nothing
+// here sends an upgrade.
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/fleetapi"
+ "github.com/carlosframework/platform/internal/gate"
+ "github.com/carlosframework/platform/internal/host"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/tunnelclient"
+)
+
+// fprTinyServer is the release the witness ships: a server that takes its
+// listening socket on fd 3, as a socket-activated unit does, answers every
+// path with its own name, and counts the requests for /limited, which it
+// reports at /count.
+const fprTinyServer = `package main
+
+import (
+ "fmt"
+ "net"
+ "net/http"
+ "os"
+ "sync/atomic"
+)
+
+func main() {
+ ln, err := net.FileListener(os.NewFile(3, "listener"))
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ var limited atomic.Int64
+ http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/count":
+ fmt.Fprint(w, limited.Load())
+ return
+ case "/limited":
+ limited.Add(1)
+ }
+ fmt.Fprintf(w, "shop %s", r.URL.Path)
+ }))
+}
+`
+
+// fprBuildTinyServer builds fprTinyServer for this machine, in its own
+// module so nothing of this repository's module graph is involved.
+func fprBuildTinyServer(t *testing.T) string {
+ t.Helper()
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module example.com/tinyserver\n\ngo 1.22\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte(fprTinyServer), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ out := filepath.Join(dir, "shop")
+ cmd := exec.Command("go", "build", "-trimpath", "-o", out, ".")
+ cmd.Dir = dir
+ cmd.Env = append(os.Environ(), "CGO_ENABLED=0", "GOWORK=off", "GOFLAGS=-buildvcs=false")
+ if b, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("build the tiny server: %v\n%s", err, b)
+ }
+ return out
+}
+
+// fprLogTap copies the process's log output to a buffer the test can read,
+// as well as to wherever it went before.
+type fprLogTap struct {
+ mu sync.Mutex
+ buf bytes.Buffer
+}
+
+func (l *fprLogTap) Write(p []byte) (int, error) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.buf.Write(p)
+}
+
+func (l *fprLogTap) String() string {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.buf.String()
+}
+
+func (l *fprLogTap) Reset() {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ l.buf.Reset()
+}
+
+// fprEnv is a getenv over a fixed set, for a pass's BoxProvisionConfig.
+func fprEnv(kv map[string]string) func(string) string {
+ return func(k string) string { return kv[k] }
+}
+
+// errNotAdmitted is the hub listener's refusal of an SNI name hub.Allowed
+// refuses.
+var errNotAdmitted = errors.New("not admitted")
+
+// fprHub is the hub as a client sees it: its TLS listener, reached by
+// address, with the host as SNI and Host.
+type fprHub struct {
+ t *testing.T
+ addr string // 127.0.0.1:port of the TLS listener
+}
+
+// transport is a client transport presenting host as SNI. The certificate
+// is not checked: the assertion is admission, not the test CA.
+func (h fprHub) transport(host string, keepAlive bool) *http.Transport {
+ return &http.Transport{
+ TLSClientConfig: &tls.Config{ServerName: host, InsecureSkipVerify: true},
+ DisableKeepAlives: !keepAlive,
+ Proxy: nil,
+ }
+}
+
+// do sends one request for host to the hub on a fresh connection and reads
+// the whole answer. Redirects are not followed: a browser's next request is
+// the test's next call.
+func (h fprHub) do(method, host, path string, body io.Reader, hdr http.Header) (*http.Response, string, error) {
+ tr := h.transport(host, false)
+ defer tr.CloseIdleConnections()
+ c := &http.Client{Transport: tr, Timeout: 20 * time.Second,
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+ req, err := http.NewRequest(method, "https://"+h.addr+path, body)
+ if err != nil {
+ return nil, "", err
+ }
+ req.Host = host
+ for k, v := range hdr {
+ req.Header[k] = v
+ }
+ resp, err := c.Do(req)
+ if err != nil {
+ return nil, "", err
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(resp.Body)
+ return resp, string(b), err
+}
+
+func (h fprHub) mustDo(method, host, path string, body io.Reader, hdr http.Header) (*http.Response, string) {
+ h.t.Helper()
+ resp, b, err := h.do(method, host, path, body, hdr)
+ if err != nil {
+ h.t.Fatalf("%s https://%s%s: %v", method, host, path, err)
+ }
+ return resp, b
+}
+
+// handshake opens a fresh TLS connection to the hub with SNI host and
+// reports the handshake's error.
+func (h fprHub) handshake(host string) error {
+ d := &net.Dialer{Timeout: 10 * time.Second}
+ c, err := tls.DialWithDialer(d, "tcp", h.addr, &tls.Config{ServerName: host, InsecureSkipVerify: true})
+ if err != nil {
+ return err
+ }
+ return c.Close()
+}
+
+var fprFormNext = regexp.MustCompile(`<input type="hidden" name="next" value="([^"]*)">`)
+var fprFormAction = regexp.MustCompile(`<form method="post" action="([^"]*)">`)
+
+// login posts the gate's form back as a browser sends it: to the form's
+// action, with its hidden next field, the password typed, and the page's
+// own origin. It returns the answer.
+func (h fprHub) login(host, page, password string) (*http.Response, string) {
+ h.t.Helper()
+ action, next := fprFormAction.FindStringSubmatch(page), fprFormNext.FindStringSubmatch(page)
+ if action == nil || next == nil {
+ h.t.Fatalf("no login form to post back on %s:\n%s", host, page)
+ }
+ form := url.Values{"next": {next[1]}, "password": {password}}
+ return h.mustDo(http.MethodPost, host, action[1], strings.NewReader(form.Encode()), http.Header{
+ "Content-Type": {"application/x-www-form-urlencoded"},
+ "Origin": {"https://" + host},
+ })
+}
+
+// signIn posts the right password back through page's form and returns the
+// Cookie header a browser would send from then on.
+func (h fprHub) signIn(host, page, password string) http.Header {
+ h.t.Helper()
+ resp, _ := h.login(host, page, password)
+ for _, c := range resp.Cookies() {
+ if c.Name == gate.CookieName && resp.StatusCode == http.StatusSeeOther {
+ return http.Header{"Cookie": {c.Name + "=" + c.Value}}
+ }
+ }
+ h.t.Fatalf("right password on %s = %d %v, want 303 with the gate cookie", host, resp.StatusCode, resp.Cookies())
+ return nil
+}
+
+// fprCount asks the instance directly how many /limited requests reached it.
+func fprCount(t *testing.T, addr string) int {
+ t.Helper()
+ resp, err := http.Get("http://" + addr + "/count")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ b, _ := io.ReadAll(resp.Body)
+ var n int
+ if _, err := fmt.Sscan(string(b), &n); err != nil {
+ t.Fatalf("count %q: %v", b, err)
+ }
+ return n
+}
+
+// isLoginForm reports whether an answer is the gate's login page.
+func isLoginForm(resp *http.Response, body string) bool {
+ return resp.StatusCode == http.StatusUnauthorized && strings.Contains(body, `name="password"`) &&
+ strings.Contains(body, "action=\""+gate.LoginPath+"\"")
+}
+
+func TestFleetAppServesThroughTheHub(t *testing.T) {
+ bin := buildCarlos(t) // first: useTempCredentials changes directory
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ ctx := context.Background()
+
+ // The process environment is the hub's (Reload reads HubArmed from it),
+ // and both edges are built after it: the rate mode is read once, in
+ // edge.New (Astra plan R3 P1-2).
+ const tunnelHost = "127.0.0.1"
+ t.Setenv("CARLOS_RATE_LIMIT", "enforce")
+ t.Setenv("CARLOS_TUNNEL_HOST", tunnelHost)
+ t.Setenv("CARLOS_FLEET", "")
+ t.Setenv("CARLOS_REGION", "")
+
+ tap := &fprLogTap{}
+ prevLog := log.Writer()
+ log.SetOutput(io.MultiWriter(prevLog, tap))
+ t.Cleanup(func() { log.SetOutput(prevLog) })
+
+ tmp := t.TempDir()
+ store := release.NewDirStore(filepath.Join(tmp, "store"))
+ seed, pubB64, err := release.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ priv, err := release.ParseSigningKey(seed, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := release.ParsePublicKey(pubB64, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // --- the console, on the hub's registry file ---------------------------
+ regPath := filepath.Join(tmp, "registry.db")
+ hubReg, err := registry.Open(regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { hubReg.Close() }) // registered first, so it runs after everything that uses it
+ cst, err := console.Open(filepath.Join(tmp, "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cst.Close() })
+ var srv *console.Server
+ cts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv.ServeHTTP(w, r) }))
+ t.Cleanup(cts.Close)
+ srv, err = console.NewServer(console.Config{
+ Origin: cts.URL, Keymail: "http://keymail.invalid",
+ Registry: regPath, Releases: store, ReleasePub: pub, Key: priv,
+ // The apps domain is a level down so that a custom parent under
+ // example.com is not under it: the console refuses an instance
+ // catch-all whose parent is (catchallParentRefused).
+ AppScheme: "https", AppsDomain: "apps.example.com",
+ }, cst)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const member = "paul@keymail.dev"
+ // The member holds the operator bit, granted as the console box's own
+ // `console operator grant` grants it (cmd/console): only an operator may
+ // point an instance at an upstream address, which is how this test's
+ // instance is served (see the file comment).
+ if err := cst.SetOperator(member, true); err != nil {
+ t.Fatal(err)
+ }
+ token, expiresAt := e2eDeviceLogin(t, cts.URL, cst, member, "e2e@laptop")
+ creds := filepath.Join(t.TempDir(), "credentials")
+ e2eWriteCredential(t, creds, cts.URL, member, token, expiresAt)
+ cliReg := filepath.Join(t.TempDir(), "cli-registry.db")
+ carlos := func(args ...string) (string, error) {
+ t.Helper()
+ cmd := exec.Command(bin, args...)
+ cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+creds, "CARLOS_DEPLOYMENT_BUCKET=", "CARLOS_DEPLOYMENT_DIR=")
+ cmd.Dir = t.TempDir()
+ out, err := cmd.CombinedOutput()
+ return string(out), err
+ }
+ mustCarlos := func(args ...string) string {
+ t.Helper()
+ out, err := carlos(args...)
+ if err != nil {
+ t.Fatalf("carlos %s: %v\n%s", strings.Join(args, " "), err, out)
+ }
+ t.Logf("carlos %s:\n%s", strings.Join(args, " "), out)
+ return out
+ }
+ sqidOf := func(out string) string {
+ t.Helper()
+ m := regexp.MustCompile(`(?m)^\s*sqid:\s+(\S+)\s*$`).FindStringSubmatch(out)
+ if m == nil {
+ t.Fatalf("no sqid in:\n%s", out)
+ }
+ return m[1]
+ }
+
+ // --- the hub: its edge on the console's registry ------------------------
+ hubEnv := fprEnv(map[string]string{"CARLOS_TUNNEL_HOST": tunnelHost, "CARLOS_DATA_DIR": filepath.Join(tmp, "hub-data")})
+ hub, err := edge.New(hubReg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Every agent arms a usage meter on its edge; here it is how the test
+ // tells which edge refused a request.
+ hubMeter := edge.NewUsageMeter()
+ hub.EnableUsage(hubMeter)
+ hub.EnableStatic(store, pub, filepath.Join(tmp, "hub-static"))
+ hub.EnableTunnels(edge.NewTunnelHub(tunnelHost, nil))
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ hubTLS := httptest.NewUnstartedServer(hub)
+ hubTLS.TLS = &tls.Config{GetCertificate: func(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ if !hub.Allowed(h.ServerName) {
+ return nil, errNotAdmitted
+ }
+ return nil, nil // the test certificate StartTLS installs
+ }}
+ hubTLS.StartTLS()
+ t.Cleanup(hubTLS.Close)
+ // The box dials the hub's tunnel host and its store door over plain
+ // HTTP: the tunnel client checks the hub's certificate against the
+ // system roots, which the test certificate is not in. The same edge
+ // answers both listeners.
+ hubPlain := httptest.NewServer(hub)
+ t.Cleanup(hubPlain.Close)
+ hubURL := fprHub{t: t, addr: strings.TrimPrefix(hubTLS.URL, "https://")}
+ hubPass := func() {
+ t.Helper()
+ if err := provision.Reconcile(ctx, store, hubReg, host.BoxProvisionConfig(hubReg, hubEnv, nil, nil)); err != nil {
+ t.Fatalf("hub pass: %v", err)
+ }
+ if err := hub.Reload(); err != nil {
+ t.Fatalf("hub reload: %v", err)
+ }
+ }
+
+ // --- step 1: account, fleet, box, app, gate, limit, release, instance ---
+ owner := sqidOf(mustCarlos("accounts", "create", "-registry", cliReg, "-name", "shopkeeper"))
+ mustCarlos("fleets", "create", "--account", owner, "--bucket", "home-data", "home")
+ addOut := mustCarlos("fleets", "add-box", "--account", owner, "home", "box-1")
+ boxToken := regexp.MustCompile(`home/box-1 token: (\S+)`).FindStringSubmatch(addOut)
+ if boxToken == nil {
+ t.Fatalf("no token in:\n%s", addOut)
+ }
+ mustCarlos("apps", "create", "--account", owner, "--app", "shop", "--place", "fleet/home")
+
+ tiny := fprBuildTinyServer(t)
+ target := runtime.GOOS + "-" + runtime.GOARCH
+ mustCarlos("ship", "-app", "shop", "-account", owner, "-version", "v1", "-target", target, tiny)
+ mustCarlos("promote", "-app", "shop", "-account", owner, "v1", "canary/shop")
+ mustCarlos("instances", "enable", "-app", "shop", "-account", owner, "-channel", "canary/shop")
+
+ // The instance's upstream address: a listening socket the test holds,
+ // handed to the staged binary below.
+ upLn, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ upAddr := upLn.Addr().String()
+ shopHost := "shop." + owner + ".apps.example.com"
+ mustCarlos("instances", "create", "-app", "shop", "-account", owner, "-host", shopHost, "-addr", upAddr)
+ const password = "open sesame 1"
+ mustCarlos("gate", "set", "-app", "shop", "-account", owner, "-host", shopHost, "-password", password)
+ mustCarlos("ratelimit", "set", "-app", "shop", "-account", owner, "-host", shopHost, "-path", "/limited:rate=1,burst=5")
+
+ // The box: its own registry and edge, its store the door.
+ boxReg, err := registry.Open(filepath.Join(tmp, "box-registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { boxReg.Close() })
+ box, err := edge.New(boxReg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ boxMeter := edge.NewUsageMeter()
+ box.EnableUsage(boxMeter)
+ optDir := filepath.Join(tmp, "box-opt")
+ if err := os.MkdirAll(optDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ boxEnv := fprEnv(map[string]string{"CARLOS_FLEET": "home", "CARLOS_REGION": "fleet/home", "CARLOS_DATA_DIR": filepath.Join(tmp, "box-data")})
+ var boxStore release.Store
+ dial := func(tok string) func() {
+ t.Helper()
+ s, err := fleetapi.New(hubPlain.URL, "home/box-1", tok)
+ if err != nil {
+ t.Fatal(err)
+ }
+ boxStore = s
+ lctx, cancel := context.WithCancel(context.Background())
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ tunnelclient.Loop(lctx, tunnelclient.Config{URL: hubPlain.URL, Name: "home/box-1", Token: tok, Handler: box,
+ Logf: func(f string, a ...any) { log.Printf("box-1: "+f, a...) }})
+ }()
+ var once sync.Once
+ return func() { once.Do(func() { cancel(); wg.Wait() }) }
+ }
+ boxPass := func() {
+ t.Helper()
+ if err := provision.Reconcile(ctx, boxStore, boxReg, host.BoxProvisionConfig(boxReg, boxEnv, nil, nil)); err != nil {
+ t.Fatalf("box pass: %v", err)
+ }
+ if err := release.Pass(ctx, boxReg, boxStore, pub, optDir, nil); err != nil {
+ t.Fatalf("box adopt pass: %v", err)
+ }
+ if err := box.Reload(); err != nil {
+ t.Fatalf("box reload: %v", err)
+ }
+ }
+ stopBox := dial(boxToken[1])
+ t.Cleanup(stopBox)
+
+ hubPass()
+ boxPass()
+ // The hub admits the instance's name: a fresh connection's handshake
+ // with it as SNI succeeds only while hub.Allowed says yes.
+ if err := hubURL.handshake(shopHost); err != nil {
+ t.Fatalf("a fresh TLS handshake with SNI %s: %v, want it admitted: the hub serves the forward row", shopHost, err)
+ }
+ fwd, err := hubReg.Get(shopHost)
+ if err != nil || fwd == nil || !fwd.IsForward() {
+ t.Fatalf("hub row at %s = %+v (%v), want the forward row the hub's pass mints", shopHost, fwd, err)
+ }
+ brow, err := boxReg.Get(shopHost)
+ if err != nil || brow == nil || brow.Kind != "instance" || brow.Version != "v1" || brow.Gate == "" {
+ t.Fatalf("box row at %s = %+v (%v), want the instance row the box's pass mints, stamped v1 and gated", shopHost, brow, err)
+ }
+
+ // The staged binary, started as its unit would start it: the listening
+ // socket on fd 3.
+ lf, err := upLn.(*net.TCPListener).File()
+ if err != nil {
+ t.Fatal(err)
+ }
+ upLn.Close()
+ proc := exec.Command(release.LiveLink(optDir, shopHost))
+ proc.ExtraFiles = []*os.File{lf}
+ proc.Env = []string{"LISTEN_FDS=1"}
+ proc.Stderr = os.Stderr
+ if err := proc.Start(); err != nil {
+ t.Fatalf("start the staged binary %s: %v", release.LiveLink(optDir, shopHost), err)
+ }
+ lf.Close()
+ t.Cleanup(func() { proc.Process.Kill(); proc.Wait() })
+
+ // The box is connected before anything is asked of it.
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ resp, _, err := hubURL.do(http.MethodGet, shopHost, "/up", nil, nil)
+ if err == nil && resp.StatusCode != http.StatusServiceUnavailable {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("box-1 never answered through the hub: %v %v", resp, err)
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+
+ // --- step 2: the gate, through the hub's TLS listener -------------------
+ resp, page := hubURL.mustDo(http.MethodGet, shopHost, "/up", nil, nil)
+ if !isLoginForm(resp, page) {
+ t.Fatalf("GET /up = %d %q, want the fleet edge's login form", resp.StatusCode, page)
+ }
+ resp, body := hubURL.login(shopHost, page, "not the password")
+ if resp.StatusCode != http.StatusUnauthorized || !strings.Contains(body, "That password is not right.") || len(resp.Cookies()) != 0 {
+ t.Fatalf("wrong password = %d %v %q, want the wrong-password page and no cookie", resp.StatusCode, resp.Cookies(), body)
+ }
+ withCookie := hubURL.signIn(shopHost, page, password)
+ resp, body = hubURL.mustDo(http.MethodGet, shopHost, "/up", nil, withCookie)
+ if resp.StatusCode != http.StatusOK || body != "shop /up" {
+ t.Fatalf("GET /up with the cookie = %d %q, want the app's 200", resp.StatusCode, body)
+ }
+ if got := resp.Header.Values("X-Carlos-Version"); len(got) != 1 || got[0] != "v1" {
+ t.Fatalf("X-Carlos-Version = %q, want exactly [v1]: the box stamps it once and the hub adds none", got)
+ }
+ resp, page = hubURL.mustDo(http.MethodGet, shopHost, "/up", nil, nil)
+ if !isLoginForm(resp, page) {
+ t.Fatalf("GET /up without the cookie = %d %q, want the login form again", resp.StatusCode, page)
+ }
+
+ // --- step 3: over the limit, the hub refuses ----------------------------
+ // The limit is a path rule, /limited at a burst of 5 refilled one a
+ // second, so the requests above (on other paths) spent none of it.
+ hubMeter.Drain()
+ boxMeter.Drain()
+ oks := 0
+ var refused *http.Response
+ var refusedBody string
+ for i := 0; i < 12 && refused == nil; i++ {
+ resp, body := hubURL.mustDo(http.MethodGet, shopHost, "/limited", nil, withCookie)
+ switch {
+ case resp.StatusCode == http.StatusOK && body == "shop /limited":
+ oks++
+ case resp.StatusCode == http.StatusTooManyRequests:
+ refused, refusedBody = resp, body
+ default:
+ t.Fatalf("GET /limited %d = %d %q, want the app's 200 or the hub's 429", i+1, resp.StatusCode, body)
+ }
+ }
+ if refused == nil || oks < 5 {
+ t.Fatalf("%d answered before a refusal (%v), want the burst of 5 and then a 429", oks, refused != nil)
+ }
+ if refused.Header.Get("Retry-After") == "" || refused.Header.Get("Cache-Control") != "no-store" ||
+ refusedBody != "Too many requests. Try again in a moment." {
+ t.Fatalf("the refusal = %v %q, want the edge's whole 429", refused.Header, refusedBody)
+ }
+ if got := fprCount(t, upAddr); got != oks {
+ t.Fatalf("the app saw %d requests for /limited, want the %d admitted: the refused one never crossed the tunnel", got, oks)
+ }
+ if h, b := hubMeter.Drain()[shopHost], boxMeter.Drain()[shopHost]; h.RateCeiling != 1 || b.RateCeiling != 0 {
+ t.Fatalf("refusals counted: hub %d, box %d; want the hub's 1 and none on the box", h.RateCeiling, b.RateCeiling)
+ }
+
+ // --- step 4: a custom parent with an instance catch-all -----------------
+ const parent = "shops.example.com"
+ mustCarlos("domains", "attach", "--app", "shop", "--account", owner, parent)
+ mustCarlos("domains", "attach", "--app", "shop", "--account", owner, "*."+parent)
+ aliasPass := func(s release.Store, reg *registry.Registry, hubSide bool) domains.AliasReport {
+ t.Helper()
+ // What the agent's alias pass (aliasPassReporting) hands the
+ // domains package: the deployment's routes from the edges files, and
+ // the edge's own fleet-arm refusals over the listing.
+ deploymentRoutes, whole := edgesfile.DeploymentRoutesComplete(ctx, s, time.Now())
+ fleets, err := reg.ListFleets()
+ if err != nil {
+ t.Fatal(err)
+ }
+ owners := map[string]string{}
+ for _, f := range fleets {
+ owners[f.Name] = f.Account
+ }
+ rep := domains.AliasReport{DeploymentRoutesPartial: deploymentRoutes != nil && !whole,
+ FleetRefused: func(routes []registry.Route) map[string]string {
+ return edge.FleetArmVerdict(routes, owners, hubSide, hubSide).Refused
+ }}
+ if err := domains.ReconcileAliasesReport(ctx, s, reg, time.Now, deploymentRoutes, nil, &rep); err != nil {
+ t.Fatalf("alias pass: %v", err)
+ }
+ return rep
+ }
+ hubPass()
+ aliasPass(store, hubReg, true)
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ boxPass()
+ aliasPass(boxStore, boxReg, false)
+ if err := box.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ slugHost := "shop." + parent
+ resp, page = hubURL.mustDo(http.MethodGet, slugHost, "/up", nil, nil)
+ if !isLoginForm(resp, page) {
+ t.Fatalf("GET %s/up = %d %q, want the fleet edge's login form", slugHost, resp.StatusCode, page)
+ }
+ slugCookie := hubURL.signIn(slugHost, page, password)
+ resp, body = hubURL.mustDo(http.MethodGet, slugHost, "/up", nil, slugCookie)
+ if resp.StatusCode != http.StatusOK || body != "shop /up" {
+ t.Fatalf("GET %s/up with its cookie = %d %q, want the app's 200", slugHost, resp.StatusCode, body)
+ }
+
+ // --- step 5: detach the box, then add it back ---------------------------
+ mustCarlos("fleets", "detach-box", "--account", owner, "home", "box-1")
+ hubPass()
+ waitFor := func(what string, ok func() (bool, string)) {
+ t.Helper()
+ deadline := time.Now().Add(15 * time.Second)
+ for {
+ done, last := ok()
+ if done {
+ return
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("%s: last answer %s", what, last)
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ }
+ waitFor("the detached box's host to answer 503", func() (bool, string) {
+ resp, body, err := hubURL.do(http.MethodGet, shopHost, "/up", nil, withCookie)
+ if err != nil {
+ return false, err.Error()
+ }
+ return resp.StatusCode == http.StatusServiceUnavailable && resp.Header.Get("Retry-After") != "",
+ fmt.Sprintf("%d %v %q", resp.StatusCode, resp.Header, body)
+ })
+ addOut = mustCarlos("fleets", "add-box", "--account", owner, "home", "box-1")
+ newToken := regexp.MustCompile(`home/box-1 token: (\S+)`).FindStringSubmatch(addOut)
+ if newToken == nil || newToken[1] == boxToken[1] {
+ t.Fatalf("no new token in:\n%s", addOut)
+ }
+ stopBox()
+ hubPass()
+ stopBox = dial(newToken[1])
+ t.Cleanup(stopBox)
+ waitFor("the redialled box to serve", func() (bool, string) {
+ resp, body, err := hubURL.do(http.MethodGet, shopHost, "/up", nil, withCookie)
+ if err != nil {
+ return false, err.Error()
+ }
+ return resp.StatusCode == http.StatusOK && body == "shop /up", fmt.Sprintf("%d %q", resp.StatusCode, body)
+ })
+ boxPass() // the box's pass runs over the door with its new token
+
+ // --- step 6: trash the app ----------------------------------------------
+ mustCarlos("apps", "delete", "--account", owner, "shop")
+ if rt, err := hubReg.Get(shopHost); err != nil || rt == nil || !rt.IsForward() {
+ t.Fatalf("before the hub's pass, the row at %s = %+v (%v), want the forward row still there: only the hub's pass retires it", shopHost, rt, err)
+ }
+ hubPass()
+ if rt, err := hubReg.Get(shopHost); err != nil || rt != nil {
+ t.Fatalf("after the hub's pass, the row at %s = %+v (%v), want it gone", shopHost, rt, err)
+ }
+ if err := hubURL.handshake(shopHost); err == nil {
+ t.Fatalf("a fresh TLS handshake with SNI %s succeeded after the app was trashed, want it refused", shopHost)
+ }
+
+ // --- step 7: another account's record on this fleet ---------------------
+ // No row and no admission. Whether the host reaches the hub's edges file
+ // is the edges-file writer's (internal/host, unexported here), which asks
+ // the same verdict and has its own tests (Task 6).
+ // A real second account, created the way the first was, whose record
+ // names fleet/home: written straight to the store, as anyone holding
+ // that account's bucket access could.
+ other := sqidOf(mustCarlos("accounts", "create", "-registry", cliReg, "-name", "neighbour"))
+ if other == owner {
+ t.Fatalf("the second account has the owner's sqid %s", other)
+ }
+ otherHost := "blog." + other + ".apps.example.com"
+ if err := provision.CreateRecord(ctx, store, provision.Record{
+ Schema: 1, Host: otherHost, Slug: "blog", App: "blog", Account: other,
+ Region: "fleet/home", Channel: "canary/blog", CreatedAt: time.Now().UTC(),
+ }); err != nil {
+ t.Fatal(err)
+ }
+ tap.Reset()
+ hubPass()
+ // The record reached the ownership judgment (the forward phase logs every
+ // refusal, once per host per pass) before its absence is asserted.
+ if want := fmt.Sprintf("provision: forward %s: refused: account %q does not own fleet %q", otherHost, other, "home"); !strings.Contains(tap.String(), want) {
+ t.Fatalf("the hub's pass never judged %s's owner, want the log line %q; the pass logged:\n%s", otherHost, want, tap.String())
+ }
+ if rt, err := hubReg.Get(otherHost); err != nil || rt != nil {
+ t.Fatalf("the row at %s = %+v (%v), want none", otherHost, rt, err)
+ }
+ if hub.Allowed(otherHost) {
+ t.Fatalf("hub.Allowed(%s) = true, want false", otherHost)
+ }
+}