carlos / platform Public

edge: bind backhaul substitutions to the door's owner

Carry the checked namespace owner through holder memory and both backhaul fallback paths. Refuse substitutions after account, app, name, class or target changes, and resolve asset bypass destinations with their owner.

Add production-wired door regressions and mutation-check both owner guards. Update the W3 status, latency bound and final-review P3 follow-ups.
Implemented-by: Astra (codex)
claude pushed by paul@keymail.dev dff109057ca166865645299fc2c52a6e0bea0b11 parent 94a9a17
18 files changed, +372 −107
  • docs/superpowers/notes/2026-11-06-region-ha-g2-follow-ups.md +15 −2
  • internal/edge/admission_exact_test.go +2 −1
  • internal/edge/assetcatch.go +9 −8
  • internal/edge/backhaul_holder.go +42 −19
  • internal/edge/backhaul_holder_test.go +17 −15
  • internal/edge/backhaul_owner_export_test.go +117 −0
  • internal/edge/backhaul_owner_wiring_test.go +115 −0
  • internal/edge/backhaul_retry.go +3 −3
  • internal/edge/backhaul_retry_test.go +1 −1
  • internal/edge/backhaul_share_test.go +1 −1
  • internal/edge/door.go +1 −1
  • internal/edge/door_test.go +2 −2
  • internal/edge/edge.go +16 −19
  • internal/edge/forwardha_test.go +1 −1
  • internal/edge/group_names_test.go +5 −4
  • internal/edge/homemap.go +12 −19
  • internal/edge/homemap_assets_test.go +2 −2
  • internal/edge/homemap_test.go +11 −9

Intent

Human

<task-notification> <task-id>bxyntdsba</task-id> <tool-use-id>toolu_01LGv5pJyVPLF7GgDdNBVz9u</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/87a21814-5655-4016-9e7e-41935ee8e96e/tasks/bxyntdsba.output</output-file> <status>completed</status> <summary>Background command "W=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/g2r-fixes/.superpowers/sdd/2026-11-06-region-ha-g2r-fixes; for i in $(seq 1 340); do [ -f $W/t6apply.done ] &amp;&amp; [ -f $W/t3.done ] &amp;&amp; break; sleep 10; done; cat $W/t6apply.done $W/t3.done 2&gt;/dev/null; tail -1 $W/t6apply.log; tail -1 $W/t3.log" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bwhtadmns</task-id> <tool-use-id>toolu_01YbiqTwzZtLdRSr6E1r1FVN</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/87a21814-5655-4016-9e7e-41935ee8e96e/tasks/bwhtadmns.output</output-file> <status>completed</status> <summary>Background command "W=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/g2r-fixes/.superpowers/sdd/2026-11-06-region-ha-g2r-fixes; for i in $(seq 1 340); do [ -f $W/t3.done ] &amp;&amp; break; sleep 10; done; cat $W/t3.done 2&gt;/dev/null; tail -1 $W/t3.log" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a20d8f6b050c05101</task-id> <tool-use-id>toolu_01F16h89GEaYeFp3gr9EANFx</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/87a21814-5655-4016-9e7e-41935ee8e96e/tasks/a20d8f6b050c05101.output</output-file> <status>completed</status> <summary>Agent "Review Task 3 W3 connect fallback" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Task 3 review: commit 39417638 (W3 connect fallback)** **Spec compliance ✅** - **Retry only on connect failure.** The retry needs `!connected` plus either a dial or TLS handshake error (`backhaul_holder.go:175-176`). Once `GotConn` fires, the request is never retried. That covers a reused pooled connection too, so it errs toward no retry. Errors after connect give 502. - **Attempt bound.** The first attempt passes `retry=true` and the second passes `false` (`:199`). The connect fallback and the §6.5 holder follow share that one retry, so there are at most two attempts. The second attempt is still an ordinary signed hop. A hop that arrives at the far box is refused onward by `hopVerified` (`edge.go:4204`), so no third forwarded hop can reach an app. - **Same name, same view, not the failed box.** `backhaulAlternative` (`backhaul_retry.go:53-91`) keeps the resolved owner's account, app, class and target. Every candidate must pass `boxInRegionSnapshot` against the failed box's view, and the failed box itself is removed (`:76`). - **Suspect marks.** They last 60 s with a 50,000-entry cap. A suspect box is only skipped when another box can be chosen; if it is the only eligible claim, it is still chosen (`:84-90`). A non-HA host with one claim gets no alternative, so it behaves as before. - **Remembered holder.** If it fails to connect, it is dropped and marked suspect, and the same request falls back to the normal choice as its single retry. - **Single writer.** The edge only routes. The receiving box still re-checks the lease and answers 503 with the holder (Task 2 path). - **Request body on retry.** On Go 1.26, `ReverseProxy` wraps the outbound body in `noopCloseReader` before the transport runs (`reverseproxy.go:440-451`), and the transport reads no body before it has a connection. With Expect: 100-continue, the inbound server only sends 100 on the first body read, which never happens before connect. The backhaul transport speaks HTTP/1.1 only (`ForceAttemptHTTP2` is false), and inbound HTTP/2 bodies stay unread until the outbound connection exists. So the body is unconsumed when the retry starts. - **Production-wired tests.** They use real edges at both ends, real TLS and registries. The seams only redirect the dial. **Critical:** none. **Important:** none. **Minor** 1. **The new dial-error wrapper is never exercised.** `edge.go:4355-4358` wraps dial errors in `forwardConnectError`, but the test seam replaces `tr.DialContext` wholesale (`backhaul_retry_export_test.go:38`). Detection in tests therefore relies only on the `ConnectDone` trace. If someone deleted the wrapper, every test would still pass. The report calls it the path for errors with no trace event, and that path has no witness. Fix: have the seam wrap its error the same way, or inject a failing `net.Dialer` without replacing the production `DialContext`. 2. **No timeout test, and up to about 10 s of extra latency.** A blackholed box costs one request up to 5 s (dial timeout), plus up to 5 s for the fallback dial or 5 s for its TLS handshake. There is no overall deadline across the two attempts. Requests in the next 60 s skip the box, which limits the cost to about one request per minute per edge. The report never states this worst case, and only refused connections and bad TLS are tested, not a hanging dial. Fix: state the bound in the code comment or notes. 3. **A write lock on every backhauled request.** `backhaulTarget` calls `backhaulSuspect`, which takes `m.mu.Lock()` (`backhaul_retry.go:41`). That is the same RWMutex `snapshot()` read-locks on every request (`homemap.go:1036`). This adds contention under load. When the map is full, eviction also scans all 50,000 entries while holding the lock (realistically never, since keys are bounded by the box set). Fix: a separate mutex, or an RLock read with lazy expiry. 4. **One host's TLS failure sidelines the whole box.** Suspicion is keyed by box. A TLS failure for one host's SNI (for example, a far box that has not issued that host's certificate yet) moves every HA host off that box for 60 s. It only changes preference, but nothing logs that one host caused it. A dedicated log line on the first mark would help. 5. **Double-counted metric and a mixed log key.** `observeRegional` counts once per attempt, so a request that falls back counts twice. The log key changed to `backhaul-retry &lt;ref&gt;`, which merges holder follows and connect fallbacks under one throttle key; the reason is still in the message text. **⚠️ Cannot verify from diff** - **Door path.** The door comment says it dials exactly the box its own `Owner()` read named (`edge.go:2150-2155`). Since Task 2 that is no longer true for holder memory, and now not for fallback or suspect avoidance either. The candidate filter keeps the account and app of `resolveHomeName`'s authority, but I did not prove that always matches `Owner()`'s account and app. The comment is now stale either way. - **Local claim.** At `edge.go:2105`, the first resolution includes the local claim, while `backhaulAlternative` resolves without it. I assume the owner is the same whenever the remote box wins, but I did not check every class and wildcard mix. - **Tests not re-run.** I did not run the race or timing tests; I relied on the report's output. **Task quality: Approved.** Minor 1 (the untested wrapper) should be fixed cheaply before merge.</result> <usage><subagent_tokens>69665</subagent_tokens><tool_uses>11</tool_uses><duration_ms>128022</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a1faf929dfb02114c</task-id> <tool-use-id>toolu_01QYxkxbYTjLwvz3neiRy151</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/87a21814-5655-4016-9e7e-41935ee8e96e/tasks/a1faf929dfb02114c.output</output-file> <status>completed</status> <summary>Agent "Whole-branch review G2R fixes" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>P1 count: 0 **Verdict.** The branch can merge once the P2 items below are fixed. Rule 1 applies: round 1 found no P1, so the review stops here. Apply the P2 fixes without opening another round. **What I checked against the global constraints.** - **Single writer:** holds. Every attempt lands on a box that re-checks the lease itself. Nothing touches placement or the proof conditions. - **Attempt bound:** holds. There are at most two attempts. Only the first is called with `retry=true` (`backhaul_holder.go:191`, `:199`). A holder follow and a connect fallback spend the same retry. `TestBackhaulFallbackAttemptBound` covers both orders. - **App-set holder header:** still stripped. No new trust is placed in it. - **Request bodies on fallback:** I suspected the first dial might close the request body before the retry. A small `ReverseProxy` experiment on go1.26.10 showed it does not: 10 B, 100 KB and 2 MB bodies all survived a failed dial. `TestBackhaulConnectFallback` (all methods) and `TestBackhaulTLSConnectFallback` pass. Not a finding. - **Suspect marks:** `homes` is stored once (`homemap.go:419`), so suspect marks survive a refresh. - **Fallback owner:** `backhaulAlternative` resolves the name with the same `resolveHomeName(host, nil, false, hosts)` call that `Owner` uses. It then keeps only claims with the same name, class, account, app and target. So when both read the same snapshot, the fallback box always serves the owner the door checked. No P1 there. **Findings** **P2-1: door path. Owner check and dial can now disagree (invariant: door #175 P7, "the check and the dial cannot disagree").** - Where: `edge.go:2146-2156`, `backhaul_holder.go:86-101`, `homemap.go:1145-1157`. - `backhaulTo` now swaps the box `Owner` returned for two things: a remembered holder, and the suspect-path alternative. - (a) The alternative re-reads the snapshot. If a refresh lands between `Owner` and `backhaulTarget` and the name has changed owner, the door call goes to the new owner's box and carries `signHopDoor`. - (b) The holder memory is keyed by host only. It never checks that the holder claims the host for the same account and app. Scenario: X releases a host, Y claims it, and the old holder still has X's route for a short while. Y's door call is then dialled to that holder and served by X's app. The window is the holder's route lag. A 503 without the header drops the entry, so it cannot last the full 10 min. - Not P1: the window is narrow and bounded, and the box reached is one that any public client would also reach. - Fix: pass the expected account and app into `backhaulTo`/`backhaulTarget`. Store the owner in `backhaulHolderEntry` when it is learned. Skip the memory and the alternative when the owner doesn't match. Then rewrite the stale comments at `edge.go:2146-2150` and on `Owner`. This also settles the ledger's cannot-verify item. **P2-2: docs. Follow-ups note W3 is out of date.** - Where: `docs/superpowers/notes/2026-11-06-region-ha-g2-follow-ups.md`, "G2 rerun findings" item 5. - It still says Task 3 is "on this branch as Task 3, still being built". It was built in `39417638`. - Fix: update the status line. While there, state the worst-case extra latency on a blackholed box: about two 5 s dial timeouts, then 60 s of suspicion. **P3-A: T5. A changed row resets the withdrawal backoff to 30 s.** - Where: `provision/poolwithdrawal.go` `prune` and `pending`. - If a host stays pending by design (follow-up 3) and its row keeps changing, it now retries at 30 s, 60 s, 120 s… after every change, instead of waiting 5 min. Each retry is a record GET plus a proof job. - Before the branch, a row change already caused one immediate retry. Bounded, but more S3 reads in that family. Measure under N4 (follow-up 17). **P3-B: T2/T3. The headroom freshness check also gates fallback, not just the follow.** - Where: `holderview.go:96` (`HeadroomFresh`). - Boxes that publish no headroom only refresh their edges file when something changes. After 15 min they can't be a follow target or a fallback target. Pool boxes publish headroom, so the G2 path is covered. - Confirm on dev, as the ledger's T2 minor already says. **Triage of deferred minors** - T1 certwarm skips names under wildcard parents when the issuer has no DNS provider: **P3.** That box couldn't renew wildcards before the branch either. On-demand per-host issuance still covers a handshake when no valid wildcard is present. Moot after W2b. - T1 serve-only boxes complete handshakes for unregistered one-label names: **P3.** Same posture as fixed boxes. Add a census note. - T1 TLS test rebuilds the wiring and has no `w != nil` assert: **P3.** - T1 journal prints the serve-only line, then "wildcard certs on": **P3.** The runbook line still matches. Optionally reword the second line when `w.dns == nil`. - T4 a walk longer than 60 s can start a second round: **P3.** It stays within the three-round cap. - T2 the idle-connection race can drop one hint; trace hooks chain: **P3.** - T2 the headroom freshness check may never pass: **P3.** Fold into P3-B. - T3 the `forwardConnectError` dial wrapper is not exercised by tests: **P3.** The trace callback (`ConnectDone`) already catches dial errors, and the wrapper only ever fires before a connection exists, so it cannot cause a replay. Add a test that keeps the real wrapper when convenient. - T3 about 10 s extra latency on a blackholed box: **P3.** Covered by the doc line in P2-2. - T3 `backhaulSuspect` takes the `homeMap` write lock on every backhauled request: **P3.** Cheap fix: check under the read lock first and take the write lock only to delete an expired entry. `backhaulAlternative` also locks once per claim. - T3 one host's TLS failure marks the whole box suspect, with no log on the first mark: **P3.** Add a throttled log on the first mark. - T3 `observeRegional` counts a fallback twice, and the log key merges follow and fallback: **P3.** - T3 cannot-verify (stale door comment; local claim versus alternative owner): **resolved into P2-1.** The 2118 path has a local claim; dropping that losing local claim does not change the winning remote authority. **Cross-task checks with no finding** - **T1 handshake posture:** the only change for group members is wildcard serving. `devbox.go` still refuses without a DNS provider. Who wins the issuer election is unchanged and stays with W2b. - **T4:** the nudge runs serially in the one backstop goroutine. It never runs `Rebuild` at the same time as the timer round, and `Rebuild` runs on the agent context. The incremental Refresh contract is untouched. On boxes with no change index it only sets `backstopFullDue`, which the fast loop always consumes, rate-limited by `fastFullClamp`. - **T5:** the `Unwrap`/`Is` change is safe. The only consumer, `withdrawPools`, uses `errors.As` for the code. `cause=&lt;nil&gt;` is printed when there is no cause. **Runbook and notes** - Runbook: correct. The quoted format string and `CARLOS_DNSIMPLE_TOKEN missing` match `wildcard.go` and `dns.go:77`. - Follow-ups note: only the W3 stale status (P2-2). - Investigation note: nothing wrong found. Files: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/g2r-fixes/internal/edge/backhaul_holder.go`, `.../internal/edge/backhaul_retry.go`, `.../internal/edge/edge.go`, `.../internal/edge/homemap.go`, `.../docs/superpowers/notes/2026-11-06-region-ha-g2-follow-ups.md`</result> <usage><subagent_tokens>131225</subagent_tokens><tool_uses>34</tool_uses><duration_ms>376005</duration_ms></usage> </task-notification>

Attributed to this commit: 11.6 g CO₂e (1,401,455 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-g2r-fixes, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/superpowers/notes/2026-11-06-region-ha-g2-follow-ups.md b/docs/superpowers/notes/2026-11-06-region-ha-g2-follow-ups.md
index 2fc9a05e1..b81a7c75a 100644
--- a/docs/superpowers/notes/2026-11-06-region-ha-g2-follow-ups.md
+++ b/docs/superpowers/notes/2026-11-06-region-ha-g2-follow-ups.md
@@ -186,8 +186,7 @@ simulation does not reopen a closed review round.
5. **W3: departure inventory and connect-failure fallback.**
Status: the inventory nudge was built in `68082f7b` and corrected in `a5ecbe76`.
The backstop loop performs an early full record walk for a departure waiting for fresh inventory. All departures share at most three early attempts during a fixed evidence window. The attempts are spaced at least 60 s apart.
- Connect-failure fallback is on this branch as Task 3, still being
- built. Plan commit: `15118be9`. Before writing any request bytes, try one other eligible box in the same region view. For 60 s after a failed connect, prefer another eligible claim without dropping the only claim. Do not retry after connecting.
+ Connect-failure fallback was built in `39417638`. Before writing any request bytes, try one other eligible box in the same region view. For 60 s after a failed connect, prefer another eligible claim without dropping the only claim. Do not retry after connecting. Worst-case extra latency on a blackholed box is about two 5 s dial timeouts for one request, then that box is skipped for 60 s while another eligible box exists.
6. **W4: cross-region holder follow and memory.**
Status: built in `445e881d`, corrected in `5ee6d6ae`.
@@ -200,3 +199,17 @@ simulation does not reopen a closed review round.
7. **W5: lease loss after a brief S3 failure.**
Status: recorded for later design, not built. Since `98c43eea`, an S3 failure of about 30 s overlapping a lease renewal latches lease loss.
The observed result is an unclean release and re-acquisition on the same box, with 20-40 s of 503 responses per host and no data loss. The open design question is whether a single missed renewal well inside the TTL should latch lease loss.
+
+## P3 follow-ups from the final review
+
+- withdrawal backoff restarts at 30 s after every row change (more record GETs; measure under N4)
+- HeadroomFresh gates holder follow and fallback, confirm pool-box headroom cadence on dev
+- certwarm skips names under wildcard parents when the issuer has no DNS provider (moot after W2b)
+- serve-only boxes complete handshakes for unregistered one-label names (same posture as fixed boxes)
+- serve-only journal prints "wildcard certs on" after the serve-only line
+- a backstop walk over 60 s can start a second early round (within the cap)
+- idle-connection race can drop one holder hint
+- forwardConnectError dial wrapper not exercised by tests
+- backhaulSuspect takes the homeMap write lock per backhauled request
+- one host's TLS failure marks the whole box suspect with no log on first mark
+- observeRegional counts a fallback twice and the log key merges follow and fallback
diff --git a/internal/edge/admission_exact_test.go b/internal/edge/admission_exact_test.go
index 18b74e1e3..d8e6c7f96 100644
--- a/internal/edge/admission_exact_test.go
+++ b/internal/edge/admission_exact_test.go
@@ -69,7 +69,8 @@ func TestAdmissionExactNameStopsPeerWildcard(t *testing.T) {
for label, m := range map[string]*homeMap{"peer": s.b.homes, "observer": observer} {
entry, held := m.lookupHome(host)
eip, box, exact := m.ExactHome(host)
- acct, _, _, _, owned := m.Owner(host)
+ owner, owned := m.Owner(host)
+ acct := owner.Account
if state.closed {
if !held || entry.dial || entry.eip != "" || entry.box != "" {
t.Errorf("%s lookupHome = %+v, %v; want held with no dial target", label, entry, held)
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go
index 757f874c1..ec7e4b352 100644
--- a/internal/edge/assetcatch.go
+++ b/internal/edge/assetcatch.go
@@ -1122,7 +1122,7 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string
// 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) }
+ forward := func() { e.farForward(w, r, host) }
if !canonicalAssetPath(r.URL) {
forward()
return true
@@ -1207,7 +1207,7 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string
WroteHeaders: func() { hopped.Store(true) },
}))
}
- e.farForward(cw, fr, host, eip, box)
+ e.farForward(cw, fr, host)
}
var judged, admitted bool
throttle := func() bool {
@@ -1328,13 +1328,14 @@ func assetAcknowledged(h http.Header, key []byte, assertion string) (expires int
}
// farForward is the far catch's uncached fallback: the ordinary backhaul,
-// answered Carlos-Cache: bypass. backhaulTo answers false only when the mesh
-// key went away after farAssetCatch read it; the client is then told to come
-// back shortly rather than given an answer for a host this box does not
-// serve. The backhaul itself keeps the asset vocabulary off the response
+// answered Carlos-Cache: bypass. The owner and destination are resolved together
+// again so a refresh cannot label an old box's holder hint with a new owner.
+// If the home or mesh key went away after farAssetCatch read it, the client
+// is told to come back shortly rather than given an answer for a host this
+// box does not serve. The backhaul itself keeps the asset vocabulary off the response
// (scrubBackhaulResponse, assetInformationalScrub).
-func (e *Edge) farForward(w http.ResponseWriter, r *http.Request, host, eip, box string) {
- if !e.backhaulTo(&assetResultWriter{ResponseWriter: w, result: "bypass"}, r, host, eip, box) {
+func (e *Edge) farForward(w http.ResponseWriter, r *http.Request, host string) {
+ if !e.backhaul(&assetResultWriter{ResponseWriter: w, result: "bypass"}, r, host) {
w.Header().Set("Retry-After", "2")
http.Error(w, "temporarily busy", http.StatusServiceUnavailable)
}
diff --git a/internal/edge/backhaul_holder.go b/internal/edge/backhaul_holder.go
index 282af0aa5..fb6316307 100644
--- a/internal/edge/backhaul_holder.go
+++ b/internal/edge/backhaul_holder.go
@@ -10,13 +10,32 @@ import (
"sync"
"sync/atomic"
"time"
+
+ "github.com/carlosframework/platform/internal/edgesfile"
)
const backhaulHolderTTL = 10 * time.Minute
const backhaulHolderLimit = 50_000
+// backhaulOwner is the identity ResolveNameAuthority requires for a substitute.
+// Stamps and serving sequences choose a replica within that identity.
+type backhaulOwner struct {
+ name string
+ class edgesfile.NameClass
+ account, app, targetHost string
+}
+
+func backhaulOwnerOf(c edgesfile.NameClaim) backhaulOwner {
+ return backhaulOwner{c.Name, c.Class, c.Account, c.App, c.TargetHost}
+}
+
+func (o backhaulOwner) matches(other backhaulOwner) bool {
+ return o.account != "" && o.app != "" && o == other
+}
+
type backhaulHolderEntry struct {
host, ref string
+ owner backhaulOwner
until time.Time
}
@@ -26,7 +45,7 @@ type backhaulHolderCache struct {
order list.List
}
-func (c *backhaulHolderCache) get(host string, now time.Time) string {
+func (c *backhaulHolderCache) get(host string, owner backhaulOwner, now time.Time) string {
c.mu.Lock()
defer c.mu.Unlock()
el := c.entries[host]
@@ -39,18 +58,22 @@ func (c *backhaulHolderCache) get(host string, now time.Time) string {
c.order.Remove(el)
return ""
}
+ if !owner.matches(entry.owner) {
+ return ""
+ }
return entry.ref
}
-func (c *backhaulHolderCache) remember(host, ref string, now time.Time) bool {
+func (c *backhaulHolderCache) remember(host, ref string, owner backhaulOwner, now time.Time) bool {
c.mu.Lock()
defer c.mu.Unlock()
if c.entries == nil {
c.entries = make(map[string]*list.Element)
}
- entry := backhaulHolderEntry{host: host, ref: ref, until: now.Add(backhaulHolderTTL)}
+ entry := backhaulHolderEntry{host: host, ref: ref, owner: owner, until: now.Add(backhaulHolderTTL)}
if el := c.entries[host]; el != nil {
- changed := el.Value.(backhaulHolderEntry).ref != ref
+ old := el.Value.(backhaulHolderEntry)
+ changed := old.ref != ref || old.owner != owner
el.Value = entry
c.order.MoveToBack(el)
return changed
@@ -64,10 +87,10 @@ func (c *backhaulHolderCache) remember(host, ref string, now time.Time) bool {
return true
}
-func (c *backhaulHolderCache) drop(host, ref string) bool {
+func (c *backhaulHolderCache) drop(host, ref string, owner backhaulOwner) bool {
c.mu.Lock()
defer c.mu.Unlock()
- if el := c.entries[host]; el != nil && el.Value.(backhaulHolderEntry).ref == ref {
+ if el := c.entries[host]; el != nil && el.Value.(backhaulHolderEntry).ref == ref && el.Value.(backhaulHolderEntry).owner == owner {
delete(c.entries, host)
c.order.Remove(el)
return true
@@ -75,25 +98,25 @@ func (c *backhaulHolderCache) drop(host, ref string) bool {
return false
}
-func (e *Edge) dropBackhaulHolder(host, ref, reason string) {
- if e.backhaulHolders.drop(host, ref) {
+func (e *Edge) dropBackhaulHolder(host, ref, reason string, owner backhaulOwner) {
+ if e.backhaulHolders.drop(host, ref, owner) {
e.logThrottled("backhaul-holder-drop "+ref, fmt.Sprintf("backhaul holder dropped for %s: %s (%s)", host, ref, reason))
}
}
// backhaulTarget is the initial choice for this request. Every cache hit is
-// checked against the current destination view before it can change the dial.
-func (e *Edge) backhaulTarget(host, dial, box string) (string, string) {
+// bound to the checked owner and validated against the destination view.
+func (e *Edge) backhaulTarget(host, dial, box string, owner backhaulOwner) (string, string) {
now := time.Now()
- if ref := e.backhaulHolders.get(host, now); ref != "" {
+ if ref := e.backhaulHolders.get(host, owner, now); ref != "" {
if addr, ok := e.homes.Load().boxInRegionView(ref, box, now); ok {
dial, box = addr, ref
} else {
- e.dropBackhaulHolder(host, ref, "left region view")
+ e.dropBackhaulHolder(host, ref, "left region view", owner)
}
}
if m := e.homes.Load(); m.backhaulSuspect(box, now) {
- if addr, ref, ok := m.backhaulAlternative(host, box, now); ok {
+ if addr, ref, ok := m.backhaulAlternative(host, box, owner, now); ok {
return addr, ref
}
}
@@ -122,7 +145,7 @@ func (t backhaulHolderTransport) RoundTrip(r *http.Request) (*http.Response, err
return resp, nil
}
-func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dial, box string, key []byte, retry bool) {
+func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dial, box string, key []byte, owner backhaulOwner, retry bool) {
var nextDial, nextRef, nextReason string
// Only connection failures disprove a hint. A canceled client or an
// error after connecting says nothing about which box holds the lease.
@@ -147,7 +170,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")
+ e.dropBackhaulHolder(host, box, "holder refusal", owner)
}
if ref == "" || ref == "none" || ref == box {
return nil
@@ -157,7 +180,7 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia
if !ok {
return nil
}
- if e.backhaulHolders.remember(host, ref, now) {
+ if e.backhaulHolders.remember(host, ref, owner, now) {
e.logThrottled("backhaul-holder-learn "+ref, fmt.Sprintf("backhaul holder learned for %s: %s", host, ref))
}
// HTTP/2 supplies a body object even when the request has no body.
@@ -174,12 +197,12 @@ 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")
+ e.dropBackhaulHolder(host, 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, now); ok {
+ if addr, ref, ok := m.backhaulAlternative(host, box, owner, now); ok {
nextDial, nextRef, nextReason = addr, ref, "connect fallback"
return
}
@@ -196,6 +219,6 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia
// First attempt plus one retry, at most two attempts total. A connect
// fallback and a §6.5 holder follow spend the same retry budget.
// Start with the original context so trace callbacks cannot accumulate.
- e.backhaulAttempt(w, original, host, nextDial, nextRef, key, false)
+ e.backhaulAttempt(w, original, host, nextDial, nextRef, key, owner, false)
}
}
diff --git a/internal/edge/backhaul_holder_test.go b/internal/edge/backhaul_holder_test.go
index f4a54dd61..9fec32dac 100644
--- a/internal/edge/backhaul_holder_test.go
+++ b/internal/edge/backhaul_holder_test.go
@@ -10,39 +10,41 @@ import (
func TestBackhaulHolderMemoryBounds(t *testing.T) {
now := time.Date(2026, 11, 6, 12, 0, 0, 0, time.UTC)
var c backhaulHolderCache
- c.remember("first", "a", now)
- if got := c.get("first", now.Add(10*time.Minute-time.Nanosecond)); got != "a" {
+ owner := backhaulOwner{account: "acct", app: "shop"}
+ c.remember("first", "a", owner, now)
+ if got := c.get("first", owner, now.Add(10*time.Minute-time.Nanosecond)); got != "a" {
t.Fatalf("before TTL: %q", got)
}
- if got := c.get("first", now.Add(10*time.Minute)); got != "" {
+ if got := c.get("first", owner, now.Add(10*time.Minute)); got != "" {
t.Fatalf("at TTL: %q", got)
}
for i := 0; i < 50_001; i++ {
- c.remember(fmt.Sprint(i), "a", now)
+ c.remember(fmt.Sprint(i), "a", owner, now)
}
if len(c.entries) != 50_000 || c.order.Len() != 50_000 {
t.Fatalf("size=%d order=%d", len(c.entries), c.order.Len())
}
- if c.get("0", now) != "" || c.get("50000", now) != "a" {
+ if c.get("0", owner, now) != "" || c.get("50000", owner, now) != "a" {
t.Fatal("oldest hint was not evicted")
}
- c.remember("1", "b", now.Add(time.Minute))
- c.remember("last", "a", now.Add(time.Minute))
- if c.get("1", now) != "b" || c.get("2", now) != "" {
+ c.remember("1", "b", owner, now.Add(time.Minute))
+ c.remember("last", "a", owner, now.Add(time.Minute))
+ if c.get("1", owner, now) != "b" || c.get("2", owner, now) != "" {
t.Fatal("refresh did not move eviction order")
}
- c.drop("1", "a")
- if c.get("1", now) != "b" {
+ c.drop("1", "a", owner)
+ if c.get("1", owner, now) != "b" {
t.Fatal("old holder's failure dropped its replacement")
}
- c.drop("1", "b")
- if c.get("1", now) != "" {
+ c.drop("1", "b", owner)
+ if c.get("1", owner, now) != "" {
t.Fatal("holder failure retained its hint")
}
}
func TestBackhaulHolderMemoryConcurrent(t *testing.T) {
var c backhaulHolderCache
+ owner := backhaulOwner{account: "acct", app: "shop"}
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
@@ -50,9 +52,9 @@ func TestBackhaulHolderMemoryConcurrent(t *testing.T) {
defer wg.Done()
for j := 0; j < 100; j++ {
host := fmt.Sprint(j)
- c.remember(host, "a", time.Now())
- c.get(host, time.Now())
- c.drop(host, "a")
+ c.remember(host, "a", owner, time.Now())
+ c.get(host, owner, time.Now())
+ c.drop(host, "a", owner)
}
}()
}
diff --git a/internal/edge/backhaul_owner_export_test.go b/internal/edge/backhaul_owner_export_test.go
new file mode 100644
index 000000000..19b4b639f
--- /dev/null
+++ b/internal/edge/backhaul_owner_export_test.go
@@ -0,0 +1,117 @@
+package edge
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/doorkey"
+)
+
+func (s *BackhaulHolderScene) ownerRequest(t *testing.T, account, app string) *http.Request {
+ t.Helper()
+ fx := newDoorKeyFixture(t)
+ raw, entry := fx.mint(t, account, app)
+ putJSON(t, s.store, doorkey.RecordKey(account, app), string(fx.record(t, account, app, 1, entry)))
+ s.sender.edge.doorKeys = fx.mirror(s.store)
+ refreshDoorKeys(t, s.sender.edge.doorKeys)
+ s.sender.edge.doorAddr = doorTestAddr
+ r := httptest.NewRequest(http.MethodPost, "http://"+HAForwardHost+"/", nil)
+ r.RemoteAddr = "@"
+ r.Header.Set(doorkey.Header, raw)
+ return r
+}
+
+func (s *BackhaulHolderScene) DoorRequest(t *testing.T, account, app string) (int, string) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ s.sender.edge.serveDoor(w, s.ownerRequest(t, account, app))
+ return w.Code, w.Body.String()
+}
+
+func (s *BackhaulHolderScene) SetBackhaulOwner(t *testing.T, box, field string, value any) {
+ t.Helper()
+ key := "control/edges/" + box + ".json"
+ data, _, err := s.store.Get(t.Context(), key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var f map[string]any
+ if err := json.Unmarshal(data, &f); err != nil {
+ t.Fatal(err)
+ }
+ hosts := f["hosts"].(map[string]any)
+ claim := hosts[HAForwardHost].(map[string]any)
+ if field == "name" {
+ delete(hosts, HAForwardHost)
+ hosts[value.(string)] = claim
+ } else {
+ claim[field] = value
+ }
+ b, err := json.Marshal(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ putJSON(t, s.store, key, string(b))
+ refreshHomeMap(t, s.sender.homes)
+}
+
+// DoorAfterOwnerRefresh pauses at the production Owner/backhaulTo boundary.
+// The request has passed real door-key verification before the publication changes.
+func (s *BackhaulHolderScene) DoorAfterOwnerRefresh(t *testing.T, account, app, field string, value any, suspect bool) (int, string) {
+ t.Helper()
+ r, ok := s.sender.edge.doorRequest(s.ownerRequest(t, account, app))
+ if !ok {
+ t.Fatal("door key refused")
+ }
+ owner, ok := s.sender.homes.Owner(HAForwardHost)
+ if !ok || owner.Account != account || owner.App != app {
+ t.Fatalf("owner=%s/%s, want %s/%s", owner.Account, owner.App, account, app)
+ }
+ s.SetBackhaulOwner(t, "annie", field, value)
+ s.SetBackhaulOwner(t, "betty", field, value)
+ if suspect {
+ s.sender.homes.markBackhaulSuspect(owner.Box, time.Now())
+ }
+ w := httptest.NewRecorder()
+ if !s.sender.edge.backhaulTo(w, r, HAForwardHost, owner.Dial, owner.Box, backhaulOwnerOf(owner)) {
+ t.Fatal("backhaul refused")
+ }
+ return w.Code, w.Body.String()
+}
+
+func (s *BackhaulHolderScene) SetBackhaulRouteOwner(t *testing.T, holder bool, account, app string) {
+ t.Helper()
+ be := s.first
+ if holder {
+ be = s.holder
+ }
+ rt, err := be.reg.Get(HAForwardHost)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rt.Account, rt.App = account, app
+ if err := be.reg.Upsert(*rt); err != nil {
+ t.Fatal(err)
+ }
+ if err := be.edge.Reload(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func (s *BackhaulHolderScene) FarForwardAfterOwnerRefresh(t *testing.T) (int, string) {
+ t.Helper()
+ _, box, ok := s.sender.homes.Home(HAForwardHost)
+ if !ok || box != "annie" {
+ t.Fatal("home missing")
+ }
+ // Retire the old destination between the asset lookup and its bypass.
+ s.SetBackhaulOwner(t, "annie", "name", "retired.forward.test")
+ s.SetBackhaulOwner(t, "betty", "app", "other")
+ r := httptest.NewRequest(http.MethodGet, "https://"+HAForwardHost+"/", nil)
+ w := httptest.NewRecorder()
+ s.sender.edge.farForward(w, r, HAForwardHost)
+ return w.Code, w.Body.String()
+}
diff --git a/internal/edge/backhaul_owner_wiring_test.go b/internal/edge/backhaul_owner_wiring_test.go
new file mode 100644
index 000000000..50e895256
--- /dev/null
+++ b/internal/edge/backhaul_owner_wiring_test.go
@@ -0,0 +1,115 @@
+package edge_test
+
+import (
+ "testing"
+
+ "github.com/carlosframework/platform/internal/edge"
+)
+
+func TestDoorBackhaulHolderOwner(t *testing.T) {
+ for _, tc := range []struct {
+ field string
+ value any
+ }{
+ {"account", "other"},
+ {"app", "other"},
+ {"alias", true},
+ {"target_host", "other.forward.test"},
+ {"name", "*.forward.test"},
+ } {
+ t.Run(tc.field, func(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ s.SetBackhaulRouteOwner(t, true, rt.Account, rt.App)
+ if status, _, _ := s.Request(t, "GET", "/", ""); status != 200 {
+ t.Fatalf("learn holder: %d", status)
+ }
+ s.FirstApp(t)
+ s.SetBackhaulOwner(t, "annie", tc.field, tc.value)
+ s.HolderFile(t, "hosts", map[string]any{})
+ account, app := rt.Account, rt.App
+ if tc.field == "account" {
+ account = "other"
+ } else if tc.field == "app" {
+ app = "other"
+ }
+ s.SetBackhaulRouteOwner(t, false, account, app)
+ beforeA, beforeB := s.Counts()
+ status, body := s.DoorRequest(t, account, app)
+ a, b := s.Counts()
+ if status != 200 || body != "first|"+rt.Host+"|/" || a != beforeA+1 || b != beforeB {
+ t.Fatalf("door reached old owner's holder: status=%d body=%q requests=%d/%d, want first only", status, body, a-beforeA, b-beforeB)
+ }
+ })
+ }
+}
+
+func TestDoorBackhaulAlternativeOwnerRefresh(t *testing.T) {
+ for _, suspect := range []bool{true, false} {
+ for _, tc := range []struct {
+ field string
+ value any
+ }{
+ {"account", "other"},
+ {"app", "other"},
+ {"alias", true},
+ {"target_host", "other.forward.test"},
+ {"name", "*.forward.test"},
+ } {
+ name := "connect/" + tc.field
+ if suspect {
+ name = "suspect/" + tc.field
+ }
+ t.Run(name, func(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ s.FirstApp(t)
+ wantStatus := 200
+ if !suspect {
+ s.FailBackhaulDial(t, false)
+ wantStatus = 502
+ }
+ status, body := s.DoorAfterOwnerRefresh(t, rt.Account, rt.App, tc.field, tc.value, suspect)
+ a, b := s.Counts()
+ if status != wantStatus || b != 0 || (suspect && (a != 1 || body != "first|"+rt.Host+"|/")) {
+ t.Fatalf("owner refresh changed door destination: status=%d body=%q requests=%d/%d, want status %d and no holder request", status, body, a, b, wantStatus)
+ }
+ })
+ }
+ }
+}
+
+func TestDoorBackhaulSameOwnerSubstitutions(t *testing.T) {
+ for _, mode := range []string{"holder", "connect"} {
+ t.Run(mode, func(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ if mode == "holder" {
+ if status, _, _ := s.Request(t, "GET", "/", ""); status != 200 {
+ t.Fatalf("learn holder: %d", status)
+ }
+ } else {
+ s.FailBackhaulDial(t, false)
+ }
+ beforeA, beforeB := s.Counts()
+ // The second connect case uses the suspect preference learned by the first.
+ for i := int64(1); i <= 2; i++ {
+ status, body := s.DoorRequest(t, rt.Account, rt.App)
+ a, b := s.Counts()
+ if status != 200 || body != "holder|"+rt.Host+"|/" || a != beforeA || b != beforeB+i {
+ t.Fatalf("same owner substitution: status=%d body=%q requests=%d/%d", status, body, a-beforeA, b-beforeB)
+ }
+ }
+ })
+ }
+}
+
+func TestBackhaulAssetBypassOwnerRefresh(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ status, body := s.FarForwardAfterOwnerRefresh(t)
+ a, b := s.Counts()
+ if status != 200 || body != "holder|"+rt.Host+"|/" || a != 0 || b != 1 {
+ t.Fatalf("asset bypass mixed old destination with new owner: status=%d body=%q requests=%d/%d", status, body, a, b)
+ }
+}
diff --git a/internal/edge/backhaul_retry.go b/internal/edge/backhaul_retry.go
index 22e0bfeea..a1c8f03d9 100644
--- a/internal/edge/backhaul_retry.go
+++ b/internal/edge/backhaul_retry.go
@@ -49,14 +49,14 @@ func (m *homeMap) backhaulSuspect(box string, now time.Time) bool {
// backhaulAlternative retains namespace authority while excluding a failed
// box from service. All candidates belong to the destination's region view,
-// and the resolver still requires the same owner, name, class and target.
-func (m *homeMap) backhaulAlternative(host, failed string, now time.Time) (string, string, bool) {
+// and a refreshed snapshot must still name the expected owner, class and target.
+func (m *homeMap) backhaulAlternative(host, failed string, expected backhaulOwner, now time.Time) (string, string, bool) {
if m == nil || m.self == "" {
return "", "", false
}
snap := m.snapshot()
original := resolveHomeName(host, nil, false, snap.hosts)
- if original.State != edgesfile.NameDialable {
+ if original.State != edgesfile.NameDialable || !expected.matches(backhaulOwnerOf(original.Authority)) {
return "", "", false
}
owner := original.Authority
diff --git a/internal/edge/backhaul_retry_test.go b/internal/edge/backhaul_retry_test.go
index 27bc8eba0..9d3a124c8 100644
--- a/internal/edge/backhaul_retry_test.go
+++ b/internal/edge/backhaul_retry_test.go
@@ -65,7 +65,7 @@ func TestBackhaulFallbackWildcardAuthority(t *testing.T) {
if _, ref, ok := m.Home("app.test"); !ok || ref != "annie" {
t.Fatalf("normal home=%s %t", ref, ok)
}
- if _, ref, ok := m.backhaulAlternative("app.test", "annie", time.Now()); !ok || ref != "betty" {
+ if _, ref, ok := m.backhaulAlternative("app.test", "annie", backhaulOwnerOf(m.resolveName("app.test", nil, false).Authority), time.Now()); !ok || ref != "betty" {
t.Fatalf("alternate=%s %t, want betty under original wildcard owner", ref, ok)
}
}
diff --git a/internal/edge/backhaul_share_test.go b/internal/edge/backhaul_share_test.go
index 59af83526..25754429c 100644
--- a/internal/edge/backhaul_share_test.go
+++ b/internal/edge/backhaul_share_test.go
@@ -206,7 +206,7 @@ func TestBackhaulShareDoorExempt(t *testing.T) {
req.RemoteAddr = net.JoinHostPort(shareClientA, "40000")
req = req.WithContext(context.WithValue(req.Context(), doorCallerKey{}, doorCaller{Account: "shop", App: "web"}))
rec := httptest.NewRecorder()
- if !s.e.backhaulTo(rec, req, "example.com", s.eip, "betty") {
+ if !s.e.backhaulTo(rec, req, "example.com", s.eip, "betty", backhaulOwner{}) {
t.Fatal("backhaulTo declined the request")
}
if rec.Code != http.StatusOK || rec.Body.String() != homeEdgeBody {
diff --git a/internal/edge/door.go b/internal/edge/door.go
index 47a7fa86f..12c9b0206 100644
--- a/internal/edge/door.go
+++ b/internal/edge/door.go
@@ -20,7 +20,7 @@ package edge
// - the tunnel and steering-probe hostnames are unknown hosts to a door
// caller, in any spelling, and their handlers never run;
// - a host this box does not serve is dialled only when the owner its home
-// box published is the caller's app, and only at the box Owner named;
+// box published is the caller's app; substitutions keep that owner;
// - a host this box serves is checked against the FINAL upstream, after
// the gate's login re-resolution, before the gate, the cache and the
// dispatch.
diff --git a/internal/edge/door_test.go b/internal/edge/door_test.go
index 2069c01f2..eaf617546 100644
--- a/internal/edge/door_test.go
+++ b/internal/edge/door_test.go
@@ -323,8 +323,8 @@ func TestDoorRemoteHostChecksThePublishedOwner(t *testing.T) {
m := newHomeMap(s.store, "annie")
refreshHomeMap(t, m)
s.e.homes.Store(m)
- if acct, app, gotEIP, box, ok := m.Owner("example.com"); !ok || acct != "bae" || app != "titogo" || gotEIP != eip || box != doorHomeEdgeKey {
- t.Fatalf("precondition: Owner = %q %q %q %q %v", acct, app, gotEIP, box, ok)
+ if owner, ok := m.Owner("example.com"); !ok || owner.Account != "bae" || owner.App != "titogo" || owner.Dial != eip || owner.Box != doorHomeEdgeKey {
+ t.Fatalf("precondition: Owner = %q %q %q %q %v", owner.Account, owner.App, owner.Dial, owner.Box, ok)
}
r := s.do(t, http.MethodGet, "example.com", "/", s.key, nil, nil)
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 0b3b92c47..127dac2c5 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -2115,7 +2115,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
e.unknownHost(w, r)
return
}
- if e.serveAssetFar(w, r, host) || e.backhaulTo(w, r, host, resolved.Serving.Dial, resolved.Serving.Box) {
+ 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
@@ -2145,14 +2145,12 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
e.homes.Load().staleHopRefusal(w, host)
return
}
- // A door caller reaches a host served elsewhere only when the owner
- // its home box published is the caller's app, and is dialled at
- // exactly the box that same Owner read named, so the check and the
- // dial cannot disagree. A hostname split between apps publishes no
- // owner and is refused here. The far edge sees an ordinary hop.
+ // A door caller can backhaul only to its own app. Carry the checked
+ // name, class and target through every holder or fallback choice;
+ // a snapshot refresh must not change the owner of the signed call.
if isDoor {
- if acct, app, eip, box, ok := e.homes.Load().Owner(host); ok && acct == door.Account && app == door.App {
- if e.backhaulTo(w, r, host, eip, box) {
+ if owner, ok := e.homes.Load().Owner(host); ok && owner.Account == door.Account && owner.App == door.App {
+ if e.backhaulTo(w, r, host, owner.Dial, owner.Box, backhaulOwnerOf(owner)) {
return
}
}
@@ -4187,19 +4185,18 @@ func (e *Edge) backhaul(w http.ResponseWriter, r *http.Request, host string) boo
m.staleHopRefusal(w, host)
return true
}
- eip, box, ok := m.Home(host)
- if !ok {
+ resolved := m.resolveName(host, nil, false)
+ if resolved.State == edgesfile.NameAbsent {
return false
}
- return e.backhaulTo(w, r, host, eip, box)
+ observeRegional("home", host)
+ return e.backhaulTo(w, r, host, resolved.Serving.Dial, resolved.Serving.Box, backhaulOwnerOf(resolved.Authority))
}
-// backhaulTo is backhaul's dial half: sign, contain, and forward to the box at
-// eip. Split out so the edge-local door dials exactly the target its own
-// Owner read returned (door.go); backhaul is Home plus this, unchanged. It
-// answers false only when no mesh key is mirrored, and it repeats backhaul's
-// arrived-hop guard so neither caller can forward a hop onward.
-func (e *Edge) backhaulTo(w http.ResponseWriter, r *http.Request, host, eip, box string) bool {
+// 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.
+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)
@@ -4221,8 +4218,8 @@ func (e *Edge) backhaulTo(w http.ResponseWriter, r *http.Request, host, eip, box
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)
- e.backhaulAttempt(w, r, host, eip, box, key, true)
+ eip, box = e.backhaulTarget(host, eip, box, owner)
+ e.backhaulAttempt(w, r, host, eip, box, key, owner, true)
return true
}
diff --git a/internal/edge/forwardha_test.go b/internal/edge/forwardha_test.go
index b7e3420ea..931d438ad 100644
--- a/internal/edge/forwardha_test.go
+++ b/internal/edge/forwardha_test.go
@@ -1134,7 +1134,7 @@ func TestForwardHADialFailureIs503RetryTen(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "https://"+fwHost+"/hopped", nil)
r.RemoteAddr = "203.0.113.9:4000"
rec := httptest.NewRecorder()
- if !x.a.edge.backhaulTo(rec, r, fwHost, dial, "betty") {
+ if !x.a.edge.backhaulTo(rec, r, fwHost, dial, "betty", backhaulOwner{}) {
t.Fatal("backhaulTo did not answer")
}
if rec.Code != http.StatusOK || rec.Body.String() != "annie|"+fwHost+"|/hopped" {
diff --git a/internal/edge/group_names_test.go b/internal/edge/group_names_test.go
index dfe7e6003..5d9f64971 100644
--- a/internal/edge/group_names_test.go
+++ b/internal/edge/group_names_test.go
@@ -123,7 +123,7 @@ func TestGroupNamesClosedCatchallChildren(t *testing.T) {
if got := m.resolveName("new.example.com", nil, false); got.State != edgesfile.NameHeld {
t.Errorf("child = %+v, want held", got)
}
- if _, _, _, _, ok := m.Owner("new.example.com"); ok {
+ if _, ok := m.Owner("new.example.com"); ok {
t.Error("closed child has dial owner")
}
w := httptest.NewRecorder()
@@ -209,7 +209,7 @@ func TestGroupNamesBeforeAdmission(t *testing.T) {
if !ok || ip != "" || box != "" {
t.Errorf("ExactHome = %q %q %v; want held", ip, box, ok)
}
- if _, _, _, _, ok := m.Owner(tc.key); ok {
+ if _, ok := m.Owner(tc.key); ok {
t.Error("closed owner authorized a dial")
}
if _, ok := m.AssetsFor(tc.key, time.Now()); ok {
@@ -279,7 +279,7 @@ func TestGroupNamesBeforeAdmission(t *testing.T) {
if !exact || (ip != "") != tc.want || (tc.want && box != "z-open") {
t.Fatalf("ExactHome %q %q %v", ip, box, exact)
}
- _, _, _, _, owned := m.Owner("a.example.com")
+ _, owned := m.Owner("a.example.com")
if owned != tc.want {
t.Fatalf("Owner eligible=%v", owned)
}
@@ -299,7 +299,8 @@ func TestGroupNamesBeforeAdmission(t *testing.T) {
putJSON(t, s, edgesfile.Key("z-open"), `{"v":1,"box":"z-open","eip":"192.0.2.2","hosts":{"*.example.com":{"role":"home","alias":true,"account":"b","app":"shop","target_host":"b.other.net"}}}`)
m := newHomeMap(s, "observer")
refreshHomeMap(t, m)
- acct, _, ip, box, ok := m.Owner("new.example.com")
+ owner, ok := m.Owner("new.example.com")
+ acct, ip, box := owner.Account, owner.Dial, owner.Box
if !ok || acct != "b" || ip != "192.0.2.2" || box != "z-open" {
t.Fatalf("peer catchall %s %s %s %v", acct, ip, box, ok)
}
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index 2de1286d8..204f7f800 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -1083,8 +1083,7 @@ func (m *homeMap) ExactHome(host string) (eip, box string, ok bool) {
}
// lookupHome is Home's lookup, answering the whole winning entry from one
-// snapshot read. Home and Owner both go through it, so they can never pick
-// different entries for the same host.
+// snapshot read. Home and Owner use the same namespace resolver.
func (m *homeMap) lookupHome(host string) (homeEntry, bool) {
if m == nil || m.self == "" {
return homeEntry{}, false
@@ -1143,23 +1142,17 @@ func resolveHomeName(host string, local []edgesfile.NameClaim, exact bool, hosts
return edgesfile.ResolveNameAuthority(host, local, peers)
}
-// Owner answers, from one read of one snapshot, both whom the edge-local
-// door must check and where it would dial (#175 P7), so the check and the
-// dial cannot disagree. The lookup is Home's, one-label wildcard included,
-// and eip and box are exactly what Home returns for the same host.
-//
-// ok is false, and everything else zero, when the winning entry is not a
-// dial target or published no owner: a hostname split between apps, or a
-// publisher that predates the field. An ownerless exact entry does not fall
-// through to a wildcard that names one, because the exact entry is the one
-// Home dials. A nil map, or one with no self label, answers nothing, as Home
-// does.
-func (m *homeMap) Owner(host string) (account, app, eip, box string, ok bool) {
- h, found := m.lookupHome(host)
- if !found || h.account == "" || h.app == "" {
- return "", "", "", "", false
- }
- return h.account, h.app, h.eip, h.box, true
+// Owner returns the serving claim and its owner from one snapshot (#175 P7).
+// The door checks its account and app, then passes the full name, class and
+// target identity to backhaulTo. A substitute must match that identity even
+// if the snapshot changes before the dial. Without one, dial this claim's box.
+// An ownerless or held exact name cannot borrow a wildcard's owner.
+func (m *homeMap) Owner(host string) (edgesfile.NameClaim, bool) {
+ r := m.resolveName(host, nil, false)
+ if r.State != edgesfile.NameDialable || r.Serving.Account == "" || r.Serving.App == "" {
+ return edgesfile.NameClaim{}, false
+ }
+ return r.Serving, true
}
// assetsFreshFor is how old a host's authority time may be and still be
diff --git a/internal/edge/homemap_assets_test.go b/internal/edge/homemap_assets_test.go
index 1a66002a9..13b34a76e 100644
--- a/internal/edge/homemap_assets_test.go
+++ b/internal/edge/homemap_assets_test.go
@@ -270,8 +270,8 @@ func TestOldFileWithoutAssetsParses(t *testing.T) {
if eip, box, ok := m.Home("shop.example.com"); !ok || eip != "2.2.2.2" || box != "betty" {
t.Fatalf("Home = %s %s %v", eip, box, ok)
}
- if acct, app, _, _, ok := m.Owner("shop.example.com"); !ok || acct != "abc" || app != "shop" {
- t.Fatalf("Owner = %s %s %v", acct, app, ok)
+ if owner, ok := m.Owner("shop.example.com"); !ok || owner.Account != "abc" || owner.App != "shop" {
+ t.Fatalf("Owner = %s %s %v", owner.Account, owner.App, ok)
}
if _, ok := m.AssetsFor("shop.example.com", goldenAt); ok {
t.Fatal("a host with no block answered")
diff --git a/internal/edge/homemap_test.go b/internal/edge/homemap_test.go
index 0a7365d13..f65c83c4f 100644
--- a/internal/edge/homemap_test.go
+++ b/internal/edge/homemap_test.go
@@ -1592,7 +1592,8 @@ func TestOwnerFoldsThroughExactAndWildcardLookup(t *testing.T) {
{"acme.go.tito.io", "titogo"},
{"ti.classic.tito.io", "classic"},
} {
- acct, app, eip, box, ok := m.Owner(c.host)
+ owner, ok := m.Owner(c.host)
+ acct, app, eip, box := owner.Account, owner.App, owner.Dial, owner.Box
if !ok || acct != "bae" || app != c.app {
t.Fatalf("Owner(%s) = %s/%s %v, want bae/%s", c.host, acct, app, ok, c.app)
}
@@ -1601,7 +1602,7 @@ func TestOwnerFoldsThroughExactAndWildcardLookup(t *testing.T) {
t.Fatalf("Owner(%s) dials %s/%s, Home dials %s/%s", c.host, eip, box, heip, hbox)
}
}
- if _, _, _, _, ok := m.Owner("a.b.classic.tito.io"); ok {
+ if _, ok := m.Owner("a.b.classic.tito.io"); ok {
t.Fatal("a two-label host must miss the one-label wildcard, as Home does")
}
}
@@ -1619,8 +1620,8 @@ func TestOwnerIsFalseWithoutAnOwnerOrADialTarget(t *testing.T) {
m := newHomeMap(s, "annie")
refreshHomeMap(t, m)
for _, host := range []string{"mixed.test", "halfowned.test", "x.certonly.test", "own.test", "nowhere.test"} {
- if acct, app, eip, box, ok := m.Owner(host); ok || acct != "" || app != "" || eip != "" || box != "" {
- t.Errorf("Owner(%s) = %q/%q %q/%q %v, want zeros and false", host, acct, app, eip, box, ok)
+ if owner, ok := m.Owner(host); ok || owner.Account != "" || owner.App != "" || owner.Dial != "" || owner.Box != "" {
+ t.Errorf("Owner(%s) = %q/%q %q/%q %v, want zeros and false", host, owner.Account, owner.App, owner.Dial, owner.Box, ok)
}
}
// An exact entry with no owner is the winner: the lookup does not fall
@@ -1628,11 +1629,11 @@ func TestOwnerIsFalseWithoutAnOwnerOrADialTarget(t *testing.T) {
putJSON(t, s, "control/edges/betty.json", `{"v":1,"box":"betty","eip":"2.2.2.2","hosts":{`+
`"exact.wild.test":{"role":"home"},"*.wild.test":{"role":"home","account":"bae","app":"titogo"}}}`)
refreshHomeMap(t, m)
- if _, _, _, _, ok := m.Owner("exact.wild.test"); ok {
+ if _, ok := m.Owner("exact.wild.test"); ok {
t.Error("an ownerless exact entry borrowed the wildcard's owner")
}
var nilMap *homeMap
- if acct, app, eip, box, ok := nilMap.Owner("acme.go.tito.io"); ok || acct != "" || app != "" || eip != "" || box != "" {
+ if owner, ok := nilMap.Owner("acme.go.tito.io"); ok || owner.Account != "" || owner.App != "" || owner.Dial != "" || owner.Box != "" {
t.Error("a nil map answered an owner")
}
}
@@ -1647,14 +1648,15 @@ func TestOwnerOfARouteReplacingAnAliasIsTheRoutes(t *testing.T) {
`"ownerless.test":{"role":"home"}}}`)
m := newHomeMap(s, "annie")
refreshHomeMap(t, m)
- acct, app, eip, box, ok := m.Owner("shared.test")
+ owner, ok := m.Owner("shared.test")
+ acct, app, eip, box := owner.Account, owner.App, owner.Dial, owner.Box
if !ok || acct != "bae" || app != "titogo" || eip != "3.3.3.3" || box != "carol" {
t.Fatalf("Owner(shared.test) = %s/%s %s/%s %v, want the route's bae/titogo on carol", acct, app, eip, box, ok)
}
// The ownerless route on carol replaces betty's owned alias: its lack of
// an owner is not filled in from the alias it beat.
- if _, _, _, box, ok := m.Owner("ownerless.test"); ok {
- t.Fatalf("Owner(ownerless.test) = %s, true; the losing alias's owner leaked into the winner", box)
+ if owner, ok := m.Owner("ownerless.test"); ok {
+ t.Fatalf("Owner(ownerless.test) = %s, true; the losing alias's owner leaked into the winner", owner.Box)
}
if _, box, _ := m.Home("ownerless.test"); box != "carol" {
t.Fatalf("Home(ownerless.test) = %s, want carol", box)