| new file mode 100644 |
| index 000000000..9e5189081 |
| --- /dev/null |
| +++ b/internal/edge/forwardha_test.go |
| @@ -0,0 +1,817 @@ |
| +package edge |
| + |
| +// Region HA P1b-2 Task 2: the front-door forward. The scene is the |
| +// multi-region backhaul's (newBackhaulSceneWith): two real Edges over one |
| +// DirStore, real TLS on both doors, the mesh key minted into the bucket and |
| +// real hop auth. Here both boxes serve the same born-HA hosts, both are in |
| +// region "ie" and placement "p" with the same data bucket and secrets key, |
| +// and annie's activator is a fake HAForwarder naming betty as the holder. |
| +// Every request below is a real client's, handshaken with annie by name. |
| +// |
| +// One seam stands in for the network: every box in a scene is dialled on |
| +// one port (backhaulPort), so forwardDial sends annie's forwards to betty's |
| +// door, where the dial address would be betty's EIP in production. |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "crypto/tls" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/analytics" |
| + "github.com/carlosframework/platform/internal/assetcache" |
| + "github.com/carlosframework/platform/internal/gate" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/reqrec" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +const ( |
| + // fwHost is the plain born-HA instance both boxes serve. |
| + fwHost = "ha.forward.test" |
| + // fwGatedHost is the same behind the password gate. |
| + fwGatedHost = "gated.forward.test" |
| + // fwAssetHost is an ungated HA instance whose /assets/ the asset cache |
| + // catches on both boxes. |
| + fwAssetHost = "assets.forward.test" |
| + // fwRateHost is an HA instance with a one-request backstop. |
| + fwRateHost = "rate.forward.test" |
| + // fwLegacyHost is an activator-managed instance that is not HA. |
| + fwLegacyHost = "legacy.forward.test" |
| + |
| + fwAssetBody = "console.log('forwarded');\n" |
| + fwPassword = "correct horse" |
| +) |
| + |
| +var fwHosts = []string{fwHost, fwGatedHost, fwAssetHost, fwRateHost, fwLegacyHost} |
| + |
| +// fwAct is a box's activator: it wakes nothing (the route's TCP upstream |
| +// answers) and, as an HAForwarder, names target and keeps every note. |
| +type fwAct struct { |
| + target string |
| + asked atomic.Int64 |
| + mu sync.Mutex |
| + notes []fwNote |
| +} |
| + |
| +type fwNote struct { |
| + host string |
| + res ForwardResult |
| +} |
| + |
| +var _ HAForwarder = (*fwAct)(nil) |
| + |
| +func (a *fwAct) ServeHTTP(http.ResponseWriter, *http.Request, registry.Route, http.Handler) bool { |
| + return false |
| +} |
| +func (a *fwAct) RetireExcept(map[string]bool) {} |
| +func (a *fwAct) ForwardTarget(_ context.Context, _ registry.Route) string { |
| + a.asked.Add(1) |
| + return a.target |
| +} |
| +func (a *fwAct) NoteForward(host string, res ForwardResult) { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + a.notes = append(a.notes, fwNote{host, res}) |
| +} |
| + |
| +func (a *fwAct) noted() []fwNote { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + return append([]fwNote(nil), a.notes...) |
| +} |
| + |
| +// fwPlainAct is an activator without the forwarding interface. |
| +type fwPlainAct struct{} |
| + |
| +func (fwPlainAct) ServeHTTP(http.ResponseWriter, *http.Request, registry.Route, http.Handler) bool { |
| + return false |
| +} |
| +func (fwPlainAct) RetireExcept(map[string]bool) {} |
| + |
| +// fwApp is one box's app behind every forward host. Its ordinary body names |
| +// the box, the host and the path; /missing is a 404; /holder answers 503 with |
| +// X-Carlos-Holder set to its ref query (none when the query is empty); |
| +// /assets/ is a cacheable script, and /assets/held.js waits on the first |
| +// request until the test releases it; an upgrade echoes with the box's name. |
| +type fwAppServer struct { |
| + srv *httptest.Server |
| + n atomic.Int64 |
| + first func() bool |
| + started chan struct{} |
| + wait, release func() |
| + heldRequests, assetRequests atomic.Int64 |
| +} |
| + |
| +func fwApp(t *testing.T, box string) *fwAppServer { |
| + t.Helper() |
| + a := &fwAppServer{} |
| + a.first, a.started, a.wait, a.release = fillGate() |
| + t.Cleanup(a.release) |
| + echo := upgradeEchoHandler(box) |
| + a.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + a.n.Add(1) |
| + switch { |
| + case isUpgradeRequest(r): |
| + echo.ServeHTTP(w, r) |
| + case r.URL.Path == "/missing": |
| + http.NotFound(w, r) |
| + case r.URL.Path == "/holder": |
| + if ref := r.URL.Query().Get("ref"); ref != "" { |
| + w.Header().Set(holderHeader, ref) |
| + } |
| + w.Header().Set("Retry-After", "1") |
| + http.Error(w, "held", http.StatusServiceUnavailable) |
| + case r.URL.Path == "/assets/held.js": |
| + a.heldRequests.Add(1) |
| + if a.first() { |
| + close(a.started) |
| + a.wait() |
| + } |
| + assetOK(fwAssetBody, "ETag", `"f1"`)(w, r) |
| + case strings.HasPrefix(r.URL.Path, "/assets/"): |
| + a.assetRequests.Add(1) |
| + assetOK(fwAssetBody, "ETag", `"f1"`)(w, r) |
| + default: |
| + fmt.Fprintf(w, "%s|%s|%s", box, r.Host, r.URL.Path) |
| + } |
| + })) |
| + t.Cleanup(a.srv.Close) |
| + return a |
| +} |
| + |
| +// fwScene is the armed two-edge scene: annie forwards, betty holds. |
| +type fwScene struct { |
| + *backhaulScene |
| + aAct, bAct *fwAct |
| + aApp, bApp *fwAppServer |
| + aMeter, bMeter *UsageMeter |
| + aObs, bObs *memAnalytics |
| + aRec, bRec *lockedRecorder |
| + aStore, bStore *assetcache.Store |
| + hash string |
| + // seen are the record and observation counts the last take returned up to. |
| + seen map[*lockedRecorder][2]int |
| + obs map[*memAnalytics]int |
| +} |
| + |
| +type fwOpts struct { |
| + // aAct replaces annie's forwarding fake (nil keeps it). |
| + aAct Activator |
| + // aTarget is the box annie's fake names ("" is betty). |
| + aTarget string |
| + // bettyLacks leaves betty without the HA hosts: in view, not serving. |
| + bettyLacks bool |
| +} |
| + |
| +func newFwScene(t *testing.T, o fwOpts) *fwScene { |
| + t.Helper() |
| + t.Setenv("CARLOS_RATE_LIMIT", "observe") |
| + t.Setenv("CARLOS_REGION_HA", "") |
| + hash, err := gate.Hash(fwPassword) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + x := &fwScene{ |
| + aAct: &fwAct{target: "betty"}, bAct: &fwAct{target: "annie"}, |
| + aApp: fwApp(t, "annie"), bApp: fwApp(t, "betty"), |
| + aMeter: NewUsageMeter(), bMeter: NewUsageMeter(), |
| + aObs: &memAnalytics{}, bObs: &memAnalytics{}, |
| + aRec: &lockedRecorder{}, bRec: &lockedRecorder{}, |
| + hash: hash, seen: map[*lockedRecorder][2]int{}, obs: map[*memAnalytics]int{}, |
| + } |
| + routes := func(addr string) []registry.Route { |
| + base := registry.Route{Kind: "instance", Hibernate: true, Addr: addr, Status: "ready", Account: "abc", App: "shop"} |
| + rs := make([]registry.Route, 0, len(fwHosts)) |
| + for _, h := range fwHosts { |
| + rt := base |
| + rt.Host = h |
| + switch h { |
| + case fwGatedHost: |
| + rt.Gate = hash |
| + case fwAssetHost: |
| + rt.AssetGen, rt.Version = laGen, laBuild |
| + case fwRateHost: |
| + rt.RateLimit = `{"rate":1,"burst":1}` |
| + } |
| + rs = append(rs, rt) |
| + } |
| + return rs |
| + } |
| + if o.aTarget != "" { |
| + x.aAct.target = o.aTarget |
| + } |
| + var aAct Activator = x.aAct |
| + if o.aAct != nil { |
| + aAct = o.aAct |
| + } |
| + extra := backhaulSceneExtra{ |
| + homeRoutes: routes(x.aApp.srv.Listener.Addr().String()), |
| + homeAct: aAct, |
| + farAct: x.bAct, |
| + certs: fwHosts, |
| + } |
| + if !o.bettyLacks { |
| + extra.farRoutes = routes(x.bApp.srv.Listener.Addr().String()) |
| + } |
| + x.backhaulScene = newBackhaulSceneWith(t, extra) |
| + for _, be := range []*backhaulEdge{x.a, x.b} { |
| + for _, h := range fwHosts { |
| + if h == fwLegacyHost { |
| + continue |
| + } |
| + if _, ok := be.edge.lookupUpstream(h); !ok { |
| + continue |
| + } |
| + if err := be.reg.SetHA(h); err != nil { |
| + t.Fatalf("SetHA %s: %v", h, err) |
| + } |
| + } |
| + if err := be.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + x.publishViewFiles(t, time.Now()) |
| + x.converge(t) |
| + fwDialTo(t, x.b.tlsAddr) |
| + |
| + x.aStore = openStoreAt(t, filepath.Join(t.TempDir(), "asset-cache")) |
| + x.bStore = openStoreAt(t, filepath.Join(t.TempDir(), "asset-cache")) |
| + for _, w := range []struct { |
| + be *backhaulEdge |
| + meter *UsageMeter |
| + obs *memAnalytics |
| + rec *lockedRecorder |
| + store *assetcache.Store |
| + }{{x.a, x.aMeter, x.aObs, x.aRec, x.aStore}, {x.b, x.bMeter, x.bObs, x.bRec, x.bStore}} { |
| + e := w.be.edge |
| + e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes)) |
| + e.EnableUsage(w.meter) |
| + e.EnableAnalytics(w.obs) |
| + e.SetAnalyticsOn(map[string]bool{"abc/shop": true}) |
| + e.EnableRequestRecords(w.rec) |
| + e.guard = guardWatch |
| + armForTest(t, e, w.store, &fakeLocalAssets{ |
| + hosts: map[string]HostAssets{fwAssetHost: {Account: "abc", App: "shop", Paths: []string{"/assets/"}, |
| + Gen: laGen, At: time.Now(), Primary: fwAssetHost}}, |
| + builds: map[string]bool{laBuild: true}, |
| + }) |
| + } |
| + return x |
| +} |
| + |
| +// publishViewFiles rewrites both boxes' edges files with the holder view's |
| +// fields: one region and placement, one data bucket and secrets key, written |
| +// at gen. |
| +func (x *fwScene) publishViewFiles(t *testing.T, gen time.Time) { |
| + t.Helper() |
| + for _, f := range []struct { |
| + box, eip string |
| + hosts []string |
| + }{{"annie", x.aEIP, []string{e2eHomedHost, e2eMovedHost}}, {"betty", x.bEIP, []string{e2eSenderHost}}} { |
| + parts := make([]string, 0, len(f.hosts)) |
| + for _, h := range f.hosts { |
| + parts = append(parts, fmt.Sprintf(`%q:{"role":"home"}`, h)) |
| + } |
| + putJSON(t, x.seed, "control/edges/"+f.box+".json", fmt.Sprintf( |
| + `{"v":1,"box":%q,"eip":%q,"region":"ie","placement":"p","generation":%q,"data_bucket":"bkt","secrets_key_fp":"fp","hosts":{%s}}`, |
| + f.box, f.eip, gen.UTC().Format(time.RFC3339), strings.Join(parts, ","))) |
| + } |
| +} |
| + |
| +// fwDialTo points every forward dial at addr for the test's lifetime. |
| +func fwDialTo(t *testing.T, addr string) { |
| + t.Helper() |
| + old := forwardDial |
| + forwardDial = func(ctx context.Context, network, _ string) (net.Conn, error) { |
| + var d net.Dialer |
| + return d.DialContext(ctx, network, addr) |
| + } |
| + t.Cleanup(func() { forwardDial = old }) |
| +} |
| + |
| +func (x *fwScene) fetch(t *testing.T, host, path string, hdr ...string) (*http.Response, string) { |
| + t.Helper() |
| + return x.get(t, x.a, "https://"+host+path, e2eHeaders(hdr), true) |
| +} |
| + |
| +func (x *fwScene) fetchAsync(host, path string) <-chan e2eResult { |
| + ch := make(chan e2eResult, 1) |
| + go func() { |
| + resp, err := x.try(x.a, "https://"+host+path, e2eHeaders(nil), true) |
| + if err != nil { |
| + ch <- e2eResult{err: err} |
| + return |
| + } |
| + b, err := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + ch <- e2eResult{resp: resp, body: string(b), err: err} |
| + }() |
| + return ch |
| +} |
| + |
| +// fwBox is what one box recorded for a host since the last take. |
| +type fwBox struct { |
| + use usage.EdgeRow |
| + obs []analytics.Obs |
| + resp []reqrec.Response |
| + match []reqrec.Match |
| +} |
| + |
| +// take waits for every handler on both boxes to return, then drains both |
| +// meters for host and returns each box's new observations and records. |
| +func (x *fwScene) take(t *testing.T, host string) (annie, betty fwBox) { |
| + t.Helper() |
| + laWaitFor(t, "both edges' handlers to return", func() bool { |
| + return x.a.served.Load() == x.a.calls.Load() && x.b.served.Load() == x.b.calls.Load() |
| + }) |
| + box := func(m *UsageMeter, obs *memAnalytics, rec *lockedRecorder) fwBox { |
| + var b fwBox |
| + b.use = m.Drain()[host] |
| + all := obs.snap() |
| + b.obs = all[x.obs[obs]:] |
| + x.obs[obs] = len(all) |
| + rec.mu.Lock() |
| + seen := x.seen[rec] |
| + b.resp = append([]reqrec.Response(nil), rec.resp[seen[0]:]...) |
| + b.match = append([]reqrec.Match(nil), rec.match[seen[1]:]...) |
| + x.seen[rec] = [2]int{len(rec.resp), len(rec.match)} |
| + rec.mu.Unlock() |
| + return b |
| + } |
| + return box(x.aMeter, x.aObs, x.aRec), box(x.bMeter, x.bObs, x.bRec) |
| +} |
| + |
| +// wantNothing: the box recorded nothing at all. |
| +func wantNothing(t *testing.T, step string, b fwBox) { |
| + t.Helper() |
| + if b.use.Requests != 0 || b.use.BytesOut != 0 || b.use.RateCeiling != 0 || b.use.RateShed != 0 || |
| + len(b.obs) != 0 || len(b.resp) != 0 || len(b.match) != 0 { |
| + t.Fatalf("%s: the forwarding box recorded usage %+v, %d observations, %d responses, %d matches; want nothing", |
| + step, b.use, len(b.obs), len(b.resp), len(b.match)) |
| + } |
| +} |
| + |
| +// wantOneDelivery: the box recorded one request of n bytes, as a hop, in |
| +// usage, analytics and one response record of status. |
| +func wantOneDelivery(t *testing.T, step string, b fwBox, n int, status int) { |
| + t.Helper() |
| + if b.use.Requests != 1 || b.use.BytesOut != int64(n) || b.use.HopRequests != 1 { |
| + t.Fatalf("%s: the holder metered %+v, want one hop request of %d bytes", step, b.use, n) |
| + } |
| + if len(b.obs) != 1 || b.obs[0].Bytes != int64(n) || b.obs[0].Status != status { |
| + t.Fatalf("%s: the holder observed %+v, want one observation of %d bytes, status %d", step, b.obs, n, status) |
| + } |
| + if len(b.resp) != 1 || b.resp[0].Status != status || len(b.match) != 0 { |
| + t.Fatalf("%s: the holder recorded responses %+v matches %+v, want one response %d", step, b.resp, b.match, status) |
| + } |
| +} |
| + |
| +func (x *fwScene) wantNote(t *testing.T, want ...fwNote) { |
| + t.Helper() |
| + got := x.aAct.noted() |
| + if len(got) != len(want) { |
| + t.Fatalf("notes = %+v, want %+v", got, want) |
| + } |
| + for i := range want { |
| + if got[i] != want[i] { |
| + t.Fatalf("note %d = %+v, want %+v", i, got[i], want[i]) |
| + } |
| + } |
| +} |
| + |
| +// ---- the forward ------------------------------------------------------------- |
| + |
| +func TestFrontForwardReachesTheHolder(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + resp, body := x.fetch(t, fwHost, "/deep?q=1") |
| + if resp.StatusCode != http.StatusOK || body != "betty|"+fwHost+"|/deep" { |
| + t.Fatalf("GET = %d %q, want betty's 200", resp.StatusCode, body) |
| + } |
| + annie, betty := x.take(t, fwHost) |
| + wantNothing(t, "a forward", annie) |
| + // Metered as a hop: betty saw a verified one. |
| + wantOneDelivery(t, "a forward", betty, len(body), http.StatusOK) |
| + if n := x.aApp.n.Load(); n != 0 { |
| + t.Fatalf("annie's app saw %d requests", n) |
| + } |
| + if got := x.aAct.asked.Load(); got != 1 { |
| + t.Fatalf("annie asked its activator %d times, want 1", got) |
| + } |
| + // One hop: betty never asks where to send a hop. |
| + if got := x.bAct.asked.Load(); got != 0 { |
| + t.Fatalf("betty asked its activator %d times for a hop, want 0", got) |
| + } |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusOK}}) |
| +} |
| + |
| +func TestFrontForwardRunsNoLocalStep(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + |
| + t.Run("a gate", func(t *testing.T) { |
| + cookie := gate.CookieName + "=" + gate.Mint(fwGatedHost, x.hash, time.Now().Add(time.Hour)) |
| + resp, body := x.fetch(t, fwGatedHost, "/in", "Cookie", cookie) |
| + if resp.StatusCode != http.StatusOK || body != "betty|"+fwGatedHost+"|/in" { |
| + t.Fatalf("with the cookie = %d %q, want betty's 200", resp.StatusCode, body) |
| + } |
| + annie, betty := x.take(t, fwGatedHost) |
| + wantNothing(t, "a gated pass", annie) |
| + wantOneDelivery(t, "a gated pass", betty, len(body), http.StatusOK) |
| + |
| + calls := x.b.calls.Load() |
| + resp, body = x.fetch(t, fwGatedHost, "/in") |
| + if resp.StatusCode != http.StatusUnauthorized || !strings.Contains(body, gate.LoginPath) { |
| + t.Fatalf("without the cookie = %d %q, want the login page", resp.StatusCode, body) |
| + } |
| + if got := x.b.calls.Load() - calls; got != 1 { |
| + t.Fatalf("betty saw %d requests for the refusal, want 1: annie's gate answered", got) |
| + } |
| + annie, betty = x.take(t, fwGatedHost) |
| + wantNothing(t, "a gated refusal", annie) |
| + wantOneDelivery(t, "a gated refusal", betty, len(body), http.StatusUnauthorized) |
| + }) |
| + |
| + t.Run("b assets", func(t *testing.T) { |
| + step := func(name, path string, wantStatus int, hdr ...string) *http.Response { |
| + t.Helper() |
| + resp, body := x.fetch(t, fwAssetHost, path, hdr...) |
| + if resp.StatusCode != wantStatus { |
| + t.Fatalf("%s = %d %q, want %d", name, resp.StatusCode, body, wantStatus) |
| + } |
| + annie, betty := x.take(t, fwAssetHost) |
| + wantNothing(t, name, annie) |
| + wantOneDelivery(t, name, betty, len(body), wantStatus) |
| + return resp |
| + } |
| + // Carlos-Cache does not cross a hop (scrubBackhaulResponse), so the |
| + // catch is read off betty's store and app. |
| + get := step("GET", "/assets/app.js", http.StatusOK) |
| + appKey := assetcache.Key{Account: "abc", App: "shop", Gen: laGen, Host: fwAssetHost, Path: "/assets/app.js"} |
| + if _, ok := x.bStore.Get(appKey); !ok { |
| + t.Fatal("betty's asset cache did not catch the GET") |
| + } |
| + step("HEAD", "/assets/app.js", http.StatusOK) |
| + step("range", "/assets/app.js", http.StatusPartialContent, "Range", "bytes=0-4") |
| + step("conditional", "/assets/app.js", http.StatusNotModified, "If-None-Match", get.Header.Get("ETag")) |
| + if n := x.bApp.assetRequests.Load(); n != 1 { |
| + t.Fatalf("betty's app saw %d asset requests, want the one fill", n) |
| + } |
| + |
| + // Two coalesced GETs: the second waits on betty's fill. |
| + lead := x.fetchAsync(fwAssetHost, "/assets/held.js") |
| + e2eStarted(t, x.bApp.started, lead) |
| + rest := x.fetchAsync(fwAssetHost, "/assets/held.js") |
| + key := assetcache.Key{Account: "abc", App: "shop", Gen: laGen, Host: fwAssetHost, Path: "/assets/held.js"} |
| + laWaitFor(t, "the second GET to join betty's fill", func() bool { return flightWaitersOf(x.b.edge, key.ID()) == 1 }) |
| + x.bApp.release() |
| + for _, ch := range []<-chan e2eResult{lead, rest} { |
| + if r := e2eAwait(t, ch); r.resp.StatusCode != http.StatusOK || r.body != fwAssetBody { |
| + t.Fatalf("coalesced GET = %d %q", r.resp.StatusCode, r.body) |
| + } |
| + } |
| + annie, betty := x.take(t, fwAssetHost) |
| + wantNothing(t, "coalesced", annie) |
| + if betty.use.Requests != 2 || betty.use.BytesOut != int64(2*len(fwAssetBody)) || len(betty.obs) != 2 || len(betty.resp) != 2 { |
| + t.Fatalf("coalesced: the holder metered %+v, %d observations, %d records; want two of %d bytes each", |
| + betty.use, len(betty.obs), len(betty.resp), len(fwAssetBody)) |
| + } |
| + if n := x.bApp.heldRequests.Load(); n != 1 { |
| + t.Fatalf("betty's app saw %d requests for the coalesced path, want one fill", n) |
| + } |
| + |
| + // Annie filled nothing and asked its app nothing. |
| + if s := x.aStore.Stats(); s.Entries != 0 || s.Reserved != 0 { |
| + t.Fatalf("annie's asset store holds %+v", s) |
| + } |
| + if n := x.aApp.n.Load(); n != 0 { |
| + t.Fatalf("annie's app saw %d requests", n) |
| + } |
| + if s := x.bStore.Stats(); s.Entries != 2 { |
| + t.Fatalf("betty's asset store holds %+v, want the two paths", s) |
| + } |
| + }) |
| + |
| + t.Run("c guard and not found", func(t *testing.T) { |
| + resp, body := x.fetch(t, fwHost, "/.env") |
| + if resp.StatusCode != http.StatusOK || !strings.HasPrefix(body, "betty|") { |
| + t.Fatalf("watched = %d %q, want betty's 200", resp.StatusCode, body) |
| + } |
| + annie, betty := x.take(t, fwHost) |
| + wantNothing(t, "watched", annie) |
| + if len(betty.match) != 1 || betty.match[0].Kind != reqrec.KindWatch || len(betty.resp) != 0 { |
| + t.Fatalf("watched: the holder recorded matches %+v responses %+v, want one watch match", betty.match, betty.resp) |
| + } |
| + |
| + resp, body = x.fetch(t, fwHost, "/missing") |
| + if resp.StatusCode != http.StatusNotFound { |
| + t.Fatalf("missing = %d %q, want 404", resp.StatusCode, body) |
| + } |
| + annie, betty = x.take(t, fwHost) |
| + wantNothing(t, "not found", annie) |
| + wantOneDelivery(t, "not found", betty, len(body), http.StatusNotFound) |
| + }) |
| + |
| + t.Run("d rate limit observed", func(t *testing.T) { |
| + x.fetch(t, fwRateHost, "/") // spends the backstop's one token, at betty |
| + x.take(t, fwRateHost) |
| + for i := range 3 { |
| + if resp, _ := x.fetch(t, fwRateHost, "/"); resp.StatusCode != http.StatusOK { |
| + t.Fatalf("request %d = %d, want observe mode to serve", i, resp.StatusCode) |
| + } |
| + annie, betty := x.take(t, fwRateHost) |
| + wantNothing(t, fmt.Sprintf("rate %d", i), annie) |
| + if betty.use.RateCeiling != 1 || betty.use.Requests != 1 { |
| + t.Fatalf("rate %d: the holder counted %+v, want one request over the backstop", i, betty.use) |
| + } |
| + } |
| + if n := x.aApp.n.Load(); n != 0 { |
| + t.Fatalf("annie's app saw %d requests", n) |
| + } |
| + }) |
| +} |
| + |
| +func TestForwardHAHolderLostHost(t *testing.T) { |
| + x := newFwScene(t, fwOpts{bettyLacks: true}) |
| + resp, body := x.fetch(t, fwHost, "/") |
| + if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "2" { |
| + t.Fatalf("GET = %d Retry-After %q %q, want betty's no-route 503", resp.StatusCode, resp.Header.Get("Retry-After"), body) |
| + } |
| + if v := resp.Header.Values(holderHeader); len(v) != 0 { |
| + t.Fatalf("%s = %q, want none", holderHeader, v) |
| + } |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusServiceUnavailable}}) |
| + if n := x.aApp.n.Load(); n != 0 { |
| + t.Fatalf("annie's app saw %d requests", n) |
| + } |
| +} |
| + |
| +func TestFrontForwardSkips(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + local := func(t *testing.T, host, body string) { |
| + t.Helper() |
| + if !strings.HasPrefix(body, "annie|"+host+"|") { |
| + t.Fatalf("%s: body %q, want annie's own app", host, body) |
| + } |
| + } |
| + wantNotAsked := func(t *testing.T) { |
| + t.Helper() |
| + if n := x.aAct.asked.Load(); n != 0 { |
| + t.Fatalf("the activator was asked %d times", n) |
| + } |
| + if notes := x.aAct.noted(); len(notes) != 0 { |
| + t.Fatalf("notes = %+v", notes) |
| + } |
| + } |
| + direct := func(t *testing.T, r *http.Request, up upstream, hopped, isDoor bool) { |
| + t.Helper() |
| + rec := httptest.NewRecorder() |
| + if x.a.edge.frontForwardHA(rec, r, fwHost, up, hopped, isDoor) { |
| + t.Fatal("frontForwardHA answered") |
| + } |
| + if rec.Code != http.StatusOK || rec.Body.Len() != 0 || len(rec.Header()) != 0 { |
| + t.Fatalf("frontForwardHA wrote %d %q %v", rec.Code, rec.Body.String(), rec.Header()) |
| + } |
| + } |
| + haUp, ok := x.a.edge.lookupUpstream(fwHost) |
| + if !ok || !haUp.route.HA || !haUp.hibernating || haUp.regional != regionalNone { |
| + t.Fatalf("test bug: %s is not a local HA activator route: %+v", fwHost, haUp) |
| + } |
| + newReq := func() *http.Request { |
| + r := httptest.NewRequest(http.MethodGet, "https://"+fwHost+"/", nil) |
| + r.RemoteAddr = "203.0.113.9:4000" |
| + return r |
| + } |
| + |
| + t.Run("verified hop", func(t *testing.T) { |
| + resp, body := x.fetch(t, fwHost, "/hop", hopHeader, "1", hopAuthHeader, signHop(x.key, fwHost, time.Now())) |
| + if resp.StatusCode != http.StatusOK { |
| + t.Fatalf("hop = %d %q", resp.StatusCode, body) |
| + } |
| + local(t, fwHost, body) |
| + r := newReq() |
| + direct(t, r.WithContext(withHopVerified(r.Context())), haUp, false, false) |
| + direct(t, newReq(), haUp, true, false) |
| + wantNotAsked(t) |
| + }) |
| + t.Run("door call", func(t *testing.T) { |
| + r := newReq() |
| + r = r.WithContext(context.WithValue(r.Context(), doorCallerKey{}, doorCaller{Account: "abc", App: "shop"})) |
| + rec := httptest.NewRecorder() |
| + x.a.edge.ServeHTTP(rec, r) |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("door call = %d %q", rec.Code, rec.Body.String()) |
| + } |
| + local(t, fwHost, rec.Body.String()) |
| + direct(t, newReq(), haUp, false, true) |
| + wantNotAsked(t) |
| + }) |
| + t.Run("from a tunnel", func(t *testing.T) { |
| + old := fromTunnel |
| + fromTunnel = func(context.Context) bool { return true } |
| + defer func() { fromTunnel = old }() |
| + direct(t, newReq(), haUp, false, false) |
| + wantNotAsked(t) |
| + }) |
| + t.Run("regional name", func(t *testing.T) { |
| + for _, mode := range []regionalMode{regionalServe, regionalDeny} { |
| + up := haUp |
| + up.regional = mode |
| + direct(t, newReq(), up, false, false) |
| + } |
| + wantNotAsked(t) |
| + }) |
| + t.Run("not HA", func(t *testing.T) { |
| + _, body := x.fetch(t, fwLegacyHost, "/") |
| + local(t, fwLegacyHost, body) |
| + up := haUp |
| + up.route.HA = false |
| + direct(t, newReq(), up, false, false) |
| + wantNotAsked(t) |
| + }) |
| + t.Run("not activator-managed", func(t *testing.T) { |
| + if err := x.a.reg.SetHA(e2eHomedHost); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := x.a.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if up, ok := x.a.edge.lookupUpstream(e2eHomedHost); !ok || !up.route.HA || up.hibernating { |
| + t.Fatalf("test bug: %s is not an HA service route: %+v", e2eHomedHost, up) |
| + } |
| + resp, body := x.fetch(t, e2eHomedHost, "/") |
| + if resp.StatusCode != http.StatusOK || e2eParseApp(t, body).marker != e2eHomeMarker { |
| + t.Fatalf("service = %d %q, want annie's own", resp.StatusCode, body) |
| + } |
| + up := haUp |
| + up.hibernating = false |
| + direct(t, newReq(), up, false, false) |
| + wantNotAsked(t) |
| + }) |
| + t.Run("an activator without the interface", func(t *testing.T) { |
| + y := newFwScene(t, fwOpts{aAct: fwPlainAct{}}) |
| + calls := y.b.calls.Load() |
| + _, body := y.fetch(t, fwHost, "/") |
| + local(t, fwHost, body) |
| + if n := y.b.calls.Load() - calls; n != 0 { |
| + t.Fatalf("betty saw %d requests", n) |
| + } |
| + }) |
| + if n := x.bApp.n.Load(); n != 0 { |
| + t.Fatalf("betty's app saw %d requests", n) |
| + } |
| +} |
| + |
| +func TestForwardHANotInView(t *testing.T) { |
| + x := newFwScene(t, fwOpts{aTarget: "carol"}) |
| + if err := x.seed.Delete(context.Background(), "control/edges/carol.json"); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.converge(t) |
| + if _, ok := x.a.homes.boxInView("carol", time.Now()); ok { |
| + t.Fatal("test bug: carol is in view") |
| + } |
| + calls := x.b.calls.Load() |
| + resp, body := x.fetch(t, fwHost, "/") |
| + if resp.StatusCode != http.StatusOK || !strings.HasPrefix(body, "annie|") { |
| + t.Fatalf("GET = %d %q, want annie's own 200", resp.StatusCode, body) |
| + } |
| + if n := x.b.calls.Load() - calls; n != 0 { |
| + t.Fatalf("betty saw %d requests", n) |
| + } |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardNotInView}}) |
| + // Served here, it is recorded here. |
| + annie, _ := x.take(t, fwHost) |
| + if annie.use.Requests != 1 || annie.use.HopRequests != 0 { |
| + t.Fatalf("annie metered %+v, want its own one request", annie.use) |
| + } |
| +} |
| + |
| +func TestForwardHADialFailureIs503RetryTen(t *testing.T) { |
| + stall := func(t *testing.T) { |
| + t.Helper() |
| + old := forwardDial |
| + forwardDial = func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + <-ctx.Done() |
| + return nil, ctx.Err() |
| + } |
| + t.Cleanup(func() { forwardDial = old }) |
| + } |
| + forward := func(t *testing.T, x *fwScene) { |
| + t.Helper() |
| + start := time.Now() |
| + resp, body := x.fetch(t, fwHost, "/") |
| + took := time.Since(start) |
| + if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "10" || |
| + body != "instance is waking elsewhere; retry shortly\n" { |
| + t.Fatalf("GET = %d Retry-After %q %q, want the unreachable 503", resp.StatusCode, resp.Header.Get("Retry-After"), body) |
| + } |
| + if took < forwardDialTimeout-100*time.Millisecond || took >= backhaulDialTimeout { |
| + t.Fatalf("the unreachable answer took %v, want about %v", took, forwardDialTimeout) |
| + } |
| + notes := x.aAct.noted() |
| + if len(notes) == 0 || notes[len(notes)-1] != (fwNote{fwHost, ForwardResult{Outcome: ForwardUnreachable}}) { |
| + t.Fatalf("notes = %+v, want ForwardUnreachable last", notes) |
| + } |
| + if n := x.bApp.n.Load(); n != 0 { |
| + t.Fatalf("betty's app saw %d requests", n) |
| + } |
| + } |
| + // backhaulTo the same address: every box here is dialled on annie's |
| + // port, so the hop lands on annie, which serves it itself (a verified |
| + // hop is never forwarded). It succeeds whatever the forward's dial seam |
| + // does, because it dials through its own 5 s transport. |
| + backhaul := func(t *testing.T, x *fwScene) { |
| + t.Helper() |
| + dial, ok := x.a.homes.boxInView("betty", time.Now()) |
| + if !ok { |
| + t.Fatal("test bug: betty is out of view") |
| + } |
| + r := httptest.NewRequest(http.MethodGet, "https://"+fwHost+"/hopped", nil) |
| + r.RemoteAddr = "203.0.113.9:4000" |
| + rec := httptest.NewRecorder() |
| + if !x.a.edge.backhaulTo(rec, r, fwHost, dial, "betty") { |
| + t.Fatal("backhaulTo did not answer") |
| + } |
| + if rec.Code != http.StatusOK || rec.Body.String() != "annie|"+fwHost+"|/hopped" { |
| + t.Fatalf("backhaulTo = %d %q, want the hop served", rec.Code, rec.Body.String()) |
| + } |
| + bt, ok := x.a.edge.backhaulTransports.Load(dial) |
| + if !ok || bt.(*http.Transport).TLSHandshakeTimeout != backhaulDialTimeout { |
| + t.Fatalf("backhaul transport for %s = %v, want its 5 s one", dial, bt) |
| + } |
| + } |
| + wantTwoTransports := func(t *testing.T, x *fwScene) { |
| + t.Helper() |
| + dial, _ := x.a.homes.boxInView("betty", time.Now()) |
| + bt, _ := x.a.edge.backhaulTransports.Load(dial) |
| + ft, ok := x.a.edge.forwardTransports.Load(dial) |
| + if !ok || ft == bt { |
| + t.Fatalf("forward transport %v, backhaul transport %v: want two", ft, bt) |
| + } |
| + } |
| + t.Run("forward then backhaul", func(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + stall(t) |
| + forward(t, x) |
| + backhaul(t, x) |
| + wantTwoTransports(t, x) |
| + }) |
| + t.Run("backhaul then forward", func(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + stall(t) |
| + backhaul(t, x) |
| + forward(t, x) |
| + wantTwoTransports(t, x) |
| + }) |
| +} |
| + |
| +func TestForwardHAReadsHolderHeader(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + for i, ref := range []string{"carol", "none"} { |
| + resp, _ := x.fetch(t, fwHost, "/holder?ref="+ref) |
| + if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get(holderHeader) != ref { |
| + t.Fatalf("GET = %d %s %q, want betty's 503 naming %s", resp.StatusCode, holderHeader, resp.Header.Get(holderHeader), ref) |
| + } |
| + notes := x.aAct.noted() |
| + if len(notes) != i+1 || notes[i] != (fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusServiceUnavailable, Holder: ref}}) { |
| + t.Fatalf("notes = %+v, want ForwardDone 503 %q", notes, ref) |
| + } |
| + } |
| +} |
| + |
| +func TestForwardHAUpgradeSwitchesProtocols(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + raw, err := net.DialTimeout("tcp", x.a.tlsAddr, 10*time.Second) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c := tls.Client(raw, &tls.Config{ServerName: fwHost, RootCAs: x.ca.pool, MinVersion: tls.VersionTLS12}) |
| + defer c.Close() |
| + c.SetDeadline(time.Now().Add(10 * time.Second)) |
| + fmt.Fprintf(c, "GET /socket HTTP/1.1\r\nHost: %s\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", fwHost) |
| + br := bufio.NewReader(c) |
| + resp, err := http.ReadResponse(br, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if resp.StatusCode != http.StatusSwitchingProtocols { |
| + t.Fatalf("handshake = %d, want 101", resp.StatusCode) |
| + } |
| + fmt.Fprint(c, "ping\n") |
| + if line, err := br.ReadString('\n'); err != nil || line != "betty:ping\n" { |
| + t.Fatalf("echo = %q %v, want betty's", line, err) |
| + } |
| + c.Close() |
| + laWaitFor(t, "the forward's note", func() bool { return len(x.aAct.noted()) == 1 }) |
| + x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusSwitchingProtocols}}) |
| +} |