| 1 | package adopt |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "io" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "path/filepath" |
| 9 | "reflect" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | "testing" |
| 13 | |
| 14 | "amadan.net/oficina/alta/homeop" |
| 15 | "amadan.net/oficina/alta/homeop/fakehome" |
| 16 | "amadan.net/oficina/alta/provision" |
| 17 | family "amadan.net/rastrillo/rastrillo/crypto" |
| 18 | ) |
| 19 | |
| 20 | // inspectHome answers <role>.inspect with whatever state a test sets, |
| 21 | // echoing the signed challenge so the client accepts the answer. |
| 22 | type inspectHome struct { |
| 23 | mu sync.Mutex |
| 24 | state map[string]homeop.Inspection |
| 25 | // status, when set for a role, is that role's answer instead. |
| 26 | status map[string]int |
| 27 | calls map[string]int |
| 28 | } |
| 29 | |
| 30 | func (f *inspectHome) handler(role string) http.Handler { |
| 31 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 32 | f.mu.Lock() |
| 33 | defer f.mu.Unlock() |
| 34 | f.calls[role]++ |
| 35 | if s := f.status[role]; s != 0 { |
| 36 | w.WriteHeader(s) |
| 37 | return |
| 38 | } |
| 39 | raw, _ := io.ReadAll(r.Body) |
| 40 | payload, err := homeop.EnvelopePayload(raw) |
| 41 | var c homeop.InspectChallenge |
| 42 | if err != nil || homeop.Decode(payload, &c) != nil || c.Role != role { |
| 43 | w.WriteHeader(http.StatusForbidden) |
| 44 | return |
| 45 | } |
| 46 | out := f.state[role] |
| 47 | out.Version, out.Role, out.Challenge = 1, role, c.Challenge |
| 48 | b, _ := homeop.Encode(out) |
| 49 | _, _ = w.Write(b) |
| 50 | }) |
| 51 | } |
| 52 | |
| 53 | type preflightFixture struct { |
| 54 | home *inspectHome |
| 55 | client *homeop.Client |
| 56 | ps *provision.Store |
| 57 | } |
| 58 | |
| 59 | func newPreflightFixture(t *testing.T) *preflightFixture { |
| 60 | t.Helper() |
| 61 | key, err := family.Generate() |
| 62 | if err != nil { |
| 63 | t.Fatal(err) |
| 64 | } |
| 65 | f := &inspectHome{state: map[string]homeop.Inspection{ |
| 66 | homeop.Credential: {}, |
| 67 | homeop.Directory: {TeamID: 1, TeamSQID: "Uk"}, |
| 68 | }, calls: map[string]int{}} |
| 69 | roles := map[string]homeop.Role{} |
| 70 | for _, r := range []string{homeop.Credential, homeop.Directory} { |
| 71 | srv := httptest.NewServer(f.handler(r)) |
| 72 | t.Cleanup(srv.Close) |
| 73 | roles[r] = homeop.Role{Name: r, Origin: "https://" + r + ".example.test", URL: srv.URL, Installation: homeop.Token(), Registry: homeop.Token(), Device: homeop.Token()} |
| 74 | } |
| 75 | ps, _ := journal(t, filepath.Join(t.TempDir(), "alta.db")) |
| 76 | return &preflightFixture{home: f, client: &homeop.Client{Key: key, Prefilter: homeop.Token(), Roles: roles, Now: clock}, ps: ps} |
| 77 | } |
| 78 | |
| 79 | func (p *preflightFixture) set(role string, edit func(*homeop.Inspection)) { |
| 80 | p.home.mu.Lock() |
| 81 | defer p.home.mu.Unlock() |
| 82 | in := p.home.state[role] |
| 83 | edit(&in) |
| 84 | p.home.state[role] = in |
| 85 | } |
| 86 | |
| 87 | // initialized puts Home and Alta's journal where Alta's initialize leaves |
| 88 | // them: directory at sequence 1 on both sides, a generation, one roster |
| 89 | // generation row and one operator receipt. |
| 90 | func (p *preflightFixture) initialized(t *testing.T) (string, map[string]int64) { |
| 91 | t.Helper() |
| 92 | head, gen := homeop.Token(), homeop.Token() |
| 93 | p.set(homeop.Directory, func(in *homeop.Inspection) { in.Sequence, in.Head, in.Generation = 1, head, &gen }) |
| 94 | if err := p.ps.SetStream(context.Background(), homeop.Directory, 1, head); err != nil { |
| 95 | t.Fatal(err) |
| 96 | } |
| 97 | counts := zeroCounts() |
| 98 | counts["roster_generation"], counts["roster_operator_receipts"] = 1, 1 |
| 99 | return head, counts |
| 100 | } |
| 101 | |
| 102 | var wantTables = []string{"teams", "memberships", "team_instances", "operator_http_teams", "roster_generation", "roster_consumers", "roster_tokens", "roster_operator_receipts"} |
| 103 | |
| 104 | func zeroCounts() map[string]int64 { |
| 105 | c := map[string]int64{} |
| 106 | for _, t := range wantTables { |
| 107 | c[t] = 0 |
| 108 | } |
| 109 | return c |
| 110 | } |
| 111 | |
| 112 | func (p *preflightFixture) check(t *testing.T, counts map[string]int64, phase string) (HomePreflight, []string) { |
| 113 | t.Helper() |
| 114 | r, codes, err := CheckHome(context.Background(), p.client, p.ps, counts, phase) |
| 115 | if err != nil { |
| 116 | t.Fatalf("CheckHome: %v", err) |
| 117 | } |
| 118 | return r, codes |
| 119 | } |
| 120 | |
| 121 | func wantCodes(t *testing.T, got []string, want ...string) { |
| 122 | t.Helper() |
| 123 | if len(got) == 0 && len(want) == 0 { |
| 124 | return |
| 125 | } |
| 126 | if !reflect.DeepEqual(got, want) { |
| 127 | t.Fatalf("codes = %q, want %q", got, want) |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | func TestHomePreflightQueriesAreExact(t *testing.T) { |
| 132 | var want []string |
| 133 | for _, tb := range wantTables { |
| 134 | want = append(want, "SELECT count(*) FROM "+tb) |
| 135 | } |
| 136 | if got := HomeQueries(); !reflect.DeepEqual(got, want) { |
| 137 | t.Fatalf("HomeQueries = %q, want %q", got, want) |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | func TestHomePreflightBeforeInitializeRefusesAnyRow(t *testing.T) { |
| 142 | p := newPreflightFixture(t) |
| 143 | r, codes := p.check(t, zeroCounts(), PhasePreInitialize) |
| 144 | wantCodes(t, codes) |
| 145 | if r.Phase != PhasePreInitialize || r.ProposedID != 1 || r.ProposedSQID != "Uk" || !r.AttestedAt.Equal(at) || !reflect.DeepEqual(r.Counts, zeroCounts()) { |
| 146 | t.Fatalf("record = %+v", r) |
| 147 | } |
| 148 | if p.home.calls[homeop.Credential] != 1 || p.home.calls[homeop.Directory] != 1 { |
| 149 | t.Fatalf("inspect calls = %v, want one per role", p.home.calls) |
| 150 | } |
| 151 | for _, tb := range wantTables { |
| 152 | t.Run(tb, func(t *testing.T) { |
| 153 | c := zeroCounts() |
| 154 | c[tb] = 1 |
| 155 | _, codes := p.check(t, c, PhasePreInitialize) |
| 156 | wantCodes(t, codes, "count-unexpected-"+tb) |
| 157 | }) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | func TestHomePreflightRefusesUsedStreams(t *testing.T) { |
| 162 | gen := homeop.Token() |
| 163 | cases := []struct { |
| 164 | name string |
| 165 | role string |
| 166 | edit func(*homeop.Inspection) |
| 167 | code string |
| 168 | }{ |
| 169 | {"credential-sequence", homeop.Credential, func(in *homeop.Inspection) { in.Sequence, in.Head = 1, homeop.Token() }, "credential-stream-used"}, |
| 170 | {"credential-head", homeop.Credential, func(in *homeop.Inspection) { in.Head = homeop.Token() }, "credential-stream-used"}, |
| 171 | {"directory-sequence", homeop.Directory, func(in *homeop.Inspection) { in.Sequence, in.Head = 1, homeop.Token() }, "directory-stream-used"}, |
| 172 | {"directory-head", homeop.Directory, func(in *homeop.Inspection) { in.Head = homeop.Token() }, "directory-stream-used"}, |
| 173 | {"generation", homeop.Directory, func(in *homeop.Inspection) { in.Generation = &gen }, "generation-set"}, |
| 174 | {"credential-pending", homeop.Credential, func(in *homeop.Inspection) { in.PendingPlan = homeop.Token() }, "plan-pending"}, |
| 175 | {"directory-pending", homeop.Directory, func(in *homeop.Inspection) { in.PendingPlan = homeop.Token() }, "plan-pending"}, |
| 176 | {"credential-open", homeop.Credential, func(in *homeop.Inspection) { in.OpenPlan = homeop.Token() }, "plan-open"}, |
| 177 | {"directory-open", homeop.Directory, func(in *homeop.Inspection) { in.OpenPlan = homeop.Token() }, "plan-open"}, |
| 178 | } |
| 179 | for _, c := range cases { |
| 180 | t.Run(c.name, func(t *testing.T) { |
| 181 | p := newPreflightFixture(t) |
| 182 | p.set(c.role, c.edit) |
| 183 | _, codes := p.check(t, zeroCounts(), PhasePreInitialize) |
| 184 | wantCodes(t, codes, c.code) |
| 185 | }) |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | func TestHomePreflightRefusesProposedNotOne(t *testing.T) { |
| 190 | for _, id := range []int64{0, 2, 7} { |
| 191 | p := newPreflightFixture(t) |
| 192 | p.set(homeop.Directory, func(in *homeop.Inspection) { in.TeamID = id }) |
| 193 | _, codes := p.check(t, zeroCounts(), PhasePreInitialize) |
| 194 | wantCodes(t, codes, "proposed-not-one") |
| 195 | |
| 196 | _, counts := p.initialized(t) |
| 197 | _, codes = p.check(t, counts, PhasePrePlanA) |
| 198 | wantCodes(t, codes, "proposed-not-one") |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | func TestHomePreflightRefusesMissingCount(t *testing.T) { |
| 203 | for _, phase := range []string{PhasePreInitialize, PhasePrePlanA} { |
| 204 | for _, tb := range wantTables { |
| 205 | t.Run(phase+"/"+tb, func(t *testing.T) { |
| 206 | p := newPreflightFixture(t) |
| 207 | counts := zeroCounts() |
| 208 | if phase == PhasePrePlanA { |
| 209 | _, counts = p.initialized(t) |
| 210 | } |
| 211 | delete(counts, tb) |
| 212 | r, codes := p.check(t, counts, phase) |
| 213 | wantCodes(t, codes, "count-missing-"+tb) |
| 214 | if _, ok := r.Counts[tb]; ok { |
| 215 | t.Fatalf("record holds a count for %s that was not pasted", tb) |
| 216 | } |
| 217 | }) |
| 218 | } |
| 219 | } |
| 220 | p := newPreflightFixture(t) |
| 221 | _, codes := p.check(t, nil, PhasePreInitialize) |
| 222 | var want []string |
| 223 | for _, tb := range wantTables { |
| 224 | want = append(want, "count-missing-"+tb) |
| 225 | } |
| 226 | wantCodes(t, codes, want...) |
| 227 | } |
| 228 | |
| 229 | func TestHomePreflightPrePlanAAcceptsOwnInitialize(t *testing.T) { |
| 230 | p := newPreflightFixture(t) |
| 231 | _, counts := p.initialized(t) |
| 232 | r, codes := p.check(t, counts, PhasePrePlanA) |
| 233 | wantCodes(t, codes) |
| 234 | if r.Phase != PhasePrePlanA || r.DirectorySeq != 1 || r.CredentialSeq != 0 || r.Generation == nil || r.ProposedID != 1 || !reflect.DeepEqual(r.Counts, counts) { |
| 235 | t.Fatalf("record = %+v", r) |
| 236 | } |
| 237 | |
| 238 | // The credential stream may have moved, if Alta's own journal moved it. |
| 239 | credHead := homeop.Token() |
| 240 | p.set(homeop.Credential, func(in *homeop.Inspection) { in.Sequence, in.Head = 3, credHead }) |
| 241 | if err := p.ps.SetStream(context.Background(), homeop.Credential, 3, credHead); err != nil { |
| 242 | t.Fatal(err) |
| 243 | } |
| 244 | r, codes = p.check(t, counts, PhasePrePlanA) |
| 245 | wantCodes(t, codes) |
| 246 | if r.CredentialSeq != 3 || r.CredentialHead != credHead { |
| 247 | t.Fatalf("record = %+v", r) |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | // A pasted table HomeQueries does not ask for is a typo or a stray line: |
| 252 | // refused, with one fixed code, and not recorded. |
| 253 | func TestHomePreflightRefusesUnknownTable(t *testing.T) { |
| 254 | for _, phase := range []string{PhasePreInitialize, PhasePrePlanA} { |
| 255 | t.Run(phase, func(t *testing.T) { |
| 256 | p := newPreflightFixture(t) |
| 257 | counts := zeroCounts() |
| 258 | if phase == PhasePrePlanA { |
| 259 | _, counts = p.initialized(t) |
| 260 | } |
| 261 | counts["extra"] = 0 |
| 262 | r, codes := p.check(t, counts, phase) |
| 263 | wantCodes(t, codes, "count-unknown-table") |
| 264 | if _, ok := r.Counts["extra"]; ok { |
| 265 | t.Fatal("record holds a table HomeQueries does not ask for") |
| 266 | } |
| 267 | |
| 268 | delete(counts, "extra") |
| 269 | delete(counts, "teams") |
| 270 | counts["team"] = 0 |
| 271 | _, codes = p.check(t, counts, phase) |
| 272 | wantCodes(t, codes, "count-missing-teams", "count-unknown-table") |
| 273 | }) |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | // Before Plan A, a pending or open plan on either role is refused: the |
| 278 | // spec allows none, and Plan A must be the only plan in flight. |
| 279 | func TestHomePreflightPrePlanARefusesPendingOrOpenPlan(t *testing.T) { |
| 280 | cases := []struct { |
| 281 | name, role string |
| 282 | edit func(*homeop.Inspection) |
| 283 | code string |
| 284 | }{ |
| 285 | {"credential-pending", homeop.Credential, func(in *homeop.Inspection) { in.PendingPlan = homeop.Token() }, "plan-pending"}, |
| 286 | {"directory-pending", homeop.Directory, func(in *homeop.Inspection) { in.PendingPlan = homeop.Token() }, "plan-pending"}, |
| 287 | {"credential-open", homeop.Credential, func(in *homeop.Inspection) { in.OpenPlan = homeop.Token() }, "plan-open"}, |
| 288 | {"directory-open", homeop.Directory, func(in *homeop.Inspection) { in.OpenPlan = homeop.Token() }, "plan-open"}, |
| 289 | } |
| 290 | for _, c := range cases { |
| 291 | t.Run(c.name, func(t *testing.T) { |
| 292 | p := newPreflightFixture(t) |
| 293 | _, counts := p.initialized(t) |
| 294 | p.set(c.role, c.edit) |
| 295 | r, codes := p.check(t, counts, PhasePrePlanA) |
| 296 | wantCodes(t, codes, c.code) |
| 297 | if r.Pending != (c.code == "plan-pending") || r.Open != (c.code == "plan-open") { |
| 298 | t.Fatalf("record pending=%v open=%v", r.Pending, r.Open) |
| 299 | } |
| 300 | }) |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | func TestHomePreflightPrePlanARefusesForeignDirectoryHead(t *testing.T) { |
| 305 | gen := homeop.Token() |
| 306 | cases := []struct { |
| 307 | name string |
| 308 | edit func(*testing.T, *preflightFixture) |
| 309 | code string |
| 310 | }{ |
| 311 | {"other-head", func(t *testing.T, p *preflightFixture) { |
| 312 | p.set(homeop.Directory, func(in *homeop.Inspection) { in.Head = homeop.Token() }) |
| 313 | }, "directory-stream-foreign"}, |
| 314 | {"further-sequence", func(t *testing.T, p *preflightFixture) { |
| 315 | p.set(homeop.Directory, func(in *homeop.Inspection) { in.Sequence = 2 }) |
| 316 | }, "directory-stream-foreign"}, |
| 317 | {"journal-beyond-initialize", func(t *testing.T, p *preflightFixture) { |
| 318 | h := homeop.Token() |
| 319 | p.set(homeop.Directory, func(in *homeop.Inspection) { in.Sequence, in.Head = 2, h }) |
| 320 | if err := p.ps.SetStream(context.Background(), homeop.Directory, 2, h); err != nil { |
| 321 | t.Fatal(err) |
| 322 | } |
| 323 | }, "directory-stream-foreign"}, |
| 324 | {"journal-at-zero", func(t *testing.T, p *preflightFixture) { |
| 325 | p.set(homeop.Directory, func(in *homeop.Inspection) { in.Sequence, in.Head = 0, "" }) |
| 326 | if err := p.ps.SetStream(context.Background(), homeop.Directory, 0, ""); err != nil { |
| 327 | t.Fatal(err) |
| 328 | } |
| 329 | }, "directory-stream-foreign"}, |
| 330 | {"credential-foreign", func(t *testing.T, p *preflightFixture) { |
| 331 | p.set(homeop.Credential, func(in *homeop.Inspection) { in.Sequence, in.Head = 1, homeop.Token() }) |
| 332 | }, "credential-stream-foreign"}, |
| 333 | {"credential-other-head", func(t *testing.T, p *preflightFixture) { |
| 334 | p.set(homeop.Credential, func(in *homeop.Inspection) { in.Sequence, in.Head = 1, homeop.Token() }) |
| 335 | if err := p.ps.SetStream(context.Background(), homeop.Credential, 1, homeop.Token()); err != nil { |
| 336 | t.Fatal(err) |
| 337 | } |
| 338 | }, "credential-stream-foreign"}, |
| 339 | {"no-generation", func(t *testing.T, p *preflightFixture) { |
| 340 | p.set(homeop.Directory, func(in *homeop.Inspection) { in.Generation = nil }) |
| 341 | }, "generation-missing"}, |
| 342 | {"generation-kept", func(t *testing.T, p *preflightFixture) { |
| 343 | p.set(homeop.Directory, func(in *homeop.Inspection) { in.Generation = &gen }) |
| 344 | }, ""}, |
| 345 | } |
| 346 | for _, c := range cases { |
| 347 | t.Run(c.name, func(t *testing.T) { |
| 348 | p := newPreflightFixture(t) |
| 349 | _, counts := p.initialized(t) |
| 350 | c.edit(t, p) |
| 351 | _, codes := p.check(t, counts, PhasePrePlanA) |
| 352 | if c.code == "" { |
| 353 | wantCodes(t, codes) |
| 354 | return |
| 355 | } |
| 356 | wantCodes(t, codes, c.code) |
| 357 | }) |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | func TestHomePreflightPrePlanARefusesExtraReceipt(t *testing.T) { |
| 362 | for _, tb := range wantTables { |
| 363 | for _, n := range []int64{0, 1, 2} { |
| 364 | p := newPreflightFixture(t) |
| 365 | _, counts := p.initialized(t) |
| 366 | want := int64(0) |
| 367 | if tb == "roster_generation" || tb == "roster_operator_receipts" { |
| 368 | want = 1 |
| 369 | } |
| 370 | counts[tb] = n |
| 371 | _, codes := p.check(t, counts, PhasePrePlanA) |
| 372 | if n == want { |
| 373 | wantCodes(t, codes) |
| 374 | } else { |
| 375 | wantCodes(t, codes, "count-unexpected-"+tb) |
| 376 | } |
| 377 | } |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | // A fresh fake Home, reached through signed inspects it verifies, passes |
| 382 | // pre-initialize. |
| 383 | func TestHomePreflightPreInitializeAcceptsFreshHome(t *testing.T) { |
| 384 | key, err := family.Generate() |
| 385 | if err != nil { |
| 386 | t.Fatal(err) |
| 387 | } |
| 388 | pre := homeop.Token() |
| 389 | home := fakehome.New(key.SignPub(), pre, "https://id.example.test", "https://dir.example.test", clock) |
| 390 | roles := map[string]homeop.Role{} |
| 391 | for r, origin := range map[string]string{homeop.Credential: "https://id.example.test", homeop.Directory: "https://dir.example.test"} { |
| 392 | srv := httptest.NewServer(home.Handler(r)) |
| 393 | t.Cleanup(srv.Close) |
| 394 | pins := home.Pins(r) |
| 395 | roles[r] = homeop.Role{Name: r, Origin: origin, URL: srv.URL, Installation: pins.Installation, Registry: pins.Registry, Device: pins.Device} |
| 396 | } |
| 397 | ps, _ := journal(t, filepath.Join(t.TempDir(), "alta.db")) |
| 398 | r, codes, err := CheckHome(context.Background(), &homeop.Client{Key: key, Prefilter: pre, Roles: roles, Now: clock}, ps, zeroCounts(), PhasePreInitialize) |
| 399 | if err != nil { |
| 400 | t.Fatal(err) |
| 401 | } |
| 402 | wantCodes(t, codes) |
| 403 | if r.ProposedID != 1 || r.ProposedSQID == "" { |
| 404 | t.Fatalf("record = %+v", r) |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | func TestHomePreflightErrors(t *testing.T) { |
| 409 | p := newPreflightFixture(t) |
| 410 | for _, phase := range []string{"", "plan-a", "pre-plan-b"} { |
| 411 | if _, _, err := CheckHome(context.Background(), p.client, p.ps, zeroCounts(), phase); err == nil { |
| 412 | t.Fatalf("phase %q accepted", phase) |
| 413 | } |
| 414 | } |
| 415 | // Each role failing alone gives that role's fixed error, naming no |
| 416 | // endpoint of either role. |
| 417 | for _, role := range []string{homeop.Credential, homeop.Directory} { |
| 418 | p.home.status = map[string]int{role: http.StatusServiceUnavailable} |
| 419 | _, codes, err := CheckHome(context.Background(), p.client, p.ps, zeroCounts(), PhasePreInitialize) |
| 420 | if err == nil || codes != nil { |
| 421 | t.Fatalf("%s unavailable gave codes %q, err %v", role, codes, err) |
| 422 | } |
| 423 | if want := "adopt: " + role + " inspect failed"; err.Error() != want { |
| 424 | t.Fatalf("error = %q, want %q", err, want) |
| 425 | } |
| 426 | for _, r := range p.client.Roles { |
| 427 | if strings.Contains(err.Error(), r.URL) || strings.Contains(err.Error(), r.Origin) { |
| 428 | t.Fatalf("error names an endpoint: %v", err) |
| 429 | } |
| 430 | } |
| 431 | } |
| 432 | } |
| 433 | |