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 .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, when set for a role, is that role's answer instead. status map[string]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 s := f.status[role]; s != 0 { w.WriteHeader(s) 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) } } // A pasted table HomeQueries does not ask for is a typo or a stray line: // refused, with one fixed code, and not recorded. func TestHomePreflightRefusesUnknownTable(t *testing.T) { for _, phase := range []string{PhasePreInitialize, PhasePrePlanA} { t.Run(phase, func(t *testing.T) { p := newPreflightFixture(t) counts := zeroCounts() if phase == PhasePrePlanA { _, counts = p.initialized(t) } counts["extra"] = 0 r, codes := p.check(t, counts, phase) wantCodes(t, codes, "count-unknown-table") if _, ok := r.Counts["extra"]; ok { t.Fatal("record holds a table HomeQueries does not ask for") } delete(counts, "extra") delete(counts, "teams") counts["team"] = 0 _, codes = p.check(t, counts, phase) wantCodes(t, codes, "count-missing-teams", "count-unknown-table") }) } } // Before Plan A, a pending or open plan on either role is refused: the // spec allows none, and Plan A must be the only plan in flight. func TestHomePreflightPrePlanARefusesPendingOrOpenPlan(t *testing.T) { cases := []struct { name, role string edit func(*homeop.Inspection) code string }{ {"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) _, counts := p.initialized(t) p.set(c.role, c.edit) r, codes := p.check(t, counts, PhasePrePlanA) wantCodes(t, codes, c.code) if r.Pending != (c.code == "plan-pending") || r.Open != (c.code == "plan-open") { t.Fatalf("record pending=%v open=%v", r.Pending, r.Open) } }) } } 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) } } // Each role failing alone gives that role's fixed error, naming no // endpoint of either role. for _, role := range []string{homeop.Credential, homeop.Directory} { p.home.status = map[string]int{role: http.StatusServiceUnavailable} _, codes, err := CheckHome(context.Background(), p.client, p.ps, zeroCounts(), PhasePreInitialize) if err == nil || codes != nil { t.Fatalf("%s unavailable gave codes %q, err %v", role, codes, err) } if want := "adopt: " + role + " inspect failed"; err.Error() != want { t.Fatalf("error = %q, want %q", err, want) } for _, r := range p.client.Roles { if strings.Contains(err.Error(), r.URL) || strings.Contains(err.Error(), r.Origin) { t.Fatalf("error names an endpoint: %v", err) } } } }