package thintest import ( "context" "net/http" "slices" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // Research's site inventory (Research spec ยง3.3; decision R4 as refined, // slice R3). Equipo detects the primary's own addresses itself: those // its hello reports, and the one the instance saw its stream connect // from (the edge's own X-Forwarded-For element, never one a client // wrote). A Research step waits until every detected address is inside // a prefix an owner confirmed on a one-time card, and the dispatch // carries the confirmed prefixes. // until polls cond (a database state the runner stream reaches in its // own time). func (r *toolRig) until(what string, cond func() bool) { r.t.Helper() deadline := time.Now().Add(15 * time.Second) for !cond() { if time.Now().After(deadline) { r.t.Fatalf("timed out waiting for %s", what) } time.Sleep(20 * time.Millisecond) } } // researchHello is the rig's primary hello at protocol 13 reporting addrs. func (r *toolRig) researchHello(addrs ...string) wire.Hello { h := primaryAt(toolHello(r.runner.Welcome.Generation), wire.ProtocolCurrent) h.Capabilities.Research = &wire.ResearchCapability{Addresses: append([]string{}, addrs...)} return h } // addresses sends a hello reporting addrs and waits until the instance // holds want of them as the runner's interface addresses. func (r *toolRig) addresses(want int, addrs ...string) { r.t.Helper() if err := r.runner.Send(r.ctx, "h-inv-"+itoa(len(r.runner.Sent)), wire.FrameHello, r.researchHello(addrs...)); err != nil { r.t.Fatal(err) } r.until("the hello's addresses", func() bool { return r.rows("SELECT count(*) FROM chat_research_addresses WHERE runner_id = ? AND source = 'interface'", r.runner.Welcome.RunnerID) == want && (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) }) } func firstValid(addrs []string) string { for _, a := range addrs { if wire.ValidResearchAddress(a) { return a } } return "" } // redial reconnects the rig's primary (same generation) through an edge // that wrote forwarded, reporting addrs in its first hello. func (r *toolRig) redial(forwarded string, addrs ...string) { r.t.Helper() var h http.Header if forwarded != "" { h = http.Header{"X-Forwarded-For": {forwarded}} } f, err := DialRunnerFrom(r.ctx, r.inst.URL, r.rig.runner, r.researchHello(addrs...), h) if err != nil { r.t.Fatal(err) } r.t.Cleanup(f.Close) r.runner = f } // observed is the address the instance recorded for the rig's primary's // stream connection, "" for none. func (r *toolRig) observed() string { r.t.Helper() var out []string rows, err := r.inst.DB.Writer().Query("SELECT address FROM chat_research_addresses WHERE runner_id = ? AND source = 'observed'", r.runner.Welcome.RunnerID) if err != nil { r.t.Fatal(err) } defer rows.Close() for rows.Next() { var a string if err := rows.Scan(&a); err != nil { r.t.Fatal(err) } out = append(out, a) } if len(out) > 1 { r.t.Fatalf("more than one observed address %v", out) } if len(out) == 0 { return "" } return out[0] } func (r *toolRig) inventoryCard(state string) wire.Card { r.t.Helper() var card wire.Card r.wait("inventory card "+state, func(c *Conversation) bool { for _, k := range c.Cards { if k.Kind == wire.CardResearchInventory && k.State == state { card = k return true } } return false }) return card } func (r *toolRig) inventoryCards() int { r.t.Helper() return r.rows("SELECT count(*) FROM chat_cards WHERE kind = ?", wire.CardResearchInventory) } // namedTask records a separate change task with a title of its own (the // same title twice is the same task). func (r *toolRig) namedTask(key string) string { r.t.Helper() 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})) } // waitingTask records a task with Research at its start and starts it: // the Research step waits for the inventory, Engineering is held. func (r *toolRig) waitingTask(key string) (string, wire.Step) { r.t.Helper() id := r.namedTask(key) if res := r.research(key+"-r", id); res.IsError { r.t.Fatalf("research %+v", res) } r.begin(key+"-start", id) r.heldForResearch(id) s := r.newest(id, wire.SpecialistResearch) if s.State != wire.StepQueued || s.Placement != wire.PlacementInventory || s.RunnerID != "" { r.t.Fatalf("not waiting for the inventory %+v", s) } return id, s } // TestResearchInventoryCard: the card lists every detected address (the // hello's valid ones and the observed one), once per primary however // many steps wait; another person cannot answer it, nor another answer, // nor a stale revision; Confirm records the prefixes with who and when, // audits it, and dispatches every waiting step with them. func TestResearchInventoryCard(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() r.inst.Store.Chat().SetForwardedHops(1) // A client-written element on the left is never the one used; the // edge's own element (the last) is. 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") r.until("the observed address", func() bool { return r.observed() == "81.2.69.9" }) a, _ := r.waitingTask("a") card := r.inventoryCard(wire.CardOpen) v := card.Inventory want := []string{"81.2.69.7", "81.2.69.9", "2a01:4f8:1:2::7"} 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}) { t.Fatalf("card %+v %+v", card, v) } if r.researchDispatches() != 0 { t.Fatal("dispatched before Confirm") } // Only valid addresses are recorded at all. if n := r.rows("SELECT count(*) FROM chat_research_addresses WHERE runner_id = ?", r.runner.Welcome.RunnerID); n != 3 { t.Fatalf("%d addresses recorded", n) } // A second waiting step does not raise a second card. b, _ := r.waitingTask("b") if n := r.inventoryCards(); n != 1 { t.Fatalf("%d inventory cards", n) } r.get(r.inst.SessionFor(t, Owner), "/conversation", 200) r.get(r.inst.SessionFor(t, Owner), "/tasks/"+a, 200) for _, rev := range []int64{card.Revision + 1, card.Revision - 1} { if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, rev); Status(err) != 409 { t.Fatalf("revision %d: %v", rev, err) } } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceAllow, card.Revision); Status(err) != 422 { t.Fatalf("another answer: %v", err) } m := personToolRigAt(t, r, "member@example.com", equipo.RoleMember, wire.ProtocolCurrent) if _, err := m.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, card.Revision); Status(err) != 404 { t.Fatalf("a teammate confirmed: %v", err) } if n := r.rows("SELECT count(*) FROM chat_research_prefixes"); n != 0 { t.Fatalf("%d prefixes before Confirm", n) } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, card.Revision); err != nil { t.Fatal(err) } if done := r.inventoryCard(wire.CardAnswered); done.Choice != wire.ChoiceConfirm { t.Fatalf("answered %+v", done) } prefixes := []string{"2a01:4f8:1:2::/64", "2a01:4f8:1:2::7/128", "81.2.69.7/32", "81.2.69.9/32"} for _, p := range prefixes { 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 { t.Fatalf("prefix %s: %d", p, n) } } if n := r.rows("SELECT count(*) FROM chat_research_prefixes"); n != len(prefixes) { t.Fatalf("%d prefixes", n) } 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 { t.Fatalf("%d audit rows", n) } got := map[string]bool{} for range 2 { d := r.nextDispatch() if d.Specialist != wire.SpecialistResearch || d.Research == nil || !slices.Equal(d.Research.Inventory, prefixes) { t.Fatalf("dispatch after Confirm %+v", d) } got[d.TaskID] = true } if !got[a] || !got[b] { t.Fatalf("dispatched %v", got) } for _, id := range []string{a, b} { if s := r.newest(id, wire.SpecialistResearch); s.Placement != "" || s.RunnerID != r.runner.Welcome.RunnerID { t.Fatalf("after Confirm %+v", s) } r.heldForResearch(id) } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, card.Revision+1); Status(err) != 409 { t.Fatalf("confirmed twice: %v", err) } } // TestResearchInventoryOwner: the card goes to the task's creator while // they are an owner; only they answer it, and only while they are still // an owner, read in the answer's transaction. func TestResearchInventoryOwner(t *testing.T) { a := newToolRigAt(t, wire.ProtocolCurrent) a.researchOn() b := personToolRigAt(t, a, "second@example.com", equipo.RoleOwner, wire.ProtocolCurrent) b.addresses(1, "81.2.69.70") id := b.shopTask("g") if res := b.research("g-r", id, "https://maps.example.org/place/shop"); res.IsError { t.Fatalf("request %+v", res) } src := b.sourcesCard(wire.CardOpen) if _, err := b.client.Answer(b.ctx, src.ID, wire.ChoiceAllow, src.Revision); err != nil { t.Fatal(err) } b.begin("g-start", id) card := b.inventoryCard(wire.CardOpen) if card.Inventory == nil || card.Inventory.RunnerID != b.runner.Welcome.RunnerID || !slices.Equal(card.Inventory.Addresses, []string{"81.2.69.70"}) { t.Fatalf("B's card %+v", card) } if _, err := a.client.Answer(a.ctx, card.ID, wire.ChoiceConfirm, card.Revision); Status(err) != 404 { t.Fatalf("another owner confirmed: %v", err) } var revision int64 if err := a.inst.DB.Writer().QueryRow("SELECT revision FROM members WHERE address = ?", "second@example.com").Scan(&revision); err != nil { t.Fatal(err) } if err := a.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, "second@example.com", equipo.RoleMember, true, revision); err != nil { t.Fatal(err) } if _, err := b.client.Answer(b.ctx, card.ID, wire.ChoiceConfirm, card.Revision); Status(err) != 403 { t.Fatalf("a former owner confirmed: %v", err) } if n := a.rows("SELECT count(*) FROM chat_research_prefixes"); n != 0 { t.Fatalf("%d prefixes without an owner", n) } if b.researchDispatches() != 0 { t.Fatal("dispatched without an owner's Confirm") } } // TestResearchInventoryNewAddress: an address the primary reports later // is outside the confirmed prefixes, so the next step waits again with a // new card listing every address; an address that changes while that // card is open moves its revision, so an answer to the old list is a // conflict; Confirm then dispatches. func TestResearchInventoryNewAddress(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() r.inventoryOn() r.addresses(2, "81.2.69.7", "2a01:4f8:5:6::1") _, s := r.waitingTask("a") card := r.inventoryCard(wire.CardOpen) if !slices.Equal(card.Inventory.Addresses, []string{"81.2.69.7", "2a01:4f8:5:6::1"}) { t.Fatalf("card %+v", card.Inventory) } // Another new address while the card is open. r.addresses(3, "81.2.69.7", "2a01:4f8:5:6::1", "81.2.69.21") var moved wire.Card r.wait("the card's new list", func(c *Conversation) bool { moved = c.Cards[card.ID] return moved.Revision > card.Revision }) if !slices.Equal(moved.Inventory.Addresses, []string{"81.2.69.7", "81.2.69.21", "2a01:4f8:5:6::1"}) || r.inventoryCards() != 1 { t.Fatalf("moved %+v (%d cards)", moved.Inventory, r.inventoryCards()) } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, card.Revision); Status(err) != 409 { t.Fatalf("Confirm of the old list: %v", err) } if r.researchDispatches() != 0 || r.rows("SELECT count(*) FROM chat_research_prefixes WHERE prefix = '81.2.69.21/32'") != 0 { t.Fatal("the old list was confirmed") } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceConfirm, moved.Revision); err != nil { t.Fatal(err) } d := r.nextDispatch() 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"}) { t.Fatalf("dispatch %+v", d.Research) } // Covered addresses raise nothing more. r.addresses(1, "81.2.69.21") r.waitingTaskDispatched("b") if n := r.inventoryCards(); n != 1 { t.Fatalf("%d inventory cards", n) } } // waitingTaskDispatched records and starts a task whose Research goes at // once (the inventory covers every detected address). func (r *toolRig) waitingTaskDispatched(key string) { r.t.Helper() id := r.namedTask(key) r.research(key+"-r", id) r.begin(key+"-start", id) if d := r.nextDispatch(); d.Specialist != wire.SpecialistResearch || d.TaskID != id { r.t.Fatalf("not dispatched at once %+v", d) } } // TestResearchInventoryObservedAddress: the observed address is the // edge's own X-Forwarded-For element, and only a valid global address; // a private or garbage one, or anything with no edge in front (the // default off CARLOS), is ignored, and the connection's own address is // used only when it is global (never loopback). func TestResearchInventoryObservedAddress(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) for _, c := range []struct { hops int forwarded, want string }{ {0, "81.2.69.9", ""}, {1, "81.2.69.9", "81.2.69.9"}, {1, "10.1.2.3", ""}, {1, "81.2.69.9, 192.168.0.4", ""}, {1, "garbage", ""}, {1, "100.64.0.1, ::ffff:81.2.69.5", "81.2.69.5"}, // ValidResearchAddress is the rule, the fetcher's public-address // one: a shared (CGNAT or tailnet) address is no public egress and // never counts (Astra security finding 2). {1, "81.2.69.9, 100.64.0.1", ""}, {1, "100.100.1.2", ""}, {1, "203.0.113.9", ""}, {1, "2A01:4F8::9", "2a01:4f8::9"}, {1, "", ""}, {1, "127.0.0.1", ""}, } { r.inst.Store.Chat().SetForwardedHops(c.hops) // Connect records it before the welcome. r.redial(c.forwarded, "81.2.69.7") if got := r.observed(); got != c.want { t.Errorf("%d hops, %q: observed %q, want %q", c.hops, c.forwarded, got, c.want) } } } // TestResearchInventoryOlderPrimary (mixed versions): a step waiting for // the inventory whose primary comes back at 11 is not left waiting for a // card it cannot use: it ends research_unsupported and Engineering goes. func TestResearchInventoryOlderPrimary(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() r.addresses(1, "81.2.69.7") id, _ := r.waitingTask("a") r.inventoryCard(wire.CardOpen) 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)) if err != nil { t.Fatal(err) } defer old.Close() _, body, err := old.Expect(r.ctx, wire.FrameDispatch) if err != nil { t.Fatal(err) } if e := body.(*wire.DispatchCommand); e.Specialist != wire.SpecialistEngineering || e.TaskID != id { t.Fatalf("to the older runner %+v", e) } if s := r.newest(id, wire.SpecialistResearch); s.State != wire.StepCancelled || s.Reason != wire.ReasonResearchUnsupported { t.Fatalf("at 11 %+v", s) } if r.researchDispatches() != 0 { t.Fatal("a research dispatch for a primary at 11") } }