carlos / platform Public

edge: path targets across boxes in ServeHTTP (#186)

ServeHTTP reads the full selection. A case 3 target (a front this box
does not serve) is the upstream every check sees, admission included. A
Remote selection is one backhaulRouteTo hop to the target's box with the
request's Host, dispatched right after the regional gate and before any
front HA step, the ownership block, the far asset catch and the miss arm
(servePathRemote). The Task 6 sameBox adapter is gone from the main
dispatch.

The ownership block moves to serveNameOwner (pathhop.go). It skips a case
3 target only while its front mark still matches the home map's exact
row; a stale mark runs the block, and a target whose front no box
publishes any more is refused (503), never served unchecked. The page
cache never takes a case 3 target (up.front).

path_across_e2e_test.go builds pathAcrossScene: three real edges (hub,
tenant, third) on one bucket with per-destination dial counters, reused
by Task 9.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev eba0430a4c2ca51e815ba1ba14cbb9d33272516c parent 3c619fc
4 files changed, +857 −50
  • internal/edge/edge.go +16 −48
  • internal/edge/pagecache.go +3 −2
  • internal/edge/path_across_e2e_test.go +732 −0
  • internal/edge/pathhop.go +106 −0
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index d53efa508..bc3cffef5 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -2314,9 +2314,10 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !pinned && e.serveDemoAPIAlias(w, r, host, hopped && demoHopWellFormed, demoHopPresent) {
return
}
- // sameBox: a target on another box, or a target for a front not served
- // here, still answers as before #186 until this dispatches them.
- up, ok := e.selectUpstream(r, host, r.URL.Path).sameBox()
+ // A case 3 target (a front not served here) is the up every check below
+ // sees; a Remote selection is dispatched after the regional gate.
+ sel := e.selectUpstream(r, host, r.URL.Path)
+ up, ok := sel.Up, sel.OK
// A pin that selects nothing here is answered here: never the backhaul,
// the far asset catch or the unknown-host fallback below.
if pinned && !ok {
@@ -2365,55 +2366,22 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if e.regionalGate(w, r, host, up, ok, hopped) {
return
}
+ // A prefix selected a target on another box (#186 spec §5.5): one hop
+ // to it, before any front HA step, the ownership block, the far asset
+ // catch or the miss arm. Never a verified hop, door call or pin.
+ if sel.Remote != nil && e.servePathRemote(w, r, host, sel.Remote) {
+ return
+ }
if e.routeHAIngress(w, r, host, up, ok) {
return
}
// Resolve local aliases and catch-alls against peer ownership before
- // serving. A held exact name refuses even a signed hop; a hop or door
- // request can never start another backhaul here. A linked request's
- // upstream is never an alias or a catch-all (pinnedUpstream), and it is
- // never backhauled: skipped outright, so a reload between the selection
- // and servesExactly cannot send it to another box.
- if ok && !pinned && (!e.servesExactly(host) || (up.alias && !up.platformAlias)) {
- name := host
- if !e.servesExactly(host) {
- if i := strings.IndexByte(host, '.'); i > 0 {
- name = "*" + host[i:]
- }
- }
- class := edgesfile.NameRoute
- if up.alias && !up.platformAlias {
- class = edgesfile.NameAlias
- }
- local := edgesfile.NameClaim{Name: name, Class: class, Account: registry.EffectiveAccount(up.route.Account), App: up.route.App,
- Stamp: int64(up.route.ClaimStamp), Incarnation: up.route.Incarnation, ServingSeq: up.route.ServingSeq, Eligible: true, Local: true}
- if class == edgesfile.NameAlias {
- local.TargetHost = up.route.Host
- }
- resolved := e.homes.Load().resolveName(host, []edgesfile.NameClaim{local}, false)
- if resolved.State == edgesfile.NameHeld {
- AdmissionResponse(w, r)
- return
- }
- if resolved.State == edgesfile.NameDialable && !resolved.Serving.Local && (resolved.AdmissionAware || (!hopped && !isDoor)) {
- if hopped {
- e.homes.Load().staleHopRefusal(w, host)
- return
- }
- if isDoor {
- e.unknownHost(w, r)
- return
- }
- if e.serveAssetFar(w, r, host) || e.backhaulTo(w, r, host, resolved.Serving.Dial, resolved.Serving.Box, backhaulOwnerOf(resolved.Authority)) {
- return
- }
- // A known remote owner must not fall through to another local app
- // when its mesh key or transport is unavailable.
- if resolved.AdmissionAware {
- AdmissionResponse(w, r)
- return
- }
- }
+ // serving (serveNameOwner, pathhop.go). A linked request's upstream is
+ // never an alias or a catch-all (pinnedUpstream), and it is never
+ // backhauled: skipped outright, so a reload between the selection and
+ // servesExactly cannot send it to another box.
+ if ok && !pinned && e.serveNameOwner(w, r, host, up, hopped, isDoor) {
+ return
}
// A regional deny entry has no local proxy. Refuse it if the legacy
diff --git a/internal/edge/pagecache.go b/internal/edge/pagecache.go
index 639157aa0..7526d9e2f 100644
--- a/internal/edge/pagecache.go
+++ b/internal/edge/pagecache.go
@@ -220,7 +220,8 @@ func (e *Edge) pagesOptedIn(up upstream) bool {
// - no plan throttle is active for the account, as the installed hook
// says, whether or not this request was let through (R3-9);
// - neither host's own entry nor the route's primary has path rows, and
-// the request was not dispatched by path to another route (P1-6);
+// the request was not dispatched by path to another route (P1-6),
+// here or for a front this box does not serve (#186 case 3, up.front);
// - the serving app's build's asset declarations are known and path is
// not under one of them (P2-9): those paths are the asset cache's. The
// app is the route's own account and app (pageScopeOf), so a policy
@@ -232,7 +233,7 @@ func (e *Edge) pageRouteEligible(host, path string, up upstream) (inputs string,
}
rt := up.route
m := e.current()
- if !pageServedHere(m, rt) || up.viaTunnel {
+ if !pageServedHere(m, rt) || up.viaTunnel || up.front != nil {
return "", false
}
if f := e.planThrottle.Load(); f != nil {
diff --git a/internal/edge/path_across_e2e_test.go b/internal/edge/path_across_e2e_test.go
new file mode 100644
index 000000000..31521da44
--- /dev/null
+++ b/internal/edge/path_across_e2e_test.go
@@ -0,0 +1,732 @@
+package edge
+
+// Path routes across boxes (#186, spec §5.4, §5.5): ServeHTTP dispatches a
+// selection end to end over three real edges sharing one bucket. A prefix on
+// the front name hub.example selects the target route tenant.example, homed
+// on another box.
+//
+// A (annie, 127.0.0.1): the hub, serving hub.example (the front)
+// B (betty, 127.0.0.2): the tenant, serving tenant.example (the target)
+// C (cindy, 127.0.0.3): neither
+//
+// Every box holds the claim's path rows (acme -> tenant.example), as Task 3
+// derives them on every box. Each edge dials every other through its own
+// per-address backhaul transport, counted per destination.
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const (
+ acrossHub = "hub.example"
+ acrossTenant = "tenant.example"
+ acrossAcct = "bae"
+ acrossOther = "baf"
+ acrossPrefix = "acme"
+
+ acrossIPHub = "127.0.0.1"
+ acrossIPTenant = "127.0.0.2"
+ acrossIPThird = "127.0.0.3"
+)
+
+// acrossSeen is one request a backend received: the Host it was asked for
+// and its path.
+type acrossSeen struct{ Host, Path string }
+
+// acrossApp is one box's backend. It records each request and answers
+// X-Carlos-Version: version, with the body version|Host|path.
+type acrossApp struct {
+ version string
+ srv *httptest.Server
+ mu sync.Mutex
+ seen []acrossSeen
+}
+
+func newAcrossApp(t *testing.T, version string) *acrossApp {
+ t.Helper()
+ a := &acrossApp{version: version}
+ a.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ a.mu.Lock()
+ a.seen = append(a.seen, acrossSeen{r.Host, r.URL.Path})
+ a.mu.Unlock()
+ w.Header().Set("X-Carlos-Version", version)
+ io.WriteString(w, version+"|"+r.Host+"|"+r.URL.Path)
+ }))
+ t.Cleanup(a.srv.Close)
+ return a
+}
+
+// addr is the backend's listening address, for a route's Addr.
+func (a *acrossApp) addr() string { return a.srv.Listener.Addr().String() }
+
+// requests is every request the backend has received, in order.
+func (a *acrossApp) requests() []acrossSeen {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return slices.Clone(a.seen)
+}
+
+// wantSeen fails unless the backend received exactly want, in order.
+func (a *acrossApp) wantSeen(t *testing.T, want ...acrossSeen) {
+ t.Helper()
+ if got := a.requests(); !slices.Equal(got, want) {
+ t.Fatalf("%s backend saw %v, want %v", a.version, got, want)
+ }
+}
+
+// pathAcrossScene is the three-edge deployment. Task 9 reuses it.
+//
+// Fields:
+// - hub, tenant, third: boxes A, B and C (backhaulEdge: edge, reg, homes,
+// mirror, client, calls).
+// - hubApp, tenantApp: the backends of hub.example on A and tenant.example
+// on B.
+// - store, ca, bucket: the shared bucket and the deployment CA.
+// - files: each box's edges-file hosts (box label -> host -> entry JSON),
+// as last published.
+//
+// Methods: publish/unpublish (an edges-file entry, then every home map and
+// cert mirror refreshed), route (a route row on one box, reloaded), path and
+// dropPath (one box's path row, reloaded), get (a client request landing on
+// one box), hop (a signed hop, optionally door-marked, landing on one box),
+// serve (ServeHTTP in process with a context, for door calls), dialsFrom and
+// dialsFromAny (a box's backhaul dials per destination address).
+type pathAcrossScene struct {
+ store release.Store
+ ca *e2eCA
+ bucket string
+
+ hub, tenant, third *backhaulEdge
+ hubApp, tenantApp *acrossApp
+
+ files map[string]map[string]string // box -> host -> entry JSON
+ ips map[*backhaulEdge]string
+ // dials counts each box's backhaul dials, keyed "box>ip".
+ dials sync.Map
+}
+
+// acrossRouteEntry is an edges-file entry for an exact route row: its door
+// owner (account, app), the route's own account and app, and both path
+// marks as the shared predicates publish them for a ready instance route.
+func acrossRouteEntry(account, app string, stamp int) string {
+ return acrossEntry(account, app, account, app, stamp, true, true)
+}
+
+// acrossEntry is an edges-file entry with every field given.
+func acrossEntry(account, app, routeAccount, routeApp string, stamp int, front, target bool) string {
+ return fmt.Sprintf(`{"role":"home","account":%q,"app":%q,"stamp":%d,"incarnation":1,"route_account":%q,"route_app":%q,"path_front":%t,"path_target":%t}`,
+ account, app, stamp, routeAccount, routeApp, front, target)
+}
+
+// acrossInstance is a ready instance route of account/app served from addr.
+func acrossInstance(host, account, app, addr string) registry.Route {
+ return registry.Route{Host: host, Kind: "instance", Status: "ready", Addr: addr, Account: account, App: app}
+}
+
+// newPathAcrossScene builds the standard scene: hub.example on A with the
+// prefix acme -> tenant.example, tenant.example on B, nothing on C; the path
+// row on all three boxes; A publishes hub.example and B tenant.example.
+func newPathAcrossScene(t *testing.T) *pathAcrossScene {
+ t.Helper()
+ s := &pathAcrossScene{bucket: t.TempDir(), ca: newE2ECA(t), files: map[string]map[string]string{}, ips: map[*backhaulEdge]string{}}
+ s.store = release.NewDirStore(s.bucket)
+ for _, h := range []string{acrossHub, acrossTenant} {
+ s.ca.publish(t, s.store, h)
+ }
+ if err := MintMeshKey(t.Context(), s.store); err != nil {
+ t.Fatal(err)
+ }
+ s.hubApp = newAcrossApp(t, "hub-1")
+ s.tenantApp = newAcrossApp(t, "tenant-1")
+ s.hub = newBackhaulEdgeWith(t, s.bucket, "annie", s.ca, nil, nil, []registry.Route{acrossInstance(acrossHub, acrossAcct, "hub", s.hubApp.addr())})
+ s.tenant = newBackhaulEdgeWith(t, s.bucket, "betty", s.ca, nil, nil, []registry.Route{acrossInstance(acrossTenant, acrossAcct, "tenant", s.tenantApp.addr())})
+ s.third = newBackhaulEdgeWith(t, s.bucket, "cindy", s.ca, nil, nil, nil)
+ s.ips[s.hub], s.ips[s.tenant], s.ips[s.third] = acrossIPHub, acrossIPTenant, acrossIPThird
+ old := backhaulRootCAs
+ backhaulRootCAs = s.ca.pool
+ t.Cleanup(func() { backhaulRootCAs = old })
+ for _, from := range s.boxes() {
+ for _, to := range s.boxes() {
+ s.dialAt(t, from, s.ips[to], to.tlsAddr)
+ }
+ }
+ for _, be := range s.boxes() {
+ s.path(t, be, acrossHub, acrossPrefix, acrossTenant, acrossAcct, "hub")
+ }
+ s.files["annie"] = map[string]string{acrossHub: acrossRouteEntry(acrossAcct, "hub", 5)}
+ s.files["betty"] = map[string]string{acrossTenant: acrossRouteEntry(acrossAcct, "tenant", 5)}
+ s.files["cindy"] = map[string]string{}
+ for _, be := range s.boxes() {
+ s.writeFile(t, be)
+ }
+ s.refresh(t)
+ return s
+}
+
+func (s *pathAcrossScene) boxes() []*backhaulEdge {
+ return []*backhaulEdge{s.hub, s.tenant, s.third}
+}
+
+// dialAt points from's backhaul transport for ip at addr, counting dials.
+func (s *pathAcrossScene) dialAt(t *testing.T, from *backhaulEdge, ip, addr string) {
+ t.Helper()
+ n, _ := s.dials.LoadOrStore(from.box+">"+ip, new(atomic.Int64))
+ tr := from.edge.backhaulTransport(ip)
+ tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ n.(*atomic.Int64).Add(1)
+ var d net.Dialer
+ return d.DialContext(ctx, network, addr)
+ }
+ t.Cleanup(tr.CloseIdleConnections)
+}
+
+// dialsFrom is how many backhaul dials from has made to ip.
+func (s *pathAcrossScene) dialsFrom(from *backhaulEdge, ip string) int64 {
+ n, ok := s.dials.Load(from.box + ">" + ip)
+ if !ok {
+ return 0
+ }
+ return n.(*atomic.Int64).Load()
+}
+
+// dialsFromAny is how many backhaul dials from has made to any box.
+func (s *pathAcrossScene) dialsFromAny(from *backhaulEdge) int64 {
+ var total int64
+ for _, to := range s.boxes() {
+ total += s.dialsFrom(from, s.ips[to])
+ }
+ return total
+}
+
+// fileBody is be's edges file as last published.
+func (s *pathAcrossScene) fileBody(be *backhaulEdge) string {
+ hosts := ""
+ for h, e := range s.files[be.box] {
+ if hosts != "" {
+ hosts += ","
+ }
+ hosts += fmt.Sprintf("%q:%s", h, e)
+ }
+ return fmt.Sprintf(`{"v":1,"box":%q,"eip":%q,"region":"eu","placement":"p","data_bucket":"data","secrets_key_fp":"fp","box_role":"serve","admitted":true,"drained":false,"generation":%q,"hosts":{%s}}`,
+ be.box, s.ips[be], time.Now().UTC().Format(time.RFC3339Nano), hosts)
+}
+
+func (s *pathAcrossScene) writeFile(t *testing.T, be *backhaulEdge) {
+ t.Helper()
+ putJSON(t, s.store, "control/edges/"+be.box+".json", s.fileBody(be))
+}
+
+// refresh refreshes every box's home map and cert mirror.
+func (s *pathAcrossScene) refresh(t *testing.T) {
+ t.Helper()
+ for _, be := range s.boxes() {
+ refreshHomeMap(t, be.homes)
+ if err := be.mirror.Refresh(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+// publish sets host's entry in be's edges file, writes it, and refreshes
+// every box.
+func (s *pathAcrossScene) publish(t *testing.T, be *backhaulEdge, host, entry string) {
+ t.Helper()
+ s.files[be.box][host] = entry
+ s.writeFile(t, be)
+ s.refresh(t)
+}
+
+// unpublish drops host from be's edges file and refreshes every box.
+func (s *pathAcrossScene) unpublish(t *testing.T, be *backhaulEdge, host string) {
+ t.Helper()
+ delete(s.files[be.box], host)
+ s.writeFile(t, be)
+ s.refresh(t)
+}
+
+func (s *pathAcrossScene) reload(t *testing.T, be *backhaulEdge) {
+ t.Helper()
+ if err := be.edge.Reload(); err != nil {
+ t.Fatalf("%s reload: %v", be.box, err)
+ }
+}
+
+// route writes a route row on be and reloads it.
+func (s *pathAcrossScene) route(t *testing.T, be *backhaulEdge, rt registry.Route) {
+ t.Helper()
+ if err := be.reg.Upsert(rt); err != nil {
+ t.Fatalf("%s upsert %s: %v", be.box, rt.Host, err)
+ }
+ s.reload(t, be)
+}
+
+// path writes one path row of the claim account/app on be and reloads it.
+func (s *pathAcrossScene) path(t *testing.T, be *backhaulEdge, host, prefix, target, account, app string) {
+ t.Helper()
+ remotePathRow(t, be.reg, host, prefix, target, account, app)
+ s.reload(t, be)
+}
+
+// dropPath deletes one path row on be and reloads it: one fold.
+func (s *pathAcrossScene) dropPath(t *testing.T, be *backhaulEdge, host, prefix string) {
+ t.Helper()
+ if err := be.reg.DeletePath(host, prefix); err != nil {
+ t.Fatalf("%s delete path %s/%s: %v", be.box, host, prefix, err)
+ }
+ s.reload(t, be)
+}
+
+// acrossResp is one answer as the client read it.
+type acrossResp struct {
+ code int
+ header http.Header
+ body string
+}
+
+// want fails unless the answer is code with a body starting with prefix.
+func (r acrossResp) want(t *testing.T, code int, prefix string) {
+ t.Helper()
+ if r.code != code || !strings.HasPrefix(r.body, prefix) {
+ t.Fatalf("answer %d %q, want %d %q...", r.code, r.body, code, prefix)
+ }
+}
+
+// wantStale fails unless the answer is the stale-hop refusal.
+func (r acrossResp) wantStale(t *testing.T) {
+ t.Helper()
+ if r.code != http.StatusServiceUnavailable || r.header.Get("Retry-After") != "2" {
+ t.Fatalf("answer %d %v %q, want 503 with Retry-After: 2", r.code, r.header, r.body)
+ }
+}
+
+// do sends req through be's client: DNS pointed at be.
+func (s *pathAcrossScene) do(t *testing.T, be *backhaulEdge, req *http.Request) acrossResp {
+ t.Helper()
+ resp, err := be.client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return acrossResp{resp.StatusCode, resp.Header, string(b)}
+}
+
+// get is a client's GET for https://host+path landing on be.
+func (s *pathAcrossScene) get(t *testing.T, be *backhaulEdge, host, path string) acrossResp {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodGet, "https://"+host+path, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s.do(t, be, req)
+}
+
+// hop is a verified hop for host+path landing on be, as a sending edge
+// signs one, door-marked when door is set.
+func (s *pathAcrossScene) hop(t *testing.T, be *backhaulEdge, host, path string, door bool) acrossResp {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodGet, "https://"+host+path, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ key := signingKey(be.homes.meshKeys())
+ if len(key) == 0 {
+ t.Fatal("no mesh key mirrored")
+ }
+ now := time.Now()
+ req.Header.Set(hopHeader, "1")
+ req.Header.Set(hopAuthHeader, signHop(key, host, now))
+ if door {
+ req.Header.Set(hopDoorHeader, signHopDoor(key, host, now))
+ }
+ return s.do(t, be, req)
+}
+
+// serve is ServeHTTP on be in process for GET host+path, with ctx applied to
+// the request's context (a door caller, for one).
+func (s *pathAcrossScene) serve(t *testing.T, be *backhaulEdge, host, path string, ctx func(context.Context) context.Context) acrossResp {
+ t.Helper()
+ r := httptest.NewRequest(http.MethodGet, "https://"+host+path, nil)
+ r = r.WithContext(ctx(r.Context()))
+ w := httptest.NewRecorder()
+ be.edge.ServeHTTP(w, r)
+ return acrossResp{w.Code, w.Header(), w.Body.String()}
+}
+
+// ---- the three placements ---------------------------------------------------
+
+// On the front's own box (case 2): the prefix selects the target on B, and
+// the request crosses once, Host unchanged.
+func TestPathAcrossFromFrontBox(t *testing.T) {
+ s := newPathAcrossScene(t)
+ res := s.get(t, s.hub, acrossHub, "/acme/api/version")
+ res.want(t, http.StatusOK, "tenant-1|")
+ if v := res.header.Get("X-Carlos-Version"); v != "tenant-1" {
+ t.Fatalf("X-Carlos-Version = %q, want tenant-1", v)
+ }
+ s.tenantApp.wantSeen(t, acrossSeen{acrossHub, "/acme/api/version"})
+ s.hubApp.wantSeen(t)
+ if a, c := s.dialsFrom(s.hub, acrossIPTenant), s.dialsFrom(s.hub, acrossIPThird); a != 1 || c != 0 {
+ t.Fatalf("A dialled B %d and C %d times, want 1 and 0", a, c)
+ }
+ // The receiving box made no hop of its own.
+ if n := s.dialsFromAny(s.tenant); n != 0 {
+ t.Fatalf("B dialled %d times, want 0", n)
+ }
+ // No prefix: the front's own route, here.
+ s.get(t, s.hub, acrossHub, "/other").want(t, http.StatusOK, "hub-1|"+acrossHub+"|/other")
+ if n := s.dialsFromAny(s.hub); n != 1 {
+ t.Fatalf("A dialled %d times after a prefix miss, want still 1", n)
+ }
+}
+
+// On the target's box, which does not serve the front (case 3): served
+// here, with every local check, and nothing dialled.
+func TestPathAcrossFromTenantBox(t *testing.T) {
+ s := newPathAcrossScene(t)
+ s.get(t, s.tenant, acrossHub, "/acme/x").want(t, http.StatusOK, "tenant-1|"+acrossHub+"|/acme/x")
+ s.hubApp.wantSeen(t)
+ if n := s.dialsFromAny(s.tenant); n != 0 {
+ t.Fatalf("B dialled %d times, want 0", n)
+ }
+}
+
+// On a box that serves neither (case 3, remote target): exactly one dial,
+// to the target's box.
+func TestPathAcrossFromThirdBox(t *testing.T) {
+ s := newPathAcrossScene(t)
+ s.get(t, s.third, acrossHub, "/acme/x").want(t, http.StatusOK, "tenant-1|"+acrossHub+"|/acme/x")
+ s.hubApp.wantSeen(t)
+ if b, a := s.dialsFrom(s.third, acrossIPTenant), s.dialsFrom(s.third, acrossIPHub); b != 1 || a != 0 {
+ t.Fatalf("C dialled B %d and A %d times, want 1 and 0", b, a)
+ }
+}
+
+// The wire host is the request's Host after the port strip, exactly as an
+// ordinary backhaul passes it: B verifies the MAC over its own literal
+// request host.
+func TestPathAcrossWireHostWithPort(t *testing.T) {
+ s := newPathAcrossScene(t)
+ req, err := http.NewRequest(http.MethodGet, "https://"+acrossHub+"/acme/port", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = acrossHub + ":443"
+ s.do(t, s.third, req).want(t, http.StatusOK, "tenant-1|")
+ if got := s.tenantApp.requests(); len(got) != 1 || got[0].Path != "/acme/port" {
+ t.Fatalf("tenant backend saw %v", got)
+ }
+ if n := s.dialsFrom(s.third, acrossIPTenant); n != 1 {
+ t.Fatalf("C dialled B %d times, want 1", n)
+ }
+}
+
+// A path that selects no prefix is today's backhaul to the front's home,
+// from either box that does not serve the front.
+func TestPathAcrossPrefixMissGoesToHub(t *testing.T) {
+ s := newPathAcrossScene(t)
+ s.get(t, s.third, acrossHub, "/other").want(t, http.StatusOK, "hub-1|"+acrossHub+"|/other")
+ s.get(t, s.tenant, acrossHub, "/").want(t, http.StatusOK, "hub-1|"+acrossHub+"|/")
+ s.tenantApp.wantSeen(t)
+ if a, b := s.dialsFrom(s.third, acrossIPHub), s.dialsFrom(s.third, acrossIPTenant); a != 1 || b != 0 {
+ t.Fatalf("C dialled A %d and B %d times, want 1 and 0", a, b)
+ }
+ if a := s.dialsFrom(s.tenant, acrossIPHub); a != 1 {
+ t.Fatalf("B dialled A %d times, want 1", a)
+ }
+}
+
+// A removed prefix stops selecting on a box as soon as that box folds the
+// removal: C sends the request to the front's home, and A, whose map still
+// names the target, serves the front on the arrived hop.
+func TestPathAcrossRemovedPrefixStopsWithinOneFold(t *testing.T) {
+ s := newPathAcrossScene(t)
+ s.get(t, s.third, acrossHub, "/acme/one").want(t, http.StatusOK, "tenant-1|")
+ s.dropPath(t, s.third, acrossHub, acrossPrefix)
+ s.get(t, s.third, acrossHub, "/acme/two").want(t, http.StatusOK, "hub-1|"+acrossHub+"|/acme/two")
+ s.tenantApp.wantSeen(t, acrossSeen{acrossHub, "/acme/one"})
+ if n := s.dialsFromAny(s.hub); n != 0 {
+ t.Fatalf("A dialled %d times serving an arrived hop, want 0", n)
+ }
+}
+
+// Review Focus 2: the sender's map and the receiver's disagree after a
+// republish (B now sends the prefix to tenant2.example on C). B answers the
+// stale-hop refusal and never forwards.
+func TestPathAcrossReceiverMapDiffers(t *testing.T) {
+ s := newPathAcrossScene(t)
+ const moved = "tenant2.example"
+ s.publish(t, s.third, moved, acrossRouteEntry(acrossAcct, "tenant2", 5))
+ s.dropPath(t, s.tenant, acrossHub, acrossPrefix)
+ s.path(t, s.tenant, acrossHub, acrossPrefix, moved, acrossAcct, "hub")
+
+ s.get(t, s.hub, acrossHub, "/acme/x").wantStale(t)
+ if n := s.dialsFrom(s.hub, acrossIPTenant); n != 1 {
+ t.Fatalf("A dialled B %d times, want 1", n)
+ }
+ if n := s.dialsFromAny(s.tenant); n != 0 {
+ t.Fatalf("B dialled %d times on an arrived hop, want 0", n)
+ }
+ s.tenantApp.wantSeen(t)
+ s.hubApp.wantSeen(t)
+}
+
+// A hop reaching the front's own box, whose map sends the prefix elsewhere
+// (a sender a tick behind): the front's own route, here, never onward.
+func TestPathAcrossHopToHubSelectingRemoteServesHub(t *testing.T) {
+ s := newPathAcrossScene(t)
+ s.hop(t, s.hub, acrossHub, "/acme/x", false).want(t, http.StatusOK, "hub-1|"+acrossHub+"|/acme/x")
+ if n := s.dialsFromAny(s.hub); n != 0 {
+ t.Fatalf("A dialled %d times on an arrived hop, want 0", n)
+ }
+ s.tenantApp.wantSeen(t)
+}
+
+// One hop, ever: a hop reaching a box that serves neither the front nor the
+// target is refused, whether or not a prefix selects.
+func TestPathAcrossNeverASecondHop(t *testing.T) {
+ s := newPathAcrossScene(t)
+ s.hop(t, s.third, acrossHub, "/acme/x", false).wantStale(t)
+ s.hop(t, s.third, acrossHub, "/other", false).wantStale(t)
+ if n := s.dialsFromAny(s.third); n != 0 {
+ t.Fatalf("C dialled %d times on arrived hops, want 0", n)
+ }
+ s.tenantApp.wantSeen(t)
+ s.hubApp.wantSeen(t)
+ // The target's box serves its local answer to a hop (no further hop).
+ s.hop(t, s.tenant, acrossHub, "/acme/y", false).want(t, http.StatusOK, "tenant-1|")
+ if n := s.dialsFromAny(s.tenant); n != 0 {
+ t.Fatalf("B dialled %d times on an arrived hop, want 0", n)
+ }
+}
+
+// Review Focus 1: a catch-all on B whose primary has a prefix map (one
+// target here, one on another box) is hit for another account's exact name
+// homed on C. The ownership block sends it to C, never to a prefix target.
+func TestPathAcrossWildcardDoesNotBeatExactName(t *testing.T) {
+ s := newPathAcrossScene(t)
+ const wild, other, far = "wild.example", "other.example", "far.example"
+ s.ca.publish(t, s.store, other)
+ wildApp := newAcrossApp(t, "wild-1")
+ otherApp := newAcrossApp(t, "other-1")
+ s.route(t, s.tenant, acrossInstance(wild, acrossAcct, "wild", wildApp.addr()))
+ if err := s.tenant.reg.UpsertAlias(registry.RouteAlias{Alias: "*.example", Host: wild, Account: acrossAcct, App: "wild"}); err != nil {
+ t.Fatal(err)
+ }
+ s.path(t, s.tenant, wild, acrossPrefix, acrossTenant, acrossAcct, "wild")
+ s.path(t, s.tenant, wild, "far", far, acrossAcct, "wild")
+ s.route(t, s.third, acrossInstance(other, acrossOther, "other", otherApp.addr()))
+ s.files["annie"][far] = acrossRouteEntry(acrossAcct, "far", 5)
+ s.writeFile(t, s.hub)
+ s.publish(t, s.third, other, acrossRouteEntry(acrossOther, "other", 5))
+
+ s.get(t, s.tenant, other, "/acme/x").want(t, http.StatusOK, "other-1|"+other+"|/acme/x")
+ s.get(t, s.tenant, other, "/far/y").want(t, http.StatusOK, "other-1|"+other+"|/far/y")
+ s.tenantApp.wantSeen(t)
+ wildApp.wantSeen(t)
+ if c, a := s.dialsFrom(s.tenant, acrossIPThird), s.dialsFrom(s.tenant, acrossIPHub); c < 1 || a != 0 {
+ t.Fatalf("B dialled C %d and A %d times, want at least 1 and 0", c, a)
+ }
+}
+
+// A door caller never selects across boxes: on the front's box it gets the
+// front's own route; on a box that does not serve the front, the door's
+// backhaul to the front's home, where the door-marked hop gets the front's
+// own route too.
+func TestPathAcrossDoorCallStaysSameBox(t *testing.T) {
+ s := newPathAcrossScene(t)
+ door := func(c context.Context) context.Context {
+ return context.WithValue(c, doorCallerKey{}, doorCaller{Account: acrossAcct, App: "hub"})
+ }
+ s.serve(t, s.hub, acrossHub, "/acme/x", door).want(t, http.StatusOK, "hub-1|"+acrossHub+"|/acme/x")
+ if n := s.dialsFromAny(s.hub); n != 0 {
+ t.Fatalf("A dialled %d times for a door call, want 0", n)
+ }
+ s.serve(t, s.third, acrossHub, "/acme/y", door).want(t, http.StatusOK, "hub-1|"+acrossHub+"|/acme/y")
+ if a, b := s.dialsFrom(s.third, acrossIPHub), s.dialsFrom(s.third, acrossIPTenant); a != 1 || b != 0 {
+ t.Fatalf("C dialled A %d and B %d times for a door call, want 1 and 0", a, b)
+ }
+ s.tenantApp.wantSeen(t)
+}
+
+// A door-marked hop never takes a remote-map answer: on the target's box it
+// is the stale-hop refusal, though an ordinary hop is served there; on the
+// front's box, the front's own route.
+func TestPathAcrossDoorHopMapsDiffer(t *testing.T) {
+ s := newPathAcrossScene(t)
+ s.hop(t, s.tenant, acrossHub, "/acme/x", true).wantStale(t)
+ s.tenantApp.wantSeen(t)
+ s.hop(t, s.hub, acrossHub, "/acme/x", true).want(t, http.StatusOK, "hub-1|")
+ for _, be := range s.boxes() {
+ if n := s.dialsFromAny(be); n != 0 {
+ t.Fatalf("%s dialled %d times on an arrived door hop, want 0", be.box, n)
+ }
+ }
+}
+
+// acrossAdmission is a tenant admission gate. Admitted reports open; exempt
+// is the route host it exempts; asked records each route it was asked to
+// exempt. between, when set, runs once inside the next TenantAdmitted call,
+// which ServeHTTP makes after selection and before the ownership block.
+type acrossAdmission struct {
+ mu sync.Mutex
+ open bool
+ exempt string
+ asked []string
+ between func()
+}
+
+func (a *acrossAdmission) TenantAdmitted() bool {
+ a.mu.Lock()
+ f := a.between
+ a.between = nil
+ open := a.open
+ a.mu.Unlock()
+ if f != nil {
+ f()
+ }
+ return open
+}
+
+func (a *acrossAdmission) TenantAdmissionExempt(rt registry.Route) bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.asked = append(a.asked, rt.Host)
+ return rt.Host == a.exempt
+}
+
+func (a *acrossAdmission) askedHosts() []string {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return slices.Clone(a.asked)
+}
+
+// A case 3 target is the upstream admission sees: B's tenant admission is
+// closed, and it is judged (and refused) against the tenant route, though
+// it exempts the front name.
+func TestPathAcrossAdmissionClosedRefusesCase3(t *testing.T) {
+ s := newPathAcrossScene(t)
+ adm := &acrossAdmission{exempt: acrossHub}
+ s.tenant.edge.admission = adm
+ res := s.get(t, s.tenant, acrossHub, "/acme/x")
+ if res.code != http.StatusServiceUnavailable {
+ t.Fatalf("closed admission: %d %q, want 503", res.code, res.body)
+ }
+ if got := adm.askedHosts(); !slices.Equal(got, []string{acrossTenant}) {
+ t.Fatalf("admission was asked about %v, want the tenant route only", got)
+ }
+ s.tenantApp.wantSeen(t)
+ s.hubApp.wantSeen(t)
+ if n := s.dialsFromAny(s.tenant); n != 0 {
+ t.Fatalf("B dialled %d times, want 0", n)
+ }
+ // The same gate exempting the tenant route lets it through.
+ adm.mu.Lock()
+ adm.exempt = acrossTenant
+ adm.mu.Unlock()
+ s.get(t, s.tenant, acrossHub, "/acme/y").want(t, http.StatusOK, "tenant-1|")
+}
+
+// The front's published row changes between selection (which marked the
+// case 3 target with the row it checked) and the ownership block. The mark
+// no longer matches, so the block runs as for any name this box does not
+// serve exactly, and the target never sees the request: re-owned, it goes to
+// the front's home; withdrawn from every box, it is refused (503), never
+// served here unchecked.
+func TestPathAcrossFrontOwnerChangedBetweenChecks(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ entry string // annie's new entry for the front; "" withdraws it
+ code int
+ body string
+ dials int64 // B's dials to A
+ }{
+ {"reowned", acrossEntry(acrossOther, "hub2", acrossOther, "hub2", 9, true, true), http.StatusOK, "hub-1|" + acrossHub + "|/acme/x", 1},
+ {"withdrawn", "", http.StatusServiceUnavailable, "", 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s := newPathAcrossScene(t)
+ var hookErr error
+ ran := false
+ adm := &acrossAdmission{open: true}
+ adm.between = func() {
+ ran = true
+ if tc.entry == "" {
+ delete(s.files["annie"], acrossHub)
+ } else {
+ s.files["annie"][acrossHub] = tc.entry
+ }
+ if _, etag, err := s.store.Get(context.Background(), "control/edges/annie.json"); err != nil {
+ hookErr = err
+ } else if _, err := s.store.Put(context.Background(), "control/edges/annie.json", []byte(s.fileBody(s.hub)), etag); err != nil {
+ hookErr = err
+ } else {
+ hookErr = s.tenant.homes.Refresh(context.Background())
+ }
+ }
+ s.tenant.edge.admission = adm
+ res := s.get(t, s.tenant, acrossHub, "/acme/x")
+ if !ran || hookErr != nil {
+ t.Fatalf("the republish between the checks did not run cleanly: ran=%v err=%v", ran, hookErr)
+ }
+ res.want(t, tc.code, tc.body)
+ s.tenantApp.wantSeen(t)
+ if n := s.dialsFrom(s.tenant, acrossIPHub); n != tc.dials {
+ t.Fatalf("B dialled A %d times, want %d", n, tc.dials)
+ }
+ })
+ }
+}
+
+// Spec §5.5: the page cache's exclusion of path-routed hosts holds for case
+// 3. The target serves the front's request every time and nothing is
+// stored, while the target's own host is cached as usual.
+func TestPathAcrossPageCacheExcludesCase3(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody))
+ const front = "hub.pcfront.example"
+ remotePathRow(t, s.reg, front, acrossPrefix, pcHost, "abc", "hub")
+ if err := s.e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ m := newHomeMap(meshTestStore(t), "annie")
+ putPathFile(t, m, "betty", "2.2.2.2", map[string]string{front: frontRow("abc", "hub")})
+ refreshHomeMap(t, m)
+ s.e.homes.Store(m)
+
+ sel := s.e.selectUpstream(httptest.NewRequest(http.MethodGet, "http://"+front+"/acme/p", nil), front, "/acme/p")
+ if !sel.OK || !sel.LocalTarget || sel.Up.front == nil {
+ t.Fatalf("precondition: selection %s, want a case 3 local target", describeSel(sel))
+ }
+ if _, ok := s.e.pageRouteEligible(front, "/acme/p", sel.Up); ok {
+ t.Fatal("a case 3 target is eligible for the page cache")
+ }
+ for i := range 2 {
+ rec := s.do(http.MethodGet, "http://"+front+"/acme/p")
+ wantBody(t, rec, http.StatusOK, pcBody)
+ wantCache(t, rec, "bypass")
+ if n := s.b.n.Load(); n != int64(i+1) {
+ t.Fatalf("request %d: the app saw %d requests, want %d", i, n, i+1)
+ }
+ }
+ s.wantNothingStored("case 3 requests")
+ // Control: the target's own host is cached on the same box.
+ wantCache(t, s.get("/p"), "miss")
+ wantCache(t, s.get("/p"), "hit")
+}
diff --git a/internal/edge/pathhop.go b/internal/edge/pathhop.go
index c061e624b..54bf06ead 100644
--- a/internal/edge/pathhop.go
+++ b/internal/edge/pathhop.go
@@ -8,6 +8,10 @@ package edge
import (
"fmt"
"net/http"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/registry"
)
// backhaulRouteTo is backhaulTo for a request whose wire Host (signed, SNI,
@@ -61,3 +65,105 @@ func hopName(wireHost, routeHost string) string {
}
return wireHost + " (route " + routeHost + ")"
}
+
+// servePathRemote answers a non-hop request whose selection is Remote:
+// backhaulRouteTo(w, r, host, rt.Target, rt.Route.Dial, rt.Route.Box, rt.Route.Owner).
+// Never reached on a verified hop (selectUpstream settles that), a door call
+// or a pinned request, none of which selects across boxes.
+//
+// host is ServeHTTP's request host after its port strip, exactly what an
+// ordinary backhaul signs: the receiving box verifies the MAC against its own
+// literal request host. The receiving box selects again, from Host and path,
+// and serves only a local answer (spec §5.4).
+//
+// It always answers. With no mesh key mirrored (backhaulRouteTo's one false)
+// the request still belongs to the target, so nothing on this box answers it
+// instead (not the front's route, not its declared assets): the 503 a known
+// remote owner gets when it cannot be reached (serveNameOwner).
+func (e *Edge) servePathRemote(w http.ResponseWriter, r *http.Request, host string, rt *remoteTarget) bool {
+ if !e.backhaulRouteTo(w, r, host, rt.Target, rt.Route.Dial, rt.Route.Box, rt.Route.Owner) {
+ AdmissionResponse(w, r)
+ }
+ return true
+}
+
+// frontMarkHolds reports whether up is a case 3 target (selectAcross: a front
+// this box does not serve) whose front mark names host and still matches the
+// home map's exact row for host: a front route with the same account, app,
+// stamp and incarnation. A wildcard or alias match never carries a mark.
+func (e *Edge) frontMarkHolds(host string, up upstream) bool {
+ f := up.front
+ if f == nil || f.Host != host {
+ return false
+ }
+ fi, ok := e.homes.Load().exactPathRoute(host)
+ return ok && fi.Front && fi.Account == f.Account && fi.App == f.App && fi.Stamp == f.Stamp && fi.Incarnation == f.Incarnation
+}
+
+// serveNameOwner is ServeHTTP's ownership block: a selected upstream reached
+// through a name this box does not serve exactly (a catch-all, or a case 3
+// target), or through an attached alias, is resolved against peer ownership
+// before it is served. It reports whether it answered. A held exact name
+// refuses even a signed hop; a hop or door request never starts another
+// backhaul here.
+//
+// The one exception (spec §5.5): a case 3 target whose front mark still holds
+// (frontMarkHolds) is served here without it. A case 3 target whose mark no
+// longer holds (the front was re-owned or re-claimed since selection) runs the
+// block as any name this box does not serve, and is never served here
+// unchecked: when the block finds no other owner, the 503 a known remote
+// owner gets, so the next request selects again.
+func (e *Edge) serveNameOwner(w http.ResponseWriter, r *http.Request, host string, up upstream, hopped, isDoor bool) bool {
+ if e.frontMarkHolds(host, up) {
+ return false
+ }
+ exact := e.servesExactly(host)
+ attached := up.alias && !up.platformAlias
+ if up.front == nil && exact && !attached {
+ return false
+ }
+ name := host
+ if !exact {
+ if i := strings.IndexByte(host, '.'); i > 0 {
+ name = "*" + host[i:]
+ }
+ }
+ class := edgesfile.NameRoute
+ if attached {
+ class = edgesfile.NameAlias
+ }
+ local := edgesfile.NameClaim{Name: name, Class: class, Account: registry.EffectiveAccount(up.route.Account), App: up.route.App,
+ Stamp: int64(up.route.ClaimStamp), Incarnation: up.route.Incarnation, ServingSeq: up.route.ServingSeq, Eligible: true, Local: true}
+ if class == edgesfile.NameAlias {
+ local.TargetHost = up.route.Host
+ }
+ resolved := e.homes.Load().resolveName(host, []edgesfile.NameClaim{local}, false)
+ if resolved.State == edgesfile.NameHeld {
+ AdmissionResponse(w, r)
+ return true
+ }
+ if resolved.State == edgesfile.NameDialable && !resolved.Serving.Local && (resolved.AdmissionAware || (!hopped && !isDoor)) {
+ if hopped {
+ e.homes.Load().staleHopRefusal(w, host)
+ return true
+ }
+ if isDoor {
+ e.unknownHost(w, r)
+ return true
+ }
+ if e.serveAssetFar(w, r, host) || e.backhaulTo(w, r, host, resolved.Serving.Dial, resolved.Serving.Box, backhaulOwnerOf(resolved.Authority)) {
+ return true
+ }
+ // A known remote owner must not fall through to another local app
+ // when its mesh key or transport is unavailable.
+ if resolved.AdmissionAware {
+ AdmissionResponse(w, r)
+ return true
+ }
+ }
+ if up.front != nil {
+ AdmissionResponse(w, r)
+ return true
+ }
+ return false
+}