| 1 | package thintest |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "net/http" |
| 6 | "slices" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/equipo" |
| 11 | "amadan.net/oficina/equipo/internal/wire" |
| 12 | ) |
| 13 | |
| 14 | // Research's site inventory (Research spec §3.3; decision R4 as refined, |
| 15 | // slice R3). Equipo detects the primary's own addresses itself: those |
| 16 | // its hello reports, and the one the instance saw its stream connect |
| 17 | // from (the edge's own X-Forwarded-For element, never one a client |
| 18 | // wrote). A Research step waits until every detected address is inside |
| 19 | // a prefix an owner confirmed on a one-time card, and the dispatch |
| 20 | // carries the confirmed prefixes. |
| 21 | |
| 22 | // until polls cond (a database state the runner stream reaches in its |
| 23 | // own time). |
| 24 | func (r *toolRig) until(what string, cond func() bool) { |
| 25 | r.t.Helper() |
| 26 | deadline := time.Now().Add(15 * time.Second) |
| 27 | for !cond() { |
| 28 | if time.Now().After(deadline) { |
| 29 | r.t.Fatalf("timed out waiting for %s", what) |
| 30 | } |
| 31 | time.Sleep(20 * time.Millisecond) |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | // researchHello is the rig's primary hello at protocol 13 reporting addrs. |
| 36 | func (r *toolRig) researchHello(addrs ...string) wire.Hello { |
| 37 | h := primaryAt(toolHello(r.runner.Welcome.Generation), wire.ProtocolCurrent) |
| 38 | h.Capabilities.Research = &wire.ResearchCapability{Addresses: append([]string{}, addrs...)} |
| 39 | return h |
| 40 | } |
| 41 | |
| 42 | // addresses sends a hello reporting addrs and waits until the instance |
| 43 | // holds want of them as the runner's interface addresses. |
| 44 | func (r *toolRig) addresses(want int, addrs ...string) { |
| 45 | r.t.Helper() |
| 46 | if err := r.runner.Send(r.ctx, "h-inv-"+itoa(len(r.runner.Sent)), wire.FrameHello, r.researchHello(addrs...)); err != nil { |
| 47 | r.t.Fatal(err) |
| 48 | } |
| 49 | r.until("the hello's addresses", func() bool { |
| 50 | return r.rows("SELECT count(*) FROM chat_research_addresses WHERE runner_id = ? AND source = 'interface'", r.runner.Welcome.RunnerID) == want && |
| 51 | (len(addrs) == 0 || want == 0 || r.rows("SELECT count(*) FROM chat_research_addresses WHERE runner_id = ? AND source = 'interface' AND address = ?", r.runner.Welcome.RunnerID, firstValid(addrs)) == 1) |
| 52 | }) |
| 53 | } |
| 54 | |
| 55 | func firstValid(addrs []string) string { |
| 56 | for _, a := range addrs { |
| 57 | if wire.ValidResearchAddress(a) { |
| 58 | return a |
| 59 | } |
| 60 | } |
| 61 | return "" |
| 62 | } |
| 63 | |
| 64 | // redial reconnects the rig's primary (same generation) through an edge |
| 65 | // that wrote forwarded, reporting addrs in its first hello. |
| 66 | func (r *toolRig) redial(forwarded string, addrs ...string) { |
| 67 | r.t.Helper() |
| 68 | var h http.Header |
| 69 | if forwarded != "" { |
| 70 | h = http.Header{"X-Forwarded-For": {forwarded}} |
| 71 | } |
| 72 | f, err := DialRunnerFrom(r.ctx, r.inst.URL, r.rig.runner, r.researchHello(addrs...), h) |
| 73 | if err != nil { |
| 74 | r.t.Fatal(err) |
| 75 | } |
| 76 | r.t.Cleanup(f.Close) |
| 77 | r.runner = f |
| 78 | } |
| 79 | |
| 80 | // observed is the address the instance recorded for the rig's primary's |
| 81 | // stream connection, "" for none. |
| 82 | func (r *toolRig) observed() string { |
| 83 | r.t.Helper() |
| 84 | var out []string |
| 85 | rows, err := r.inst.DB.Writer().Query("SELECT address FROM chat_research_addresses WHERE runner_id = ? AND source = 'observed'", r.runner.Welcome.RunnerID) |
| 86 | if err != nil { |
| 87 | r.t.Fatal(err) |
| 88 | } |
| 89 | defer rows.Close() |
| 90 | for rows.Next() { |
| 91 | var a string |
| 92 | if err := rows.Scan(&a); err != nil { |
| 93 | r.t.Fatal(err) |
| 94 | } |
| 95 | out = append(out, a) |
| 96 | } |
| 97 | if len(out) > 1 { |
| 98 | r.t.Fatalf("more than one observed address %v", out) |
| 99 | } |
| 100 | if len(out) == 0 { |
| 101 | return "" |
| 102 | } |
| 103 | return out[0] |
| 104 | } |
| 105 | |
| 106 | func (r *toolRig) inventoryCard(state string) wire.Card { |
| 107 | r.t.Helper() |
| 108 | var card wire.Card |
| 109 | r.wait("inventory card "+state, func(c *Conversation) bool { |
| 110 | for _, k := range c.Cards { |
| 111 | if k.Kind == wire.CardResearchInventory && k.State == state { |
| 112 | card = k |
| 113 | return true |
| 114 | } |
| 115 | } |
| 116 | return false |
| 117 | }) |
| 118 | return card |
| 119 | } |
| 120 | |
| 121 | func (r *toolRig) inventoryCards() int { |
| 122 | r.t.Helper() |
| 123 | return r.rows("SELECT count(*) FROM chat_cards WHERE kind = ?", wire.CardResearchInventory) |
| 124 | } |
| 125 | |
| 126 | // namedTask records a separate change task with a title of its own (the |
| 127 | // same title twice is the same task). |
| 128 | func (r *toolRig) namedTask(key string) string { |
| 129 | r.t.Helper() |
| 130 | return taskID(r.t, r.call(key+"-rec", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Shop mockups, part " + key, "brief": "Mockups that match the shop.", "separate": true})) |
| 131 | } |
| 132 | |
| 133 | // waitingTask records a task with Research at its start and starts it: |
| 134 | // the Research step waits for the inventory, Engineering is held. |
| 135 | func (r *toolRig) waitingTask(key string) (string, wire.Step) { |
| 136 | r.t.Helper() |
| 137 | id := r.namedTask(key) |
| 138 | if res := r.research(key+"-r", id); res.IsError { |
| 139 | r.t.Fatalf("research %+v", res) |
| 140 | } |
| 141 | r.begin(key+"-start", id) |
| 142 | r.heldForResearch(id) |
| 143 | s := r.newest(id, wire.SpecialistResearch) |
| 144 | if s.State != wire.StepQueued || s.Placement != wire.PlacementInventory || s.RunnerID != "" { |
| 145 | r.t.Fatalf("not waiting for the inventory %+v", s) |
| 146 | } |
| 147 | return id, s |
| 148 | } |
| 149 | |
| 150 | // TestResearchInventoryCard: the card lists every detected address (the |
| 151 | // hello's valid ones and the observed one), once per primary however |
| 152 | // many steps wait; another person cannot answer it, nor another answer, |
| 153 | // nor a stale revision; Confirm records the prefixes with who and when, |
| 154 | // audits it, and dispatches every waiting step with them. |
| 155 | func TestResearchInventoryCard(t *testing.T) { |
| 156 | r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) |
| 157 | r.researchOn() |
| 158 | r.inst.Store.Chat().SetForwardedHops(1) |
| 159 | // A client-written element on the left is never the one used; the |
| 160 | // edge's own element (the last) is. |
| 161 | r.redial("198.51.100.1, 81.2.69.9", "2a01:4f8:1:2::7", "81.2.69.7", "10.0.0.5", "fe80::1", "bogus", "81.2.69.007") |
| 162 | r.until("the observed address", func() bool { return r.observed() == "81.2.69.9" }) |
| 163 | a, _ := r.waitingTask("a") |
| 164 | card := r.inventoryCard(wire.CardOpen) |
| 165 | v := card.Inventory |
| 166 | want := []string{"81.2.69.7", "81.2.69.9", "2a01:4f8:1:2::7"} |
| 167 | if v == nil || v.RunnerID != r.runner.Welcome.RunnerID || !slices.Equal(v.Addresses, want) || card.Question == "" || card.TaskID != a || !slices.Equal(card.Options, []string{wire.ChoiceConfirm}) { |
| 168 | t.Fatalf("card %+v %+v", card, v) |
| 169 | } |
| 170 | if r.researchDispatches() != 0 { |
| 171 | t.Fatal("dispatched before Confirm") |
| 172 | } |
| 173 | // Only valid addresses are recorded at all. |
| 174 | if n := r.rows("SELECT count(*) FROM chat_research_addresses WHERE runner_id = ?", r.runner.Welcome.RunnerID); n != 3 { |
| 175 | t.Fatalf("%d addresses recorded", n) |
| 176 | } |
| 177 | // A second waiting step does not raise a second card. |
| 178 | b, _ := r.waitingTask("b") |
| 179 | if n := r.inventoryCards(); n != 1 { |
| 180 | t.Fatalf("%d inventory cards", n) |
| 181 | } |
| 182 | r.get(r.inst.SessionFor(t, Owner), "/conversation", 200) |
| 183 | r.get(r.inst.SessionFor(t, Owner), "/tasks/"+a, 200) |
| 184 | for _, rev := range []int64{card.Revision + 1, card.Revision - 1} { |
| 185 | if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, rev); Status(err) != 409 { |
| 186 | t.Fatalf("revision %d: %v", rev, err) |
| 187 | } |
| 188 | } |
| 189 | if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAllow, card.Revision); Status(err) != 422 { |
| 190 | t.Fatalf("another answer: %v", err) |
| 191 | } |
| 192 | m := personToolRigAt(t, r, "member@example.com", equipo.RoleMember, wire.ProtocolCurrent) |
| 193 | if _, err := m.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, card.Revision); Status(err) != 404 { |
| 194 | t.Fatalf("a teammate confirmed: %v", err) |
| 195 | } |
| 196 | if n := r.rows("SELECT count(*) FROM chat_research_prefixes"); n != 0 { |
| 197 | t.Fatalf("%d prefixes before Confirm", n) |
| 198 | } |
| 199 | if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, card.Revision); err != nil { |
| 200 | t.Fatal(err) |
| 201 | } |
| 202 | if done := r.inventoryCard(wire.CardAnswered); done.Choice != wire.ChoiceConfirm { |
| 203 | t.Fatalf("answered %+v", done) |
| 204 | } |
| 205 | prefixes := []string{"2a01:4f8:1:2::/64", "2a01:4f8:1:2::7/128", "81.2.69.7/32", "81.2.69.9/32"} |
| 206 | for _, p := range prefixes { |
| 207 | if n := r.rows("SELECT count(*) FROM chat_research_prefixes WHERE runner_id = ? AND prefix = ? AND confirmed_by = ? AND confirmed_at IS NOT NULL AND card_id = ?", r.runner.Welcome.RunnerID, p, Owner, card.ID); n != 1 { |
| 208 | t.Fatalf("prefix %s: %d", p, n) |
| 209 | } |
| 210 | } |
| 211 | if n := r.rows("SELECT count(*) FROM chat_research_prefixes"); n != len(prefixes) { |
| 212 | t.Fatalf("%d prefixes", n) |
| 213 | } |
| 214 | if n := r.rows("SELECT count(*) FROM audit_events WHERE actor = ? AND kind = 'research.inventory_confirmed' AND record_id LIKE ?", Owner, r.runner.Welcome.RunnerID+"%"); n != 1 { |
| 215 | t.Fatalf("%d audit rows", n) |
| 216 | } |
| 217 | got := map[string]bool{} |
| 218 | for range 2 { |
| 219 | d := r.nextDispatch() |
| 220 | if d.Specialist != wire.SpecialistResearch || d.Research == nil || !slices.Equal(d.Research.Inventory, prefixes) { |
| 221 | t.Fatalf("dispatch after Confirm %+v", d) |
| 222 | } |
| 223 | got[d.TaskID] = true |
| 224 | } |
| 225 | if !got[a] || !got[b] { |
| 226 | t.Fatalf("dispatched %v", got) |
| 227 | } |
| 228 | for _, id := range []string{a, b} { |
| 229 | if s := r.newest(id, wire.SpecialistResearch); s.Placement != "" || s.RunnerID != r.runner.Welcome.RunnerID { |
| 230 | t.Fatalf("after Confirm %+v", s) |
| 231 | } |
| 232 | r.heldForResearch(id) |
| 233 | } |
| 234 | if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, card.Revision+1); Status(err) != 409 { |
| 235 | t.Fatalf("confirmed twice: %v", err) |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | // TestResearchInventoryOwner: the card goes to the task's creator while |
| 240 | // they are an owner; only they answer it, and only while they are still |
| 241 | // an owner, read in the answer's transaction. |
| 242 | func TestResearchInventoryOwner(t *testing.T) { |
| 243 | a := newToolRigAt(t, wire.ProtocolCurrent) |
| 244 | a.researchOn() |
| 245 | b := personToolRigAt(t, a, "second@example.com", equipo.RoleOwner, wire.ProtocolCurrent) |
| 246 | b.addresses(1, "81.2.69.70") |
| 247 | id := b.shopTask("g") |
| 248 | if res := b.research("g-r", id, "https://maps.example.org/place/shop"); res.IsError { |
| 249 | t.Fatalf("request %+v", res) |
| 250 | } |
| 251 | src := b.sourcesCard(wire.CardOpen) |
| 252 | if _, err := b.client.Answer(b.ctx, src.ID, wire.ChoiceAllow, src.Revision); err != nil { |
| 253 | t.Fatal(err) |
| 254 | } |
| 255 | b.begin("g-start", id) |
| 256 | card := b.inventoryCard(wire.CardOpen) |
| 257 | if card.Inventory == nil || card.Inventory.RunnerID != b.runner.Welcome.RunnerID || !slices.Equal(card.Inventory.Addresses, []string{"81.2.69.70"}) { |
| 258 | t.Fatalf("B's card %+v", card) |
| 259 | } |
| 260 | if _, err := a.client.Answer(a.ctx, card.ID, wire.ChoiceConfirm, card.Revision); Status(err) != 404 { |
| 261 | t.Fatalf("another owner confirmed: %v", err) |
| 262 | } |
| 263 | var revision int64 |
| 264 | if err := a.inst.DB.Writer().QueryRow("SELECT revision FROM members WHERE address = ?", "second@example.com").Scan(&revision); err != nil { |
| 265 | t.Fatal(err) |
| 266 | } |
| 267 | if err := a.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, "second@example.com", equipo.RoleMember, true, revision); err != nil { |
| 268 | t.Fatal(err) |
| 269 | } |
| 270 | if _, err := b.client.Answer(b.ctx, card.ID, wire.ChoiceConfirm, card.Revision); Status(err) != 403 { |
| 271 | t.Fatalf("a former owner confirmed: %v", err) |
| 272 | } |
| 273 | if n := a.rows("SELECT count(*) FROM chat_research_prefixes"); n != 0 { |
| 274 | t.Fatalf("%d prefixes without an owner", n) |
| 275 | } |
| 276 | if b.researchDispatches() != 0 { |
| 277 | t.Fatal("dispatched without an owner's Confirm") |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | // TestResearchInventoryNewAddress: an address the primary reports later |
| 282 | // is outside the confirmed prefixes, so the next step waits again with a |
| 283 | // new card listing every address; an address that changes while that |
| 284 | // card is open moves its revision, so an answer to the old list is a |
| 285 | // conflict; Confirm then dispatches. |
| 286 | func TestResearchInventoryNewAddress(t *testing.T) { |
| 287 | r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) |
| 288 | r.researchOn() |
| 289 | r.inventoryOn() |
| 290 | r.addresses(2, "81.2.69.7", "2a01:4f8:5:6::1") |
| 291 | _, s := r.waitingTask("a") |
| 292 | card := r.inventoryCard(wire.CardOpen) |
| 293 | if !slices.Equal(card.Inventory.Addresses, []string{"81.2.69.7", "2a01:4f8:5:6::1"}) { |
| 294 | t.Fatalf("card %+v", card.Inventory) |
| 295 | } |
| 296 | // Another new address while the card is open. |
| 297 | r.addresses(3, "81.2.69.7", "2a01:4f8:5:6::1", "81.2.69.21") |
| 298 | var moved wire.Card |
| 299 | r.wait("the card's new list", func(c *Conversation) bool { |
| 300 | moved = c.Cards[card.ID] |
| 301 | return moved.Revision > card.Revision |
| 302 | }) |
| 303 | if !slices.Equal(moved.Inventory.Addresses, []string{"81.2.69.7", "81.2.69.21", "2a01:4f8:5:6::1"}) || r.inventoryCards() != 1 { |
| 304 | t.Fatalf("moved %+v (%d cards)", moved.Inventory, r.inventoryCards()) |
| 305 | } |
| 306 | if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, card.Revision); Status(err) != 409 { |
| 307 | t.Fatalf("Confirm of the old list: %v", err) |
| 308 | } |
| 309 | if r.researchDispatches() != 0 || r.rows("SELECT count(*) FROM chat_research_prefixes WHERE prefix = '81.2.69.21/32'") != 0 { |
| 310 | t.Fatal("the old list was confirmed") |
| 311 | } |
| 312 | if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, moved.Revision); err != nil { |
| 313 | t.Fatal(err) |
| 314 | } |
| 315 | d := r.nextDispatch() |
| 316 | if d.StepID != s.ID || !slices.Equal(d.Research.Inventory, []string{"2a01:4f8:5:6::/64", "2a01:4f8:5:6::1/128", "81.2.69.21/32", "81.2.69.7/32"}) { |
| 317 | t.Fatalf("dispatch %+v", d.Research) |
| 318 | } |
| 319 | // Covered addresses raise nothing more. |
| 320 | r.addresses(1, "81.2.69.21") |
| 321 | r.waitingTaskDispatched("b") |
| 322 | if n := r.inventoryCards(); n != 1 { |
| 323 | t.Fatalf("%d inventory cards", n) |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | // waitingTaskDispatched records and starts a task whose Research goes at |
| 328 | // once (the inventory covers every detected address). |
| 329 | func (r *toolRig) waitingTaskDispatched(key string) { |
| 330 | r.t.Helper() |
| 331 | id := r.namedTask(key) |
| 332 | r.research(key+"-r", id) |
| 333 | r.begin(key+"-start", id) |
| 334 | if d := r.nextDispatch(); d.Specialist != wire.SpecialistResearch || d.TaskID != id { |
| 335 | r.t.Fatalf("not dispatched at once %+v", d) |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | // TestResearchInventoryObservedAddress: the observed address is the |
| 340 | // edge's own X-Forwarded-For element, and only a valid global address; |
| 341 | // a private or garbage one, or anything with no edge in front (the |
| 342 | // default off CARLOS), is ignored, and the connection's own address is |
| 343 | // used only when it is global (never loopback). |
| 344 | func TestResearchInventoryObservedAddress(t *testing.T) { |
| 345 | r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) |
| 346 | for _, c := range []struct { |
| 347 | hops int |
| 348 | forwarded, want string |
| 349 | }{ |
| 350 | {0, "81.2.69.9", ""}, |
| 351 | {1, "81.2.69.9", "81.2.69.9"}, |
| 352 | {1, "10.1.2.3", ""}, |
| 353 | {1, "81.2.69.9, 192.168.0.4", ""}, |
| 354 | {1, "garbage", ""}, |
| 355 | {1, "100.64.0.1, ::ffff:81.2.69.5", "81.2.69.5"}, |
| 356 | // ValidResearchAddress is the rule, the fetcher's public-address |
| 357 | // one: a shared (CGNAT or tailnet) address is no public egress and |
| 358 | // never counts (Astra security finding 2). |
| 359 | {1, "81.2.69.9, 100.64.0.1", ""}, |
| 360 | {1, "100.100.1.2", ""}, |
| 361 | {1, "203.0.113.9", ""}, |
| 362 | {1, "2A01:4F8::9", "2a01:4f8::9"}, |
| 363 | {1, "", ""}, |
| 364 | {1, "127.0.0.1", ""}, |
| 365 | } { |
| 366 | r.inst.Store.Chat().SetForwardedHops(c.hops) |
| 367 | // Connect records it before the welcome. |
| 368 | r.redial(c.forwarded, "81.2.69.7") |
| 369 | if got := r.observed(); got != c.want { |
| 370 | t.Errorf("%d hops, %q: observed %q, want %q", c.hops, c.forwarded, got, c.want) |
| 371 | } |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | // TestResearchInventoryOlderPrimary (mixed versions): a step waiting for |
| 376 | // the inventory whose primary comes back at 11 is not left waiting for a |
| 377 | // card it cannot use: it ends research_unsupported and Engineering goes. |
| 378 | func TestResearchInventoryOlderPrimary(t *testing.T) { |
| 379 | r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) |
| 380 | r.researchOn() |
| 381 | r.addresses(1, "81.2.69.7") |
| 382 | id, _ := r.waitingTask("a") |
| 383 | r.inventoryCard(wire.CardOpen) |
| 384 | old, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, primaryAt(wire.Hello{Generation: r.runner.Welcome.Generation, Repos: []string{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test"}}, wire.ProtocolPreviewHost)) |
| 385 | if err != nil { |
| 386 | t.Fatal(err) |
| 387 | } |
| 388 | defer old.Close() |
| 389 | _, body, err := old.Expect(r.ctx, wire.FrameDispatch) |
| 390 | if err != nil { |
| 391 | t.Fatal(err) |
| 392 | } |
| 393 | if e := body.(*wire.DispatchCommand); e.Specialist != wire.SpecialistEngineering || e.TaskID != id { |
| 394 | t.Fatalf("to the older runner %+v", e) |
| 395 | } |
| 396 | if s := r.newest(id, wire.SpecialistResearch); s.State != wire.StepCancelled || s.Reason != wire.ReasonResearchUnsupported { |
| 397 | t.Fatalf("at 11 %+v", s) |
| 398 | } |
| 399 | if r.researchDispatches() != 0 { |
| 400 | t.Fatal("a research dispatch for a primary at 11") |
| 401 | } |
| 402 | } |
| 403 | |