carlos / platform Public

Regional domains (#447) Task 5: edge regional entries and regionalGate

Reload folds every regional_domains row, after the alias fold, into a
serve entry (a copy of the bound target's entry with no path map) or a
deny entry (zero route, nil proxy). A row beats a real route at its own
key, apex and star alike (ruling 5b), and is logged throttled. Each
target is rechecked with release.RegionalTarget against the routes slice
the same Reload read. lookupUpstreamPath returns early for a regional
entry (ruling 4). regionalGate, called straight after lookupUpstreamPath
in ServeHTTP, answers 503 + Retry-After: 2 for every hop and every deny
before any arm can leave the box. A star match whose exact name another
box serves passes to the exact-home arm (not for door callers). A deny
entry the arm does not answer is refused after it, never served through
its nil proxy. regionalObserve is a test hook in backhaulTo,
serveAssetFar, Home and ExactHome.

Witnesses: W1 TestRegionalNameNeverLeavesItsRegion (legs a-i, plus j:
another box's exact name under the regional star), W9
TestRegionalApexIsAllowedForCertificates, W10
TestRegionalEntryRechecksItsTarget,
TestRegionalDenyStarRefusedWhenTheExactHomeCannotBeDialled, and
internal/host TestRegionalNameWakesItsSleepingTarget. The backhaul scene
gains farEntries (box B's edges file) and its bucket path.

Mutation checks:
1. regionalGate call removed: W1 fails (d) (hops 200, Tie 4->6), (e)
   (fresh box's hop served, Tie 6->8), (g) and (h). (c) stays 503: the
   deny backstop after the exact-home arm refuses the deny entry.
2. serve entry keeps the target's path map and lookupUpstreamPath's test
   is back to up.paths == nil: (g) hop 200, Tother 1->2. (f) fails too,
   including the direct assertion. The kept map alone fails only the
   direct assertion.
3. "route wins" restored in the fold: (i) 502, the hand route's backend
   accepted 2 connections.
4. W10, RegionalTarget replaced by a presence test: every leg serves;
   (a) another account 200, Tie 1->3.
Also: backstop removed: the deny-star test gets EOF (nil proxy panic);
star exemption removed: W1 (j) 503 instead of A's 200.
All restored before this commit; green after.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev d9a0fe6115f2200799a472af148f3c074d565980 parent 7fc98ba
8 files changed, +1,145 −9
  • internal/edge/assetcatch.go +3 −0
  • internal/edge/backhaul_e2e_test.go +23 −8
  • internal/edge/edge.go +37 −1
  • internal/edge/homemap.go +2 −0
  • internal/edge/regional.go +145 −0
  • internal/edge/regional_e2e_test.go +656 −0
  • internal/edge/regional_test.go +191 −0
  • internal/host/regionalwake_test.go +88 −0
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go
index 9716a2273..d082efa33 100644
--- a/internal/edge/assetcatch.go
+++ b/internal/edge/assetcatch.go
@@ -1048,6 +1048,9 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string
if !ok {
return false
}
+ // The regional test hook (regional.go): the far catch has taken the
+ // request, so a fill or a forward to the home may follow.
+ observeRegional("asset-fill", host)
forward := func() { e.farForward(w, r, host, eip, box) }
if !canonicalAssetPath(r.URL) {
forward()
diff --git a/internal/edge/backhaul_e2e_test.go b/internal/edge/backhaul_e2e_test.go
index 1283bb114..1ed30579c 100644
--- a/internal/edge/backhaul_e2e_test.go
+++ b/internal/edge/backhaul_e2e_test.go
@@ -504,18 +504,21 @@ type backhaulScene struct {
// aEIP and bEIP are the two edges' addresses as their edges files
// publish them.
aEIP, bEIP string
+ // bucket is the shared bucket's directory, so a test can boot another
+ // box on it (a fresh box with an empty registry).
+ bucket string
}
// backhaulSceneExtra is what a scene adds to the standard two edges: more
// route rows on either edge, the home edge's activator, more certificates in
-// the bucket, and more entries in the home edge's edges file (host → the
-// JSON of its entry, edgesHostView's shape). The zero value is the standard
-// scene.
+// the bucket, and more entries in the home edge's and the sending edge's
+// edges files (host → the JSON of its entry, edgesHostView's shape). The zero
+// value is the standard scene.
type backhaulSceneExtra struct {
- homeRoutes, farRoutes []registry.Route
- homeAct Activator
- certs []string
- homeEntries map[string]string
+ homeRoutes, farRoutes []registry.Route
+ homeAct Activator
+ certs []string
+ homeEntries, farEntries map[string]string
}
func newBackhaulScene(t *testing.T) *backhaulScene {
@@ -532,6 +535,7 @@ func newBackhaulSceneWith(t *testing.T, x backhaulSceneExtra) *backhaulScene {
ca: newE2ECA(t),
leaf: map[string]*x509.Certificate{},
deadEIP: e2eDeadEIP(t),
+ bucket: bucket,
}
// The housekeeper's one-time mint (Task 2), and the certs Part 2's issuer
@@ -579,7 +583,7 @@ func newBackhaulSceneWith(t *testing.T, x backhaulSceneExtra) *backhaulScene {
}
s.aEIP, s.bEIP = eip, bEIP
s.publishHomeEdgesFile(t, x.homeEntries)
- s.publishEdgesFile(t, "betty", bEIP, e2eSenderHost)
+ s.publishFarEdgesFile(t, x.farEntries)
s.publishEdgesFile(t, "carol", s.deadEIP, e2eDeadHost)
return s
}
@@ -596,6 +600,17 @@ func (s *backhaulScene) publishHomeEdgesFile(t *testing.T, extra map[string]stri
s.publishEdgesEntries(t, "annie", s.aEIP, entries)
}
+// publishFarEdgesFile (re)writes the sending edge's file: its own route, plus
+// extra (host → entry JSON).
+func (s *backhaulScene) publishFarEdgesFile(t *testing.T, extra map[string]string) {
+ t.Helper()
+ entries := map[string]string{e2eSenderHost: `{"role":"home"}`}
+ for h, entry := range extra {
+ entries[h] = entry
+ }
+ s.publishEdgesEntries(t, "betty", s.bEIP, entries)
+}
+
// publishEdgesFile writes one box's control/edges/<box>.json — homedOn's shape,
// written through the seed handle so neither edge is the publisher of its own
// map (which is the production writer arrangement: the box's own host loop
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 838665aa8..15b254516 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -453,6 +453,13 @@ type upstream struct {
// rate_limit column, parsed once per reload (parseRateSettings). An alias
// copies it with the rest of the primary's entry.
rate ratelimit.Settings
+ // regional marks an entry built from a regional_domains row (#447,
+ // regional.go): regionalServe (the bound target's entry, no path map) or
+ // regionalDeny (zero route, nil proxy). regionalGate decides on it before
+ // any arm can leave the box. regionalKey is the row's host, the bounded
+ // key the gate logs under.
+ regional regionalMode
+ regionalKey string
}
// New builds an Edge over reg and performs the startup reload. act may be nil
@@ -1082,6 +1089,16 @@ func (e *Edge) Reload() error {
up.alias, up.platformAlias = true, false
m[a.Alias] = up
}
+ // Regional names (#447, regional.go): after the alias fold, so a
+ // regional row replaces any alias of the same key, and over a real route
+ // at its own key too (ruling 5b): every row becomes a serve or a deny
+ // entry, judged against the same routes slice this reload built m from.
+ // An error aborts the reload like every registry read here.
+ regionalRows, err := e.reg.ListRegional()
+ if err != nil {
+ return err
+ }
+ e.foldRegional(m, routes, regionalRows)
// Fleet channel auth: registry-backed, so this refreshes on the SAME poll
// that rebuilds routes — Task 1's Fingerprint moves on every fleet
// mutation (including token rotation), and the edge's existing 2s
@@ -1445,7 +1462,9 @@ func (e *Edge) lookupUpstream(host string) (upstream, bool) {
func (e *Edge) lookupUpstreamPath(host, urlPath string) (upstream, bool) {
m := e.current()
up, ok := lookupIn(m, host)
- if !ok || up.paths == nil {
+ // A regional entry (#447) never selects by path: regionalGate decides
+ // on the request's Host, before any path is selected.
+ if !ok || up.paths == nil || up.regional != regionalNone {
return up, ok
}
// BOTH FORMS, cleaned first. The prefix map is consulted for the
@@ -1673,6 +1692,14 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r = e.withForwardKey(r)
up, ok := e.lookupUpstreamPath(host, r.URL.Path)
+ // Regional names (#447, regional.go): a regional name is never served
+ // from, or backhauled to, another region. Decided here, on the Host's own
+ // entry, before every arm below that can leave the box: the exact-home
+ // backhaul and far asset catch, and the miss arm's door dial, far asset
+ // catch and backhaul. Door callers pass through this same line.
+ if e.regionalGate(w, r, host, up, ok, hopped) {
+ return
+ }
// A local match through a one-label "*.<parent>" key (a route
// catch-all) does not beat ANOTHER box's exact host. That is the same
// precedence one box keeps (lookupIn: exact first, then the star),
@@ -1693,6 +1720,14 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
}
+ // A regional deny entry the gate let through to the exact-home arm above
+ // (a star match whose exact name another box served) that the arm did
+ // not answer: no mesh key, or the map moved between the two reads. The
+ // entry has no proxy; it is refused, never served.
+ if ok && up.regional == regionalDeny {
+ e.regionalRefuse(w, up, "no bound target on this box")
+ return
+ }
if !ok {
if hopped {
// A PROVEN hop from a sibling edge, for a host that has moved (or
@@ -3389,6 +3424,7 @@ func (e *Edge) backhaulTo(w http.ResponseWriter, r *http.Request, host, eip, box
// The client boundary for informational responses: a 1xx from the home
// reaches w through the proxy's trace hook, past ModifyResponse, so the
// asset vocabulary comes off it here (assetInformationalScrub).
+ observeRegional("backhaul", host)
backhaulProxy(host, eip, box, auth, doorAuth, false, e.backhaulTransport(eip), e.logThrottled).ServeHTTP(assetInformationalScrub{w}, r)
return true
}
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index 9820ad0fb..b5e32d997 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -985,6 +985,7 @@ func (m *homeMap) Home(host string) (eip, box string, ok bool) {
if !ok {
return "", "", false
}
+ observeRegional("home", host)
return h.eip, h.box, true
}
@@ -998,6 +999,7 @@ func (m *homeMap) ExactHome(host string) (eip, box string, ok bool) {
return "", "", false
}
if h, found := m.snapshot().hosts[host]; found && h.dial {
+ observeRegional("exact-home", host)
return h.eip, h.box, true
}
return "", "", false
diff --git a/internal/edge/regional.go b/internal/edge/regional.go
new file mode 100644
index 000000000..7009ac93a
--- /dev/null
+++ b/internal/edge/regional.go
@@ -0,0 +1,145 @@
+package edge
+
+// Regional custom-domain placements (#447, spec §1, §7.3): a regional name is
+// never served from, or backhauled to, another region. The domains pass
+// writes one regional_domains row per regional claim on every box, naming
+// this box's bound target or none; Reload turns each row into a serve or a
+// deny entry; and regionalGate, called straight after lookupUpstreamPath in
+// ServeHTTP, refuses every hop and every deny before any arm that leaves the
+// box (the exact-home backhaul, the far asset catch, the door's Owner dial
+// and the miss arm's backhaul).
+
+import (
+ "fmt"
+ "net/http"
+ "sync/atomic"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// regionalMode marks an upstream entry built from a regional_domains row.
+type regionalMode uint8
+
+const (
+ // regionalNone is every entry that did not come from a regional row.
+ regionalNone regionalMode = iota
+ // regionalServe is a row whose target is a route this box serves and
+ // release.RegionalTarget holds for: a copy of the target's entry with
+ // no path map.
+ regionalServe
+ // regionalDeny is every other row: a zero route and a nil proxy, which
+ // regionalGate answers 503 before anything reads either.
+ regionalDeny
+)
+
+// regionalObserve is a test hook: nil in production, an atomic load per call.
+// Events: "backhaul" (backhaulTo, before dialling), "asset-fill"
+// (serveAssetFar, when the far catch takes a request, before any fill or
+// forward), "home" and "exact-home" (Home and ExactHome returning a dial
+// target).
+var regionalObserve atomic.Pointer[func(event, host string)]
+
+// observeRegional reports one event to the test hook, if one is set.
+func observeRegional(event, host string) {
+ if fn := regionalObserve.Load(); fn != nil {
+ (*fn)(event, host)
+ }
+}
+
+// regionalGate answers and returns true when the request must stop here.
+// Not ok or not regional: false. A star match (!e.servesExactly(host)), not
+// hopped and not a door call, for which e.homes.Load().ExactHome(host) names
+// another box: false, so the exact-home arm serves that distinct exact name,
+// which is never regional (§7.1). A hop: 503, serve or deny. Deny: 503.
+// Serve: false, and the request goes on to the target's upstream.
+//
+// A door caller never takes the exact-home arm (ServeHTTP skips it for
+// doors), so the star exemption does not apply to one: a door gets the same
+// answer as a visitor whose request this box keeps.
+//
+// The 503 is staleHopRefusal's answer: Retry-After: 2 and a body that says
+// nothing about where the name is served. The log is throttled per
+// regionalKey, the row's host, so its keys are bounded by the regional rows.
+func (e *Edge) regionalGate(w http.ResponseWriter, r *http.Request, host string, up upstream, ok, hopped bool) bool {
+ if !ok || up.regional == regionalNone {
+ return false
+ }
+ if !hopped && !e.servesExactly(host) {
+ if _, isDoor := doorCallerFrom(r.Context()); !isDoor {
+ if _, _, remote := e.homes.Load().ExactHome(host); remote {
+ return false
+ }
+ }
+ }
+ switch {
+ case hopped:
+ e.regionalRefuse(w, up, "a hop")
+ case up.regional == regionalDeny:
+ e.regionalRefuse(w, up, "no bound target on this box")
+ default:
+ return false
+ }
+ return true
+}
+
+// regionalRefuse writes the gate's 503 and logs it, throttled per row.
+func (e *Edge) regionalRefuse(w http.ResponseWriter, up upstream, why string) {
+ w.Header().Set("Retry-After", "2")
+ http.Error(w, "not served here", http.StatusServiceUnavailable)
+ e.logThrottled("regional "+up.regionalKey, fmt.Sprintf(
+ "regional name %s refused (%s): it is served only from its own region's instance on its own box", up.regionalKey, why))
+}
+
+// foldRegional applies the regional_domains rows to m, the map Reload is
+// building, after the alias fold. routes is the slice the same Reload built
+// m from, so each target is judged against the routes being served now.
+//
+// For each row (spec §7.3, ruling 5b):
+// 1. m[row.Host] is a real route (present, not an alias): a deny entry, and
+// a throttled log naming the host. The route's registry row is untouched;
+// only its key in the map is taken, for the apex and the star alike.
+// 2. Otherwise a serve entry only if the row names a target, that target is
+// a route in routes for which release.RegionalTarget holds, and its own
+// entry in m is a plain route (not an alias, a platform alias or a
+// tunnelled host). The serve entry is a copy of the target's entry with
+// no path map.
+// 3. Anything else: a deny entry.
+//
+// The entry replaces whatever m held at the key, alias or route.
+func (e *Edge) foldRegional(m map[string]upstream, routes []registry.Route, rows []registry.RegionalDomain) {
+ if len(rows) == 0 {
+ return
+ }
+ byHost := make(map[string]registry.Route, len(routes))
+ for _, rt := range routes {
+ byHost[rt.Host] = rt
+ }
+ for _, row := range rows {
+ deny := upstream{alias: true, regional: regionalDeny, regionalKey: row.Host}
+ if cur, present := m[row.Host]; present && !cur.alias {
+ e.logThrottled("regional-over-route "+row.Host, fmt.Sprintf(
+ "route %s is not served: a regional domain holds that name, so it answers 503 on this box (the route's row is left as it is)", row.Host))
+ m[row.Host] = deny
+ continue
+ }
+ if row.Target == "" {
+ m[row.Host] = deny
+ continue
+ }
+ rt, found := byHost[row.Target]
+ if !found || !release.RegionalTarget(rt, row.Account, row.App, row.Region) {
+ m[row.Host] = deny
+ continue
+ }
+ tu, present := m[row.Target]
+ if !present || tu.alias || tu.platformAlias || tu.viaTunnel {
+ m[row.Host] = deny
+ continue
+ }
+ tu.paths = nil
+ tu.alias, tu.platformAlias = true, false
+ tu.regional, tu.regionalKey = regionalServe, row.Host
+ m[row.Host] = tu
+ }
+}
diff --git a/internal/edge/regional_e2e_test.go b/internal/edge/regional_e2e_test.go
new file mode 100644
index 000000000..ff17e67ee
--- /dev/null
+++ b/internal/edge/regional_e2e_test.go
@@ -0,0 +1,656 @@
+package edge
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/gate"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// Regional custom-domain placements (#447): the names W1, W9 and W10 turn on.
+// The claim, its account and app, and the two bound targets are the ones the
+// writer-pinned goldens (internal/edgesfile/testdata/regional-box*.golden.json)
+// were generated from.
+const (
+ rgApex = "shop.example.com"
+ rgStar = "*.shop.example.com"
+ rgUnder = "alice.shop.example.com"
+ rgTie = "shop-ie.example.net"
+ rgTuk = "shop-uk.example.net"
+ rgTother = "shop-api.example.net"
+ // rgExactElsewhere is a distinct exact name under the regional star,
+ // served by another box: never regional (§7.1).
+ rgExactElsewhere = "bob.shop.example.com"
+ rgAccount = "abc"
+ rgApp = "shop"
+)
+
+// rgClaim is the regional claim: Wildcard and Catchall (fixed at creation,
+// ruling 6), home bound to rgTie and uk to rgTuk.
+func rgClaim() domains.Claim {
+ return domains.Claim{
+ Schema: 2, Host: rgApex, Account: rgAccount, App: rgApp, Route: rgTie,
+ Wildcard: true, Catchall: true,
+ CreatedAt: "2026-10-29T00:00:00Z", CreatedBy: "owner@example.com",
+ Placements: []domains.Placement{
+ {Region: "", Host: rgTie},
+ {Region: "uk", Host: rgTuk},
+ },
+ }
+}
+
+// rgWriteClaim writes c through the production writer.
+func rgWriteClaim(t *testing.T, s release.Store, c domains.Claim) {
+ t.Helper()
+ if changed, err := domains.SetClaimPlacements(context.Background(), s, c, nil, ""); err != nil || !changed {
+ t.Fatalf("SetClaimPlacements: changed=%v err=%v", changed, err)
+ }
+}
+
+// rgPass runs the domains pass for a box in region, as the agent's
+// aliasPassReporting does, and returns its report.
+func rgPass(t *testing.T, s release.Store, reg *registry.Registry, region string) domains.AliasReport {
+ t.Helper()
+ rep := domains.AliasReport{Region: region}
+ if err := domains.ReconcileAliasesReport(context.Background(), s, reg, time.Now, map[string]bool{}, nil, &rep); err != nil {
+ t.Fatalf("alias pass (region %q): %v", region, err)
+ }
+ return rep
+}
+
+// rgRows is the box's regional_domains rows by host.
+func rgRows(t *testing.T, reg *registry.Registry) map[string]registry.RegionalDomain {
+ t.Helper()
+ rows, err := reg.ListRegional()
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := make(map[string]registry.RegionalDomain, len(rows))
+ for _, r := range rows {
+ out[r.Host] = r
+ }
+ return out
+}
+
+// rgUnreadableStore is the deployment bucket with one key's GET failing:
+// the claim listed but unreadable (spec §7.2).
+type rgUnreadableStore struct {
+ release.Store
+ failKey string
+}
+
+func (s rgUnreadableStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if key == s.failKey {
+ return nil, "", errors.New("synthetic 403")
+ }
+ return s.Store.Get(ctx, key)
+}
+
+// rgBackend is a counting HTTP server on a unix socket: an instance's
+// process. Every request it answers moves n; its body is its name.
+type rgBackend struct {
+ sock string
+ n atomic.Int64
+}
+
+func rgSocketBackend(t *testing.T, dir, name string) *rgBackend {
+ t.Helper()
+ b := &rgBackend{sock: filepath.Join(dir, name+".sock")}
+ ln, err := net.Listen("unix", b.sock)
+ if err != nil {
+ t.Fatalf("listen unix %s: %v", b.sock, err)
+ }
+ srv := &httptest.Server{Listener: ln, Config: &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b.n.Add(1)
+ io.WriteString(w, name)
+ })}}
+ srv.Start()
+ t.Cleanup(srv.Close)
+ return b
+}
+
+// rgTCPCounter is a TCP listener on 127.0.0.1 that counts accepted
+// connections and answers nothing: the backend of a hand route.
+func rgTCPCounter(t *testing.T) (string, *atomic.Int64) {
+ t.Helper()
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("listen: %v", err)
+ }
+ t.Cleanup(func() { ln.Close() })
+ var n atomic.Int64
+ go func() {
+ for {
+ conn, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ n.Add(1)
+ conn.Close()
+ }
+ }()
+ return ln.Addr().String(), &n
+}
+
+// rgInstance is a bound target's route row: a ready, provisioned instance of
+// the claim's account, served from a socket, in region.
+func rgInstance(host, sock, app, region string) registry.Route {
+ return registry.Route{Host: host, Kind: "instance", Socket: sock, Provisioned: true, Status: "ready",
+ Account: rgAccount, App: app, Region: region}
+}
+
+// rgEvents counts the regional test hook's events (regionalObserve).
+type rgEvents struct {
+ mu sync.Mutex
+ n map[string]int
+}
+
+func armRegionalObserve(t *testing.T) *rgEvents {
+ t.Helper()
+ ev := &rgEvents{n: map[string]int{}}
+ fn := func(event, host string) {
+ ev.mu.Lock()
+ ev.n[event]++
+ ev.mu.Unlock()
+ }
+ regionalObserve.Store(&fn)
+ t.Cleanup(func() { regionalObserve.Store(nil) })
+ return ev
+}
+
+func (ev *rgEvents) snapshot() map[string]int {
+ ev.mu.Lock()
+ defer ev.mu.Unlock()
+ out := make(map[string]int, len(ev.n))
+ for k, v := range ev.n {
+ out[k] = v
+ }
+ return out
+}
+
+// since is the events counted after before was taken.
+func (ev *rgEvents) since(before map[string]int) map[string]int {
+ out := map[string]int{}
+ for k, v := range ev.snapshot() {
+ if d := v - before[k]; d != 0 {
+ out[k] = d
+ }
+ }
+ return out
+}
+
+// rgGolden reads one box's hosts block from the writer-pinned golden, as
+// host → entry JSON.
+func rgGolden(t *testing.T, name string) map[string]string {
+ t.Helper()
+ raw, err := os.ReadFile(filepath.Join("..", "edgesfile", "testdata", name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var hosts map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &hosts); err != nil {
+ t.Fatal(err)
+ }
+ out := make(map[string]string, len(hosts))
+ for h, entry := range hosts {
+ var c bytes.Buffer
+ if err := json.Compact(&c, entry); err != nil {
+ t.Fatal(err)
+ }
+ out[h] = c.String()
+ }
+ return out
+}
+
+// rgLogBuffer is a log writer safe to read while the edge writes.
+type rgLogBuffer struct {
+ mu sync.Mutex
+ b bytes.Buffer
+}
+
+func (l *rgLogBuffer) Write(p []byte) (int, error) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.b.Write(p)
+}
+
+func (l *rgLogBuffer) String() string {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.b.String()
+}
+
+// rgDo drives one request at one box through its client and reads the body.
+func rgDo(t *testing.T, be *backhaulEdge, method, rawURL string, headers map[string]string, form url.Values) (*http.Response, string) {
+ t.Helper()
+ var body io.Reader
+ if form != nil {
+ body = strings.NewReader(form.Encode())
+ }
+ req, err := http.NewRequest(method, rawURL, body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if form != nil {
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ }
+ for k, v := range headers {
+ req.Header.Set(k, v)
+ }
+ c := *be.client
+ c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ resp, err := c.Do(req)
+ if err != nil {
+ t.Fatalf("%s %s: %v", method, rawURL, err)
+ }
+ b, err := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if err != nil {
+ t.Fatalf("read %s: %v", rawURL, err)
+ }
+ return resp, string(b)
+}
+
+// TestRegionalNameNeverLeavesItsRegion is W1 (#447 spec §1, §13): a regional
+// name is never served from, or backhauled to, another region, through
+// production wiring: two real edges on one DirStore bucket, each with its own
+// registry, the real domains pass with the box's region, the real Reload,
+// home maps over the writer-pinned edges files, and real hop auth, all on
+// 127.0.0.1 and unix sockets under the test's temp directory.
+//
+// Box A (annie) is the home region, named ie by the console, and runs Tie;
+// box B (betty) is uk and runs Tuk. The claim shop.example.com is regional
+// with a catch-all. Hooks count backhaulTo dials, far asset catches and the
+// dial targets Home and ExactHome return; calls on each box count arrivals.
+func TestRegionalNameNeverLeavesItsRegion(t *testing.T) {
+ dir := shortSockDir(t)
+ tie := rgSocketBackend(t, dir, "tie")
+ tuk := rgSocketBackend(t, dir, "tuk")
+ tother := rgSocketBackend(t, dir, "tother")
+ bob := rgSocketBackend(t, dir, "bob")
+
+ s := newBackhaulSceneWith(t, backhaulSceneExtra{
+ homeRoutes: []registry.Route{
+ rgInstance(rgTie, tie.sock, rgApp, ""),
+ // Tother: a ready route of the same account on A, another app.
+ rgInstance(rgTother, tother.sock, "api", ""),
+ // An exact name under the regional star, another app's on A.
+ rgInstance(rgExactElsewhere, bob.sock, "blog", ""),
+ },
+ farRoutes: []registry.Route{rgInstance(rgTuk, tuk.sock, rgApp, "uk")},
+ certs: []string{rgApex, rgUnder, rgExactElsewhere},
+ homeEntries: rgGolden(t, "regional-box.golden.json"),
+ farEntries: rgGolden(t, "regional-box-uk.golden.json"),
+ })
+ rgWriteClaim(t, s.seed, rgClaim())
+ reload := func(t *testing.T, be *backhaulEdge) {
+ t.Helper()
+ if err := be.edge.Reload(); err != nil {
+ t.Fatalf("Reload %s: %v", be.box, err)
+ }
+ }
+ // Each box's own pass, with its own region, then its own Reload.
+ passAndReload := func(t *testing.T, be *backhaulEdge, region string, st release.Store) domains.AliasReport {
+ t.Helper()
+ rep := rgPass(t, st, be.reg, region)
+ reload(t, be)
+ return rep
+ }
+ passAndReload(t, s.a, "", s.seed)
+ passAndReload(t, s.b, "uk", s.seed)
+ for _, c := range []struct {
+ be *backhaulEdge
+ target string
+ }{{s.a, rgTie}, {s.b, rgTuk}} {
+ rows := rgRows(t, c.be.reg)
+ if rows[rgApex].Target != c.target || rows[rgStar].Target != c.target {
+ t.Fatalf("%s rows = %+v, want %s and %s bound to %s", c.be.box, rows, rgApex, rgStar, c.target)
+ }
+ }
+ s.converge(t)
+ ev := armRegionalObserve(t)
+
+ type counts struct{ tie, tuk, tother, a, b int64 }
+ now := func() counts {
+ return counts{tie.n.Load(), tuk.n.Load(), tother.n.Load(), s.a.calls.Load(), s.b.calls.Load()}
+ }
+ // quiet asserts that nothing left a box since before: no dial, no far
+ // catch, no dial target returned.
+ quiet := func(t *testing.T, before map[string]int) {
+ t.Helper()
+ if got := ev.since(before); len(got) != 0 {
+ t.Errorf("events %v, want no dial, fill or dial target", got)
+ }
+ }
+ refused := func(t *testing.T, resp *http.Response, what string) {
+ t.Helper()
+ if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "2" {
+ t.Errorf("%s: %d (Retry-After %q), want 503 with Retry-After: 2", what, resp.StatusCode, resp.Header.Get("Retry-After"))
+ }
+ }
+ hop := func(host string) map[string]string {
+ return map[string]string{hopHeader: "1", hopAuthHeader: signHop(s.key, host, time.Now())}
+ }
+ names := []string{rgApex, rgUnder}
+ fresh := func(t *testing.T) *backhaulEdge {
+ t.Helper()
+ var from *net.TCPAddr
+ if s.clientIP != "" {
+ from = &net.TCPAddr{IP: net.ParseIP(s.clientIP)}
+ }
+ be := newBackhaulEdgeWith(t, s.bucket, "betty", s.ca, from, nil, nil)
+ if err := be.mirror.Refresh(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ refreshHomeMap(t, be.homes)
+ return be
+ }
+
+ t.Run("a each box serves from its own region", func(t *testing.T) {
+ for _, c := range []struct {
+ be *backhaulEdge
+ want string
+ }{{s.a, "tie"}, {s.b, "tuk"}} {
+ before, evBefore := now(), ev.snapshot()
+ for _, host := range names {
+ for _, method := range []string{http.MethodGet, http.MethodPost} {
+ var form url.Values
+ if method == http.MethodPost {
+ form = url.Values{"q": {"1"}}
+ }
+ resp, body := rgDo(t, c.be, method, "https://"+host+"/", nil, form)
+ if resp.StatusCode != http.StatusOK || body != c.want {
+ t.Errorf("%s %s at %s = %d %q, want 200 %q", method, host, c.be.box, resp.StatusCode, body, c.want)
+ }
+ }
+ }
+ after := now()
+ moved := map[string]int64{"tie": after.tie - before.tie, "tuk": after.tuk - before.tuk}
+ if moved[c.want] != 4 || after.tie-before.tie+after.tuk-before.tuk != 4 || after.tother != before.tother {
+ t.Errorf("at %s: moved %+v (tother %d), want only %s, four times", c.be.box, moved, after.tother-before.tother, c.want)
+ }
+ if c.be == s.a && after.b != before.b || c.be == s.b && after.a != before.a {
+ t.Errorf("at %s the other box was reached", c.be.box)
+ }
+ quiet(t, evBefore)
+ }
+ })
+
+ t.Run("b far target not ready then removed", func(t *testing.T) {
+ if err := s.b.reg.SetStatus(rgTuk, "moving"); err != nil {
+ t.Fatal(err)
+ }
+ check := func(t *testing.T, what string) {
+ t.Helper()
+ before, evBefore := now(), ev.snapshot()
+ for _, host := range names {
+ resp, _ := rgDo(t, s.b, http.MethodGet, "https://"+host+"/", nil, nil)
+ refused(t, resp, what+" "+host)
+ }
+ after := now()
+ if after.tie != before.tie || after.tuk != before.tuk || after.a != before.a {
+ t.Errorf("%s: moved %+v -> %+v, want no target or box reached", what, before, after)
+ }
+ quiet(t, evBefore)
+ }
+ // The Reload alone rechecks the kept row's target against the
+ // routes it serves.
+ reload(t, s.b)
+ check(t, "not ready, before the pass")
+ passAndReload(t, s.b, "uk", s.seed)
+ if rows := rgRows(t, s.b.reg); rows[rgApex].Target != "" {
+ t.Fatalf("rows = %+v, want no target", rows)
+ }
+ check(t, "not ready")
+ if err := s.b.reg.Delete(rgTuk); err != nil {
+ t.Fatal(err)
+ }
+ passAndReload(t, s.b, "uk", s.seed)
+ check(t, "removed")
+ })
+
+ // An old-binary-shaped file for A, naming the regional apex and star as
+ // dial-capable home rows.
+ oldShape := map[string]string{rgApex: `{"role":"home"}`, rgStar: `{"role":"home"}`}
+ t.Run("c old-binary map on B", func(t *testing.T) {
+ s.publishHomeEdgesFile(t, oldShape)
+ s.converge(t)
+ if _, box, ok := s.b.homes.Home(rgApex); !ok || box != "annie" {
+ t.Fatalf("precondition: B's map does not home %s on annie (%s %v)", rgApex, box, ok)
+ }
+ before, evBefore := now(), ev.snapshot()
+ for _, host := range names {
+ resp, _ := rgDo(t, s.b, http.MethodGet, "https://"+host+"/", nil, nil)
+ refused(t, resp, host)
+ }
+ after := now()
+ if after.a != before.a || after.tie != before.tie {
+ t.Errorf("A reached from B: %+v -> %+v", before, after)
+ }
+ quiet(t, evBefore)
+ })
+
+ t.Run("d signed hop to A", func(t *testing.T) {
+ before, evBefore := now(), ev.snapshot()
+ for _, host := range names {
+ resp, _ := rgDo(t, s.a, http.MethodGet, "https://"+host+"/", hop(host), nil)
+ refused(t, resp, "hop "+host)
+ }
+ if after := now(); after.tie != before.tie || after.tother != before.tother {
+ t.Errorf("a hop reached a target: %+v -> %+v", before, after)
+ }
+ quiet(t, evBefore)
+ })
+
+ t.Run("e restart with the claim unreadable, then a fresh box", func(t *testing.T) {
+ unreadable := rgUnreadableStore{s.seed, domains.ClaimKey(rgApex)}
+ if rep := rgPass(t, unreadable, s.b.reg, "uk"); rep.Complete {
+ t.Error("a pass that could not read the claim reported complete")
+ }
+ if rows := rgRows(t, s.b.reg); len(rows) != 2 {
+ t.Fatalf("rows after an unreadable pass = %+v, want both kept", rows)
+ }
+ s.b.restart(t)
+ s.converge(t)
+ before, evBefore := now(), ev.snapshot()
+ for _, host := range names {
+ resp, _ := rgDo(t, s.b, http.MethodGet, "https://"+host+"/", nil, nil)
+ refused(t, resp, "restarted "+host)
+ }
+ if after := now(); after.a != before.a || after.tie != before.tie {
+ t.Errorf("A reached from the restarted B: %+v -> %+v", before, after)
+ }
+ quiet(t, evBefore)
+
+ // A fresh B, empty registry, with (c)'s map: it dials A, and A
+ // refuses the hop.
+ nb := fresh(t)
+ before, evBefore = now(), ev.snapshot()
+ for _, host := range names {
+ resp, _ := rgDo(t, nb, http.MethodGet, "https://"+host+"/", nil, nil)
+ refused(t, resp, "fresh "+host)
+ }
+ after := now()
+ if after.tie != before.tie || after.tother != before.tother {
+ t.Errorf("a fresh box's hop reached a target on A: %+v -> %+v", before, after)
+ }
+ if got := ev.since(evBefore); got["backhaul"] != 2 || after.a-before.a != 2 {
+ t.Errorf("fresh box: events %v, A reached %d times, want two dials A refused", got, after.a-before.a)
+ }
+ })
+
+ t.Run("f path row on the target", func(t *testing.T) {
+ if err := s.a.reg.UpsertPath(registry.RoutePath{Host: rgTie, Prefix: "api", Target: rgTother}); err != nil {
+ t.Fatal(err)
+ }
+ reload(t, s.a)
+ // The direct assertion: no regional entry carries a path map, while
+ // the target's own entry keeps its prefix.
+ m := s.a.edge.current()
+ for _, k := range []string{rgApex, rgStar} {
+ if up := m[k]; up.regional != regionalServe || up.paths != nil {
+ t.Errorf("%s entry: regional %d paths %v, want a serve entry with no path map", k, up.regional, up.paths)
+ }
+ }
+ if got := m[rgTie].paths["api"]; got != rgTother {
+ t.Errorf("%s paths = %v, want api -> %s", rgTie, m[rgTie].paths, rgTother)
+ }
+
+ before, evBefore := now(), ev.snapshot()
+ resp, body := rgDo(t, s.a, http.MethodGet, "https://"+rgApex+"/api/x", nil, nil)
+ if resp.StatusCode != http.StatusOK || body != "tie" {
+ t.Errorf("GET %s/api/x = %d %q, want 200 tie", rgApex, resp.StatusCode, body)
+ }
+ if after := now(); after.tie-before.tie != 1 || after.tother != before.tother {
+ t.Errorf("GET %s/api/x moved %+v -> %+v, want Tie only", rgApex, before, after)
+ }
+ quiet(t, evBefore)
+
+ // A login POST re-resolves by next's path: it gets the regional entry
+ // back (Tie's route, ungated, so a stray 404), billed to Tie.
+ meter := NewUsageMeter()
+ s.a.edge.EnableUsage(meter)
+ before = now()
+ resp, _ = rgDo(t, s.a, http.MethodPost, "https://"+rgApex+gate.LoginPath, nil, url.Values{"next": {"/api/x"}, "password": {"x"}})
+ rows := meter.Drain()
+ if resp.StatusCode != http.StatusNotFound {
+ t.Errorf("login POST = %d, want the ungated stray 404 of the regional entry", resp.StatusCode)
+ }
+ if _, ok := rows[rgTie]; !ok {
+ t.Errorf("login POST metered %v, want %s", rows, rgTie)
+ }
+ if _, ok := rows[rgTother]; ok {
+ t.Errorf("login POST resolved to %s: %v", rgTother, rows)
+ }
+ if after := now(); after.tie != before.tie || after.tother != before.tother {
+ t.Errorf("login POST reached a target: %+v -> %+v", before, after)
+ }
+ })
+
+ t.Run("g signed hop with a prefix", func(t *testing.T) {
+ before, evBefore := now(), ev.snapshot()
+ resp, _ := rgDo(t, s.a, http.MethodGet, "https://"+rgApex+"/api/x", hop(rgApex), nil)
+ refused(t, resp, "hop "+rgApex+"/api/x")
+ if after := now(); after.tie != before.tie || after.tother != before.tother {
+ t.Errorf("a prefixed hop reached a target: %+v -> %+v", before, after)
+ }
+ quiet(t, evBefore)
+ })
+
+ t.Run("h fresh box with a covering old-binary star", func(t *testing.T) {
+ s.publishHomeEdgesFile(t, map[string]string{"*.example.com": `{"role":"home"}`})
+ nb := fresh(t)
+ if _, box, ok := nb.homes.Home(rgApex); !ok || box != "annie" {
+ t.Fatalf("precondition: the fresh map does not home %s on annie (%s %v)", rgApex, box, ok)
+ }
+ before, evBefore := now(), ev.snapshot()
+ resp, _ := rgDo(t, nb, http.MethodGet, "https://"+rgApex+"/", nil, nil)
+ refused(t, resp, "fresh "+rgApex)
+ after := now()
+ if after.tie != before.tie || after.tother != before.tother {
+ t.Errorf("the hop reached a target on A: %+v -> %+v", before, after)
+ }
+ if got := ev.since(evBefore); got["backhaul"] != 1 || after.a-before.a != 1 {
+ t.Errorf("events %v, A reached %d times, want one dial A refused", got, after.a-before.a)
+ }
+ s.publishHomeEdgesFile(t, rgGolden(t, "regional-box.golden.json"))
+ s.converge(t)
+ })
+
+ t.Run("i a hand route at the regional keys", func(t *testing.T) {
+ // Tuk back, the claim readable: B serves the name again.
+ if err := s.b.reg.Upsert(rgInstance(rgTuk, tuk.sock, rgApp, "uk")); err != nil {
+ t.Fatal(err)
+ }
+ passAndReload(t, s.b, "uk", s.seed)
+ if resp, body := rgDo(t, s.b, http.MethodGet, "https://"+rgApex+"/", nil, nil); resp.StatusCode != http.StatusOK || body != "tuk" {
+ t.Fatalf("precondition: B answers %d %q, want 200 tuk", resp.StatusCode, body)
+ }
+
+ logs := &rgLogBuffer{}
+ log.SetOutput(logs)
+ t.Cleanup(func() { log.SetOutput(io.Discard) })
+
+ addr, accepts := rgTCPCounter(t)
+ for _, h := range []string{rgStar, rgApex} {
+ if err := s.b.reg.Upsert(registry.Route{Host: h, Kind: "service", Addr: addr, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // The pass still writes the rows over the routes, and every reload
+ // denies both keys.
+ passAndReload(t, s.b, "uk", s.seed)
+ reload(t, s.b)
+ reload(t, s.b)
+ if rows := rgRows(t, s.b.reg); rows[rgApex].Target != rgTuk || rows[rgStar].Target != rgTuk {
+ t.Fatalf("rows = %+v, want both bound to %s", rows, rgTuk)
+ }
+
+ before, evBefore := now(), ev.snapshot()
+ for _, host := range names {
+ resp, _ := rgDo(t, s.b, http.MethodGet, "https://"+host+"/", nil, nil)
+ refused(t, resp, "hand route "+host)
+ }
+ after := now()
+ if n := accepts.Load(); n != 0 {
+ t.Errorf("the hand route's backend accepted %d connection(s), want none", n)
+ }
+ if after.tuk != before.tuk || after.a != before.a || after.tie != before.tie {
+ t.Errorf("moved %+v -> %+v, want nothing reached", before, after)
+ }
+ quiet(t, evBefore)
+ out := logs.String()
+ for _, h := range []string{rgApex, rgStar} {
+ line := fmt.Sprintf("route %s is not served: a regional domain holds that name", h)
+ if n := strings.Count(out, line); n != 1 {
+ t.Errorf("log names %s %d time(s), want once:\n%s", h, n, out)
+ }
+ }
+ })
+
+ // (§7.4) Another box's exact name beats a local regional star: the gate
+ // lets a star match through when ExactHome names another box, and the
+ // exact-home arm backhauls that distinct name, which is never regional.
+ // B's star is a deny entry here (leg i's hand route), so this is the
+ // exemption at its sharpest.
+ t.Run("j another box's exact name under the regional star", func(t *testing.T) {
+ entries := rgGolden(t, "regional-box.golden.json")
+ entries[rgExactElsewhere] = `{"role":"home"}`
+ s.publishHomeEdgesFile(t, entries)
+ s.converge(t)
+ if up := s.b.edge.current()[rgStar]; up.regional != regionalDeny {
+ t.Fatalf("precondition: B's star is %d, want a deny entry", up.regional)
+ }
+ before, evBefore := now(), ev.snapshot()
+ resp, body := rgDo(t, s.b, http.MethodGet, "https://"+rgExactElsewhere+"/", nil, nil)
+ if resp.StatusCode != http.StatusOK || body != "bob" {
+ t.Errorf("%s at B = %d %q, want 200 bob from A", rgExactElsewhere, resp.StatusCode, body)
+ }
+ after := now()
+ if after.tuk != before.tuk || after.tie != before.tie || after.a-before.a != 1 {
+ t.Errorf("moved %+v -> %+v, want one hop to A and no regional target reached", before, after)
+ }
+ if got := ev.since(evBefore); got["exact-home"] < 1 || got["backhaul"] != 1 {
+ t.Errorf("events %v, want the exact-home arm's one dial", got)
+ }
+ })
+}
diff --git a/internal/edge/regional_test.go b/internal/edge/regional_test.go
new file mode 100644
index 000000000..8e4eabd24
--- /dev/null
+++ b/internal/edge/regional_test.go
@@ -0,0 +1,191 @@
+package edge
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// rgGet asks srv for host's root and returns the status and body.
+func rgGet(t *testing.T, srv *httptest.Server, host string) (int, string) {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodGet, srv.URL+"/", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = host
+ resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req)
+ if err != nil {
+ t.Fatalf("GET %s: %v", host, err)
+ }
+ defer resp.Body.Close()
+ b, _ := io.ReadAll(resp.Body)
+ return resp.StatusCode, string(b)
+}
+
+// TestRegionalEntryRechecksItsTarget is W10 (#447 spec §7.3, §13): A serves
+// shop.example.com from Tie; the claim's GET then fails, so the pass keeps
+// the row as it was. Each leg rewrites Tie's route row so that it no longer
+// satisfies release.RegionalTarget and reloads: Reload's own recheck turns
+// the kept row into a deny entry, so the name answers 503 and Tie is never
+// reached. Restoring the row serves again.
+func TestRegionalEntryRechecksItsTarget(t *testing.T) {
+ tie := rgSocketBackend(t, shortSockDir(t), "tie")
+ tcpAddr, tcpAccepts := rgTCPCounter(t)
+ reg := openReg(t)
+ put := func(t *testing.T, mutate func(*registry.Route), replica bool) {
+ t.Helper()
+ // Delete then insert: Upsert keeps a stored tunnel when the new
+ // row names none, and the legs must each start from a clean row.
+ if err := reg.Delete(rgTie); err != nil {
+ t.Fatal(err)
+ }
+ rt := rgInstance(rgTie, tie.sock, rgApp, "")
+ if mutate != nil {
+ mutate(&rt)
+ }
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ if replica {
+ if err := reg.SetReplica(rgTie, true); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ put(t, nil, false)
+ store := release.NewDirStore(t.TempDir())
+ rgWriteClaim(t, store, rgClaim())
+ rgPass(t, store, reg, "")
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ if code, body := rgGet(t, srv, rgApex); code != http.StatusOK || body != "tie" {
+ t.Fatalf("bound: %d %q, want 200 tie", code, body)
+ }
+
+ unreadable := rgUnreadableStore{store, domains.ClaimKey(rgApex)}
+ keptPassAndReload := func(t *testing.T) {
+ t.Helper()
+ if rep := rgPass(t, unreadable, reg, ""); rep.Complete {
+ t.Error("a pass that could not read the claim reported complete")
+ }
+ if rows := rgRows(t, reg); rows[rgApex].Target != rgTie {
+ t.Fatalf("rows = %+v, want the row kept, bound to %s", rows, rgTie)
+ }
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, leg := range []struct {
+ name string
+ mutate func(*registry.Route)
+ replica bool
+ }{
+ {"a another account", func(rt *registry.Route) { rt.Account = "xyz" }, false},
+ {"b tunnel", func(rt *registry.Route) { rt.Tunnel = "chan" }, false},
+ {"c fleet placement", func(rt *registry.Route) { rt.Region = "fleet/edge" }, false},
+ {"d another region", func(rt *registry.Route) { rt.Region = "uk" }, false},
+ {"e replica", nil, true},
+ {"f socket empty with an addr", func(rt *registry.Route) { rt.Socket, rt.Addr = "", tcpAddr }, false},
+ } {
+ t.Run(leg.name, func(t *testing.T) {
+ put(t, leg.mutate, leg.replica)
+ keptPassAndReload(t)
+ before := tie.n.Load()
+ if code, _ := rgGet(t, srv, rgApex); code != http.StatusServiceUnavailable {
+ t.Errorf("%s: %d, want 503", rgApex, code)
+ }
+ if code, _ := rgGet(t, srv, rgUnder); code != http.StatusServiceUnavailable {
+ t.Errorf("%s: %d, want 503", rgUnder, code)
+ }
+ if tie.n.Load() != before || tcpAccepts.Load() != 0 {
+ t.Errorf("a refused name reached a backend: tie %d -> %d, tcp accepts %d", before, tie.n.Load(), tcpAccepts.Load())
+ }
+ put(t, nil, false)
+ keptPassAndReload(t)
+ if code, body := rgGet(t, srv, rgApex); code != http.StatusOK || body != "tie" {
+ t.Errorf("restored: %d %q, want 200 tie", code, body)
+ }
+ })
+ }
+}
+
+// TestRegionalApexIsAllowedForCertificates is W9 (#447 spec §9): a box with
+// only deny entries (no bound target in its region) still admits the
+// regional apex for certificates, and the housekeeper's warm set carries it;
+// the star key and a name under it are not admitted (the star is the
+// wildcard manager's).
+func TestRegionalApexIsAllowedForCertificates(t *testing.T) {
+ store := release.NewDirStore(t.TempDir())
+ rgWriteClaim(t, store, rgClaim())
+ reg := openReg(t)
+ rgPass(t, store, reg, "de")
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ m := e.current()
+ if len(m) != 2 || m[rgApex].regional != regionalDeny || m[rgStar].regional != regionalDeny {
+ t.Fatalf("map = %+v, want deny entries for %s and %s only", m, rgApex, rgStar)
+ }
+ if !e.Allowed(rgApex) {
+ t.Errorf("Allowed(%s) = false, want true", rgApex)
+ }
+ for _, h := range []string{rgStar, rgUnder} {
+ if e.Allowed(h) {
+ t.Errorf("Allowed(%s) = true, want false", h)
+ }
+ }
+ warm := e.warmSet("apps.example.net", nil)
+ if !slices.Contains(warm, rgApex) {
+ t.Errorf("warmSet = %v, want %s", warm, rgApex)
+ }
+}
+
+// A deny star whose name another box serves exactly, on a box that cannot
+// dial it (no mesh key mirrored): the gate lets the star match through to
+// the exact-home arm, the arm cannot answer, and the deny entry, which has no
+// proxy, is refused there rather than served.
+func TestRegionalDenyStarRefusedWhenTheExactHomeCannotBeDialled(t *testing.T) {
+ store := release.NewDirStore(t.TempDir())
+ rgWriteClaim(t, store, rgClaim())
+ reg := openReg(t)
+ rgPass(t, store, reg, "de")
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ e.staticStore = store
+ WithBoxLabel("carol")(e)
+ putJSON(t, store, "control/edges/annie.json",
+ `{"v":1,"box":"annie","eip":"127.0.0.1","hosts":{"bob.shop.example.com":{"role":"home"}}}`)
+ homes := e.newHomeMap()
+ refreshHomeMap(t, homes)
+ e.homes.Store(homes)
+ if key, next := homes.meshKeys(); len(key) != 0 || len(next) != 0 {
+ t.Fatal("precondition: no mesh key is mirrored")
+ }
+ ev := armRegionalObserve(t)
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ if code, _ := rgGet(t, srv, "bob.shop.example.com"); code != http.StatusServiceUnavailable {
+ t.Errorf("bob.shop.example.com: %d, want 503", code)
+ }
+ if got := ev.snapshot(); got["exact-home"] < 1 || got["backhaul"] != 0 {
+ t.Errorf("events %v, want the exact-home arm reached and no dial", got)
+ }
+}
diff --git a/internal/host/regionalwake_test.go b/internal/host/regionalwake_test.go
new file mode 100644
index 000000000..bb3f2f4f7
--- /dev/null
+++ b/internal/host/regionalwake_test.go
@@ -0,0 +1,88 @@
+package host
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// TestRegionalNameWakesItsSleepingTarget (#447, plan review focus 1),
+// production-wired as TestPlatformAliasWakesItsSleepingInstance is: a real
+// edge over a real activator and registry, the regional row derived by the
+// agent's own alias pass. A request for the regional name to a box whose
+// bound target is hibernating wakes the target through the target's own
+// wake path (one start, keyed on the target's host) and is served, and the
+// app sees the name the browser asked for.
+func TestRegionalNameWakesItsSleepingTarget(t *testing.T) {
+ const (
+ target = "shop-ie.example.net"
+ apex = "shop.example.com"
+ )
+ reg, inst, svc, _ := wakeFixture(t, target, time.Hour, func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "awake")
+ })
+ if err := reg.SetProvisioned(target, true); err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ s := release.NewDirStore(t.TempDir())
+ // wakeFixture's instance is account bab, app app.
+ claim := domains.Claim{
+ Schema: 2, Host: apex, Account: "bab", App: "app", Route: target,
+ CreatedAt: "2026-10-29T00:00:00Z", CreatedBy: "owner@example.com",
+ Placements: []domains.Placement{{Region: "", Host: target}, {Region: "uk", Host: "shop-uk.example.net"}},
+ }
+ if changed, err := domains.SetClaimPlacements(ctx, s, claim, nil, ""); err != nil || !changed {
+ t.Fatalf("SetClaimPlacements: changed=%v err=%v", changed, err)
+ }
+ if err := aliasPassReporting(ctx, s, reg, nil, newAssetAuthority(nil), ""); err != nil {
+ t.Fatalf("alias pass: %v", err)
+ }
+ rows, err := reg.ListRegional()
+ if err != nil || len(rows) != 1 || rows[0].Host != apex || rows[0].Target != target {
+ t.Fatalf("regional rows = %+v (%v), want %s bound to %s", rows, err, apex, target)
+ }
+
+ e, err := edge.New(reg, svc)
+ if err != nil {
+ t.Fatal(err)
+ }
+ server := httptest.NewServer(e)
+ defer server.Close()
+ get := func(host string) (int, string) {
+ t.Helper()
+ r, _ := http.NewRequest(http.MethodGet, server.URL+"/", nil)
+ r.Host = host
+ resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ b, _ := io.ReadAll(resp.Body)
+ return resp.StatusCode, string(b)
+ }
+
+ if inst.running() || svc.Owns(target) || inst.startCount() != 0 {
+ t.Fatal("the target is supposed to start asleep")
+ }
+ if code, body := get(apex); code != http.StatusOK || body != "awake" {
+ t.Fatalf("regional name: %d %q, want 200 awake", code, body)
+ }
+ if !svc.Owns(target) || inst.startCount() != 1 {
+ t.Fatalf("after the regional name: owns %v, starts %d, want the target's own wake", svc.Owns(target), inst.startCount())
+ }
+ // The target's own host shares that one wake.
+ if code, body := get(target); code != http.StatusOK || body != "awake" || inst.startCount() != 1 {
+ t.Fatalf("target: %d %q, starts %d", code, body, inst.startCount())
+ }
+ if served := inst.served(); len(served) == 0 || served[0].Host != apex {
+ t.Errorf("first request reached the app with Host %v, want %s", served, apex)
+ }
+}