carlos / platform Public

edge: backhaul a route under its front Host (#186)

backhaulRouteTo (pathhop.go) is backhaulTo for a hop whose wire Host
(the MAC, SNI, the proxied Host and the transport's pool key) is the
front name while every holder, alternative and handover decision is
keyed on the route it is for (spec §5.4, §5.7). backhaulTo is now the
wrapper with both names one host; the hopVerified guard stays first.
backhaulAttempt takes the two names and uses each where it belongs.

Not yet called from dispatch (Task 8 wires it).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a8d8f5e7c151c39f4f6a333a98986408ffd2d5c6 parent f09a3fd
4 files changed, +422 −40
  • internal/edge/backhaul_holder.go +18 −14
  • internal/edge/edge.go +3 −26
  • internal/edge/pathhop.go +63 −0
  • internal/edge/pathhop_test.go +338 −0
diff --git a/internal/edge/backhaul_holder.go b/internal/edge/backhaul_holder.go
index d84a8dbed..d9ee78ed6 100644
--- a/internal/edge/backhaul_holder.go
+++ b/internal/edge/backhaul_holder.go
@@ -201,11 +201,15 @@ func (t backhaulHolderTransport) RoundTrip(r *http.Request) (*http.Response, err
// with a body is never copied here, never marked, and streams as it
// always has; it gets today's answer from a draining box (§25.8). whole
// is the (empty) copy on the second attempt.
-func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dial, box string, key []byte, owner backhaulOwner, whole *wholeBody) {
+//
+// wireHost is what the hop is signed for and sent as (hopTo); routeHost is
+// the route it is for, and keys every holder, alternative and handover
+// decision (backhaulRouteTo). They are one name except on a path hop.
+func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, wireHost, routeHost, dial, box string, key []byte, owner backhaulOwner, whole *wholeBody) {
n, ok := nextForwardAttempt(r)
if !ok {
// I4: never a third attempt.
- e.logThrottled("backhaul-error "+box, fmt.Sprintf("backhaul %s to %s: no attempt left", host, box))
+ e.logThrottled("backhaul-error "+box, fmt.Sprintf("backhaul %s to %s: no attempt left", hopName(wireHost, routeHost), box))
w.WriteHeader(http.StatusBadGateway)
return
}
@@ -247,7 +251,7 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia
}
ref := resp.Header.Get(holderHeader)
if ref != box {
- e.dropBackhaulHolder(host, box, "holder refusal", owner)
+ e.dropBackhaulHolder(routeHost, box, "holder refusal", owner)
}
if handover != "" {
// §25.5: followed only on a marked first attempt (H2, H3), to a
@@ -262,12 +266,12 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia
return nil
}
now := time.Now()
- addr, ok := e.homes.Load().handoverAlternative(host, hRef, box, owner, now)
+ addr, ok := e.homes.Load().handoverAlternative(routeHost, hRef, box, owner, now)
if !ok {
return nil
}
- if e.backhaulHolders.remember(host, hRef, owner, now) {
- e.logThrottled("backhaul-holder-learn "+hRef, fmt.Sprintf("backhaul holder learned for %s: %s", host, hRef))
+ if e.backhaulHolders.remember(routeHost, hRef, owner, now) {
+ e.logThrottled("backhaul-holder-learn "+hRef, fmt.Sprintf("backhaul holder learned for %s: %s", routeHost, hRef))
}
nextDial, nextRef, nextReason = addr, hRef, "handover"
return errBackhaulHolder
@@ -280,8 +284,8 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia
if !ok {
return nil
}
- if e.backhaulHolders.remember(host, ref, owner, now) {
- e.logThrottled("backhaul-holder-learn "+ref, fmt.Sprintf("backhaul holder learned for %s: %s", host, ref))
+ if e.backhaulHolders.remember(routeHost, ref, owner, now) {
+ e.logThrottled("backhaul-holder-learn "+ref, fmt.Sprintf("backhaul holder learned for %s: %s", routeHost, ref))
}
// HTTP/2 supplies a body object even when the request has no body.
noBody := r.ContentLength == 0 && len(r.TransferEncoding) == 0
@@ -297,18 +301,18 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia
}
var dialErr *forwardConnectError
if !connected.Load() && (connectFailed.Load() || errors.As(err, &dialErr)) && r.Context().Err() == nil {
- e.dropBackhaulHolder(host, box, "connect failure", owner)
+ e.dropBackhaulHolder(routeHost, box, "connect failure", owner)
m := e.homes.Load()
now := time.Now()
m.markBackhaulSuspect(box, now)
if retry {
- if addr, ref, ok := m.backhaulAlternative(host, box, owner, now); ok {
+ if addr, ref, ok := m.backhaulAlternative(routeHost, box, owner, now); ok {
nextDial, nextRef, nextReason = addr, ref, "connect fallback"
return
}
}
}
- e.logThrottled("backhaul-error "+box, fmt.Sprintf("backhaul %s to %s (%s): %v", host, box, dial, err))
+ e.logThrottled("backhaul-error "+box, fmt.Sprintf("backhaul %s to %s (%s): %v", hopName(wireHost, routeHost), box, dial, err))
w.WriteHeader(http.StatusBadGateway)
}
// A streamed body is watched for its end: an upstream that answers
@@ -322,17 +326,17 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia
onResponse = func(resp *http.Response) { closeAfterEarlyAnswer(w, r, streamed, resp) }
}
}
- e.hopTo(w, r, host, dial, box, key, "backhaul", tr, onError, onResponse)
+ e.hopTo(w, r, wireHost, dial, box, key, "backhaul", tr, onError, onResponse)
finishEarlyAnswer(w, streamed)
// The refused hop releases its capacity slot before the holder starts a
// response that may stream or remain upgraded indefinitely.
if nextRef != "" {
- e.logThrottled("backhaul-retry "+nextRef, fmt.Sprintf("backhaul %s for %s: %s to %s", nextReason, host, box, nextRef))
+ e.logThrottled("backhaul-retry "+nextRef, fmt.Sprintf("backhaul %s for %s: %s to %s", nextReason, hopName(wireHost, routeHost), box, nextRef))
// First attempt plus one retry, at most two attempts total. A connect
// fallback, a §6.5 holder follow and a handover follow spend the
// same budget (nextForwardAttempt). Start with the original context
// so trace callbacks cannot accumulate; a marked bodyless request
// goes again unmarked.
- e.backhaulAttempt(w, original, host, nextDial, nextRef, key, owner, whole)
+ e.backhaulAttempt(w, original, wireHost, routeHost, nextDial, nextRef, key, owner, whole)
}
}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 8a7b9e044..d53efa508 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -4632,33 +4632,10 @@ func (e *Edge) backhaul(w http.ResponseWriter, r *http.Request, host string) boo
}
// backhaulTo signs and forwards to the checked owner's box or a substitute
-// with the same owner. The arrived-hop guard prevents onward forwarding.
-// It answers false only when no mesh key is mirrored.
+// with the same owner: backhaulRouteTo (pathhop.go) for a request whose wire
+// Host and route are one name. The arrived-hop guard is that function's first.
func (e *Edge) backhaulTo(w http.ResponseWriter, r *http.Request, host, eip, box string, owner backhaulOwner) bool {
- m := e.homes.Load()
- if hopVerified(r.Context()) {
- m.staleHopRefusal(w, host)
- return true
- }
- if eip == "" {
- AdmissionResponse(w, r)
- return true
- }
- // Sign with the mirror's cached pair, .next preferred (signingKey, mesh.go)
- // — never a store read on the request path. NO KEY MEANS NO DIAL: signHop
- // would happily HMAC under an empty key, the home edge would refuse the
- // result, and the request would have crossed a region to be served as an
- // ordinary client with its forwarding chain stripped. Falling through to
- // the unknown-host answer is both cheaper and honest about the deployment
- // being mid-bootstrap.
- key := signingKey(m.meshKeys())
- if len(key) == 0 {
- e.logThrottled("backhaul-no-mesh-key", fmt.Sprintf("%s is homed on %s but no mesh key is mirrored — not dialling (the request gets the unknown-host answer until the key lands)", host, box))
- return false
- }
- eip, box = e.backhaulTarget(host, eip, box, owner)
- e.backhaulAttempt(w, withForwardAttempts(r), host, eip, box, key, owner, nil)
- return true
+ return e.backhaulRouteTo(w, r, host, host, eip, box, owner)
}
// hopTo is the sign-admit-proxy core backhaulTo and a region HA forward
diff --git a/internal/edge/pathhop.go b/internal/edge/pathhop.go
new file mode 100644
index 000000000..c061e624b
--- /dev/null
+++ b/internal/edge/pathhop.go
@@ -0,0 +1,63 @@
+package edge
+
+// Path routes across boxes (#186, spec §5.4 and §5.7): the hop a remote
+// selection makes. A prefix on the front name H selects a target route T on
+// another box, and the request crosses as an ordinary backhaul for T in every
+// respect but its wire Host and MAC, which stay H's.
+
+import (
+ "fmt"
+ "net/http"
+)
+
+// backhaulRouteTo is backhaulTo for a request whose wire Host (signed, SNI,
+// sent) is wireHost while every holder, alternative and handover decision is
+// keyed on routeHost. backhaulTo(w, r, h, ...) == backhaulRouteTo(w, r, h, h, ...).
+//
+// The split (spec §5.7): wireHost is the request's own Host, the name the app
+// is asked for, the hop's MAC and SNI, and the transport's pool key
+// (hopTo). routeHost is the route the hop is for: the holder cache, the
+// suspect-box and handover alternatives, the holder drops, and the log lines
+// naming the host a holder was learned for. owner is routeHost's backhaul
+// owner, and eip and box are where routeHost is served.
+//
+// The hopVerified guard is FIRST, as in backhaul: one hop, ever. A request
+// that arrived as a verified hop is refused here, not forwarded, whichever
+// route it would have been for. It answers false only when no mesh key is
+// mirrored.
+func (e *Edge) backhaulRouteTo(w http.ResponseWriter, r *http.Request, wireHost, routeHost, eip, box string, owner backhaulOwner) bool {
+ m := e.homes.Load()
+ if hopVerified(r.Context()) {
+ m.staleHopRefusal(w, wireHost)
+ return true
+ }
+ if eip == "" {
+ AdmissionResponse(w, r)
+ return true
+ }
+ // Sign with the mirror's cached pair, .next preferred (signingKey, mesh.go)
+ // — never a store read on the request path. NO KEY MEANS NO DIAL: signHop
+ // would happily HMAC under an empty key, the home edge would refuse the
+ // result, and the request would have crossed a region to be served as an
+ // ordinary client with its forwarding chain stripped. Falling through to
+ // the unknown-host answer is both cheaper and honest about the deployment
+ // being mid-bootstrap.
+ key := signingKey(m.meshKeys())
+ if len(key) == 0 {
+ e.logThrottled("backhaul-no-mesh-key", fmt.Sprintf("%s is homed on %s but no mesh key is mirrored — not dialling (the request gets the unknown-host answer until the key lands)", hopName(wireHost, routeHost), box))
+ return false
+ }
+ eip, box = e.backhaulTarget(routeHost, eip, box, owner)
+ e.backhaulAttempt(w, withForwardAttempts(r), wireHost, routeHost, eip, box, key, owner, nil)
+ return true
+}
+
+// hopName is how a backhaul's log lines name what it carries: the host
+// alone for an ordinary backhaul, and the wire host with its route for a
+// path hop, so an operator reading a failure sees both names.
+func hopName(wireHost, routeHost string) string {
+ if wireHost == routeHost {
+ return wireHost
+ }
+ return wireHost + " (route " + routeHost + ")"
+}
diff --git a/internal/edge/pathhop_test.go b/internal/edge/pathhop_test.go
new file mode 100644
index 000000000..3a6cad5a5
--- /dev/null
+++ b/internal/edge/pathhop_test.go
@@ -0,0 +1,338 @@
+package edge
+
+import (
+ "context"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "fmt"
+ "io"
+ "math/big"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// A path-selected hop (#186 spec §5.4, §5.7): the request's Host is the front
+// name hub.example, and the route the hop is for is tenant.example on another
+// box. The wire carries hub.example; every holder decision is tenant.example's.
+const (
+ pathHopWire = "hub.example"
+ pathHopRoute = "tenant.example"
+)
+
+// pathHopScene is BackhaulHolderScene's layout for a path hop: a sending edge
+// (dennis, region us) and destination boxes at distinct 127.0.0.N addresses,
+// each dialled through the sender's own per-address backhaul transport. A
+// destination's edges file publishes the target route's row; the front name
+// is published nowhere.
+type pathHopScene struct {
+ store release.Store
+ ca *e2eCA
+ bucket string
+ sender *backhaulEdge
+ edges []*backhaulEdge
+}
+
+func newPathHopScene(t *testing.T) *pathHopScene {
+ t.Helper()
+ s := &pathHopScene{bucket: t.TempDir(), ca: newE2ECA(t)}
+ s.store = release.NewDirStore(s.bucket)
+ s.ca.publish(t, s.store, pathHopWire)
+ if err := MintMeshKey(t.Context(), s.store); err != nil {
+ t.Fatal(err)
+ }
+ s.sender = newBackhaulEdge(t, s.bucket, "dennis", s.ca, nil, nil)
+ s.edges = append(s.edges, s.sender)
+ old := backhaulRootCAs
+ backhaulRootCAs = s.ca.pool
+ t.Cleanup(func() { backhaulRootCAs = old })
+ s.file(t, "dennis", "127.0.0.1", "us", 0)
+ return s
+}
+
+// file publishes box's edges file at ip in region. A non-zero stamp gives it
+// the target route's row with that stamp (the higher stamp serves).
+func (s *pathHopScene) file(t *testing.T, box, ip, region string, stamp int) {
+ t.Helper()
+ hosts := ""
+ if stamp != 0 {
+ hosts = fmt.Sprintf(`%q:{"role":"home","account":"acct","app":"tenant","stamp":%d,"route_account":"acct","route_app":"tenant","path_target":true}`, pathHopRoute, stamp)
+ }
+ putJSON(t, s.store, "control/edges/"+box+".json", fmt.Sprintf(`{"v":1,"box":%q,"eip":%q,"region":%q,"placement":"p","data_bucket":"data","secrets_key_fp":"fp","box_role":"serve","admitted":true,"drained":false,"generation":%q,"hosts":{%s}}`,
+ box, ip, region, time.Now().UTC().Format(time.RFC3339Nano), hosts))
+}
+
+// dialAt points the sender's backhaul transport for ip at addr.
+func (s *pathHopScene) dialAt(t *testing.T, ip, addr string) {
+ t.Helper()
+ tr := s.sender.edge.backhaulTransport(ip)
+ tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ var d net.Dialer
+ return d.DialContext(ctx, network, addr)
+ }
+ t.Cleanup(tr.CloseIdleConnections)
+}
+
+// edge adds a real receiving edge whose registry serves routes.
+func (s *pathHopScene) edge(t *testing.T, box, ip string, stamp int, routes map[string]string) *backhaulEdge {
+ t.Helper()
+ be := newBackhaulEdge(t, s.bucket, box, s.ca, nil, routes)
+ s.edges = append(s.edges, be)
+ s.file(t, box, ip, "eu", stamp)
+ s.dialAt(t, ip, be.tlsAddr)
+ return be
+}
+
+// pathHopBox is a destination box's 443 door reduced to a handler, presenting
+// the deployment CA's certificate for the front name only. It records what
+// arrived on the wire.
+type pathHopBox struct {
+ mu sync.Mutex
+ hosts []string // r.Host of each request
+ auths []string // X-Carlos-Hop-Auth of each request
+ srv *httptest.Server
+}
+
+func (b *pathHopBox) seen() (hosts, auths []string) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return append([]string(nil), b.hosts...), append([]string(nil), b.auths...)
+}
+
+// box adds a raw destination box answering with h.
+func (s *pathHopScene) box(t *testing.T, name, ip string, stamp int, h http.HandlerFunc) *pathHopBox {
+ t.Helper()
+ b := &pathHopBox{}
+ b.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b.mu.Lock()
+ b.hosts = append(b.hosts, r.Host)
+ b.auths = append(b.auths, r.Header.Get(hopAuthHeader))
+ b.mu.Unlock()
+ h(w, r)
+ }))
+ b.srv.TLS = &tls.Config{Certificates: []tls.Certificate{s.ca.leaf(t, pathHopWire)}}
+ b.srv.StartTLS()
+ t.Cleanup(b.srv.Close)
+ s.file(t, name, ip, "eu", stamp)
+ s.dialAt(t, ip, b.srv.Listener.Addr().String())
+ return b
+}
+
+// leaf mints a serving certificate for host under the deployment CA.
+func (ca *e2eCA) leaf(t *testing.T, host string) tls.Certificate {
+ t.Helper()
+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tmpl := &x509.Certificate{
+ SerialNumber: big.NewInt(time.Now().UnixNano()),
+ Subject: pkix.Name{CommonName: host},
+ DNSNames: []string{host},
+ NotBefore: time.Now().Add(-time.Hour),
+ NotAfter: time.Now().Add(time.Hour),
+ KeyUsage: x509.KeyUsageDigitalSignature,
+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+ }
+ der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, &key.PublicKey, ca.key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}
+}
+
+func (s *pathHopScene) refresh(t *testing.T) {
+ t.Helper()
+ for _, be := range s.edges {
+ refreshHomeMap(t, be.homes)
+ if err := be.mirror.Refresh(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+// target is the target route's published row, as Task 8's dispatch reads it.
+func (s *pathHopScene) target(t *testing.T) pathRouteInfo {
+ t.Helper()
+ info, ok := s.sender.homes.exactPathRoute(pathHopRoute)
+ if !ok {
+ t.Fatalf("no published row for %s", pathHopRoute)
+ }
+ return info
+}
+
+// send makes one path hop from the sender for a request to the front name.
+func (s *pathHopScene) send(t *testing.T, r *http.Request) *httptest.ResponseRecorder {
+ t.Helper()
+ info := s.target(t)
+ w := httptest.NewRecorder()
+ if !s.sender.edge.backhaulRouteTo(w, r, pathHopWire, pathHopRoute, info.Dial, info.Box, info.Owner) {
+ t.Fatal("backhaulRouteTo did not answer")
+ }
+ return w
+}
+
+func pathHopRequest() *http.Request {
+ r := httptest.NewRequest(http.MethodGet, "https://"+pathHopWire+"/tenant/page", nil)
+ r.RemoteAddr = "192.0.2.7:4242"
+ return r
+}
+
+// The hop is signed for, sent to and presented as the front name: the
+// receiving edge verifies the MAC for hub.example (the client's chain is
+// believed, which only a verified hop earns) and the app behind it is asked
+// for hub.example.
+func TestBackhaulRouteToSignsWireHost(t *testing.T) {
+ s := newPathHopScene(t)
+ app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, "%s|%s|%s", r.Host, r.URL.Path, r.Header.Get("X-Forwarded-For"))
+ }))
+ t.Cleanup(app.Close)
+ betty := s.edge(t, "betty", "127.0.0.2", 5, map[string]string{pathHopWire: app.Listener.Addr().String()})
+ tap := &e2eTap{}
+ betty.tap.Store(tap)
+ s.refresh(t)
+
+ w := s.send(t, pathHopRequest())
+ if w.Code != http.StatusOK {
+ t.Fatalf("hop: %d %q", w.Code, w.Body.String())
+ }
+ if got, want := w.Body.String(), pathHopWire+"|/tenant/page|192.0.2.7"; got != want {
+ t.Fatalf("app saw %q, want %q (Host, path, the verified hop's client chain)", got, want)
+ }
+ if n := betty.calls.Load(); n != 1 {
+ t.Fatalf("betty calls=%d, want 1", n)
+ }
+ req, _ := tap.last()
+ auth := req.Get(hopAuthHeader)
+ key := signingKey(s.sender.homes.meshKeys())
+ if !verifyHop(key, pathHopWire, auth, time.Now()) {
+ t.Fatalf("hop MAC %q does not verify for the wire host %s", auth, pathHopWire)
+ }
+ if verifyHop(key, pathHopRoute, auth, time.Now()) {
+ t.Fatalf("hop MAC verifies for the route host %s", pathHopRoute)
+ }
+}
+
+// A holder answer to a path hop is learned under the route, never under the
+// front name, and the next hop for the route goes straight to the holder,
+// still carrying the front name on the wire. A handover answer is the same.
+func TestBackhaulRouteToKeysHolderOnRoute(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ refuse func(http.ResponseWriter)
+ }{
+ {"holder", func(w http.ResponseWriter) {
+ w.Header().Set(holderHeader, "carol")
+ }},
+ {"handover", func(w http.ResponseWriter) {
+ w.Header().Set(HandoverHeader, FormatHandover("carol", 3))
+ w.Header().Set(holderHeader, "carol")
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s := newPathHopScene(t)
+ betty := s.box(t, "betty", "127.0.0.2", 9, func(w http.ResponseWriter, _ *http.Request) {
+ tc.refuse(w)
+ w.WriteHeader(http.StatusServiceUnavailable)
+ })
+ carol := s.box(t, "carol", "127.0.0.3", 5, func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "carol|"+r.Host)
+ })
+ s.refresh(t)
+ owner := s.target(t).Owner
+ if box := s.target(t).Box; box != "betty" {
+ t.Fatalf("precondition: the route is served from %s, want betty", box)
+ }
+
+ w := s.send(t, pathHopRequest())
+ if w.Code != http.StatusOK || w.Body.String() != "carol|"+pathHopWire {
+ t.Fatalf("followed hop: %d %q", w.Code, w.Body.String())
+ }
+ c := &s.sender.edge.backhaulHolders
+ if ref := c.get(pathHopRoute, owner, time.Now()); ref != "carol" {
+ t.Fatalf("holder under %s = %q, want carol", pathHopRoute, ref)
+ }
+ c.mu.Lock()
+ _, underWire := c.entries[pathHopWire]
+ c.mu.Unlock()
+ if underWire {
+ t.Fatalf("a holder was remembered under the front name %s", pathHopWire)
+ }
+
+ // The next hop starts at the learned holder.
+ w = s.send(t, pathHopRequest())
+ if w.Code != http.StatusOK || w.Body.String() != "carol|"+pathHopWire {
+ t.Fatalf("second hop: %d %q", w.Code, w.Body.String())
+ }
+ bHosts, _ := betty.seen()
+ cHosts, cAuths := carol.seen()
+ if len(bHosts) != 1 || len(cHosts) != 2 {
+ t.Fatalf("calls betty=%v carol=%v, want 1 and 2", bHosts, cHosts)
+ }
+ key := signingKey(s.sender.homes.meshKeys())
+ for i, h := range append(bHosts, cHosts...) {
+ if h != pathHopWire {
+ t.Fatalf("request %d carried Host %q, want %s", i, h, pathHopWire)
+ }
+ }
+ for _, a := range cAuths {
+ if !verifyHop(key, pathHopWire, a, time.Now()) {
+ t.Fatalf("followed hop MAC %q is not over %s", a, pathHopWire)
+ }
+ }
+ })
+ }
+}
+
+// A destination that cannot be reached falls back to another serving box of
+// the route (backhaulAlternative keyed on the route), and the next hop skips
+// the suspect box for the route's alternative.
+func TestBackhaulRouteToFallsBackOnRoute(t *testing.T) {
+ s := newPathHopScene(t)
+ betty := s.box(t, "betty", "127.0.0.2", 9, func(w http.ResponseWriter, _ *http.Request) {
+ io.WriteString(w, "betty")
+ })
+ carol := s.box(t, "carol", "127.0.0.3", 5, func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "carol|"+r.Host)
+ })
+ s.refresh(t)
+ betty.srv.Close()
+ for i := range 2 {
+ w := s.send(t, pathHopRequest())
+ if w.Code != http.StatusOK || w.Body.String() != "carol|"+pathHopWire {
+ t.Fatalf("hop %d: %d %q", i, w.Code, w.Body.String())
+ }
+ }
+ if hosts, _ := carol.seen(); len(hosts) != 2 {
+ t.Fatalf("carol calls=%v, want 2", hosts)
+ }
+}
+
+// One hop, ever: a request that arrived as a verified hop is refused, not
+// forwarded, whatever route it would have been for.
+func TestBackhaulRouteToRefusesArrivedHop(t *testing.T) {
+ s := newPathHopScene(t)
+ betty := s.box(t, "betty", "127.0.0.2", 9, func(w http.ResponseWriter, _ *http.Request) {
+ io.WriteString(w, "betty")
+ })
+ s.refresh(t)
+ r := pathHopRequest()
+ r = r.WithContext(context.WithValue(r.Context(), hopVerifiedKey{}, true))
+ w := s.send(t, r)
+ if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") != "2" {
+ t.Fatalf("arrived hop: %d %v, want the stale-hop refusal", w.Code, w.Header())
+ }
+ if hosts, _ := betty.seen(); len(hosts) != 0 {
+ t.Fatalf("an arrived hop was forwarded: %v", hosts)
+ }
+}