package adopt import ( "context" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "slices" "testing" "time" "amadan.net/oficina/alta/carlosop" "amadan.net/oficina/alta/provision" ) // observerFixture is an app through configure: written, restarted until // delivered, its after snapshot captured and its delivery checked, with the // pre-plan-a Home preflight recorded and its served release reviewed. type observerFixture struct { *writeFixture o *Observer now time.Time } func sha256Hex(s string) string { sum := sha256.Sum256([]byte(s)) return hex.EncodeToString(sum[:]) } func newObserverFixture(t *testing.T, slug string, before ...func(*writeFixture)) *observerFixture { t.Helper() w := newWriteFixture(t, slug) for _, f := range before { f(w) } w.configured(t) ctx := context.Background() if err := CheckDelivery(ctx, w.s, w.c, w.h, w.app, sha256Hex(w.site.header)); err != nil { t.Fatalf("CheckDelivery: %v", err) } if err := w.s.SaveHomePreflight(ctx, HomePreflight{Phase: PhasePrePlanA, ProposedID: 1, ProposedSQID: fixtureSQID, AttestedAt: at.Add(-time.Hour)}); err != nil { t.Fatal(err) } x := &observerFixture{writeFixture: w, now: at} 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 }} return x } func (x *observerFixture) observe() (provision.Observation, error) { return x.o.Observe(context.Background(), x.app.Slug, fixtureSQID) } // refused observes and returns the refusal's codes, failing unless the // observation was refused with every code in want. func (x *observerFixture) refused(t *testing.T, want ...string) []string { t.Helper() obs, err := x.observe() if err == nil { // The observation is not printed: the binding never is. t.Fatal("observed, want a refusal") } noValues(t, err) var r *Refusal if !errors.As(err, &r) { t.Fatalf("err = %v, want a refusal", err) } if obs != (provision.Observation{}) { t.Fatal("a refusal carried an observation") } for _, c := range want { if !slices.Contains(r.Codes, c) { t.Fatalf("codes = %q, want %q among them", r.Codes, c) } } return r.Codes } // evidence is the journal's records the gate reads; nil is absent. type evidence struct { home *HomePreflight base *Snapshot write *WriteRecord after *Snapshot check *DeliveryCheck } // rejournal moves the observer onto a new journal holding the current // records as edit leaves them: how an absent or hand-written record is // staged, since the journal itself refuses to drop or retake one. func (x *observerFixture) rejournal(t *testing.T, edit func(e *evidence)) { t.Helper() ctx := context.Background() var e evidence if r, ok, err := x.s.HomePreflight(ctx, PhasePrePlanA); err != nil { t.Fatal(err) } else if ok { e.home = &r } if r, ok, err := x.s.Baseline(ctx, x.app.Slug); err != nil { t.Fatal(err) } else if ok { e.base = &r } if r, ok, err := x.s.Write(ctx, x.app.Slug); err != nil { t.Fatal(err) } else if ok { e.write = &r } if r, ok, err := x.s.After(ctx, x.app.Slug); err != nil { t.Fatal(err) } else if ok { e.after = &r } if r, ok, err := x.s.DeliveryCheck(ctx, x.app.Slug); err != nil { t.Fatal(err) } else if ok { e.check = &r } edit(&e) s := newJournal(t) must := func(err error) { t.Helper() if err != nil { t.Fatal(err) } } if e.home != nil { must(s.SaveHomePreflight(ctx, *e.home)) } if e.base != nil { must(s.SaveBaseline(ctx, x.app.Slug, *e.base)) } if e.write != nil { must(s.SaveWrite(ctx, *e.write)) } if e.after != nil { must(s.SaveAfter(ctx, x.app.Slug, *e.after)) } if e.check != nil { must(s.SaveDeliveryCheck(ctx, *e.check)) } x.s, x.o.S = s, s } func TestObserverHappyPathEvidenceTokens(t *testing.T) { x := newObserverFixture(t, "calendar") ctx := context.Background() host := routeOf(x.app) puts, restarts := x.puts(), x.f.RestartCount(host) obs, err := x.observe() if err != nil { t.Fatalf("Observe: %v", err) } if obs.AppVersion != valueVersion { t.Fatal("app_version is not the delivered version") } sum := sha256.Sum256([]byte(valueVersion)) if obs.ArtifactDigest != base64.RawURLEncoding.EncodeToString(sum[:]) { t.Fatal("artifact_digest is not base64url of the reviewed SHA-256") } // The binding is over the journal's evidence and this observation. base, ok1, err1 := x.s.Baseline(ctx, "calendar") after, ok2, err2 := x.s.After(ctx, "calendar") chk, ok3, err3 := x.s.DeliveryCheck(ctx, "calendar") if err := errors.Join(err1, err2, err3); err != nil || !ok1 || !ok2 || !ok3 { t.Fatalf("the journal lacks the evidence: %v", err) } now := x.site.delivery(t, x.carlosFixture) now.At = x.now want := EnvironmentBinding(BindingInput{ Before: base.Identity, After: after.Identity, BeforeVars: base.Vars, AfterVars: after.Vars, BeforeLayers: base.Layers, AfterLayers: after.Layers, TeamSQID: fixtureSQID, Issuer: Issuer, ArtifactSHA256: hex.EncodeToString(sum[:]), Version: valueVersion, BeforeDelivery: base.Delivery, AfterDelivery: after.Delivery, NowDelivery: now, Check: chk, }) if obs.EnvironmentBinding != want { t.Fatal("environment_binding is not the binding of the journal's evidence and the fresh delivery") } // Observing reads; it writes and restarts nothing. if x.puts() != puts || x.f.RestartCount(host) != restarts || x.f.AppWideRestarts() != 0 { t.Fatal("Observe wrote or restarted") } } // The delivery check has no age limit: a later session, days on, with // nothing else changed, still passes. func TestObserverAcceptsDeliveryCheckFromEarlierSession(t *testing.T) { x := newObserverFixture(t, "calendar") first, err := x.observe() if err != nil { t.Fatalf("Observe: %v", err) } later := time.Now().Add(72 * time.Hour) o := &Observer{C: x.c, H: x.h, S: x.s, Artifacts: x.o.Artifacts, Now: func() time.Time { return later }} obs, err := o.Observe(context.Background(), "calendar", fixtureSQID) if err != nil { t.Fatalf("Observe three days on: %v", err) } if obs.AppVersion != first.AppVersion || obs.ArtifactDigest != first.ArtifactDigest { t.Fatal("the observation's tokens moved with the clock") } } func TestObserverRefusesSupersededDeliveryCheck(t *testing.T) { t.Run("after snapshot retaken", func(t *testing.T) { x := newObserverFixture(t, "calendar") // A platform writer adds a key (reported, not fatal) and the after // snapshot is taken again: the check saw the earlier version. x.f.PlatformWrite("calendar", "", x.app.Prefix+"_PLATFORM_NOTE", "n") if _, err := CaptureAfter(context.Background(), x.c, x.h, x.s, x.app); err != nil { t.Fatalf("CaptureAfter: %v", err) } wantCodes(t, x.refused(t), "delivery-check-superseded") }) edits := map[string]func(c *DeliveryCheck){ "after version": func(c *DeliveryCheck) { c.AfterVersion = "cv1:" + hex64("9") }, "delivered version": func(c *DeliveryCheck) { c.Delivery.Version = "v1.3.9" }, "delivered header": func(c *DeliveryCheck) { c.Delivery.Header = "v1.3.9" }, } for name, edit := range edits { t.Run(name, func(t *testing.T) { x := newObserverFixture(t, "calendar") x.rejournal(t, func(e *evidence) { edit(e.check) }) wantCodes(t, x.refused(t), "delivery-check-superseded") }) } t.Run("redeployed", func(t *testing.T) { x := newObserverFixture(t, "calendar") x.site.version, x.site.header = "v1.5.0", "v1.5.0" x.refused(t, "delivery-check-superseded") }) } // Each guard refuses with its own code. func TestObserverRefusals(t *testing.T) { ctx := context.Background() cases := []struct { name string app string before func(*writeFixture) edit func(t *testing.T, x *observerFixture) want []string exact bool }{ {name: "no pre-plan-a preflight", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.home = nil }) setupOK(t, x.s.SaveHomePreflight(ctx, HomePreflight{Phase: PhasePreInitialize})) }, want: []string{"missing-home-preflight"}, exact: true}, {name: "no baseline", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.base = nil }) }, want: []string{"missing-baseline"}, exact: true}, {name: "write not landed", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.write.State = "sent" }) }, want: []string{"missing-write"}, exact: true}, {name: "no after", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.after = nil }) }, want: []string{"missing-after"}, exact: true}, {name: "no delivery check", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.check = nil }) }, want: []string{"missing-delivery-check"}, exact: true}, {name: "rollback recorded", edit: func(t *testing.T, x *observerFixture) { setupOK(t, x.s.SaveRollback(ctx, RollbackRecord{App: x.app.Slug, State: "sent"})) }, want: []string{"rollback-recorded"}, exact: true}, {name: "canary not active", app: "docs", want: []string{"canary-not-active"}, exact: true}, {name: "canary rolled back since", app: "docs", edit: func(t *testing.T, x *observerFixture) { canaryActive(t, x.s) setupOK(t, x.s.SaveRollback(ctx, RollbackRecord{App: CanaryApp, State: "restarted"})) }, want: []string{"canary-not-active"}, exact: true}, {name: "artifact not reviewed", edit: func(t *testing.T, x *observerFixture) { x.o.Artifacts = nil }, want: []string{"artifact-unreviewed"}, exact: true}, {name: "artifact not lowercase hex", edit: func(t *testing.T, x *observerFixture) { x.o.Artifacts = map[string]string{"calendar": "AB" + sha256Hex(valueVersion)[2:]} }, want: []string{"artifact-unreviewed"}, exact: true}, {name: "artifact differs", edit: func(t *testing.T, x *observerFixture) { x.o.Artifacts = map[string]string{"calendar": hex64("0")} }, want: []string{"artifact-mismatch"}, exact: true}, {name: "another team", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.write.Sent[AgentKeys(x.app)[1]] = "otherTeam" }) }, want: []string{"team-mismatch"}, exact: true}, {name: "another issuer", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.write.Sent[AgentKeys(x.app)[0]] = "https://elsewhere.example" }) }, want: []string{"issuer-mismatch"}, exact: true}, {name: "identity changed", edit: func(t *testing.T, x *observerFixture) { x.f.AddInstance(carlosop.Instance{Host: routeOf(x.app), App: "calendar", Slug: "s-calendar", Channel: "stable", Region: "us", CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4, ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`)}) }, want: []string{"identity-region"}}, {name: "baseline identity differs", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.base.Identity.Region = "us" }) }, want: []string{"after-not-preserved", "drift-region", "identity-region"}, exact: true}, {name: "after identity differs", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.after.Identity.Region = "us" }) }, want: []string{"after-not-preserved", "identity-region"}, exact: true}, {name: "delivery check identity differs", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.check.Identity.Channel = "beta" }) }, want: []string{"identity-channel"}, exact: true}, {name: "after not preserved", edit: func(t *testing.T, x *observerFixture) { // A hand-written after row in which a preserved secret was // resealed: CaptureAfter would have refused it. x.rejournal(t, func(e *evidence) { for i, v := range e.after.Vars { if v.Key == "CALENDAR_INSTANCE_KEY" { e.after.Vars = withDigest(e.after.Vars, i, "vd1:"+hex64("7")) } } }) }, want: []string{"after-not-preserved"}}, {name: "secret resealed since", edit: func(t *testing.T, x *observerFixture) { x.f.SetSecret("calendar", "", "CALENDAR_INSTANCE_KEY") }, want: []string{"drift-changed:CALENDAR_INSTANCE_KEY"}}, {name: "plain value changed since", edit: func(t *testing.T, x *observerFixture) { x.f.SetVar("calendar", "", "CALENDAR_ORIGIN", "https://calendar.oficina.works/another-plain-value") }, want: []string{"drift-changed:CALENDAR_ORIGIN"}}, {name: "config moved since", edit: func(t *testing.T, x *observerFixture) { x.f.PlatformWrite("calendar", "", "CALENDAR_PLATFORM_NOTE", "n") }, want: []string{"config-added:CALENDAR_PLATFORM_NOTE"}}, {name: "team-mode key", edit: func(t *testing.T, x *observerFixture) { x.f.SetVar("calendar", "", "CALENDAR_TEAM_ROSTER", "x") }, want: []string{"team-mode-CALENDAR_TEAM_ROSTER"}}, {name: "agent key with another digest", edit: func(t *testing.T, x *observerFixture) { x.f.SetVar("calendar", "", "CALENDAR_AGENT_TEAM", "otherTeam") }, want: []string{"agent-key-CALENDAR_AGENT_TEAM"}}, {name: "overlay shadows an agent key", edit: func(t *testing.T, x *observerFixture) { // The same value, so the same digest: only its source differs. x.f.SetOverlay("calendar", routeOf(x.app), "CALENDAR_AGENT_ISSUER", Issuer) }, want: []string{"agent-key-CALENDAR_AGENT_ISSUER"}}, {name: "unhealthy", edit: func(t *testing.T, x *observerFixture) { x.site.health = 503 }, want: []string{"not-delivered"}, exact: true}, {name: "operations reverted", edit: func(t *testing.T, x *observerFixture) { x.site.ops = nil }, want: []string{"not-delivered"}, exact: true}, {name: "version malformed", before: func(w *writeFixture) { w.site.version, w.site.header = "-v1", "-v1" }, want: []string{"version-unacceptable"}, exact: true}, {name: "version body and header differ", edit: func(t *testing.T, x *observerFixture) { x.site.header = "rel-2026" x.o.Artifacts = map[string]string{"calendar": sha256Hex("rel-2026")} x.rejournal(t, func(e *evidence) { e.base.Delivery.Header, e.after.Delivery.Header, e.check.Delivery.Header = "rel-2026", "rel-2026", "rel-2026" }) }, want: []string{"version-header-mismatch"}, exact: true}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { app := tc.app if app == "" { app = "calendar" } var before []func(*writeFixture) if tc.before != nil { before = append(before, tc.before) } x := newObserverFixture(t, app, before...) if tc.edit != nil { tc.edit(t, x) } codes := x.refused(t, tc.want...) if tc.exact { wantCodes(t, codes, tc.want...) } }) } } func TestObserverRefusesUnknownAppAndBadTeam(t *testing.T) { x := newObserverFixture(t, "calendar") codes := func(app, team string) []string { var r *Refusal if _, err := x.o.Observe(context.Background(), app, team); !errors.As(err, &r) { t.Fatalf("%s/%s: err = %v, want a refusal", app, team, err) } return r.Codes } wantCodes(t, codes("nope", fixtureSQID), "unknown-app") wantCodes(t, codes("calendar", "not a sqid"), "team-not-sqid") for _, o := range []*Observer{nil, {}, {C: x.c, H: x.h}, {C: x.c, S: x.s}, {H: x.h, S: x.s}} { if _, err := o.Observe(context.Background(), "calendar", fixtureSQID); err == nil { t.Fatal("an Observer without a console, a client or the journal observed") } } } // Plan C needs Plan B alone: with the canary active, a non-canary app // passes, with no live check recorded. func TestObserverPassesNonCanaryOnceCanaryActive(t *testing.T) { x := newObserverFixture(t, "docs") canaryActive(t, x.s) if _, err := x.observe(); err != nil { t.Fatalf("Observe: %v", err) } } // canaryActive records Plan B's activation of the canary in s's engine // steps, as the engine does when Home has activated it. func canaryActive(t *testing.T, s *Store) { t.Helper() setupOK(t, s.ps.SetStep(context.Background(), provision.AdoptionLabel, CanaryApp, provision.StepActivate, "done", "", nil)) } // setupOK fails the test on a setup write that did not succeed, so a case // never passes without the state it means to stage. func setupOK(t *testing.T, err error) { t.Helper() if err != nil { t.Fatalf("setup: %v", err) } } // provision's engine parks an activation with the gate's own codes: it // reads them through provision.ObserverRefusal, as a copy. func TestObserverRefusalReachesTheEngine(t *testing.T) { err := error(refuse("delivery-check-superseded", "missing-delivery-check")) var r provision.ObserverRefusal if !errors.As(err, &r) { t.Fatal("a refusal is not a provision.ObserverRefusal") } codes := r.RefusalCodes() if !slices.Equal(codes, []string{"delivery-check-superseded", "missing-delivery-check"}) { t.Fatalf("codes %v", codes) } codes[0] = "edited" if r.RefusalCodes()[0] != "delivery-check-superseded" { t.Fatal("the engine can edit the refusal's codes") } }