package adopt import ( "context" "encoding/json" "io" "net" "net/http" "net/http/httptest" "reflect" "strings" "testing" "time" "amadan.net/oficina/alta/carlosop" "amadan.net/oficina/alta/carlosop/fakecarlos" "amadan.net/oficina/alta/provision" ) // carlosFixture is one app on a fake console, with its canonical instance // on the default bundle and a fake origin answering every probe. type carlosFixture struct { f *fakecarlos.Fake c *carlosop.Client h *http.Client site *site app provision.App } const ( fixtureAccount = "bds" // Plain values seeded into the fake: none may appear in any output. valueOrigin = "https://docs.oficina.works/plain-origin-value" valueVersion = "v1.4.0" ) func appNamed(t *testing.T, slug string) provision.App { t.Helper() a, ok := provision.AppBySlug(slug) if !ok { t.Fatalf("no app %q", slug) } return a } // routeOf is the host of app's canonical record, as production has it: // the route the canonical domain (CanonicalHost) is claimed for, never // the domain itself. func routeOf(app provision.App) string { return app.Slug + "." + fixtureAccount + ".oncarlos.com" } // docsRoute is routeOf(docs). const docsRoute = "docs.bds.oncarlos.com" // attachCanonical claims app's canonical domain on f for its route, live, // as `carlos domains list` shows it in production. func attachCanonical(f *fakecarlos.Fake, app provision.App) { f.AttachDomain(app.Slug, CanonicalHost(app), routeOf(app), "live") } // fixtureInstance is the canonical host's instance record as the // fixture first stores it. func fixtureInstance(app provision.App) carlosop.Instance { return carlosop.Instance{ Host: routeOf(app), App: app.Slug, Slug: "s-" + app.Slug, Channel: "stable", Region: "eu", CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4, ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`), } } func newCarlosFixture(t *testing.T, slug string) *carlosFixture { t.Helper() app := appNamed(t, slug) f := fakecarlos.New(fixtureAccount) t.Cleanup(f.Close) p := app.Prefix f.SetVar(app.Slug, "", p+"_HOME_ISSUER", HomeIssuerOrigin) f.SetVar(app.Slug, "", p+"_HOME_CONSUMER_ID", provision.ConsumerID(provision.AdoptionLabel, app.Slug)) f.SetVar(app.Slug, "", p+"_ORIGIN", valueOrigin) f.SetSecret(app.Slug, "", p+"_INSTANCE_KEY") f.AddInstance(fixtureInstance(app)) attachCanonical(f, app) c := carlosop.New(f.URL(), fixtureAccount, f.Token()) t.Cleanup(c.Close) s := &site{version: valueVersion, header: valueVersion, health: 200} switch BaselineOps(app) { case OpsApp401: s.ops = app401 case OpsAgent401: s.ops = agent401 } srv := httptest.NewTLSServer(s.handler()) t.Cleanup(srv.Close) tr := srv.Client().Transport.(*http.Transport).Clone() addr := srv.Listener.Addr().String() // Every https origin the probe names lands on the fake site. tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { var d net.Dialer return d.DialContext(ctx, network, addr) } tr.TLSClientConfig.ServerName = "example.com" return &carlosFixture{f: f, c: c, h: &http.Client{Transport: tr, Timeout: 10 * time.Second}, site: s, app: app} } // neighbour adds another instance of the fixture's app on env (""= none). func (x *carlosFixture) neighbour(host, env string) { x.f.AddInstance(carlosop.Instance{Host: host, App: x.app.Slug, Slug: "s-" + host, Environment: env, Channel: "stable", Region: "eu", CreatedAt: time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)}) } func (x *carlosFixture) preflight(t *testing.T, mine map[string]string) (Snapshot, []string) { t.Helper() snap, codes, err := Preflight(context.Background(), x.c, x.h, x.app, mine) if err != nil { t.Fatalf("Preflight: %v", err) } return snap, codes } func TestPreflightPassesCleanApp(t *testing.T) { x := newCarlosFixture(t, "docs") snap, codes := x.preflight(t, nil) wantCodes(t, codes) if snap.WriteLayer != "" || snap.Layer.Bundle != "default" || snap.HomeIssuer != HomeIssuerOrigin || snap.HomeConsumer != "docs" { t.Fatalf("snapshot write layer %q bundle %q", snap.WriteLayer, snap.Layer.Bundle) } if snap.Identity.RecordHost != docsRoute || snap.Identity.Domain != "docs.oficina.works" || snap.Identity.Route != docsRoute || snap.Delivery.Version != valueVersion || snap.At.IsZero() { t.Fatalf("snapshot identity/delivery not recorded") } if len(snap.Vars) != 4 || len(snap.Layers) != 2 { t.Fatalf("vars %d layers %d", len(snap.Vars), len(snap.Layers)) } } // productionShape is docs as production has it (carlos domains list and // instances list, 2026-11-17): the canonical domain claimed, live, for // docs.bds.oncarlos.com; a lagged domain for a lagged record on the same // channel; and canary records with no domain of their own, one of them on // an owned environment. func productionShape(t *testing.T) *carlosFixture { t.Helper() x := newCarlosFixture(t, "docs") x.f = fakecarlos.New(fixtureAccount) t.Cleanup(x.f.Close) x.f.SetVar("docs", "", "DOCS_HOME_ISSUER", HomeIssuerOrigin) x.f.SetVar("docs", "", "DOCS_HOME_CONSUMER_ID", "docs") x.f.AddInstance(fixtureInstance(x.app)) x.f.AttachDomain("docs", "docs.oficina.works", docsRoute, "live") for _, env := range []string{"lagged", "overnight-release", "contract-demo", "google-import"} { x.f.SetVar("docs", env, "DOCS_HOME_ISSUER", HomeIssuerOrigin) x.f.AddInstance(carlosop.Instance{Host: env + "-docs.bds.oncarlos.com", App: "docs", Slug: "s-" + env, Environment: env, Channel: "stable", Region: "eu", CreatedAt: time.Date(2026, 10, 27, 0, 0, 0, 0, time.UTC)}) } x.f.Own("docs", "google-import", "alta") x.f.AttachDomain("docs", "lagged.docs.oficina.works", "lagged-docs.bds.oncarlos.com", "live") x.c = carlosop.New(x.f.URL(), fixtureAccount, x.f.Token()) t.Cleanup(x.c.Close) return x } // The canonical name is a domain claim, and the record is the one its // route names. The other records, with a domain of their own or none, are // neighbours: each that folds in the default would inherit the keys. func TestPreflightResolvesCanonicalDomainInProductionShape(t *testing.T) { x := productionShape(t) snap, codes := x.preflight(t, nil) wantCodes(t, codes, "inherits-contract-demo-docs.bds.oncarlos.com", "inherits-lagged-docs.bds.oncarlos.com", "inherits-overnight-release-docs.bds.oncarlos.com") id := snap.Identity if id.RecordHost != docsRoute || id.Domain != "docs.oficina.works" || id.Route != docsRoute || id.Slug != "s-docs" { t.Fatalf("identity %+v", id) } if snap.WriteLayer != "" || snap.Delivery.Header != valueVersion { t.Fatalf("write layer %q, delivery header %q", snap.WriteLayer, snap.Delivery.Header) } if code := ReviewedRelease(snap.Delivery, sha256Hex(valueVersion)); code != "" { t.Fatalf("the reviewed release read %s from the canonical domain", code) } if got := x.site.lastHost(); got != "docs.oficina.works" { t.Fatalf("the probe asked %q, not the canonical domain", got) } } // Each lookalike of the canonical binding refuses with its own code and // no delivery probe; nothing falls back to a guess. func TestPreflightRefusesCanonicalDomainLookalikes(t *testing.T) { cases := map[string]struct { edit func(x *carlosFixture) want string }{ "no claim": {func(x *carlosFixture) { x.f.DetachDomain("docs", "docs.oficina.works") }, "domain-missing"}, // The canonical name as a record's own host is not a claim. "record named like the domain": {func(x *carlosFixture) { x.f.DetachDomain("docs", "docs.oficina.works") x.f.AddInstance(carlosop.Instance{Host: "docs.oficina.works", App: "docs", Slug: "s-docs", Channel: "stable"}) }, "domain-missing"}, "claim pending DNS": {func(x *carlosFixture) { x.f.AttachDomain("docs", "docs.oficina.works", docsRoute, "pending-dns") }, "domain-not-live"}, "claim unverified": {func(x *carlosFixture) { x.f.AttachDomain("docs", "docs.oficina.works", docsRoute, "unverified") }, "domain-not-live"}, "claim with no state": {func(x *carlosFixture) { x.f.AttachDomain("docs", "docs.oficina.works", docsRoute, "") }, "domain-not-live"}, "route to a missing record": {func(x *carlosFixture) { x.f.AttachDomain("docs", "docs.oficina.works", "gone-docs.bds.oncarlos.com", "live") }, "instance-missing"}, "claim with no route": {func(x *carlosFixture) { x.f.AttachDomain("docs", "docs.oficina.works", "", "live") }, "instance-missing"}, } for name, c := range cases { t.Run(name, func(t *testing.T) { x := productionShape(t) c.edit(x) snap, codes := x.preflight(t, nil) wantCodes(t, codes, c.want) if snap.Delivery != (Delivery{}) || x.site.lastHost() != "" { t.Fatalf("a refused binding was probed") } if _, err := Observe(context.Background(), x.c, x.h, x.app); err == nil || !strings.Contains(err.Error(), c.want) { t.Fatalf("Observe: %v, want %s", err, c.want) } }) } } // Two claims answering for the canonical name are ambiguous: neither is // picked. A name a catch-all derives is not a claim, beside one or alone. func TestCanonicalRecordRefusesTwoClaims(t *testing.T) { x := productionShape(t) all, err := x.c.Instances(context.Background(), "docs") if err != nil { t.Fatalf("Instances: %v", err) } canon := carlosop.Domain{Host: "docs.oficina.works", Route: docsRoute, State: "live"} other := carlosop.Domain{Host: "docs.oficina.works", Route: "lagged-docs.bds.oncarlos.com", State: "live"} if _, rec, code, err := canonicalRecord("docs.oficina.works", []carlosop.Domain{canon, other}, all); err != nil || rec != nil || code != "domain-ambiguous" { t.Fatalf("two claims: %v %v %q", rec, err, code) } derived := other derived.Via = "*.oficina.works" if d, rec, code, err := canonicalRecord("docs.oficina.works", []carlosop.Domain{canon, derived}, all); err != nil || code != "" || rec.Host != docsRoute || d != canon { t.Fatalf("a claim beside a derived name: %v %q", err, code) } if _, _, code, _ := canonicalRecord("docs.oficina.works", []carlosop.Domain{derived}, all); code != "domain-missing" { t.Fatalf("a derived name alone was read as the claim: %q", code) } // The console's own answer with two rows for the name refuses // Preflight before any config is read. var reads []string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reads = append(reads, r.URL.Path) w.Header().Set("Content-Type", "application/json") switch r.URL.Path { case "/api/cli/apps/bds/docs/domains": _, _ = io.WriteString(w, `{"domains":[`+ `{"host":"docs.oficina.works","route":"docs.bds.oncarlos.com","state":"live"},`+ `{"host":"docs.oficina.works","route":"lagged-docs.bds.oncarlos.com","state":"live"}]}`) case "/api/cli/apps/bds/docs/instances": _, _ = io.WriteString(w, `{"instances":[{"host":"docs.bds.oncarlos.com","app":"docs","account":"bds"},`+ `{"host":"lagged-docs.bds.oncarlos.com","app":"docs","account":"bds"}],"truncated":false}`) default: w.WriteHeader(http.StatusNotFound) } })) t.Cleanup(srv.Close) c := carlosop.New(srv.URL, fixtureAccount, []byte("svc_token")) t.Cleanup(c.Close) _, codes, err := Preflight(context.Background(), c, x.h, x.app, nil) if err != nil { t.Fatalf("Preflight: %v", err) } wantCodes(t, codes, "domain-ambiguous") if len(reads) != 2 || x.site.lastHost() != "" { t.Fatalf("an ambiguous claim went on to read %v, or probed", reads) } } // The domain re-pointed at another record between two observations // changes the identity, though neither record changed. func TestRepointedDomainChangesIdentity(t *testing.T) { x := productionShape(t) before, err := Observe(context.Background(), x.c, x.h, x.app) if err != nil { t.Fatalf("Observe: %v", err) } x.f.AttachDomain("docs", "docs.oficina.works", "lagged-docs.bds.oncarlos.com", "live") after, _, codes, err := observe(context.Background(), x.c, nil, x.app) if err != nil { t.Fatalf("observe: %v", err) } wantCodes(t, codes) if got := SameIdentity(before.Identity, after.Identity); !reflect.DeepEqual(got, []string{"alias", "environment", "instance", "record", "storage"}) { t.Fatalf("SameIdentity = %v", got) } // The claim's route alone moving is the alias. moved := before.Identity moved.Route = "lagged-docs.bds.oncarlos.com" if got := SameIdentity(before.Identity, moved); !reflect.DeepEqual(got, []string{"alias"}) { t.Fatalf("SameIdentity = %v", got) } } // Review focus 1: a neighbour overriding another key still inherits both // agent keys from the shared default. func TestPreflightRefusesInheritanceDespiteOtherOverride(t *testing.T) { x := newCarlosFixture(t, "docs") x.neighbour("staging.docs.example", "staging") x.f.SetVar("docs", "staging", "DOCS_HOME_ISSUER", "https://id.staging.example") _, codes := x.preflight(t, nil) wantCodes(t, codes, "inherits-staging.docs.example") } func TestPreflightRefusesUnboundNeighbour(t *testing.T) { x := newCarlosFixture(t, "docs") x.neighbour("bare.docs.example", "") _, codes := x.preflight(t, nil) wantCodes(t, codes, "inherits-bare.docs.example") } func TestPreflightRefusesNeighbourShadowingOneKey(t *testing.T) { x := newCarlosFixture(t, "docs") x.neighbour("staging.docs.example", "staging") x.f.SetVar("docs", "staging", "DOCS_AGENT_ISSUER", "https://connect.staging.example") _, codes := x.preflight(t, nil) wantCodes(t, codes, "inherits-staging.docs.example") } func TestPreflightAllowsOwnedEnvironmentNeighbour(t *testing.T) { x := newCarlosFixture(t, "docs") x.neighbour("acme.docs.oficina.works", "acme-docs") x.f.SetVar("docs", "acme-docs", "DOCS_HOME_ISSUER", HomeIssuerOrigin) x.f.Own("docs", "acme-docs", "alta") _, codes := x.preflight(t, nil) wantCodes(t, codes) } func TestPreflightAllowsNeighbourThatAlreadyShadowsBothKeys(t *testing.T) { x := newCarlosFixture(t, "docs") x.neighbour("staging.docs.example", "staging") x.f.SetVar("docs", "staging", "DOCS_AGENT_ISSUER", "https://connect.staging.example") x.f.SetVar("docs", "staging", "DOCS_AGENT_TEAM", "stg") _, codes := x.preflight(t, nil) wantCodes(t, codes) } // A write to a named environment reaches only that environment's routes. func TestPreflightNamedWriteLayerInheritance(t *testing.T) { x := newCarlosFixture(t, "docs") x.f = fakecarlos.New(fixtureAccount) t.Cleanup(x.f.Close) x.f.SetVar("docs", "prod", "DOCS_HOME_ISSUER", HomeIssuerOrigin) x.f.SetVar("docs", "prod", "DOCS_HOME_CONSUMER_ID", "docs") x.f.SetVar("docs", "other", "DOCS_ORIGIN", "x") x.f.AddInstance(carlosop.Instance{Host: docsRoute, App: "docs", Slug: "s", Environment: "prod", Channel: "stable"}) attachCanonical(x.f, x.app) x.f.AddInstance(carlosop.Instance{Host: "other.docs.example", App: "docs", Slug: "o", Environment: "other", Channel: "stable"}) x.f.AddInstance(carlosop.Instance{Host: "bare.docs.example", App: "docs", Slug: "b", Channel: "stable"}) x.c = carlosop.New(x.f.URL(), fixtureAccount, x.f.Token()) t.Cleanup(x.c.Close) snap, codes := x.preflight(t, nil) wantCodes(t, codes) if snap.WriteLayer != "prod" || snap.Layer.Bundle != "prod" { t.Fatalf("write layer %q", snap.WriteLayer) } x.f.AddInstance(carlosop.Instance{Host: "twin.docs.example", App: "docs", Slug: "t", Environment: "prod", Channel: "stable"}) _, codes = x.preflight(t, nil) wantCodes(t, codes, "inherits-twin.docs.example") } func TestPreflightRefusesTeamMode(t *testing.T) { x := newCarlosFixture(t, "docs") x.f.SetVar("docs", "", "DOCS_TEAM_ID", "abc") x.f.SetVar("docs", "", "DOCS_TEAM_SOMETHING_NEW", "1") _, codes := x.preflight(t, nil) wantCodes(t, codes, "team-mode-DOCS_TEAM_ID", "team-mode-DOCS_TEAM_SOMETHING_NEW") m := newCarlosFixture(t, "memoria") m.f.SetVar("memoria", "", "MEMORIA_TEAM", "on") _, codes = m.preflight(t, nil) wantCodes(t, codes) m.f.SetSecret("memoria", "", "MEMORIA_TEAM_ROSTER_TOKEN") _, codes = m.preflight(t, nil) wantCodes(t, codes, "team-mode-MEMORIA_TEAM_ROSTER_TOKEN") } func TestTeamModeKeys(t *testing.T) { app := appNamed(t, "calls") got := TeamModeKeys(app, []carlosop.EffectiveVar{ {Key: "CALLS_TEAM"}, {Key: "CALLS_TEAM_ZZ"}, {Key: "CALLS_TEAM_ID"}, {Key: "DOCS_TEAM_ID"}, {Key: "CALLS_ORIGIN"}, }) if !reflect.DeepEqual(got, []string{"CALLS_TEAM_ID", "CALLS_TEAM_ZZ"}) { t.Fatalf("team keys = %q", got) } } func TestPreflightRefusesForeignAgentKeys(t *testing.T) { mine := map[string]string{"DOCS_AGENT_ISSUER": Issuer, "DOCS_AGENT_TEAM": "tQ3"} x := newCarlosFixture(t, "docs") x.f.SetVar("docs", "", "DOCS_AGENT_ISSUER", Issuer) x.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "someone-else") _, codes := x.preflight(t, mine) wantCodes(t, codes, "agent-keys-present") _, codes = x.preflight(t, nil) wantCodes(t, codes, "agent-keys-present") // The journal's own sent values, on a resume, pass. x.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "tQ3") _, codes = x.preflight(t, mine) wantCodes(t, codes) // The same value as a secret is not ours. x.f.SetSecret("docs", "", "DOCS_AGENT_TEAM") _, codes = x.preflight(t, mine) wantCodes(t, codes, "agent-keys-present") // Our value, but from a layer above the write layer: not ours either. y := newCarlosFixture(t, "docs") y.f.SetOverlay("docs", docsRoute, "DOCS_AGENT_ISSUER", Issuer) _, codes = y.preflight(t, mine) wantCodes(t, codes, "agent-keys-present") } func TestPreflightRefusesMovingInstance(t *testing.T) { x := newCarlosFixture(t, "docs") x.f.AddInstance(carlosop.Instance{Host: docsRoute, App: "docs", Slug: "s-docs", Channel: "stable", Region: "eu", Move: json.RawMessage(`{"to":"us"}`)}) _, codes := x.preflight(t, nil) wantCodes(t, codes, "instance-moving") } func TestPreflightRefusesEachConfigCode(t *testing.T) { cases := map[string]struct { edit func(x *carlosFixture) want []string }{ "instance-missing": {func(x *carlosFixture) { x.f = fakecarlos.New(fixtureAccount) x.f.SetVar("docs", "", "DOCS_HOME_ISSUER", HomeIssuerOrigin) x.f.AddInstance(carlosop.Instance{Host: "elsewhere.docs.example", App: "docs", Slug: "e", Channel: "stable"}) attachCanonical(x.f, x.app) x.c = carlosop.New(x.f.URL(), fixtureAccount, x.f.Token()) }, []string{"instance-missing"}}, "layer-overlay": {func(x *carlosFixture) { x.f.SetOverlay("docs", docsRoute, "DOCS_HOME_ISSUER", HomeIssuerOrigin) }, []string{"layer-overlay"}}, "home-issuer-absent": {func(x *carlosFixture) { x.f.Unset("docs", "", "DOCS_HOME_ISSUER") }, []string{"home-issuer-mismatch"}}, "home-issuer-other": {func(x *carlosFixture) { x.f.SetVar("docs", "", "DOCS_HOME_ISSUER", "https://id.example") }, []string{"home-issuer-mismatch"}}, "home-issuer-secret": {func(x *carlosFixture) { x.f.SetSecret("docs", "", "DOCS_HOME_ISSUER") }, []string{"home-issuer-mismatch"}}, "home-consumer-other": {func(x *carlosFixture) { x.f.SetVar("docs", "", "DOCS_HOME_CONSUMER_ID", "oficina-docs") }, []string{"home-consumer-mismatch"}}, "home-consumer-absent": {func(x *carlosFixture) { x.f.Unset("docs", "", "DOCS_HOME_CONSUMER_ID") }, []string{"home-consumer-mismatch"}}, "home-consumer-overlay": {func(x *carlosFixture) { x.f.SetOverlay("docs", docsRoute, "DOCS_HOME_CONSUMER_ID", "docs") }, []string{"home-consumer-mismatch"}}, "owned-environment": {func(x *carlosFixture) { x.f.AddInstance(carlosop.Instance{Host: docsRoute, App: "docs", Slug: "s-docs", Environment: "mine", Channel: "stable"}) x.f.SetVar("docs", "mine", "DOCS_HOME_ISSUER", HomeIssuerOrigin) x.f.SetVar("docs", "mine", "DOCS_HOME_CONSUMER_ID", "docs") x.f.Own("docs", "mine", "alta") }, []string{"owned-environment"}}, "version-header-mismatch": {func(x *carlosFixture) { x.site.header = "v1.3.9" }, []string{"version-header-mismatch"}}, "version-empty": {func(x *carlosFixture) { x.site.version, x.site.header = "", "" }, []string{"version-header-mismatch"}}, "version-redirect": {func(x *carlosFixture) { x.site.redirectVersion = true }, []string{"version-header-mismatch"}}, "ops-redirect": {func(x *carlosFixture) { x.site.ops = func(w http.ResponseWriter) { w.Header().Set("Location", "/elsewhere"); w.WriteHeader(http.StatusFound) } }, []string{"operations-other", "version-header-mismatch"}}, "healthz": {func(x *carlosFixture) { x.site.health = 503 }, []string{"healthz"}}, } for name, c := range cases { t.Run(name, func(t *testing.T) { x := newCarlosFixture(t, "docs") c.edit(x) t.Cleanup(x.f.Close) t.Cleanup(x.c.Close) _, codes := x.preflight(t, nil) wantCodes(t, codes, c.want...) }) } } // A baseline Delivered could never move on is refused before anything is // journalled: each app's operations door must answer as BaselineOps says. func TestPreflightRefusesUnsupportedOperationsBaseline(t *testing.T) { cases := []struct { app string ops func(w http.ResponseWriter) want string // "" passes }{ {"docs", nil, ""}, {"docs", app401, "operations-app-401"}, {"docs", func(w http.ResponseWriter) { w.WriteHeader(500) }, "operations-other"}, {"docs", agent200(`{"user":"x"}`), "operations-other"}, {"docs", agent401, "operations-agent-401"}, {"slides", app401, ""}, {"slides", nil, "operations-absent"}, {"calls", agent401, "operations-agent-401"}, {"calls", app401, ""}, } for _, c := range cases { x := newCarlosFixture(t, c.app) x.site.ops = c.ops _, codes := x.preflight(t, nil) if c.want == "" { wantCodes(t, codes) continue } wantCodes(t, codes, c.want) } } // On a resume, the journal's own keys stored and the door already giving // agent-access's answer (a restart came between) is not a refusal: an // already-sent write stays recoverable. The keys of anyone else are. func TestPreflightAdmitsAgentDoorBehindOwnKeysOnResume(t *testing.T) { x := newCarlosFixture(t, "slides") keys := AgentKeys(x.app) mine := map[string]string{keys[0]: Issuer, keys[1]: fixtureSQID} for k, v := range mine { x.f.SetVar("slides", "", k, v) } x.site.ops = agent401 _, codes := x.preflight(t, mine) wantCodes(t, codes) // Not ours: refused, the door with it. _, codes = x.preflight(t, nil) wantCodes(t, codes, "agent-keys-present", "operations-agent-401") // Ours, but the door a lookalike: refused. x.site.ops = agent200(`{}`) _, codes = x.preflight(t, mine) wantCodes(t, codes, "operations-other") } func TestPreflightErrorsOnUnreadableNeighbour(t *testing.T) { x := newCarlosFixture(t, "docs") // Bound to an environment that was never created: the console answers // 502 for its view, and the run stops rather than guess. x.neighbour("ghost.docs.example", "ghost") _, _, err := Preflight(context.Background(), x.c, x.h, x.app, nil) if err == nil { t.Fatal("an unreadable neighbour passed") } } func TestObserveRefusesWithoutWriteLayer(t *testing.T) { x := newCarlosFixture(t, "docs") x.f.SetOverlay("docs", docsRoute, "DOCS_HOME_ISSUER", HomeIssuerOrigin) if _, err := Observe(context.Background(), x.c, x.h, x.app); err == nil || !strings.Contains(err.Error(), "layer-overlay") { t.Fatalf("Observe = %v", err) } y := newCarlosFixture(t, "docs") snap, err := Observe(context.Background(), y.c, y.h, y.app) if err != nil || snap.Layer.Version == "" || snap.Identity.Slug != "s-docs" { t.Fatalf("Observe = %v", err) } } func TestPreflightOutputHasNoValuesOrDigests(t *testing.T) { x := newCarlosFixture(t, "docs") x.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "foreign-team-value") x.f.SetVar("docs", "", "DOCS_TEAM_ID", "team-id-value") x.f.SetVar("docs", "", "DOCS_HOME_CONSUMER_ID", "consumer-value") x.neighbour("staging.docs.example", "staging") x.f.SetVar("docs", "staging", "DOCS_HOME_ISSUER", "https://issuer-value.example") x.site.header = "header-value" x.site.health = 500 _, codes, err := Preflight(context.Background(), x.c, x.h, x.app, map[string]string{"DOCS_AGENT_TEAM": "mine-value"}) if err != nil { t.Fatalf("Preflight: %v", err) } if len(codes) < 5 { t.Fatalf("codes = %q", codes) } out := strings.Join(codes, " ") for _, bad := range []string{"vd1:", "cv1:", "-value", valueOrigin, valueVersion, HomeIssuerOrigin, x.f.URL(), string(x.f.Token())} { if strings.Contains(out, bad) { t.Fatalf("codes carry %q: %q", bad, out) } } // And the errors: an Observe that refuses names codes only. x.f.SetOverlay("docs", docsRoute, "DOCS_HOME_ISSUER", "https://overlay-value.example") _, err = Observe(context.Background(), x.c, x.h, x.app) if err == nil { t.Fatal("Observe passed an overlay issuer") } for _, bad := range []string{"vd1:", "cv1:", "-value", x.f.URL()} { if strings.Contains(err.Error(), bad) { t.Fatalf("error carries %q: %v", bad, err) } } } // ---- Preserved and NewKeys ---- const ( dA = "vd1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" dB = "vd1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" dC = "vd1:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" vA = "cv1:1111111111111111111111111111111111111111111111111111111111111111" vB = "cv1:2222222222222222222222222222222222222222222222222222222222222222" vC = "cv1:3333333333333333333333333333333333333333333333333333333333333333" ) var added = [2]string{"DOCS_AGENT_ISSUER", "DOCS_AGENT_TEAM"} // beforeSnap is a canonical host on default, with an environment layer // it does not write and an overlay. func beforeSnap() Snapshot { id, eff := inst() return Snapshot{ Identity: IdentityOf(dom(), id, eff), WriteLayer: "", Layer: carlosop.Layer{Bundle: "default", Version: vA, Vars: []carlosop.Var{ {Key: "DOCS_HOME_ISSUER", Kind: "env", Digest: dA}, {Key: "DOCS_KEY", Kind: "secret", Digest: dB}, {Key: "DOCS_SHADOWED", Kind: "env", Digest: dA}, }}, Layers: map[string]string{"default": vA, "environment": vB, "overlay": "none"}, Vars: []carlosop.EffectiveVar{ {Key: "DOCS_HOME_ISSUER", Kind: "env", Digest: dA, From: "default"}, {Key: "DOCS_KEY", Kind: "secret", Digest: dB, From: "default"}, {Key: "DOCS_SHADOWED", Kind: "env", Digest: dC, From: "environment", Shadows: []string{"default"}}, {Key: "DOCS_ZONE", Kind: "env", Digest: dC, From: "environment"}, }, } } // afterSnap is beforeSnap with the two agent keys written to default. func afterSnap() Snapshot { s := beforeSnap() s.Layer.Version = vC s.Layer.Vars = append(append([]carlosop.Var{}, s.Layer.Vars...), carlosop.Var{Key: "DOCS_AGENT_ISSUER", Kind: "env", Digest: dA}, carlosop.Var{Key: "DOCS_AGENT_TEAM", Kind: "env", Digest: dB}) s.Layers = map[string]string{"default": vC, "environment": vB, "overlay": "none"} s.Vars = append(append([]carlosop.EffectiveVar{}, s.Vars...), carlosop.EffectiveVar{Key: "DOCS_AGENT_ISSUER", Kind: "env", Digest: dA, From: "default"}, carlosop.EffectiveVar{Key: "DOCS_AGENT_TEAM", Kind: "env", Digest: dB, From: "default"}) return s } func effVar(s *Snapshot, key string) *carlosop.EffectiveVar { for i := range s.Vars { if s.Vars[i].Key == key { return &s.Vars[i] } } return nil } func TestPreservedAcceptsTheWrite(t *testing.T) { if v := Preserved(beforeSnap(), afterSnap(), added); len(v) != 0 { t.Fatalf("violations = %q", v) } if v := Preserved(beforeSnap(), beforeSnap(), added); len(v) != 0 { t.Fatalf("violations = %q", v) } } func TestPreservedReportsEachViolation(t *testing.T) { cases := map[string]struct { edit func(a *Snapshot) want []string }{ "changed": {func(a *Snapshot) { effVar(a, "DOCS_KEY").Digest = dC }, []string{"changed:DOCS_KEY"}}, "gone": {func(a *Snapshot) { kept := a.Vars[:0] for _, v := range a.Vars { if v.Key != "DOCS_ZONE" { kept = append(kept, v) } } a.Vars = kept }, []string{"gone:DOCS_ZONE"}}, "kind": {func(a *Snapshot) { effVar(a, "DOCS_HOME_ISSUER").Kind = "secret" }, []string{"kind:DOCS_HOME_ISSUER"}}, "from": {func(a *Snapshot) { effVar(a, "DOCS_ZONE").From = "overlay" }, []string{"from:DOCS_ZONE"}}, "shadowed-in-write-layer": {func(a *Snapshot) { for i := range a.Layer.Vars { if a.Layer.Vars[i].Key == "DOCS_SHADOWED" { a.Layer.Vars[i].Digest = dB } } }, []string{"changed:DOCS_SHADOWED"}}, "gone-from-write-layer": {func(a *Snapshot) { a.Layer.Vars = a.Layer.Vars[1:] }, []string{"gone:DOCS_HOME_ISSUER"}}, "layer-environment": {func(a *Snapshot) { a.Layers["environment"] = vA }, []string{"layer:environment"}}, "layer-overlay": {func(a *Snapshot) { a.Layers["overlay"] = vA }, []string{"layer:overlay"}}, "layer-dropped": {func(a *Snapshot) { delete(a.Layers, "environment") }, []string{"layer:environment"}}, "identity": {func(a *Snapshot) { a.Identity.Slug = "other" a.Identity.RecordSeq++ }, []string{"record", "storage"}}, "several": {func(a *Snapshot) { effVar(a, "DOCS_KEY").Digest = dC effVar(a, "DOCS_ZONE").Kind = "secret" a.Identity.Moving = true }, []string{"changed:DOCS_KEY", "kind:DOCS_ZONE", "moving"}}, } for name, c := range cases { t.Run(name, func(t *testing.T) { a := afterSnap() c.edit(&a) wantCodes(t, Preserved(beforeSnap(), a, added), c.want...) }) } } func TestPreservedIgnoresNewUnrelatedKey(t *testing.T) { a := afterSnap() a.Vars = append(a.Vars, carlosop.EffectiveVar{Key: "DOCS_SMTP_HOST", Kind: "env", Digest: dA, From: "default"}) a.Layer.Vars = append(a.Layer.Vars, carlosop.Var{Key: "DOCS_SMTP_HOST", Kind: "env", Digest: dA}) if v := Preserved(beforeSnap(), a, added); len(v) != 0 { t.Fatalf("violations = %q", v) } if got := NewKeys(beforeSnap(), a, added); !reflect.DeepEqual(got, []string{"added:DOCS_SMTP_HOST"}) { t.Fatalf("new keys = %q", got) } if got := NewKeys(beforeSnap(), afterSnap(), added); len(got) != 0 { t.Fatalf("new keys = %q", got) } } // Exactly the two keys passed as added are exempt, even when present // before and changed after; any other key that changes, an agent key not // passed as added included, is a violation. func TestPreservedExemptsOnlyTheTwoAdded(t *testing.T) { b := afterSnap() a := afterSnap() effVar(&a, "DOCS_AGENT_TEAM").Digest = dC if v := Preserved(b, a, added); len(v) != 0 { t.Fatalf("an added key is preserved-checked: %q", v) } wantCodes(t, Preserved(b, a, [2]string{"DOCS_AGENT_ISSUER", "DOCS_OTHER"}), "changed:DOCS_AGENT_TEAM") } // A platform writer landing between the effective read and the layer's // read leaves no single moment to describe: Observe errors, never mixes. func TestPreflightErrorsWhenLayerMovesBetweenReads(t *testing.T) { x := newCarlosFixture(t, "docs") moved := false proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/config") && !moved { moved = true x.f.PlatformWrite("docs", "", "DOCS_SMTP_HOST", "smtp.example") } req, _ := http.NewRequestWithContext(r.Context(), r.Method, x.f.URL()+r.URL.RequestURI(), r.Body) req.Header = r.Header.Clone() resp, err := http.DefaultClient.Do(req) if err != nil { w.WriteHeader(502) return } defer resp.Body.Close() w.WriteHeader(resp.StatusCode) _, _ = io.Copy(w, resp.Body) })) t.Cleanup(proxy.Close) c := carlosop.New(proxy.URL, fixtureAccount, x.f.Token()) t.Cleanup(c.Close) if _, _, err := Preflight(context.Background(), c, x.h, x.app, nil); err == nil { t.Fatal("a layer that moved between reads passed") } if !moved { t.Fatal("the proxy never saw the layer read") } // The next read is coherent again. if _, codes, err := Preflight(context.Background(), c, x.h, x.app, nil); err != nil || len(codes) != 0 { t.Fatalf("Preflight = %q, %v", codes, err) } }