| 1 | package adopt |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "log/slog" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "path/filepath" |
| 12 | "slices" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/oficina/alta/carlosop" |
| 18 | "amadan.net/oficina/alta/console" |
| 19 | "amadan.net/oficina/alta/homeop" |
| 20 | "amadan.net/oficina/alta/homeop/fakehome" |
| 21 | "amadan.net/oficina/alta/provision" |
| 22 | family "amadan.net/rastrillo/rastrillo/crypto" |
| 23 | ) |
| 24 | |
| 25 | // The adverse suite drives the whole activation gate: the real Observer, |
| 26 | // reading the fake console and the fake app, inside Alta's real engine, |
| 27 | // talking to the in-memory Home. Every case ends where it matters: the |
| 28 | // run is parked with the gate's own code, and Home never saw a |
| 29 | // directory.activate-consumer for any app. |
| 30 | |
| 31 | const gateOwner = "owner@adverse.test" |
| 32 | |
| 33 | // gate is an initialized Home with Plan A done for the six canonical apps. |
| 34 | // js is the adoption journal over the engine's own store, as alta-adopt |
| 35 | // opens it: Plan C's gate reads the engine's steps through it. |
| 36 | type gate struct { |
| 37 | t *testing.T |
| 38 | now time.Time |
| 39 | home *fakehome.Home |
| 40 | store *provision.Store |
| 41 | js *Store |
| 42 | cfg provision.Config |
| 43 | team string |
| 44 | } |
| 45 | |
| 46 | func (g *gate) clock() time.Time { return g.now } |
| 47 | |
| 48 | func (g *gate) tick(d time.Duration) { g.now = g.now.Add(d) } |
| 49 | |
| 50 | func (g *gate) confirm(kind string) { |
| 51 | g.t.Helper() |
| 52 | if err := g.home.Confirm(homeop.Directory, ""); err != nil { |
| 53 | g.t.Fatal(err) |
| 54 | } |
| 55 | if kind == homeop.KindInitialize { |
| 56 | return |
| 57 | } |
| 58 | owner := "" |
| 59 | if kind == homeop.KindCreateTeam { |
| 60 | owner = gateOwner |
| 61 | } |
| 62 | if err := g.home.Confirm(homeop.Credential, owner); err != nil { |
| 63 | g.t.Fatal(err) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // drive advances run until it is done, failed or has stood still for |
| 68 | // rounds passes. |
| 69 | func (g *gate) drive(e *provision.Engine, run int64, rounds int) provision.Run { |
| 70 | g.t.Helper() |
| 71 | var r provision.Run |
| 72 | for i := 0; i < rounds; i++ { |
| 73 | if err := e.Advance(context.Background(), run); err != nil { |
| 74 | var fl *provision.Fail |
| 75 | if !errors.As(err, &fl) { |
| 76 | g.t.Fatalf("advance: %v", err) |
| 77 | } |
| 78 | } |
| 79 | var err error |
| 80 | if r, err = g.store.Run(context.Background(), run); err != nil { |
| 81 | g.t.Fatal(err) |
| 82 | } |
| 83 | if r.State == "done" || r.State == "failed" { |
| 84 | return r |
| 85 | } |
| 86 | g.tick(5 * time.Second) |
| 87 | } |
| 88 | return r |
| 89 | } |
| 90 | |
| 91 | type offlineNet struct{} |
| 92 | |
| 93 | func (offlineNet) RoundTrip(*http.Request) (*http.Response, error) { |
| 94 | return nil, errors.New("offline: an adoption made a network call") |
| 95 | } |
| 96 | |
| 97 | func (g *gate) engine(obs provision.Observer) *provision.Engine { |
| 98 | cfg := g.cfg |
| 99 | cfg.Observer = obs |
| 100 | return provision.New(cfg) |
| 101 | } |
| 102 | |
| 103 | func newGate(t *testing.T) *gate { |
| 104 | t.Helper() |
| 105 | g := &gate{t: t, now: time.Unix(2_000_000_000, 0)} |
| 106 | key, err := family.Generate() |
| 107 | if err != nil { |
| 108 | t.Fatal(err) |
| 109 | } |
| 110 | pre := homeop.Token() |
| 111 | const credOrigin, dirOrigin = "https://id.oficina.works", "https://oficina.works" |
| 112 | g.home = fakehome.New(key.SignPub(), pre, credOrigin, dirOrigin, g.clock) |
| 113 | g.home.AddPerson(gateOwner) |
| 114 | roles := map[string]homeop.Role{} |
| 115 | for r, origin := range map[string]string{homeop.Credential: credOrigin, homeop.Directory: dirOrigin} { |
| 116 | srv := httptest.NewServer(g.home.Handler(r)) |
| 117 | t.Cleanup(srv.Close) |
| 118 | p := g.home.Pins(r) |
| 119 | roles[r] = homeop.Role{Name: r, Origin: origin, URL: srv.URL, Installation: p.Installation, Registry: p.Registry, Device: p.Device} |
| 120 | } |
| 121 | db, err := provision.OpenDB(filepath.Join(t.TempDir(), "alta.db")) |
| 122 | if err != nil { |
| 123 | t.Fatal(err) |
| 124 | } |
| 125 | t.Cleanup(func() { db.Close() }) |
| 126 | g.store, err = provision.NewStore(context.Background(), db, bytes.Repeat([]byte{4}, 32), g.clock, Schema) |
| 127 | if err != nil { |
| 128 | t.Fatal(err) |
| 129 | } |
| 130 | if g.js, err = NewStore(g.store); err != nil { |
| 131 | t.Fatal(err) |
| 132 | } |
| 133 | net := &http.Client{Transport: offlineNet{}} |
| 134 | g.cfg = provision.Config{ |
| 135 | Store: g.store, Home: &homeop.Client{Key: key, Prefilter: pre, Roles: roles, Now: g.clock}, |
| 136 | Console: &console.Client{HTTP: net, Base: "https://console.invalid", Account: fixtureAccount, Tokens: map[string]string{}}, |
| 137 | Public: net, |
| 138 | HomeCfg: provision.HomeConfig{Issuer: credOrigin, Directory: dirOrigin, KeysBase64: "eyJrMSI6IkJBPT0ifQ==", Provisioner: g.home.ProvisioningPublic()}, |
| 139 | Account: fixtureAccount, Now: g.clock, Logger: slog.New(slog.NewTextHandler(&bytes.Buffer{}, nil)), |
| 140 | Debug: func(err error) { t.Logf("transient: %v", err) }, |
| 141 | } |
| 142 | |
| 143 | ctx := context.Background() |
| 144 | e := g.engine(nil) |
| 145 | run, err := e.StartInitialize(ctx, provision.InitializeAttestation) |
| 146 | if err != nil { |
| 147 | t.Fatal(err) |
| 148 | } |
| 149 | g.confirm(homeop.KindInitialize) |
| 150 | if r := g.drive(e, run, 3); r.State != "done" { |
| 151 | t.Fatalf("initialize: %s %s", r.State, r.Code) |
| 152 | } |
| 153 | g.tick(homeop.WindowLifetime * time.Second) |
| 154 | for _, a := range provision.Slugs() { |
| 155 | g.home.AddEnvConsumer(a, homeop.CanonicalOrigin(a)) |
| 156 | } |
| 157 | if run, err = e.StartAdoption(ctx, "Oficina", gateOwner); err != nil { |
| 158 | t.Fatal(err) |
| 159 | } |
| 160 | g.confirm(homeop.KindCreateTeam) |
| 161 | if r := g.drive(e, run, 20); r.State != "done" || r.Code != "awaiting-configuration" { |
| 162 | t.Fatalf("plan A: %s %s", r.State, r.Code) |
| 163 | } |
| 164 | team, err := g.store.Team(ctx, provision.AdoptionLabel) |
| 165 | if err != nil || team.TeamSQID == "" { |
| 166 | t.Fatalf("no seeded team: %v", err) |
| 167 | } |
| 168 | g.team = team.TeamSQID |
| 169 | return g |
| 170 | } |
| 171 | |
| 172 | // noActivation fails unless Home has never been asked to activate any |
| 173 | // consumer. |
| 174 | func (g *gate) noActivation() { |
| 175 | g.t.Helper() |
| 176 | for _, r := range g.home.Requests() { |
| 177 | if strings.HasPrefix(r, homeop.DirectoryActivate) { |
| 178 | g.t.Fatalf("Home committed %s", r) |
| 179 | } |
| 180 | } |
| 181 | if g.home.Calls[homeop.DirectoryActivate] != 0 { |
| 182 | g.t.Fatal("Home was sent an activation") |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | // attempt is the add-apps run for app with obs: confirmed and driven. |
| 187 | func (g *gate) attempt(app string, obs provision.Observer) provision.Run { |
| 188 | g.t.Helper() |
| 189 | e := g.engine(obs) |
| 190 | g.tick(homeop.WindowLifetime * time.Second) |
| 191 | run, err := e.ActivateAdopted(context.Background(), []string{app}) |
| 192 | if err != nil { |
| 193 | g.t.Fatalf("ActivateAdopted: %v", err) |
| 194 | } |
| 195 | g.confirm(homeop.KindAddApps) |
| 196 | return g.drive(e, run, 3) |
| 197 | } |
| 198 | |
| 199 | // refused is attempt that must end parked with each of want among the |
| 200 | // gate's codes, and with Home never asked to activate. |
| 201 | func (g *gate) refused(app string, obs provision.Observer, want ...string) []string { |
| 202 | g.t.Helper() |
| 203 | r := g.attempt(app, obs) |
| 204 | g.noActivation() |
| 205 | if r.State != "parked" || !strings.HasPrefix(r.Code, "observe-") { |
| 206 | g.t.Fatalf("run %s %q, want parked by the gate", r.State, r.Code) |
| 207 | } |
| 208 | codes := strings.Split(strings.TrimPrefix(r.Code, "observe-"), ",") |
| 209 | for _, c := range want { |
| 210 | if !slices.Contains(codes, c) { |
| 211 | g.t.Fatalf("codes = %q, want %q among them", codes, c) |
| 212 | } |
| 213 | } |
| 214 | return codes |
| 215 | } |
| 216 | |
| 217 | // gateFixture is an app through configure, as newObserverFixture builds |
| 218 | // it, but for the team Home seeded and on the gate's own journal. |
| 219 | func (g *gate) fixture(slug string, before ...func(*writeFixture)) *observerFixture { |
| 220 | g.t.Helper() |
| 221 | t := g.t |
| 222 | w := newWriteFixture(t, slug) |
| 223 | w.s = g.js |
| 224 | for _, f := range before { |
| 225 | f(w) |
| 226 | } |
| 227 | fastPolls(t, 5*time.Millisecond, 2*time.Second) |
| 228 | w.process(false) |
| 229 | ctx := context.Background() |
| 230 | if _, err := WriteAgentKeys(ctx, w.c, w.h, w.s, w.app, g.team, sha256Hex(w.site.header), true); err != nil { |
| 231 | t.Fatalf("WriteAgentKeys: %v", err) |
| 232 | } |
| 233 | g.finish(w) |
| 234 | return g.observer(w) |
| 235 | } |
| 236 | |
| 237 | // finish restarts until delivered, captures the after snapshot and |
| 238 | // records the delivery check and the pre-plan-a preflight. |
| 239 | func (g *gate) finish(w *writeFixture) { |
| 240 | g.t.Helper() |
| 241 | ctx := context.Background() |
| 242 | base := w.baseline(g.t) |
| 243 | if _, err := RestartAndWait(ctx, w.c, w.h, w.app, base.Identity, func(d Delivery) error { return Delivered(w.app, base.Delivery, d) }, true); err != nil { |
| 244 | g.t.Fatalf("RestartAndWait: %v", err) |
| 245 | } |
| 246 | if _, err := CaptureAfter(ctx, w.c, w.h, w.s, w.app); err != nil { |
| 247 | g.t.Fatalf("CaptureAfter: %v", err) |
| 248 | } |
| 249 | if err := CheckDelivery(ctx, w.s, w.c, w.h, w.app, sha256Hex(w.site.header)); err != nil { |
| 250 | g.t.Fatalf("CheckDelivery: %v", err) |
| 251 | } |
| 252 | if err := w.s.SaveHomePreflight(ctx, HomePreflight{Phase: PhasePrePlanA, ProposedID: 1, ProposedSQID: g.team, AttestedAt: at.Add(-time.Hour)}); err != nil { |
| 253 | g.t.Fatal(err) |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | func (g *gate) observer(w *writeFixture) *observerFixture { |
| 258 | x := &observerFixture{writeFixture: w, now: at} |
| 259 | x.o = &Observer{C: w.c, H: w.h, S: w.s, Artifacts: map[string]string{w.app.Slug: sha256Hex(w.site.header)}, Now: func() time.Time { return x.now }} |
| 260 | return x |
| 261 | } |
| 262 | |
| 263 | // ---- The control: the harness reaches activation when nothing is wrong ---- |
| 264 | |
| 265 | func TestAdverseControlActivatesWhenEverythingHolds(t *testing.T) { |
| 266 | g := newGate(t) |
| 267 | x := g.fixture("calendar") |
| 268 | r := g.attempt("calendar", x.o) |
| 269 | if r.State != "done" || g.home.InstanceState("calendar") != "live" { |
| 270 | t.Fatalf("run %s %q, instance %q", r.State, r.Code, g.home.InstanceState("calendar")) |
| 271 | } |
| 272 | if n := len(g.home.Requests()); n == 0 { |
| 273 | t.Fatal("no requests") |
| 274 | } |
| 275 | found := false |
| 276 | for _, q := range g.home.Requests() { |
| 277 | found = found || q == homeop.DirectoryActivate+":calendar" |
| 278 | } |
| 279 | if !found { |
| 280 | t.Fatalf("calendar was not activated: %v", g.home.Requests()) |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | // adverse is one case: how the world or the journal is made wrong, and a |
| 285 | // code the gate must refuse with. |
| 286 | type adverse struct { |
| 287 | name string |
| 288 | app string |
| 289 | before func(*writeFixture) |
| 290 | edit func(t *testing.T, x *observerFixture) |
| 291 | want []string |
| 292 | } |
| 293 | |
| 294 | func (c adverse) run(t *testing.T) { |
| 295 | t.Run(c.name, func(t *testing.T) { |
| 296 | g := newGate(t) |
| 297 | app := c.app |
| 298 | if app == "" { |
| 299 | app = "calendar" |
| 300 | } |
| 301 | var before []func(*writeFixture) |
| 302 | if c.before != nil { |
| 303 | before = append(before, c.before) |
| 304 | } |
| 305 | x := g.fixture(app, before...) |
| 306 | if app != CanaryApp { |
| 307 | canaryActive(t, x.s) |
| 308 | } |
| 309 | if c.edit != nil { |
| 310 | c.edit(t, x) |
| 311 | } |
| 312 | g.refused(app, x.o, c.want...) |
| 313 | }) |
| 314 | } |
| 315 | |
| 316 | func runAdverse(t *testing.T, cases []adverse) { |
| 317 | t.Helper() |
| 318 | for _, c := range cases { |
| 319 | c.run(t) |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | // ---- Missing evidence ---- |
| 324 | |
| 325 | func TestAdverseMissingEvidence(t *testing.T) { |
| 326 | ctx := context.Background() |
| 327 | runAdverse(t, []adverse{ |
| 328 | {name: "no pre-plan-a home preflight", edit: func(t *testing.T, x *observerFixture) { |
| 329 | x.rejournal(t, func(e *evidence) { e.home = nil }) |
| 330 | setupOK(t, x.s.SaveHomePreflight(ctx, HomePreflight{Phase: PhasePreInitialize})) |
| 331 | }, want: []string{"missing-home-preflight"}}, |
| 332 | {name: "no baseline", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.base = nil }) }, |
| 333 | want: []string{"missing-baseline"}}, |
| 334 | {name: "write sent but not landed", edit: func(t *testing.T, x *observerFixture) { |
| 335 | x.rejournal(t, func(e *evidence) { e.write.State = "sent" }) |
| 336 | }, want: []string{"missing-write"}}, |
| 337 | {name: "no after snapshot", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.after = nil }) }, |
| 338 | want: []string{"missing-after"}}, |
| 339 | {name: "no delivery check", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.check = nil }) }, |
| 340 | want: []string{"missing-delivery-check"}}, |
| 341 | {name: "rolled back", edit: func(t *testing.T, x *observerFixture) { |
| 342 | setupOK(t, x.s.SaveRollback(ctx, RollbackRecord{App: x.app.Slug, State: "sent"})) |
| 343 | }, want: []string{"rollback-recorded"}}, |
| 344 | {name: "artifact not reviewed", edit: func(t *testing.T, x *observerFixture) { x.o.Artifacts = nil }, |
| 345 | want: []string{"artifact-unreviewed"}}, |
| 346 | }) |
| 347 | } |
| 348 | |
| 349 | // Plan C waits on Plan B alone (Paul, 2026-11-17), through the real |
| 350 | // engine and Home: a non-canary app is refused until Plan B has activated |
| 351 | // the canary, then activates with no live check recorded; a canary |
| 352 | // rolled back since closes the gate again. |
| 353 | func TestAdversePlanCWaitsOnPlanB(t *testing.T) { |
| 354 | t.Run("before Plan B", func(t *testing.T) { |
| 355 | g := newGate(t) |
| 356 | g.fixture("calendar") |
| 357 | x := g.fixture("docs") |
| 358 | g.refused("docs", x.o, "canary-not-active") |
| 359 | }) |
| 360 | t.Run("after Plan B", func(t *testing.T) { |
| 361 | g := newGate(t) |
| 362 | cal := g.fixture("calendar") |
| 363 | docs := g.fixture("docs") |
| 364 | if r := g.attempt("calendar", cal.o); r.State != "done" || g.home.InstanceState("calendar") != "live" { |
| 365 | t.Fatalf("Plan B: run %s %q", r.State, r.Code) |
| 366 | } |
| 367 | if r := g.attempt("docs", docs.o); r.State != "done" || g.home.InstanceState("docs") != "live" { |
| 368 | t.Fatalf("Plan C: run %s %q, docs %q", r.State, r.Code, g.home.InstanceState("docs")) |
| 369 | } |
| 370 | }) |
| 371 | t.Run("canary rolled back after Plan B", func(t *testing.T) { |
| 372 | g := newGate(t) |
| 373 | cal := g.fixture("calendar") |
| 374 | docs := g.fixture("docs") |
| 375 | if r := g.attempt("calendar", cal.o); r.State != "done" { |
| 376 | t.Fatalf("Plan B: run %s %q", r.State, r.Code) |
| 377 | } |
| 378 | setupOK(t, g.js.SaveRollback(context.Background(), RollbackRecord{App: CanaryApp, State: "restarted"})) |
| 379 | r := g.attempt("docs", docs.o) |
| 380 | if r.State != "parked" || !strings.Contains(r.Code, "canary-not-active") { |
| 381 | t.Fatalf("Plan C after a canary rollback: run %s %q", r.State, r.Code) |
| 382 | } |
| 383 | if g.home.InstanceState("docs") == "live" { |
| 384 | t.Fatal("docs was activated") |
| 385 | } |
| 386 | }) |
| 387 | } |
| 388 | |
| 389 | // ---- Changed identity ---- |
| 390 | |
| 391 | func instanceOf(x *observerFixture) carlosop.Instance { |
| 392 | return carlosop.Instance{Host: routeOf(x.app), App: x.app.Slug, Slug: "s-" + x.app.Slug, Channel: "stable", Region: "eu", |
| 393 | CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4, ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`)} |
| 394 | } |
| 395 | |
| 396 | func TestAdverseChangedIdentity(t *testing.T) { |
| 397 | changed := func(edit func(in *carlosop.Instance)) func(*testing.T, *observerFixture) { |
| 398 | return func(t *testing.T, x *observerFixture) { |
| 399 | in := instanceOf(x) |
| 400 | edit(&in) |
| 401 | x.f.AddInstance(in) |
| 402 | } |
| 403 | } |
| 404 | runAdverse(t, []adverse{ |
| 405 | {name: "slug", edit: changed(func(in *carlosop.Instance) { in.Slug = "s-another" }), want: []string{"identity-storage"}}, |
| 406 | {name: "created_at", edit: changed(func(in *carlosop.Instance) { in.CreatedAt = in.CreatedAt.Add(time.Hour) }), want: []string{"identity-storage"}}, |
| 407 | {name: "replica assignment", edit: changed(func(in *carlosop.Instance) { in.ReplicaAssignment = json.RawMessage(`{"boxes":["b2"]}`) }), |
| 408 | want: []string{"identity-storage"}}, |
| 409 | {name: "seed", edit: changed(func(in *carlosop.Instance) { in.Seed = json.RawMessage(`{"from":"another"}`) }), want: []string{"identity-storage"}}, |
| 410 | // The canonical domain re-pointed at another record: the |
| 411 | // evidence was bound to the old route. |
| 412 | {name: "domain re-pointed", edit: func(t *testing.T, x *observerFixture) { |
| 413 | in := instanceOf(x) |
| 414 | in.Host = "calendar-2.bds.oncarlos.com" |
| 415 | x.f.AddInstance(in) |
| 416 | x.f.AttachDomain(x.app.Slug, CanonicalHost(x.app), in.Host, "live") |
| 417 | }, want: []string{"identity-alias", "identity-instance"}}, |
| 418 | {name: "channel", edit: changed(func(in *carlosop.Instance) { in.Channel = "beta" }), want: []string{"identity-channel"}}, |
| 419 | {name: "region", edit: changed(func(in *carlosop.Instance) { in.Region = "us" }), want: []string{"identity-region"}}, |
| 420 | {name: "moving", edit: changed(func(in *carlosop.Instance) { in.Move = json.RawMessage(`{"to":"us"}`) }), want: []string{"identity-moving"}}, |
| 421 | {name: "record_seq", edit: changed(func(in *carlosop.Instance) { in.RecordSeq++ }), want: []string{"identity-record"}}, |
| 422 | // A second record answering for the host is an error in the read |
| 423 | // (never a silent pick), so the record host is staged in the journal. |
| 424 | {name: "record host", edit: func(t *testing.T, x *observerFixture) { |
| 425 | x.rejournal(t, func(e *evidence) { e.check.Identity.RecordHost = "calendar-record.example.test" }) |
| 426 | }, want: []string{"identity-instance"}}, |
| 427 | // The journal's own records describe another environment or |
| 428 | // ownership than the one the host now serves. |
| 429 | {name: "environment", edit: func(t *testing.T, x *observerFixture) { |
| 430 | x.rejournal(t, func(e *evidence) { e.check.Identity.Environment = "another" }) |
| 431 | }, want: []string{"identity-environment"}}, |
| 432 | {name: "owned", edit: func(t *testing.T, x *observerFixture) { |
| 433 | x.rejournal(t, func(e *evidence) { e.check.Identity.Owned = true }) |
| 434 | }, want: []string{"identity-owned"}}, |
| 435 | {name: "baseline's owner differs", edit: func(t *testing.T, x *observerFixture) { |
| 436 | x.rejournal(t, func(e *evidence) { e.base.Identity.Owned = true }) |
| 437 | }, want: []string{"identity-owned"}}, |
| 438 | }) |
| 439 | } |
| 440 | |
| 441 | // ---- Changed config ---- |
| 442 | |
| 443 | func TestAdverseChangedConfig(t *testing.T) { |
| 444 | runAdverse(t, []adverse{ |
| 445 | {name: "preserved secret resealed before the after snapshot", edit: func(t *testing.T, x *observerFixture) { |
| 446 | // A hand-written after row, as CaptureAfter would have refused. |
| 447 | x.rejournal(t, func(e *evidence) { |
| 448 | for i, v := range e.after.Vars { |
| 449 | if v.Key == "CALENDAR_INSTANCE_KEY" { |
| 450 | e.after.Vars = withDigest(e.after.Vars, i, "vd1:"+hex64("7")) |
| 451 | } |
| 452 | } |
| 453 | }) |
| 454 | }, want: []string{"after-not-preserved"}}, |
| 455 | {name: "preserved secret resealed after the after snapshot", edit: func(t *testing.T, x *observerFixture) { |
| 456 | x.f.SetSecret("calendar", "", "CALENDAR_INSTANCE_KEY") |
| 457 | }, want: []string{"drift-changed:CALENDAR_INSTANCE_KEY"}}, |
| 458 | {name: "plain value changed", edit: func(t *testing.T, x *observerFixture) { |
| 459 | x.f.SetVar("calendar", "", "CALENDAR_ORIGIN", "https://calendar.oficina.works/another-plain-value") |
| 460 | }, want: []string{"drift-changed:CALENDAR_ORIGIN"}}, |
| 461 | {name: "key removed", edit: func(t *testing.T, x *observerFixture) { |
| 462 | x.f.Unset("calendar", "", "CALENDAR_ORIGIN") |
| 463 | }, want: []string{"drift-gone:CALENDAR_ORIGIN"}}, |
| 464 | {name: "new team-mode key", edit: func(t *testing.T, x *observerFixture) { |
| 465 | x.f.SetVar("calendar", "", provision.TeamKeyNames(x.app)[0], "x") |
| 466 | }, want: []string{"team-mode-" + provision.TeamKeyNames(appNamedStatic("calendar"))[0]}}, |
| 467 | {name: "agent key with another digest", edit: func(t *testing.T, x *observerFixture) { |
| 468 | x.f.SetVar("calendar", "", "CALENDAR_AGENT_TEAM", "otherTeam") |
| 469 | }, want: []string{"agent-key-CALENDAR_AGENT_TEAM"}}, |
| 470 | {name: "issuer key with another digest", edit: func(t *testing.T, x *observerFixture) { |
| 471 | x.f.SetVar("calendar", "", "CALENDAR_AGENT_ISSUER", "https://elsewhere.example") |
| 472 | }, want: []string{"agent-key-CALENDAR_AGENT_ISSUER"}}, |
| 473 | {name: "overlay shadows an agent key", edit: func(t *testing.T, x *observerFixture) { |
| 474 | // The same value, so the same digest: only its source differs. |
| 475 | x.f.SetOverlay("calendar", routeOf(x.app), "CALENDAR_AGENT_ISSUER", Issuer) |
| 476 | }, want: []string{"agent-key-CALENDAR_AGENT_ISSUER"}}, |
| 477 | {name: "one agent key unset", edit: func(t *testing.T, x *observerFixture) { |
| 478 | x.f.Unset("calendar", "", "CALENDAR_AGENT_TEAM") |
| 479 | }, want: []string{"agent-key-CALENDAR_AGENT_TEAM"}}, |
| 480 | {name: "a key the runner did not write is added", edit: func(t *testing.T, x *observerFixture) { |
| 481 | x.f.PlatformWrite("calendar", "", "CALENDAR_PLATFORM_NOTE", "n") |
| 482 | }, want: []string{"config-added:CALENDAR_PLATFORM_NOTE"}}, |
| 483 | {name: "written for another team", edit: func(t *testing.T, x *observerFixture) { |
| 484 | x.rejournal(t, func(e *evidence) { e.write.Sent[AgentKeys(x.app)[1]] = "otherTeam" }) |
| 485 | }, want: []string{"team-mismatch"}}, |
| 486 | {name: "written for another issuer", edit: func(t *testing.T, x *observerFixture) { |
| 487 | x.rejournal(t, func(e *evidence) { e.write.Sent[AgentKeys(x.app)[0]] = "https://elsewhere.example" }) |
| 488 | }, want: []string{"issuer-mismatch"}}, |
| 489 | }) |
| 490 | } |
| 491 | |
| 492 | func appNamedStatic(slug string) provision.App { |
| 493 | a, _ := provision.AppBySlug(slug) |
| 494 | return a |
| 495 | } |
| 496 | |
| 497 | // ---- Superseded delivery check ---- |
| 498 | |
| 499 | func TestAdverseSupersededDeliveryCheck(t *testing.T) { |
| 500 | runAdverse(t, []adverse{ |
| 501 | {name: "after version changed", edit: func(t *testing.T, x *observerFixture) { |
| 502 | // A platform writer adds a key and the after snapshot is |
| 503 | // taken again: the check saw the earlier version. |
| 504 | x.f.PlatformWrite("calendar", "", "CALENDAR_PLATFORM_NOTE", "n") |
| 505 | if _, err := CaptureAfter(context.Background(), x.c, x.h, x.s, x.app); err != nil { |
| 506 | t.Fatalf("CaptureAfter: %v", err) |
| 507 | } |
| 508 | }, want: []string{"delivery-check-superseded"}}, |
| 509 | {name: "check saw another after version", edit: func(t *testing.T, x *observerFixture) { |
| 510 | x.rejournal(t, func(e *evidence) { e.check.AfterVersion = "cv1:" + hex64("9") }) |
| 511 | }, want: []string{"delivery-check-superseded"}}, |
| 512 | {name: "delivered version changed", edit: func(t *testing.T, x *observerFixture) { |
| 513 | x.rejournal(t, func(e *evidence) { e.check.Delivery.Version = "v1.3.9" }) |
| 514 | }, want: []string{"delivery-check-superseded"}}, |
| 515 | {name: "delivered header changed", edit: func(t *testing.T, x *observerFixture) { |
| 516 | x.rejournal(t, func(e *evidence) { e.check.Delivery.Header = "v1.3.9" }) |
| 517 | }, want: []string{"delivery-check-superseded"}}, |
| 518 | {name: "redeployed since", edit: func(t *testing.T, x *observerFixture) { |
| 519 | x.site.version, x.site.header = "v1.5.0", "v1.5.0" |
| 520 | }, want: []string{"delivery-check-superseded"}}, |
| 521 | }) |
| 522 | } |
| 523 | |
| 524 | // ---- Changed delivery ---- |
| 525 | |
| 526 | func TestAdverseChangedDelivery(t *testing.T) { |
| 527 | runAdverse(t, []adverse{ |
| 528 | {name: "version body", edit: func(t *testing.T, x *observerFixture) { x.site.version = "v9.9.9" }, |
| 529 | want: []string{"not-delivered", "version-header-mismatch", "delivery-check-superseded"}}, |
| 530 | {name: "header", edit: func(t *testing.T, x *observerFixture) { x.site.header = "v9.9.9" }, |
| 531 | want: []string{"not-delivered", "version-header-mismatch", "delivery-check-superseded"}}, |
| 532 | {name: "redirect", edit: func(t *testing.T, x *observerFixture) { x.site.redirectVersion = true }, want: []string{"not-delivered"}}, |
| 533 | {name: "healthz 503", edit: func(t *testing.T, x *observerFixture) { x.site.health = 503 }, want: []string{"not-delivered"}}, |
| 534 | {name: "operations reverted to app-401", edit: func(t *testing.T, x *observerFixture) { |
| 535 | x.site.ops = func(w http.ResponseWriter) { |
| 536 | w.Header().Set("Content-Type", "application/json") |
| 537 | w.WriteHeader(401) |
| 538 | _, _ = w.Write([]byte(`{"error":"unauthorized"}`)) |
| 539 | } |
| 540 | }, want: []string{"not-delivered"}}, |
| 541 | {name: "operations gone", edit: func(t *testing.T, x *observerFixture) { x.site.ops = nil }, want: []string{"not-delivered"}}, |
| 542 | }) |
| 543 | } |
| 544 | |
| 545 | // ---- Artifact ---- |
| 546 | |
| 547 | func TestAdverseArtifact(t *testing.T) { |
| 548 | runAdverse(t, []adverse{ |
| 549 | {name: "reviewed digest differs", edit: func(t *testing.T, x *observerFixture) { |
| 550 | x.o.Artifacts = map[string]string{"calendar": hex64("0")} |
| 551 | }, want: []string{"artifact-mismatch"}}, |
| 552 | {name: "reviewed digest malformed", edit: func(t *testing.T, x *observerFixture) { |
| 553 | x.o.Artifacts = map[string]string{"calendar": "AB" + sha256Hex(valueVersion)[2:]} |
| 554 | }, want: []string{"artifact-unreviewed"}}, |
| 555 | {name: "version malformed", before: func(w *writeFixture) { w.site.version, w.site.header = "-v1", "-v1" }, |
| 556 | want: []string{"version-unacceptable"}}, |
| 557 | }) |
| 558 | } |
| 559 | |
| 560 | // ---- Malformed receipts ---- |
| 561 | |
| 562 | // Each malformed answer to the write leaves it stopped, never landed, so |
| 563 | // the gate has no write for the app. |
| 564 | func TestAdverseMalformedReceipts(t *testing.T) { |
| 565 | other := "cv1:" + strings.Repeat("9", 64) |
| 566 | cases := map[string]func(p string) func(rc map[string]any){ |
| 567 | "extra set key": func(p string) func(rc map[string]any) { |
| 568 | return func(rc map[string]any) { rc["set"] = append(rc["set"].([]any), p+"_ORIGIN") } |
| 569 | }, |
| 570 | "missing digest": func(p string) func(rc map[string]any) { |
| 571 | return func(rc map[string]any) { delete(rc["digests"].(map[string]any), p+"_AGENT_TEAM") } |
| 572 | }, |
| 573 | "wrong digest": func(p string) func(rc map[string]any) { |
| 574 | return func(rc map[string]any) { |
| 575 | rc["digests"].(map[string]any)[p+"_AGENT_TEAM"] = carlosop.EnvDigest("tOther9") |
| 576 | } |
| 577 | }, |
| 578 | "unset not empty": func(p string) func(rc map[string]any) { |
| 579 | return func(rc map[string]any) { rc["unset"] = []any{p + "_ORIGIN"} } |
| 580 | }, |
| 581 | "unset_absent set": func(p string) func(rc map[string]any) { |
| 582 | return func(rc map[string]any) { rc["unset_absent"] = []any{p + "_ORIGIN"} } |
| 583 | }, |
| 584 | "others moved": func(string) func(rc map[string]any) { |
| 585 | return func(rc map[string]any) { |
| 586 | rc["others"] = map[string]any{"default": map[string]any{"before": rc["version_before"], "after": other}} |
| 587 | } |
| 588 | }, |
| 589 | "version before": func(string) func(rc map[string]any) { |
| 590 | return func(rc map[string]any) { rc["version_before"] = other } |
| 591 | }, |
| 592 | } |
| 593 | for name, edit := range cases { |
| 594 | t.Run(name, func(t *testing.T) { |
| 595 | g := newGate(t) |
| 596 | w := newWriteFixture(t, "calendar") |
| 597 | fastPolls(t, 5*time.Millisecond, 2*time.Second) |
| 598 | w.process(false) |
| 599 | w.putRewriter(t, edit(w.app.Prefix)) |
| 600 | if _, err := WriteAgentKeys(context.Background(), w.c, w.h, w.s, w.app, g.team, sha256Hex(w.site.header), true); !errors.Is(err, ErrStopConflict) { |
| 601 | t.Fatalf("err = %v, want ErrStopConflict", err) |
| 602 | } |
| 603 | rec, ok := w.writeRecord(t) |
| 604 | if !ok || rec.State == "landed" { |
| 605 | t.Fatalf("write %q, want one that did not land", rec.State) |
| 606 | } |
| 607 | setupOK(t, w.s.SaveHomePreflight(context.Background(), HomePreflight{Phase: PhasePrePlanA, ProposedID: 1, ProposedSQID: g.team, AttestedAt: at})) |
| 608 | x := g.observer(w) |
| 609 | g.refused("calendar", x.o, "missing-write") |
| 610 | }) |
| 611 | } |
| 612 | } |
| 613 | |