oficina / alta Public

Clone
git clone https://amadan.net/oficina/alta

Plain git — no account needed to clone.

Download

Download this file

1package adopt
2
3import (
4 "context"
5 "encoding/json"
6 "io"
7 "net"
8 "net/http"
9 "net/http/httptest"
10 "reflect"
11 "strings"
12 "testing"
13 "time"
14
15 "amadan.net/oficina/alta/carlosop"
16 "amadan.net/oficina/alta/carlosop/fakecarlos"
17 "amadan.net/oficina/alta/provision"
18)
19
20// carlosFixture is one app on a fake console, with its canonical instance
21// on the default bundle and a fake origin answering every probe.
22type carlosFixture struct {
23 f *fakecarlos.Fake
24 c *carlosop.Client
25 h *http.Client
26 site *site
27 app provision.App
28}
29
30const (
31 fixtureAccount = "bds"
32 // Plain values seeded into the fake: none may appear in any output.
33 valueOrigin = "https://docs.oficina.works/plain-origin-value"
34 valueVersion = "v1.4.0"
35)
36
37func appNamed(t *testing.T, slug string) provision.App {
38 t.Helper()
39 a, ok := provision.AppBySlug(slug)
40 if !ok {
41 t.Fatalf("no app %q", slug)
42 }
43 return a
44}
45
46// routeOf is the host of app's canonical record, as production has it:
47// the route the canonical domain (CanonicalHost) is claimed for, never
48// the domain itself.
49func routeOf(app provision.App) string { return app.Slug + "." + fixtureAccount + ".oncarlos.com" }
50
51// docsRoute is routeOf(docs).
52const docsRoute = "docs.bds.oncarlos.com"
53
54// attachCanonical claims app's canonical domain on f for its route, live,
55// as `carlos domains list` shows it in production.
56func attachCanonical(f *fakecarlos.Fake, app provision.App) {
57 f.AttachDomain(app.Slug, CanonicalHost(app), routeOf(app), "live")
58}
59
60// fixtureInstance is the canonical host's instance record as the
61// fixture first stores it.
62func fixtureInstance(app provision.App) carlosop.Instance {
63 return carlosop.Instance{
64 Host: routeOf(app), App: app.Slug, Slug: "s-" + app.Slug, Channel: "stable", Region: "eu",
65 CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4,
66 ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`),
67 }
68}
69
70func newCarlosFixture(t *testing.T, slug string) *carlosFixture {
71 t.Helper()
72 app := appNamed(t, slug)
73 f := fakecarlos.New(fixtureAccount)
74 t.Cleanup(f.Close)
75 p := app.Prefix
76 f.SetVar(app.Slug, "", p+"_HOME_ISSUER", HomeIssuerOrigin)
77 f.SetVar(app.Slug, "", p+"_HOME_CONSUMER_ID", provision.ConsumerID(provision.AdoptionLabel, app.Slug))
78 f.SetVar(app.Slug, "", p+"_ORIGIN", valueOrigin)
79 f.SetSecret(app.Slug, "", p+"_INSTANCE_KEY")
80 f.AddInstance(fixtureInstance(app))
81 attachCanonical(f, app)
82 c := carlosop.New(f.URL(), fixtureAccount, f.Token())
83 t.Cleanup(c.Close)
84
85 s := &site{version: valueVersion, header: valueVersion, health: 200}
86 switch BaselineOps(app) {
87 case OpsApp401:
88 s.ops = app401
89 case OpsAgent401:
90 s.ops = agent401
91 }
92 srv := httptest.NewTLSServer(s.handler())
93 t.Cleanup(srv.Close)
94 tr := srv.Client().Transport.(*http.Transport).Clone()
95 addr := srv.Listener.Addr().String()
96 // Every https origin the probe names lands on the fake site.
97 tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
98 var d net.Dialer
99 return d.DialContext(ctx, network, addr)
100 }
101 tr.TLSClientConfig.ServerName = "example.com"
102 return &carlosFixture{f: f, c: c, h: &http.Client{Transport: tr, Timeout: 10 * time.Second}, site: s, app: app}
103}
104
105// neighbour adds another instance of the fixture's app on env (""= none).
106func (x *carlosFixture) neighbour(host, env string) {
107 x.f.AddInstance(carlosop.Instance{Host: host, App: x.app.Slug, Slug: "s-" + host, Environment: env,
108 Channel: "stable", Region: "eu", CreatedAt: time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)})
109}
110
111func (x *carlosFixture) preflight(t *testing.T, mine map[string]string) (Snapshot, []string) {
112 t.Helper()
113 snap, codes, err := Preflight(context.Background(), x.c, x.h, x.app, mine)
114 if err != nil {
115 t.Fatalf("Preflight: %v", err)
116 }
117 return snap, codes
118}
119
120func TestPreflightPassesCleanApp(t *testing.T) {
121 x := newCarlosFixture(t, "docs")
122 snap, codes := x.preflight(t, nil)
123 wantCodes(t, codes)
124 if snap.WriteLayer != "" || snap.Layer.Bundle != "default" || snap.HomeIssuer != HomeIssuerOrigin || snap.HomeConsumer != "docs" {
125 t.Fatalf("snapshot write layer %q bundle %q", snap.WriteLayer, snap.Layer.Bundle)
126 }
127 if snap.Identity.RecordHost != docsRoute || snap.Identity.Domain != "docs.oficina.works" || snap.Identity.Route != docsRoute ||
128 snap.Delivery.Version != valueVersion || snap.At.IsZero() {
129 t.Fatalf("snapshot identity/delivery not recorded")
130 }
131 if len(snap.Vars) != 4 || len(snap.Layers) != 2 {
132 t.Fatalf("vars %d layers %d", len(snap.Vars), len(snap.Layers))
133 }
134}
135
136// productionShape is docs as production has it (carlos domains list and
137// instances list, 2026-11-17): the canonical domain claimed, live, for
138// docs.bds.oncarlos.com; a lagged domain for a lagged record on the same
139// channel; and canary records with no domain of their own, one of them on
140// an owned environment.
141func productionShape(t *testing.T) *carlosFixture {
142 t.Helper()
143 x := newCarlosFixture(t, "docs")
144 x.f = fakecarlos.New(fixtureAccount)
145 t.Cleanup(x.f.Close)
146 x.f.SetVar("docs", "", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
147 x.f.SetVar("docs", "", "DOCS_HOME_CONSUMER_ID", "docs")
148 x.f.AddInstance(fixtureInstance(x.app))
149 x.f.AttachDomain("docs", "docs.oficina.works", docsRoute, "live")
150 for _, env := range []string{"lagged", "overnight-release", "contract-demo", "google-import"} {
151 x.f.SetVar("docs", env, "DOCS_HOME_ISSUER", HomeIssuerOrigin)
152 x.f.AddInstance(carlosop.Instance{Host: env + "-docs.bds.oncarlos.com", App: "docs", Slug: "s-" + env, Environment: env,
153 Channel: "stable", Region: "eu", CreatedAt: time.Date(2026, 10, 27, 0, 0, 0, 0, time.UTC)})
154 }
155 x.f.Own("docs", "google-import", "alta")
156 x.f.AttachDomain("docs", "lagged.docs.oficina.works", "lagged-docs.bds.oncarlos.com", "live")
157 x.c = carlosop.New(x.f.URL(), fixtureAccount, x.f.Token())
158 t.Cleanup(x.c.Close)
159 return x
160}
161
162// The canonical name is a domain claim, and the record is the one its
163// route names. The other records, with a domain of their own or none, are
164// neighbours: each that folds in the default would inherit the keys.
165func TestPreflightResolvesCanonicalDomainInProductionShape(t *testing.T) {
166 x := productionShape(t)
167 snap, codes := x.preflight(t, nil)
168 wantCodes(t, codes, "inherits-contract-demo-docs.bds.oncarlos.com", "inherits-lagged-docs.bds.oncarlos.com",
169 "inherits-overnight-release-docs.bds.oncarlos.com")
170 id := snap.Identity
171 if id.RecordHost != docsRoute || id.Domain != "docs.oficina.works" || id.Route != docsRoute || id.Slug != "s-docs" {
172 t.Fatalf("identity %+v", id)
173 }
174 if snap.WriteLayer != "" || snap.Delivery.Header != valueVersion {
175 t.Fatalf("write layer %q, delivery header %q", snap.WriteLayer, snap.Delivery.Header)
176 }
177 if code := ReviewedRelease(snap.Delivery, sha256Hex(valueVersion)); code != "" {
178 t.Fatalf("the reviewed release read %s from the canonical domain", code)
179 }
180 if got := x.site.lastHost(); got != "docs.oficina.works" {
181 t.Fatalf("the probe asked %q, not the canonical domain", got)
182 }
183}
184
185// Each lookalike of the canonical binding refuses with its own code and
186// no delivery probe; nothing falls back to a guess.
187func TestPreflightRefusesCanonicalDomainLookalikes(t *testing.T) {
188 cases := map[string]struct {
189 edit func(x *carlosFixture)
190 want string
191 }{
192 "no claim": {func(x *carlosFixture) { x.f.DetachDomain("docs", "docs.oficina.works") }, "domain-missing"},
193 // The canonical name as a record's own host is not a claim.
194 "record named like the domain": {func(x *carlosFixture) {
195 x.f.DetachDomain("docs", "docs.oficina.works")
196 x.f.AddInstance(carlosop.Instance{Host: "docs.oficina.works", App: "docs", Slug: "s-docs", Channel: "stable"})
197 }, "domain-missing"},
198 "claim pending DNS": {func(x *carlosFixture) { x.f.AttachDomain("docs", "docs.oficina.works", docsRoute, "pending-dns") }, "domain-not-live"},
199 "claim unverified": {func(x *carlosFixture) { x.f.AttachDomain("docs", "docs.oficina.works", docsRoute, "unverified") }, "domain-not-live"},
200 "claim with no state": {func(x *carlosFixture) { x.f.AttachDomain("docs", "docs.oficina.works", docsRoute, "") }, "domain-not-live"},
201 "route to a missing record": {func(x *carlosFixture) {
202 x.f.AttachDomain("docs", "docs.oficina.works", "gone-docs.bds.oncarlos.com", "live")
203 }, "instance-missing"},
204 "claim with no route": {func(x *carlosFixture) { x.f.AttachDomain("docs", "docs.oficina.works", "", "live") }, "instance-missing"},
205 }
206 for name, c := range cases {
207 t.Run(name, func(t *testing.T) {
208 x := productionShape(t)
209 c.edit(x)
210 snap, codes := x.preflight(t, nil)
211 wantCodes(t, codes, c.want)
212 if snap.Delivery != (Delivery{}) || x.site.lastHost() != "" {
213 t.Fatalf("a refused binding was probed")
214 }
215 if _, err := Observe(context.Background(), x.c, x.h, x.app); err == nil || !strings.Contains(err.Error(), c.want) {
216 t.Fatalf("Observe: %v, want %s", err, c.want)
217 }
218 })
219 }
220}
221
222// Two claims answering for the canonical name are ambiguous: neither is
223// picked. A name a catch-all derives is not a claim, beside one or alone.
224func TestCanonicalRecordRefusesTwoClaims(t *testing.T) {
225 x := productionShape(t)
226 all, err := x.c.Instances(context.Background(), "docs")
227 if err != nil {
228 t.Fatalf("Instances: %v", err)
229 }
230 canon := carlosop.Domain{Host: "docs.oficina.works", Route: docsRoute, State: "live"}
231 other := carlosop.Domain{Host: "docs.oficina.works", Route: "lagged-docs.bds.oncarlos.com", State: "live"}
232 if _, rec, code, err := canonicalRecord("docs.oficina.works", []carlosop.Domain{canon, other}, all); err != nil || rec != nil || code != "domain-ambiguous" {
233 t.Fatalf("two claims: %v %v %q", rec, err, code)
234 }
235 derived := other
236 derived.Via = "*.oficina.works"
237 if d, rec, code, err := canonicalRecord("docs.oficina.works", []carlosop.Domain{canon, derived}, all); err != nil || code != "" || rec.Host != docsRoute || d != canon {
238 t.Fatalf("a claim beside a derived name: %v %q", err, code)
239 }
240 if _, _, code, _ := canonicalRecord("docs.oficina.works", []carlosop.Domain{derived}, all); code != "domain-missing" {
241 t.Fatalf("a derived name alone was read as the claim: %q", code)
242 }
243 // The console's own answer with two rows for the name refuses
244 // Preflight before any config is read.
245 var reads []string
246 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
247 reads = append(reads, r.URL.Path)
248 w.Header().Set("Content-Type", "application/json")
249 switch r.URL.Path {
250 case "/api/cli/apps/bds/docs/domains":
251 _, _ = io.WriteString(w, `{"domains":[`+
252 `{"host":"docs.oficina.works","route":"docs.bds.oncarlos.com","state":"live"},`+
253 `{"host":"docs.oficina.works","route":"lagged-docs.bds.oncarlos.com","state":"live"}]}`)
254 case "/api/cli/apps/bds/docs/instances":
255 _, _ = io.WriteString(w, `{"instances":[{"host":"docs.bds.oncarlos.com","app":"docs","account":"bds"},`+
256 `{"host":"lagged-docs.bds.oncarlos.com","app":"docs","account":"bds"}],"truncated":false}`)
257 default:
258 w.WriteHeader(http.StatusNotFound)
259 }
260 }))
261 t.Cleanup(srv.Close)
262 c := carlosop.New(srv.URL, fixtureAccount, []byte("svc_token"))
263 t.Cleanup(c.Close)
264 _, codes, err := Preflight(context.Background(), c, x.h, x.app, nil)
265 if err != nil {
266 t.Fatalf("Preflight: %v", err)
267 }
268 wantCodes(t, codes, "domain-ambiguous")
269 if len(reads) != 2 || x.site.lastHost() != "" {
270 t.Fatalf("an ambiguous claim went on to read %v, or probed", reads)
271 }
272}
273
274// The domain re-pointed at another record between two observations
275// changes the identity, though neither record changed.
276func TestRepointedDomainChangesIdentity(t *testing.T) {
277 x := productionShape(t)
278 before, err := Observe(context.Background(), x.c, x.h, x.app)
279 if err != nil {
280 t.Fatalf("Observe: %v", err)
281 }
282 x.f.AttachDomain("docs", "docs.oficina.works", "lagged-docs.bds.oncarlos.com", "live")
283 after, _, codes, err := observe(context.Background(), x.c, nil, x.app)
284 if err != nil {
285 t.Fatalf("observe: %v", err)
286 }
287 wantCodes(t, codes)
288 if got := SameIdentity(before.Identity, after.Identity); !reflect.DeepEqual(got, []string{"alias", "environment", "instance", "record", "storage"}) {
289 t.Fatalf("SameIdentity = %v", got)
290 }
291 // The claim's route alone moving is the alias.
292 moved := before.Identity
293 moved.Route = "lagged-docs.bds.oncarlos.com"
294 if got := SameIdentity(before.Identity, moved); !reflect.DeepEqual(got, []string{"alias"}) {
295 t.Fatalf("SameIdentity = %v", got)
296 }
297}
298
299// Review focus 1: a neighbour overriding another key still inherits both
300// agent keys from the shared default.
301func TestPreflightRefusesInheritanceDespiteOtherOverride(t *testing.T) {
302 x := newCarlosFixture(t, "docs")
303 x.neighbour("staging.docs.example", "staging")
304 x.f.SetVar("docs", "staging", "DOCS_HOME_ISSUER", "https://id.staging.example")
305 _, codes := x.preflight(t, nil)
306 wantCodes(t, codes, "inherits-staging.docs.example")
307}
308
309func TestPreflightRefusesUnboundNeighbour(t *testing.T) {
310 x := newCarlosFixture(t, "docs")
311 x.neighbour("bare.docs.example", "")
312 _, codes := x.preflight(t, nil)
313 wantCodes(t, codes, "inherits-bare.docs.example")
314}
315
316func TestPreflightRefusesNeighbourShadowingOneKey(t *testing.T) {
317 x := newCarlosFixture(t, "docs")
318 x.neighbour("staging.docs.example", "staging")
319 x.f.SetVar("docs", "staging", "DOCS_AGENT_ISSUER", "https://connect.staging.example")
320 _, codes := x.preflight(t, nil)
321 wantCodes(t, codes, "inherits-staging.docs.example")
322}
323
324func TestPreflightAllowsOwnedEnvironmentNeighbour(t *testing.T) {
325 x := newCarlosFixture(t, "docs")
326 x.neighbour("acme.docs.oficina.works", "acme-docs")
327 x.f.SetVar("docs", "acme-docs", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
328 x.f.Own("docs", "acme-docs", "alta")
329 _, codes := x.preflight(t, nil)
330 wantCodes(t, codes)
331}
332
333func TestPreflightAllowsNeighbourThatAlreadyShadowsBothKeys(t *testing.T) {
334 x := newCarlosFixture(t, "docs")
335 x.neighbour("staging.docs.example", "staging")
336 x.f.SetVar("docs", "staging", "DOCS_AGENT_ISSUER", "https://connect.staging.example")
337 x.f.SetVar("docs", "staging", "DOCS_AGENT_TEAM", "stg")
338 _, codes := x.preflight(t, nil)
339 wantCodes(t, codes)
340}
341
342// A write to a named environment reaches only that environment's routes.
343func TestPreflightNamedWriteLayerInheritance(t *testing.T) {
344 x := newCarlosFixture(t, "docs")
345 x.f = fakecarlos.New(fixtureAccount)
346 t.Cleanup(x.f.Close)
347 x.f.SetVar("docs", "prod", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
348 x.f.SetVar("docs", "prod", "DOCS_HOME_CONSUMER_ID", "docs")
349 x.f.SetVar("docs", "other", "DOCS_ORIGIN", "x")
350 x.f.AddInstance(carlosop.Instance{Host: docsRoute, App: "docs", Slug: "s", Environment: "prod", Channel: "stable"})
351 attachCanonical(x.f, x.app)
352 x.f.AddInstance(carlosop.Instance{Host: "other.docs.example", App: "docs", Slug: "o", Environment: "other", Channel: "stable"})
353 x.f.AddInstance(carlosop.Instance{Host: "bare.docs.example", App: "docs", Slug: "b", Channel: "stable"})
354 x.c = carlosop.New(x.f.URL(), fixtureAccount, x.f.Token())
355 t.Cleanup(x.c.Close)
356 snap, codes := x.preflight(t, nil)
357 wantCodes(t, codes)
358 if snap.WriteLayer != "prod" || snap.Layer.Bundle != "prod" {
359 t.Fatalf("write layer %q", snap.WriteLayer)
360 }
361 x.f.AddInstance(carlosop.Instance{Host: "twin.docs.example", App: "docs", Slug: "t", Environment: "prod", Channel: "stable"})
362 _, codes = x.preflight(t, nil)
363 wantCodes(t, codes, "inherits-twin.docs.example")
364}
365
366func TestPreflightRefusesTeamMode(t *testing.T) {
367 x := newCarlosFixture(t, "docs")
368 x.f.SetVar("docs", "", "DOCS_TEAM_ID", "abc")
369 x.f.SetVar("docs", "", "DOCS_TEAM_SOMETHING_NEW", "1")
370 _, codes := x.preflight(t, nil)
371 wantCodes(t, codes, "team-mode-DOCS_TEAM_ID", "team-mode-DOCS_TEAM_SOMETHING_NEW")
372
373 m := newCarlosFixture(t, "memoria")
374 m.f.SetVar("memoria", "", "MEMORIA_TEAM", "on")
375 _, codes = m.preflight(t, nil)
376 wantCodes(t, codes)
377 m.f.SetSecret("memoria", "", "MEMORIA_TEAM_ROSTER_TOKEN")
378 _, codes = m.preflight(t, nil)
379 wantCodes(t, codes, "team-mode-MEMORIA_TEAM_ROSTER_TOKEN")
380}
381
382func TestTeamModeKeys(t *testing.T) {
383 app := appNamed(t, "calls")
384 got := TeamModeKeys(app, []carlosop.EffectiveVar{
385 {Key: "CALLS_TEAM"}, {Key: "CALLS_TEAM_ZZ"}, {Key: "CALLS_TEAM_ID"}, {Key: "DOCS_TEAM_ID"}, {Key: "CALLS_ORIGIN"},
386 })
387 if !reflect.DeepEqual(got, []string{"CALLS_TEAM_ID", "CALLS_TEAM_ZZ"}) {
388 t.Fatalf("team keys = %q", got)
389 }
390}
391
392func TestPreflightRefusesForeignAgentKeys(t *testing.T) {
393 mine := map[string]string{"DOCS_AGENT_ISSUER": Issuer, "DOCS_AGENT_TEAM": "tQ3"}
394
395 x := newCarlosFixture(t, "docs")
396 x.f.SetVar("docs", "", "DOCS_AGENT_ISSUER", Issuer)
397 x.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "someone-else")
398 _, codes := x.preflight(t, mine)
399 wantCodes(t, codes, "agent-keys-present")
400 _, codes = x.preflight(t, nil)
401 wantCodes(t, codes, "agent-keys-present")
402
403 // The journal's own sent values, on a resume, pass.
404 x.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "tQ3")
405 _, codes = x.preflight(t, mine)
406 wantCodes(t, codes)
407
408 // The same value as a secret is not ours.
409 x.f.SetSecret("docs", "", "DOCS_AGENT_TEAM")
410 _, codes = x.preflight(t, mine)
411 wantCodes(t, codes, "agent-keys-present")
412
413 // Our value, but from a layer above the write layer: not ours either.
414 y := newCarlosFixture(t, "docs")
415 y.f.SetOverlay("docs", docsRoute, "DOCS_AGENT_ISSUER", Issuer)
416 _, codes = y.preflight(t, mine)
417 wantCodes(t, codes, "agent-keys-present")
418}
419
420func TestPreflightRefusesMovingInstance(t *testing.T) {
421 x := newCarlosFixture(t, "docs")
422 x.f.AddInstance(carlosop.Instance{Host: docsRoute, App: "docs", Slug: "s-docs", Channel: "stable", Region: "eu",
423 Move: json.RawMessage(`{"to":"us"}`)})
424 _, codes := x.preflight(t, nil)
425 wantCodes(t, codes, "instance-moving")
426}
427
428func TestPreflightRefusesEachConfigCode(t *testing.T) {
429 cases := map[string]struct {
430 edit func(x *carlosFixture)
431 want []string
432 }{
433 "instance-missing": {func(x *carlosFixture) {
434 x.f = fakecarlos.New(fixtureAccount)
435 x.f.SetVar("docs", "", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
436 x.f.AddInstance(carlosop.Instance{Host: "elsewhere.docs.example", App: "docs", Slug: "e", Channel: "stable"})
437 attachCanonical(x.f, x.app)
438 x.c = carlosop.New(x.f.URL(), fixtureAccount, x.f.Token())
439 }, []string{"instance-missing"}},
440 "layer-overlay": {func(x *carlosFixture) {
441 x.f.SetOverlay("docs", docsRoute, "DOCS_HOME_ISSUER", HomeIssuerOrigin)
442 }, []string{"layer-overlay"}},
443 "home-issuer-absent": {func(x *carlosFixture) {
444 x.f.Unset("docs", "", "DOCS_HOME_ISSUER")
445 }, []string{"home-issuer-mismatch"}},
446 "home-issuer-other": {func(x *carlosFixture) {
447 x.f.SetVar("docs", "", "DOCS_HOME_ISSUER", "https://id.example")
448 }, []string{"home-issuer-mismatch"}},
449 "home-issuer-secret": {func(x *carlosFixture) {
450 x.f.SetSecret("docs", "", "DOCS_HOME_ISSUER")
451 }, []string{"home-issuer-mismatch"}},
452 "home-consumer-other": {func(x *carlosFixture) {
453 x.f.SetVar("docs", "", "DOCS_HOME_CONSUMER_ID", "oficina-docs")
454 }, []string{"home-consumer-mismatch"}},
455 "home-consumer-absent": {func(x *carlosFixture) {
456 x.f.Unset("docs", "", "DOCS_HOME_CONSUMER_ID")
457 }, []string{"home-consumer-mismatch"}},
458 "home-consumer-overlay": {func(x *carlosFixture) {
459 x.f.SetOverlay("docs", docsRoute, "DOCS_HOME_CONSUMER_ID", "docs")
460 }, []string{"home-consumer-mismatch"}},
461 "owned-environment": {func(x *carlosFixture) {
462 x.f.AddInstance(carlosop.Instance{Host: docsRoute, App: "docs", Slug: "s-docs", Environment: "mine", Channel: "stable"})
463 x.f.SetVar("docs", "mine", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
464 x.f.SetVar("docs", "mine", "DOCS_HOME_CONSUMER_ID", "docs")
465 x.f.Own("docs", "mine", "alta")
466 }, []string{"owned-environment"}},
467 "version-header-mismatch": {func(x *carlosFixture) { x.site.header = "v1.3.9" }, []string{"version-header-mismatch"}},
468 "version-empty": {func(x *carlosFixture) { x.site.version, x.site.header = "", "" }, []string{"version-header-mismatch"}},
469 "version-redirect": {func(x *carlosFixture) { x.site.redirectVersion = true }, []string{"version-header-mismatch"}},
470 "ops-redirect": {func(x *carlosFixture) {
471 x.site.ops = func(w http.ResponseWriter) { w.Header().Set("Location", "/elsewhere"); w.WriteHeader(http.StatusFound) }
472 }, []string{"operations-other", "version-header-mismatch"}},
473 "healthz": {func(x *carlosFixture) { x.site.health = 503 }, []string{"healthz"}},
474 }
475 for name, c := range cases {
476 t.Run(name, func(t *testing.T) {
477 x := newCarlosFixture(t, "docs")
478 c.edit(x)
479 t.Cleanup(x.f.Close)
480 t.Cleanup(x.c.Close)
481 _, codes := x.preflight(t, nil)
482 wantCodes(t, codes, c.want...)
483 })
484 }
485}
486
487// A baseline Delivered could never move on is refused before anything is
488// journalled: each app's operations door must answer as BaselineOps says.
489func TestPreflightRefusesUnsupportedOperationsBaseline(t *testing.T) {
490 cases := []struct {
491 app string
492 ops func(w http.ResponseWriter)
493 want string // "" passes
494 }{
495 {"docs", nil, ""},
496 {"docs", app401, "operations-app-401"},
497 {"docs", func(w http.ResponseWriter) { w.WriteHeader(500) }, "operations-other"},
498 {"docs", agent200(`{"user":"x"}`), "operations-other"},
499 {"docs", agent401, "operations-agent-401"},
500 {"slides", app401, ""},
501 {"slides", nil, "operations-absent"},
502 {"calls", agent401, "operations-agent-401"},
503 {"calls", app401, ""},
504 }
505 for _, c := range cases {
506 x := newCarlosFixture(t, c.app)
507 x.site.ops = c.ops
508 _, codes := x.preflight(t, nil)
509 if c.want == "" {
510 wantCodes(t, codes)
511 continue
512 }
513 wantCodes(t, codes, c.want)
514 }
515}
516
517// On a resume, the journal's own keys stored and the door already giving
518// agent-access's answer (a restart came between) is not a refusal: an
519// already-sent write stays recoverable. The keys of anyone else are.
520func TestPreflightAdmitsAgentDoorBehindOwnKeysOnResume(t *testing.T) {
521 x := newCarlosFixture(t, "slides")
522 keys := AgentKeys(x.app)
523 mine := map[string]string{keys[0]: Issuer, keys[1]: fixtureSQID}
524 for k, v := range mine {
525 x.f.SetVar("slides", "", k, v)
526 }
527 x.site.ops = agent401
528 _, codes := x.preflight(t, mine)
529 wantCodes(t, codes)
530 // Not ours: refused, the door with it.
531 _, codes = x.preflight(t, nil)
532 wantCodes(t, codes, "agent-keys-present", "operations-agent-401")
533 // Ours, but the door a lookalike: refused.
534 x.site.ops = agent200(`{}`)
535 _, codes = x.preflight(t, mine)
536 wantCodes(t, codes, "operations-other")
537}
538
539func TestPreflightErrorsOnUnreadableNeighbour(t *testing.T) {
540 x := newCarlosFixture(t, "docs")
541 // Bound to an environment that was never created: the console answers
542 // 502 for its view, and the run stops rather than guess.
543 x.neighbour("ghost.docs.example", "ghost")
544 _, _, err := Preflight(context.Background(), x.c, x.h, x.app, nil)
545 if err == nil {
546 t.Fatal("an unreadable neighbour passed")
547 }
548}
549
550func TestObserveRefusesWithoutWriteLayer(t *testing.T) {
551 x := newCarlosFixture(t, "docs")
552 x.f.SetOverlay("docs", docsRoute, "DOCS_HOME_ISSUER", HomeIssuerOrigin)
553 if _, err := Observe(context.Background(), x.c, x.h, x.app); err == nil || !strings.Contains(err.Error(), "layer-overlay") {
554 t.Fatalf("Observe = %v", err)
555 }
556 y := newCarlosFixture(t, "docs")
557 snap, err := Observe(context.Background(), y.c, y.h, y.app)
558 if err != nil || snap.Layer.Version == "" || snap.Identity.Slug != "s-docs" {
559 t.Fatalf("Observe = %v", err)
560 }
561}
562
563func TestPreflightOutputHasNoValuesOrDigests(t *testing.T) {
564 x := newCarlosFixture(t, "docs")
565 x.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "foreign-team-value")
566 x.f.SetVar("docs", "", "DOCS_TEAM_ID", "team-id-value")
567 x.f.SetVar("docs", "", "DOCS_HOME_CONSUMER_ID", "consumer-value")
568 x.neighbour("staging.docs.example", "staging")
569 x.f.SetVar("docs", "staging", "DOCS_HOME_ISSUER", "https://issuer-value.example")
570 x.site.header = "header-value"
571 x.site.health = 500
572 _, codes, err := Preflight(context.Background(), x.c, x.h, x.app, map[string]string{"DOCS_AGENT_TEAM": "mine-value"})
573 if err != nil {
574 t.Fatalf("Preflight: %v", err)
575 }
576 if len(codes) < 5 {
577 t.Fatalf("codes = %q", codes)
578 }
579 out := strings.Join(codes, " ")
580 for _, bad := range []string{"vd1:", "cv1:", "-value", valueOrigin, valueVersion, HomeIssuerOrigin, x.f.URL(), string(x.f.Token())} {
581 if strings.Contains(out, bad) {
582 t.Fatalf("codes carry %q: %q", bad, out)
583 }
584 }
585 // And the errors: an Observe that refuses names codes only.
586 x.f.SetOverlay("docs", docsRoute, "DOCS_HOME_ISSUER", "https://overlay-value.example")
587 _, err = Observe(context.Background(), x.c, x.h, x.app)
588 if err == nil {
589 t.Fatal("Observe passed an overlay issuer")
590 }
591 for _, bad := range []string{"vd1:", "cv1:", "-value", x.f.URL()} {
592 if strings.Contains(err.Error(), bad) {
593 t.Fatalf("error carries %q: %v", bad, err)
594 }
595 }
596}
597
598// ---- Preserved and NewKeys ----
599
600const (
601 dA = "vd1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
602 dB = "vd1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
603 dC = "vd1:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
604 vA = "cv1:1111111111111111111111111111111111111111111111111111111111111111"
605 vB = "cv1:2222222222222222222222222222222222222222222222222222222222222222"
606 vC = "cv1:3333333333333333333333333333333333333333333333333333333333333333"
607)
608
609var added = [2]string{"DOCS_AGENT_ISSUER", "DOCS_AGENT_TEAM"}
610
611// beforeSnap is a canonical host on default, with an environment layer
612// it does not write and an overlay.
613func beforeSnap() Snapshot {
614 id, eff := inst()
615 return Snapshot{
616 Identity: IdentityOf(dom(), id, eff),
617 WriteLayer: "",
618 Layer: carlosop.Layer{Bundle: "default", Version: vA, Vars: []carlosop.Var{
619 {Key: "DOCS_HOME_ISSUER", Kind: "env", Digest: dA},
620 {Key: "DOCS_KEY", Kind: "secret", Digest: dB},
621 {Key: "DOCS_SHADOWED", Kind: "env", Digest: dA},
622 }},
623 Layers: map[string]string{"default": vA, "environment": vB, "overlay": "none"},
624 Vars: []carlosop.EffectiveVar{
625 {Key: "DOCS_HOME_ISSUER", Kind: "env", Digest: dA, From: "default"},
626 {Key: "DOCS_KEY", Kind: "secret", Digest: dB, From: "default"},
627 {Key: "DOCS_SHADOWED", Kind: "env", Digest: dC, From: "environment", Shadows: []string{"default"}},
628 {Key: "DOCS_ZONE", Kind: "env", Digest: dC, From: "environment"},
629 },
630 }
631}
632
633// afterSnap is beforeSnap with the two agent keys written to default.
634func afterSnap() Snapshot {
635 s := beforeSnap()
636 s.Layer.Version = vC
637 s.Layer.Vars = append(append([]carlosop.Var{}, s.Layer.Vars...),
638 carlosop.Var{Key: "DOCS_AGENT_ISSUER", Kind: "env", Digest: dA}, carlosop.Var{Key: "DOCS_AGENT_TEAM", Kind: "env", Digest: dB})
639 s.Layers = map[string]string{"default": vC, "environment": vB, "overlay": "none"}
640 s.Vars = append(append([]carlosop.EffectiveVar{}, s.Vars...),
641 carlosop.EffectiveVar{Key: "DOCS_AGENT_ISSUER", Kind: "env", Digest: dA, From: "default"},
642 carlosop.EffectiveVar{Key: "DOCS_AGENT_TEAM", Kind: "env", Digest: dB, From: "default"})
643 return s
644}
645
646func effVar(s *Snapshot, key string) *carlosop.EffectiveVar {
647 for i := range s.Vars {
648 if s.Vars[i].Key == key {
649 return &s.Vars[i]
650 }
651 }
652 return nil
653}
654
655func TestPreservedAcceptsTheWrite(t *testing.T) {
656 if v := Preserved(beforeSnap(), afterSnap(), added); len(v) != 0 {
657 t.Fatalf("violations = %q", v)
658 }
659 if v := Preserved(beforeSnap(), beforeSnap(), added); len(v) != 0 {
660 t.Fatalf("violations = %q", v)
661 }
662}
663
664func TestPreservedReportsEachViolation(t *testing.T) {
665 cases := map[string]struct {
666 edit func(a *Snapshot)
667 want []string
668 }{
669 "changed": {func(a *Snapshot) { effVar(a, "DOCS_KEY").Digest = dC }, []string{"changed:DOCS_KEY"}},
670 "gone": {func(a *Snapshot) {
671 kept := a.Vars[:0]
672 for _, v := range a.Vars {
673 if v.Key != "DOCS_ZONE" {
674 kept = append(kept, v)
675 }
676 }
677 a.Vars = kept
678 }, []string{"gone:DOCS_ZONE"}},
679 "kind": {func(a *Snapshot) { effVar(a, "DOCS_HOME_ISSUER").Kind = "secret" }, []string{"kind:DOCS_HOME_ISSUER"}},
680 "from": {func(a *Snapshot) { effVar(a, "DOCS_ZONE").From = "overlay" }, []string{"from:DOCS_ZONE"}},
681 "shadowed-in-write-layer": {func(a *Snapshot) {
682 for i := range a.Layer.Vars {
683 if a.Layer.Vars[i].Key == "DOCS_SHADOWED" {
684 a.Layer.Vars[i].Digest = dB
685 }
686 }
687 }, []string{"changed:DOCS_SHADOWED"}},
688 "gone-from-write-layer": {func(a *Snapshot) { a.Layer.Vars = a.Layer.Vars[1:] }, []string{"gone:DOCS_HOME_ISSUER"}},
689 "layer-environment": {func(a *Snapshot) { a.Layers["environment"] = vA }, []string{"layer:environment"}},
690 "layer-overlay": {func(a *Snapshot) { a.Layers["overlay"] = vA }, []string{"layer:overlay"}},
691 "layer-dropped": {func(a *Snapshot) { delete(a.Layers, "environment") }, []string{"layer:environment"}},
692 "identity": {func(a *Snapshot) {
693 a.Identity.Slug = "other"
694 a.Identity.RecordSeq++
695 }, []string{"record", "storage"}},
696 "several": {func(a *Snapshot) {
697 effVar(a, "DOCS_KEY").Digest = dC
698 effVar(a, "DOCS_ZONE").Kind = "secret"
699 a.Identity.Moving = true
700 }, []string{"changed:DOCS_KEY", "kind:DOCS_ZONE", "moving"}},
701 }
702 for name, c := range cases {
703 t.Run(name, func(t *testing.T) {
704 a := afterSnap()
705 c.edit(&a)
706 wantCodes(t, Preserved(beforeSnap(), a, added), c.want...)
707 })
708 }
709}
710
711func TestPreservedIgnoresNewUnrelatedKey(t *testing.T) {
712 a := afterSnap()
713 a.Vars = append(a.Vars, carlosop.EffectiveVar{Key: "DOCS_SMTP_HOST", Kind: "env", Digest: dA, From: "default"})
714 a.Layer.Vars = append(a.Layer.Vars, carlosop.Var{Key: "DOCS_SMTP_HOST", Kind: "env", Digest: dA})
715 if v := Preserved(beforeSnap(), a, added); len(v) != 0 {
716 t.Fatalf("violations = %q", v)
717 }
718 if got := NewKeys(beforeSnap(), a, added); !reflect.DeepEqual(got, []string{"added:DOCS_SMTP_HOST"}) {
719 t.Fatalf("new keys = %q", got)
720 }
721 if got := NewKeys(beforeSnap(), afterSnap(), added); len(got) != 0 {
722 t.Fatalf("new keys = %q", got)
723 }
724}
725
726// Exactly the two keys passed as added are exempt, even when present
727// before and changed after; any other key that changes, an agent key not
728// passed as added included, is a violation.
729func TestPreservedExemptsOnlyTheTwoAdded(t *testing.T) {
730 b := afterSnap()
731 a := afterSnap()
732 effVar(&a, "DOCS_AGENT_TEAM").Digest = dC
733 if v := Preserved(b, a, added); len(v) != 0 {
734 t.Fatalf("an added key is preserved-checked: %q", v)
735 }
736 wantCodes(t, Preserved(b, a, [2]string{"DOCS_AGENT_ISSUER", "DOCS_OTHER"}), "changed:DOCS_AGENT_TEAM")
737}
738
739// A platform writer landing between the effective read and the layer's
740// read leaves no single moment to describe: Observe errors, never mixes.
741func TestPreflightErrorsWhenLayerMovesBetweenReads(t *testing.T) {
742 x := newCarlosFixture(t, "docs")
743 moved := false
744 proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
745 if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/config") && !moved {
746 moved = true
747 x.f.PlatformWrite("docs", "", "DOCS_SMTP_HOST", "smtp.example")
748 }
749 req, _ := http.NewRequestWithContext(r.Context(), r.Method, x.f.URL()+r.URL.RequestURI(), r.Body)
750 req.Header = r.Header.Clone()
751 resp, err := http.DefaultClient.Do(req)
752 if err != nil {
753 w.WriteHeader(502)
754 return
755 }
756 defer resp.Body.Close()
757 w.WriteHeader(resp.StatusCode)
758 _, _ = io.Copy(w, resp.Body)
759 }))
760 t.Cleanup(proxy.Close)
761 c := carlosop.New(proxy.URL, fixtureAccount, x.f.Token())
762 t.Cleanup(c.Close)
763 if _, _, err := Preflight(context.Background(), c, x.h, x.app, nil); err == nil {
764 t.Fatal("a layer that moved between reads passed")
765 }
766 if !moved {
767 t.Fatal("the proxy never saw the layer read")
768 }
769 // The next read is coherent again.
770 if _, codes, err := Preflight(context.Background(), c, x.h, x.app, nil); err != nil || len(codes) != 0 {
771 t.Fatalf("Preflight = %q, %v", codes, err)
772 }
773}
774