package console // The domains door (apidomains.go): attach, detach and list of the extra // hostnames an app's routes answer on (#151). The properties that matter, in // the order they'd hurt if lost: the gate is the instance family's, so an app // token bound elsewhere gets the byte-identical 404 and learns nothing; a // hostname someone else holds answers a NEUTRAL 409 that never names the // holder; detach is quiet in both directions (unknown host and another // owner's host read alike, and neither touches the claim or the serial); and // every effective write — and only an effective write — bumps control/serial // so boxes converge in seconds. import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "sort" "strings" "testing" "time" "github.com/carlosframework/platform/internal/certwarm" "github.com/carlosframework/platform/internal/domains" "github.com/carlosframework/platform/internal/edgesfile" "github.com/carlosframework/platform/internal/provision" "github.com/carlosframework/platform/internal/registry" "github.com/carlosframework/platform/internal/release" "github.com/carlosframework/platform/internal/status" "github.com/carlosframework/platform/internal/svcrole" ) func domainsURL(fx *consoleFixture, acct, app string) string { return fx.ts.URL + "/api/cli/apps/" + acct + "/" + app + "/domains" } // attachBody is the door's request shape. route is always sent (empty means // "default it"), because an omitted field and an empty one must behave the // same and the tests exercise the empty one. func attachBody(host, route string) string { b, err := json.Marshal(map[string]string{"host": host, "route": route}) if err != nil { panic(err) } return string(b) } type domainAttachResp struct { Host string `json:"host"` Route string `json:"route"` Created bool `json:"created"` } type domainDetachResp struct { Host string `json:"host"` Removed bool `json:"removed"` } type domainListResp struct { Domains []struct { Host string `json:"host"` Route string `json:"route"` Status string `json:"status"` DNSStatus string `json:"dns_status"` CertExpiresAt int64 `json:"cert_expires_at"` Wildcard bool `json:"wildcard"` Catchall bool `json:"catchall"` DelegationStatus string `json:"delegation_status"` } `json:"domains"` } // attachDomain posts one attach and returns the decoded answer, failing the // test on any status but the one asked for. func attachDomain(t *testing.T, fx *consoleFixture, token, host, route string) domainAttachResp { t.Helper() code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), token, attachBody(host, route)) if code != http.StatusOK { t.Fatalf("attach %s = %d %s, want 200", host, code, out) } var got domainAttachResp if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("attach body %s: %v", out, err) } return got } // claimOf reads a claim straight from the bucket — the store side of every // assertion here, so a handler that answers 200 without writing is caught. func claimOf(t *testing.T, fx *consoleFixture, host string) *domains.Claim { t.Helper() c, err := domains.GetClaim(context.Background(), fx.rel, host) if err != nil { t.Fatalf("claim %s: %v", host, err) } return c } func claimAbsent(t *testing.T, fx *consoleFixture, host string) { t.Helper() if _, err := domains.GetClaim(context.Background(), fx.rel, host); !errors.Is(err, os.ErrNotExist) { t.Fatalf("claim %s exists (err=%v), want none", host, err) } } // TestAPIDomainAttachCreates: a member's token attaches a hostname to a // named route — 200, created true, and a claim object in the bucket carrying // the member as its author. func TestAPIDomainAttachCreates(t *testing.T) { fx, member := instanceFixture(t, "code-dom-create") got := attachDomain(t, fx, member, "tickets.example.com", "go.tito.io") if got != (domainAttachResp{Host: "tickets.example.com", Route: "go.tito.io", Created: true}) { t.Fatalf("attach answer = %+v, want the host/route echoed with created true", got) } c := claimOf(t, fx, "tickets.example.com") if c.Schema != 1 || c.Account != "bab" || c.App != "titogo" || c.Route != "go.tito.io" { t.Fatalf("claim = %+v, want schema 1 bab/titogo -> go.tito.io", *c) } if c.CreatedBy != "alice@keymail.dev" { t.Fatalf("created_by = %q, want the member's address", c.CreatedBy) } if c.CreatedAt == "" { t.Fatalf("claim has no created_at: %+v", *c) } // The hostname is normalized before it is stored: a caller shouting the // host with a trailing dot claims the same object, not a second one. if got := attachDomain(t, fx, member, "TICKETS.example.com.", "go.tito.io"); got.Created || got.Host != "tickets.example.com" { t.Fatalf("re-attach of the same host in another case = %+v, want the normalized host, created false", got) } } func TestAPIDomainAttachRecordsDescriptionAndCanonicalRoute(t *testing.T) { fx, member := instanceFixture(t, "code-dom-message") body := `{"host":"tickets.example.com","route":"go.tito.io","message":"attach the ticket checkout"}` code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, body) if code != http.StatusOK { t.Fatalf("attach = %d %s, want 200", code, out) } events, err := fx.st.Events(OpsAccountID, "titogo", 1) if err != nil || len(events) != 1 { t.Fatalf("Events = %+v, %v", events, err) } got := events[0] if got.Action != "domain-attach" || got.TargetType != "instance" || got.Target != "go.tito.io" || got.Message != "attach the ticket checkout" || got.Detail != "attached hostname tickets.example.com -> go.tito.io (cli)" { t.Fatalf("activity = %+v", got) } } func TestAPIDomainAttachRejectsInvalidDescriptionBeforeWriting(t *testing.T) { fx, member := instanceFixture(t, "code-dom-message-invalid") body := `{"host":"tickets.example.com","route":"go.tito.io","message":"first\nsecond"}` code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, body) if code != http.StatusBadRequest { t.Fatalf("attach = %d %s, want 400", code, out) } claimAbsent(t, fx, "tickets.example.com") if events, err := fx.st.Events(OpsAccountID, "titogo", 10); err != nil || len(events) != 0 { t.Fatalf("activity after invalid message = %+v, %v", events, err) } } // TestAPIDomainAttachAppToken: the app-held credential works on its own app // — and a token bound to a NEIGHBOURING app in the same account meets the // family's byte-identical 404 (apiInstancePrincipal's contract), never a // hint that the path exists. func TestAPIDomainAttachAppToken(t *testing.T) { fx, _ := instanceFixture(t, "code-dom-apptoken") now := time.Now() if _, err := fx.st.CreateAppIn(OpsAccountID, "other", "alice@keymail.dev", now); err != nil { t.Fatal(err) } mine, err := fx.st.NewAppToken(OpsAccountID, "titogo", "alice@keymail.dev", "signup", now) if err != nil { t.Fatal(err) } foreign, err := fx.st.NewAppToken(OpsAccountID, "other", "alice@keymail.dev", "signup", now) if err != nil { t.Fatal(err) } got := attachDomain(t, fx, mine, "tickets.example.com", "go.tito.io") if !got.Created { t.Fatalf("app token attach = %+v, want created true", got) } if c := claimOf(t, fx, "tickets.example.com"); c.CreatedBy != "app:bab/titogo" { t.Fatalf("created_by = %q, want the app principal app:bab/titogo", c.CreatedBy) } want := canonicalNotFound(t) for _, c := range []struct{ what, method, url, body string }{ {"foreign app token attach", http.MethodPost, domainsURL(fx, "bab", "titogo"), attachBody("other.example.com", "go.tito.io")}, {"foreign app token list", http.MethodGet, domainsURL(fx, "bab", "titogo"), ""}, {"foreign app token detach", http.MethodDelete, domainsURL(fx, "bab", "titogo") + "/tickets.example.com", ""}, } { code, h, out := rawReq(t, c.method, c.url, foreign, c.body) assertNotFound(t, c.what, want, code, h, out) } // The refused calls changed nothing: no new claim, and the one that // existed is still there. claimAbsent(t, fx, "other.example.com") claimOf(t, fx, "tickets.example.com") } // TestAPIDomainAttachIdempotent: attach is the caller's GOAL, not an event — // a second identical attach is 200 with created false, and an attach naming a // different route converges the claim in place rather than refusing it. func TestAPIDomainAttachIdempotent(t *testing.T) { fx, member := instanceFixture(t, "code-dom-idem") if got := attachDomain(t, fx, member, "tickets.example.com", "go.tito.io"); !got.Created { t.Fatalf("first attach = %+v, want created true", got) } if got := attachDomain(t, fx, member, "tickets.example.com", "go.tito.io"); got.Created { t.Fatalf("second identical attach = %+v, want created false", got) } if got := attachDomain(t, fx, member, "tickets.example.com", "two.go.tito.io"); got.Created || got.Route != "two.go.tito.io" { t.Fatalf("re-attach to another route = %+v, want created false on the new route", got) } if c := claimOf(t, fx, "tickets.example.com"); c.Route != "two.go.tito.io" { t.Fatalf("claim route = %q, want the converged two.go.tito.io", c.Route) } } // TestAPIDomainAttachConflictNeutral: a hostname another account holds is a // 409 whose body says exactly one thing — never who holds it, never whether // the holder is in this deployment at all. func TestAPIDomainAttachConflictNeutral(t *testing.T) { fx, member := instanceFixture(t, "code-dom-conflict") if _, _, err := domains.AttachClaim(context.Background(), fx.rel, domains.Claim{ Host: "tickets.example.com", Account: "cdef", App: "widgets", Route: "widgets.example.net", CreatedAt: time.Now().UTC().Format(time.RFC3339), }); err != nil { t.Fatal(err) } code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, attachBody("tickets.example.com", "go.tito.io")) if code != http.StatusConflict { t.Fatalf("attach of a held hostname = %d %s, want 409", code, out) } if got := strings.TrimSpace(out); got != `{"error":"hostname unavailable"}` { t.Fatalf("409 body = %s, want the neutral {\"error\":\"hostname unavailable\"}", got) } // The holder's claim is untouched by the refusal. if c := claimOf(t, fx, "tickets.example.com"); c.Account != "cdef" || c.App != "widgets" { t.Fatalf("claim after a refused attach = %+v, want the holder's own", *c) } } // TestAPIDomainAttachValidation: every hostname this door refuses on a // deployment that reserves platform domains (the flagship, carloku), each // with nothing written behind it: malformed, bare-label, under a configured // deny domain, under the deployment's apps domain, the console's own origin // host and a name under it, and a RETIRED console origin // (CONSOLE_REDIRECT_HOSTS, which this console still answers on and 301s // away, such as tito's carlos.tito.io). func TestAPIDomainAttachValidation(t *testing.T) { fx, member := instanceFixture(t, "code-dom-validate") fx.srv.cfg.DenyDomains = []string{"", "denied.test"} fx.srv.cfg.AppsDomain = "oncarlos.test" fx.srv.cfg.RedirectHosts = []string{"", "Carlos.Tito.Test:8443"} fx.srv.cfg.ReservePlatformDomains = true origin, err := url.Parse(fx.srv.cfg.Origin) if err != nil { t.Fatal(err) } for _, host := range []string{ "Bad_Host!", // not a hostname at all "nodots", // a bare label is never a public hostname "x.denied.test", // under a CONSOLE_DENY_DOMAINS entry "denied.test", // the deny entry itself "one.bab.oncarlos.test", // platform apex space (spec §5) "oncarlos.test", // the apps domain itself origin.Hostname(), // the console's own origin host "x." + origin.Hostname(), // and anything under it "carlos.tito.test", // a retired console origin, normalized as ServeHTTP normalizes it "old.carlos.tito.test", // and anything under it } { code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, attachBody(host, "go.tito.io")) if code != http.StatusBadRequest { t.Errorf("attach %q = %d %s, want 400", host, code, out) } claimAbsent(t, fx, strings.ToLower(host)) } // An empty deny entry matches nothing: the ordinary hostname still goes // through with "" in the list. if got := attachDomain(t, fx, member, "tickets.example.com", "go.tito.io"); !got.Created { t.Fatalf("ordinary attach with an empty deny entry present = %+v, want created true", got) } } // TestAPIDomainAttachUnreservedDefault: ReservePlatformDomains is off by // default, which is the self-hosted shape. There the console, the apps // domain and the custom domains usually share one zone that one person // owns. The console's own hostnames and the operator's CONSOLE_DENY_DOMAINS // are still refused. The apps domain, and names under the console's // hostnames, are not. func TestAPIDomainAttachUnreservedDefault(t *testing.T) { fx, member := instanceFixture(t, "code-dom-unreserved") origin, err := url.Parse(fx.srv.cfg.Origin) if err != nil { t.Fatal(err) } fx.srv.cfg.DenyDomains = []string{"denied.test"} fx.srv.cfg.AppsDomain = origin.Hostname() // the console sits at the apps-domain apex fx.srv.cfg.RedirectHosts = []string{"Carlos.Tito.Test:8443"} for _, host := range []string{ "x.denied.test", // the operator's own list still applies origin.Hostname(), // the console's own origin host "carlos.tito.test", // a retired console origin } { code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, attachBody(host, "go.tito.io")) if code != http.StatusBadRequest { t.Errorf("attach %q = %d %s, want 400", host, code, out) } claimAbsent(t, fx, host) } for _, host := range []string{ "blog." + origin.Hostname(), // under the console host AND the apps domain "one.bab." + origin.Hostname(), // platform-shaped, but no route holds it "old.carlos.tito.test", // under a retired console origin } { if got := attachDomain(t, fx, member, host, "go.tito.io"); !got.Created { t.Errorf("attach %q unreserved = %+v, want created true", host, got) } } } // TestAPIDomainAttachRouteDefault: the route may be omitted when there is // exactly one thing it could mean. Two instance records make it ambiguous, // and ambiguity names the flag that resolves it rather than guessing. func TestAPIDomainAttachRouteDefault(t *testing.T) { fx, member := instanceFixture(t, "code-dom-route") ctx := context.Background() rec := provision.Record{Schema: 1, Host: "one.go.tito.io", Slug: "one", App: "titogo", Account: "bab", Channel: "stable", CreatedAt: time.Now().UTC()} if err := provision.CreateRecord(ctx, fx.rel, rec); err != nil { t.Fatal(err) } if got := attachDomain(t, fx, member, "tickets.example.com", ""); got.Route != "one.go.tito.io" { t.Fatalf("attach with no route = %+v, want the app's one instance as the route", got) } if c := claimOf(t, fx, "tickets.example.com"); c.Route != "one.go.tito.io" { t.Fatalf("claim route = %q, want one.go.tito.io", c.Route) } rec.Host, rec.Slug = "two.go.tito.io", "two" if err := provision.CreateRecord(ctx, fx.rel, rec); err != nil { t.Fatal(err) } code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, attachBody("other.example.com", "")) if code != http.StatusBadRequest { t.Fatalf("ambiguous attach = %d %s, want 400", code, out) } if !strings.Contains(out, "-route") { t.Fatalf("ambiguous attach body = %s, want it to name the --route flag", out) } claimAbsent(t, fx, "other.example.com") } // TestAPIDomainDetachQuiet: detach answers the same 200 shape three ways — // the claim it removed, a hostname nobody claimed, and one another account // holds — so a caller cannot use detach to discover who owns a hostname. // Only the first of the three actually removes anything. func TestAPIDomainDetachQuiet(t *testing.T) { fx, member := instanceFixture(t, "code-dom-detach") attachDomain(t, fx, member, "tickets.example.com", "go.tito.io") if _, _, err := domains.AttachClaim(context.Background(), fx.rel, domains.Claim{ Host: "theirs.example.com", Account: "cdef", App: "widgets", Route: "widgets.example.net", CreatedAt: time.Now().UTC().Format(time.RFC3339), }); err != nil { t.Fatal(err) } detach := func(host string) domainDetachResp { t.Helper() code, _, out := rawReq(t, http.MethodDelete, domainsURL(fx, "bab", "titogo")+"/"+host, member, "") if code != http.StatusOK { t.Fatalf("detach %s = %d %s, want 200", host, code, out) } var got domainDetachResp if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("detach body %s: %v", out, err) } return got } if got := detach("tickets.example.com"); got != (domainDetachResp{Host: "tickets.example.com", Removed: true}) { t.Fatalf("detach of an own claim = %+v, want removed true", got) } claimAbsent(t, fx, "tickets.example.com") if got := detach("tickets.example.com"); got.Removed { t.Fatalf("second detach = %+v, want removed false", got) } if got := detach("never.example.com"); got != (domainDetachResp{Host: "never.example.com", Removed: false}) { t.Fatalf("detach of an unknown hostname = %+v, want the same shape, removed false", got) } if got := detach("theirs.example.com"); got != (domainDetachResp{Host: "theirs.example.com", Removed: false}) { t.Fatalf("detach of another account's claim = %+v, want the same quiet answer", got) } if c := claimOf(t, fx, "theirs.example.com"); c.Account != "cdef" || c.App != "widgets" { t.Fatalf("another account's claim after a detach = %+v, want it intact", *c) } // Traversal defence: a {host} arrives percent-decoded, so a path with // separators in it reaches the handler. It is refused on shape, before // anything builds a bucket key from it. for _, bad := range []string{"bad_host", "..%2F..%2Finstances.json"} { if code, _, out := rawReq(t, http.MethodDelete, domainsURL(fx, "bab", "titogo")+"/"+bad, member, ""); code != http.StatusBadRequest { t.Errorf("detach %q = %d %s, want 400", bad, code, out) } } } // TestAPIDomainList: this app's claims only, each joined to the box readings // sweep — a hostname a live box reports carries its DNS/cert columns and // reads "live"; one no live box reports reads "pending", including one only a // STALE box still remembers. func TestAPIDomainList(t *testing.T) { fx, member := instanceFixture(t, "code-dom-list") ctx := context.Background() now := time.Now() if _, err := fx.st.CreateAppIn(OpsAccountID, "other", "alice@keymail.dev", now); err != nil { t.Fatal(err) } attachDomain(t, fx, member, "live.example.com", "go.tito.io") attachDomain(t, fx, member, "pending.example.com", "go.tito.io") attachDomain(t, fx, member, "stale.example.com", "go.tito.io") if _, _, err := domains.AttachClaim(ctx, fx.rel, domains.Claim{ Host: "elsewhere.example.com", Account: "bab", App: "other", Route: "other.go.tito.io", CreatedAt: now.UTC().Format(time.RFC3339), }); err != nil { t.Fatal(err) } if err := status.WriteBox(ctx, fx.rel, status.Box{ GeneratedAt: now, Label: "ada-reporting", Region: "eu-west-1", Metrics: &status.BoxMetrics{Aliases: map[string]status.AliasReading{ "live.example.com": {Route: "go.tito.io", DNSStatus: "ok", CertExpiresAt: 1786000000}, "elsewhere.example.com": {Route: "other.go.tito.io", DNSStatus: "ok"}, }}, }); err != nil { t.Fatal(err) } // A box that stopped reporting drops OUT of the join (the stagedVersions // rule): its last-known reading must not go on answering as if current. if err := status.WriteBox(ctx, fx.rel, status.Box{ GeneratedAt: now.Add(-2 * time.Hour), Label: "bob-silent", Region: "eu-west-1", Metrics: &status.BoxMetrics{Aliases: map[string]status.AliasReading{ "stale.example.com": {Route: "go.tito.io", DNSStatus: "ok", CertExpiresAt: 1786000000}, }}, }); err != nil { t.Fatal(err) } code, _, out := rawReq(t, http.MethodGet, domainsURL(fx, "bab", "titogo"), member, "") if code != http.StatusOK { t.Fatalf("list = %d %s, want 200", code, out) } var got domainListResp if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("list body %s: %v", out, err) } if len(got.Domains) != 3 { t.Fatalf("list = %+v, want exactly this app's three claims", got.Domains) } byHost := map[string]struct { Host string `json:"host"` Route string `json:"route"` Status string `json:"status"` DNSStatus string `json:"dns_status"` CertExpiresAt int64 `json:"cert_expires_at"` Wildcard bool `json:"wildcard"` Catchall bool `json:"catchall"` DelegationStatus string `json:"delegation_status"` }{} for _, d := range got.Domains { byHost[d.Host] = d } if _, ok := byHost["elsewhere.example.com"]; ok { t.Fatalf("another app's claim is in this app's listing: %+v", got.Domains) } live := byHost["live.example.com"] if live.Status != "live" || live.DNSStatus != "ok" || live.CertExpiresAt != 1786000000 || live.Route != "go.tito.io" { t.Fatalf("reported hostname = %+v, want live with its DNS/cert columns", live) } if p := byHost["pending.example.com"]; p.Status != "pending" || p.DNSStatus != "" || p.CertExpiresAt != 0 { t.Fatalf("unreported hostname = %+v, want pending with no readings", p) } if s := byHost["stale.example.com"]; s.Status != "pending" || s.DNSStatus != "" { t.Fatalf("hostname only a stale box reports = %+v, want pending", s) } } // TestAPIDomainListSuppressesGuidanceForUnresolvedDNS pins the honesty rule // this task adds: "unresolved" means the DNS LOOKUP FAILED (our resolver), // not that the member's record is missing or wrong. The door must not print // "point your DNS here" guidance for it — that would blame the member for // our outage. "elsewhere" (a real, wrong answer) still earns guidance, so // the suppression is specific to "unresolved" and not a blanket regression. func TestAPIDomainListSuppressesGuidanceForUnresolvedDNS(t *testing.T) { fx, member := instanceFixture(t, "code-dom-unresolved") ctx := context.Background() now := time.Now() attachDomain(t, fx, member, "broken.example.com", "go.tito.io") attachDomain(t, fx, member, "wrong.example.com", "go.tito.io") if err := status.WriteBox(ctx, fx.rel, status.Box{ GeneratedAt: now, Label: "ada-reporting", Region: "eu-west-1", Metrics: &status.BoxMetrics{Aliases: map[string]status.AliasReading{ "broken.example.com": {Route: "go.tito.io", DNSStatus: "unresolved"}, "wrong.example.com": {Route: "go.tito.io", DNSStatus: "elsewhere"}, }}, }); err != nil { t.Fatal(err) } code, _, out := rawReq(t, http.MethodGet, domainsURL(fx, "bab", "titogo"), member, "") if code != http.StatusOK { t.Fatalf("list = %d %s, want 200", code, out) } var got struct { Domains []struct { Host string `json:"host"` DNSStatus string `json:"dns_status"` Guidance string `json:"guidance"` } `json:"domains"` } if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("list body %s: %v", out, err) } byHost := map[string]string{} for _, d := range got.Domains { if d.DNSStatus != map[string]string{"broken.example.com": "unresolved", "wrong.example.com": "elsewhere"}[d.Host] { t.Fatalf("%s dns_status = %q, unexpected", d.Host, d.DNSStatus) } byHost[d.Host] = d.Guidance } if g := byHost["broken.example.com"]; g != "" { t.Fatalf("unresolved host got guidance %q, want none — our lookup failure is not the member's problem to fix", g) } if g := byHost["wrong.example.com"]; g == "" { t.Fatal("a real wrong-answer (elsewhere) host must still get point-your-DNS guidance") } } // domainEvents counts this app's audit rows whose action starts "domain-". func domainEvents(t *testing.T, fx *consoleFixture) int { t.Helper() events, err := fx.st.Events(OpsAccountID, "titogo", 50) if err != nil { t.Fatal(err) } n := 0 for _, e := range events { if strings.HasPrefix(e.Action, "domain-") { n++ } } return n } // TestAPIDomainSerialBump: boxes converge off control/serial, so every // EFFECTIVE write announces itself — and the two no-ops, a re-attach that // changed nothing and a detach that removed nothing, announce nothing and // write no audit row. That matters more than it looks: titogo's router // re-attaches its hostnames on every reload pass, so redundant attaches are // the STEADY STATE — a bump per pass would keep the whole fleet converging // onto nothing, and an audit row per pass would bury the tenant's log. func TestAPIDomainSerialBump(t *testing.T) { fx, member := instanceFixture(t, "code-dom-serial") if got := serial(t, fx); got != 0 { t.Fatalf("serial before any domain write = %d, want 0", got) } attachDomain(t, fx, member, "tickets.example.com", "go.tito.io") if got := serial(t, fx); got != 1 { t.Fatalf("serial after an attach = %d, want 1", got) } if got := domainEvents(t, fx); got != 1 { t.Fatalf("audit rows after an attach = %d, want 1", got) } // The router's steady state: the same attach again, changing nothing. if got := attachDomain(t, fx, member, "tickets.example.com", "go.tito.io"); got.Created { t.Fatalf("no-op re-attach = %+v, want created false", got) } if got := serial(t, fx); got != 1 { t.Fatalf("serial after a no-op re-attach = %d, want it unmoved at 1", got) } if got := domainEvents(t, fx); got != 1 { t.Fatalf("audit rows after a no-op re-attach = %d, want it unmoved at 1", got) } // A converge IS a write: new route, so the fleet hears about it. if got := attachDomain(t, fx, member, "tickets.example.com", "two.go.tito.io"); got.Created { t.Fatalf("converge attach = %+v, want created false", got) } if got := serial(t, fx); got != 2 { t.Fatalf("serial after a converge = %d, want 2", got) } if got := domainEvents(t, fx); got != 2 { t.Fatalf("audit rows after a converge = %d, want 2", got) } if code, _, out := rawReq(t, http.MethodDelete, domainsURL(fx, "bab", "titogo")+"/tickets.example.com", member, ""); code != http.StatusOK { t.Fatalf("detach = %d %s, want 200", code, out) } if got := serial(t, fx); got != 3 { t.Fatalf("serial after an effective detach = %d, want 3", got) } if got := domainEvents(t, fx); got != 3 { t.Fatalf("audit rows after an effective detach = %d, want 3", got) } if code, _, out := rawReq(t, http.MethodDelete, domainsURL(fx, "bab", "titogo")+"/never.example.com", member, ""); code != http.StatusOK { t.Fatalf("no-op detach = %d %s, want 200", code, out) } if got := serial(t, fx); got != 3 { t.Fatalf("serial after a no-op detach = %d, want it unmoved at 3", got) } if got := domainEvents(t, fx); got != 3 { t.Fatalf("audit rows after a no-op detach = %d, want it unmoved at 3", got) } } // attachBodyKind is attachBody with the deploy extras (#82): kind and/or // channel ride the same POST body; empty fields are simply absent, matching // what the client sends (omitempty). func attachBodyKind(host, route, kind, channel string) string { m := map[string]string{"host": host} if route != "" { m["route"] = route } if kind != "" { m["kind"] = kind } if channel != "" { m["channel"] = channel } b, err := json.Marshal(m) if err != nil { panic(err) } return string(b) } // TestAPIDomainAttachKindValidation pins the two 400s the kind extension // adds: route and kind together (an alias target and a first-route mint are // two different instructions), and any kind but "static" (nothing else can // be minted from a domain attach). Neither writes a claim. func TestAPIDomainAttachKindValidation(t *testing.T) { fx, member := instanceFixture(t, "code-dom-kind-400") for name, body := range map[string]string{ "route and kind together": attachBodyKind("both.example.com", "go.tito.io", "static", ""), "kind other than static": attachBodyKind("both.example.com", "", "binary", ""), } { code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, body) if code != http.StatusBadRequest { t.Errorf("%s = %d %s, want 400", name, code, out) } claimAbsent(t, fx, "both.example.com") } } // TestAPIDomainAttachKindStaticFirstRoute: kind=static against an app with // no ready route runs the shared attach core's first-route branch — the // claim (empty stored route) AND a declared static provision record land, // and the answer's route is the host itself, the primary the record just // declared. This is `carlos deploy -kind static -host `'s server half. func TestAPIDomainAttachKindStaticFirstRoute(t *testing.T) { fx, member := instanceFixture(t, "code-dom-kind-first") // The fixture registry holds no titogo routes, so the core has nothing // to alias; the first-route branch needs something shipped to resolve // the record's channel from. shipVersion(t, fx, "titogo", "v1") seedChannel(t, fx, "titogo", "canary/live", "v1") const host = "fresh.example.com" code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"fresh.example.com","kind":"static","message":"publish the new site"}`) if code != http.StatusOK { t.Fatalf("attach = %d %s, want 200", code, out) } var got domainAttachResp if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("attach body %s: %v", out, err) } if got != (domainAttachResp{Host: host, Route: host, Created: true}) { t.Fatalf("attach answer = %+v, want route == host (the first-route primary) and created true", got) } c := claimOf(t, fx, host) if c.Route != "" || c.Account != "bab" || c.App != "titogo" { t.Fatalf("claim = %+v, want a first-route claim (empty stored route) for bab/titogo", *c) } rec, err := provision.GetRecord(context.Background(), fx.rel, "bab", "titogo", host) if err != nil { t.Fatalf("record: %v, want the declared static record", err) } if rec.Kind != "static" || rec.Channel != "canary/live" || rec.Slug != "" { t.Fatalf("record = %+v, want a static record on canary/live", *rec) } events, err := fx.st.Events(OpsAccountID, "titogo", 1) if err != nil || len(events) != 1 { t.Fatalf("Events = %+v, %v", events, err) } if got := events[0]; got.Action != "domain-attach" || got.TargetType != "instance" || got.Target != host || got.Message != "publish the new site" || got.Detail != host+" (first route, canary/live)" { t.Fatalf("activity = %+v", got) } } // TestAPIDomainAttachKindStaticWithReadyRouteAliases: the same kind=static // body against an app that DOES hold a ready route is an ordinary alias — // the core answers its own question and nothing static is minted: the claim // stores the ready route, the answer reports it, and no provision record // appears at the host's key. func TestAPIDomainAttachKindStaticWithReadyRouteAliases(t *testing.T) { fx, member := instanceFixture(t, "code-dom-kind-alias") fx.srv.cfg.Registry = attachRegistry(t, registry.Route{Host: "titogo.bab.oncarlos.test", Kind: "static", App: "titogo", Account: "bab", Channel: "canary/live", Status: "ready"}, ) const host = "alias.example.com" code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, attachBodyKind(host, "", "static", "")) if code != http.StatusOK { t.Fatalf("attach = %d %s, want 200", code, out) } var got domainAttachResp if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("attach body %s: %v", out, err) } if got != (domainAttachResp{Host: host, Route: "titogo.bab.oncarlos.test", Created: true}) { t.Fatalf("attach answer = %+v, want the ready route as the alias target", got) } if c := claimOf(t, fx, host); c.Route != "titogo.bab.oncarlos.test" { t.Fatalf("claim = %+v, want the alias claim naming the ready route", *c) } if _, err := provision.GetRecord(context.Background(), fx.rel, "bab", "titogo", host); !errors.Is(err, os.ErrNotExist) { t.Fatalf("record: %v, want NONE — an alias attach must not mint a static record", err) } } // ---- wildcard/catchall capability door (Task 5) ---------------------------- // TestAttachWildcardCNAMEGate: the attach body's optional wildcard/catchall // pointers (Task 5). Enabling wildcard is gated on two things — a configured // delegation zone, and a live _acme-challenge CNAME delegating to it — and // catchall is refused without wildcard, the same ErrCatchallNeedsWildcard // domains.SetClaimCapabilities itself enforces. Every refusal here leaves the // stored claim exactly as it was. func TestAttachWildcardCNAMEGate(t *testing.T) { const zone = "acme.oncarlos.com" const host = "woodstar.app" wantCNAME := "_acme-challenge." + host + "." + zone + "." t.Run("missing CNAME refuses with the record to create", func(t *testing.T) { fx, member := instanceFixture(t, "code-dom-wc-missing") fx.srv.delegationZone = zone fx.srv.lookupCNAME = func(context.Context, string) (string, error) { return "", errors.New("not found") } code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"`+host+`","route":"go.tito.io","wildcard":true}`) if code != http.StatusUnprocessableEntity { t.Fatalf("attach with a missing CNAME = %d %s, want 422", code, out) } // Decoded, not a raw substring match: json.Encoder HTML-escapes ">" // to > by default, which json.Unmarshal undoes transparently // but a literal strings.Contains against the raw wire bytes would not. var got struct { Error string `json:"error"` } if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("422 body %s: %v", out, err) } want := "create CNAME _acme-challenge." + host + " -> _acme-challenge." + host + "." + zone + ", then retry" if got.Error != want { t.Fatalf("422 error = %q, want %q", got.Error, want) } if c := claimOf(t, fx, host); c.Wildcard { t.Fatalf("claim after a refused wildcard enable = %+v, want Wildcard still false", *c) } }) t.Run("correct CNAME enables wildcard and bumps the serial", func(t *testing.T) { fx, member := instanceFixture(t, "code-dom-wc-ok") fx.srv.delegationZone = zone fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) { if name == "_acme-challenge."+host { return wantCNAME, nil } return "", errors.New("not found") } before := serial(t, fx) code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"`+host+`","route":"go.tito.io","wildcard":true}`) if code != http.StatusOK { t.Fatalf("attach with a correct CNAME = %d %s, want 200", code, out) } if c := claimOf(t, fx, host); !c.Wildcard { t.Fatalf("claim after an accepted wildcard enable = %+v, want Wildcard true", *c) } if got := serial(t, fx); got <= before { t.Fatalf("serial after a wildcard enable = %d, want it to have moved past %d", got, before) } }) // IMPORTANT-1 (review): DNS names compare case-insensitively (RFC 4343) // and a resolver answers in the record's own authored case, not the // zone's. A customer who typed their CNAME target in mixed case must // still delegate, not read as a permanently broken/missing record. t.Run("mixed-case CNAME target still delegates", func(t *testing.T) { fx, member := instanceFixture(t, "code-dom-wc-mixedcase") fx.srv.delegationZone = zone mixedCase := "_ACME-Challenge." + host + "." + strings.ToUpper(zone) + "." fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) { if name == "_acme-challenge."+host { return mixedCase, nil } return "", errors.New("not found") } code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"`+host+`","route":"go.tito.io","wildcard":true}`) if code != http.StatusOK { t.Fatalf("attach with a mixed-case CNAME target = %d %s, want 200", code, out) } if c := claimOf(t, fx, host); !c.Wildcard { t.Fatalf("claim after a mixed-case CNAME enable = %+v, want Wildcard true", *c) } }) // IMPORTANT-2 (review): re-sending wildcard:true for a claim that // already has it must not re-run the CNAME lookup at all — proven here // by a stub that always errors (simulating a resolver blip) plus a call // counter: if the gate wrongly re-checked on every idempotent re-attach, // this would 422 instead of succeeding, and the counter would be // nonzero. t.Run("re-sending wildcard true on an already-wildcard claim skips the lookup", func(t *testing.T) { fx, member := instanceFixture(t, "code-dom-wc-idempotent") fx.srv.delegationZone = zone calls := 0 fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) { if name == "_acme-challenge."+host { return wantCNAME, nil } return "", errors.New("not found") } code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"`+host+`","route":"go.tito.io","wildcard":true}`) if code != http.StatusOK { t.Fatalf("seed wildcard enable = %d %s, want 200", code, out) } // Now break the resolver entirely (a blip) and count every call. fx.srv.lookupCNAME = func(context.Context, string) (string, error) { calls++ return "", errors.New("resolver unavailable") } code, _, out = rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"`+host+`","route":"go.tito.io","wildcard":true}`) if code != http.StatusOK { t.Fatalf("re-sending wildcard:true on an already-wildcard claim = %d %s, want 200 (no re-check)", code, out) } if calls != 0 { t.Fatalf("lookupCNAME was called %d times on an idempotent re-attach, want 0", calls) } if c := claimOf(t, fx, host); !c.Wildcard { t.Fatalf("claim after the idempotent re-attach = %+v, want Wildcard still true", *c) } }) // IMPORTANT-3 (review): the capability write's own ErrHostUnavailable // branch (setDomainCapabilities, apidomains.go), forced without a new // test seam: the lookupCNAME stub DETACHES the claim as a side effect // (simulating the claim changing hands between the attach write above // and SetClaimCapabilities's own read) and THEN returns the correct // CNAME, so the gate passes but SetClaimCapabilities's read finds // os.ErrNotExist and returns ErrHostUnavailable — which must answer the // SAME byte-identical 404 every other non-owner refusal does. t.Run("claim vanishing between attach and capability write answers the byte-identical 404", func(t *testing.T) { fx, member := instanceFixture(t, "code-dom-wc-vanish") fx.srv.delegationZone = zone fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) { if _, err := domains.DetachClaim(context.Background(), fx.rel, host, "bab", "titogo"); err != nil { t.Fatal(err) } return wantCNAME, nil } want := canonicalNotFound(t) code, h, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"`+host+`","route":"go.tito.io","wildcard":true}`) assertNotFound(t, "capability write after the claim vanished mid-request", want, code, h, out) claimAbsent(t, fx, host) }) t.Run("catchall without wildcard refuses and stores nothing", func(t *testing.T) { fx, member := instanceFixture(t, "code-dom-wc-catchall") fx.srv.delegationZone = zone fx.srv.lookupCNAME = func(context.Context, string) (string, error) { return "", errors.New("not found") } code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"`+host+`","route":"go.tito.io","catchall":true}`) if code != http.StatusUnprocessableEntity { t.Fatalf("attach with catchall and no wildcard = %d %s, want 422", code, out) } if !strings.Contains(out, "catchall requires wildcard") { t.Fatalf("422 body = %s, want it to mention catchall requires wildcard", out) } if c := claimOf(t, fx, host); c.Wildcard || c.Catchall { t.Fatalf("claim after a refused catchall = %+v, want both false", *c) } }) t.Run("wildcard and catchall together with a correct CNAME store both", func(t *testing.T) { fx, member := instanceFixture(t, "code-dom-wc-both") fx.srv.delegationZone = zone fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) { if name == "_acme-challenge."+host { return wantCNAME, nil } return "", errors.New("not found") } code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"`+host+`","route":"go.tito.io","wildcard":true,"catchall":true}`) if code != http.StatusOK { t.Fatalf("attach with wildcard+catchall and a correct CNAME = %d %s, want 200", code, out) } c := claimOf(t, fx, host) if !c.Wildcard || !c.Catchall { t.Fatalf("claim = %+v, want both wildcard and catchall true", *c) } }) t.Run("non-owner token gets the byte-identical 404", func(t *testing.T) { fx, _ := instanceFixture(t, "code-dom-wc-nonowner") fx.srv.delegationZone = zone now := time.Now() if _, err := fx.st.CreateAppIn(OpsAccountID, "other", "alice@keymail.dev", now); err != nil { t.Fatal(err) } foreign, err := fx.st.NewAppToken(OpsAccountID, "other", "alice@keymail.dev", "signup", now) if err != nil { t.Fatal(err) } want := canonicalNotFound(t) code, h, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), foreign, `{"host":"`+host+`","route":"go.tito.io","wildcard":true}`) assertNotFound(t, "foreign token attach with wildcard", want, code, h, out) claimAbsent(t, fx, host) }) // The zone-unset case doubles as the Task 1 review's authority-hole // regression: the body smuggles BOTH wildcard and catchall alongside // host/route, in the very attach call that creates the claim. If the // handler ever passed those fields straight into AttachClaim's create // path (which marshals its Claim argument verbatim), they would land // even though the capability step below refuses. They must not: the // only writer of Wildcard/Catchall is SetClaimCapabilities, called AFTER // the create, and gated on the zone. t.Run("zone unset refuses, and smuggled capability fields never reach the claim", func(t *testing.T) { fx, member := instanceFixture(t, "code-dom-wc-nozone") // fx.srv.delegationZone is left at its zero value "" — no // CARLOS_ACME_DELEGATION_ZONE configured for this fixture. code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"`+host+`","route":"go.tito.io","wildcard":true,"catchall":true}`) if code != http.StatusUnprocessableEntity { t.Fatalf("attach with wildcard and no zone = %d %s, want 422", code, out) } if !strings.Contains(out, "no delegation zone") { t.Fatalf("422 body = %s, want it to mention no delegation zone", out) } if c := claimOf(t, fx, host); c.Wildcard || c.Catchall { t.Fatalf("claim after a refused capability request = %+v, want both false — the smuggled fields must not reach AttachClaim's create path", *c) } }) } // TestAttachWildcardDisableCascadesCatchallOff: turning wildcard off never // requires DNS (the CNAME gate is skipped entirely — proven here by breaking // the stub before the disable call), and catchall — which cannot legally // outlive wildcard — cascades off in the SAME call rather than making the // caller send catchall=false too, or the door routing itself into // ErrCatchallNeedsWildcard on its own converge. func TestAttachWildcardDisableCascadesCatchallOff(t *testing.T) { const zone = "acme.oncarlos.com" const host = "wild.example.com" fx, member := instanceFixture(t, "code-dom-wc-disable") fx.srv.delegationZone = zone wantCNAME := "_acme-challenge." + host + "." + zone + "." fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) { if name == "_acme-challenge."+host { return wantCNAME, nil } return "", errors.New("not found") } attachDomain(t, fx, member, host, "go.tito.io") if changed, err := domains.SetClaimCapabilities(context.Background(), fx.rel, host, "bab", "titogo", true, true); err != nil || !changed { t.Fatalf("seed SetClaimCapabilities(wildcard,catchall) = changed=%v err=%v", changed, err) } // Break the stub: a disable call that still consulted it would now fail // the CNAME check and 422 — proving the disable path skips it entirely. fx.srv.lookupCNAME = func(context.Context, string) (string, error) { return "", errors.New("not found") } code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"`+host+`","route":"go.tito.io","wildcard":false}`) if code != http.StatusOK { t.Fatalf("disabling wildcard = %d %s, want 200 (no CNAME check on the way off)", code, out) } c := claimOf(t, fx, host) if c.Wildcard || c.Catchall { t.Fatalf("claim after disabling wildcard = %+v, want both false (catchall cascades off)", *c) } } // TestDomainsListDelegationStamp: a claim with Wildcard stamps // delegation_status from the same CNAME check the attach gate uses — // "delegated" or "missing", live-read on every list call (not cached from // whenever wildcard was enabled). A claim without Wildcard never carries the // field at all. func TestDomainsListDelegationStamp(t *testing.T) { const zone = "acme.oncarlos.com" fx, member := instanceFixture(t, "code-dom-list-deleg") fx.srv.delegationZone = zone const wildHost = "wild.example.com" const plainHost = "plain.example.com" wantCNAME := "_acme-challenge." + wildHost + "." + zone + "." fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) { if name == "_acme-challenge."+wildHost { return wantCNAME, nil } return "", errors.New("not found") } attachDomain(t, fx, member, wildHost, "go.tito.io") if changed, err := domains.SetClaimCapabilities(context.Background(), fx.rel, wildHost, "bab", "titogo", true, false); err != nil || !changed { t.Fatalf("seed SetClaimCapabilities(%s, wildcard) = changed=%v err=%v", wildHost, changed, err) } attachDomain(t, fx, member, plainHost, "go.tito.io") list := func(t *testing.T) domainListResp { t.Helper() code, _, out := rawReq(t, http.MethodGet, domainsURL(fx, "bab", "titogo"), member, "") if code != http.StatusOK { t.Fatalf("list = %d %s, want 200", code, out) } var got domainListResp if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("list body %s: %v", out, err) } return got } byHost := func(got domainListResp) map[string]struct { Wildcard bool Catchall bool DelegationStatus string } { m := map[string]struct { Wildcard bool Catchall bool DelegationStatus string }{} for _, d := range got.Domains { m[d.Host] = struct { Wildcard bool Catchall bool DelegationStatus string }{d.Wildcard, d.Catchall, d.DelegationStatus} } return m } m := byHost(list(t)) if row := m[wildHost]; !row.Wildcard || row.DelegationStatus != "delegated" { t.Fatalf("%s row = %+v, want wildcard true and delegated", wildHost, row) } if row := m[plainHost]; row.Wildcard || row.DelegationStatus != "" { t.Fatalf("%s row = %+v, want wildcard false and delegation_status absent", plainHost, row) } // Break the CNAME stub: the same claim now reads "missing" — the stamp is // a live read, not something cached from when wildcard was enabled. fx.srv.lookupCNAME = func(context.Context, string) (string, error) { return "", errors.New("not found") } m = byHost(list(t)) if row := m[wildHost]; !row.Wildcard || row.DelegationStatus != "missing" { t.Fatalf("%s row after breaking the CNAME = %+v, want wildcard true and missing", wildHost, row) } } // TestDomainsListDelegationStampCapsLookups: IMPORTANT-2 (review) bounds the // list door's live CNAME work at domainListCNAMELookupCap per call. Nine // wildcard-enabled claims, host-sorted "h0".."h8": only the lexicographically // first 8 get a delegation_status stamp (and only 8 lookupCNAME calls are // made at all); the 9th lists with the field simply omitted, same as an // unset zone or wildcard off — never an error. func TestDomainsListDelegationStampCapsLookups(t *testing.T) { const zone = "acme.oncarlos.com" fx, member := instanceFixture(t, "code-dom-list-cap") fx.srv.delegationZone = zone var calls int fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) { calls++ host := strings.TrimPrefix(name, "_acme-challenge.") return "_acme-challenge." + host + "." + zone + ".", nil } hosts := make([]string, 9) for i := range hosts { h := fmt.Sprintf("h%d.example.com", i) hosts[i] = h attachDomain(t, fx, member, h, "go.tito.io") if changed, err := domains.SetClaimCapabilities(context.Background(), fx.rel, h, "bab", "titogo", true, false); err != nil || !changed { t.Fatalf("seed SetClaimCapabilities(%s, wildcard) = changed=%v err=%v", h, changed, err) } } sort.Strings(hosts) code, _, out := rawReq(t, http.MethodGet, domainsURL(fx, "bab", "titogo"), member, "") if code != http.StatusOK { t.Fatalf("list = %d %s, want 200", code, out) } var got domainListResp if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("list body %s: %v", out, err) } if len(got.Domains) != 9 { t.Fatalf("list = %d rows, want 9", len(got.Domains)) } byHost := map[string]string{} for _, d := range got.Domains { byHost[d.Host] = d.DelegationStatus } for i, h := range hosts { if i < 8 { if byHost[h] != "delegated" { t.Errorf("host %d (%s) delegation_status = %q, want delegated (within the cap)", i, h, byHost[h]) } } else { if byHost[h] != "" { t.Errorf("host %d (%s) delegation_status = %q, want omitted (beyond the cap)", i, h, byHost[h]) } } } if calls != 8 { t.Fatalf("lookupCNAME was called %d times, want exactly 8 (the cap)", calls) } } // ---- zone validation at construction (Task 5 review, IMPORTANT-4) --------- // TestNormalizeDelegationZone: CARLOS_ACME_DELEGATION_ZONE is lowercased, // trimmed, and shape-checked the same way the edge validates the identical // variable (internal/edge/wildcard.go) — an invalid value degrades to "", // never a panic or a value handed to lookupCNAME verbatim. func TestNormalizeDelegationZone(t *testing.T) { for _, tc := range []struct{ raw, want string }{ {"", ""}, {" ", ""}, {"ACME.OnCarlos.Com", "acme.oncarlos.com"}, {" acme.oncarlos.com ", "acme.oncarlos.com"}, {"*.bad zone", ""}, {"-leading-hyphen.example.com", ""}, {"has a space.example.com", ""}, } { if got := normalizeDelegationZone(tc.raw); got != tc.want { t.Errorf("normalizeDelegationZone(%q) = %q, want %q", tc.raw, got, tc.want) } } } // zoneFixtureWithDelegation builds a full console fixture the same shape // instanceFixture does, but with Config.DelegationZone set AT CONSTRUCTION — // the only way to exercise NewServer's own zone validation (IMPORTANT-4): // every other test in this file stubs delegationZone directly on an // already-constructed Server, which bypasses normalizeDelegationZone // entirely. func zoneFixtureWithDelegation(t *testing.T, zone, code string) (*consoleFixture, string) { t.Helper() regPath, relStore, priv, pub := buildFixtures(t) st, err := Open(filepath.Join(t.TempDir(), "console.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { st.Close() }) fk := newFakeKeymail(t, "paul@keymail.dev") var srv *Server ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv.ServeHTTP(w, r) })) t.Cleanup(ts.Close) srv, err = NewServer(Config{ Origin: ts.URL, Keymail: fk.srv.URL, Registry: regPath, Releases: relStore, ReleasePub: pub, Key: priv, AppScheme: "http", DelegationZone: zone, }, st) if err != nil { t.Fatal(err) } srv.instances.timeout = 100 * time.Millisecond if err := st.AddMember(OpsAccountID, "paul@keymail.dev", RoleOwner, time.Now()); err != nil { t.Fatal(err) } if _, err := st.CreateAppIn(OpsAccountID, "kass", "paul@keymail.dev", time.Now()); err != nil { t.Fatal(err) } fx := &consoleFixture{ts: ts, srv: srv, st: st, fk: fk, rel: relStore, regPath: regPath, priv: priv, pub: pub, sqid: release.OpsAccount} now := time.Now() if _, err := st.CreateAppIn(OpsAccountID, "titogo", "paul@keymail.dev", now); err != nil { t.Fatal(err) } if err := st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, now); err != nil { t.Fatal(err) } return fx, cliToken(t, fx, "alice@keymail.dev", code) } // TestDelegationZoneInvalidAtConstruction: a garbage // CARLOS_ACME_DELEGATION_ZONE degrades to delegation-off at Server // construction (IMPORTANT-4) — a wildcard-enable request against it answers // the ordinary "no delegation zone configured" 422, the exact same refusal // an unset zone gets, never a distinguishable error and never a lookupCNAME // call built from an invalid zone. func TestDelegationZoneInvalidAtConstruction(t *testing.T) { fx, member := zoneFixtureWithDelegation(t, "*.bad zone", "code-dom-wc-badzone") fx.srv.lookupCNAME = func(context.Context, string) (string, error) { t.Fatal("lookupCNAME must not be called when the configured zone is invalid") return "", nil } code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"woodstar.app","route":"go.tito.io","wildcard":true}`) if code != http.StatusUnprocessableEntity { t.Fatalf("attach with wildcard under an invalid configured zone = %d %s, want 422", code, out) } if !strings.Contains(out, "no delegation zone") { t.Fatalf("422 body = %s, want it to mention no delegation zone", out) } } // ---- wildcard exemption from the write/instance budgets (Task 5, spec §4a) // TestWildcardEnableIsNotRateLimited: a Pages hub with wildcard DNS makes no // per-repo hostname call at all — one claim on the hub host with both flags, // every repo's subdomain serves off the catchall. So the domains doors are // EXEMPT from the write/instance WORKLOAD budgets rather than uplifted. // // attempts is deliberately ABOVE both cliInstanceBurst (the instance workload // budget this door must be exempt from) and svcWriteBurst (the write budget // it must equally be exempt from) and BELOW domainsCeilingBurst (the // convergence-rate ceiling that still applies, see // TestDomainsCeilingBoundsConvergenceRate below): a pass here means BOTH // workload budgets are genuinely gone, not that the loop merely stayed under // one of them. domainsCeilingBurst is kept deliberately clear of // svcWriteBurst (see its comment, authcli.go) so that a volume satisfying // this inequality can exist at all — when the two constants were equal, no // attempts count could sit strictly between them, and a regression that put // the write budget back onto this door would have refused at the same // threshold this ceiling does, so this test would have kept passing anyway. // Derived from all three constants, not a literal, so the claim cannot // quietly stop being true if any of them moves — the assertion just below // catches that instead of the test silently starting to prove nothing // (Task 5 review, round 3; sharpened in the fix wave). func TestWildcardEnableIsNotRateLimited(t *testing.T) { const zone = "acme.example" const floor = max(cliInstanceBurst, svcWriteBurst) const attempts = (floor + domainsCeilingBurst) / 2 if !(cliInstanceBurst < attempts && svcWriteBurst < attempts && attempts < domainsCeilingBurst) { t.Fatalf("attempts (%d) must sit strictly above cliInstanceBurst (%d) and svcWriteBurst (%d) and strictly below domainsCeilingBurst (%d) — as written, this test would no longer prove the exemption it is named for", attempts, cliInstanceBurst, svcWriteBurst, domainsCeilingBurst) } fx, _ := instanceFixture(t, "code-wc-exempt") svc := serviceToken(t, fx.st, OpsAccountID, "hub", "titogo", svcrole.Publish) fx.srv.delegationZone = zone fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) { return name + "." + zone, nil } for i := 0; i < attempts; i++ { host := fmt.Sprintf("r%d.pages.example", i) code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), svc, `{"host":"`+host+`","route":"hub.pages.example","wildcard":true,"catchall":true}`) if code == http.StatusTooManyRequests { t.Fatalf("attach %d = 429: %s", i, out) } if code != http.StatusOK { t.Fatalf("attach %d = %d: %s", i, code, out) } } } // TestDomainsCeilingBoundsConvergenceRate is C34's correction: the // exemption above establishes that the legitimate wildcard workload does // not NEED a budget, not that no budget is safe. Every effective attach // audits and bumps control/serial, which every box polls at 2s and reacts // to with a full pass, so domainsGate keeps a convergence-rate ceiling // (domainsCeilingBurst, keyed on the principal) even though it dropped the // write/instance budgets. Plain, non-wildcard attaches are enough to show // it — the ceiling applies to the door, not to the wildcard flags. func TestDomainsCeilingBoundsConvergenceRate(t *testing.T) { fx, _ := instanceFixture(t, "code-wc-ceiling") svc := serviceToken(t, fx.st, OpsAccountID, "hub", "titogo", svcrole.Publish) var saw429 bool for i := 0; i < domainsCeilingBurst+5; i++ { host := fmt.Sprintf("c%d.pages.example", i) code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), svc, `{"host":"`+host+`","route":"hub.pages.example"}`) if code == http.StatusTooManyRequests { saw429 = true break } if code != http.StatusOK { t.Fatalf("attach %d = %d: %s", i, code, out) } } if !saw429 { t.Error("unbounded attaches from one credential; want a 429 after domainsCeilingBurst") } } // TestFailedWildcardEnableIsBounded is the hazard the exemption has to // survive: the CNAME check is a live, sequential DNS round trip on the // request path, and a caller whose CNAME is not there yet can retry // forever. A SUCCEEDING enable is once-per-domain and exempt (the test // above); a FAILING one is bounded at wildFailBurst per principal per // minute. func TestFailedWildcardEnableIsBounded(t *testing.T) { const zone = "acme.example" fx, _ := instanceFixture(t, "code-wc-bounded") svc := serviceToken(t, fx.st, OpsAccountID, "hub", "titogo", svcrole.Publish) fx.srv.delegationZone = zone fx.srv.lookupCNAME = func(context.Context, string) (string, error) { return "", errors.New("not found") // no _acme-challenge CNAME anywhere } var saw429 bool for i := 0; i < wildFailBurst+5; i++ { code, _, _ := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), svc, `{"host":"retry.pages.example","route":"hub.pages.example","wildcard":true}`) if code == http.StatusTooManyRequests { saw429 = true break } if code != http.StatusUnprocessableEntity { t.Fatalf("failing attach %d = %d, want 422 (until the bound trips)", i, code) } } if !saw429 { t.Error("unbounded failing wildcard enables; want a 429 after wildFailBurst") } } // TestIdempotentReattachTouchesNeitherBudget: titogo's router re-attaches // every hostname with its capability flags on every reload pass. `enabling` // is a false->true transition, so a re-send of wildcard:true on an // already-wildcard claim skips the DNS lookup entirely — it must skip the // failure bound with it, even once the resolver goes dark. func TestIdempotentReattachTouchesNeitherBudget(t *testing.T) { const zone = "acme.example" fx, _ := instanceFixture(t, "code-wc-idempotent") svc := serviceToken(t, fx.st, OpsAccountID, "hub", "titogo", svcrole.Instance) fx.srv.delegationZone = zone const host = "one.pages.example" fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) { return name + "." + zone, nil } code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), svc, `{"host":"`+host+`","route":"hub.pages.example","wildcard":true,"catchall":true}`) if code != http.StatusOK { t.Fatalf("first attach = %d: %s", code, out) } fx.srv.lookupCNAME = func(context.Context, string) (string, error) { return "", errors.New("resolver is dark") // a re-attach must not care } for i := 0; i < wildFailBurst*2; i++ { code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), svc, `{"host":"`+host+`","route":"hub.pages.example","wildcard":true,"catchall":true}`) if code != http.StatusOK { t.Fatalf("re-attach %d = %d: %s", i, code, out) } } } // TestLegacyAppTokensHaveSeparateWildFailBudgets is C32's fix, made // concrete: titogo's routers each hold their OWN app token (kind='app', // Name==""), often bound to different apps in the same account. Before the // fix, principalKey collapsed every one of them onto "service:/" — // whichever app it was bound to — so one router's mistyped CNAME could 429 // every other router's wildcard enable in the account. auditActor already // keys this exact row on App for the same reason; principalKey must agree. func TestLegacyAppTokensHaveSeparateWildFailBudgets(t *testing.T) { const zone = "acme.example" fx, _ := instanceFixture(t, "code-wc-legacy-sep") now := time.Now() if _, err := fx.st.CreateAppIn(OpsAccountID, "widgets", "paul@keymail.dev", now); err != nil { t.Fatal(err) } tokTitogo, err := fx.st.NewAppToken(OpsAccountID, "titogo", "paul@keymail.dev", "router-titogo", now) if err != nil { t.Fatalf("NewAppToken(titogo): %v", err) } tokWidgets, err := fx.st.NewAppToken(OpsAccountID, "widgets", "paul@keymail.dev", "router-widgets", now) if err != nil { t.Fatalf("NewAppToken(widgets): %v", err) } fx.srv.delegationZone = zone fx.srv.lookupCNAME = func(context.Context, string) (string, error) { return "", errors.New("not found") // no _acme-challenge CNAME anywhere } // Exhaust titogo's app token's wildFail budget. var saw429 bool for i := 0; i < wildFailBurst+5; i++ { code, _, _ := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), tokTitogo, `{"host":"retry.pages.example","route":"hub.pages.example","wildcard":true}`) if code == http.StatusTooManyRequests { saw429 = true break } if code != http.StatusUnprocessableEntity { t.Fatalf("titogo failing attach %d = %d, want 422 (until the bound trips)", i, code) } } if !saw429 { t.Fatal("titogo's app token never tripped wildFail — the setup is broken, not the fix") } // widgets' app token — a DIFFERENT app, same account — must be // untouched: a single failure answers 422, never 429. code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "widgets"), tokWidgets, `{"host":"retry2.pages.example","route":"hub.pages.example","wildcard":true}`) if code != http.StatusUnprocessableEntity { t.Fatalf("widgets' app token after titogo's exhausted its budget = %d: %s, want 422 (separate budget)", code, out) } } // TestAPIDomainAttachRefusesADeploymentRouteNeutrally: defence in depth for // the fleet-wide route collision. An operator-minted route carries no // instance record, so this door has never been able to see it and // deliberately does not verify that a route exists — which left a hostname // another box already SERVES free for anyone to claim. Now that aliases // publish fleet-wide, such a claim captures that traffic on every remote // edge, so the door refuses it. // // The refusal must be indistinguishable from the "someone else holds it" // 409 in TWO ways, and this test asserts both: // // 1. SAME BYTES. Status and body are compared against the pre-existing // refusal itself, not against a literal, so the two cannot drift apart. // // 2. SAME REACHABILITY. Byte-identical bodies are worthless if the new // check runs EARLIER than the old one, because a prober can then // deliberately fail a later gate and read the two apart by which // refusal comes back first (Task 5 review). So the probes below use a // BAD route and an ABSENT route — request shapes that must be refused // by resolveAliasRoute before the hostname is ever considered — and // assert a deployment-route host and a never-heard-of host answer // IDENTICALLY. With the guard ordered above resolveAliasRoute these // read 409 vs 400 and the deployment's whole non-alias route set can be // enumerated one host at a time, side-effect-free, inside the ceiling. // // A test that only probes with a VALID route (as the first version of this // one did) cannot see failure mode 2 at all. func TestAPIDomainAttachRefusesADeploymentRouteNeutrally(t *testing.T) { ctx := context.Background() fx, member := instanceFixture(t, "code-dom-deproute") // go.tito.io is a real, NON-ALIAS route published by a live box called // "annie". Both halves are required: DeploymentRoutes drops any edges // file whose box has no fresh status snapshot. if _, err := fx.rel.Put(ctx, edgesfile.Key("annie"), []byte(`{"v":1,"box":"annie","eip":"198.51.100.9","hosts":{"go.tito.io":{"role":"home"}}}`), ""); err != nil { t.Fatal(err) } if err := status.WriteBox(ctx, fx.rel, status.Box{Label: "annie", GeneratedAt: time.Now()}); err != nil { t.Fatal(err) } // A hostname held by a different account: the pre-existing refusal, and // the yardstick the new one is measured against. if _, _, err := domains.AttachClaim(ctx, fx.rel, domains.Claim{ Host: "claimed-by-someone-else.com", Account: "cdef", App: "widgets", Route: "widgets.example.net", CreatedAt: time.Now().UTC().Format(time.RFC3339), }); err != nil { t.Fatal(err) } attach := func(body string) (int, string) { t.Helper() code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, body) return code, strings.TrimSpace(out) } // (1) Same bytes: with a perfectly valid route, both refused hostnames // answer the identical neutral 409. takenCode, takenBody := attach(attachBody("go.tito.io", "two.go.tito.io")) heldCode, heldBody := attach(attachBody("claimed-by-someone-else.com", "two.go.tito.io")) if takenCode != http.StatusConflict { t.Fatalf("attach of another box's route = %d %s, want 409", takenCode, takenBody) } if takenCode != heldCode || takenBody != heldBody { t.Fatalf("refusal %d %q differs from the existing unavailable %d %q — that is an existence oracle", takenCode, takenBody, heldCode, heldBody) } claimAbsent(t, fx, "go.tito.io") // (2) Same reachability. "never-heard-of.example" is not a deployment // route, is claimed by nobody, and is not denied — the ONLY thing that // differs between the two probes in each pair is whether a live box // serves the hostname. That difference must not be observable. for _, probe := range []struct { what string body func(host string) string }{ // A malformed route: resolveAliasRoute's 400 must come first. {"a malformed route", func(host string) string { return attachBody(host, "!!") }}, // No route at all, from an app with zero instance records: the // "specify -route" 400 must come first. Needs no malformed input at // all, which is what makes it the cheap version of this probe. {"an absent route", func(host string) string { return attachBody(host, "") }}, // The kind=static branch, which takes no route and so has none of // the gates above — its later gate is attachChannel, inside the // shared attachDomain core. Round 1 left the guard at the top of // this branch on the reasoning that there was nothing earlier to // order against; there was nothing earlier, but there was something // LATER, and that is just as readable. Round 2 moved the guard down // into the core, immediately before each AttachClaim. {"a malformed channel on the static branch", func(host string) string { b, err := json.Marshal(map[string]string{"host": host, "kind": "static", "channel": "!!"}) if err != nil { t.Fatal(err) } return string(b) }}, } { routeCode, routeBody := attach(probe.body("go.tito.io")) unknownCode, unknownBody := attach(probe.body("never-heard-of.example")) if routeCode != unknownCode || routeBody != unknownBody { t.Errorf("with %s, a deployment-route host answered %d %q but an unknown host answered %d %q — "+ "the deployment-route check is ordered ABOVE the gate that should refuse first, "+ "so this door enumerates every non-alias route in the fleet", probe.what, routeCode, routeBody, unknownCode, unknownBody) } if routeCode == http.StatusConflict { t.Errorf("with %s, the request was refused as a conflict (%d %q) — a request that "+ "cannot name a route must never get as far as deciding whether the hostname is free", probe.what, routeCode, routeBody) } } // (3) The kind=static branch actually REFUSES, not merely refuses in the // right order. The ordering probes above cannot see this: with a // malformed channel, attachChannel refuses BOTH hosts identically and // the pair agrees whether or not the guard behind it exists at all. So // probe once more with a VALID channel, where nothing stands between the // guard and the claim write, and compare against the held hostname on // the same branch. staticBody := func(host string) string { b, err := json.Marshal(map[string]string{"host": host, "kind": "static", "channel": "stable"}) if err != nil { t.Fatal(err) } return string(b) } staticRouteCode, staticRouteBody := attach(staticBody("go.tito.io")) staticHeldCode, staticHeldBody := attach(staticBody("claimed-by-someone-else.com")) if staticRouteCode != http.StatusConflict { t.Errorf("kind=static attach of another box's route = %d %q, want 409 — the first-route "+ "branch reaches AttachClaim with no deployment-route guard in front of it", staticRouteCode, staticRouteBody) } if staticRouteCode != staticHeldCode || staticRouteBody != staticHeldBody { t.Errorf("kind=static refusal %d %q differs from the held-hostname refusal %d %q — that is an existence oracle", staticRouteCode, staticRouteBody, staticHeldCode, staticHeldBody) } // Nothing was written by any probe. claimAbsent(t, fx, "go.tito.io") claimAbsent(t, fx, "never-heard-of.example") } // A hostname this very app ALREADY holds the claim on stays attachable. This // is not a softening of the rule above, it is what makes it survive a // first-route attach: such an attach materializes the host as a REAL route // on the claimant's own box, so from the second call onward the fold reports // the caller's own route back at them. titogo's router re-attaches every // hostname on each reload pass, so without this the steady state would be a // permanent 409 on hostnames this deployment itself granted. func TestAPIDomainAttachStillConvergesTheCallersOwnDeploymentRoute(t *testing.T) { ctx := context.Background() fx, member := instanceFixture(t, "code-dom-ownroute") if _, err := fx.rel.Put(ctx, edgesfile.Key("annie"), []byte(`{"v":1,"box":"annie","eip":"198.51.100.9","hosts":{"mine.example.com":{"role":"home"}}}`), ""); err != nil { t.Fatal(err) } if err := status.WriteBox(ctx, fx.rel, status.Box{Label: "annie", GeneratedAt: time.Now()}); err != nil { t.Fatal(err) } if _, _, err := domains.AttachClaim(ctx, fx.rel, domains.Claim{ Host: "mine.example.com", Account: "bab", App: "titogo", CreatedAt: time.Now().UTC().Format(time.RFC3339), }); err != nil { t.Fatal(err) } if got := attachDomain(t, fx, member, "mine.example.com", "go.tito.io"); got.Created { t.Fatalf("re-attach of the caller's own hostname = %+v, want 200 created=false", got) } } // readingsTestStore is a bare release store for aliasReadings tests that // don't need a full consoleFixture — same DirStore-over-TempDir pattern // status_test.go's teststore uses. func readingsTestStore(t *testing.T) release.Store { t.Helper() return release.NewDirStore(t.TempDir()) } // writeBoxWithAlias publishes one box whose Metrics.Aliases carries a single // reading, all under the fixed hostname "shop.customer.com" — the tests // using this helper are about the FOLD across boxes (freshest stamp wins), // not about hostname routing, so every box in a given test contends for the // same key on purpose. func writeBoxWithAlias(t *testing.T, s release.Store, label string, now time.Time, reading status.AliasReading) { t.Helper() if err := status.WriteBox(context.Background(), s, status.Box{ Label: label, GeneratedAt: now, Metrics: &status.BoxMetrics{Aliases: map[string]status.AliasReading{ "shop.customer.com": reading, }}, }); err != nil { t.Fatal(err) } } // Two boxes can both carry an alias (an everywhere-class primary). The fold // must take the FRESHEST stamp, not whichever box the map happened to yield // last — otherwise a frozen reading deterministically overwrites a live one. // // DirStore.List returns keys sorted, and WriteBox keys off the box label, so // LoadBoxes iterates boxes in label order regardless of write order. A test // with only one label ordering can't tell a genuine freshness comparison // apart from a last-write-wins bug that happens to agree with it for that // ordering — so this asserts BOTH directions: the fresher box sorting // alphabetically first (where a last-write-wins fold would wrongly keep the // stale, later-sorted box's reading) and sorting last (where naive // last-write-wins would coincidentally get it right too). Only a real // DNSCheckedAt comparison passes both. func TestAliasReadingsPrefersTheFreshestStamp(t *testing.T) { t.Run("fresher box sorts first", func(t *testing.T) { s := readingsTestStore(t) now := time.Unix(1756300060, 0) writeBoxWithAlias(t, s, "annie", now, status.AliasReading{ Route: "app.example.com", DNSStatus: "pointing", DNSCheckedAt: 1756300000}) writeBoxWithAlias(t, s, "betty", now, status.AliasReading{ Route: "app.example.com", DNSStatus: "elsewhere", DNSCheckedAt: 1756200000}) got := aliasReadings(context.Background(), s, now) if got["shop.customer.com"].DNSStatus != "pointing" { t.Fatalf("reading = %+v, want the freshest box's stamp (annie, which sorts first)", got["shop.customer.com"]) } }) t.Run("fresher box sorts last", func(t *testing.T) { s := readingsTestStore(t) now := time.Unix(1756300060, 0) writeBoxWithAlias(t, s, "annie", now, status.AliasReading{ Route: "app.example.com", DNSStatus: "elsewhere", DNSCheckedAt: 1756200000}) writeBoxWithAlias(t, s, "betty", now, status.AliasReading{ Route: "app.example.com", DNSStatus: "pointing", DNSCheckedAt: 1756300000}) got := aliasReadings(context.Background(), s, now) if got["shop.customer.com"].DNSStatus != "pointing" { t.Fatalf("reading = %+v, want the freshest box's stamp (betty, which sorts last)", got["shop.customer.com"]) } }) } // domainGetURL is the per-host read's URL (#299 §2e). func domainGetURL(fx *consoleFixture, acct, app, host string) string { return domainsURL(fx, acct, app) + "/" + host } // The per-host door answers the SAME verdict as the list door for the same // hostname. It exists to be cheap, not to be different — a consumer that // refreshes one host and compares it against a listed row must not see a // mirrored status flap for reasons that have nothing to do with the domain. func TestAPIDomainGetAgreesWithTheListRow(t *testing.T) { fx, member := instanceFixture(t, "code-dom-get") ctx := context.Background() now := time.Now() attachDomain(t, fx, member, "live.example.com", "go.tito.io") if err := status.WriteBox(ctx, fx.rel, status.Box{ GeneratedAt: now, Label: "ada-reporting", Region: "eu-west-1", Metrics: &status.BoxMetrics{Aliases: map[string]status.AliasReading{ "live.example.com": {Route: "go.tito.io", DNSStatus: "pointing", CertExpiresAt: now.Add(24 * time.Hour).Unix(), DNSCheckedAt: 1786000123}, }}, }); err != nil { t.Fatal(err) } code, _, out := rawReq(t, http.MethodGet, domainGetURL(fx, "bab", "titogo", "live.example.com"), member, "") if code != http.StatusOK { t.Fatalf("get = %d %s, want 200", code, out) } var got struct { Domain struct { Host string `json:"host"` State string `json:"state"` Reason string `json:"reason"` CheckedAt int64 `json:"checked_at"` } `json:"domain"` Deployment struct { ManagedDomains bool `json:"managed_domains"` } `json:"deployment"` } if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("get body %s: %v", out, err) } if got.Domain.Host != "live.example.com" || got.Domain.State != StateLive { t.Fatalf("domain = %+v, want live.example.com in state %q", got.Domain, StateLive) } // checked_at is what makes a mirrored state ageable. Without it a // consumer cannot tell a verdict confirmed a minute ago from one // confirmed before an outage began, and "live" is not monotonic. if got.Domain.CheckedAt != 1786000123 { t.Errorf("checked_at = %d, want the box's own stamp", got.Domain.CheckedAt) } // The capability block rides on this answer too, so a client refreshing // one host never has to call the list door just to learn the deployment // still manages domains. if !got.Deployment.ManagedDomains { t.Error("the per-host answer carries no capability block") } // And the same host, listed, agrees. _, _, listOut := rawReq(t, http.MethodGet, domainsURL(fx, "bab", "titogo"), member, "") var list struct { Domains []struct { Host string `json:"host"` State string `json:"state"` CheckedAt int64 `json:"checked_at"` } `json:"domains"` } if err := json.Unmarshal([]byte(listOut), &list); err != nil { t.Fatal(err) } if len(list.Domains) != 1 { t.Fatalf("list = %+v", list.Domains) } if list.Domains[0].State != got.Domain.State || list.Domains[0].CheckedAt != got.Domain.CheckedAt { t.Fatalf("list row %+v disagrees with the per-host answer %+v", list.Domains[0], got.Domain) } } // THE tenant-isolation property. The claims keyspace is GLOBAL — the key is // the cross-account uniqueness gate — so a host another account holds must be // indistinguishable from a host nobody has claimed. Otherwise this door // becomes an existence oracle over every hostname in the deployment, leaking // exactly what AttachClaim's neutral refusal protects. func TestAPIDomainGetCannotDistinguishAnotherOwnerFromUnclaimed(t *testing.T) { fx, member := instanceFixture(t, "code-dom-get-iso") ctx := context.Background() now := time.Now() if _, err := fx.st.CreateAppIn(OpsAccountID, "other", "alice@keymail.dev", now); err != nil { t.Fatal(err) } if _, _, err := domains.AttachClaim(ctx, fx.rel, domains.Claim{ Host: "taken.example.com", Account: "bab", App: "other", Route: "other.go.tito.io", CreatedAt: now.UTC().Format(time.RFC3339), }); err != nil { t.Fatal(err) } takenCode, _, takenBody := rawReq(t, http.MethodGet, domainGetURL(fx, "bab", "titogo", "taken.example.com"), member, "") freeCode, _, freeBody := rawReq(t, http.MethodGet, domainGetURL(fx, "bab", "titogo", "nobody.example.com"), member, "") if takenCode != http.StatusNotFound || freeCode != http.StatusNotFound { t.Fatalf("taken = %d, unclaimed = %d; both must be 404", takenCode, freeCode) } if takenBody != freeBody { t.Fatalf("a host another account holds answers %q but an unclaimed one answers %q — that difference IS the oracle", takenBody, freeBody) } } // A {host} segment arrives percent-decoded, so a traversal attempt reaches // the handler as a path with separators in it. It must be refused on SHAPE, // before anything builds a bucket key from it. func TestAPIDomainGetRefusesATraversalHost(t *testing.T) { fx, member := instanceFixture(t, "code-dom-get-trav") for _, bad := range []string{"..%2f..%2finstances.json", "not a host", "%2e%2e%2fclaims"} { code, _, _ := rawReq(t, http.MethodGet, domainsURL(fx, "bab", "titogo")+"/"+bad, member, "") if code == http.StatusOK { t.Errorf("%q answered 200", bad) } } } // The whole of §3e, end to end and through both doors: an issuer's outcome // record in the bucket is what turns a hostname that has been trying for // hours from "issuing-cert" into "failed". Both doors must reach the same // verdict — one reads the record by key, the other folds the prefix, and a // consumer refreshing a single host and comparing it against a listed row // must never see them disagree. func TestAPIDomainFailedStateComesFromTheWarmRecord(t *testing.T) { fx, member := instanceFixture(t, "code-dom-warm") ctx := context.Background() now := time.Now() attachDomain(t, fx, member, "broken.example.com", "go.tito.io") if err := status.WriteBox(ctx, fx.rel, status.Box{ GeneratedAt: now, Label: "ada-reporting", Region: "eu-west-1", Metrics: &status.BoxMetrics{Aliases: map[string]status.AliasReading{ // DNS is right. No certificate. Without a record this is // "issuing-cert" and stays that way forever. "broken.example.com": {Route: "go.tito.io", DNSStatus: "pointing", DNSCheckedAt: now.Unix()}, }}, }); err != nil { t.Fatal(err) } state := func(t *testing.T) (get, list string) { t.Helper() code, _, out := rawReq(t, http.MethodGet, domainGetURL(fx, "bab", "titogo", "broken.example.com"), member, "") if code != http.StatusOK { t.Fatalf("get = %d %s", code, out) } var one struct { Domain struct{ State string } `json:"domain"` } if err := json.Unmarshal([]byte(out), &one); err != nil { t.Fatal(err) } _, _, listOut := rawReq(t, http.MethodGet, domainsURL(fx, "bab", "titogo"), member, "") var many struct { Domains []struct{ State string } `json:"domains"` } if err := json.Unmarshal([]byte(listOut), &many); err != nil { t.Fatal(err) } if len(many.Domains) != 1 { t.Fatalf("list = %+v", many.Domains) } return one.Domain.State, many.Domains[0].State } if get, list := state(t); get != StateIssuingCert || list != StateIssuingCert { t.Fatalf("with no record: get=%q list=%q, want both %q", get, list, StateIssuingCert) } writeWarm := func(t *testing.T, rec certwarm.Record) { t.Helper() body, err := rec.Encode(now) if err != nil { t.Fatal(err) } _, etag, err := fx.rel.Get(ctx, certwarm.Key(rec.Host)) if err != nil && !errors.Is(err, os.ErrNotExist) { t.Fatal(err) } if _, err := fx.rel.Put(ctx, certwarm.Key(rec.Host), body, etag); err != nil { t.Fatal(err) } } // One failed attempt is ordinary and must not change the story. writeWarm(t, certwarm.Record{Host: "broken.example.com", Attempts: 1, Class: certwarm.ClassOther, NextAttemptAt: now.Add(time.Hour).Unix()}) if get, list := state(t); get != StateIssuingCert || list != StateIssuingCert { t.Fatalf("after one failure: get=%q list=%q, want both %q", get, list, StateIssuingCert) } // At the threshold both doors say so. writeWarm(t, certwarm.Record{Host: "broken.example.com", Attempts: domainFailedAttempts, Class: certwarm.ClassOther, NextAttemptAt: now.Add(time.Hour).Unix()}) if get, list := state(t); get != StateFailed || list != StateFailed { t.Fatalf("at the threshold: get=%q list=%q, want both %q", get, list, StateFailed) } } // A record for somebody ELSE's hostname must not reach this app's answer. // The cert-warm prefix is deployment-global (there is one issuer, and it // writes for every domain it warms), so the join has to be by exact host or // one tenant's certificate trouble shows up on another tenant's domain. func TestAPIDomainWarmRecordsJoinByExactHost(t *testing.T) { fx, member := instanceFixture(t, "code-dom-warm-iso") ctx := context.Background() now := time.Now() attachDomain(t, fx, member, "mine.example.com", "go.tito.io") if err := status.WriteBox(ctx, fx.rel, status.Box{ GeneratedAt: now, Label: "ada-reporting", Region: "eu-west-1", Metrics: &status.BoxMetrics{Aliases: map[string]status.AliasReading{ "mine.example.com": {Route: "go.tito.io", DNSStatus: "pointing", DNSCheckedAt: now.Unix()}, }}, }); err != nil { t.Fatal(err) } body, err := certwarm.Record{Host: "theirs.example.com", Attempts: 99, Class: certwarm.ClassOther, NextAttemptAt: now.Add(time.Hour).Unix()}.Encode(now) if err != nil { t.Fatal(err) } if _, err := fx.rel.Put(ctx, certwarm.Key("theirs.example.com"), body, ""); err != nil { t.Fatal(err) } _, _, out := rawReq(t, http.MethodGet, domainsURL(fx, "bab", "titogo"), member, "") var list struct { Domains []struct { Host string `json:"host"` State string `json:"state"` } `json:"domains"` } if err := json.Unmarshal([]byte(out), &list); err != nil { t.Fatal(err) } if len(list.Domains) != 1 || list.Domains[0].Host != "mine.example.com" { t.Fatalf("list = %+v", list.Domains) } if list.Domains[0].State != StateIssuingCert { t.Errorf("state = %q, want %q — another hostname's failure record was joined to this one", list.Domains[0].State, StateIssuingCert) } }