Regional domains (#447): T4+T5 fix round 1 (ruling 7): one transaction per claim's regional rows
P1-1: registry.ReplaceRegionalSet(host, rows) writes a regional claim's apex and *.apex rows as one SQLite transaction, locally and as one remote request; UpsertRegional/DeleteRegional are gone, so it is the table's only writer. writeRegional groups rows by claim and writes or removes each claim as a set; a failed set write leaves the claim's rows as they were and marks the pass incomplete. P2-1: an unread regional claim keeps its wildcard_domains parent while the kept apex row's target still passes release.RegionalTarget (row's account, app, region; parent of the same tenancy; per-box cap counted). P2-2: spec §10.5 detach/recreate residual ends at a successful derivation or removal of the conflicting route, not adoption (rev 5.1); §7.2 names the per-claim transaction. Witnesses: TestRegionalStarWriteFailureLeavesNoHalfClaim (edge, real registry file, trigger fault, TCP hand route, two restarts); TestRegionalRowsPairOrNothingUnderFaults (seeded guard, 300 passes); TestReplaceRegionalSetIsAtomic (local + remote); TestRegionalWildcardParentKeptWhileClaimUnreadable, TestRegionalWildcardCertSurvivesAnUnreadableClaim (real wildcard manager), W2 "after unread passes" (real writer vs golden). Mutation checks: - HEAD's per-row writer: edge witness fails (apex without star; alice reaches the hand route, accepted 1); guard fails (star without apex). - ReplaceRegionalSet with per-row semantics: guard, atomic test (local, remote) and edge witness fail. - Parent retention off: domains, edge cert and host W2 legs fail; tenancy check off and RegionalTarget-as-presence each fail their leg.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/specs/2026-10-28-regional-domains-447-design.md+7 −2internal/domains/aliases.go+86 −27internal/domains/regional_derive_test.go+93 −2internal/domains/regional_guard_test.go+333 −0internal/edge/regional_cert_test.go+109 −0internal/edge/regional_fault_test.go+197 −0internal/host/edgesfile_test.go+48 −0internal/registry/regional_test.go+185 −35internal/registry/registry.go+51 −20internal/registry/remote_dispatch.go+3 −5
Intent
<agent-message from="af17d5e1dbe1fd0b0"> #447 build stopped under ruling 6: the Task 4+5 Astra review found a P1 in the covering-routes family again. I haven't fixed it; Paul's go is needed. Branch regional-domains-447, tip a44a4cff (pushed). origin/main was merged at 7fc98ba1 after v0.30.3. Progress: - T1 placements GET and CLI read: done, review clean. - T2 claim shape and T3 console writer rules: done. Astra R1 found 1 P1 (a team detach could delete a regional claim that replaced the one it was authorized on). Fixed with an ETag-conditional delete and a scope recheck; R2 READY. - T4 derivation and T5 edge regionalGate: built, with mutation checks in the commits. Astra R1 NOT READY (below). - T6 carlos add refusal: Astra READY AFTER FIXES, with 2 P2s (trailing-dot hosts; the test isn't isolated from deployment config). Not applied because of the stop. - T7 placements PUT: built (63f904b2), not reviewed. Its review is joint with T8. - T8-T13 not started. The P1 (I checked the citation and it holds): box-side derivation writes a regional claim's apex and *.X rows as separate statements and carries on after a failed upsert (internal/domains/aliases.go:863, internal/registry/registry.go:3535). If the star write fails and the apex write succeeds, a box that has read the current claim holds no *.X row. A root hand route at *.X then serves alice.X, possibly from another region. That is outside the accepted never-read-the-claim limit. The same review also found two P2s: an unread claim drops its wildcard certificate parent, and spec §10.5's recovery bound for the detach/recreate residual is wrong. It confirmed that the R4 pending-allocation fix is sufficient. Options (posted on #447 and in the branch handoff): - A. Write each claim's apex and star rows in one SQLite transaction, for both the local and the remote registry, so a failure writes neither. A box with no rows falls into the accepted never-read class. The witness injects the star failure, with a hand-route backend and a restart. Then one scoped Astra re-review: round 2 of 3 for this change. - B. Cut regional catch-alls (apex only). This removes the case, but the #447 consumer's handles live under the catch-all. - C. Park the branch as built. My recommendation is A, together with the two P2 fixes and T6's two P2s. Send Paul's choice to resume me. My ledger is .superpowers/sdd/2026-10-28-regional-domains-447/progress.md. </agent-message>
<task-notification> <task-id>af17d5e1dbe1fd0b0</task-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/c2acaf22-306d-491b-b2b6-addbf33b8e87/tasks/af17d5e1dbe1fd0b0.output</output-file> <status>completed</status> <summary>Agent "Controller: build regional domains #447" 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>The #447 build has stopped again: the Astra review of Tasks 4 and 5 found another P1 in the covering-routes family. Ruling 6 says stop and report, so I haven't fixed it. Paul needs to choose how to proceed. **What's built** (branch tip a44a4cff, pushed; main merged in after v0.30.3): | Task | State | |---|---| | T1 placements GET and CLI read | Done, review clean | | T2 claim shape, T3 console writer rules | Done. Astra round 1 found one P1 (a team delete could remove a regional claim that replaced the one it was authorized on). Fixed; round 2 READY | | T4 box-side derivation, T5 edge guard | Built, with mutation checks recorded in the commits. Astra round 1 NOT READY (below) | | T6 `carlos add` refusal | Astra READY AFTER FIXES. Its two P2s (trailing-dot hostnames; the test isn't isolated from deployment config) are not applied yet | | T7 placements PUT | Built (63f904b2), not reviewed yet; its review is joint with T8 | | T8–T13 | Not started | **The P1.** The box writes a regional domain's apex row and its catch-all row as two separate statements. If the catch-all write fails, it logs the error and carries on (`internal/domains/aliases.go:863`, `internal/registry/registry.go:3535`). The box can then end up with the apex row but no catch-all row, even though it has read the current claim. If a root hand route on that box holds the catch-all key, requests under the catch-all are served from that route, possibly in another region. That falls outside the accepted "never read the claim" limit. I checked the code and the finding holds. The same review also found two P2s: - A claim the box can't read for a pass loses its wildcard certificate parent. - The spec's recovery bound for the detach-and-recreate case is wrong: adopting a current binary alone doesn't end it. It also confirmed the pending-allocation fix from design round 4 is sufficient. **Decision needed** (posted on #447, in the branch handoff, and sent to the root session): - **A. Write each claim's rows together.** The apex and catch-all rows go in one database transaction, so a failure writes neither, and a box with no rows is in the accepted limit. Add a test that forces the catch-all write to fail with a hand route present and a restart, then one scoped Astra re-review (round 2 of 3). - **B. Cut regional catch-alls** and serve the apex only. This removes the case, but the #447 consumer's user handles live under the catch-all. - **C. Park the branch** as built. I recommend A, together with the two P2 fixes and Task 6's two P2s. No reviews or implementers are still running. The scratch folder stays until the finish. The ledger to resume from is `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/regional-domains-447/.superpowers/sdd/2026-10-28-regional-domains-447/progress.md`. Review briefs and findings are in `docs/superpowers/reviews/regional-domains-447/` under the worktree.</result> <usage><subagent_tokens>297123</subagent_tokens><tool_uses>57</tool_uses><duration_ms>12167311</duration_ms></usage> </task-notification>
diff --git a/docs/superpowers/specs/2026-10-28-regional-domains-447-design.md b/docs/superpowers/specs/2026-10-28-regional-domains-447-design.md| index eeae59e1a..ccbe3c883 100644 |
| --- a/docs/superpowers/specs/2026-10-28-regional-domains-447-design.md |
| +++ b/docs/superpowers/specs/2026-10-28-regional-domains-447-design.md |
| @@ -683,7 +683,7 @@ through its own key, and §6.7 keeps every covering key away. Guard test: W2. |
| fixed from its creation: a box's first derivation of a catch-all claim |
| writes `host` and `*.host` together, and no later pass adds or removes |
| the star. A box holding the apex row of a catch-all claim holds its star |
| - row too. |
| + row too. (rev 5.1, ruling 7) A claim's rows are written as one set, in one SQLite transaction on the local or remote registry (`ReplaceRegionalSet`), so a failed write leaves the claim's previous rows exactly as they were and the pass incomplete: a box whose write failed has not derived the claim (§10.5). |
| - Undesired rows are deleted, except rows whose claim is listed but |
| unreadable this pass (dropped, not not-found): they stay as they were and |
| the pass reports incomplete (the `deriveInstanceAliases` rule). A kept row |
| @@ -978,7 +978,12 @@ the apex, because a regional claim's capabilities are fixed at creation |
| claim desires. Changing capabilities is a detach and a fresh PUT, which |
| makes a new claim. A box that holds rows kept from the old claim (listed |
| but unreadable, §7.2) and has not read the new one has never read this |
| -claim either, so it is in the same class, with the same end. |
| +claim either, so it is in the same class. (rev 5.1) Its end is narrower: |
| +a restart or an adoption reloads the same old rows (§7.5), and `Reload` |
| +judges only the rows a box holds, so neither can add a key the new claim |
| +desires and the old one lacked. The residual ends when a successful |
| +derivation installs the new claim's rows, or when the conflicting route is |
| +removed; adoption alone is insufficient. |
| ## 11. Request budget |
diff --git a/internal/domains/aliases.go b/internal/domains/aliases.go| index 960ac57e6..0c5757618 100644 |
| --- a/internal/domains/aliases.go |
| +++ b/internal/domains/aliases.go |
| @@ -365,7 +365,7 @@ func relevantDropped(dropped []droppedClaim, routes []registry.Route, aliases [] |
| // - the label count for an instance catch-all failed |
| // - an alias, instance alias, catch-all alias, wildcard or path upsert failed |
| // - an alias, wildcard or path delete failed |
| -// - a regional_domains upsert or delete failed, or a regional row was kept |
| +// - a regional_domains set write failed, or a regional row was kept |
| // because its claim was listed but not read this pass |
| // - a listed claim yielded no claim and the pass cannot rule it out |
| // (relevantDropped: any read error, unparseable body or newer schema; a |
| @@ -755,6 +755,38 @@ func ReconcileAliasesReport(ctx context.Context, s release.Store, reg *registry. |
| if err != nil { |
| return err |
| } |
| + // One exception (#447, T4+T5 R1 P2-1): a regional claim listed but not |
| + // read this pass keeps its rows (above), and its wildcard parent stays |
| + // with them while the kept binding still serves here, i.e. the kept |
| + // apex row names a target that release.RegionalTarget accepts on the |
| + // routes this pass read, for the row's own account, app and region (the |
| + // test Reload applies to the same row), and the parent row is of that |
| + // same account and app. It counts against the per-box cap like any |
| + // other parent. Without it the parent goes, the edges file withdraws |
| + // the certificate-only entry, and the edge stops presenting the |
| + // wildcard for names the kept row still serves. |
| + keptRegional := make(map[string]registry.RegionalDomain, len(existingRegional)) |
| + for _, d := range existingRegional { |
| + keptRegional[d.Host] = d |
| + } |
| + for _, w := range existingWild { |
| + if _, ok := desiredWild[w.Host]; ok || !unread[w.Host] { |
| + continue |
| + } |
| + row, ok := keptRegional[w.Host] |
| + if !ok || row.Target == "" || row.Account != w.Account || row.App != w.App { |
| + continue |
| + } |
| + if rt, ok := byHost[row.Target]; !ok || !release.RegionalTarget(rt, row.Account, row.App, row.Region) { |
| + continue |
| + } |
| + if wildCount >= maxWildcardDomains { |
| + log.Printf("domains: wildcard %s dropped: per-box cap %d reached", w.Host, maxWildcardDomains) |
| + continue |
| + } |
| + wildCount++ |
| + desiredWild[w.Host] = w |
| + } |
| for h, w := range desiredWild { |
| cur := false |
| for _, e := range existingWild { |
| @@ -845,43 +877,70 @@ func deriveRegional(c Claim, byHost map[string]registry.Route, boxRegion string, |
| return t != "" |
| } |
| -// writeRegional brings regional_domains to desired: a row that differs (or is |
| -// missing) is upserted, and a row not desired is deleted unless its claim |
| -// (the row's host, or for "*.<apex>" the apex) is in unread, in which case it |
| -// is kept as it is. It reports whether the result is incomplete: a write |
| -// failed, or a row was kept. |
| +// writeRegional brings regional_domains to desired, one claim at a time |
| +// (#447, ruling 7). A claim's rows are its apex and, for a catch-all, |
| +// "*.<apex>"; they are grouped by the apex and written only as a whole set, |
| +// by registry.ReplaceRegionalSet in one transaction, so a box never holds |
| +// one without the other: a box holding a catch-all claim's apex holds its |
| +// star (spec §7.2), and a failed write leaves the claim's rows exactly as |
| +// they were. A claim whose rows already match is not written. A claim no |
| +// longer desired has its rows removed as a set, unless the claim (the |
| +// apex) is in unread, in which case they are kept as they are. It reports |
| +// whether the result is incomplete: a set write failed, or rows were kept. |
| func writeRegional(reg *registry.Registry, existing []registry.RegionalDomain, desired map[string]registry.RegionalDomain, unread map[string]bool) (incomplete bool) { |
| - have := make(map[string]registry.RegionalDomain, len(existing)) |
| + claimOf := func(key string) string { return strings.TrimPrefix(key, "*.") } |
| + have := map[string][]registry.RegionalDomain{} |
| for _, d := range existing { |
| - have[d.Host] = d |
| + have[claimOf(d.Host)] = append(have[claimOf(d.Host)], d) |
| } |
| - keys := make([]string, 0, len(desired)) |
| - for k := range desired { |
| - keys = append(keys, k) |
| + want := map[string][]registry.RegionalDomain{} |
| + for _, d := range desired { |
| + want[claimOf(d.Host)] = append(want[claimOf(d.Host)], d) |
| } |
| - sort.Strings(keys) |
| - for _, k := range keys { |
| - d := desired[k] |
| - if h, ok := have[k]; ok && h.Target == d.Target && h.Account == d.Account && h.App == d.App && h.Region == d.Region { |
| - continue // already the row we want: no write |
| - } |
| - if err := reg.UpsertRegional(d); err != nil { |
| - log.Printf("domains: upsert regional %s: %v", k, err) |
| - incomplete = true |
| + claims := make([]string, 0, len(have)+len(want)) |
| + for c := range want { |
| + claims = append(claims, c) |
| + } |
| + for c := range have { |
| + if _, ok := want[c]; !ok { |
| + claims = append(claims, c) |
| } |
| } |
| - for _, d := range existing { |
| - if _, ok := desired[d.Host]; ok { |
| + sort.Strings(claims) |
| + for _, c := range claims { |
| + rows, desiredHere := want[c] |
| + if !desiredHere && unread[c] { |
| + incomplete = true // kept as they are: the claim was not read |
| continue |
| } |
| - if unread[strings.TrimPrefix(d.Host, "*.")] { |
| - incomplete = true |
| - continue |
| + if regionalSetEqual(have[c], rows) { |
| + continue // already the rows we want: no write |
| } |
| - if err := reg.DeleteRegional(d.Host); err != nil { |
| - log.Printf("domains: remove regional %s: %v", d.Host, err) |
| + sort.Slice(rows, func(i, j int) bool { return rows[i].Host < rows[j].Host }) |
| + if err := reg.ReplaceRegionalSet(c, rows); err != nil { |
| + log.Printf("domains: write regional %s (%d row(s)): %v; its rows are left as they were", c, len(rows), err) |
| incomplete = true |
| } |
| } |
| return incomplete |
| } |
| + |
| +// regionalSetEqual reports whether two sets of one claim's rows hold the |
| +// same keys with the same target, account, app and region (created_at is |
| +// not part of any decision). |
| +func regionalSetEqual(a, b []registry.RegionalDomain) bool { |
| + if len(a) != len(b) { |
| + return false |
| + } |
| + byHost := make(map[string]registry.RegionalDomain, len(a)) |
| + for _, d := range a { |
| + byHost[d.Host] = d |
| + } |
| + for _, d := range b { |
| + h, ok := byHost[d.Host] |
| + if !ok || h.Target != d.Target || h.Account != d.Account || h.App != d.App || h.Region != d.Region { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
diff --git a/internal/domains/regional_derive_test.go b/internal/domains/regional_derive_test.go| index 2d99653d2..9995b6e12 100644 |
| --- a/internal/domains/regional_derive_test.go |
| +++ b/internal/domains/regional_derive_test.go |
| @@ -2,8 +2,10 @@ package domains |
| import ( |
| "context" |
| + "fmt" |
| "os" |
| "reflect" |
| + "slices" |
| "testing" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -346,15 +348,19 @@ func TestRegionalWildcardRowOnlyWhereBound(t *testing.T) { |
| } |
| // A regional row write that fails is logged and makes the pass incomplete, |
| -// as every other derived write does; the pass still returns nil. |
| +// as every other derived write does; the pass still returns nil. The claim's |
| +// rows are one set (ruling 7): a failed star write lands no apex either, and |
| +// a failed star removal leaves the pair. |
| func TestRegionalRowWriteFailureIsIncomplete(t *testing.T) { |
| for _, c := range []struct { |
| name string |
| inject func(e *aliasEnv) |
| detach bool |
| + after []string // the rows left |
| }{ |
| {name: "upsert", inject: func(e *aliasEnv) { e.failUpsert("regional_domains", "host = '"+rdStar+"'") }}, |
| - {name: "delete", inject: func(e *aliasEnv) { e.failDelete("regional_domains", "host = '"+rdStar+"'") }, detach: true}, |
| + {name: "delete", inject: func(e *aliasEnv) { e.failDelete("regional_domains", "host = '"+rdStar+"'") }, detach: true, |
| + after: []string{rdApex, rdStar}}, |
| } { |
| t.Run(c.name, func(t *testing.T) { |
| e := newAliasEnv(t) |
| @@ -371,6 +377,91 @@ func TestRegionalRowWriteFailureIsIncomplete(t *testing.T) { |
| if err != nil || rep.Complete { |
| t.Fatalf("complete=%v err=%v, want incomplete and nil", rep.Complete, err) |
| } |
| + wantRegionalRows(t, e.reg, "uk", "", c.after...) |
| + }) |
| + } |
| +} |
| + |
| +// An unread regional claim keeps its wildcard parent with its rows (#447, |
| +// T4+T5 R1 P2-1) while the kept binding still serves here: the kept apex |
| +// row's target passes release.RegionalTarget on this pass's routes, and the |
| +// parent is of the row's account and app. Otherwise it goes, as before; and |
| +// it counts against the per-box cap, read claims first. |
| +func TestRegionalWildcardParentKeptWhileClaimUnreadable(t *testing.T) { |
| + dir := release.NewDirStore(t.TempDir()) |
| + putRegional(t, dir, regionalCatchall()) |
| + for name, s := range map[string]release.Store{ |
| + "read error": unreadableKeyStore{dir, ClaimKey(rdApex)}, |
| + "not found": notFoundKeyStore{dir, ClaimKey(rdApex)}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + setup := func(t *testing.T) *registry.Registry { |
| + t.Helper() |
| + reg := aliasRegWith(t) |
| + regionalInstance(t, reg, rdUK, "uk") |
| + if rep := regionalPass(t, dir, reg, "uk", nil); !rep.Complete { |
| + t.Fatal("setup pass incomplete") |
| + } |
| + if got := wildcardHosts(t, reg); !reflect.DeepEqual(got, []string{rdApex}) { |
| + t.Fatalf("setup wildcard rows = %v", got) |
| + } |
| + return reg |
| + } |
| + |
| + t.Run("kept while the binding serves", func(t *testing.T) { |
| + reg := setup(t) |
| + for i := 0; i < 2; i++ { |
| + if rep := regionalPass(t, s, reg, "uk", nil); rep.Complete { |
| + t.Fatal("a pass that kept unread rows reported complete") |
| + } |
| + if got := wildcardHosts(t, reg); !reflect.DeepEqual(got, []string{rdApex}) { |
| + t.Fatalf("pass %d: wildcard rows = %v, want the parent kept", i, got) |
| + } |
| + } |
| + wantRegionalRows(t, reg, "uk", rdUK, rdApex, rdStar) |
| + }) |
| + |
| + t.Run("gone when the target stops qualifying", func(t *testing.T) { |
| + reg := setup(t) |
| + if err := reg.SetStatus(rdUK, "starting"); err != nil { |
| + t.Fatal(err) |
| + } |
| + regionalPass(t, s, reg, "uk", nil) |
| + if got := wildcardHosts(t, reg); len(got) != 0 { |
| + t.Fatalf("wildcard rows = %v, want the parent gone", got) |
| + } |
| + wantRegionalRows(t, reg, "uk", rdUK, rdApex, rdStar) |
| + }) |
| + |
| + t.Run("gone when the parent is another tenant's", func(t *testing.T) { |
| + reg := setup(t) |
| + if err := reg.UpsertWildcardDomain(registry.WildcardDomain{Host: rdApex, Account: "other", App: "shop"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + regionalPass(t, s, reg, "uk", nil) |
| + if got := wildcardHosts(t, reg); len(got) != 0 { |
| + t.Fatalf("wildcard rows = %v, want a parent of another account gone", got) |
| + } |
| + }) |
| + |
| + t.Run("counted against the cap", func(t *testing.T) { |
| + reg := setup(t) |
| + addRoute(t, reg, "primary.example.net", "bab", "site") |
| + for i := 0; i < maxWildcardDomains; i++ { |
| + putClaim(t, dir, Claim{Host: fmt.Sprintf("w%02d.example.net", i), Account: "bab", App: "site", |
| + Route: "primary.example.net", CreatedAt: "2026-10-29T00:00:00Z", Wildcard: true}) |
| + } |
| + t.Cleanup(func() { |
| + for i := 0; i < maxWildcardDomains; i++ { |
| + deleteClaim(t, dir, fmt.Sprintf("w%02d.example.net", i)) |
| + } |
| + }) |
| + regionalPass(t, s, reg, "uk", nil) |
| + got := wildcardHosts(t, reg) |
| + if len(got) != maxWildcardDomains || slices.Contains(got, rdApex) { |
| + t.Fatalf("wildcard rows = %d %v, want the %d read claims and not the kept parent", len(got), got, maxWildcardDomains) |
| + } |
| + }) |
| }) |
| } |
| } |
diff --git a/internal/domains/regional_guard_test.go b/internal/domains/regional_guard_test.go| new file mode 100644 |
| index 000000000..60c1b012c |
| --- /dev/null |
| +++ b/internal/domains/regional_guard_test.go |
| @@ -0,0 +1,333 @@ |
| +package domains |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "math/rand" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "strconv" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The pair guard (#447, ruling 7). For every regional claim a box has read, |
| +// its regional_domains rows exist as a whole set or not at all: a catch-all |
| +// claim's apex and "*.<apex>" both or neither, any other claim's apex alone. |
| +// Stated over a pass: |
| +// |
| +// - a claim the pass read ends with exactly the rows it desires, or with |
| +// the rows it had before the pass (a set write that failed), and then |
| +// the pass is incomplete; |
| +// - a claim listed but not read keeps its rows as they were; |
| +// - a claim no longer listed ends with no row, or (a failed removal) the |
| +// rows it had, and then the pass is incomplete; |
| +// - whatever a claim holds is one whole set: a star never without its |
| +// apex, every row of the set with the same target, account, app and |
| +// region; and once the current claim's own set has landed, exactly |
| +// that claim's keys (the pair for a catch-all, the apex otherwise). |
| +// |
| +// It runs the real derivation over a real registry, with faults injected as |
| +// triggers on the registry's own SQLite file, over seeded random sequences of |
| +// claim sets (created, detached, recreated with other capabilities), target |
| +// routes (qualifying, not ready, gone), unreadable claims and failing writes. |
| +// CARLOS_REGIONAL_GUARD_SEED replays one seed; every failure prints it. |
| + |
| +// guardClaims are the regional claims a run draws from. www.shop.example.com |
| +// sits under shop.example.com's star: a separate claim whose rows must never |
| +// be mixed up with the star row. |
| +var guardClaims = []struct{ apex, uk string }{ |
| + {"shop.example.com", "shop-uk.example.net"}, |
| + {"www.shop.example.com", "www-uk.example.net"}, |
| + {"shop.example.net", "net-uk.example.net"}, |
| +} |
| + |
| +// guardStore is the deployment bucket with some claim reads failing this |
| +// pass: a read error, or a not-found for a listed key. |
| +type guardStore struct { |
| + *release.DirStore |
| + fail map[string]error |
| +} |
| + |
| +func (s guardStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if err, ok := s.fail[key]; ok { |
| + return nil, "", err |
| + } |
| + return s.DirStore.Get(ctx, key) |
| +} |
| + |
| +type guardRows = map[string]registry.RegionalDomain // key -> row, created_at zeroed |
| + |
| +func guardRowsByClaim(t *testing.T, reg *registry.Registry) map[string]guardRows { |
| + t.Helper() |
| + rows, err := reg.ListRegional() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out := map[string]guardRows{} |
| + for _, d := range rows { |
| + d.CreatedAt = 0 |
| + apex := d.Host |
| + if len(apex) > 2 && apex[:2] == "*." { |
| + apex = apex[2:] |
| + } |
| + if out[apex] == nil { |
| + out[apex] = guardRows{} |
| + } |
| + out[apex][d.Host] = d |
| + } |
| + return out |
| +} |
| + |
| +func guardEqual(a, b guardRows) bool { |
| + if len(a) == 0 && len(b) == 0 { |
| + return true |
| + } |
| + return reflect.DeepEqual(a, b) |
| +} |
| + |
| +func TestRegionalRowsPairOrNothingUnderFaults(t *testing.T) { |
| + seed := time.Now().UnixNano() |
| + if v := os.Getenv("CARLOS_REGIONAL_GUARD_SEED"); v != "" { |
| + n, err := strconv.ParseInt(v, 10, 64) |
| + if err != nil { |
| + t.Fatalf("CARLOS_REGIONAL_GUARD_SEED=%q: %v", v, err) |
| + } |
| + seed = n |
| + } |
| + t.Logf("seed %d (replay with CARLOS_REGIONAL_GUARD_SEED=%d)", seed, seed) |
| + const runs, steps = 30, 10 |
| + start := time.Now() |
| + var held, kept, removedHeld int |
| + for run := 0; run < runs; run++ { |
| + h, k, r := guardRun(t, seed, run, steps) |
| + held, kept, removedHeld = held+h, kept+k, removedHeld+r |
| + if t.Failed() { |
| + return |
| + } |
| + } |
| + t.Logf("%d runs x %d passes in %s: %d set writes failed and held the old rows, %d unread claims kept rows, %d failed removals held rows", |
| + runs, steps, time.Since(start).Round(time.Millisecond), held, kept, removedHeld) |
| + // The faults must actually bite, or the guard proves nothing. (A failed |
| + // removal is rarer, a few per run of the test; it is reported above, |
| + // not required, so the test cannot flake on it.) |
| + if held == 0 || kept == 0 { |
| + t.Fatalf("seed %d: a fault class never fired (held %d, kept %d)", seed, held, kept) |
| + } |
| +} |
| + |
| +func guardRun(t *testing.T, seed int64, run, steps int) (held, kept, removedHeld int) { |
| + t.Helper() |
| + rng := rand.New(rand.NewSource(seed + int64(run))) |
| + fail := func(step int, format string, args ...any) { |
| + t.Helper() |
| + t.Fatalf("seed %d run %d step %d: %s (replay with CARLOS_REGIONAL_GUARD_SEED=%d)", |
| + seed, run, step, fmt.Sprintf(format, args...), seed) |
| + } |
| + dir := release.NewDirStore(t.TempDir()) |
| + path := filepath.Join(t.TempDir(), "registry.db") |
| + reg, err := registry.Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reg.Close() |
| + db, err := sql.Open("sqlite", path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + // One connection, unsynced: the trigger DDL is the fault injector's |
| + // own bookkeeping, and an fsync per trigger would dominate the run. |
| + db.SetMaxOpenConns(1) |
| + if _, err := db.Exec("PRAGMA busy_timeout=5000"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := db.Exec("PRAGMA synchronous=OFF"); err != nil { |
| + t.Fatal(err) |
| + } |
| + var triggers []string |
| + |
| + type state struct { |
| + claim *Claim // nil: not in the bucket |
| + rev int // the claim's revision: bumped on every create |
| + route int // 0 gone, 1 qualifying, 2 not ready |
| + } |
| + st := make([]state, len(guardClaims)) |
| + wroteRev := map[string]int{} // apex -> the revision whose whole set landed |
| + rev := 0 |
| + |
| + for step := 0; step < steps; step++ { |
| + // The world moves. |
| + for i, g := range guardClaims { |
| + // Detach, and maybe recreate in the same step with fresh |
| + // capabilities (ruling 6: the only way they change). |
| + if st[i].claim != nil && rng.Intn(5) == 0 { |
| + deleteClaim(t, dir, g.apex) |
| + st[i].claim = nil |
| + } |
| + if st[i].claim == nil && rng.Intn(3) > 0 { |
| + rev++ |
| + c := Claim{ |
| + Schema: 2, Host: g.apex, Account: "bab", App: "shop", Route: "home-" + g.uk, |
| + CreatedAt: "2026-10-29T00:00:00Z", CreatedBy: "owner@example.com", |
| + Placements: []Placement{{Region: "", Host: "home-" + g.uk}, {Region: "uk", Host: g.uk}}, |
| + } |
| + c.Wildcard = rng.Intn(2) == 0 |
| + c.Catchall = c.Wildcard && rng.Intn(3) > 0 |
| + putRegional(t, dir, c) |
| + st[i].claim, st[i].rev = &c, rev |
| + } |
| + if r := rng.Intn(3); r != st[i].route { |
| + st[i].route = r |
| + switch r { |
| + case 0: |
| + if err := reg.Delete(g.uk); err != nil { |
| + t.Fatal(err) |
| + } |
| + default: |
| + status := "ready" |
| + if r == 2 { |
| + status = "starting" |
| + } |
| + regionalInstance(t, reg, g.uk, "uk", func(rt *registry.Route) { rt.Status = status }) |
| + } |
| + } |
| + } |
| + // Faults for this pass: clear the last pass's, then fail some |
| + // writes of some keys. |
| + for _, name := range triggers { |
| + if _, err := db.Exec("DROP TRIGGER " + name); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + triggers = triggers[:0] |
| + for n := rng.Intn(4); n > 0; n-- { |
| + g := guardClaims[rng.Intn(len(guardClaims))] |
| + key := g.apex |
| + if rng.Intn(2) == 0 { |
| + key = "*." + g.apex |
| + } |
| + event, row := [...]string{"INSERT", "UPDATE", "DELETE"}[rng.Intn(3)], "NEW" |
| + if event == "DELETE" { |
| + row = "OLD" |
| + } |
| + name := fmt.Sprintf("inject_guard_%d", len(triggers)) |
| + q := fmt.Sprintf("CREATE TRIGGER %s BEFORE %s ON regional_domains WHEN %s.host = '%s' BEGIN SELECT RAISE(FAIL, 'injected'); END", |
| + name, event, row, key) |
| + if _, err := db.Exec(q); err != nil { |
| + t.Fatalf("%s: %v", q, err) |
| + } |
| + triggers = append(triggers, name) |
| + } |
| + unread := map[string]bool{} |
| + store := guardStore{DirStore: dir, fail: map[string]error{}} |
| + for i, g := range guardClaims { |
| + if st[i].claim == nil || rng.Intn(4) > 0 { |
| + continue |
| + } |
| + unread[g.apex] = true |
| + if rng.Intn(2) == 0 { |
| + store.fail[ClaimKey(g.apex)] = errors.New("synthetic 403") |
| + } else { |
| + store.fail[ClaimKey(g.apex)] = os.ErrNotExist |
| + } |
| + } |
| + |
| + before := guardRowsByClaim(t, reg) |
| + rep := AliasReport{Complete: true, Region: "uk"} |
| + if err := ReconcileAliasesReport(context.Background(), store, reg, aliasNow(), map[string]bool{}, nil, &rep); err != nil { |
| + fail(step, "pass: %v", err) |
| + } |
| + after := guardRowsByClaim(t, reg) |
| + |
| + for apex, rows := range after { |
| + star := "*." + apex |
| + if _, ok := rows[star]; ok { |
| + if _, ok := rows[apex]; !ok { |
| + fail(step, "%s holds its star without its apex: %+v", apex, rows) |
| + } |
| + } |
| + var first *registry.RegionalDomain |
| + for _, d := range rows { |
| + if d.Host != apex && d.Host != star { |
| + fail(step, "row %s grouped under %s", d.Host, apex) |
| + } |
| + if first == nil { |
| + d := d |
| + first = &d |
| + } else if d.Target != first.Target || d.Account != first.Account || d.App != first.App || d.Region != first.Region { |
| + fail(step, "%s's rows disagree: %+v", apex, rows) |
| + } |
| + } |
| + known := false |
| + for _, g := range guardClaims { |
| + known = known || g.apex == apex |
| + } |
| + if !known { |
| + fail(step, "rows for %s, which no claim ever named: %+v", apex, rows) |
| + } |
| + } |
| + |
| + for i, g := range guardClaims { |
| + b, a := before[g.apex], after[g.apex] |
| + c := st[i].claim |
| + switch { |
| + case c != nil && !unread[g.apex]: // read this pass |
| + target := "" |
| + if st[i].route == 1 { |
| + target = g.uk |
| + } |
| + want := guardRows{g.apex: {Host: g.apex, Target: target, Account: "bab", App: "shop", Region: "uk"}} |
| + if c.Wildcard && c.Catchall { |
| + want["*."+g.apex] = registry.RegionalDomain{Host: "*." + g.apex, Target: target, Account: "bab", App: "shop", Region: "uk"} |
| + } |
| + switch { |
| + case guardEqual(a, want): |
| + wroteRev[g.apex] = st[i].rev |
| + case guardEqual(a, b): |
| + held++ |
| + if rep.Complete { |
| + fail(step, "%s read but its set did not land (%+v, want %+v) and the pass reported complete", g.apex, a, want) |
| + } |
| + default: |
| + fail(step, "%s read: rows %+v are neither the desired set %+v nor the rows before the pass %+v", g.apex, a, want, b) |
| + } |
| + if len(a) > 0 && wroteRev[g.apex] == st[i].rev { |
| + _, hasStar := a["*."+g.apex] |
| + if hasStar != (c.Wildcard && c.Catchall) || len(a) != len(want) { |
| + fail(step, "%s (catch-all %v) holds %+v: not its pair", g.apex, c.Wildcard && c.Catchall, a) |
| + } |
| + } |
| + case c != nil: // listed, not read |
| + if !guardEqual(a, b) { |
| + fail(step, "%s unread: rows moved %+v -> %+v", g.apex, b, a) |
| + } |
| + if len(b) > 0 { |
| + kept++ |
| + } |
| + if len(b) > 0 && rep.Complete { |
| + fail(step, "%s unread with rows kept and the pass reported complete", g.apex) |
| + } |
| + default: // not listed |
| + switch { |
| + case len(a) == 0: |
| + delete(wroteRev, g.apex) |
| + case guardEqual(a, b): |
| + removedHeld++ |
| + if rep.Complete { |
| + fail(step, "%s detached, rows %+v left and the pass reported complete", g.apex, a) |
| + } |
| + default: |
| + fail(step, "%s detached: rows %+v are neither none nor the rows before %+v", g.apex, a, b) |
| + } |
| + } |
| + } |
| + } |
| + return held, kept, removedHeld |
| +} |
diff --git a/internal/edge/regional_cert_test.go b/internal/edge/regional_cert_test.go| new file mode 100644 |
| index 000000000..53a879d60 |
| --- /dev/null |
| +++ b/internal/edge/regional_cert_test.go |
| @@ -0,0 +1,109 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "slices" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/crypto/acme/autocert" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// TestRegionalWildcardCertSurvivesAnUnreadableClaim (#447, T4+T5 R1 P2-1): |
| +// betty, the uk box, serves the regional catch-all from its bound target, |
| +// and the claim's wildcard parent comes from her own wildcard_domains row; |
| +// annie's edges file carries no parent for it (annie has no bound target). |
| +// The claim then becomes unreadable. Through the real derivation, the real |
| +// wildcard manager built from the environment and a refreshed home map, the |
| +// parent stays while the kept row still serves here, so the loaded wildcard |
| +// certificate keeps answering names under the claim; once the target stops |
| +// qualifying, the row denies and the parent goes with it. |
| +func TestRegionalWildcardCertSurvivesAnUnreadableClaim(t *testing.T) { |
| + reg := openReg(t) |
| + if err := reg.Upsert(rgInstance(rgTuk, "/run/carlos/"+rgTuk+".sock", rgApp, "uk")); err != nil { |
| + t.Fatal(err) |
| + } |
| + store := release.NewDirStore(t.TempDir()) |
| + rgWriteClaim(t, store, rgClaim()) |
| + unreadable := rgUnreadableStore{store, domains.ClaimKey(rgApex)} |
| + putJSON(t, store, "control/edges/annie.json", |
| + `{"v":1,"box":"annie","eip":"127.0.0.1","hosts":{"site.example.net":{"role":"home","platform":true,"account":"abc","app":"site"}}}`) |
| + |
| + if rep := rgPass(t, store, reg, "uk"); !rep.Complete { |
| + t.Fatal("setup pass incomplete") |
| + } |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + e.staticStore = store |
| + WithBoxLabel("betty")(e) |
| + homes := e.newHomeMap() |
| + refreshHomeMap(t, homes) |
| + e.homes.Store(homes) |
| + |
| + t.Setenv("CARLOS_WILDCARD_DOMAINS", "") |
| + t.Setenv("PLATFORM_APPS_DOMAIN", "apps.test") |
| + t.Setenv("CARLOS_DNS_PROVIDER", "route53") |
| + t.Setenv("CARLOS_ACME_DELEGATION_ZONE", "acme.apps.test") |
| + cache := autocert.DirCache(t.TempDir()) |
| + cert, key := selfSignedWildcard(t, rgApex, time.Now().Add(60*24*time.Hour)) |
| + pem, err := encodeWildcardPEM(cert, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cache.Put(context.Background(), wildcardPEMKey(rgApex), pem); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := newWildcardFromEnv(e, cache) |
| + if w == nil { |
| + t.Fatal("want a manager") |
| + } |
| + w.refresh() |
| + if !w.loadCached(context.Background(), rgApex) { |
| + t.Fatal("the cached wildcard did not load") |
| + } |
| + |
| + // refreshed is the production refresh order after a pass: the edge |
| + // reloads its map, the home map re-reads every box's edges file, and the |
| + // manager recomputes its parents from both. |
| + refreshed := func(stage string, wantParent bool) { |
| + t.Helper() |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + refreshHomeMap(t, homes) |
| + w.refresh() |
| + if got := slices.Contains(w.currentParents(), rgApex); got != wantParent { |
| + t.Errorf("%s: %s in the parent set = %v, want %v (parents %v)", stage, rgApex, got, wantParent, w.currentParents()) |
| + } |
| + if got := w.certFor(rgUnder) != nil; got != wantParent { |
| + t.Errorf("%s: certFor(%s) presented the wildcard = %v, want %v", stage, rgUnder, got, wantParent) |
| + } |
| + mode := regionalDeny |
| + if wantParent { |
| + mode = regionalServe |
| + } |
| + if got := e.current()[rgStar].regional; got != mode { |
| + t.Errorf("%s: the star entry is %v, want %v", stage, got, mode) |
| + } |
| + } |
| + refreshed("readable", true) |
| + |
| + for i := 0; i < 2; i++ { |
| + if rep := rgPass(t, unreadable, reg, "uk"); rep.Complete { |
| + t.Error("a pass that could not read the claim reported complete") |
| + } |
| + refreshed("unreadable", true) |
| + } |
| + |
| + if err := reg.SetStatus(rgTuk, "starting"); err != nil { |
| + t.Fatal(err) |
| + } |
| + rgPass(t, unreadable, reg, "uk") |
| + refreshed("unreadable, target not ready", false) |
| +} |
diff --git a/internal/edge/regional_fault_test.go b/internal/edge/regional_fault_test.go| new file mode 100644 |
| index 000000000..f4d571d7d |
| --- /dev/null |
| +++ b/internal/edge/regional_fault_test.go |
| @@ -0,0 +1,197 @@ |
| +package edge |
| + |
| +import ( |
| + "database/sql" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// TestRegionalStarWriteFailureLeavesNoHalfClaim is ruling 7's witness |
| +// (#447, T4+T5 R1 P1-1). A uk box serves the claim's uk target from a |
| +// socket and holds a hand route at "*.shop.example.com" whose TCP backend |
| +// on 127.0.0.1 counts every connection it accepts. The claim is a regional |
| +// catch-all. Its first derivation on this box fails the star's INSERT, |
| +// injected as a trigger on the registry's own SQLite file (no fake |
| +// registry), then the box restarts from the same file, reads the claim as |
| +// unreadable, reads it again with the fault still in place, and finally |
| +// writes once the fault clears. |
| +// |
| +// What it pins, at every stage: the box holds the claim's apex and star |
| +// rows both or neither, and while it holds them alice.shop.example.com |
| +// never reaches the hand route's backend. A failed set write changes |
| +// nothing, so while the write keeps failing the box answers exactly as it |
| +// did before it read the claim (the hand route still answers the star |
| +// match there: spec §10.5's class of a box that has not derived the claim, |
| +// which ends at its first successful derivation, stage 4). Against the old |
| +// per-row writes stage 1 leaves the apex alone and the hand route answers |
| +// alice on a box that holds the claim's apex. |
| +func TestRegionalStarWriteFailureLeavesNoHalfClaim(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "registry.db") |
| + reg, err := registry.Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tuk := rgSocketBackend(t, shortSockDir(t), "tuk") |
| + if err := reg.Upsert(rgInstance(rgTuk, tuk.sock, rgApp, "uk")); err != nil { |
| + t.Fatal(err) |
| + } |
| + addr, accepts := rgTCPCounter(t) |
| + if err := reg.Upsert(registry.Route{Host: rgStar, Kind: "service", Addr: addr, Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + store := release.NewDirStore(t.TempDir()) |
| + rgWriteClaim(t, store, rgClaim()) |
| + unreadable := rgUnreadableStore{store, domains.ClaimKey(rgApex)} |
| + |
| + var e *Edge |
| + var srv *httptest.Server |
| + up := false |
| + boot := func() { |
| + t.Helper() |
| + var err error |
| + if e, err = New(reg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + srv = httptest.NewServer(e) |
| + up = true |
| + } |
| + shutdown := func() { |
| + if !up { |
| + return |
| + } |
| + up = false |
| + srv.Close() |
| + e.probers.Stop() |
| + reg.Close() |
| + } |
| + t.Cleanup(func() { shutdown() }) |
| + restart := func() { |
| + t.Helper() |
| + shutdown() |
| + var err error |
| + if reg, err = registry.Open(path); err != nil { |
| + t.Fatal(err) |
| + } |
| + boot() |
| + } |
| + boot() |
| + |
| + // The pre-read answer for alice: the hand route (a 502, its backend |
| + // closes every connection it accepts). |
| + baseline, _ := rgGet(t, srv, rgUnder) |
| + if accepts.Load() != 1 { |
| + t.Fatalf("precondition: the hand route's backend accepted %d, want 1", accepts.Load()) |
| + } |
| + |
| + // check asserts the pair rule and answers for alice (and the apex) as |
| + // the rows say; it returns whether the box holds the claim. |
| + check := func(stage string) bool { |
| + t.Helper() |
| + rows := rgRows(t, reg) |
| + _, apex := rows[rgApex] |
| + _, star := rows[rgStar] |
| + if apex != star { |
| + t.Errorf("%s: the box holds apex=%v star=%v: half a claim (rows %+v)", stage, apex, star, rows) |
| + } |
| + before := accepts.Load() |
| + code, _ := rgGet(t, srv, rgUnder) |
| + reached := accepts.Load() - before |
| + if apex || star { |
| + if code != http.StatusServiceUnavailable || reached != 0 { |
| + t.Errorf("%s: the box holds the claim's rows and %s answered %d, the hand route's backend accepted %d, want 503 and none", |
| + stage, rgUnder, code, reached) |
| + } |
| + if code, body := rgGet(t, srv, rgApex); code != http.StatusOK || body != "tuk" { |
| + t.Errorf("%s: %s = %d %q, want 200 tuk", stage, rgApex, code, body) |
| + } |
| + return true |
| + } |
| + if code != baseline { |
| + t.Errorf("%s: the box holds no row and %s answered %d, want %d as before it read the claim", stage, rgUnder, code, baseline) |
| + } |
| + return false |
| + } |
| + reload := func() { |
| + t.Helper() |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + |
| + db, err := sql.Open("sqlite", path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { db.Close() }) |
| + for _, q := range []string{ |
| + "PRAGMA busy_timeout=5000", |
| + "CREATE TRIGGER inject_star BEFORE INSERT ON regional_domains WHEN NEW.host = '" + rgStar + |
| + "' BEGIN SELECT RAISE(FAIL, 'injected'); END", |
| + } { |
| + if _, err := db.Exec(q); err != nil { |
| + t.Fatalf("%s: %v", q, err) |
| + } |
| + } |
| + |
| + // 1. The first derivation reads the claim and its star write fails. |
| + if rep := rgPass(t, store, reg, "uk"); rep.Complete { |
| + t.Error("1: a pass whose star write failed reported complete") |
| + } |
| + reload() |
| + if check("1 star write failed") { |
| + t.Error("1: rows landed although the star write failed") |
| + } |
| + |
| + // 2. A restart from the same registry, and a pass that cannot read the |
| + // claim: the same rows (none), the same answers. |
| + restart() |
| + if rep := rgPass(t, unreadable, reg, "uk"); rep.Complete { |
| + t.Error("2: a pass that could not read the claim reported complete") |
| + } |
| + reload() |
| + check("2 restarted, claim unreadable") |
| + |
| + // 3. The claim readable again, the fault still there. |
| + if rep := rgPass(t, store, reg, "uk"); rep.Complete { |
| + t.Error("3: a pass whose star write failed reported complete") |
| + } |
| + reload() |
| + check("3 claim readable, fault still there") |
| + |
| + // 4. The fault clears: the first successful derivation writes both |
| + // rows, and from here the hand route never answers alice. |
| + if _, err := db.Exec("DROP TRIGGER inject_star"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rep := rgPass(t, store, reg, "uk"); !rep.Complete { |
| + t.Error("4: a clean pass reported incomplete") |
| + } |
| + reload() |
| + if !check("4 fault cleared") { |
| + t.Fatal("4: a clean pass wrote no row") |
| + } |
| + held := accepts.Load() |
| + |
| + // 5. Restart again and lose the claim's body: the pair is kept and |
| + // still denies the hand route. |
| + restart() |
| + if !check("5 restarted") { |
| + t.Error("5: the restarted box lost the rows") |
| + } |
| + if rep := rgPass(t, unreadable, reg, "uk"); rep.Complete { |
| + t.Error("5: a pass that kept unread rows reported complete") |
| + } |
| + reload() |
| + if !check("5 restarted, claim unreadable") { |
| + t.Error("5: an unreadable pass dropped the kept rows") |
| + } |
| + if n := accepts.Load(); n != held { |
| + t.Errorf("the hand route's backend accepted %d connection(s) after the box first held the claim, want none", n-held) |
| + } |
| +} |
diff --git a/internal/host/edgesfile_test.go b/internal/host/edgesfile_test.go| index f65e71fdd..3172d3819 100644 |
| --- a/internal/host/edgesfile_test.go |
| +++ b/internal/host/edgesfile_test.go |
| @@ -2361,6 +2361,25 @@ var regionalBoxGoldens = []struct { |
| // the box in its region. It returns the published hosts block raw and |
| // parsed. |
| func regionalEdgesHosts(t *testing.T, box, region, target string) (json.RawMessage, map[string]edgeHost) { |
| + t.Helper() |
| + return regionalEdgesHostsAfter(t, box, region, target, 0) |
| +} |
| + |
| +// regionalClaimUnreadable is the deployment bucket with the regional claim's |
| +// GET failing while the listing still shows it (spec §7.2's unread claim). |
| +type regionalClaimUnreadable struct{ release.Store } |
| + |
| +func (s regionalClaimUnreadable) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == domains.ClaimKey("shop.example.com") { |
| + return nil, "", errors.New("synthetic 403") |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| + |
| +// regionalEdgesHostsAfter is regionalEdgesHosts with unreadPasses more alias |
| +// passes, each unable to read the claim, between the first pass and the |
| +// write. |
| +func regionalEdgesHostsAfter(t *testing.T, box, region, target string, unreadPasses int) (json.RawMessage, map[string]edgeHost) { |
| t.Helper() |
| ctx := context.Background() |
| s := release.NewDirStore(t.TempDir()) |
| @@ -2389,6 +2408,11 @@ func regionalEdgesHosts(t *testing.T, box, region, target string) (json.RawMessa |
| if err := aliasPassReporting(ctx, s, reg, nil, newAssetAuthority(nil), region); err != nil { |
| t.Fatalf("alias pass: %v", err) |
| } |
| + for i := 0; i < unreadPasses; i++ { |
| + if err := aliasPassReporting(ctx, regionalClaimUnreadable{s}, reg, nil, newAssetAuthority(nil), region); err != nil { |
| + t.Fatalf("unread alias pass: %v", err) |
| + } |
| + } |
| var last []byte |
| if err := edgesFileWrite(ctx, s, reg, edgesFile{Box: box}, "1.2.3.4", &last, false); err != nil { |
| t.Fatal(err) |
| @@ -2465,6 +2489,30 @@ func TestEdgesFileNeverPublishesRegionalNames(t *testing.T) { |
| } |
| }) |
| } |
| + // (#447, T4+T5 R1 P2-1) After passes that cannot read the claim, a |
| + // bound box still publishes the same block, the certificate-only |
| + // wildcard entry included, so every box keeps loading the parent's PEM |
| + // for the names the kept rows serve. internal/edge's |
| + // TestRegionalWildcardCertSurvivesAnUnreadableClaim is the reader half. |
| + for _, b := range regionalBoxGoldens { |
| + t.Run(b.box+" after unread passes", func(t *testing.T) { |
| + raw, _ := regionalEdgesHostsAfter(t, b.box, b.region, b.target, 2) |
| + golden, err := os.ReadFile(filepath.Join("..", "edgesfile", "testdata", b.golden)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var want, got bytes.Buffer |
| + if err := json.Compact(&want, golden); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := json.Compact(&got, raw); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !bytes.Equal(got.Bytes(), want.Bytes()) { |
| + t.Fatalf("hosts block after unread passes =\n%s\nwant (golden %s)\n%s", got.Bytes(), b.golden, want.Bytes()) |
| + } |
| + }) |
| + } |
| t.Run("unbound", func(t *testing.T) { |
| _, hosts := regionalEdgesHosts(t, "carol", "de", "") |
| for _, k := range []string{apex, star} { |
diff --git a/internal/registry/regional_test.go b/internal/registry/regional_test.go| index fd4b42c38..e84590c4f 100644 |
| --- a/internal/registry/regional_test.go |
| +++ b/internal/registry/regional_test.go |
| @@ -1,15 +1,18 @@ |
| package registry |
| import ( |
| + "database/sql" |
| + "path/filepath" |
| "reflect" |
| + "strings" |
| "testing" |
| ) |
| // TestRegionalDomainsTable pins the regional_domains table (#447, spec §7.2) |
| // on a local registry and over the remote transport the root passes use: |
| -// upsert, an ordered list, a Fingerprint that moves on what the edge reads |
| -// (host, target, account, app, region) and not on created_at, and an |
| -// idempotent delete. |
| +// a claim's rows written as one set, an ordered list, a Fingerprint that |
| +// moves on what the edge reads (host, target, account, app, region) and not |
| +// on created_at, and an idempotent empty set that removes a claim's rows. |
| func TestRegionalDomainsTable(t *testing.T) { |
| local := openTestRegistry(t) |
| t.Cleanup(func() { local.Close() }) |
| @@ -40,6 +43,12 @@ func regionalTableCase(t *testing.T, reg *Registry) { |
| } |
| return got |
| } |
| + set := func(host string, rows ...RegionalDomain) { |
| + t.Helper() |
| + if err := reg.ReplaceRegionalSet(host, rows); err != nil { |
| + t.Fatalf("ReplaceRegionalSet(%s): %v", host, err) |
| + } |
| + } |
| empty := fp() |
| if got := list(); len(got) != 0 { |
| t.Fatalf("a fresh registry lists %+v", got) |
| @@ -48,11 +57,8 @@ func regionalTableCase(t *testing.T, reg *Registry) { |
| star := RegionalDomain{Host: "*.shop.example.com", Target: "shop-uk.example.net", Account: "abc", App: "shop", Region: "uk", CreatedAt: 100} |
| apex := RegionalDomain{Host: "shop.example.com", Target: "shop-uk.example.net", Account: "abc", App: "shop", Region: "uk", CreatedAt: 100} |
| deny := RegionalDomain{Host: "cafe.example.com", Account: "abc", App: "cafe", Region: "uk", CreatedAt: 100} |
| - for _, d := range []RegionalDomain{apex, star, deny} { |
| - if err := reg.UpsertRegional(d); err != nil { |
| - t.Fatalf("UpsertRegional(%s): %v", d.Host, err) |
| - } |
| - } |
| + set(apex.Host, apex, star) |
| + set(deny.Host, deny) |
| // Ordered by host: "*" sorts before letters. |
| if got, want := list(), []RegionalDomain{star, deny, apex}; !reflect.DeepEqual(got, want) { |
| t.Fatalf("ListRegional =\n%+v\nwant\n%+v", got, want) |
| @@ -62,18 +68,16 @@ func regionalTableCase(t *testing.T, reg *Registry) { |
| t.Fatal("Fingerprint blind to new regional_domains rows") |
| } |
| - // A re-upsert with only a new created_at: same digest, and created_at |
| + // A rewrite with only a new created_at: same digest, and created_at |
| // itself is kept (ON CONFLICT updates target, account, app, region only). |
| - again := apex |
| - again.CreatedAt = 999 |
| - if err := reg.UpsertRegional(again); err != nil { |
| - t.Fatal(err) |
| - } |
| + again, againStar := apex, star |
| + again.CreatedAt, againStar.CreatedAt = 999, 999 |
| + set(apex.Host, again, againStar) |
| if got := fp(); got != withRows { |
| - t.Fatalf("Fingerprint moved on a created_at-only re-upsert: %s -> %s", withRows, got) |
| + t.Fatalf("Fingerprint moved on a created_at-only rewrite: %s -> %s", withRows, got) |
| } |
| - if got := list()[2]; got.CreatedAt != 100 { |
| - t.Fatalf("re-upsert rewrote created_at: %+v", got) |
| + if got := list(); got[0].CreatedAt != 100 || got[2].CreatedAt != 100 { |
| + t.Fatalf("rewrite changed created_at: %+v", got) |
| } |
| // Each field the edge reads moves the digest. |
| @@ -87,37 +91,183 @@ func regionalTableCase(t *testing.T, reg *Registry) { |
| {"region", func(d *RegionalDomain) { d.Region = "" }}, |
| } { |
| before := fp() |
| - d := apex |
| + d, ds := apex, star |
| mod.set(&d) |
| - if err := reg.UpsertRegional(d); err != nil { |
| - t.Fatal(err) |
| - } |
| + mod.set(&ds) |
| + set(apex.Host, d, ds) |
| if fp() == before { |
| t.Fatalf("Fingerprint blind to a %s change", mod.field) |
| } |
| - got := list()[2] |
| - d.CreatedAt = 100 |
| - if got != d { |
| - t.Fatalf("after a %s change the row is %+v, want %+v", mod.field, got, d) |
| - } |
| - if err := reg.UpsertRegional(apex); err != nil { |
| - t.Fatal(err) |
| + d.CreatedAt, ds.CreatedAt = 100, 100 |
| + if got := list(); got[0] != ds || got[2] != d { |
| + t.Fatalf("after a %s change the rows are %+v, want %+v and %+v", mod.field, got, ds, d) |
| } |
| + set(apex.Host, apex, star) |
| } |
| if got := fp(); got != withRows { |
| - t.Fatalf("Fingerprint after restoring the row = %s, want %s", got, withRows) |
| + t.Fatalf("Fingerprint after restoring the rows = %s, want %s", got, withRows) |
| } |
| - // Delete is idempotent, and removing every row restores the empty digest. |
| - for _, h := range []string{star.Host, deny.Host, apex.Host, apex.Host, "never.example.com"} { |
| - if err := reg.DeleteRegional(h); err != nil { |
| - t.Fatalf("DeleteRegional(%s): %v", h, err) |
| - } |
| + // A smaller set removes the claim's other key in the same write; other |
| + // claims' rows are untouched. |
| + set(apex.Host, apex) |
| + if got, want := list(), []RegionalDomain{deny, apex}; !reflect.DeepEqual(got, want) { |
| + t.Fatalf("after the apex-only set ListRegional = %+v, want %+v", got, want) |
| + } |
| + set(apex.Host, apex, star) |
| + |
| + // The empty set removes a claim's rows and is idempotent, and removing |
| + // every row restores the empty digest. |
| + for _, h := range []string{apex.Host, deny.Host, apex.Host, "never.example.com"} { |
| + set(h) |
| } |
| if got := list(); len(got) != 0 { |
| - t.Fatalf("after deletes ListRegional = %+v", got) |
| + t.Fatalf("after the empty sets ListRegional = %+v", got) |
| } |
| if got := fp(); got != empty { |
| t.Fatalf("Fingerprint after add+remove = %s, want back to %s", got, empty) |
| } |
| } |
| + |
| +// TestReplaceRegionalSetRefusesForeignKeys: a set holds only its claim's |
| +// keys (the apex and "*.<apex>"); any other key refuses the whole set and |
| +// writes nothing, so one claim's write can never touch another's rows. |
| +func TestReplaceRegionalSetRefusesForeignKeys(t *testing.T) { |
| + local := openTestRegistry(t) |
| + t.Cleanup(func() { local.Close() }) |
| + remote, _ := remoteTestRegistry(t) |
| + for _, c := range []struct { |
| + name string |
| + reg *Registry |
| + }{{"local", local}, {"remote", remote}} { |
| + t.Run(c.name, func(t *testing.T) { |
| + apex := RegionalDomain{Host: "shop.example.com", Account: "abc", App: "shop"} |
| + for _, rows := range [][]RegionalDomain{ |
| + {apex, {Host: "cafe.example.com"}}, |
| + {apex, {Host: "*.cafe.example.com"}}, |
| + {apex, {Host: "a.shop.example.com"}}, |
| + {apex, apex}, |
| + } { |
| + if err := c.reg.ReplaceRegionalSet("shop.example.com", rows); err == nil { |
| + t.Errorf("set %+v accepted", rows) |
| + } |
| + } |
| + if err := c.reg.ReplaceRegionalSet("", nil); err == nil { |
| + t.Error("a set with no claim host accepted") |
| + } |
| + if got, err := c.reg.ListRegional(); err != nil || len(got) != 0 { |
| + t.Fatalf("a refused set wrote %+v (%v)", got, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestReplaceRegionalSetIsAtomic (#447 ruling 7): a claim's apex and star |
| +// rows are one transaction. A failure on any row, injected at the SQL level |
| +// on the registry's own file, leaves the claim's rows exactly as they were |
| +// (none on a first write, the old pair on a rewrite or a removal), on a |
| +// local registry and through the remote transport. |
| +func TestReplaceRegionalSetIsAtomic(t *testing.T) { |
| + localPath := filepath.Join(t.TempDir(), "registry.db") |
| + local, err := Open(localPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { local.Close() }) |
| + remote, remotePath := remoteTestRegistry(t) |
| + for _, c := range []struct { |
| + name string |
| + reg *Registry |
| + path string |
| + }{{"local", local, localPath}, {"remote", remote, remotePath}} { |
| + t.Run(c.name, func(t *testing.T) { |
| + apex := RegionalDomain{Host: "shop.example.com", Target: "shop-uk.example.net", Account: "abc", App: "shop", Region: "uk", CreatedAt: 100} |
| + star := apex |
| + star.Host = "*.shop.example.com" |
| + list := func() []RegionalDomain { |
| + t.Helper() |
| + got, err := c.reg.ListRegional() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return got |
| + } |
| + |
| + // First write, the star's INSERT fails: neither row. |
| + drop := injectRegionalFault(t, c.path, "INSERT", "NEW.host = '*.shop.example.com'") |
| + if err := c.reg.ReplaceRegionalSet(apex.Host, []RegionalDomain{apex, star}); err == nil { |
| + t.Fatal("a set whose star write failed reported success") |
| + } |
| + if got := list(); len(got) != 0 { |
| + t.Fatalf("a failed first set left %+v, want no row", got) |
| + } |
| + drop() |
| + if err := c.reg.ReplaceRegionalSet(apex.Host, []RegionalDomain{apex, star}); err != nil { |
| + t.Fatal(err) |
| + } |
| + pair := list() |
| + if len(pair) != 2 { |
| + t.Fatalf("rows = %+v, want the pair", pair) |
| + } |
| + |
| + // Rewrite to deny, the star's UPDATE fails: the old pair stays. |
| + drop = injectRegionalFault(t, c.path, "UPDATE", "NEW.host = '*.shop.example.com'") |
| + da, ds := apex, star |
| + da.Target, ds.Target = "", "" |
| + if err := c.reg.ReplaceRegionalSet(apex.Host, []RegionalDomain{da, ds}); err == nil { |
| + t.Fatal("a rewrite whose star update failed reported success") |
| + } |
| + if got := list(); !reflect.DeepEqual(got, pair) { |
| + t.Fatalf("a failed rewrite left %+v, want %+v", got, pair) |
| + } |
| + drop() |
| + |
| + // Removal, and an apex-only set (the star removed), with the |
| + // star's DELETE failing: the old pair stays. |
| + drop = injectRegionalFault(t, c.path, "DELETE", "OLD.host = '*.shop.example.com'") |
| + for _, rows := range [][]RegionalDomain{nil, {apex}} { |
| + if err := c.reg.ReplaceRegionalSet(apex.Host, rows); err == nil { |
| + t.Fatalf("set %+v whose star delete failed reported success", rows) |
| + } |
| + if got := list(); !reflect.DeepEqual(got, pair) { |
| + t.Fatalf("a failed set %+v left %+v, want %+v", rows, got, pair) |
| + } |
| + } |
| + drop() |
| + if err := c.reg.ReplaceRegionalSet(apex.Host, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := list(); len(got) != 0 { |
| + t.Fatalf("after the removal rows = %+v", got) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// injectRegionalFault opens the registry file a second time and creates a |
| +// BEFORE trigger on regional_domains that raises when cond holds; the |
| +// returned func drops it. |
| +func injectRegionalFault(t *testing.T, path, event, cond string) (drop func()) { |
| + t.Helper() |
| + db, err := sql.Open("sqlite", path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { db.Close() }) |
| + name := "inject_regional_" + strings.ToLower(event) |
| + for _, q := range []string{ |
| + "PRAGMA busy_timeout=5000", |
| + "CREATE TRIGGER " + name + " BEFORE " + event + " ON regional_domains WHEN " + cond + |
| + " BEGIN SELECT RAISE(FAIL, 'injected'); END", |
| + } { |
| + if _, err := db.Exec(q); err != nil { |
| + t.Fatalf("%s: %v", q, err) |
| + } |
| + } |
| + return func() { |
| + t.Helper() |
| + if _, err := db.Exec("DROP TRIGGER " + name); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
diff --git a/internal/registry/registry.go b/internal/registry/registry.go| index e2b435867..e4a374d29 100644 |
| --- a/internal/registry/registry.go |
| +++ b/internal/registry/registry.go |
| @@ -3522,34 +3522,65 @@ func (r *Registry) ListRegional() ([]RegionalDomain, error) { |
| return out, rows.Err() |
| } |
| -// UpsertRegional inserts a row, or updates an existing one's target, |
| -// account, app and region. created_at keeps the row's first value: it is |
| -// not hashed by Fingerprint, and a pass that re-derives the same row must |
| -// not look like a change. |
| -func (r *Registry) UpsertRegional(d RegionalDomain) error { |
| +// ReplaceRegionalSet makes host's regional_domains rows exactly rows, in |
| +// one SQLite transaction (#447, ruling 7). host is a regional claim's host; |
| +// its rows are keyed host and "*."+host, and rows may hold only those keys |
| +// (each at most once), or nothing, which removes the claim's rows. A row |
| +// already present has its target, account, app and region updated and |
| +// keeps its first created_at: created_at is not hashed by Fingerprint, and |
| +// a pass that re-derives the same row must not look like a change. A key of |
| +// the claim's that rows does not name is deleted. |
| +// |
| +// It is the only writer of the table. A claim's apex and star rows decide |
| +// together whether a covering route can answer a name under the claim |
| +// (spec §7.3, §7.4), so a write that fails at any row (an injected fault, a |
| +// full disk) rolls back and leaves the claim's rows exactly as they were; |
| +// no half of a set ever lands. Other claims' rows are never touched. Over |
| +// the remote transport the whole set is one request, applied by the same |
| +// transaction on the serving side. |
| +func (r *Registry) ReplaceRegionalSet(host string, rows []RegionalDomain) error { |
| + star := "*." + host |
| + if host == "" || strings.HasPrefix(host, "*.") { |
| + return fmt.Errorf("regional set: %q is not a claim host", host) |
| + } |
| + seen := make(map[string]bool, 2) |
| + for _, d := range rows { |
| + if d.Host != host && d.Host != star { |
| + return fmt.Errorf("regional set %s: row %q is not one of its keys", host, d.Host) |
| + } |
| + if seen[d.Host] { |
| + return fmt.Errorf("regional set %s: row %q given twice", host, d.Host) |
| + } |
| + seen[d.Host] = true |
| + } |
| if r.remote != nil { |
| - _, err := r.remote.call(nil, remoteRequest{Method: "UpsertRegional", RD: d}, nil) |
| + _, err := r.remote.call(nil, remoteRequest{Method: "ReplaceRegionalSet", Host: host, RDs: rows}, nil) |
| return err |
| } |
| - _, err := r.sql.Exec(` |
| + tx, err := r.sql.Begin() |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + for _, d := range rows { |
| + if _, err := tx.Exec(` |
| INSERT INTO regional_domains (host, target, account, app, region, created_at) |
| VALUES (?, ?, ?, ?, ?, ?) |
| ON CONFLICT(host) DO UPDATE SET target=excluded.target, account=excluded.account, app=excluded.app, region=excluded.region`, |
| - d.Host, d.Target, d.Account, d.App, d.Region, d.CreatedAt) |
| - return err |
| -} |
| - |
| -// DeleteRegional removes host's row. Idempotent: a host already gone is a |
| -// success, same contract as DeleteAlias. |
| -func (r *Registry) DeleteRegional(host string) error { |
| - if r.remote != nil { |
| - _, err := r.remote.call(nil, remoteRequest{Method: "DeleteRegional", Host: host}, nil) |
| - return err |
| + d.Host, d.Target, d.Account, d.App, d.Region, d.CreatedAt); err != nil { |
| + return err |
| + } |
| } |
| - |
| - _, err := r.sql.Exec(`DELETE FROM regional_domains WHERE host = ?`, host) |
| - return err |
| + for _, k := range []string{host, star} { |
| + if seen[k] { |
| + continue |
| + } |
| + if _, err := tx.Exec(`DELETE FROM regional_domains WHERE host = ?`, k); err != nil { |
| + return err |
| + } |
| + } |
| + return tx.Commit() |
| } |
| // RoutePath is one derived row of the route_paths table: a leading URL path |
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go| index 5f45d3211..d4e53f6c7 100644 |
| --- a/internal/registry/remote_dispatch.go |
| +++ b/internal/registry/remote_dispatch.go |
| @@ -82,7 +82,7 @@ type remoteRequest struct { |
| A RouteAlias |
| Alias string |
| W WildcardDomain |
| - RD RegionalDomain |
| + RDs []RegionalDomain |
| P RoutePath |
| Prefix string |
| Path string |
| @@ -343,10 +343,8 @@ func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback |
| err = r.DeleteWildcardDomain(q.Host) |
| case "ListRegional": |
| out.Regional, err = r.ListRegional() |
| - case "UpsertRegional": |
| - err = r.UpsertRegional(q.RD) |
| - case "DeleteRegional": |
| - err = r.DeleteRegional(q.Host) |
| + case "ReplaceRegionalSet": |
| + err = r.ReplaceRegionalSet(q.Host, q.RDs) |
| case "ListPaths": |
| out.Paths, err = r.ListPaths() |
| case "UpsertPath": |