oficina / alta Public

adopt: Home preflight from inspect and attested counts

CheckHome inspects both roles once, reads Alta's journal streams and
checks them, with Paul's pasted row counts, against pre-initialize or
pre-plan-a. HomeQueries prints the eight read-only count queries.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev a3b3a3a109e3ed2771f65f54d3a336cb492cc568 parent 9f88cae
2 files changed, +503 −0
  • adopt/homepreflight.go +126 −0
  • adopt/homepreflight_test.go +377 −0
diff --git a/adopt/homepreflight.go b/adopt/homepreflight.go
new file mode 100644
index 0000000..e727a0c
--- /dev/null
+++ b/adopt/homepreflight.go
@@ -0,0 +1,126 @@
+package adopt
+
+// Home preflight. Signed inspect gives each role's stream position, the
+// directory's generation and next team id, and any pending or open plan.
+// It does not give memberships or team_instances, and Home's db doors
+// admit people only, so the row counts come from Paul's read-only
+// `carlos db query` runs of HomeQueries, pasted back as counts.
+
+import (
+ "context"
+ "errors"
+ "time"
+
+ "amadan.net/oficina/alta/homeop"
+ "amadan.net/oficina/alta/provision"
+)
+
+// homeTables are the tables whose rows the preflight counts.
+var homeTables = []string{
+ "teams", "memberships", "team_instances", "operator_http_teams",
+ "roster_generation", "roster_consumers", "roster_tokens", "roster_operator_receipts",
+}
+
+// HomeQueries are the read-only queries Paul runs against Home, one count
+// per table, in a fixed order.
+func HomeQueries() []string {
+ q := make([]string, len(homeTables))
+ for i, t := range homeTables {
+ q[i] = "SELECT count(*) FROM " + t
+ }
+ return q
+}
+
+// expectedCount is the row count each phase requires of table t: nothing
+// before initialize; afterwards only initialize's generation and receipt.
+func expectedCount(phase, t string) int64 {
+ if phase == PhasePrePlanA && (t == "roster_generation" || t == "roster_operator_receipts") {
+ return 1
+ }
+ return 0
+}
+
+// CheckHome inspects both roles once, reads Alta's journal streams, and
+// checks them and the pasted counts against phase. It returns the record
+// to store and the refusal codes, in a fixed order; no codes means Home is
+// as phase requires. An error means the evidence could not be gathered.
+func CheckHome(ctx context.Context, h *homeop.Client, ps *provision.Store, counts map[string]int64, phase string) (HomePreflight, []string, error) {
+ if phase != PhasePreInitialize && phase != PhasePrePlanA {
+ return HomePreflight{}, nil, errors.New("adopt: unknown home preflight phase")
+ }
+ cred, err := inspect(ctx, h, homeop.Credential)
+ if err != nil {
+ return HomePreflight{}, nil, err
+ }
+ dir, err := inspect(ctx, h, homeop.Directory)
+ if err != nil {
+ return HomePreflight{}, nil, err
+ }
+ credSeq, credHead, _, err := ps.Stream(ctx, homeop.Credential)
+ if err != nil {
+ return HomePreflight{}, nil, errors.New("adopt: journal stream unreadable")
+ }
+ dirSeq, dirHead, _, err := ps.Stream(ctx, homeop.Directory)
+ if err != nil {
+ return HomePreflight{}, nil, errors.New("adopt: journal stream unreadable")
+ }
+
+ now := time.Now
+ if h.Now != nil {
+ now = h.Now
+ }
+ r := HomePreflight{
+ Phase: phase,
+ CredentialSeq: cred.Sequence, CredentialHead: cred.Head,
+ DirectorySeq: dir.Sequence,
+ Generation: dir.Generation,
+ ProposedID: dir.TeamID, ProposedSQID: dir.TeamSQID,
+ Pending: cred.PendingPlan != "" || dir.PendingPlan != "",
+ Open: cred.OpenPlan != "" || dir.OpenPlan != "",
+ Counts: map[string]int64{},
+ AttestedAt: now(),
+ }
+
+ var codes []string
+ refuse := func(bad bool, code string) {
+ if bad {
+ codes = append(codes, code)
+ }
+ }
+ unused := func(in homeop.Inspection) bool { return in.Sequence == 0 && in.Head == "" }
+ if phase == PhasePreInitialize {
+ refuse(!unused(cred), "credential-stream-used")
+ refuse(!unused(dir), "directory-stream-used")
+ refuse(dir.Generation != nil, "generation-set")
+ refuse(r.ProposedID != 1, "proposed-not-one")
+ refuse(r.Pending, "plan-pending")
+ refuse(r.Open, "plan-open")
+ } else {
+ // Only Alta's initialize has run on the directory: sequence 1,
+ // and Home's head is the one Alta's journal holds.
+ refuse(dirSeq != 1 || dir.Sequence != dirSeq || dir.Head != dirHead, "directory-stream-foreign")
+ refuse(!unused(cred) && (cred.Sequence != credSeq || cred.Head != credHead), "credential-stream-foreign")
+ refuse(dir.Generation == nil, "generation-missing")
+ refuse(r.ProposedID != 1, "proposed-not-one")
+ }
+ for _, t := range homeTables {
+ n, ok := counts[t]
+ if !ok {
+ codes = append(codes, "count-missing-"+t)
+ continue
+ }
+ r.Counts[t] = n
+ refuse(n != expectedCount(phase, t), "count-unexpected-"+t)
+ }
+ return r, codes, nil
+}
+
+// inspect is one signed inspect of role. Its errors are fixed: no
+// endpoint, no body.
+func inspect(ctx context.Context, h *homeop.Client, role string) (homeop.Inspection, error) {
+ in, o, err := h.Inspect(ctx, role)
+ if err != nil || o != homeop.OK {
+ return homeop.Inspection{}, errors.New("adopt: " + role + " inspect failed")
+ }
+ return in, nil
+}
diff --git a/adopt/homepreflight_test.go b/adopt/homepreflight_test.go
new file mode 100644
index 0000000..948791e
--- /dev/null
+++ b/adopt/homepreflight_test.go
@@ -0,0 +1,377 @@
+package adopt
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "sync"
+ "testing"
+
+ "amadan.net/oficina/alta/homeop"
+ "amadan.net/oficina/alta/homeop/fakehome"
+ "amadan.net/oficina/alta/provision"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+)
+
+// inspectHome answers <role>.inspect with whatever state a test sets,
+// echoing the signed challenge so the client accepts the answer.
+type inspectHome struct {
+ mu sync.Mutex
+ state map[string]homeop.Inspection
+ status int
+ calls map[string]int
+}
+
+func (f *inspectHome) handler(role string) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.calls[role]++
+ if f.status != 0 {
+ w.WriteHeader(f.status)
+ return
+ }
+ raw, _ := io.ReadAll(r.Body)
+ payload, err := homeop.EnvelopePayload(raw)
+ var c homeop.InspectChallenge
+ if err != nil || homeop.Decode(payload, &c) != nil || c.Role != role {
+ w.WriteHeader(http.StatusForbidden)
+ return
+ }
+ out := f.state[role]
+ out.Version, out.Role, out.Challenge = 1, role, c.Challenge
+ b, _ := homeop.Encode(out)
+ _, _ = w.Write(b)
+ })
+}
+
+type preflightFixture struct {
+ home *inspectHome
+ client *homeop.Client
+ ps *provision.Store
+}
+
+func newPreflightFixture(t *testing.T) *preflightFixture {
+ t.Helper()
+ key, err := family.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ f := &inspectHome{state: map[string]homeop.Inspection{
+ homeop.Credential: {},
+ homeop.Directory: {TeamID: 1, TeamSQID: "Uk"},
+ }, calls: map[string]int{}}
+ roles := map[string]homeop.Role{}
+ for _, r := range []string{homeop.Credential, homeop.Directory} {
+ srv := httptest.NewServer(f.handler(r))
+ t.Cleanup(srv.Close)
+ roles[r] = homeop.Role{Name: r, Origin: "https://" + r + ".example.test", URL: srv.URL, Installation: homeop.Token(), Registry: homeop.Token(), Device: homeop.Token()}
+ }
+ ps, _ := journal(t, filepath.Join(t.TempDir(), "alta.db"))
+ return &preflightFixture{home: f, client: &homeop.Client{Key: key, Prefilter: homeop.Token(), Roles: roles, Now: clock}, ps: ps}
+}
+
+func (p *preflightFixture) set(role string, edit func(*homeop.Inspection)) {
+ p.home.mu.Lock()
+ defer p.home.mu.Unlock()
+ in := p.home.state[role]
+ edit(&in)
+ p.home.state[role] = in
+}
+
+// initialized puts Home and Alta's journal where Alta's initialize leaves
+// them: directory at sequence 1 on both sides, a generation, one roster
+// generation row and one operator receipt.
+func (p *preflightFixture) initialized(t *testing.T) (string, map[string]int64) {
+ t.Helper()
+ head, gen := homeop.Token(), homeop.Token()
+ p.set(homeop.Directory, func(in *homeop.Inspection) { in.Sequence, in.Head, in.Generation = 1, head, &gen })
+ if err := p.ps.SetStream(context.Background(), homeop.Directory, 1, head); err != nil {
+ t.Fatal(err)
+ }
+ counts := zeroCounts()
+ counts["roster_generation"], counts["roster_operator_receipts"] = 1, 1
+ return head, counts
+}
+
+var wantTables = []string{"teams", "memberships", "team_instances", "operator_http_teams", "roster_generation", "roster_consumers", "roster_tokens", "roster_operator_receipts"}
+
+func zeroCounts() map[string]int64 {
+ c := map[string]int64{}
+ for _, t := range wantTables {
+ c[t] = 0
+ }
+ return c
+}
+
+func (p *preflightFixture) check(t *testing.T, counts map[string]int64, phase string) (HomePreflight, []string) {
+ t.Helper()
+ r, codes, err := CheckHome(context.Background(), p.client, p.ps, counts, phase)
+ if err != nil {
+ t.Fatalf("CheckHome: %v", err)
+ }
+ return r, codes
+}
+
+func wantCodes(t *testing.T, got []string, want ...string) {
+ t.Helper()
+ if len(got) == 0 && len(want) == 0 {
+ return
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("codes = %q, want %q", got, want)
+ }
+}
+
+func TestHomePreflightQueriesAreExact(t *testing.T) {
+ var want []string
+ for _, tb := range wantTables {
+ want = append(want, "SELECT count(*) FROM "+tb)
+ }
+ if got := HomeQueries(); !reflect.DeepEqual(got, want) {
+ t.Fatalf("HomeQueries = %q, want %q", got, want)
+ }
+}
+
+func TestHomePreflightBeforeInitializeRefusesAnyRow(t *testing.T) {
+ p := newPreflightFixture(t)
+ r, codes := p.check(t, zeroCounts(), PhasePreInitialize)
+ wantCodes(t, codes)
+ if r.Phase != PhasePreInitialize || r.ProposedID != 1 || r.ProposedSQID != "Uk" || !r.AttestedAt.Equal(at) || !reflect.DeepEqual(r.Counts, zeroCounts()) {
+ t.Fatalf("record = %+v", r)
+ }
+ if p.home.calls[homeop.Credential] != 1 || p.home.calls[homeop.Directory] != 1 {
+ t.Fatalf("inspect calls = %v, want one per role", p.home.calls)
+ }
+ for _, tb := range wantTables {
+ t.Run(tb, func(t *testing.T) {
+ c := zeroCounts()
+ c[tb] = 1
+ _, codes := p.check(t, c, PhasePreInitialize)
+ wantCodes(t, codes, "count-unexpected-"+tb)
+ })
+ }
+}
+
+func TestHomePreflightRefusesUsedStreams(t *testing.T) {
+ gen := homeop.Token()
+ cases := []struct {
+ name string
+ role string
+ edit func(*homeop.Inspection)
+ code string
+ }{
+ {"credential-sequence", homeop.Credential, func(in *homeop.Inspection) { in.Sequence, in.Head = 1, homeop.Token() }, "credential-stream-used"},
+ {"credential-head", homeop.Credential, func(in *homeop.Inspection) { in.Head = homeop.Token() }, "credential-stream-used"},
+ {"directory-sequence", homeop.Directory, func(in *homeop.Inspection) { in.Sequence, in.Head = 1, homeop.Token() }, "directory-stream-used"},
+ {"directory-head", homeop.Directory, func(in *homeop.Inspection) { in.Head = homeop.Token() }, "directory-stream-used"},
+ {"generation", homeop.Directory, func(in *homeop.Inspection) { in.Generation = &gen }, "generation-set"},
+ {"credential-pending", homeop.Credential, func(in *homeop.Inspection) { in.PendingPlan = homeop.Token() }, "plan-pending"},
+ {"directory-pending", homeop.Directory, func(in *homeop.Inspection) { in.PendingPlan = homeop.Token() }, "plan-pending"},
+ {"credential-open", homeop.Credential, func(in *homeop.Inspection) { in.OpenPlan = homeop.Token() }, "plan-open"},
+ {"directory-open", homeop.Directory, func(in *homeop.Inspection) { in.OpenPlan = homeop.Token() }, "plan-open"},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ p := newPreflightFixture(t)
+ p.set(c.role, c.edit)
+ _, codes := p.check(t, zeroCounts(), PhasePreInitialize)
+ wantCodes(t, codes, c.code)
+ })
+ }
+}
+
+func TestHomePreflightRefusesProposedNotOne(t *testing.T) {
+ for _, id := range []int64{0, 2, 7} {
+ p := newPreflightFixture(t)
+ p.set(homeop.Directory, func(in *homeop.Inspection) { in.TeamID = id })
+ _, codes := p.check(t, zeroCounts(), PhasePreInitialize)
+ wantCodes(t, codes, "proposed-not-one")
+
+ _, counts := p.initialized(t)
+ _, codes = p.check(t, counts, PhasePrePlanA)
+ wantCodes(t, codes, "proposed-not-one")
+ }
+}
+
+func TestHomePreflightRefusesMissingCount(t *testing.T) {
+ for _, phase := range []string{PhasePreInitialize, PhasePrePlanA} {
+ for _, tb := range wantTables {
+ t.Run(phase+"/"+tb, func(t *testing.T) {
+ p := newPreflightFixture(t)
+ counts := zeroCounts()
+ if phase == PhasePrePlanA {
+ _, counts = p.initialized(t)
+ }
+ delete(counts, tb)
+ r, codes := p.check(t, counts, phase)
+ wantCodes(t, codes, "count-missing-"+tb)
+ if _, ok := r.Counts[tb]; ok {
+ t.Fatalf("record holds a count for %s that was not pasted", tb)
+ }
+ })
+ }
+ }
+ p := newPreflightFixture(t)
+ _, codes := p.check(t, nil, PhasePreInitialize)
+ var want []string
+ for _, tb := range wantTables {
+ want = append(want, "count-missing-"+tb)
+ }
+ wantCodes(t, codes, want...)
+}
+
+func TestHomePreflightPrePlanAAcceptsOwnInitialize(t *testing.T) {
+ p := newPreflightFixture(t)
+ _, counts := p.initialized(t)
+ r, codes := p.check(t, counts, PhasePrePlanA)
+ wantCodes(t, codes)
+ if r.Phase != PhasePrePlanA || r.DirectorySeq != 1 || r.CredentialSeq != 0 || r.Generation == nil || r.ProposedID != 1 || !reflect.DeepEqual(r.Counts, counts) {
+ t.Fatalf("record = %+v", r)
+ }
+
+ // The credential stream may have moved, if Alta's own journal moved it.
+ credHead := homeop.Token()
+ p.set(homeop.Credential, func(in *homeop.Inspection) { in.Sequence, in.Head = 3, credHead })
+ if err := p.ps.SetStream(context.Background(), homeop.Credential, 3, credHead); err != nil {
+ t.Fatal(err)
+ }
+ r, codes = p.check(t, counts, PhasePrePlanA)
+ wantCodes(t, codes)
+ if r.CredentialSeq != 3 || r.CredentialHead != credHead {
+ t.Fatalf("record = %+v", r)
+ }
+
+ // Unknown pasted tables are not recorded.
+ counts["extra"] = 9
+ r, codes = p.check(t, counts, PhasePrePlanA)
+ wantCodes(t, codes)
+ if _, ok := r.Counts["extra"]; ok {
+ t.Fatal("record holds a table HomeQueries does not ask for")
+ }
+}
+
+func TestHomePreflightPrePlanARefusesForeignDirectoryHead(t *testing.T) {
+ gen := homeop.Token()
+ cases := []struct {
+ name string
+ edit func(*testing.T, *preflightFixture)
+ code string
+ }{
+ {"other-head", func(t *testing.T, p *preflightFixture) {
+ p.set(homeop.Directory, func(in *homeop.Inspection) { in.Head = homeop.Token() })
+ }, "directory-stream-foreign"},
+ {"further-sequence", func(t *testing.T, p *preflightFixture) {
+ p.set(homeop.Directory, func(in *homeop.Inspection) { in.Sequence = 2 })
+ }, "directory-stream-foreign"},
+ {"journal-beyond-initialize", func(t *testing.T, p *preflightFixture) {
+ h := homeop.Token()
+ p.set(homeop.Directory, func(in *homeop.Inspection) { in.Sequence, in.Head = 2, h })
+ if err := p.ps.SetStream(context.Background(), homeop.Directory, 2, h); err != nil {
+ t.Fatal(err)
+ }
+ }, "directory-stream-foreign"},
+ {"journal-at-zero", func(t *testing.T, p *preflightFixture) {
+ p.set(homeop.Directory, func(in *homeop.Inspection) { in.Sequence, in.Head = 0, "" })
+ if err := p.ps.SetStream(context.Background(), homeop.Directory, 0, ""); err != nil {
+ t.Fatal(err)
+ }
+ }, "directory-stream-foreign"},
+ {"credential-foreign", func(t *testing.T, p *preflightFixture) {
+ p.set(homeop.Credential, func(in *homeop.Inspection) { in.Sequence, in.Head = 1, homeop.Token() })
+ }, "credential-stream-foreign"},
+ {"credential-other-head", func(t *testing.T, p *preflightFixture) {
+ p.set(homeop.Credential, func(in *homeop.Inspection) { in.Sequence, in.Head = 1, homeop.Token() })
+ if err := p.ps.SetStream(context.Background(), homeop.Credential, 1, homeop.Token()); err != nil {
+ t.Fatal(err)
+ }
+ }, "credential-stream-foreign"},
+ {"no-generation", func(t *testing.T, p *preflightFixture) {
+ p.set(homeop.Directory, func(in *homeop.Inspection) { in.Generation = nil })
+ }, "generation-missing"},
+ {"generation-kept", func(t *testing.T, p *preflightFixture) {
+ p.set(homeop.Directory, func(in *homeop.Inspection) { in.Generation = &gen })
+ }, ""},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ p := newPreflightFixture(t)
+ _, counts := p.initialized(t)
+ c.edit(t, p)
+ _, codes := p.check(t, counts, PhasePrePlanA)
+ if c.code == "" {
+ wantCodes(t, codes)
+ return
+ }
+ wantCodes(t, codes, c.code)
+ })
+ }
+}
+
+func TestHomePreflightPrePlanARefusesExtraReceipt(t *testing.T) {
+ for _, tb := range wantTables {
+ for _, n := range []int64{0, 1, 2} {
+ p := newPreflightFixture(t)
+ _, counts := p.initialized(t)
+ want := int64(0)
+ if tb == "roster_generation" || tb == "roster_operator_receipts" {
+ want = 1
+ }
+ counts[tb] = n
+ _, codes := p.check(t, counts, PhasePrePlanA)
+ if n == want {
+ wantCodes(t, codes)
+ } else {
+ wantCodes(t, codes, "count-unexpected-"+tb)
+ }
+ }
+ }
+}
+
+// A fresh fake Home, reached through signed inspects it verifies, passes
+// pre-initialize.
+func TestHomePreflightPreInitializeAcceptsFreshHome(t *testing.T) {
+ key, err := family.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ pre := homeop.Token()
+ home := fakehome.New(key.SignPub(), pre, "https://id.example.test", "https://dir.example.test", clock)
+ roles := map[string]homeop.Role{}
+ for r, origin := range map[string]string{homeop.Credential: "https://id.example.test", homeop.Directory: "https://dir.example.test"} {
+ srv := httptest.NewServer(home.Handler(r))
+ t.Cleanup(srv.Close)
+ pins := home.Pins(r)
+ roles[r] = homeop.Role{Name: r, Origin: origin, URL: srv.URL, Installation: pins.Installation, Registry: pins.Registry, Device: pins.Device}
+ }
+ ps, _ := journal(t, filepath.Join(t.TempDir(), "alta.db"))
+ r, codes, err := CheckHome(context.Background(), &homeop.Client{Key: key, Prefilter: pre, Roles: roles, Now: clock}, ps, zeroCounts(), PhasePreInitialize)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantCodes(t, codes)
+ if r.ProposedID != 1 || r.ProposedSQID == "" {
+ t.Fatalf("record = %+v", r)
+ }
+}
+
+func TestHomePreflightErrors(t *testing.T) {
+ p := newPreflightFixture(t)
+ for _, phase := range []string{"", "plan-a", "pre-plan-b"} {
+ if _, _, err := CheckHome(context.Background(), p.client, p.ps, zeroCounts(), phase); err == nil {
+ t.Fatalf("phase %q accepted", phase)
+ }
+ }
+ p.home.status = http.StatusServiceUnavailable
+ _, codes, err := CheckHome(context.Background(), p.client, p.ps, zeroCounts(), PhasePreInitialize)
+ if err == nil || codes != nil {
+ t.Fatalf("an unavailable Home gave codes %q, err %v", codes, err)
+ }
+ if strings.Contains(err.Error(), p.client.Roles[homeop.Directory].URL) {
+ t.Fatalf("error names the endpoint: %v", err)
+ }
+}