edge: one selection entry point for path routes across boxes (#186)
selectUpstream (now in pathselect.go) is the only function that chooses a request's upstream. Pinned branch first and unchanged; then pathMatch, today's lookupUpstreamPath over one map plus the same-box guard (never an attached alias, never a route in another account than the front's); then selectAcross for case 2 (front here, target on another box) and case 3 (front not served here, its remote map). Cross-box fronts and targets are judged by PathFront/PathTarget against the home map's exact rows, every account the claim's. Door callers never cross; a door hop never reads the remote map; on a verified hop a remote answer becomes the front's entry or nothing. Refusals log throttled under "path-skip <name>". exactPathRoute answers nothing before the home map's first hosts read. The five callers read the selection through sameBox, today's answer, until ServeHTTP dispatches remote and case 3 targets. The structural guard pins pathMatch, selectAcross, its two case helpers and the routeTable.remote readers. Two fixtures that path-routed across accounts now use one account; ServeHTTP's code-health record is lowered.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+1,213
−206
.amadan/code-health.tsv+1 −1internal/edge/demo.go+2 −10internal/edge/edge.go+21 −174internal/edge/linkpin_test.go+82 −13internal/edge/pagecache.go+1 −2internal/edge/pathroute_home.go+8 −2internal/edge/pathselect.go+396 −0internal/edge/pathselect_test.go+691 −0internal/edge/purge_path_test.go+6 −1internal/edge/regional.go+1 −1internal/edge/tunnel_login_test.go+4 −2
CI failed — run details
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv| index c559e6c4c..f864db29b 100644 |
| --- a/.amadan/code-health.tsv |
| +++ b/.amadan/code-health.tsv |
| @@ -2186,7 +2186,7 @@ func-lines internal/console (*Store).migrate - 335 |
| func-lines internal/console TestDemoProtectionsSourceToLimitAndTakedown - 412 |
| func-lines internal/console TestDemoSourceToLiveAndUpdate - 383 |
| func-lines internal/console TestHAP2ProductionDoors - 304 |
| -func-lines internal/edge (*Edge).ServeHTTP - 421 |
| +func-lines internal/edge (*Edge).ServeHTTP - 417 |
| func-lines internal/edge TestDemoAPIAliasBoundary - 360 |
| func-lines internal/edge TestRegionalNameNeverLeavesItsRegion - 330 |
| func-lines internal/edge TestTunnelWebSocketEndToEnd - 327 |
diff --git a/internal/edge/demo.go b/internal/edge/demo.go| index 9c368b667..b853d95e0 100644 |
| --- a/internal/edge/demo.go |
| +++ b/internal/edge/demo.go |
| @@ -91,11 +91,7 @@ func (e *Edge) redirectDemoRequest(w http.ResponseWriter, r *http.Request) bool |
| if valid && e.demoMovedPage(w, r, host) { |
| return true |
| } |
| - sel, ok := e.selectUpstream(r, host, r.URL.Path) |
| - var up upstream |
| - if ok { |
| - up = *sel |
| - } |
| + up, ok := e.selectUpstream(r, host, r.URL.Path).sameBox() |
| if !valid || !ok || !up.route.IsDemo() || !e.demoRouteOK(host, up.route) || up.alias || up.platformAlias || !e.demo.EdgeProtections || !e.demoTrafficAllowed(up.route) { |
| return e.refuseDemoRequest(w, r) |
| } |
| @@ -117,11 +113,7 @@ func (e *Edge) handleDemoRequest(w http.ResponseWriter, r *http.Request, serve b |
| if names := e.demoNames.Load(); names != nil { |
| marked = (*names)[host] |
| } |
| - sel, ok := e.selectUpstream(r, host, r.URL.Path) |
| - var up upstream |
| - if ok { |
| - up = *sel |
| - } |
| + up, ok := e.selectUpstream(r, host, r.URL.Path).sameBox() |
| if !e.demoReserved(host) && !marked && !(ok && up.route.IsDemo()) { |
| return false |
| } |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 90a45009b..8a7b9e044 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -603,13 +603,17 @@ type upstream struct { |
| // route that serves it, resolved against the same live map at request |
| // time. Nil for every host that does not use prefix routing, which is |
| // every host on the platform until a claim publishes a map — the nil |
| - // check in lookupUpstreamPath is the entire cost this feature imposes on |
| + // check in pathMatch is the entire cost this feature imposes on |
| // everyone else. |
| // |
| // Hostnames rather than resolved upstreams, deliberately: an upstream |
| // captured here would be a stale copy of the target's entry the moment |
| // the target's route changed within the same map build. |
| paths map[string]string |
| + // front, on a case 3 path target only (selectAcross: a front this box |
| + // does not serve), names the front route it was checked against. Never |
| + // set in the map; nil on every other selection. |
| + front *frontMark |
| // refusedUnder, on a one-label catch-all entry ("*.<parent>") only, names |
| // the hosts directly under parent that Reload refused (refusedHosts): |
| // lookupIn never resolves one of them through this catch-all. Nil on |
| @@ -1810,7 +1814,7 @@ func (e *Edge) deploymentHost(host string) bool { |
| // lookupIn resolves host to its upstream entry within a given map — the |
| // HOST half of the request-routing lookup (NOT Allowed's autocert HostPolicy |
| // — see the comment there). ServeHTTP does not call it directly: it calls |
| -// lookupUpstreamPath, which wraps this and then resolves a leading path |
| +// selectUpstream, whose pathMatch wraps this and then resolves a leading path |
| // segment for the hostnames that carry a prefix map. An exact match (a real route, or a plain #151 |
| // alias landed in the same map) always wins; on a miss, a one-label wildcard |
| // key folds in: "*.<parent>" is the shape Task 3's reconcile pass derives |
| @@ -1883,153 +1887,14 @@ func (e *Edge) lookupUpstream(host string) (upstream, bool) { |
| return e.lookupDemoAware(e.current(), host) |
| } |
| -// lookupUpstreamPath resolves a request: the hostname exactly as |
| -// lookupUpstream does, then — only for a hostname carrying a prefix map — the |
| -// first path segment. |
| -// |
| -// Both lookups read ONE snapshot of the map. Calling lookupUpstream and then |
| -// current() again would let a reload land between them and resolve a prefix |
| -// against a different table than the host came from. |
| -// |
| -// Every miss falls through to the hostname's own route rather than failing: |
| -// an unlisted prefix, a dangling target, a request for "/". A prefix map is a |
| -// migration in progress, and the un-migrated answer is always the safe one. |
| -// |
| -// ATTRIBUTION: a path hit returns the TARGET's upstream entry wholesale, so |
| -// everything downstream that reads up.route reads the target's row, not the |
| -// requested hostname's. Four consequences, named here because this is where a |
| -// reader will look for them: |
| -// |
| -// 1. Usage metering bills the TARGET's route, account and app (the |
| -// UsageMeter wrap in ServeHTTP keys on up.route.Host). Correct: the |
| -// target's backend did the work and burned the bytes. Pinned by |
| -// TestPathRoutedRequestMetersAgainstTheTarget — a later "fix" that |
| -// attributes to the requested hostname would double-count nothing and |
| -// bill the wrong app. |
| -// 2. The X-Carlos-Version response header reports the TARGET's release. |
| -// Correct: it names the code that produced the response. |
| -// 3. Purge tenancy is the TARGET's app and account (purgeModifier is built |
| -// from up.route), while the response CACHE keys on the REQUESTED host. |
| -// Those two disagree, and closing that is what the path-routing branch |
| -// in purgeHostInTenancy exists for — see below. |
| -// 4. Activator keying and hibernation are the TARGET's (up.hibernating and |
| -// up.route come from the same entry), so a request for a flipped prefix |
| -// wakes the target instance, not the requested hostname's. Correct: the |
| -// target is the process that has to be awake to answer. |
| -// |
| -// How (3) is closed, and what an app must do. The cache keys on the requested |
| -// host (CacheKey{Host: host} in ServeHTTP) while purgeModifier is built from |
| -// the target's route, so a path-routed app emitting a bare Carlos-Purge still |
| -// purges under go.tito.io while its entry is stored under ti.to, and drops |
| -// nothing. The fix is the documented escape hatch: name the hostname the |
| -// request arrived on, Carlos-Purge-Host: ti.to. The override check used to |
| -// refuse that — it required the override to name a host in the SAME app, and |
| -// path routing exists precisely to cross an app boundary — and now allows it |
| -// when a prefix on the named host selects this route. Account is still |
| -// required. Aliases never hit any of this: an alias key maps to the primary's |
| -// own route, so the app comparison passes trivially. |
| -// |
| -// So an app can emit Carlos-Purge-Host set to the Host header it received, |
| -// unconditionally, from shared code. The inbound Host is preserved end to end, |
| -// so on an ordinary request that equals rt.Host and takes resolvePurgeHosts' |
| -// own-host branch; on a path-routed one it names the front hostname and takes |
| -// the path-routing branch. Nothing in the app has to know which it is. |
| +// lookupUpstreamPath resolves a hostname and path on this box alone: pathMatch's |
| +// up/ok over the current map (pathselect.go holds the matcher and its |
| +// reasoning). Never a request's selection, which is selectUpstream's |
| +// (TestSelectUpstreamIsTheOnlySite): its callers ask whether a host and path |
| +// still map where they did. |
| func (e *Edge) lookupUpstreamPath(host, urlPath string) (upstream, bool) { |
| - m := e.current() |
| - up, ok := e.lookupDemoAware(m, host) |
| - // 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 |
| - // path.Clean'd first segment and then, if that missed and the two differ, |
| - // for the raw one. When both name a prefix, the cleaned one wins. |
| - // |
| - // Neither form alone is safe, and they fail in OPPOSITE directions. The |
| - // invariant being protected is one-way: during a reversible dual-run |
| - // migration, the app an account was flipped AWAY from must never answer |
| - // for that account. Serving a not-yet-flipped account from the NEW app is |
| - // the benign direction — at worst a 404 while the migration runs. |
| - // |
| - // - RAW alone misses "//paulca/foo". Rails and most other backends |
| - // collapse that to "/paulca/foo" and serve it, so the request falls |
| - // through to the legacy app, which then answers for a flipped |
| - // account. One character, silent. |
| - // - CLEANED alone misses "/paulca/../bob", which resolves to "bob". A |
| - // backend that does NOT collapse ".." — or that routes on the first |
| - // segment with a glob like "/:account/*rest" — then serves paulca's |
| - // page from the legacy app. The same bypass, reached the other way. |
| - // |
| - // Taking a hit from either form closes both: "//paulca/foo" hits on the |
| - // cleaned form, "/paulca/../bob" hits on the raw one, and a flipped |
| - // account reaches its new app whatever the backend does with the odd |
| - // shape. The cost is that "/paulca/../bob" reaches the NEW app carrying |
| - // "/paulca/../bob", which a normalising target resolves to "/bob" and |
| - // 404s — an account it was not given. Benign direction, and deliberate. |
| - // |
| - // Residue, measured rather than assumed. None of it crosses the |
| - // invariant above, and it is written down so nobody has to re-derive it: |
| - // |
| - // - "/%2e%2e/bob": r.URL.Path is already percent-DECODED, so this |
| - // cleans to "/bob" and matches "bob". The upstream receives the raw |
| - // "/%2e%2e/bob" and will most likely 404 it. Harmless. |
| - // - "/paulca%2ffoo": decodes to "/paulca/foo", so both forms match |
| - // "paulca" and the request reaches paulca's new app — while a strict |
| - // backend treats the upstream path as the SINGLE segment |
| - // "paulca/foo". A mis-flip toward the NEW app: the safe direction. |
| - // - A prefix literally named "." or ".." cannot exist: validPathPrefix |
| - // (internal/domains/claims.go) refuses both, so the raw form of |
| - // "/../bob" ("..") can never match anything. |
| - // |
| - // Do not collapse this back to a single form. Whichever one you keep, |
| - // you reopen the bypass the other one closes. |
| - // |
| - // The scope of the guarantee, stated so it is not over-read: the two |
| - // forms model percent-decoding and dot-segment removal, and the |
| - // invariant holds across every combination of a backend doing or not |
| - // doing those two. It is NOT a claim that no normalisation exists. A |
| - // backend that folds case ("/PAULCA/foo"), strips servlet-style path |
| - // parameters ("/paulca;jsessionid=x/foo"), accepts backslash |
| - // separators, strips trailing dots, or double-decodes could resolve a |
| - // path neither form matches into a flipped account's subtree. Rails |
| - // does none of these — Rack keeps ";" in PATH_INFO and routing is |
| - // case-sensitive — so Tito is not exposed, but a future consumer with |
| - // different normalisation would need this reasoning redone rather than |
| - // inherited. |
| - // |
| - // No guard is needed for the empty segment ("/", "//", ""): validPathPrefix |
| - // refuses an empty prefix, so no row can be keyed on one and both lookups |
| - // below simply miss, falling through to the host's own route. |
| - seg := firstSegmentClean(urlPath) |
| - raw := firstSegment(urlPath) |
| - target, ok := up.paths[seg] |
| - if !ok && raw != seg { |
| - target, ok = up.paths[raw] |
| - } |
| - if !ok { |
| - return up, true |
| - } |
| - // m[target], not lookupIn(m, target): the TARGET is resolved exactly, |
| - // while the host half above also accepts a one-label wildcard key. The |
| - // asymmetry is deliberate and it is documented rather than removed — |
| - // route_paths targets are hostnames the reconcile pass verified against a |
| - // real local route (aliases.go), and a real route is always an exact key, |
| - // so a target reachable ONLY through "*.parent" cannot be produced by any |
| - // supported writer. If one ever were, it would miss here and fall through |
| - // to the host's own route, which is this function's safe direction |
| - // anyway. |
| - tu, ok := m[target] |
| - if !ok { |
| - return up, true |
| - } |
| - // ONE HOP, deliberately: if tu itself carries a prefix map, it is NOT |
| - // re-resolved against this request's path. A prefix selects a route, and |
| - // the selected route's own map belongs to ITS hostname's traffic, not to |
| - // this one's. Do not add recursion here — chaining buys nothing the |
| - // publisher cannot express by pointing the prefix at the final target |
| - // directly, and it would introduce a cycle to detect. |
| - return tu, true |
| + up, ok, _, _, _ := e.pathMatch(e.current(), host, urlPath) |
| + return up, ok |
| } |
| // LinkedTarget is what a home deployment's link handler (internal/host, |
| @@ -2134,22 +1999,6 @@ func linkVisitor(h http.Header) (visitor, chain string, ok bool) { |
| return ips[len(ips)-1], strings.Join(ips, ", "), true |
| } |
| -// selectUpstream is where a request's upstream is chosen: the only |
| -// request-path caller of lookupUpstream and lookupUpstreamPath |
| -// (TestSelectUpstreamIsTheOnlySite). Without a link pin it is |
| -// lookupUpstreamPath(host, path). With one, host and path are not read: |
| -// the answer is the pinned upstream (pinnedUpstream) or nothing. |
| -func (e *Edge) selectUpstream(r *http.Request, host, path string) (*upstream, bool) { |
| - if want, pinned := linkPinFrom(r.Context()); pinned { |
| - return e.pinnedUpstream(want) |
| - } |
| - up, ok := e.lookupUpstreamPath(host, path) |
| - if !ok { |
| - return nil, false |
| - } |
| - return &up, true |
| -} |
| - |
| // pinnedUpstream is a linked request's upstream: the exact entry for |
| // want.Host, admitted only while its own route is that host's row (no |
| // alias, platform alias or regional entry, which carry another row) for |
| @@ -2208,8 +2057,8 @@ func serveLinkNotHere(w http.ResponseWriter, r *http.Request) { |
| // equal to "paulca", so a longer account name can never be dragged across a |
| // migration by a shorter one. |
| // |
| -// This is the RAW half of the matcher. See lookupUpstreamPath's match block |
| -// for why both halves exist and why neither is safe alone. |
| +// This is the RAW half of the matcher. See matchPrefix (pathselect.go) for |
| +// why both halves exist and why neither is safe alone. |
| func firstSegment(p string) string { |
| if p == "" || p[0] != '/' { |
| return "" |
| @@ -2465,11 +2314,9 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| if !pinned && e.serveDemoAPIAlias(w, r, host, hopped && demoHopWellFormed, demoHopPresent) { |
| return |
| } |
| - sel, ok := e.selectUpstream(r, host, r.URL.Path) |
| - var up upstream |
| - if ok { |
| - up = *sel |
| - } |
| + // sameBox: a target on another box, or a target for a front not served |
| + // here, still answers as before #186 until this dispatches them. |
| + up, ok := e.selectUpstream(r, host, r.URL.Path).sameBox() |
| // A pin that selects nothing here is answered here: never the backhaul, |
| // the far asset catch or the unknown-host fallback below. |
| if pinned && !ok { |
| @@ -2669,7 +2516,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // A login POST re-resolves its upstream by the path in `next`, not by |
| // its own (spec §4.2). On a hostname that routes by path prefix, |
| - // lookupUpstreamPath keys on the first segment; "/.carlos/gate" has no |
| + // selection keys on the first segment; "/.carlos/gate" has no |
| // segment that can ever be a prefix, so a login POST falls through to |
| // the FRONT host's route — the password would be judged by the wrong |
| // row (or proxied to an app that never asked for it, which the |
| @@ -2769,8 +2616,8 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| if u, err := url.ParseRequestURI(next); err == nil && u.Path != "" { |
| lookupPath = u.Path |
| } |
| - if target, hit := e.selectUpstream(r, host, lookupPath); hit { |
| - up = *target |
| + if target, hit := e.selectUpstream(r, host, lookupPath).sameBox(); hit { |
| + up = target |
| if e.admissionRefuses(w, r, up.route) { |
| return |
| } |
diff --git a/internal/edge/linkpin_test.go b/internal/edge/linkpin_test.go| index 43f661fe7..7dafdc3e9 100644 |
| --- a/internal/edge/linkpin_test.go |
| +++ b/internal/edge/linkpin_test.go |
| @@ -26,8 +26,9 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| -// The functions besides selectUpstream allowed to call lookupUpstream or |
| -// lookupUpstreamPath, and why none of them selects where a request goes. |
| +// The functions allowed to call lookupUpstream or lookupUpstreamPath, and |
| +// why none of them selects where a request goes. selectUpstream calls |
| +// neither: it selects through pathMatch (selectionEntrySites). |
| var lookupNonRequestSites = map[string]string{ |
| "httpFallbackHandler": "the :80 listener asks only whether this box serves a hostname before redirecting it to https; it never dispatches", |
| "demoTrafficAllowed": "re-reads the row of a demo route already selected, by that route's own host", |
| @@ -35,6 +36,25 @@ var lookupNonRequestSites = map[string]string{ |
| "sweepUpgrades": "the reload sweep that closes tunnel upgrades whose host no longer maps to their tenancy", |
| } |
| +// The selection functions (pathselect.go, path routes across boxes #186) |
| +// and the only functions that may call each. Exact: a caller missing here |
| +// fails, and so does an entry that no longer calls. |
| +var selectionEntrySites = map[string]map[string]string{ |
| + "pathMatch": { |
| + "selectUpstream": "THE selection: the pinned branch first, then pathMatch on the local map", |
| + "lookupUpstreamPath": "the compatibility wrapper, pathMatch's up/ok; its own callers are restricted to lookupNonRequestSites", |
| + }, |
| + "selectAcross": { |
| + "selectUpstream": "cases 2 and 3 run only inside the one selection, after the pinned branch and pathMatch, where the arrived-hop rule is settled", |
| + }, |
| + "selectFromServedFront": { |
| + "selectAcross": "case 2, after the door check and pathMatch's same-box refusal", |
| + }, |
| + "selectForUnservedFront": { |
| + "selectAcross": "case 3, after the door and door-hop checks, with the remote map selectAcross read", |
| + }, |
| +} |
| + |
| // The other ways to read the routing map by host, and where each may be |
| // used. None of them is a request's upstream selection: a pinned request's |
| // upstream comes only from selectUpstream. |
| @@ -42,7 +62,7 @@ var mapReadSites = map[string]map[string]string{ |
| // lookupIn(m, host): the host half of the lookup, wildcard fallback |
| // included. |
| "lookupIn": { |
| - "lookupDemoAware": "the lookup primitive itself, under lookupUpstream and lookupUpstreamPath", |
| + "lookupDemoAware": "the lookup primitive itself, under lookupUpstream and pathMatch", |
| "importGateAdmit": "reads the request host's own row only to refuse an import-gated front host; it can only refuse, never pick an upstream", |
| "instanceHostsIn": "the page cache's purge expansion over hosts an app's response named; a linked request never records a page", |
| "pageRouteEligible": "the page cache's eligibility of the upstream already selected; never reached by a linked request", |
| @@ -52,8 +72,8 @@ var mapReadSites = map[string]map[string]string{ |
| }, |
| // lookupDemoAware(m, host): the demo zone's exact-only lookup. |
| "lookupDemoAware": { |
| - "lookupUpstream": "the lookup primitive", |
| - "lookupUpstreamPath": "the lookup primitive", |
| + "lookupUpstream": "the lookup primitive", |
| + "pathMatch": "the host half of the selection's local match, so the demo namespace rules hold for every request", |
| }, |
| // e.current()[host]: the exact map entry. |
| "current()[]": { |
| @@ -62,16 +82,28 @@ var mapReadSites = map[string]map[string]string{ |
| "pinnedUpstream": "the pin's own exact entry, reached only from selectUpstream", |
| "takeHost": "the HA take control path, an edge-owned handler a linked request never reaches", |
| }, |
| + // routeTable.remote: the remote path map (pathremote.go), read or set. |
| + // The purge owner check for a front this box does not serve |
| + // (purgeOwnsIn, resolvePurgeOwnersIn) joins when it reads the map. |
| + "routeTable.remote": { |
| + "selectAcross": "case 3 of the one selection, reached only from selectUpstream", |
| + "Reload": "the one publisher of the table (TestReloadIsTheOnlyPublisher) sets it beside hosts", |
| + }, |
| } |
| +// TestSelectUpstreamIsTheOnlySite: selectUpstream is the one function that |
| +// chooses a request's upstream. The scan pins who calls each lookup and |
| +// selection function and who reads the routing map by host or its remote |
| +// map, against the exact lists above. |
| func TestSelectUpstreamIsTheOnlySite(t *testing.T) { |
| files, err := filepath.Glob("*.go") |
| if err != nil { |
| t.Fatal(err) |
| } |
| fset := token.NewFileSet() |
| - callers := map[string][]string{} // enclosing function -> positions |
| - reads := map[string]map[string][]string{} // kind -> enclosing function -> positions |
| + callers := map[string][]string{} // enclosing function -> positions |
| + entries := map[string]map[string][]string{} // selection function -> enclosing function -> positions |
| + reads := map[string]map[string][]string{} // kind -> enclosing function -> positions |
| note := func(kind, fn string, pos token.Pos) { |
| if reads[kind] == nil { |
| reads[kind] = map[string][]string{} |
| @@ -100,6 +132,20 @@ func TestSelectUpstreamIsTheOnlySite(t *testing.T) { |
| switch x := n.(type) { |
| case *ast.SelectorExpr: |
| ident = x.Sel |
| + if x.Sel.Name == "remote" { |
| + note("routeTable.remote", fn.Name.Name, x.Pos()) |
| + } |
| + case *ast.CompositeLit: |
| + if typ, ok := x.Type.(*ast.Ident); ok && typ.Name == "routeTable" { |
| + for _, elt := range x.Elts { |
| + if kv, ok := elt.(*ast.KeyValueExpr); ok { |
| + if key, ok := kv.Key.(*ast.Ident); ok && key.Name == "remote" { |
| + note("routeTable.remote", fn.Name.Name, kv.Pos()) |
| + } |
| + } |
| + } |
| + } |
| + return true |
| case *ast.Ident: |
| ident = x |
| case *ast.IndexExpr: |
| @@ -117,6 +163,10 @@ func TestSelectUpstreamIsTheOnlySite(t *testing.T) { |
| callers[fn.Name.Name] = append(callers[fn.Name.Name], fset.Position(ident.Pos()).String()) |
| case "lookupIn", "lookupDemoAware": |
| note(ident.Name, fn.Name.Name, ident.Pos()) |
| + case "pathMatch", "selectAcross", "selectFromServedFront", "selectForUnservedFront": |
| + if ident == n { |
| + entries[ident.Name] = appendSite(entries[ident.Name], fn.Name.Name, fset.Position(ident.Pos()).String()) |
| + } |
| } |
| return true |
| }) |
| @@ -128,7 +178,8 @@ func TestSelectUpstreamIsTheOnlySite(t *testing.T) { |
| ast.Inspect(gd, func(n ast.Node) bool { |
| if id, ok := n.(*ast.Ident); ok { |
| switch id.Name { |
| - case "lookupUpstream", "lookupUpstreamPath", "lookupIn", "lookupDemoAware": |
| + case "lookupUpstream", "lookupUpstreamPath", "lookupIn", "lookupDemoAware", |
| + "pathMatch", "selectAcross", "selectFromServedFront", "selectForUnservedFront": |
| t.Errorf("%s: %s referenced outside a function", fset.Position(id.Pos()), id.Name) |
| } |
| } |
| @@ -137,8 +188,8 @@ func TestSelectUpstreamIsTheOnlySite(t *testing.T) { |
| } |
| } |
| } |
| - if len(callers["selectUpstream"]) == 0 { |
| - t.Fatal("selectUpstream does not call lookupUpstreamPath: the scan has nothing to anchor on") |
| + if len(entries["pathMatch"]["selectUpstream"]) == 0 { |
| + t.Fatal("selectUpstream does not call pathMatch: the scan has nothing to anchor on") |
| } |
| var names []string |
| for fn := range callers { |
| @@ -146,9 +197,6 @@ func TestSelectUpstreamIsTheOnlySite(t *testing.T) { |
| } |
| sort.Strings(names) |
| for _, fn := range names { |
| - if fn == "selectUpstream" { |
| - continue |
| - } |
| if _, ok := lookupNonRequestSites[fn]; !ok { |
| t.Errorf("%s calls lookupUpstream/lookupUpstreamPath at %v: a request must select its upstream through selectUpstream, so a link pin is honoured", fn, callers[fn]) |
| } |
| @@ -158,6 +206,18 @@ func TestSelectUpstreamIsTheOnlySite(t *testing.T) { |
| t.Errorf("lookupNonRequestSites lists %s, which no longer calls a lookup: drop it", fn) |
| } |
| } |
| + for name, allowed := range selectionEntrySites { |
| + for fn, at := range entries[name] { |
| + if _, ok := allowed[fn]; !ok { |
| + t.Errorf("%s calls %s at %v: a request's upstream is chosen only by selectUpstream", fn, name, at) |
| + } |
| + } |
| + for fn := range allowed { |
| + if len(entries[name][fn]) == 0 { |
| + t.Errorf("selectionEntrySites[%s] lists %s, which no longer calls it: drop it", name, fn) |
| + } |
| + } |
| + } |
| for kind, allowed := range mapReadSites { |
| for fn, at := range reads[kind] { |
| if _, ok := allowed[fn]; !ok { |
| @@ -172,6 +232,15 @@ func TestSelectUpstreamIsTheOnlySite(t *testing.T) { |
| } |
| } |
| +// appendSite records one position of a call made from fn. |
| +func appendSite(m map[string][]string, fn, at string) map[string][]string { |
| + if m == nil { |
| + m = map[string][]string{} |
| + } |
| + m[fn] = append(m[fn], at) |
| + return m |
| +} |
| + |
| // linkedGet serves GET path on e as a link channel would deliver it, pinned |
| // to want. |
| func linkedGet(e *Edge, want LinkedTarget, path string) *httptest.ResponseRecorder { |
diff --git a/internal/edge/pagecache.go b/internal/edge/pagecache.go| index 1188a61ea..639157aa0 100644 |
| --- a/internal/edge/pagecache.go |
| +++ b/internal/edge/pagecache.go |
| @@ -530,11 +530,10 @@ func (ps *pageServe) end() { |
| // or the row while the response was written is seen. |
| func (ps *pageServe) stillCurrent() bool { |
| e := ps.e |
| - sel, ok := e.selectUpstream(ps.r, ps.host, ps.r.URL.Path) |
| + cur, ok := e.selectUpstream(ps.r, ps.host, ps.r.URL.Path).sameBox() |
| if !ok { |
| return false |
| } |
| - cur := *sel |
| if cur.route.Host != ps.up.route.Host || pageScopeOf(cur) != ps.scope { |
| return false |
| } |
diff --git a/internal/edge/pathroute_home.go b/internal/edge/pathroute_home.go| index eb906f770..f0c3eae26 100644 |
| --- a/internal/edge/pathroute_home.go |
| +++ b/internal/edge/pathroute_home.go |
| @@ -25,12 +25,18 @@ type pathRouteInfo struct { |
| // exactPathRoute answers the exact (never wildcard) dialable route row another |
| // box published for host, from one snapshot. false when absent, held, an alias |
| -// or "*." row, or published without route_account. |
| +// or "*." row, or published without route_account, and before the map has |
| +// completed a hosts read (AssetsFor's rule: the empty snapshot a restart |
| +// starts from is not an answer), so no cross-box selection is made from it. |
| func (m *homeMap) exactPathRoute(host string) (pathRouteInfo, bool) { |
| if m == nil || m.self == "" || strings.HasPrefix(host, "*.") { |
| return pathRouteInfo{}, false |
| } |
| - hosts := m.snapshot().hosts |
| + snap := m.snapshot() |
| + if !snap.read { |
| + return pathRouteInfo{}, false |
| + } |
| + hosts := snap.hosts |
| r := resolveHomeName(host, nil, true, hosts) |
| if r.State != edgesfile.NameDialable || r.Authority.Class != edgesfile.NameRoute || r.Serving.Name != host { |
| return pathRouteInfo{}, false |
diff --git a/internal/edge/pathselect.go b/internal/edge/pathselect.go| new file mode 100644 |
| index 000000000..a0e930b48 |
| --- /dev/null |
| +++ b/internal/edge/pathselect.go |
| @@ -0,0 +1,396 @@ |
| +package edge |
| + |
| +// Path routes across boxes (#186, spec §5.3): the one selection entry point. |
| +// selectUpstream is the only function that chooses a request's upstream |
| +// (TestSelectUpstreamIsTheOnlySite). It runs, in order: |
| +// |
| +// - the link pin, when there is one: the pinned entry or nothing; |
| +// - case 1, pathMatch: the host and its prefix map on this box, today's |
| +// answer with one tenancy guard on the target; |
| +// - cases 2 and 3, selectAcross: a prefix whose target route is on another |
| +// box (the front here), and a front this box does not serve whose prefix |
| +// names a target here or elsewhere. |
| +// |
| +// Two eligibility rules, never mixed. Same-box (case 1) keeps every route |
| +// kind and platform-alias targets, refusing only an attached alias or a |
| +// target in another account. Across boxes (cases 2 and 3) the front must be |
| +// a route's own exact name satisfying registry.PathFront and the target a |
| +// route satisfying registry.PathTarget, both judged against the home map's |
| +// exact rows, and every account must be the claim's. |
| + |
| +import ( |
| + "fmt" |
| + "net/http" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// frontMark names the front route a case 3 target was checked against: a |
| +// front this box does not serve, as the home map's exact row published it. |
| +// Set on the selected upstream only then (upstream.front). |
| +type frontMark struct { |
| + Host, Account, App string |
| + Stamp int64 |
| + Incarnation uint64 |
| +} |
| + |
| +// remoteTarget is a selection that belongs to a route on another box. |
| +type remoteTarget struct { |
| + Target string // the target route's host |
| + Route pathRouteInfo // its published row: Dial, Box, Owner |
| +} |
| + |
| +// requestSelection is everything a request's dispatch reads from selection. |
| +type requestSelection struct { |
| + Up upstream // dispatch this through the normal stages when OK |
| + OK bool |
| + Remote *remoteTarget // non-nil: hop to the target instead; Up/OK then hold nothing |
| + Prefix string // the matched prefix, whenever one matched |
| + Target string // the matched target host, whenever one matched |
| + // LocalTarget: Up is the matched target's own entry, served here (case 1 |
| + // or case 3). The ONLY signal downstream consumers (HA identity, login) |
| + // use for "a target was selected"; never compare Target with Up.route.Host, |
| + // which differ for a platform-alias target. |
| + LocalTarget bool |
| + |
| + // sameBoxUp/sameBoxOK are pathMatch's own answer on the same snapshot |
| + // (lookupUpstreamPath's): the front's entry, or nothing when the front |
| + // is not served here. sameBox reads them. |
| + sameBoxUp upstream |
| + sameBoxOK bool |
| +} |
| + |
| +// sameBox is the selection for a caller that never dispatches across boxes: |
| +// Up/OK, except that a Remote selection or a case 3 target (a front this box |
| +// does not serve, Up.front set) answers the front's own entry as before |
| +// path routes crossed boxes: its route when served here, else nothing. |
| +func (s requestSelection) sameBox() (upstream, bool) { |
| + if s.Remote != nil || s.Up.front != nil { |
| + return s.sameBoxUp, s.sameBoxOK |
| + } |
| + return s.Up, s.OK |
| +} |
| + |
| +// selectUpstream is THE selection: pinned branch first and unchanged; then |
| +// pathMatch on the local map; then selectAcross for cases 2 and 3. The |
| +// arrived-hop rule is settled here: on a verified hop a remote answer never |
| +// leaves Remote set; it becomes the front's own entry when this box serves the |
| +// front (spec §5.4), else OK=false (the caller's existing stale-hop refusal). |
| +// |
| +// With a link pin, host and urlPath are not read: the answer is the pinned |
| +// upstream (pinnedUpstream) or nothing, with no prefix and no remote. |
| +func (e *Edge) selectUpstream(r *http.Request, host, urlPath string) requestSelection { |
| + ctx := r.Context() |
| + if want, pinned := linkPinFrom(ctx); pinned { |
| + up, ok := e.pinnedUpstream(want) |
| + if !ok { |
| + return requestSelection{} |
| + } |
| + return requestSelection{Up: *up, OK: true, sameBoxUp: *up, sameBoxOK: true} |
| + } |
| + t := e.table() |
| + if t == nil { |
| + return requestSelection{} |
| + } |
| + up, ok, prefix, target, local := e.pathMatch(t.hosts, host, urlPath) |
| + if local { |
| + return requestSelection{Up: up, OK: true, Prefix: prefix, Target: target, LocalTarget: true, sameBoxUp: up, sameBoxOK: true} |
| + } |
| + _, door := doorCallerFrom(ctx) |
| + sel := e.selectAcross(t, host, urlPath, up, ok, prefix, target, door, hopDoorFrom(ctx)) |
| + sel.sameBoxUp, sel.sameBoxOK = up, ok |
| + if sel.Remote != nil && hopVerified(ctx) { |
| + // One hop, ever: the front's own entry when served here (pathMatch |
| + // answered it), else nothing. |
| + sel.Remote = nil |
| + sel.Up, sel.OK = up, ok |
| + } |
| + return sel |
| +} |
| + |
| +// matchPrefix is the 09-02 matcher: cleaned first segment, then raw; cleaned wins. |
| +// |
| +// BOTH FORMS, cleaned first. The prefix map is consulted for the |
| +// path.Clean'd first segment and then, if that missed and the two differ, |
| +// for the raw one. When both name a prefix, the cleaned one wins. |
| +// |
| +// Neither form alone is safe, and they fail in OPPOSITE directions. The |
| +// invariant being protected is one-way: during a reversible dual-run |
| +// migration, the app an account was flipped AWAY from must never answer |
| +// for that account. Serving a not-yet-flipped account from the NEW app is |
| +// the benign direction — at worst a 404 while the migration runs. |
| +// |
| +// - RAW alone misses "//paulca/foo". Rails and most other backends |
| +// collapse that to "/paulca/foo" and serve it, so the request falls |
| +// through to the legacy app, which then answers for a flipped |
| +// account. One character, silent. |
| +// - CLEANED alone misses "/paulca/../bob", which resolves to "bob". A |
| +// backend that does NOT collapse ".." — or that routes on the first |
| +// segment with a glob like "/:account/*rest" — then serves paulca's |
| +// page from the legacy app. The same bypass, reached the other way. |
| +// |
| +// Taking a hit from either form closes both: "//paulca/foo" hits on the |
| +// cleaned form, "/paulca/../bob" hits on the raw one, and a flipped |
| +// account reaches its new app whatever the backend does with the odd |
| +// shape. The cost is that "/paulca/../bob" reaches the NEW app carrying |
| +// "/paulca/../bob", which a normalising target resolves to "/bob" and |
| +// 404s — an account it was not given. Benign direction, and deliberate. |
| +// |
| +// Residue, measured rather than assumed. None of it crosses the |
| +// invariant above, and it is written down so nobody has to re-derive it: |
| +// |
| +// - "/%2e%2e/bob": r.URL.Path is already percent-DECODED, so this |
| +// cleans to "/bob" and matches "bob". The upstream receives the raw |
| +// "/%2e%2e/bob" and will most likely 404 it. Harmless. |
| +// - "/paulca%2ffoo": decodes to "/paulca/foo", so both forms match |
| +// "paulca" and the request reaches paulca's new app — while a strict |
| +// backend treats the upstream path as the SINGLE segment |
| +// "paulca/foo". A mis-flip toward the NEW app: the safe direction. |
| +// - A prefix literally named "." or ".." cannot exist: validPathPrefix |
| +// (internal/domains/claims.go) refuses both, so the raw form of |
| +// "/../bob" ("..") can never match anything. |
| +// |
| +// Do not collapse this back to a single form. Whichever one you keep, |
| +// you reopen the bypass the other one closes. |
| +// |
| +// The scope of the guarantee, stated so it is not over-read: the two |
| +// forms model percent-decoding and dot-segment removal, and the |
| +// invariant holds across every combination of a backend doing or not |
| +// doing those two. It is NOT a claim that no normalisation exists. A |
| +// backend that folds case ("/PAULCA/foo"), strips servlet-style path |
| +// parameters ("/paulca;jsessionid=x/foo"), accepts backslash |
| +// separators, strips trailing dots, or double-decodes could resolve a |
| +// path neither form matches into a flipped account's subtree. Rails |
| +// does none of these — Rack keeps ";" in PATH_INFO and routing is |
| +// case-sensitive — so Tito is not exposed, but a future consumer with |
| +// different normalisation would need this reasoning redone rather than |
| +// inherited. |
| +// |
| +// No guard is needed for the empty segment ("/", "//", ""): validPathPrefix |
| +// refuses an empty prefix, so no row can be keyed on one and both lookups |
| +// below simply miss, falling through to the host's own route. |
| +// |
| +// One implementation, shared by the local map (pathMatch) and the remote |
| +// map (selectAcross, case 3), so the box a request arrives on selects as the |
| +// front's home box does. |
| +func matchPrefix(prefixes map[string]string, urlPath string) (prefix, target string, ok bool) { |
| + seg := firstSegmentClean(urlPath) |
| + if target, ok := prefixes[seg]; ok { |
| + return seg, target, true |
| + } |
| + if raw := firstSegment(urlPath); raw != seg { |
| + if target, ok := prefixes[raw]; ok { |
| + return raw, target, true |
| + } |
| + } |
| + return "", "", false |
| +} |
| + |
| +// pathMatch is today's lookupUpstreamPath over one map, plus case 1's guard, |
| +// reporting what it matched: up/ok are exactly what lookupUpstreamPath returns |
| +// (the target's entry on a valid local hit, else the front's), prefix/target |
| +// are set whenever a prefix matched, local says the TARGET's entry was answered |
| +// (true for a platform-alias target too, whose route.Host is its instance's). |
| +// A method: the host half is e.lookupDemoAware, exactly as today, so demo |
| +// namespace rules hold (demo_test.go's reserved-apex witness stays green). |
| +// |
| +// The hostname resolves exactly as lookupUpstream does, then — only for a |
| +// hostname carrying a prefix map — the first path segment. Both lookups read |
| +// m, ONE snapshot: a reload landing between them cannot resolve a prefix |
| +// against a different table than the host came from. |
| +// |
| +// Every miss falls through to the hostname's own route rather than failing: |
| +// an unlisted prefix, a target not on this box, a refused target, a request |
| +// for "/". A prefix map is a migration in progress, and the un-migrated |
| +// answer is always the safe one. |
| +// |
| +// ATTRIBUTION: a path hit returns the TARGET's upstream entry wholesale, so |
| +// everything downstream that reads up.route reads the target's row, not the |
| +// requested hostname's. Four consequences, named here because this is where a |
| +// reader will look for them: |
| +// |
| +// 1. Usage metering bills the TARGET's route, account and app (the |
| +// UsageMeter wrap in ServeHTTP keys on up.route.Host). Correct: the |
| +// target's backend did the work and burned the bytes. Pinned by |
| +// TestPathRoutedRequestMetersAgainstTheTarget — a later "fix" that |
| +// attributes to the requested hostname would double-count nothing and |
| +// bill the wrong app. |
| +// 2. The X-Carlos-Version response header reports the TARGET's release. |
| +// Correct: it names the code that produced the response. |
| +// 3. Purge tenancy is the TARGET's app and account (purgeModifier is built |
| +// from up.route), while the response CACHE keys on the REQUESTED host. |
| +// Those two disagree, and closing that is what the path-routing branch |
| +// in purgeHostInTenancy exists for — see below. |
| +// 4. Activator keying and hibernation are the TARGET's (up.hibernating and |
| +// up.route come from the same entry), so a request for a flipped prefix |
| +// wakes the target instance, not the requested hostname's. Correct: the |
| +// target is the process that has to be awake to answer. |
| +// |
| +// How (3) is closed, and what an app must do. The cache keys on the requested |
| +// host (CacheKey{Host: host} in ServeHTTP) while purgeModifier is built from |
| +// the target's route, so a path-routed app emitting a bare Carlos-Purge still |
| +// purges under go.tito.io while its entry is stored under ti.to, and drops |
| +// nothing. The fix is the documented escape hatch: name the hostname the |
| +// request arrived on, Carlos-Purge-Host: ti.to. The override check used to |
| +// refuse that — it required the override to name a host in the SAME app, and |
| +// path routing exists precisely to cross an app boundary — and now allows it |
| +// when a prefix on the named host selects this route. Account is still |
| +// required. Aliases never hit any of this: an alias key maps to the primary's |
| +// own route, so the app comparison passes trivially. |
| +// |
| +// So an app can emit Carlos-Purge-Host set to the Host header it received, |
| +// unconditionally, from shared code. The inbound Host is preserved end to end, |
| +// so on an ordinary request that equals rt.Host and takes resolvePurgeHosts' |
| +// own-host branch; on a path-routed one it names the front hostname and takes |
| +// the path-routing branch. Nothing in the app has to know which it is. |
| +func (e *Edge) pathMatch(m map[string]upstream, host, urlPath string) (up upstream, ok bool, prefix, target string, local bool) { |
| + up, ok = e.lookupDemoAware(m, host) |
| + // 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, "", "", false |
| + } |
| + prefix, target, hit := matchPrefix(up.paths, urlPath) |
| + if !hit { |
| + return up, true, "", "", false |
| + } |
| + // m[target], not lookupIn(m, target): the TARGET is resolved exactly, |
| + // while the host half above also accepts a one-label wildcard key. Every |
| + // box derives the rows of every path-routed host (#186), so a target is |
| + // any hostname a claim named in its own account: a route on this box, a |
| + // route on another box (case 2, selectAcross), or nothing at all. A |
| + // target missing from m is not local and falls through here to the |
| + // host's own route. A target reachable ONLY through "*.parent" misses |
| + // here too, and is never a target route on another box either |
| + // (exactPathRoute is exact): the safe direction, deliberately. |
| + tu, found := m[target] |
| + // The same-box guard, the one tenancy check case 1 adds to the 09-02 |
| + // answer: never an attached alias (whoever's route it names; a |
| + // platform alias is the instance's own entry and stays eligible), and |
| + // never a route in another account than the front's. Every route kind |
| + // stays eligible here, unlike across boxes. |
| + if !found || (tu.alias && !tu.platformAlias) || release.RouteAccount(tu.route) != release.RouteAccount(up.route) { |
| + return up, true, prefix, target, false |
| + } |
| + // ONE HOP, deliberately: if tu itself carries a prefix map, it is NOT |
| + // re-resolved against this request's path. A prefix selects a route, and |
| + // the selected route's own map belongs to ITS hostname's traffic, not to |
| + // this one's. Do not add recursion here — chaining buys nothing the |
| + // publisher cannot express by pointing the prefix at the final target |
| + // directly, and it would introduce a cycle to detect. |
| + return tu, true, prefix, target, true |
| +} |
| + |
| +// selectAcross runs cases 2 and 3 over one table; called only by selectUpstream. |
| +// front/frontOK and prefix/target are pathMatch's answer for host on |
| +// t.hosts, which did not select a local target. door: a door caller, which |
| +// never selects across boxes. doorHop: a door-marked hop, which never takes |
| +// a remote-map answer (case 3). |
| +// |
| +// Every answer that is not a cross-box selection is the front's entry (or |
| +// nothing, when the front is not served here): today's answer. |
| +func (e *Edge) selectAcross(t *routeTable, host, urlPath string, front upstream, frontOK bool, prefix, target string, door, doorHop bool) requestSelection { |
| + stay := requestSelection{Up: front, OK: frontOK, Prefix: prefix, Target: target} |
| + if door { |
| + return stay |
| + } |
| + if frontOK { |
| + if prefix == "" { |
| + return stay |
| + } |
| + if _, here := t.hosts[target]; here { |
| + // A local target pathMatch refused: same-box rules decided it. |
| + return stay |
| + } |
| + return e.selectFromServedFront(t, host, front, prefix, target, stay) |
| + } |
| + if doorHop { |
| + return stay |
| + } |
| + rm, ok := t.remote[host] |
| + if !ok { |
| + return stay |
| + } |
| + return e.selectForUnservedFront(t, host, urlPath, rm, stay) |
| +} |
| + |
| +// selectFromServedFront is case 2: the front is served here and its prefix |
| +// names a target this box does not hold. Remote only when the front is a |
| +// route's own exact name satisfying PathFront and the home map's exact row |
| +// for the target satisfies PathTarget in the front route's account. |
| +func (e *Edge) selectFromServedFront(t *routeTable, host string, front upstream, prefix, target string, stay requestSelection) requestSelection { |
| + if _, exact := t.hosts[host]; !exact || front.alias || front.platformAlias || front.regional != regionalNone || |
| + front.route.Host != host || !registry.PathFront(front.route) { |
| + e.pathSkip(servedName(t, host), fmt.Sprintf("prefix %q names %s, which is not on this box, and only a route's own exact name (an instance or static route) sends a prefix to another box; the host's own route answers", |
| + prefix, target)) |
| + return stay |
| + } |
| + account := release.RouteAccount(front.route) |
| + info, ok := e.homes.Load().exactPathRoute(target) |
| + switch { |
| + case !ok || !info.Target: |
| + e.pathSkip(host, fmt.Sprintf("prefix %q names %s, which is not a ready instance or static route on any box; the host's own route answers", prefix, target)) |
| + return stay |
| + case info.Account != account: |
| + e.pathSkip(host, fmt.Sprintf("prefix %q names %s, a route of account %s, not %s; the host's own route answers", prefix, target, info.Account, account)) |
| + return stay |
| + } |
| + return requestSelection{Remote: &remoteTarget{Target: target, Route: info}, Prefix: prefix, Target: target} |
| +} |
| + |
| +// selectForUnservedFront is case 3: this box does not serve host, and holds |
| +// its remote map. The home map's exact row for host must be a front route of |
| +// the map's own account and app; otherwise the map is ignored. A prefix |
| +// miss, and every refusal, answer nothing (the backhaul to the host's home, |
| +// as today). |
| +func (e *Edge) selectForUnservedFront(t *routeTable, host, urlPath string, rm remotePathMap, stay requestSelection) requestSelection { |
| + homes := e.homes.Load() |
| + fi, ok := homes.exactPathRoute(host) |
| + if !ok || !fi.Front || fi.Account != rm.account || fi.App != rm.app { |
| + e.pathSkip(host, fmt.Sprintf("no box publishes it as a front route of %s/%s, so its prefixes are not routed from this box", rm.account, rm.app)) |
| + return stay |
| + } |
| + prefix, target, hit := matchPrefix(rm.prefixes, urlPath) |
| + if !hit { |
| + return stay |
| + } |
| + stay.Prefix, stay.Target = prefix, target |
| + if tu, here := t.hosts[target]; here { |
| + if tu.alias || tu.platformAlias || tu.regional != regionalNone || tu.route.Host != target || |
| + !registry.PathTarget(tu.route) || release.RouteAccount(tu.route) != rm.account { |
| + e.pathSkip(host, fmt.Sprintf("prefix %q names %s, which this box serves but not as a ready instance or static route of account %s; sent to the host's home", prefix, target, rm.account)) |
| + return stay |
| + } |
| + tu.front = &frontMark{Host: host, Account: fi.Account, App: fi.App, Stamp: fi.Stamp, Incarnation: fi.Incarnation} |
| + return requestSelection{Up: tu, OK: true, Prefix: prefix, Target: target, LocalTarget: true} |
| + } |
| + info, ok := homes.exactPathRoute(target) |
| + if !ok || !info.Target || info.Account != rm.account { |
| + e.pathSkip(host, fmt.Sprintf("prefix %q names %s, which is not a ready instance or static route of account %s on any box; sent to the host's home", prefix, target, rm.account)) |
| + return stay |
| + } |
| + return requestSelection{Remote: &remoteTarget{Target: target, Route: info}, Prefix: prefix, Target: target} |
| +} |
| + |
| +// servedName is the key t.hosts answered host under: host itself, or its |
| +// one-label catch-all. A log key, so it is never the request's own spelling |
| +// of a name only a catch-all serves (logThrottled: never key from remote |
| +// input). |
| +func servedName(t *routeTable, host string) string { |
| + if _, exact := t.hosts[host]; exact { |
| + return host |
| + } |
| + if i := strings.IndexByte(host, '.'); i > 0 { |
| + return "*" + host[i:] |
| + } |
| + return host |
| +} |
| + |
| +// pathSkip logs a cross-box refusal once per name, throttled (spec §5.6): |
| +// the "it still falls through" reasons an operator can act on. name is a |
| +// key of this box's tables, never a request's spelling. |
| +func (e *Edge) pathSkip(name, reason string) { |
| + e.logThrottled("path-skip "+name, "paths on "+name+": "+reason) |
| +} |
diff --git a/internal/edge/pathselect_test.go b/internal/edge/pathselect_test.go| new file mode 100644 |
| index 000000000..7bb8fae99 |
| --- /dev/null |
| +++ b/internal/edge/pathselect_test.go |
| @@ -0,0 +1,691 @@ |
| +package edge |
| + |
| +// Path routes across boxes (#186, spec §5.3): the one selection entry point. |
| +// Each test builds a box from a registry (routes, path rows) and a home map |
| +// (other boxes' edges files), then asks selectUpstream what a request gets. |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "maps" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +const ( |
| + selFront = "hub.example.com" |
| + selTarget = "tenant.example.com" |
| + selAcct = "bae" |
| + selOther = "baf" |
| +) |
| + |
| +// selScene is one box under test: its registry, and the edges files of the |
| +// other boxes its home map reads. |
| +type selScene struct { |
| + t *testing.T |
| + reg *registry.Registry |
| + files map[string]map[string]string // box -> host -> entry JSON |
| + act Activator |
| + e *Edge |
| + homes *homeMap |
| +} |
| + |
| +func newSelScene(t *testing.T) *selScene { |
| + t.Helper() |
| + return &selScene{t: t, reg: openReg(t), files: map[string]map[string]string{}} |
| +} |
| + |
| +// instance writes a ready instance route of account/app on an address |
| +// nothing listens on. |
| +func (s *selScene) instance(host, account, app string, mods ...func(*registry.Route)) { |
| + s.t.Helper() |
| + rt := registry.Route{Host: host, Account: account, App: app, Kind: "instance", Status: "ready", Addr: "127.0.0.1:1"} |
| + for _, m := range mods { |
| + m(&rt) |
| + } |
| + if err := s.reg.Upsert(rt); err != nil { |
| + s.t.Fatalf("upsert %s: %v", host, err) |
| + } |
| +} |
| + |
| +// path writes one route_paths row of the claim account/app. |
| +func (s *selScene) path(host, prefix, target, account, app string) { |
| + s.t.Helper() |
| + remotePathRow(s.t, s.reg, host, prefix, target, account, app) |
| +} |
| + |
| +// publish puts host's entry in box's edges file. |
| +func (s *selScene) publish(box, host, entry string) { |
| + if s.files[box] == nil { |
| + s.files[box] = map[string]string{} |
| + } |
| + s.files[box][host] = entry |
| +} |
| + |
| +// build makes the Edge and arms its home map over the published files. |
| +func (s *selScene) build() *Edge { |
| + s.t.Helper() |
| + e, err := New(s.reg, s.act) |
| + if err != nil { |
| + s.t.Fatalf("New: %v", err) |
| + } |
| + s.t.Cleanup(e.probers.Stop) |
| + m := newHomeMap(meshTestStore(s.t), "annie") |
| + for box, hosts := range s.files { |
| + eip := map[string]string{"betty": "2.2.2.2", "cindy": "3.3.3.3"}[box] |
| + putPathFile(s.t, m, box, eip, hosts) |
| + } |
| + refreshHomeMap(s.t, m) |
| + e.homes.Store(m) |
| + s.e, s.homes = e, m |
| + return e |
| +} |
| + |
| +// sel is selectUpstream for GET host+urlPath, with ctx applied. |
| +func (s *selScene) sel(host, urlPath string, ctx ...func(context.Context) context.Context) requestSelection { |
| + s.t.Helper() |
| + r := httptest.NewRequest("GET", "http://"+host+"/", nil) |
| + c := r.Context() |
| + for _, f := range ctx { |
| + c = f(c) |
| + } |
| + return s.e.selectUpstream(r.WithContext(c), host, urlPath) |
| +} |
| + |
| +// replaceHosts publishes a copy of the current table with edit applied to |
| +// its hosts: a fixture no Reload can produce. |
| +func (s *selScene) replaceHosts(edit func(map[string]upstream)) { |
| + t := s.e.table() |
| + hosts := maps.Clone(t.hosts) |
| + edit(hosts) |
| + s.e.upstreams.Store(&routeTable{hosts: hosts, remote: t.remote}) |
| +} |
| + |
| +func homeRow(account, app string, front, target bool) string { |
| + return fmt.Sprintf(`{"role":"home","account":%q,"app":%q,"stamp":7,"incarnation":3,"route_account":%q,"route_app":%q,"path_front":%t,"path_target":%t}`, |
| + account, app, account, app, front, target) |
| +} |
| + |
| +func frontRow(account, app string) string { return homeRow(account, app, true, false) } |
| +func targetRow(account, app string) string { return homeRow(account, app, false, true) } |
| + |
| +func asDoor(c context.Context) context.Context { |
| + return context.WithValue(c, doorCallerKey{}, doorCaller{Account: selAcct, App: "hub"}) |
| +} |
| +func asHop(c context.Context) context.Context { return withHopVerified(c) } |
| +func asDoorHop(c context.Context) context.Context { |
| + return context.WithValue(withHopVerified(c), hopDoorKey{}, true) |
| +} |
| + |
| +// wantLocal: the target's own entry, served here. |
| +func wantLocal(t *testing.T, got requestSelection, routeHost, prefix, target string) { |
| + t.Helper() |
| + if !got.OK || !got.LocalTarget || got.Remote != nil || got.Up.route.Host != routeHost || got.Prefix != prefix || got.Target != target { |
| + t.Fatalf("selection = %s, want the local target %s (prefix %q -> %s)", describeSel(got), routeHost, prefix, target) |
| + } |
| +} |
| + |
| +// wantFront: the front's own entry, as today. |
| +func wantFront(t *testing.T, got requestSelection, routeHost string) { |
| + t.Helper() |
| + if !got.OK || got.LocalTarget || got.Remote != nil || got.Up.route.Host != routeHost || got.Up.front != nil { |
| + t.Fatalf("selection = %s, want the front's entry %s", describeSel(got), routeHost) |
| + } |
| +} |
| + |
| +// wantNone: nothing here (today's backhaul to the host's home). |
| +func wantNone(t *testing.T, got requestSelection) { |
| + t.Helper() |
| + if got.OK || got.LocalTarget || got.Remote != nil { |
| + t.Fatalf("selection = %s, want none", describeSel(got)) |
| + } |
| +} |
| + |
| +// wantRemote: the target route on another box. |
| +func wantRemote(t *testing.T, got requestSelection, target, box string) { |
| + t.Helper() |
| + if got.Remote == nil || got.OK || got.LocalTarget || got.Remote.Target != target || got.Remote.Route.Box != box || got.Target != target { |
| + t.Fatalf("selection = %s, want remote %s on %s", describeSel(got), target, box) |
| + } |
| +} |
| + |
| +func describeSel(s requestSelection) string { |
| + remote := "nil" |
| + if s.Remote != nil { |
| + remote = s.Remote.Target + "@" + s.Remote.Route.Box |
| + } |
| + return fmt.Sprintf("{OK:%v up:%q local:%v remote:%s prefix:%q target:%q front:%+v}", |
| + s.OK, s.Up.route.Host, s.LocalTarget, remote, s.Prefix, s.Target, s.Up.front) |
| +} |
| + |
| +// ---- case 1: same box ------------------------------------------------------ |
| + |
| +func TestSelectCase1LocalTarget(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selFront, selAcct, "hub") |
| + s.instance(selTarget, selAcct, "tenant") |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.build() |
| + got := s.sel(selFront, "/acme/x") |
| + wantLocal(t, got, selTarget, "acme", selTarget) |
| + if got.Up.front != nil { |
| + t.Errorf("a same-box target carries a front mark: %+v", got.Up.front) |
| + } |
| + got = s.sel(selFront, "/other") |
| + wantFront(t, got, selFront) |
| + if got.Prefix != "" || got.Target != "" { |
| + t.Errorf("a miss reports prefix %q target %q", got.Prefix, got.Target) |
| + } |
| +} |
| + |
| +// Same-box keeps every route kind: a service target is served, though it is |
| +// not a cross-box target route. |
| +func TestSelectCase1ServiceTarget(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selFront, selAcct, "hub") |
| + s.instance(selTarget, selAcct, "tenant", func(r *registry.Route) { r.Kind = "service" }) |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.build() |
| + wantLocal(t, s.sel(selFront, "/acme"), selTarget, "acme", selTarget) |
| +} |
| + |
| +// Plan R2 P1-2: a same-account platform-minted target keeps working. Its |
| +// entry is its instance's (route.Host is the instance's), and LocalTarget |
| +// says a target was selected. |
| +func TestSelectCase1PlatformAliasTarget(t *testing.T) { |
| + s := newSelScene(t) |
| + const inst, alias = "a.bae.oncarlos.com", "shop.bae.oncarlos.com" |
| + s.instance(selFront, selAcct, "hub") |
| + s.instance(inst, selAcct, "shop", func(r *registry.Route) { r.Addr, r.Socket = "", "/s/a.sock" }) |
| + s.instance(alias, selAcct, "shop", func(r *registry.Route) { r.Addr, r.Socket, r.Platform = "", "/s/a.sock", true }) |
| + s.path(selFront, "shop", alias, selAcct, "hub") |
| + e := s.build() |
| + if up := e.current()[alias]; !up.platformAlias { |
| + t.Fatalf("fixture: %s is not a platform alias entry: %+v", alias, up) |
| + } |
| + got := s.sel(selFront, "/shop/x") |
| + wantLocal(t, got, inst, "shop", alias) |
| + if !got.Up.platformAlias { |
| + t.Error("the selected entry is not the platform alias's") |
| + } |
| +} |
| + |
| +// R3 P2-4: the reserved demo apex is never resolved through a parent |
| +// catch-all, by the local map or the remote map. |
| +func TestSelectDemoApexNotViaCatchAll(t *testing.T) { |
| + t.Setenv("CARLOS_DEMO_DOMAIN", "demos.example.com") |
| + s := newSelScene(t) |
| + s.instance("*.example.com", selAcct, "hub") |
| + s.instance(selTarget, selAcct, "tenant") |
| + s.path("demos.example.com", "acme", selTarget, selAcct, "hub") |
| + s.publish("betty", "demos.example.com", frontRow(selAcct, "hub")) |
| + s.build() |
| + wantNone(t, s.sel("demos.example.com", "/")) |
| + wantNone(t, s.sel("demos.example.com", "/acme")) |
| + wantFront(t, s.sel("shop.example.com", "/"), "*.example.com") |
| +} |
| + |
| +// An attached alias is never a path target, whoever's route it names. |
| +func TestSelectCase1AttachedAliasRefused(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selFront, selAcct, "hub") |
| + s.instance("b.example.com", selOther, "shop") |
| + s.instance("c.example.com", selAcct, "blog") |
| + upsertAlias(t, s.reg, "balias.example.com", "b.example.com") |
| + upsertAlias(t, s.reg, "calias.example.com", "c.example.com") |
| + s.path(selFront, "b", "balias.example.com", selAcct, "hub") |
| + s.path(selFront, "c", "calias.example.com", selAcct, "hub") |
| + s.build() |
| + for _, p := range []string{"/b/x", "/c/x"} { |
| + got := s.sel(selFront, p) |
| + wantFront(t, got, selFront) |
| + if got.Prefix == "" || got.Target == "" { |
| + t.Errorf("%s: a matched prefix is not reported: %s", p, describeSel(got)) |
| + } |
| + } |
| +} |
| + |
| +func TestSelectCase1OtherAccountRefused(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selFront, selAcct, "hub") |
| + s.instance(selTarget, selOther, "tenant") |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.build() |
| + got := s.sel(selFront, "/acme") |
| + wantFront(t, got, selFront) |
| + if got.Prefix != "acme" || got.Target != selTarget { |
| + t.Errorf("prefix %q target %q, want acme -> %s", got.Prefix, got.Target, selTarget) |
| + } |
| +} |
| + |
| +// A regional name of another account, as a same-box target: refused (the |
| +// regional entry carries its bound route's row, in that account). |
| +func TestSelectCase1RegionalOtherAccountRefused(t *testing.T) { |
| + s := newSelScene(t) |
| + const regional, bound = "shop.example.org", "shop-ie.example.net" |
| + s.instance(selFront, selAcct, "hub") |
| + s.instance(bound, selOther, "shop", func(r *registry.Route) { r.Addr, r.Socket, r.Provisioned = "", "/s/r.sock", true }) |
| + if err := s.reg.ReplaceRegionalSet(regional, []registry.RegionalDomain{{Host: regional, Target: bound, Account: selOther, App: "shop"}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.path(selFront, "reg", regional, selAcct, "hub") |
| + e := s.build() |
| + if up := e.current()[regional]; up.regional != regionalServe || up.route.Host != bound { |
| + t.Fatalf("fixture: %s is not a regional serve entry: %+v", regional, up) |
| + } |
| + wantFront(t, s.sel(selFront, "/reg"), selFront) |
| +} |
| + |
| +// ---- case 2: the front here, the target elsewhere -------------------------- |
| + |
| +func TestSelectCase2RemoteTarget(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selFront, selAcct, "hub") |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.publish("betty", selTarget, targetRow(selAcct, "tenant")) |
| + s.build() |
| + got := s.sel(selFront, "/acme/api") |
| + wantRemote(t, got, selTarget, "betty") |
| + if got.Prefix != "acme" || got.Remote.Route.Dial != "2.2.2.2" || got.Remote.Route.Account != selAcct || got.Up.route.Host != "" { |
| + t.Errorf("selection = %s, route %+v", describeSel(got), got.Remote.Route) |
| + } |
| + wantFront(t, s.sel(selFront, "/"), selFront) |
| +} |
| + |
| +func TestSelectCase2TargetOtherAccount(t *testing.T) { |
| + logs := captureLog(t) |
| + s := newSelScene(t) |
| + s.instance(selFront, selAcct, "hub") |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.publish("betty", selTarget, targetRow(selOther, "tenant")) |
| + s.build() |
| + wantFront(t, s.sel(selFront, "/acme"), selFront) |
| + if out := logs.String(); !strings.Contains(out, selFront) || !strings.Contains(out, selOther) { |
| + t.Errorf("no log names the host and the target's account; log:\n%s", out) |
| + } |
| +} |
| + |
| +// Review Focus 4: a target route that exists but is not ready on its box |
| +// (published without path_target), or not published at all: today's |
| +// fall-through to the host's own route, not a 502. |
| +func TestSelectCase2TargetNotReady(t *testing.T) { |
| + logs := captureLog(t) |
| + s := newSelScene(t) |
| + s.instance(selFront, selAcct, "hub") |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.path(selFront, "gone", "gone.example.com", selAcct, "hub") |
| + s.publish("betty", selTarget, homeRow(selAcct, "tenant", false, false)) |
| + s.build() |
| + wantFront(t, s.sel(selFront, "/acme"), selFront) |
| + wantFront(t, s.sel(selFront, "/gone"), selFront) |
| + if out := logs.String(); !strings.Contains(out, selTarget) { |
| + t.Errorf("no log names the ineligible target; log:\n%s", out) |
| + } |
| +} |
| + |
| +// A front that is not PathFront (a forward row, a service) never selects |
| +// across boxes, whatever its map says. |
| +func TestSelectCase2ForwardFrontNeverRemote(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selFront, selAcct, "hub") |
| + s.instance("svc.example.com", selAcct, "svc", func(r *registry.Route) { r.Kind = "service" }) |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.path("svc.example.com", "acme", selTarget, selAcct, "svc") |
| + s.publish("betty", selTarget, targetRow(selAcct, "tenant")) |
| + s.build() |
| + wantFront(t, s.sel("svc.example.com", "/acme"), "svc.example.com") |
| + // A forward row's entry never carries a path map (attachPaths); the |
| + // rule holds even if one did. |
| + s.replaceHosts(func(m map[string]upstream) { |
| + up := m[selFront] |
| + up.route.Kind = registry.KindForward |
| + m[selFront] = up |
| + }) |
| + wantFront(t, s.sel(selFront, "/acme"), selFront) |
| +} |
| + |
| +// ---- case 3: the front elsewhere ------------------------------------------- |
| + |
| +func TestSelectCase3LocalTarget(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selTarget, selAcct, "tenant") |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.publish("betty", selFront, frontRow(selAcct, "hub")) |
| + s.build() |
| + got := s.sel(selFront, "/acme/api/version") |
| + wantLocal(t, got, selTarget, "acme", selTarget) |
| + want := frontMark{Host: selFront, Account: selAcct, App: "hub", Stamp: 7, Incarnation: 3} |
| + if got.Up.front == nil || *got.Up.front != want { |
| + t.Errorf("front mark = %+v, want %+v", got.Up.front, want) |
| + } |
| +} |
| + |
| +func TestSelectCase3LocalTargetOtherAccount(t *testing.T) { |
| + logs := captureLog(t) |
| + s := newSelScene(t) |
| + s.instance(selTarget, selOther, "tenant") |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.publish("betty", selFront, frontRow(selAcct, "hub")) |
| + s.build() |
| + wantNone(t, s.sel(selFront, "/acme")) |
| + if out := logs.String(); !strings.Contains(out, selFront) || !strings.Contains(out, selTarget) { |
| + t.Errorf("no log names the host and the refused target; log:\n%s", out) |
| + } |
| +} |
| + |
| +func TestSelectCase3RemoteTargetOtherAccount(t *testing.T) { |
| + s := newSelScene(t) |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.path(selFront, "ok", "ok.example.com", selAcct, "hub") |
| + s.publish("betty", selFront, frontRow(selAcct, "hub")) |
| + s.publish("cindy", selTarget, targetRow(selOther, "tenant")) |
| + s.publish("cindy", "ok.example.com", targetRow(selAcct, "tenant")) |
| + s.build() |
| + wantNone(t, s.sel(selFront, "/acme")) |
| + wantRemote(t, s.sel(selFront, "/ok"), "ok.example.com", "cindy") |
| +} |
| + |
| +// Cross-box targets are PathTarget routes only: a service this box serves is |
| +// not one. |
| +func TestSelectCase3LocalServiceTargetRefused(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selTarget, selAcct, "tenant", func(r *registry.Route) { r.Kind = "service" }) |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.publish("betty", selFront, frontRow(selAcct, "hub")) |
| + s.build() |
| + wantNone(t, s.sel(selFront, "/acme")) |
| +} |
| + |
| +// The front check against the home map: the published row must be a front |
| +// route of the remote map's own account and app. |
| +func TestSelectCase3FrontOwnerMismatch(t *testing.T) { |
| + logs := captureLog(t) |
| + s := newSelScene(t) |
| + s.instance(selTarget, selAcct, "tenant") |
| + for _, f := range []string{"app.example.com", "acct.example.com", "nofront.example.com"} { |
| + s.path(f, "acme", selTarget, selAcct, "hub") |
| + } |
| + s.publish("betty", "app.example.com", frontRow(selAcct, "other")) |
| + s.publish("betty", "acct.example.com", frontRow(selOther, "hub")) |
| + s.publish("betty", "nofront.example.com", homeRow(selAcct, "hub", false, true)) |
| + s.build() |
| + for _, f := range []string{"app.example.com", "acct.example.com", "nofront.example.com", "unpublished.example.com"} { |
| + wantNone(t, s.sel(f, "/acme")) |
| + } |
| + if out := logs.String(); !strings.Contains(out, "app.example.com") { |
| + t.Errorf("no log names the refused front; log:\n%s", out) |
| + } |
| +} |
| + |
| +func TestSelectCase3PrefixMiss(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selTarget, selAcct, "tenant") |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.publish("betty", selFront, frontRow(selAcct, "hub")) |
| + s.build() |
| + for _, p := range []string{"/zzz", "/", ""} { |
| + got := s.sel(selFront, p) |
| + wantNone(t, got) |
| + if got.Prefix != "" || got.Target != "" { |
| + t.Errorf("%q: a miss reports prefix %q target %q", p, got.Prefix, got.Target) |
| + } |
| + } |
| +} |
| + |
| +// A home map that has not completed a hosts read gives no cross-box answer. |
| +func TestSelectCase3HomeMapNotRead(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selTarget, selAcct, "tenant") |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.publish("betty", selFront, frontRow(selAcct, "hub")) |
| + s.build() |
| + wantLocal(t, s.sel(selFront, "/acme"), selTarget, "acme", selTarget) |
| + s.homes.mu.Lock() |
| + unread := *s.homes.snap |
| + unread.read = false |
| + s.homes.snap = &unread |
| + s.homes.mu.Unlock() |
| + wantNone(t, s.sel(selFront, "/acme")) |
| +} |
| + |
| +// Review Focus 5: on a host this box does not serve, both spellings select |
| +// as the home box does (cleaned first, then raw; cleaned wins). |
| +func TestSelectBothSpellings(t *testing.T) { |
| + const t1, t2 = "t1.example.com", "t2.example.com" |
| + scene := func(frontHere bool) *selScene { |
| + s := newSelScene(t) |
| + if frontHere { |
| + s.instance(selFront, selAcct, "hub") |
| + } else { |
| + s.publish("betty", selFront, frontRow(selAcct, "hub")) |
| + } |
| + s.instance(t1, selAcct, "t1") |
| + s.instance(t2, selAcct, "t2") |
| + s.path(selFront, "paulca", t1, selAcct, "hub") |
| + s.path(selFront, "bob", t2, selAcct, "hub") |
| + s.build() |
| + return s |
| + } |
| + home, ingress := scene(true), scene(false) |
| + for _, c := range []struct{ path, want string }{ |
| + {"/paulca/../bob", t2}, // both name a prefix: the cleaned one wins |
| + {"/paulca/../carol", t1}, // only the raw form names one |
| + {"//paulca/x", t1}, // only the cleaned form names one |
| + {"/bob", t2}, |
| + } { |
| + h, i := home.sel(selFront, c.path), ingress.sel(selFront, c.path) |
| + wantLocal(t, h, c.want, h.Prefix, c.want) |
| + wantLocal(t, i, c.want, h.Prefix, c.want) |
| + if i.Up.front == nil { |
| + t.Errorf("%s: the ingress box's case 3 answer has no front mark", c.path) |
| + } |
| + } |
| +} |
| + |
| +// ---- fronts that never select across --------------------------------------- |
| + |
| +// A catch-all is never a front route: its prefix map stays same-box, and the |
| +// concrete name's own remote map is not consulted while the catch-all |
| +// serves it. |
| +func TestSelectWildcardFrontNeverAcross(t *testing.T) { |
| + logs := captureLog(t) |
| + s := newSelScene(t) |
| + s.instance("*.example.com", selAcct, "hub") |
| + s.instance("t2.example.com", selAcct, "t2") |
| + s.path("*.example.com", "acme", selTarget, selAcct, "hub") |
| + s.path("shop.example.com", "acme", "t2.example.com", selAcct, "hub") |
| + s.publish("betty", selTarget, targetRow(selAcct, "tenant")) |
| + s.publish("betty", "shop.example.com", frontRow(selAcct, "hub")) |
| + s.build() |
| + if s.e.current()["*.example.com"].paths["acme"] != selTarget { |
| + t.Fatal("fixture: the catch-all has no prefix map") |
| + } |
| + wantFront(t, s.sel("shop.example.com", "/acme"), "*.example.com") |
| + if strings.Contains(logs.String(), "shop.example.com") { |
| + t.Errorf("a log is keyed on the requested name, not the catch-all; log:\n%s", logs.String()) |
| + } |
| +} |
| + |
| +func TestSelectAliasFrontNeverAcross(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selFront, selAcct, "hub") |
| + upsertAlias(t, s.reg, "www.hub.example.com", selFront) |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.publish("betty", selTarget, targetRow(selAcct, "tenant")) |
| + s.build() |
| + wantRemote(t, s.sel(selFront, "/acme"), selTarget, "betty") |
| + got := s.sel("www.hub.example.com", "/acme") |
| + wantFront(t, got, selFront) |
| + if !got.Up.alias { |
| + t.Error("the alias's own entry was not answered") |
| + } |
| +} |
| + |
| +// A forward route is never a target: published (its marks are false) or |
| +// local. |
| +func TestSelectForwardTargetNeverSelected(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selFront, selAcct, "hub") |
| + s.instance("t3.example.com", selAcct, "t3") |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.path("away.example.com", "fwd", "t3.example.com", selAcct, "away") |
| + s.publish("betty", selTarget, homeRow(selAcct, "tenant", false, false)) |
| + s.publish("betty", "away.example.com", frontRow(selAcct, "away")) |
| + s.build() |
| + wantFront(t, s.sel(selFront, "/acme"), selFront) |
| + wantLocal(t, s.sel("away.example.com", "/fwd"), "t3.example.com", "fwd", "t3.example.com") |
| + s.replaceHosts(func(m map[string]upstream) { |
| + up := m["t3.example.com"] |
| + up.route.Kind = registry.KindForward |
| + m["t3.example.com"] = up |
| + }) |
| + wantNone(t, s.sel("away.example.com", "/fwd")) |
| +} |
| + |
| +// ---- door calls, hops ------------------------------------------------------ |
| + |
| +// acrossScene: front1 here with a remote target (case 2), front2 elsewhere |
| +// with a local target (case 3) and a remote one. |
| +func acrossScene(t *testing.T) *selScene { |
| + s := newSelScene(t) |
| + s.instance(selFront, selAcct, "hub") |
| + s.instance(selTarget, selAcct, "tenant") |
| + s.path(selFront, "acme", "far.example.com", selAcct, "hub") |
| + s.path("away.example.com", "acme", selTarget, selAcct, "hub") |
| + s.path("away.example.com", "far", "far.example.com", selAcct, "hub") |
| + s.publish("betty", "far.example.com", targetRow(selAcct, "tenant")) |
| + s.publish("betty", "away.example.com", frontRow(selAcct, "hub")) |
| + s.build() |
| + return s |
| +} |
| + |
| +func TestSelectDoorNeverAcross(t *testing.T) { |
| + s := acrossScene(t) |
| + wantRemote(t, s.sel(selFront, "/acme"), "far.example.com", "betty") |
| + wantLocal(t, s.sel("away.example.com", "/acme"), selTarget, "acme", selTarget) |
| + wantRemote(t, s.sel("away.example.com", "/far"), "far.example.com", "betty") |
| + |
| + wantFront(t, s.sel(selFront, "/acme", asDoor), selFront) |
| + wantNone(t, s.sel("away.example.com", "/acme", asDoor)) |
| + wantNone(t, s.sel("away.example.com", "/far", asDoor)) |
| +} |
| + |
| +func TestSelectDoorHopIgnoresRemoteMap(t *testing.T) { |
| + s := acrossScene(t) |
| + wantLocal(t, s.sel("away.example.com", "/acme", asHop), selTarget, "acme", selTarget) |
| + wantNone(t, s.sel("away.example.com", "/acme", asDoorHop)) |
| + wantNone(t, s.sel("away.example.com", "/far", asDoorHop)) |
| +} |
| + |
| +// HA changes neither predicate: an HA target is a target route here and |
| +// across. |
| +func TestSelectHATarget(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selTarget, selAcct, "tenant", func(r *registry.Route) { r.HA = true }) |
| + s.path("away.example.com", "acme", selTarget, selAcct, "hub") |
| + s.path("away.example.com", "far", "far.example.com", selAcct, "hub") |
| + s.publish("betty", "away.example.com", frontRow(selAcct, "hub")) |
| + s.publish("cindy", "far.example.com", targetRow(selAcct, "tenant")) |
| + e := s.build() |
| + if up, ok := e.current()[selTarget]; !ok || !up.route.HA { |
| + t.Fatalf("fixture: the HA target is not served here: %+v", up) |
| + } |
| + wantLocal(t, s.sel("away.example.com", "/acme"), selTarget, "acme", selTarget) |
| + wantRemote(t, s.sel("away.example.com", "/far"), "far.example.com", "cindy") |
| +} |
| + |
| +// Spec §5.4: on a verified hop a remote answer never stands. The front |
| +// served here answers its own entry. |
| +func TestSelectArrivedHopRemoteServesFront(t *testing.T) { |
| + s := acrossScene(t) |
| + got := s.sel(selFront, "/acme", asHop) |
| + wantFront(t, got, selFront) |
| + if got.Prefix != "acme" { |
| + t.Errorf("prefix %q, want acme", got.Prefix) |
| + } |
| +} |
| + |
| +// ...and a front not served here answers nothing (the caller's stale-hop |
| +// refusal). |
| +func TestSelectArrivedHopRemoteNotServed(t *testing.T) { |
| + s := acrossScene(t) |
| + wantNone(t, s.sel("away.example.com", "/far", asHop)) |
| +} |
| + |
| +// A pinned request reads only its pinned entry: no prefix, local or remote, |
| +// selects anything else. |
| +func TestSelectPinnedIgnoresPathMaps(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selFront, selAcct, "hub", func(r *registry.Route) { r.Addr, r.Socket = "", "/s/hub.sock" }) |
| + s.instance(selTarget, selAcct, "tenant") |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.path(selFront, "far", "far.example.com", selAcct, "hub") |
| + s.publish("betty", "far.example.com", targetRow(selAcct, "tenant")) |
| + s.build() |
| + wantLocal(t, s.sel(selFront, "/acme"), selTarget, "acme", selTarget) |
| + wantRemote(t, s.sel(selFront, "/far"), "far.example.com", "betty") |
| + pin := func(c context.Context) context.Context { |
| + return withLinkPin(c, LinkedTarget{Host: selFront, Account: selAcct, App: "hub", PublicHost: "hub.pub.example"}) |
| + } |
| + for _, p := range []string{"/acme", "/far", "/"} { |
| + got := s.sel(selFront, p, pin) |
| + if !got.OK || got.Up.route.Host != selFront || got.Prefix != "" || got.Target != "" || got.Remote != nil || got.LocalTarget { |
| + t.Errorf("pinned %s: %s, want the pinned entry alone", p, describeSel(got)) |
| + } |
| + } |
| +} |
| + |
| +// ---- the matcher and the compatibility wrapper ----------------------------- |
| + |
| +// pathMatch reports what it matched, and lookupUpstreamPath answers its |
| +// up/ok. |
| +func TestPathMatchReportsTheMatch(t *testing.T) { |
| + s := newSelScene(t) |
| + s.instance(selFront, selAcct, "hub") |
| + s.instance(selTarget, selAcct, "tenant") |
| + s.instance("other.example.com", selOther, "x") |
| + s.path(selFront, "acme", selTarget, selAcct, "hub") |
| + s.path(selFront, "far", "far.example.com", selAcct, "hub") |
| + s.path(selFront, "x", "other.example.com", selAcct, "hub") |
| + e := s.build() |
| + for _, c := range []struct { |
| + path, upHost, prefix, target string |
| + local bool |
| + }{ |
| + {"/acme/1", selTarget, "acme", selTarget, true}, |
| + {"/far", selFront, "far", "far.example.com", false}, |
| + {"/x", selFront, "x", "other.example.com", false}, |
| + {"/none", selFront, "", "", false}, |
| + } { |
| + up, ok, prefix, target, local := e.pathMatch(e.current(), selFront, c.path) |
| + if !ok || up.route.Host != c.upHost || prefix != c.prefix || target != c.target || local != c.local { |
| + t.Errorf("pathMatch(%s) = %q %v %q %q %v, want %q %q %q %v", c.path, up.route.Host, ok, prefix, target, local, c.upHost, c.prefix, c.target, c.local) |
| + } |
| + lu, lok := e.lookupUpstreamPath(selFront, c.path) |
| + if lok != ok || lu.route.Host != up.route.Host { |
| + t.Errorf("lookupUpstreamPath(%s) = %q %v, want pathMatch's %q %v", c.path, lu.route.Host, lok, up.route.Host, ok) |
| + } |
| + } |
| + for _, c := range []struct{ path, prefix string }{ |
| + {"/a/b", "a"}, |
| + {"//a/x", "a"}, // cleaned form only |
| + {"/a/../z", "a"}, // raw form only |
| + {"/a/../b", "b"}, // both: the cleaned one wins |
| + {"/", ""}, |
| + {"/z", ""}, |
| + } { |
| + prefix, target, ok := matchPrefix(map[string]string{"a": "ta", "b": "tb"}, c.path) |
| + if c.prefix == "" { |
| + if ok { |
| + t.Errorf("matchPrefix(%q) = %q, want a miss", c.path, prefix) |
| + } |
| + continue |
| + } |
| + if !ok || prefix != c.prefix || target != "t"+c.prefix { |
| + t.Errorf("matchPrefix(%q) = %q %q %v, want %q", c.path, prefix, target, ok, c.prefix) |
| + } |
| + } |
| +} |
diff --git a/internal/edge/purge_path_test.go b/internal/edge/purge_path_test.go| index 698bafdfd..61ea160ee 100644 |
| --- a/internal/edge/purge_path_test.go |
| +++ b/internal/edge/purge_path_test.go |
| @@ -85,6 +85,11 @@ func TestPurgeHostOverrideAllowedFromAPathRoutedHost(t *testing.T) { |
| // Both accounts must be valid sqids (^[a-z]{3,16}$) or release.RouteAccount |
| // folds them both onto the built-in ops account and the test asserts a |
| // boundary it never crossed. |
| +// |
| +// Selection refuses such a target too (the same-box guard: ti.to/paulca is |
| +// answered by ti.to's own route, TestSelectCase1OtherAccountRefused), so the |
| +// write arrives on the target's OWN host, where its route serves it: the |
| +// purge check is pinned on its own, whatever selection does. |
| func TestPurgeHostOverrideFromPathRoutedHostStillNeedsTheAccount(t *testing.T) { |
| e := purgePathEdge(t, |
| route("ti.to", "classic", "tenanta"), |
| @@ -98,7 +103,7 @@ func TestPurgeHostOverrideFromPathRoutedHostStillNeedsTheAccount(t *testing.T) { |
| seed(t, e.cache, "ti.to", "/paulca/events/42", "", "stale") |
| rec := httptest.NewRecorder() |
| - e.ServeHTTP(rec, httptest.NewRequest("POST", "http://ti.to/paulca/admin", nil)) |
| + e.ServeHTTP(rec, httptest.NewRequest("POST", "http://go.tito.example/paulca/admin", nil)) |
| if !cached(e.cache, "ti.to", "/paulca/events/42", "") { |
| t.Fatal("a path row pointing across ACCOUNTS let the target purge the front host's cache") |
diff --git a/internal/edge/regional.go b/internal/edge/regional.go| index 790308e76..43698c74b 100644 |
| --- a/internal/edge/regional.go |
| +++ b/internal/edge/regional.go |
| @@ -4,7 +4,7 @@ package edge |
| // 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 |
| +// deny entry; and regionalGate, called straight after selectUpstream 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). |
diff --git a/internal/edge/tunnel_login_test.go b/internal/edge/tunnel_login_test.go| index 766be8a16..de23adf0f 100644 |
| --- a/internal/edge/tunnel_login_test.go |
| +++ b/internal/edge/tunnel_login_test.go |
| @@ -85,8 +85,10 @@ func tunnelLoginScene(t *testing.T, frontGate bool) (srv *httptest.Server, front |
| reg := openReg(t) |
| for _, rt := range []registry.Route{ |
| {Host: tlFront, Kind: "instance", Status: "ready", Tunnel: "t1", Account: fwdOwner, App: "front"}, |
| - {Host: tlTarget, Kind: "service", Status: "ready", Addr: target.Listener.Addr().String(), Gate: targetHash}, |
| - {Host: tlDocs, Kind: "service", Status: "ready", Addr: docs.Listener.Addr().String()}, |
| + // The targets are the front's account's: a prefix never selects a |
| + // route in another account (pathMatch's same-box guard). |
| + {Host: tlTarget, Kind: "service", Status: "ready", Addr: target.Listener.Addr().String(), Gate: targetHash, Account: fwdOwner, App: "target"}, |
| + {Host: tlDocs, Kind: "service", Status: "ready", Addr: docs.Listener.Addr().String(), Account: fwdOwner, App: "docs"}, |
| } { |
| if err := reg.Upsert(rt); err != nil { |
| t.Fatal(err) |