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 "crypto/sha256"
6 "encoding/base64"
7 "encoding/hex"
8 "encoding/json"
9 "errors"
10 "slices"
11 "testing"
12 "time"
13
14 "amadan.net/oficina/alta/carlosop"
15 "amadan.net/oficina/alta/provision"
16)
17
18// observerFixture is an app through configure: written, restarted until
19// delivered, its after snapshot captured and its delivery checked, with the
20// pre-plan-a Home preflight recorded and its served release reviewed.
21type observerFixture struct {
22 *writeFixture
23 o *Observer
24 now time.Time
25}
26
27func sha256Hex(s string) string {
28 sum := sha256.Sum256([]byte(s))
29 return hex.EncodeToString(sum[:])
30}
31
32func newObserverFixture(t *testing.T, slug string, before ...func(*writeFixture)) *observerFixture {
33 t.Helper()
34 w := newWriteFixture(t, slug)
35 for _, f := range before {
36 f(w)
37 }
38 w.configured(t)
39 ctx := context.Background()
40 if err := CheckDelivery(ctx, w.s, w.c, w.h, w.app, sha256Hex(w.site.header)); err != nil {
41 t.Fatalf("CheckDelivery: %v", err)
42 }
43 if err := w.s.SaveHomePreflight(ctx, HomePreflight{Phase: PhasePrePlanA, ProposedID: 1, ProposedSQID: fixtureSQID, AttestedAt: at.Add(-time.Hour)}); err != nil {
44 t.Fatal(err)
45 }
46 x := &observerFixture{writeFixture: w, now: at}
47 x.o = &Observer{C: w.c, H: w.h, S: w.s, Artifacts: map[string]string{slug: sha256Hex(w.site.header)}, Now: func() time.Time { return x.now }}
48 return x
49}
50
51func (x *observerFixture) observe() (provision.Observation, error) {
52 return x.o.Observe(context.Background(), x.app.Slug, fixtureSQID)
53}
54
55// refused observes and returns the refusal's codes, failing unless the
56// observation was refused with every code in want.
57func (x *observerFixture) refused(t *testing.T, want ...string) []string {
58 t.Helper()
59 obs, err := x.observe()
60 if err == nil {
61 // The observation is not printed: the binding never is.
62 t.Fatal("observed, want a refusal")
63 }
64 noValues(t, err)
65 var r *Refusal
66 if !errors.As(err, &r) {
67 t.Fatalf("err = %v, want a refusal", err)
68 }
69 if obs != (provision.Observation{}) {
70 t.Fatal("a refusal carried an observation")
71 }
72 for _, c := range want {
73 if !slices.Contains(r.Codes, c) {
74 t.Fatalf("codes = %q, want %q among them", r.Codes, c)
75 }
76 }
77 return r.Codes
78}
79
80// evidence is the journal's records the gate reads; nil is absent.
81type evidence struct {
82 home *HomePreflight
83 base *Snapshot
84 write *WriteRecord
85 after *Snapshot
86 check *DeliveryCheck
87}
88
89// rejournal moves the observer onto a new journal holding the current
90// records as edit leaves them: how an absent or hand-written record is
91// staged, since the journal itself refuses to drop or retake one.
92func (x *observerFixture) rejournal(t *testing.T, edit func(e *evidence)) {
93 t.Helper()
94 ctx := context.Background()
95 var e evidence
96 if r, ok, err := x.s.HomePreflight(ctx, PhasePrePlanA); err != nil {
97 t.Fatal(err)
98 } else if ok {
99 e.home = &r
100 }
101 if r, ok, err := x.s.Baseline(ctx, x.app.Slug); err != nil {
102 t.Fatal(err)
103 } else if ok {
104 e.base = &r
105 }
106 if r, ok, err := x.s.Write(ctx, x.app.Slug); err != nil {
107 t.Fatal(err)
108 } else if ok {
109 e.write = &r
110 }
111 if r, ok, err := x.s.After(ctx, x.app.Slug); err != nil {
112 t.Fatal(err)
113 } else if ok {
114 e.after = &r
115 }
116 if r, ok, err := x.s.DeliveryCheck(ctx, x.app.Slug); err != nil {
117 t.Fatal(err)
118 } else if ok {
119 e.check = &r
120 }
121 edit(&e)
122 s := newJournal(t)
123 must := func(err error) {
124 t.Helper()
125 if err != nil {
126 t.Fatal(err)
127 }
128 }
129 if e.home != nil {
130 must(s.SaveHomePreflight(ctx, *e.home))
131 }
132 if e.base != nil {
133 must(s.SaveBaseline(ctx, x.app.Slug, *e.base))
134 }
135 if e.write != nil {
136 must(s.SaveWrite(ctx, *e.write))
137 }
138 if e.after != nil {
139 must(s.SaveAfter(ctx, x.app.Slug, *e.after))
140 }
141 if e.check != nil {
142 must(s.SaveDeliveryCheck(ctx, *e.check))
143 }
144 x.s, x.o.S = s, s
145}
146
147func TestObserverHappyPathEvidenceTokens(t *testing.T) {
148 x := newObserverFixture(t, "calendar")
149 ctx := context.Background()
150 host := routeOf(x.app)
151 puts, restarts := x.puts(), x.f.RestartCount(host)
152
153 obs, err := x.observe()
154 if err != nil {
155 t.Fatalf("Observe: %v", err)
156 }
157 if obs.AppVersion != valueVersion {
158 t.Fatal("app_version is not the delivered version")
159 }
160 sum := sha256.Sum256([]byte(valueVersion))
161 if obs.ArtifactDigest != base64.RawURLEncoding.EncodeToString(sum[:]) {
162 t.Fatal("artifact_digest is not base64url of the reviewed SHA-256")
163 }
164
165 // The binding is over the journal's evidence and this observation.
166 base, ok1, err1 := x.s.Baseline(ctx, "calendar")
167 after, ok2, err2 := x.s.After(ctx, "calendar")
168 chk, ok3, err3 := x.s.DeliveryCheck(ctx, "calendar")
169 if err := errors.Join(err1, err2, err3); err != nil || !ok1 || !ok2 || !ok3 {
170 t.Fatalf("the journal lacks the evidence: %v", err)
171 }
172 now := x.site.delivery(t, x.carlosFixture)
173 now.At = x.now
174 want := EnvironmentBinding(BindingInput{
175 Before: base.Identity, After: after.Identity,
176 BeforeVars: base.Vars, AfterVars: after.Vars,
177 BeforeLayers: base.Layers, AfterLayers: after.Layers,
178 TeamSQID: fixtureSQID, Issuer: Issuer, ArtifactSHA256: hex.EncodeToString(sum[:]), Version: valueVersion,
179 BeforeDelivery: base.Delivery, AfterDelivery: after.Delivery, NowDelivery: now,
180 Check: chk,
181 })
182 if obs.EnvironmentBinding != want {
183 t.Fatal("environment_binding is not the binding of the journal's evidence and the fresh delivery")
184 }
185
186 // Observing reads; it writes and restarts nothing.
187 if x.puts() != puts || x.f.RestartCount(host) != restarts || x.f.AppWideRestarts() != 0 {
188 t.Fatal("Observe wrote or restarted")
189 }
190}
191
192// The delivery check has no age limit: a later session, days on, with
193// nothing else changed, still passes.
194func TestObserverAcceptsDeliveryCheckFromEarlierSession(t *testing.T) {
195 x := newObserverFixture(t, "calendar")
196 first, err := x.observe()
197 if err != nil {
198 t.Fatalf("Observe: %v", err)
199 }
200 later := time.Now().Add(72 * time.Hour)
201 o := &Observer{C: x.c, H: x.h, S: x.s, Artifacts: x.o.Artifacts, Now: func() time.Time { return later }}
202 obs, err := o.Observe(context.Background(), "calendar", fixtureSQID)
203 if err != nil {
204 t.Fatalf("Observe three days on: %v", err)
205 }
206 if obs.AppVersion != first.AppVersion || obs.ArtifactDigest != first.ArtifactDigest {
207 t.Fatal("the observation's tokens moved with the clock")
208 }
209}
210
211func TestObserverRefusesSupersededDeliveryCheck(t *testing.T) {
212 t.Run("after snapshot retaken", func(t *testing.T) {
213 x := newObserverFixture(t, "calendar")
214 // A platform writer adds a key (reported, not fatal) and the after
215 // snapshot is taken again: the check saw the earlier version.
216 x.f.PlatformWrite("calendar", "", x.app.Prefix+"_PLATFORM_NOTE", "n")
217 if _, err := CaptureAfter(context.Background(), x.c, x.h, x.s, x.app); err != nil {
218 t.Fatalf("CaptureAfter: %v", err)
219 }
220 wantCodes(t, x.refused(t), "delivery-check-superseded")
221 })
222 edits := map[string]func(c *DeliveryCheck){
223 "after version": func(c *DeliveryCheck) { c.AfterVersion = "cv1:" + hex64("9") },
224 "delivered version": func(c *DeliveryCheck) { c.Delivery.Version = "v1.3.9" },
225 "delivered header": func(c *DeliveryCheck) { c.Delivery.Header = "v1.3.9" },
226 }
227 for name, edit := range edits {
228 t.Run(name, func(t *testing.T) {
229 x := newObserverFixture(t, "calendar")
230 x.rejournal(t, func(e *evidence) { edit(e.check) })
231 wantCodes(t, x.refused(t), "delivery-check-superseded")
232 })
233 }
234 t.Run("redeployed", func(t *testing.T) {
235 x := newObserverFixture(t, "calendar")
236 x.site.version, x.site.header = "v1.5.0", "v1.5.0"
237 x.refused(t, "delivery-check-superseded")
238 })
239}
240
241// Each guard refuses with its own code.
242func TestObserverRefusals(t *testing.T) {
243 ctx := context.Background()
244 cases := []struct {
245 name string
246 app string
247 before func(*writeFixture)
248 edit func(t *testing.T, x *observerFixture)
249 want []string
250 exact bool
251 }{
252 {name: "no pre-plan-a preflight", edit: func(t *testing.T, x *observerFixture) {
253 x.rejournal(t, func(e *evidence) { e.home = nil })
254 setupOK(t, x.s.SaveHomePreflight(ctx, HomePreflight{Phase: PhasePreInitialize}))
255 }, want: []string{"missing-home-preflight"}, exact: true},
256 {name: "no baseline", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.base = nil }) },
257 want: []string{"missing-baseline"}, exact: true},
258 {name: "write not landed", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.write.State = "sent" }) },
259 want: []string{"missing-write"}, exact: true},
260 {name: "no after", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.after = nil }) },
261 want: []string{"missing-after"}, exact: true},
262 {name: "no delivery check", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.check = nil }) },
263 want: []string{"missing-delivery-check"}, exact: true},
264 {name: "rollback recorded", edit: func(t *testing.T, x *observerFixture) {
265 setupOK(t, x.s.SaveRollback(ctx, RollbackRecord{App: x.app.Slug, State: "sent"}))
266 }, want: []string{"rollback-recorded"}, exact: true},
267 {name: "canary not active", app: "docs", want: []string{"canary-not-active"}, exact: true},
268 {name: "canary rolled back since", app: "docs", edit: func(t *testing.T, x *observerFixture) {
269 canaryActive(t, x.s)
270 setupOK(t, x.s.SaveRollback(ctx, RollbackRecord{App: CanaryApp, State: "restarted"}))
271 }, want: []string{"canary-not-active"}, exact: true},
272 {name: "artifact not reviewed", edit: func(t *testing.T, x *observerFixture) { x.o.Artifacts = nil },
273 want: []string{"artifact-unreviewed"}, exact: true},
274 {name: "artifact not lowercase hex", edit: func(t *testing.T, x *observerFixture) {
275 x.o.Artifacts = map[string]string{"calendar": "AB" + sha256Hex(valueVersion)[2:]}
276 }, want: []string{"artifact-unreviewed"}, exact: true},
277 {name: "artifact differs", edit: func(t *testing.T, x *observerFixture) {
278 x.o.Artifacts = map[string]string{"calendar": hex64("0")}
279 }, want: []string{"artifact-mismatch"}, exact: true},
280 {name: "another team", edit: func(t *testing.T, x *observerFixture) {
281 x.rejournal(t, func(e *evidence) { e.write.Sent[AgentKeys(x.app)[1]] = "otherTeam" })
282 }, want: []string{"team-mismatch"}, exact: true},
283 {name: "another issuer", edit: func(t *testing.T, x *observerFixture) {
284 x.rejournal(t, func(e *evidence) { e.write.Sent[AgentKeys(x.app)[0]] = "https://elsewhere.example" })
285 }, want: []string{"issuer-mismatch"}, exact: true},
286 {name: "identity changed", edit: func(t *testing.T, x *observerFixture) {
287 x.f.AddInstance(carlosop.Instance{Host: routeOf(x.app), App: "calendar", Slug: "s-calendar", Channel: "stable", Region: "us",
288 CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4, ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`)})
289 }, want: []string{"identity-region"}},
290 {name: "baseline identity differs", edit: func(t *testing.T, x *observerFixture) {
291 x.rejournal(t, func(e *evidence) { e.base.Identity.Region = "us" })
292 }, want: []string{"after-not-preserved", "drift-region", "identity-region"}, exact: true},
293 {name: "after identity differs", edit: func(t *testing.T, x *observerFixture) {
294 x.rejournal(t, func(e *evidence) { e.after.Identity.Region = "us" })
295 }, want: []string{"after-not-preserved", "identity-region"}, exact: true},
296 {name: "delivery check identity differs", edit: func(t *testing.T, x *observerFixture) {
297 x.rejournal(t, func(e *evidence) { e.check.Identity.Channel = "beta" })
298 }, want: []string{"identity-channel"}, exact: true},
299 {name: "after not preserved", edit: func(t *testing.T, x *observerFixture) {
300 // A hand-written after row in which a preserved secret was
301 // resealed: CaptureAfter would have refused it.
302 x.rejournal(t, func(e *evidence) {
303 for i, v := range e.after.Vars {
304 if v.Key == "CALENDAR_INSTANCE_KEY" {
305 e.after.Vars = withDigest(e.after.Vars, i, "vd1:"+hex64("7"))
306 }
307 }
308 })
309 }, want: []string{"after-not-preserved"}},
310 {name: "secret resealed since", edit: func(t *testing.T, x *observerFixture) {
311 x.f.SetSecret("calendar", "", "CALENDAR_INSTANCE_KEY")
312 }, want: []string{"drift-changed:CALENDAR_INSTANCE_KEY"}},
313 {name: "plain value changed since", edit: func(t *testing.T, x *observerFixture) {
314 x.f.SetVar("calendar", "", "CALENDAR_ORIGIN", "https://calendar.oficina.works/another-plain-value")
315 }, want: []string{"drift-changed:CALENDAR_ORIGIN"}},
316 {name: "config moved since", edit: func(t *testing.T, x *observerFixture) {
317 x.f.PlatformWrite("calendar", "", "CALENDAR_PLATFORM_NOTE", "n")
318 }, want: []string{"config-added:CALENDAR_PLATFORM_NOTE"}},
319 {name: "team-mode key", edit: func(t *testing.T, x *observerFixture) {
320 x.f.SetVar("calendar", "", "CALENDAR_TEAM_ROSTER", "x")
321 }, want: []string{"team-mode-CALENDAR_TEAM_ROSTER"}},
322 {name: "agent key with another digest", edit: func(t *testing.T, x *observerFixture) {
323 x.f.SetVar("calendar", "", "CALENDAR_AGENT_TEAM", "otherTeam")
324 }, want: []string{"agent-key-CALENDAR_AGENT_TEAM"}},
325 {name: "overlay shadows an agent key", edit: func(t *testing.T, x *observerFixture) {
326 // The same value, so the same digest: only its source differs.
327 x.f.SetOverlay("calendar", routeOf(x.app), "CALENDAR_AGENT_ISSUER", Issuer)
328 }, want: []string{"agent-key-CALENDAR_AGENT_ISSUER"}},
329 {name: "unhealthy", edit: func(t *testing.T, x *observerFixture) { x.site.health = 503 },
330 want: []string{"not-delivered"}, exact: true},
331 {name: "operations reverted", edit: func(t *testing.T, x *observerFixture) { x.site.ops = nil },
332 want: []string{"not-delivered"}, exact: true},
333 {name: "version malformed", before: func(w *writeFixture) { w.site.version, w.site.header = "-v1", "-v1" },
334 want: []string{"version-unacceptable"}, exact: true},
335 {name: "version body and header differ", edit: func(t *testing.T, x *observerFixture) {
336 x.site.header = "rel-2026"
337 x.o.Artifacts = map[string]string{"calendar": sha256Hex("rel-2026")}
338 x.rejournal(t, func(e *evidence) {
339 e.base.Delivery.Header, e.after.Delivery.Header, e.check.Delivery.Header = "rel-2026", "rel-2026", "rel-2026"
340 })
341 }, want: []string{"version-header-mismatch"}, exact: true},
342 }
343 for _, tc := range cases {
344 t.Run(tc.name, func(t *testing.T) {
345 app := tc.app
346 if app == "" {
347 app = "calendar"
348 }
349 var before []func(*writeFixture)
350 if tc.before != nil {
351 before = append(before, tc.before)
352 }
353 x := newObserverFixture(t, app, before...)
354 if tc.edit != nil {
355 tc.edit(t, x)
356 }
357 codes := x.refused(t, tc.want...)
358 if tc.exact {
359 wantCodes(t, codes, tc.want...)
360 }
361 })
362 }
363}
364
365func TestObserverRefusesUnknownAppAndBadTeam(t *testing.T) {
366 x := newObserverFixture(t, "calendar")
367 codes := func(app, team string) []string {
368 var r *Refusal
369 if _, err := x.o.Observe(context.Background(), app, team); !errors.As(err, &r) {
370 t.Fatalf("%s/%s: err = %v, want a refusal", app, team, err)
371 }
372 return r.Codes
373 }
374 wantCodes(t, codes("nope", fixtureSQID), "unknown-app")
375 wantCodes(t, codes("calendar", "not a sqid"), "team-not-sqid")
376 for _, o := range []*Observer{nil, {}, {C: x.c, H: x.h}, {C: x.c, S: x.s}, {H: x.h, S: x.s}} {
377 if _, err := o.Observe(context.Background(), "calendar", fixtureSQID); err == nil {
378 t.Fatal("an Observer without a console, a client or the journal observed")
379 }
380 }
381}
382
383// Plan C needs Plan B alone: with the canary active, a non-canary app
384// passes, with no live check recorded.
385func TestObserverPassesNonCanaryOnceCanaryActive(t *testing.T) {
386 x := newObserverFixture(t, "docs")
387 canaryActive(t, x.s)
388 if _, err := x.observe(); err != nil {
389 t.Fatalf("Observe: %v", err)
390 }
391}
392
393// canaryActive records Plan B's activation of the canary in s's engine
394// steps, as the engine does when Home has activated it.
395func canaryActive(t *testing.T, s *Store) {
396 t.Helper()
397 setupOK(t, s.ps.SetStep(context.Background(), provision.AdoptionLabel, CanaryApp, provision.StepActivate, "done", "", nil))
398}
399
400// setupOK fails the test on a setup write that did not succeed, so a case
401// never passes without the state it means to stage.
402func setupOK(t *testing.T, err error) {
403 t.Helper()
404 if err != nil {
405 t.Fatalf("setup: %v", err)
406 }
407}
408
409// provision's engine parks an activation with the gate's own codes: it
410// reads them through provision.ObserverRefusal, as a copy.
411func TestObserverRefusalReachesTheEngine(t *testing.T) {
412 err := error(refuse("delivery-check-superseded", "missing-delivery-check"))
413 var r provision.ObserverRefusal
414 if !errors.As(err, &r) {
415 t.Fatal("a refusal is not a provision.ObserverRefusal")
416 }
417 codes := r.RefusalCodes()
418 if !slices.Equal(codes, []string{"delivery-check-superseded", "missing-delivery-check"}) {
419 t.Fatalf("codes %v", codes)
420 }
421 codes[0] = "edited"
422 if r.RefusalCodes()[0] != "delivery-check-superseded" {
423 t.Fatal("the engine can edit the refusal's codes")
424 }
425}
426