package host import ( "bytes" "context" "crypto/ecdh" "encoding/base64" "encoding/json" "log" "os" "path/filepath" "strings" "sync" "testing" "time" "github.com/carlosframework/platform/internal/appconfig" "github.com/carlosframework/platform/internal/edgesfile" "github.com/carlosframework/platform/internal/moves" "github.com/carlosframework/platform/internal/registry" "github.com/carlosframework/platform/internal/release" "github.com/carlosframework/platform/internal/status" ) func edgesTestRegistry(t *testing.T) *registry.Registry { t.Helper() reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { reg.Close() }) return reg } // seedRoute upserts a minimal ready route under the given host — any served // kind does for these tests, since edgesFilePass folds every kind in // (the serving-class split is the reader's business, Task 3). func seedRoute(t *testing.T, reg *registry.Registry, host string) { t.Helper() if err := reg.Upsert(registry.Route{Host: host, Kind: "service", Addr: "10.0.0.1:3000", Status: "ready"}); err != nil { t.Fatal(err) } } // putCountingStore wraps a release.Store and counts Put calls — the same // wrap-and-count idiom agent_test.go's countingStore uses for Get, applied // to Put so the change-gate test can pin "second identical pass writes // nothing" without inspecting store internals. type putCountingStore struct { release.Store puts int } func (p *putCountingStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { p.puts++ return p.Store.Put(ctx, key, body, ifMatch) } func TestEdgesFilePublishesHomedHosts(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var lastBody []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &lastBody); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var f edgesFile if err := json.Unmarshal(got, &f); err != nil { t.Fatal(err) } if f.V != 1 || f.Box != "annie" || f.EIP != "1.2.3.4" { t.Fatalf("file = %+v", f) } if r, ok := f.Hosts["app.example.com"]; !ok || r.Role != "home" { t.Fatalf("hosts = %+v", f.Hosts) } if f.Generation == "" { t.Fatal("generation must be stamped") } if got, want := edgesFileKey("annie"), "control/edges/annie.json"; got != want { t.Fatalf("edgesFileKey = %q, want %q", got, want) } } // A box with no discoverable public IP still publishes the file, with // "eip":"" — the DR runbook's hosts list must not depend on IMDS working. func TestEdgesFilePublishesWithEmptyEIP(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var lastBody []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "", &lastBody); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var f edgesFile if err := json.Unmarshal(got, &f); err != nil { t.Fatal(err) } if f.EIP != "" { t.Fatalf("eip = %q, want empty", f.EIP) } if _, ok := f.Hosts["app.example.com"]; !ok { t.Fatalf("hosts = %+v, want app.example.com present despite empty eip", f.Hosts) } } func TestEdgesFileSkipsWriteWhenUnchanged(t *testing.T) { real := release.NewDirStore(t.TempDir()) s := &putCountingStore{Store: real} reg := edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var lastBody []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &lastBody); err != nil { t.Fatal(err) } if s.puts != 1 { t.Fatalf("first pass puts = %d, want 1", s.puts) } // Second pass, identical registry state: a fresh generation timestamp // would differ from the first pass's, but the change-gate excludes // Generation, so this must not write. if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &lastBody); err != nil { t.Fatal(err) } if s.puts != 1 { t.Fatalf("unchanged second pass puts = %d, want still 1 (no write)", s.puts) } // A registry change makes the next pass write again. seedRoute(t, reg, "second.example.com") if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &lastBody); err != nil { t.Fatal(err) } if s.puts != 2 { t.Fatalf("changed third pass puts = %d, want 2", s.puts) } } // FINDING 1 (review, 2026-08-22): readPublicIP is a single 2s best-effort // IMDS attempt, re-run every tick — a transient throttle or blip returns "" // exactly like a box that never had a public IP at all. Without a hold, a // single hiccuped tick would blank a known-good EIP in the published file, // costing every remote edge its dial address for this box's home-boxed // hosts until the next successful tick (up to 5min + jitter). A pass // reporting "" after a pass that reported "1.2.3.4" must keep "1.2.3.4". func TestEdgesFileHoldsLastKnownGoodEIPOnTransientBlank(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var last []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &last); err != nil { t.Fatal(err) } // Simulate a transient IMDS blip: this tick's probe returns "". if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "", &last); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var f edgesFile if err := json.Unmarshal(got, &f); err != nil { t.Fatal(err) } if f.EIP != "1.2.3.4" { t.Fatalf("eip after a blank probe = %q, want held value %q", f.EIP, "1.2.3.4") } } // FINDING 2 (review, 2026-08-22, ruling): edge.Reload (internal/edge/edge.go) // skips any route whose Status != "ready" — that gate is the deployment's // own definition of "serves", so a pending/creating/failed row must not // claim role:"home" here either. Hibernating routes stay Status "ready", // so this filter excludes nothing a remote backhaul could actually reach. func TestEdgesFileExcludesNonReadyRows(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "ready.example.com") if err := reg.Upsert(registry.Route{Host: "creating.example.com", Kind: "service", Addr: "10.0.0.2:3000", Status: "creating"}); err != nil { t.Fatal(err) } var last []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &last); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var f edgesFile if err := json.Unmarshal(got, &f); err != nil { t.Fatal(err) } if _, ok := f.Hosts["ready.example.com"]; !ok { t.Fatalf("hosts = %+v, want ready.example.com present", f.Hosts) } if _, ok := f.Hosts["creating.example.com"]; ok { t.Fatalf("hosts = %+v, want creating.example.com ABSENT (not ready, nothing serves it yet)", f.Hosts) } } // A sidecar row is READY — that is what makes it runnable — so the readiness // filter above lets it straight through, and this file is published to every // box in the deployment. That matters more than it looks: a REMOTE edge has // no sidecar row and never sees a Kind, so edge.Reload's refusal cannot // protect it. It misses on its own upstream lookup, reads this file through // the home map, and backhauls — dialing the home box with the sidecar's own // name as SNI. The same entry also satisfies deploymentHost, which is what // admits a name to the cert machinery. // // So the guarantee has to be made by the WRITER, exactly as // publishResidentFleetBindings makes it: a sidecar is never advertised as // served, by this box or any other. func TestEdgesFileNeverPublishesASidecar(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "ready.example.com") // Minted the way the sidecar reconcile pass mints one: ready, and // carrying neither socket nor addr, because nothing dials it. if err := reg.Upsert(registry.Route{ Host: "bot.eleven.bdm.sidecar.internal", Kind: "sidecar", App: "eleven", Account: "bdm", Status: "ready", Provisioned: true, }); err != nil { t.Fatal(err) } var last []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie"}, "1.2.3.4", &last); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var f edgesFile if err := json.Unmarshal(got, &f); err != nil { t.Fatal(err) } if _, ok := f.Hosts["ready.example.com"]; !ok { t.Fatalf("hosts = %+v, want the ordinary route still published", f.Hosts) } if _, ok := f.Hosts["bot.eleven.bdm.sidecar.internal"]; ok { t.Fatalf("hosts = %+v, want the sidecar ABSENT — publishing it makes every remote edge a backhaul door onto a member nothing may dial", f.Hosts) } } // FINDING 3 (review, 2026-08-22): a catch-all claim's registry row is a real // "*.parent" host (Task 3's reconcile pass derives it the same way // edge.go's upstream map does). This writer performs no wildcard expansion // — the row's Host lands in Hosts verbatim, exactly like every other row — // so an exact-match reader must apply edge.go's lookupUpstream one-label // rule itself; that contract is documented at the call site and in the // spec, not enforced here. func TestEdgesFileWildcardRowPublishesVerbatim(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) if err := reg.Upsert(registry.Route{Host: "*.example.com", Kind: "service", Addr: "10.0.0.3:3000", Status: "ready"}); err != nil { t.Fatal(err) } var last []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &last); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var f edgesFile if err := json.Unmarshal(got, &f); err != nil { t.Fatal(err) } if r, ok := f.Hosts["*.example.com"]; !ok || r.Role != "home" { t.Fatalf("hosts = %+v, want \"*.example.com\" present verbatim with role home", f.Hosts) } } // FINDING 4 (review, 2026-08-22): every other test in this file round-trips // through the edgesFile struct on both the write and the assert side, so a // json-tag rename (e.g. "eip" -> "publicIP") would stay green everywhere // while breaking Task 3's parser, which reads the wire bytes independently // of this package's Go types. This test pins the RAW body against a // hand-written literal matching the brief's exact schema string — every // byte is fixed except the generation timestamp, which this fixed // signature has no clock seam to inject (edgesFilePass takes no `now` // parameter, per the brief's pinned interface); that one field is read // back and re-inserted into the literal rather than relaxed by a regex. func TestEdgesFileRawWireBodyMatchesSchema(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var last []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "quiet-harbour", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "203.0.113.10", &last); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/quiet-harbour.json") if err != nil { t.Fatal(err) } var probe struct { Generation string `json:"generation"` } if err := json.Unmarshal(got, &probe); err != nil { t.Fatal(err) } if _, err := time.Parse(time.RFC3339, probe.Generation); err != nil { t.Fatalf("generation %q is not RFC3339: %v", probe.Generation, err) } want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"moves_protocol":0,"seeds_protocol":0,"generation":"` + probe.Generation + `","hosts":{"app.example.com":{"role":"home","platform":false}}}` if string(got) != want { t.Fatalf("raw wire body =\n%s\nwant\n%s", got, want) } } // FINDING 5 (task 1, 2026-08-22): region is additive to the pinned schema — // this extends FINDING 4's raw-body pin rather than replacing it. Two // bodies, byte for byte: an unresolved region (edgesFileRegion's "" case — // off EC2, no CARLOS_AWS_REGION override) must produce the IDENTICAL bytes // FINDING 4 already pins (no "region" key at all, omitempty), and a // resolved region must insert exactly `"region":"eu-west-1"` between "eip" // and "generation" — the struct field order — with nothing else disturbed. // This test drives edgesFilePass directly with the resolved value; the // resolution contract itself (override wins, IMDS otherwise, trimmed) is // pinned separately in TestEdgesFileRegionResolution. func TestEdgesFileRawWireBodyRegionField(t *testing.T) { t.Parallel() s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") genOf := func(t *testing.T, body []byte) string { t.Helper() var probe struct { Generation string `json:"generation"` } if err := json.Unmarshal(body, &probe); err != nil { t.Fatal(err) } return probe.Generation } t.Run("unset region is omitted entirely", func(t *testing.T) { var last []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "quiet-harbour", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "203.0.113.10", &last); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/quiet-harbour.json") if err != nil { t.Fatal(err) } gen := genOf(t, got) want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"moves_protocol":0,"seeds_protocol":0,"generation":"` + gen + `","hosts":{"app.example.com":{"role":"home","platform":false}}}` if string(got) != want { t.Fatalf("raw wire body (region unset) =\n%s\nwant\n%s", got, want) } }) t.Run("set region is inserted between eip and generation", func(t *testing.T) { s2, reg2 := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg2, "app.example.com") var last []byte if err := edgesFilePass(context.Background(), s2, reg2, edgesFile{Box: "quiet-harbour", Region: "eu-west-1", Placement: "", DataBucket: "", DataBucketRegion: ""}, "203.0.113.10", &last); err != nil { t.Fatal(err) } got, _, err := s2.Get(context.Background(), "control/edges/quiet-harbour.json") if err != nil { t.Fatal(err) } gen := genOf(t, got) want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","region":"eu-west-1","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"moves_protocol":0,"seeds_protocol":0,"generation":"` + gen + `","hosts":{"app.example.com":{"role":"home","platform":false}}}` if string(got) != want { t.Fatalf("raw wire body (region set) =\n%s\nwant\n%s", got, want) } }) } // Plan re-ruling (2026-08-23, review catch): CARLOS_REGION is the CARLOS // placement code ("ie"), NOT an AWS region — Task 5's // ChangeResourceRecordSets would reject it batch-wide, so the field's // value must come from CARLOS_AWS_REGION / IMDS instead, never // CARLOS_REGION. edgesFileRegion is the pure half of that contract // (getenv/probe-injectable, domainsTickConfig's own shape) — this pins // override-wins, unset-and-no-probe-answer → "", and trimming on both // inputs, all without a live IMDS server. func TestEdgesFileRegionResolution(t *testing.T) { env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } } cases := []struct { name string env map[string]string probed string want string }{ { name: "override set wins over the probed value", env: map[string]string{"CARLOS_AWS_REGION": "eu-west-1"}, probed: "us-east-1", want: "eu-west-1", }, { name: "override set, untrimmed, wins and is trimmed", env: map[string]string{"CARLOS_AWS_REGION": " eu-west-1 "}, probed: "us-east-1", want: "eu-west-1", }, { name: "override unset falls back to the probed value", env: map[string]string{}, probed: "eu-west-1", want: "eu-west-1", }, { name: "override unset, probed value untrimmed, is trimmed", env: map[string]string{}, probed: " eu-west-1 ", want: "eu-west-1", }, { name: "CARLOS_REGION (the placement code) is never consulted", env: map[string]string{"CARLOS_REGION": "ie"}, probed: "", want: "", }, { name: "unset override and no probe answer (off EC2) is empty, not an error", env: map[string]string{}, probed: "", want: "", }, { name: "blank override (set but empty) does not shadow the probed value", env: map[string]string{"CARLOS_AWS_REGION": ""}, probed: "eu-west-1", want: "eu-west-1", }, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { if got := edgesFileRegion(env(c.env), c.probed); got != c.want { t.Fatalf("edgesFileRegion() = %q, want %q", got, c.want) } }) } } // FINDING 6 (task 1, 2026-08-22, the plan-2 final review's Important 1): a // freshly ARMED loop must seed its change-gate from whatever this box last // published, or two bugs follow — see seedEdgesFileGate's doc. This test // pins the seed-then-pass contract directly: a process that primes its // *last from seedEdgesFileGate, then runs a pass against UNCHANGED registry // state, must write ZERO times. Before this task, edgesFileLoop always // started with a bare `var last []byte`, so the very first tick after any // restart always wrote — this is the regression that closes. func TestEdgesFileSeedGateSkipsWriteOnUnchangedBucketState(t *testing.T) { real := release.NewDirStore(t.TempDir()) reg := edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") // A prior process (or the prior pass of this one) already published. var priming []byte if err := edgesFilePass(context.Background(), real, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &priming); err != nil { t.Fatal(err) } // A fresh process arms: seed the gate from the bucket, as edgesFileLoop // now does at loop arm. last := seedEdgesFileGate(context.Background(), real, "annie") if last == nil { t.Fatal("seedEdgesFileGate returned nil, want the prior file's gate body") } counting := &putCountingStore{Store: real} if err := edgesFilePass(context.Background(), counting, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &last); err != nil { t.Fatal(err) } if counting.puts != 0 { t.Fatalf("puts = %d, want 0 — a seeded gate against unchanged state must not write", counting.puts) } } // The restart-blip case named in the final review: a process restarts, // arms, and its very FIRST tick hits both a transient IMDS blank AND a real // registry change (so the pass must write). The write must still carry the // bucket's held EIP, not the blank probe — seedEdgesFileGate's dual // contract (gate AND EIP hold) has to survive an ACTUAL write, not just a // no-op pass, or the hold half of the fix is unverified. func TestEdgesFileSeedHoldsEIPThroughRestartBlip(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var priming []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &priming); err != nil { t.Fatal(err) } last := seedEdgesFileGate(context.Background(), s, "annie") if last == nil { t.Fatal("seedEdgesFileGate returned nil, want the prior file's gate body") } // This tick both hits a transient IMDS blip AND sees a real registry // change, so the pass must write. seedRoute(t, reg, "second.example.com") if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "", &last); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var f edgesFile if err := json.Unmarshal(got, &f); err != nil { t.Fatal(err) } if f.EIP != "1.2.3.4" { t.Fatalf("eip after restart + blank probe = %q, want held %q", f.EIP, "1.2.3.4") } if _, ok := f.Hosts["second.example.com"]; !ok { t.Fatalf("hosts = %+v, want second.example.com present — the write must carry the real registry change too", f.Hosts) } } // Without the seed, a fresh *last is nil and edgesFilePass's own hold guard // (`*last != nil`) cannot fire — this pins that this really is the bug the // two tests above close, not a tautology of the hold logic that would pass // regardless of seeding. func TestEdgesFileUnseededLastPublishesBlankEIPOnFirstTickBlip(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var priming []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &priming); err != nil { t.Fatal(err) } // The pre-fix shape: a fresh process's *last starts nil (no seed read). var unseeded []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "", &unseeded); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var f edgesFile if err := json.Unmarshal(got, &f); err != nil { t.Fatal(err) } if f.EIP != "" { t.Fatalf("eip = %q, want blank — demonstrating why the seed in the tests above is load-bearing, not incidental", f.EIP) } } // Self-review: does the seed interact correctly with the change gate when // the bucket file PREDATES the region field? A box upgraded to this build // finds a bucket file an older build left with no "region" key at all. // Seeding *last from it must not treat this build's first pass — the one // that finally sets a real region — as unchanged: Region participates in // the change gate exactly like every other field (edgesFilePass's doc), so // a seeded pre-region gate and a fresh body WITH region differ in bytes and // must write exactly once, not zero and not on every tick after. func TestEdgesFileSeedPreRegionBucketWritesOnceWhenRegionArrives(t *testing.T) { real := release.NewDirStore(t.TempDir()) reg := edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") // Hand-written exactly as a pre-region build would have left it in the // bucket: no "region" key present. preRegion := []byte(`{"v":1,"box":"annie","eip":"1.2.3.4","generation":"2026-08-01T00:00:00Z","hosts":{"app.example.com":{"role":"home"}}}`) if err := putReplacing(context.Background(), real, edgesFileKey("annie"), preRegion); err != nil { t.Fatal(err) } last := seedEdgesFileGate(context.Background(), real, "annie") if last == nil { t.Fatal("seedEdgesFileGate returned nil") } // This build now has CARLOS_REGION set: the first pass must write, once. counting := &putCountingStore{Store: real} if err := edgesFilePass(context.Background(), counting, reg, edgesFile{Box: "annie", Region: "eu-west-1", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &last); err != nil { t.Fatal(err) } if counting.puts != 1 { t.Fatalf("puts = %d, want 1 — a region arriving on a seeded pre-region body is a real change", counting.puts) } got, _, err := real.Get(context.Background(), edgesFileKey("annie")) if err != nil { t.Fatal(err) } var f edgesFile if err := json.Unmarshal(got, &f); err != nil { t.Fatal(err) } if f.Region != "eu-west-1" { t.Fatalf("region = %q, want eu-west-1", f.Region) } // A second, identical-region pass must not write again — the gate now // includes region on both sides. if err := edgesFilePass(context.Background(), counting, reg, edgesFile{Box: "annie", Region: "eu-west-1", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &last); err != nil { t.Fatal(err) } if counting.puts != 1 { t.Fatalf("puts after unchanged second pass = %d, want still 1", counting.puts) } } // The class mark (#300): platform-minted rows carry platform:true; a stray // operator row does not, so no remote edge derives a wildcard parent from it. func TestEdgesFileMarksPlatformRows(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) for _, r := range []registry.Route{ {Host: "app.acct.apps.test", Kind: "service", Addr: "10.0.0.1:3000", Status: "ready", Platform: true}, {Host: "prov.acct.apps.test", Kind: "service", Addr: "10.0.0.1:3001", Status: "ready", Provisioned: true}, {Host: "stray.acct.apps.test", Kind: "service", Addr: "10.0.0.1:3002", Status: "ready"}, {Host: "pending.acct.apps.test", Kind: "service", Addr: "10.0.0.1:3003", Status: "pending", Platform: true}, } { if err := reg.Upsert(r); err != nil { t.Fatal(err) } } var lastBody []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &lastBody); err != nil { t.Fatal(err) } body, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var f struct { Hosts map[string]struct { Platform bool `json:"platform"` } `json:"hosts"` } if err := json.Unmarshal(body, &f); err != nil { t.Fatal(err) } for host, want := range map[string]bool{"app.acct.apps.test": true, "prov.acct.apps.test": true, "stray.acct.apps.test": false} { if got := f.Hosts[host].Platform; got != want { t.Errorf("%s platform = %v; want %v", host, got, want) } } if _, ok := f.Hosts["pending.acct.apps.test"]; ok { t.Error("a non-ready row is published regardless of class") } // The mark is always written, so a keyless host object can only mean a // pre-mark publisher. if !strings.Contains(string(body), `"stray.acct.apps.test":{"role":"home","platform":false}`) { t.Errorf("mark not emitted for an unclassed row: %s", body) } } // #287: attached custom domains are published under their own names — // only when their primary is served AND their DNS points here, marked as // aliases, never platform-class, catch-alls never, and never over a real // route. Detaching one republishes without it. func TestEdgesFilePublishesPointingAliasesOfServedPrimaries(t *testing.T) { withheldAliasSaid = sync.Map{} // once per PROCESS: isolate from -count>1 s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) if err := reg.Upsert(registry.Route{Host: "app.acct.apps.test", Kind: "service", Addr: "10.0.0.1:3000", Status: "ready", Platform: true}); err != nil { t.Fatal(err) } if err := reg.Upsert(registry.Route{Host: "pending.acct.apps.test", Kind: "service", Addr: "10.0.0.1:3001", Status: "pending"}); err != nil { t.Fatal(err) } if err := reg.Upsert(registry.Route{Host: "real.example.net", Kind: "service", Addr: "10.0.0.1:3002", Status: "ready", Platform: true}); err != nil { t.Fatal(err) } for _, a := range []registry.RouteAlias{ {Alias: "www.customer.com", Host: "app.acct.apps.test", Account: "acct", App: "app", DNSStatus: "pointing"}, {Alias: "unpointed.customer.com", Host: "app.acct.apps.test", Account: "acct", App: "app", DNSStatus: "elsewhere"}, {Alias: "fresh.customer.com", Host: "app.acct.apps.test", Account: "acct", App: "app"}, {Alias: "*.customer.com", Host: "app.acct.apps.test", Account: "acct", App: "app", DNSStatus: "pointing"}, {Alias: "orphan.example.org", Host: "pending.acct.apps.test", Account: "acct", App: "pending", DNSStatus: "pointing"}, {Alias: "real.example.net", Host: "app.acct.apps.test", Account: "acct", App: "app", DNSStatus: "pointing"}, // shadowed } { if err := reg.UpsertAlias(a); err != nil { t.Fatal(err) } } type hostView struct { Role string `json:"role"` Platform bool `json:"platform"` Alias bool `json:"alias"` } publish := func() map[string]hostView { t.Helper() var lastBody []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &lastBody); err != nil { t.Fatal(err) } body, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var f struct { Hosts map[string]hostView `json:"hosts"` } if err := json.Unmarshal(body, &f); err != nil { t.Fatal(err) } return f.Hosts } var buf strings.Builder log.SetOutput(&buf) t.Cleanup(func() { log.SetOutput(os.Stderr) }) hosts := publish() h, ok := hosts["www.customer.com"] if !ok || h.Role != "home" || !h.Alias || h.Platform { t.Errorf("www.customer.com = %+v, %v; want home, alias, not platform", h, ok) } for _, absent := range []string{"unpointed.customer.com", "fresh.customer.com", "*.customer.com", "orphan.example.org"} { if _, ok := hosts[absent]; ok { t.Errorf("%s must not be published", absent) } } if h := hosts["real.example.net"]; !h.Platform || h.Alias { t.Errorf("an alias colliding with a real route displaced the route's entry: %+v", h) } // A withheld alias says so once per process, not once per pass. publish() publish() if n := strings.Count(buf.String(), "unpointed.customer.com not published"); n != 1 { t.Errorf("withheld line logged %d times over 3 passes; want 1:\n%s", n, buf.String()) } // Detach: gone on the next pass. if err := reg.DeleteAlias("www.customer.com"); err != nil { t.Fatal(err) } if _, ok := publish()["www.customer.com"]; ok { t.Error("a detached alias was still published") } } // #305: delegated customer wildcard parents publish as "*." in their // own class — never platform, never over an existing key. func TestEdgesFilePublishesDelegatedWildcardParents(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.acct.apps.test") if err := reg.Upsert(registry.Route{Host: "*.taken.example", Kind: "service", Addr: "10.0.0.1:3001", Status: "ready", Platform: true}); err != nil { t.Fatal(err) } // customer.example has a served catch-all (Catchall claim) → dial half // too; certonly.example is a Wildcard claim without Catchall → cert // half only; pending.example's catch-all points at an unserved primary. if err := reg.Upsert(registry.Route{Host: "pend.acct.apps.test", Kind: "service", Addr: "10.0.0.1:3002", Status: "pending"}); err != nil { t.Fatal(err) } for _, a := range []registry.RouteAlias{ {Alias: "*.customer.example", Host: "app.acct.apps.test", Account: "acct", App: "app"}, {Alias: "*.pending.example", Host: "pend.acct.apps.test", Account: "acct", App: "pend"}, } { if err := reg.UpsertAlias(a); err != nil { t.Fatal(err) } } for _, w := range []registry.WildcardDomain{ {Host: "customer.example", Account: "acct", App: "app"}, {Host: "certonly.example", Account: "acct", App: "app"}, {Host: "pending.example", Account: "acct", App: "pend"}, {Host: "*.odd.example", Account: "acct", App: "app"}, // never written by the pass; refused here too {Host: "taken.example", Account: "acct", App: "app"}, // a real route owns the key } { if err := reg.UpsertWildcardDomain(w); err != nil { t.Fatal(err) } } var lastBody []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "1.2.3.4", &lastBody); err != nil { t.Fatal(err) } body, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var f struct { Hosts map[string]struct { Role string `json:"role"` Platform bool `json:"platform"` Wildcard bool `json:"wildcard"` Alias bool `json:"alias"` } `json:"hosts"` } if err := json.Unmarshal(body, &f); err != nil { t.Fatal(err) } // Marked alias BECAUSE the dial half is on: a catch-all we serve is a // materialized claim, and DeploymentRoutes keys the whole "is this // somebody's real route" question on that mark. See the end-to-end // tripwire below for what an unmarked row does to the claim. h, ok := f.Hosts["*.customer.example"] if !ok || h.Role != "home" || !h.Wildcard || h.Platform || !h.Alias { t.Fatalf("*.customer.example = %+v, %v; want home, wildcard, alias, not platform", h, ok) } for _, name := range []string{"*.certonly.example", "*.pending.example"} { h, ok := f.Hosts[name] if !ok || h.Role != "wildcard" || !h.Wildcard || h.Platform || h.Alias { t.Errorf("%s = %+v, %v; want the cert half only (role wildcard, unmarked)", name, h, ok) } } if _, ok := f.Hosts["*.*.odd.example"]; ok { t.Error("a malformed wildcard_domains row was published") } // A real route owns the key: it keeps role and class, and the parent's // class is added — the reader must still load the PEM everywhere. It // stays UNMARKED, which is the other half of the mark's meaning: this // hostname really is served as a route, so it must go on outranking any // claim another box makes on the same name. if h := f.Hosts["*.taken.example"]; !h.Platform || !h.Wildcard || h.Role != "home" || h.Alias { t.Errorf("route-owned key = %+v; want platform AND wildcard, role home, unmarked", h) } } // The tripwire on a loop that ran in production: a served catch-all published // without the alias mark is read back by DeploymentRoutes as evidence that // some live box serves that hostname as a REAL route, so the next // domains.ReconcileAliases pass refuses the very claim that produced the row // and deletes the alias. Deleting it turns the dial half off, which drops the // row, which lets the pass after that recreate it — and the name flaps // on/off forever (*.woodstar.app, every 5-6 minutes, down about half the // time). Neither half is wrong alone, so only an end-to-end check catches it: // publish with the real publisher, then fold with the real reader. func TestEdgesFileServedCatchAllIsNotItsOwnDeploymentRoute(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.acct.apps.test") if err := reg.UpsertAlias(registry.RouteAlias{ Alias: "*.customer.example", Host: "app.acct.apps.test", Account: "acct", App: "app", }); err != nil { t.Fatal(err) } if err := reg.UpsertWildcardDomain(registry.WildcardDomain{ Host: "customer.example", Account: "acct", App: "app", }); err != nil { t.Fatal(err) } var lastBody []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie"}, "1.2.3.4", &lastBody); err != nil { t.Fatal(err) } now := time.Now() if err := status.WriteBox(context.Background(), s, status.Box{Label: "annie", GeneratedAt: now}); err != nil { t.Fatal(err) } routes := edgesfile.DeploymentRoutes(context.Background(), s, now) if routes["*.customer.example"] { t.Errorf("routes = %v, want the served catch-all NOT counted as a real route — counting it makes the claim refuse itself every pass", routes) } // The join really happened: without this, an empty set would pass the // assertion above for the wrong reason (a snapshot/label mismatch reads // as "nothing known", which is permissive by contract). if !routes["app.acct.apps.test"] { t.Fatalf("routes = %v, want the box's real route counted — the fold did not join", routes) } } // The whole EIP fold rests on ONE identity: the `box` name this loop // publishes under and the `label` the status snapshot is written under must // be the same string, or edgesfile.EdgeIPs' liveness join drops every edge // silently and the deployment's edge set degrades to env-only forever — a // failure with no error, no log line and no red test. // // They are the same today because both resolve through metricsBoxLabel over // the same machine id: edgesFileLoop calls it directly, and statusTick's // snapshot label is status.Label(Probes.MachineID), which is exactly what // metricsBoxLabel falls through to off a fleet box. (A fleet box never gets // here: edgesFileLoop returns early on shouldSkipPublisherElection.) This // test is the tripwire on that, end to end through the real fold. func TestEdgesFileBoxNameJoinsTheStatusSnapshotLabel(t *testing.T) { const machineID = "ip-10-0-0-7" notAFleetBox := func(string) string { return "" } box := metricsBoxLabel(notAFleetBox, machineID) snapshot := status.CollectBox(nil, status.Probes{MachineID: machineID}, time.Now()) if box != snapshot.Label { t.Fatalf("edges file box %q vs status snapshot label %q — the fold's liveness join needs one name", box, snapshot.Label) } ctx := context.Background() s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var last []byte if err := edgesFilePass(ctx, s, reg, edgesFile{Box: box, Region: "eu-west-1", Placement: "", DataBucket: "", DataBucketRegion: ""}, "203.0.113.7", &last); err != nil { t.Fatal(err) } if err := status.WriteBox(ctx, s, snapshot); err != nil { t.Fatal(err) } got := edgesfile.EdgeIPs(ctx, s, nil, time.Now()) if len(got) != 1 || got[0] != "203.0.113.7" { t.Fatalf("fold = %v, want this box's own EIP — the two writers disagree about its name", got) } } // The placement code (issue #329): CARLOS_REGION verbatim, additive between // region and generation, omitted entirely when the box has none — the // console's armed-placement gate stays dormant on a fleet that never // publishes it, which is what makes roll order irrelevant. func TestEdgesFileRawWireBodyPlacementField(t *testing.T) { t.Parallel() s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var last []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "quiet-harbour", Region: "eu-west-2", Placement: "uk", DataBucket: "", DataBucketRegion: ""}, "203.0.113.10", &last); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/quiet-harbour.json") if err != nil { t.Fatal(err) } var probe struct { Placement string `json:"placement"` Generation string `json:"generation"` } if err := json.Unmarshal(got, &probe); err != nil { t.Fatal(err) } want := `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","region":"eu-west-2","placement":"uk","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"moves_protocol":0,"seeds_protocol":0,"generation":"` + probe.Generation + `","hosts":{"app.example.com":{"role":"home","platform":false}}}` if string(got) != want { t.Fatalf("raw wire body (placement set) =\n%s\nwant\n%s", got, want) } // Unset placement publishes no key at all. s2, reg2 := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg2, "app.example.com") var last2 []byte if err := edgesFilePass(context.Background(), s2, reg2, edgesFile{Box: "quiet-harbour", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "203.0.113.10", &last2); err != nil { t.Fatal(err) } got2, _, err := s2.Get(context.Background(), "control/edges/quiet-harbour.json") if err != nil { t.Fatal(err) } if strings.Contains(string(got2), "placement") { t.Fatalf("raw wire body with no CARLOS_REGION carries a placement key: %s", got2) } } // Data-bucket coordinates (instance-move spec): published verbatim from the // hibernate env pair, absent when unset — the same additive rule as // placement. func TestEdgesFileRawWireBodyDataBucketFields(t *testing.T) { t.Parallel() s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var last []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "quiet-harbour", Region: "eu-west-2", Placement: "uk", DataBucket: "carlos-tito-uk-1", DataBucketRegion: "eu-west-2"}, "203.0.113.10", &last); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/quiet-harbour.json") if err != nil { t.Fatal(err) } var probe struct { DataBucket string `json:"data_bucket"` DataBucketRegion string `json:"data_bucket_region"` } if err := json.Unmarshal(got, &probe); err != nil { t.Fatal(err) } if probe.DataBucket != "carlos-tito-uk-1" || probe.DataBucketRegion != "eu-west-2" { t.Fatalf("data bucket fields = %+v", probe) } s2, reg2 := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg2, "app.example.com") var last2 []byte if err := edgesFilePass(context.Background(), s2, reg2, edgesFile{Box: "quiet-harbour", Region: "", Placement: "", DataBucket: "", DataBucketRegion: ""}, "203.0.113.10", &last2); err != nil { t.Fatal(err) } got2, _, err := s2.Get(context.Background(), "control/edges/quiet-harbour.json") if err != nil { t.Fatal(err) } if strings.Contains(string(got2), "data_bucket") { t.Fatalf("unset hibernate env still published a data_bucket key: %s", got2) } } // --- #162: the replica placement's edges-file entries ---------------------- // TestEdgesFilePublishesReplicaEntries pins the data plane of replica // placements: a served row minted from a role=replica record — the Replica // mark set, Account/App carried so the account apex derives — publishes its // own host and the account's platform apex under role "home" with the // replica mark set. A PLAIN row never gains the mark, whatever placement the // box publishes; the mark is the row's, not the box's. (Raw map decode, not // the struct: the test is about the WIRE, and a struct field would make an // omitempty typo invisible.) func TestEdgesFilePublishesReplicaEntries(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) if err := reg.Upsert(registry.Route{ Host: "acme-uk.go.tito.io", Slug: "acme-uk", Kind: "service", Addr: "10.0.0.1:3000", Status: "ready", Account: "bab", App: "tito", Region: "uk", Replica: true, }); err != nil { t.Fatal(err) } // The home row, on the same box only for the test's convenience — its // entries must NOT carry the mark even when it sits here. if err := reg.Upsert(registry.Route{ Host: "acme.go.tito.io", Slug: "acme", Kind: "service", Addr: "10.0.0.2:3000", Status: "ready", Account: "bab", App: "tito", Region: "ie", }); err != nil { t.Fatal(err) } var lastBody []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "ukbox", Placement: "uk"}, "1.2.3.4", &lastBody); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/ukbox.json") if err != nil { t.Fatal(err) } var raw struct { Hosts map[string]struct { Role string `json:"role"` Replica bool `json:"replica"` } `json:"hosts"` } if err := json.Unmarshal(got, &raw); err != nil { t.Fatal(err) } for _, name := range []string{"acme-uk.go.tito.io"} { h, ok := raw.Hosts[name] if !ok { t.Errorf("replica row published nothing at %s (hosts: %+v)", name, raw.Hosts) continue } if h.Role != "home" || !h.Replica { t.Errorf("%s = %+v, want role home with the replica mark", name, h) } } if h := raw.Hosts["acme.go.tito.io"]; h.Replica { t.Errorf("the home row's entry carries the replica mark: %+v — the mark is the ROW's, and the home row is not a replica", h) } // The account apex is deliberately NOT published: a name the replica box // has no local row for must not be claimed (an apex key here would let // foldHomes' first-sorted-box rule hand the apex dial target to a // replica box fleet-wide). if _, ok := raw.Hosts["tito.bab"]; ok { t.Errorf("replica row published the account apex tito.bab — a name this box has no local row for must not be claimed (hosts: %+v)", raw.Hosts) } } // TestEdgesFileReplicaMarkFollowsTheRow pins the fail-closed default: a // plain served row publishes exactly as before #162 — no replica key at all // on the wire — on a box with no placement published, with no placement, or // with any placement. The mark cannot leak from the box's identity into an // unrelated row. func TestEdgesFileReplicaMarkFollowsTheRow(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) if err := reg.Upsert(registry.Route{ Host: "acme.go.tito.io", Kind: "service", Addr: "10.0.0.1:3000", Status: "ready", }); err != nil { t.Fatal(err) } for _, ident := range []edgesFile{{Box: "annie"}, {Box: "annie", Placement: "uk"}} { var lastBody []byte if err := edgesFilePass(context.Background(), s, reg, ident, "1.2.3.4", &lastBody); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var raw struct { Hosts map[string]struct { Replica bool `json:"replica"` } `json:"hosts"` } if err := json.Unmarshal(got, &raw); err != nil { t.Fatal(err) } if h, ok := raw.Hosts["acme.go.tito.io"]; ok && h.Replica { t.Errorf("hosts = %+v, want no replica mark on a plain row (box placement %q)", raw.Hosts, ident.Placement) } } } // ---- owners (#175 P7, the edge-local door) --------------------------------- // publishHosts runs one pass on box "annie" and reads its hosts back. func publishHosts(t *testing.T, reg *registry.Registry) map[string]edgeHost { t.Helper() s := release.NewDirStore(t.TempDir()) var last []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie"}, "1.2.3.4", &last); err != nil { t.Fatal(err) } body, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var f edgesFile if err := json.Unmarshal(body, &f); err != nil { t.Fatal(err) } return f.Hosts } func ownedRoute(t *testing.T, reg *registry.Registry, host, account, app string) { t.Helper() if err := reg.Upsert(registry.Route{Host: host, Kind: "service", Addr: "10.0.0.1:3000", Status: "ready", Account: account, App: app}); err != nil { t.Fatal(err) } } func wantOwner(t *testing.T, hosts map[string]edgeHost, host, account, app string) { t.Helper() h, ok := hosts[host] if !ok { t.Fatalf("%s not published: %+v", host, hosts) } if h.Account != account || h.App != app { t.Errorf("%s owner = %q/%q, want %q/%q", host, h.Account, h.App, account, app) } } // A home row publishes its own account and app, which the door checks // remotely. A row with no app has no owner a door key could name. func TestEdgesFilePublishesTheOwnerOfAHomeRow(t *testing.T) { reg := edgesTestRegistry(t) ownedRoute(t, reg, "acme.go.tito.io", "bae", "titogo") ownedRoute(t, reg, "*.go.tito.io", "bae", "titogo") seedRoute(t, reg, "appless.example.com") hosts := publishHosts(t, reg) wantOwner(t, hosts, "acme.go.tito.io", "bae", "titogo") wantOwner(t, hosts, "*.go.tito.io", "bae", "titogo") wantOwner(t, hosts, "appless.example.com", "", "") } // An alias is served by its primary's route, so it carries the primary's // owner, not the alias row's own columns. func TestEdgesFilePublishesAnAliasWithItsPrimarysOwner(t *testing.T) { withheldAliasSaid = sync.Map{} reg := edgesTestRegistry(t) ownedRoute(t, reg, "acme.go.tito.io", "bae", "titogo") if err := reg.UpsertAlias(registry.RouteAlias{Alias: "tickets.acme.com", Host: "acme.go.tito.io", Account: "bae", App: "somethingelse", DNSStatus: "pointing"}); err != nil { t.Fatal(err) } wantOwner(t, publishHosts(t, reg), "tickets.acme.com", "bae", "titogo") } // The served catch-all carries the wildcard claim's owner, when the primary // it serves agrees. func TestEdgesFilePublishesTheServedCatchAllsOwner(t *testing.T) { reg := edgesTestRegistry(t) ownedRoute(t, reg, "acme.go.tito.io", "bae", "titogo") if err := reg.UpsertAlias(registry.RouteAlias{Alias: "*.acme.com", Host: "acme.go.tito.io", Account: "bae", App: "titogo"}); err != nil { t.Fatal(err) } for _, w := range []registry.WildcardDomain{ {Host: "acme.com", Account: "bae", App: "titogo"}, {Host: "certonly.com", Account: "bae", App: "titogo"}, } { if err := reg.UpsertWildcardDomain(w); err != nil { t.Fatal(err) } } hosts := publishHosts(t, reg) wantOwner(t, hosts, "*.acme.com", "bae", "titogo") // The cert half dials nothing, so it names no owner. wantOwner(t, hosts, "*.certonly.com", "", "") } // Review focus 2: a hostname whose path prefixes reach two apps publishes no // owner, nor does its alias, so the door refuses it remotely. A hostname whose // prefixes all reach one app still publishes that owner. func TestEdgesFilePublishesNoOwnerForAMixedPathPrefixHostname(t *testing.T) { withheldAliasSaid = sync.Map{} reg := edgesTestRegistry(t) ownedRoute(t, reg, "ti.to", "bae", "titogo") ownedRoute(t, reg, "a.go.tito.io", "bae", "titogo") ownedRoute(t, reg, "b.classic.tito.io", "bae", "classic") ownedRoute(t, reg, "one.example", "bae", "titogo") for _, p := range []registry.RoutePath{ {Host: "ti.to", Prefix: "a", Target: "a.go.tito.io", Account: "bae", App: "titogo"}, {Host: "ti.to", Prefix: "b", Target: "b.classic.tito.io", Account: "bae", App: "titogo"}, {Host: "one.example", Prefix: "a", Target: "a.go.tito.io", Account: "bae", App: "titogo"}, } { if err := reg.UpsertPath(p); err != nil { t.Fatal(err) } } if err := reg.UpsertAlias(registry.RouteAlias{Alias: "tickets.example", Host: "ti.to", Account: "bae", App: "titogo", DNSStatus: "pointing"}); err != nil { t.Fatal(err) } hosts := publishHosts(t, reg) wantOwner(t, hosts, "ti.to", "", "") wantOwner(t, hosts, "tickets.example", "", "") wantOwner(t, hosts, "one.example", "bae", "titogo") wantOwner(t, hosts, "b.classic.tito.io", "bae", "classic") } // The two eligibility fields are NOT omitempty: absent means "a writer // that predates the field" (unknown), false means "no" (spec §6.1). func TestEdgesFileRawWireBodyEligibilityFields(t *testing.T) { t.Parallel() for _, want := range []bool{true, false} { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var last []byte ident := edgesFile{Box: "quiet-harbour", Region: "eu-west-2", Placement: "uk", ServesSharedPool: want, AcceptsInbound: want} if err := edgesFilePass(context.Background(), s, reg, ident, "203.0.113.10", &last); err != nil { t.Fatal(err) } got, _, err := s.Get(context.Background(), "control/edges/quiet-harbour.json") if err != nil { t.Fatal(err) } var raw map[string]any if err := json.Unmarshal(got, &raw); err != nil { t.Fatal(err) } for _, k := range []string{"serves_shared_pool", "accepts_inbound"} { v, present := raw[k] if !present || v != want { t.Fatalf("%s = %v (present %v), want %v always published", k, v, present, want) } } } } // What the loop publishes is the reconcile config's own answer, for every // spelling an operator might write. CARLOS_POOLS=",tito" parses to // ["tito"] (agent.go's parser drops empty elements), so it does NOT serve // the shared pool and must publish false (codex R3-3). func TestEdgesFileEligibilityFollowsTheReconcileConfig(t *testing.T) { cases := []struct { pools, inbound string shared, accept bool }{ {"", "", true, true}, {"tito", "", false, true}, {",tito", "", false, true}, {"", "none", true, false}, {"tito", "NONE", false, false}, } for _, c := range cases { getenv := func(k string) string { switch k { case "CARLOS_POOLS": return c.pools case "CARLOS_INBOUND": return c.inbound } return "" } shared, inbound := edgesFileEligibility(getenv) cfg := provisionTickConfig(getenv) wantShared, wantInbound := cfg.SharedInstanceEligibility() if shared != wantShared || inbound != wantInbound { t.Fatalf("%+v: published (%v, %v) but the reconciler says (%v, %v)", c, shared, inbound, wantShared, wantInbound) } if shared != c.shared || inbound != c.accept { t.Fatalf("%+v: got (%v, %v), want (%v, %v)", c, shared, inbound, c.shared, c.accept) } } } // R9: the box publishes the fingerprint of its secrets key's public half, // never the key; no key, or a key that does not parse, publishes nothing. func TestEdgesFileSecretsKeyFingerprint(t *testing.T) { t.Parallel() priv, err := ecdh.P256().NewPrivateKey(bytes.Repeat([]byte{1}, 32)) if err != nil { t.Fatal(err) } privB64 := base64.StdEncoding.EncodeToString(priv.Bytes()) pubB64 := base64.StdEncoding.EncodeToString(priv.PublicKey().Bytes()) env := func(v string) func(string) string { return func(k string) string { if k == "CARLOS_SECRETS_KEY" { return v } return "" } } want := appconfig.KeyFingerprint(priv.PublicKey()) if got := edgesFileSecretsFP(env(privB64)); got != want { t.Fatalf("with a key = %q, want %q", got, want) } for _, v := range []string{"", "not base64!", base64.StdEncoding.EncodeToString([]byte("short"))} { if got := edgesFileSecretsFP(env(v)); got != "" { t.Errorf("CARLOS_SECRETS_KEY=%q published %q, want nothing", v, got) } } for _, fp := range []string{want, ""} { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var last []byte ident := edgesFile{Box: "quiet-harbour", Region: "eu-west-2", Placement: "uk", SecretsKeyFP: fp} if err := edgesFilePass(context.Background(), s, reg, ident, "203.0.113.10", &last); err != nil { t.Fatal(err) } body, _, err := s.Get(context.Background(), "control/edges/quiet-harbour.json") if err != nil { t.Fatal(err) } has := strings.Contains(string(body), `"secrets_key_fp"`) if has != (fp != "") { t.Fatalf("fp %q: key present = %v in %s", fp, has, body) } for _, secret := range []string{privB64, pubB64} { if strings.Contains(string(body), secret) { t.Fatal("the edges file carries key material") } } } } func TestEdgesFileCapabilityFollowsTheFlag(t *testing.T) { env := func(v string) func(string) string { return func(k string) string { if k == "CARLOS_REGION_HA" { return v } return "" } } if got := edgesFileCapabilities(env("")); len(got) != 0 { t.Fatalf("unset: %v", got) } if got := edgesFileCapabilities(env("1")); len(got) != 1 || got[0] != "region-ha-1" { t.Fatalf("set: %v", got) } if got := edgesFileCapabilities(env("0")); len(got) != 0 { t.Fatalf("\"0\" is off: %v", got) } } func TestEdgesFileRawWireBodyCarriesBoxEvidence(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var last []byte ident := edgesFile{Box: "annie", BoxID: "i-0abc", Capabilities: []string{"region-ha-1"}, Headroom: &edgeHeadroom{MemFreeMiB: 2210, DiskFreeMiB: 31200, Awake: 14}} if err := edgesFilePass(context.Background(), s, reg, ident, "1.2.3.4", &last); err != nil { t.Fatal(err) } body, _, err := s.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var raw map[string]json.RawMessage if err := json.Unmarshal(body, &raw); err != nil { t.Fatal(err) } for key, want := range map[string]string{ "box_id": `"i-0abc"`, "capabilities": `["region-ha-1"]`, "headroom": `{"mem_free_mib":2210,"disk_free_mib":31200,"awake":14}`, } { if string(raw[key]) != want { t.Errorf("%s = %s, want %s", key, raw[key], want) } } if _, ok := raw["draining"]; ok { t.Error("draining:false must be omitted") } } func TestEdgesFileOmitsBoxEvidenceWhenAbsent(t *testing.T) { s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) var last []byte if err := edgesFilePass(context.Background(), s, reg, edgesFile{Box: "annie"}, "1.2.3.4", &last); err != nil { t.Fatal(err) } body, _, _ := s.Get(context.Background(), "control/edges/annie.json") for _, key := range []string{"box_id", "capabilities", "draining", "headroom"} { if bytes.Contains(body, []byte(`"`+key+`"`)) { t.Errorf("%s present in %s", key, body) } } } func TestEdgesFileHeadroomAloneDoesNotRewriteTheFile(t *testing.T) { st := &putCountingStore{Store: release.NewDirStore(t.TempDir())} reg := edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var last []byte ident := edgesFile{Box: "annie", Headroom: &edgeHeadroom{MemFreeMiB: 100}} if err := edgesFilePass(context.Background(), st, reg, ident, "1.2.3.4", &last); err != nil { t.Fatal(err) } ident.Headroom = &edgeHeadroom{MemFreeMiB: 99} if err := edgesFilePass(context.Background(), st, reg, ident, "1.2.3.4", &last); err != nil { t.Fatal(err) } if st.puts != 1 { t.Fatalf("puts = %d, want 1: a headroom change alone is not a reason to write", st.puts) } } // The loop's timed pass refreshes headroom even when nothing else moved. func TestEdgesFileTimedPassRefreshesHeadroom(t *testing.T) { st := &putCountingStore{Store: release.NewDirStore(t.TempDir())} reg := edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var last []byte ident := edgesFile{Box: "annie", Headroom: &edgeHeadroom{MemFreeMiB: 100}} if err := edgesFileWrite(context.Background(), st, reg, ident, "1.2.3.4", &last, false); err != nil { t.Fatal(err) } ident.Headroom = &edgeHeadroom{MemFreeMiB: 42} if err := edgesFileWrite(context.Background(), st, reg, ident, "1.2.3.4", &last, true); err != nil { t.Fatal(err) } if st.puts != 2 { t.Fatalf("puts = %d, want 2: the timed pass must publish the new reading", st.puts) } body, _, err := st.Get(context.Background(), "control/edges/annie.json") if err != nil { t.Fatal(err) } var f edgesFile if err := json.Unmarshal(body, &f); err != nil || f.Headroom == nil || f.Headroom.MemFreeMiB != 42 { t.Fatalf("published headroom = %+v, err %v", f.Headroom, err) } // A box that publishes no headroom keeps today's behaviour exactly: // a timed pass with nothing changed writes nothing. plain := &putCountingStore{Store: release.NewDirStore(t.TempDir())} var plainLast []byte for i := 0; i < 2; i++ { if err := edgesFileWrite(context.Background(), plain, reg, edgesFile{Box: "betty"}, "1.2.3.4", &plainLast, true); err != nil { t.Fatal(err) } } if plain.puts != 1 { t.Fatalf("puts = %d, want 1 for a box with no headroom", plain.puts) } } // A restart must not rewrite an unchanged file just because the stored // copy carries a headroom reading. func TestEdgesFileSeededGateIgnoresStoredHeadroom(t *testing.T) { st := &putCountingStore{Store: release.NewDirStore(t.TempDir())} reg := edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var last []byte ident := edgesFile{Box: "annie", Headroom: &edgeHeadroom{MemFreeMiB: 100}} if err := edgesFilePass(context.Background(), st, reg, ident, "1.2.3.4", &last); err != nil { t.Fatal(err) } seeded := seedEdgesFileGate(context.Background(), st, "annie") ident.Headroom = &edgeHeadroom{MemFreeMiB: 7} if err := edgesFilePass(context.Background(), st, reg, ident, "1.2.3.4", &seeded); err != nil { t.Fatal(err) } if st.puts != 1 { t.Fatalf("puts = %d, want 1", st.puts) } } func TestEdgesFileStampIsOmittedWhenZero(t *testing.T) { b, _ := json.Marshal(edgeHost{Role: "home"}) if bytes.Contains(b, []byte("stamp")) { t.Fatalf("zero stamp on the wire: %s", b) } b, _ = json.Marshal(edgeHost{Role: "home", Stamp: 41}) if !bytes.Contains(b, []byte(`"stamp":41`)) { t.Fatalf("stamp missing: %s", b) } } // The move door (Task 4) admits a move only when every edges file of both // regions shows the box's armed floor and its verdict on carlos.prev, so // the writer publishes them from the box's own files at every write. func TestEdgesFilePublishesMovesProtocolFloorAndPrev(t *testing.T) { t.Parallel() type published struct { MovesProtocol *int `json:"moves_protocol"` Floor *string `json:"moves_floor_min_release"` Prev *string `json:"prev_release"` Allowed *string `json:"prev_allowed_for"` } publish := func(t *testing.T, dd, opt string) (published, string) { t.Helper() s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") var last []byte ident := withMovesFields(edgesFile{Box: "quiet-harbour"}, dd, opt) if err := edgesFilePass(context.Background(), s, reg, ident, "203.0.113.10", &last); err != nil { t.Fatal(err) } body, _, err := s.Get(context.Background(), "control/edges/quiet-harbour.json") if err != nil { t.Fatal(err) } var p published if err := json.Unmarshal(body, &p); err != nil { t.Fatal(err) } return p, string(body) } // Nothing armed, no carlos.prev. dd, opt := t.TempDir(), t.TempDir() p, body := publish(t, dd, opt) if p.MovesProtocol == nil || *p.MovesProtocol != moves.ProtocolVersion || !strings.Contains(body, `"moves_protocol":1`) { t.Fatalf("moves_protocol missing: %s", body) } if p.Floor != nil || p.Allowed != nil || p.Prev == nil || *p.Prev != "none" { t.Fatalf("unarmed box with no carlos.prev published %s", body) } // A carlos.prev with no sidecar: its release is unknown, so absent. os.WriteFile(systemPrevPath(opt), []byte("#!/bin/sh\n"), 0o755) if p, body = publish(t, dd, opt); p.Prev != nil { t.Fatalf("carlos.prev without a sidecar published %s", body) } // Armed, judged: every value as the box's files hold it, one line each. if err := writeLocalFloor(dd, moves.Floor{Min: 1, MinRelease: "v0.30.0"}); err != nil { t.Fatal(err) } if err := writePrevVersion(opt, "v0.31.0"); err != nil { t.Fatal(err) } writeFileDurable(filepath.Join(opt, moves.PrevAllowedFile), []byte("v0.30.0\n"), 0o644) p, body = publish(t, dd, opt) if p.Floor == nil || *p.Floor != "v0.30.0" || p.Prev == nil || *p.Prev != "v0.31.0" || p.Allowed == nil || *p.Allowed != "v0.30.0" { t.Fatalf("armed box published %s", body) } // No verdict: absent, which the door reads as below the floor. os.Remove(filepath.Join(opt, moves.PrevAllowedFile)) if p, body = publish(t, dd, opt); p.Allowed != nil { t.Fatalf("no verdict, yet published %s", body) } } // Region HA spec 2 §7 reads a box's edges file as stale after 15 minutes // (boxchoice.MaxEdgesAge), and the gate clears Generation, so a quiet box // stays placeable only if its timed pass rewrites an UNCHANGED body. With // headroom published (region HA on) it does, every timed pass (at most six // minutes apart); an untimed pass with nothing changed does not; and with // region HA off (no headroom) nothing is ever rewritten. func TestEdgesFileQuietBoxStaysFreshOnTimedPassesOnlyWithRegionHA(t *testing.T) { ctx, reg := context.Background(), edgesTestRegistry(t) seedRoute(t, reg, "app.example.com") run := func(ident edgesFile) (untimedPuts, timedPuts int) { st := &putCountingStore{Store: release.NewDirStore(t.TempDir())} var last []byte if err := edgesFileWrite(ctx, st, reg, ident, "1.2.3.4", &last, false); err != nil { t.Fatal(err) } if err := edgesFileWrite(ctx, st, reg, ident, "1.2.3.4", &last, false); err != nil { t.Fatal(err) } untimedPuts = st.puts if err := edgesFileWrite(ctx, st, reg, ident, "1.2.3.4", &last, true); err != nil { t.Fatal(err) } return untimedPuts, st.puts } on := edgesFile{Box: "annie", Capabilities: []string{capRegionHA1}, Headroom: &edgeHeadroom{MemFreeMiB: 100, DiskFreeMiB: 100, Awake: 1, MemTotalMiB: 1000, DiskTotalMiB: 1000}} if untimed, timed := run(on); untimed != 1 || timed != 2 { t.Fatalf("region HA on: puts = %d untimed, %d after a timed pass; want 1, 2", untimed, timed) } if untimed, timed := run(edgesFile{Box: "annie"}); untimed != 1 || timed != 1 { t.Fatalf("region HA off: puts = %d untimed, %d after a timed pass; want 1, 1", untimed, timed) } }