package adopt import ( "context" "net/http" "strings" "testing" "amadan.net/oficina/alta/carlosop" ) // checkFixture is an app configured and restarted: its baseline taken // with the operations door absent, the agent keys stored, the door now // answering agent-access's challenge, and the after snapshot recorded. // artifact is the reviewed artifact SHA-256 of the release it serves. type checkFixture struct { *carlosFixture s *Store after Snapshot artifact string } func newCheckFixture(t *testing.T, slug string) *checkFixture { t.Helper() x := newCarlosFixture(t, slug) s := newJournal(t) ctx := context.Background() base, err := Observe(ctx, x.c, x.h, x.app) if err != nil { t.Fatalf("Observe baseline: %v", err) } if err := s.SaveBaseline(ctx, x.app.Slug, base); err != nil { t.Fatal(err) } keys := AgentKeys(x.app) x.f.SetVar(x.app.Slug, "", keys[0], Issuer) x.f.SetVar(x.app.Slug, "", keys[1], "tm_fixture_sqid") x.site.ops = agent401 after, err := Observe(ctx, x.c, x.h, x.app) if err != nil { t.Fatalf("Observe after: %v", err) } if err := s.SaveAfter(ctx, x.app.Slug, after); err != nil { t.Fatal(err) } return &checkFixture{carlosFixture: x, s: s, after: after, artifact: sha256Hex(valueVersion)} } func (w *checkFixture) check() error { return CheckDelivery(context.Background(), w.s, w.c, w.h, w.app, w.artifact) } func (w *checkFixture) noCheck(t *testing.T) { t.Helper() if _, ok, err := w.s.DeliveryCheck(context.Background(), w.app.Slug); err != nil || ok { t.Fatalf("a delivery check was recorded (ok %v, err %v)", ok, err) } } // The check asks Paul for nothing: it observes, compares and records. func TestDeliveryCheckRecordsBoundObservation(t *testing.T) { w := newCheckFixture(t, "docs") if err := w.check(); err != nil { t.Fatalf("CheckDelivery: %v", err) } got, ok, err := w.s.DeliveryCheck(context.Background(), "docs") if err != nil || !ok { t.Fatalf("no delivery check (ok %v, err %v)", ok, err) } if got.App != "docs" || got.At.IsZero() { t.Fatalf("delivery check app %q at %v", got.App, got.At) } if codes := SameIdentity(got.Identity, w.after.Identity); len(codes) > 0 { t.Fatalf("check identity differs from the after snapshot's: %v", codes) } if got.AfterVersion == "" || got.AfterVersion != w.after.Layer.Version { t.Fatal("the check is not bound to the after snapshot's write-layer version") } if got.Delivery.Ops != OpsAgent401 || got.Delivery.Version != valueVersion || got.Delivery.Header != valueVersion || got.Delivery.Health != 200 || got.Delivery.Redirected { t.Fatalf("check delivery ops %q health %d", got.Delivery.Ops, got.Delivery.Health) } } // Slides and Calls answer their own 401 before the change: only // agent-access's challenge after it counts. func TestDeliveryCheckAcceptsApp401BecomingAgentChallenge(t *testing.T) { x := newCarlosFixture(t, "slides") x.site.ops = app401 s := newJournal(t) ctx := context.Background() base, err := Observe(ctx, x.c, x.h, x.app) if err != nil || base.Delivery.Ops != OpsApp401 { t.Fatalf("baseline ops %q, %v", base.Delivery.Ops, err) } setupOK(t, s.SaveBaseline(ctx, "slides", base)) keys := AgentKeys(x.app) x.f.SetVar("slides", "", keys[0], Issuer) x.f.SetVar("slides", "", keys[1], "tm_fixture_sqid") x.site.ops = agent401 after, err := Observe(ctx, x.c, x.h, x.app) if err != nil { t.Fatal(err) } setupOK(t, s.SaveAfter(ctx, "slides", after)) w := &checkFixture{carlosFixture: x, s: s, after: after, artifact: sha256Hex(valueVersion)} // Still the app's own 401: nothing was delivered. x.site.ops = app401 if err := w.check(); err == nil || !strings.HasPrefix(err.Error(), "adopt: check-not-delivered") { t.Fatalf("app 401 after the restart: err = %v", err) } w.noCheck(t) x.site.ops = agent401 if err := w.check(); err != nil { t.Fatalf("agent challenge after the restart: %v", err) } } func TestDeliveryCheckRefusesWithoutAfterSnapshot(t *testing.T) { x := newCarlosFixture(t, "docs") s := newJournal(t) base, err := Observe(context.Background(), x.c, x.h, x.app) if err != nil { t.Fatal(err) } if err := s.SaveBaseline(context.Background(), "docs", base); err != nil { t.Fatal(err) } x.site.ops = agent401 err = CheckDelivery(context.Background(), s, x.c, x.h, x.app, sha256Hex(valueVersion)) if err == nil || err.Error() != "adopt: check-after-missing" { t.Fatalf("err = %v", err) } if _, ok, _ := s.DeliveryCheck(context.Background(), "docs"); ok { t.Fatal("recorded a delivery check without an after snapshot") } } func TestDeliveryCheckRefusesWithoutBaseline(t *testing.T) { w := newCheckFixture(t, "docs") s := newJournal(t) setupOK(t, s.SaveAfter(context.Background(), "docs", w.after)) w.s = s if err := w.check(); err == nil || err.Error() != "adopt: check-baseline-missing" { t.Fatalf("err = %v", err) } w.noCheck(t) } // The reviewed artifact is checked before anything is read, and the // served release must be it. func TestDeliveryCheckRefusesUnreviewedOrOtherArtifact(t *testing.T) { for _, artifact := range []string{"", "nothex", strings.ToUpper(sha256Hex(valueVersion))} { w := newCheckFixture(t, "docs") w.artifact = artifact n := len(w.f.Requests()) if err := w.check(); err == nil || err.Error() != "adopt: check-artifact-unreviewed" { t.Fatalf("artifact %q: err = %v", artifact, err) } if got := w.f.Requests(); len(got) != n { t.Fatalf("read the console for an unreviewed artifact: %q", got[n:]) } w.noCheck(t) } w := newCheckFixture(t, "docs") w.artifact = sha256Hex("v1.3.9") if err := w.check(); err == nil || err.Error() != "adopt: check-artifact-mismatch" { t.Fatalf("other artifact: err = %v", err) } w.noCheck(t) } func TestDeliveryCheckRefusesWithoutAgentShape(t *testing.T) { cases := map[string]func(w *checkFixture){ "absent": func(w *checkFixture) { w.site.ops = nil }, "app-401": func(w *checkFixture) { w.site.ops = app401 }, "unhealthy": func(w *checkFixture) { w.site.health = 503 }, "version moved": func(w *checkFixture) { w.site.version, w.site.header = "v1.5.0", "v1.5.0" }, "redirect": func(w *checkFixture) { w.site.redirectVersion = true }, } for name, change := range cases { t.Run(name, func(t *testing.T) { w := newCheckFixture(t, "docs") change(w) if err := w.check(); err == nil || !strings.HasPrefix(err.Error(), "adopt: check-not-delivered") { t.Fatalf("err = %v, want check-not-delivered", err) } w.noCheck(t) }) } } func TestDeliveryCheckRefusesIdentityChangedSinceAfter(t *testing.T) { cases := map[string]func(in *carlosop.Instance){ "record": func(in *carlosop.Instance) { in.RecordSeq++ }, "storage": func(in *carlosop.Instance) { in.Slug = "s-docs-recreated" }, "region": func(in *carlosop.Instance) { in.Region = "us" }, } for name, change := range cases { t.Run(name, func(t *testing.T) { w := newCheckFixture(t, "docs") in := carlosop.Instance{ Host: routeOf(w.app), App: "docs", Slug: "s-docs", Channel: "stable", Region: "eu", CreatedAt: w.after.Identity.CreatedAt, RecordSeq: w.after.Identity.RecordSeq, ReplicaAssignment: []byte(w.after.Identity.ReplicaAssignment), } change(&in) w.f.AddInstance(in) err := w.check() if err == nil || err.Error() != "adopt: check-identity-"+name { t.Fatalf("err = %v, want check-identity-%s", err, name) } w.noCheck(t) }) } } // A check run again on an unchanged app records it again: configure's // resume and re-check. func TestDeliveryCheckRepeats(t *testing.T) { w := newCheckFixture(t, "docs") setupOK(t, w.check()) setupOK(t, w.check()) if _, ok, err := w.s.DeliveryCheck(context.Background(), "docs"); err != nil || !ok { t.Fatalf("no delivery check after a repeat (ok %v, err %v)", ok, err) } } // The check is bound to the after snapshot's config: any change since, // in any key's digest, kind or source, or any layer's version, refuses. func TestDeliveryCheckRefusesConfigChangedSinceAfter(t *testing.T) { cases := map[string]struct { change func(w *checkFixture) codes []string }{ "unrelated key added": {func(w *checkFixture) { w.f.SetVar("docs", "", "DOCS_EXTRA", "x") }, []string{"added:DOCS_EXTRA", "layer:default"}}, "secret resealed": {func(w *checkFixture) { w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY") }, []string{"changed:DOCS_INSTANCE_KEY", "layer:default"}}, "agent key rewritten": {func(w *checkFixture) { w.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "tm_other") }, []string{"changed:DOCS_AGENT_TEAM", "layer:default"}}, "key unset": {func(w *checkFixture) { w.f.Unset("docs", "", "DOCS_ORIGIN") }, []string{"gone:DOCS_ORIGIN", "layer:default"}}, "overlay moved": {func(w *checkFixture) { w.f.SetOverlay("docs", docsRoute, "DOCS_ORIGIN", "https://elsewhere.example") }, []string{"from:DOCS_ORIGIN", "layer:overlay"}}, } for name, tc := range cases { t.Run(name, func(t *testing.T) { w := newCheckFixture(t, "docs") tc.change(w) err := w.check() if err == nil || !strings.HasPrefix(err.Error(), "adopt: check-config-") { t.Fatalf("err = %v, want check-config-", err) } for _, code := range tc.codes { if !strings.Contains(err.Error(), "check-config-"+code) { t.Fatalf("err = %v, want it to name %s", err, code) } } for _, leak := range []string{"vd1:", "cv1:", "tm_other", "elsewhere"} { if strings.Contains(err.Error(), leak) { t.Fatalf("err = %v carries a value", err) } } w.noCheck(t) }) } } // app401 is the operations answer Slides and Calls give before adoption: // their own middleware's 401, not agent-access's challenge. func app401(rw http.ResponseWriter) { rw.WriteHeader(401) _, _ = rw.Write([]byte(`{"error":"unauthorized"}`)) } func TestSameConfigComparesEveryPart(t *testing.T) { a := afterSnap() if codes := sameConfig(a, afterSnap()); len(codes) > 0 { t.Fatalf("identical snapshots differ: %v", codes) } cases := map[string]struct { change func(s *Snapshot) want string }{ "effective digest": {func(s *Snapshot) { s.Vars[0].Digest = "vd1:other" }, "changed:" + a.Vars[0].Key}, "effective kind": {func(s *Snapshot) { s.Vars[0].Kind = "secret" }, "kind:" + a.Vars[0].Key}, "effective from": {func(s *Snapshot) { s.Vars[0].From = "environment" }, "from:" + a.Vars[0].Key}, "effective gone": {func(s *Snapshot) { s.Vars = s.Vars[1:] }, "gone:" + a.Vars[0].Key}, "stored digest": {func(s *Snapshot) { s.Layer.Vars[0].Digest = "vd1:other" }, "changed:" + a.Layer.Vars[0].Key}, "stored added": {func(s *Snapshot) { s.Layer.Vars = append(s.Layer.Vars, carlosop.Var{Key: "DOCS_NEW", Kind: "env", Digest: "vd1:x"}) }, "added:DOCS_NEW"}, "write layer version": {func(s *Snapshot) { s.Layer.Version = "cv1:other" }, "layer:default"}, "write layer": {func(s *Snapshot) { s.WriteLayer = "staging" }, "write-layer"}, "other layer": {func(s *Snapshot) { s.Layers["environment"] = "cv1:other" }, "layer:environment"}, "layer gone": {func(s *Snapshot) { delete(s.Layers, "overlay") }, "layer:overlay"}, } for name, tc := range cases { t.Run(name, func(t *testing.T) { b := afterSnap() tc.change(&b) codes := sameConfig(a, b) found := false for _, c := range codes { found = found || c == tc.want } if !found { t.Fatalf("codes = %q, want %q among them", codes, tc.want) } }) } }