| 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) |
| + } |
| + } |
| +} |