| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/ecdsa" |
| 7 | "crypto/elliptic" |
| 8 | "crypto/rand" |
| 9 | "crypto/tls" |
| 10 | "crypto/x509" |
| 11 | "crypto/x509/pkix" |
| 12 | "encoding/json" |
| 13 | "errors" |
| 14 | "log" |
| 15 | "math/big" |
| 16 | "net/http" |
| 17 | "net/http/httptest" |
| 18 | "net/netip" |
| 19 | "strings" |
| 20 | "sync" |
| 21 | "testing" |
| 22 | "time" |
| 23 | |
| 24 | "amadan.net/oficina/equipo/internal/equipo/assist" |
| 25 | "amadan.net/oficina/equipo/internal/websearch" |
| 26 | "amadan.net/oficina/equipo/internal/websearch/websearchtest" |
| 27 | "amadan.net/oficina/equipo/internal/websource/guard" |
| 28 | "amadan.net/oficina/equipo/internal/wire" |
| 29 | gormlogger "gorm.io/gorm/logger" |
| 30 | ) |
| 31 | |
| 32 | const pageSentinel = "SENTINEL-WEB-TEXT-991" |
| 33 | |
| 34 | type readyInv struct{ ready bool } |
| 35 | |
| 36 | func (i readyInv) Ready(context.Context) error { |
| 37 | if !i.ready { |
| 38 | return guard.ErrInventoryUnconfirmed |
| 39 | } |
| 40 | return nil |
| 41 | } |
| 42 | func (readyInv) Inside(netip.Addr) bool { return false } |
| 43 | |
| 44 | // fakeBase is Base's base_apps as the registry reaches it. |
| 45 | type fakeBase struct { |
| 46 | apps string |
| 47 | fail bool |
| 48 | } |
| 49 | |
| 50 | func (fakeBase) Name() string { return "base" } |
| 51 | func (fakeBase) List(context.Context, string) ([]assist.Operation, error) { |
| 52 | return []assist.Operation{{Provider: "base", Name: "base_apps", App: "Base", Scope: "base.read", ReadOnly: true, Idempotent: true, Input: json.RawMessage(`{"type":"object"}`)}}, nil |
| 53 | } |
| 54 | func (b fakeBase) Invoke(ctx context.Context, _, op string, _ json.RawMessage, _ string) (json.RawMessage, error) { |
| 55 | if err := assist.Gate(ctx, assist.Operation{Provider: "base", Name: op, App: "Base", Scope: "base.read", ReadOnly: true, Idempotent: true, Input: json.RawMessage(`{"type":"object"}`)}); err != nil { |
| 56 | return nil, err |
| 57 | } |
| 58 | if b.fail { |
| 59 | return nil, assist.Failure{Code: "unavailable"} |
| 60 | } |
| 61 | return json.RawMessage(b.apps), nil |
| 62 | } |
| 63 | |
| 64 | // web is the public web the lookup reads: one TLS server answering as |
| 65 | // every host, recording each request by host and path. |
| 66 | type web struct { |
| 67 | srv *httptest.Server |
| 68 | roots *x509.CertPool |
| 69 | mu sync.Mutex |
| 70 | got []string |
| 71 | pages map[string]func(w http.ResponseWriter, r *http.Request) |
| 72 | } |
| 73 | |
| 74 | func newWeb(t *testing.T) *web { |
| 75 | t.Helper() |
| 76 | key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 77 | hosts := []string{"www.met.ie", "news.example.org", "shop.paul.example.org", "cal.oficina.works", "other.example.org", "www.bbc.com"} |
| 78 | tmpl := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "web"}, DNSNames: hosts, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), |
| 79 | KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, IsCA: true} |
| 80 | der, _ := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) |
| 81 | cert, _ := x509.ParseCertificate(der) |
| 82 | w := &web{roots: x509.NewCertPool(), pages: map[string]func(http.ResponseWriter, *http.Request){}} |
| 83 | w.roots.AddCert(cert) |
| 84 | w.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
| 85 | w.mu.Lock() |
| 86 | w.got = append(w.got, r.Host+r.URL.Path) |
| 87 | h := w.pages[r.Host+r.URL.Path] |
| 88 | w.mu.Unlock() |
| 89 | if h == nil { |
| 90 | rw.Header().Set("Content-Type", "text/html") |
| 91 | _, _ = rw.Write([]byte("<html><title>" + r.Host + "</title><body><p>Rain at first, 11 degrees. " + pageSentinel + "</p></body></html>")) |
| 92 | return |
| 93 | } |
| 94 | h(rw, r) |
| 95 | })) |
| 96 | w.srv.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}} |
| 97 | w.srv.StartTLS() |
| 98 | t.Cleanup(w.srv.Close) |
| 99 | return w |
| 100 | } |
| 101 | |
| 102 | func (w *web) requests() []string { |
| 103 | w.mu.Lock() |
| 104 | defer w.mu.Unlock() |
| 105 | return append([]string(nil), w.got...) |
| 106 | } |
| 107 | |
| 108 | // lookupRig is a person with web on, a Base drawing answers, a primary |
| 109 | // at protocol 36 whose model answers the two steps, a search backend and |
| 110 | // the web. |
| 111 | type lookupRig struct { |
| 112 | t *testing.T |
| 113 | h *abilitiesHarness |
| 114 | base *fakeBoardBase |
| 115 | web *web |
| 116 | search *websearchtest.Fake |
| 117 | usage *websearchtest.MemUsage |
| 118 | apps *fakeBase |
| 119 | steps []wire.LookupStep |
| 120 | mu sync.Mutex |
| 121 | queries []string |
| 122 | answer string |
| 123 | n int |
| 124 | detach func() |
| 125 | } |
| 126 | |
| 127 | func newLookupRig(t *testing.T) *lookupRig { |
| 128 | t.Helper() |
| 129 | h, base := boardBase(t) |
| 130 | refresh(t, h) |
| 131 | ctx := context.Background() |
| 132 | if err := h.s.SetCapabilities(ctx, abPerson, wire.CapLookupAnswers); err != nil { |
| 133 | t.Fatal(err) |
| 134 | } |
| 135 | r := &lookupRig{t: t, h: h, base: base, web: newWeb(t), search: &websearchtest.Fake{Backend: "kagi", Results: map[string][]websearch.Result{}}, |
| 136 | usage: &websearchtest.MemUsage{Caps: map[string]int{"kagi": 1000}, Month: "2026-11"}, apps: &fakeBase{apps: `{"installed":[{"address":"https://shop.paul.example.org"}],"oficina":[{"address":"https://cal.oficina.works"}]}`}, |
| 137 | queries: []string{"dublin weather"}, answer: "Rain at first, 11 degrees."} |
| 138 | g := guard.Config{Inventory: readyInv{true}, Resolve: func(context.Context, string) ([]netip.Addr, error) { |
| 139 | return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil |
| 140 | }, TestDial: func(string) (string, *x509.CertPool) { return r.web.srv.Listener.Addr().String(), r.web.roots }} |
| 141 | pageCfg := g |
| 142 | pageCfg.Policy, pageCfg.Redirects = guard.PolicyLookupPage, guard.MaxRedirects |
| 143 | pages, err := guard.New(pageCfg) |
| 144 | if err != nil { |
| 145 | t.Fatal(err) |
| 146 | } |
| 147 | h.s.SetLookups(&LookupConfig{Search: websearch.Chain{Primary: r.search, Usage: r.usage}, Pages: pages, Inventory: g.Inventory, Deny: []string{"equipo.example.org"}}) |
| 148 | h.s.SetOperations(assist.NewRegistry(r.apps, h.s.WebProvider())) |
| 149 | var live *liveConn |
| 150 | live, r.detach = h.s.attachLive("RUNNER1", wire.ProtocolLookup, func(_ context.Context, f wire.Frame) error { |
| 151 | body, err := f.Decode() |
| 152 | if err != nil { |
| 153 | return err |
| 154 | } |
| 155 | s := *body.(*wire.LookupStep) |
| 156 | r.mu.Lock() |
| 157 | r.steps = append(r.steps, s) |
| 158 | res := wire.LookupResult{Lookup: s.Lookup, Attempt: s.Attempt, Nonce: s.Nonce, Stage: s.Stage} |
| 159 | if s.Stage == wire.LookupStageQuery { |
| 160 | res.Queries = r.queries |
| 161 | } else { |
| 162 | res.Answer, res.Used = r.answer, []int{} |
| 163 | if len(s.Results) > 0 { |
| 164 | res.Used = []int{0} |
| 165 | } |
| 166 | } |
| 167 | r.mu.Unlock() |
| 168 | h.s.deliverLookup(live, res) |
| 169 | return nil |
| 170 | }) |
| 171 | return r |
| 172 | } |
| 173 | |
| 174 | // ask is a person turn with words as its composer message, and the call |
| 175 | // in it; kind is the turn's kind. |
| 176 | func (r *lookupRig) ask(words, kind string) toolCallRecord { |
| 177 | r.t.Helper() |
| 178 | r.n++ |
| 179 | id := "lt" + itoa64(int64(r.n)) |
| 180 | now := r.h.now() |
| 181 | turn := turnRecord{ID: id, Person: abPerson, State: wire.TurnRunning, Kind: kind, Lane: wire.LaneAssistant, Attempt: 1, CreatedAt: now, UpdatedAt: now} |
| 182 | m := messageRecord{ID: "lm" + id, Person: abPerson, IdempotencyKey: "lk" + id, Role: wire.RolePerson, Origin: originComposer, Text: words, TurnID: id, Lane: wire.LaneAssistant, CreatedAt: now} |
| 183 | call := toolCallRecord{CallID: "lc" + id, Person: abPerson, TurnID: id, Attempt: 1, Name: wire.ToolUse, CreatedAt: now} |
| 184 | for _, row := range []any{&turn, &m, &call} { |
| 185 | if err := r.h.s.db.G.Create(row).Error; err != nil { |
| 186 | r.t.Fatal(err) |
| 187 | } |
| 188 | } |
| 189 | return call |
| 190 | } |
| 191 | |
| 192 | // lookup runs web_lookup for call as the Assistant's use does. |
| 193 | func (r *lookupRig) lookup(call toolCallRecord, input string) (json.RawMessage, error) { |
| 194 | r.t.Helper() |
| 195 | ctx := context.Background() |
| 196 | gated := assist.WithGate(withCall(ctx, call), r.h.s.sendGate(ctx, abPerson, webLookupOp)) |
| 197 | return r.h.s.WebProvider().Invoke(gated, abPerson, opWebLookup, json.RawMessage(input), call.CallID) |
| 198 | } |
| 199 | |
| 200 | func codeOf(err error) string { |
| 201 | var ref assist.Refusal |
| 202 | if errors.As(err, &ref) { |
| 203 | return ref.Code |
| 204 | } |
| 205 | var f assist.Failure |
| 206 | if errors.As(err, &f) { |
| 207 | return f.Code |
| 208 | } |
| 209 | return "" |
| 210 | } |
| 211 | |
| 212 | func (r *lookupRig) row(call toolCallRecord) lookupRecord { |
| 213 | r.t.Helper() |
| 214 | var row lookupRecord |
| 215 | if err := r.h.s.db.G.Where("call_id = ?", call.CallID).First(&row).Error; err != nil { |
| 216 | r.t.Fatal(err) |
| 217 | } |
| 218 | return row |
| 219 | } |
| 220 | |
| 221 | func (r *lookupRig) webOff() { |
| 222 | r.base.set(func(f *fakeBoardBase) { f.board.Abilities["web"], f.board.Revision = false, f.board.Revision+1 }) |
| 223 | if _, _, err := r.h.s.RefreshAbilities(context.Background(), abPerson); err != nil { |
| 224 | r.t.Fatal(err) |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | func TestLookupInputIsEmpty(t *testing.T) { |
| 229 | r := newLookupRig(t) |
| 230 | if _, err := r.lookup(r.ask("Weather in Dublin?", wire.TurnPerson), `{"q":"dublin"}`); codeOf(err) != "invalid_input" { |
| 231 | t.Errorf("an input: %v", err) |
| 232 | } |
| 233 | if string(webLookupOp.Input) != `{"type":"object","additionalProperties":false}` || !webLookupOp.ReadOnly { |
| 234 | t.Errorf("op %+v", webLookupOp) |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | // Only in a turn the person started: a team_update (a connect's resume |
| 239 | // turn included) is refused, and doesn't list it. |
| 240 | func TestLookupsOnlyInPersonTurns(t *testing.T) { |
| 241 | r := newLookupRig(t) |
| 242 | call := r.ask("Weather in Dublin?", wire.TurnTeamUpdate) |
| 243 | if _, err := r.lookup(call, `{}`); codeOf(err) != wire.CodeLookupUnsupported { |
| 244 | t.Errorf("in a team_update: %v", err) |
| 245 | } |
| 246 | // Through the registry, whichever turn looks first: a team_update |
| 247 | // isn't offered it, a person turn is (round 3, P2: the listing is |
| 248 | // cached per person, the turn filtered per call). |
| 249 | look := func(c toolCallRecord) string { |
| 250 | c.Name, c.Args = wire.ToolLook, `{"query":"weather"}` |
| 251 | res, _ := r.h.s.runRemote(context.Background(), c) |
| 252 | return res.Text |
| 253 | } |
| 254 | person := r.ask("Weather?", wire.TurnPerson) |
| 255 | for _, order := range [][]toolCallRecord{{call, person}, {person, call}} { |
| 256 | for _, c := range order { |
| 257 | got := strings.Contains(look(c), "web_lookup") |
| 258 | if want := c.TurnID == person.TurnID; got != want { |
| 259 | t.Errorf("turn %s offered %v", c.TurnID, got) |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | // The top results are read, in rank order, at most 3; the answer is |
| 266 | // shown with its sources; the Assistant gets the fixed result only. |
| 267 | func TestReadsPickedByRank(t *testing.T) { |
| 268 | r := newLookupRig(t) |
| 269 | r.search.Results["dublin weather"] = []websearch.Result{ |
| 270 | {Title: "Met", URL: "https://www.met.ie/dublin"}, {Title: "BBC", URL: "https://www.bbc.com/weather"}, |
| 271 | {Title: "News", URL: "https://news.example.org/weather"}, {Title: "Other", URL: "https://other.example.org/x"}, |
| 272 | } |
| 273 | out, err := r.lookup(r.ask("What's the weather in Dublin?", wire.TurnPerson), `{}`) |
| 274 | if err != nil { |
| 275 | t.Fatal(err) |
| 276 | } |
| 277 | if got := strings.Join(r.web.requests(), " "); got != "www.met.ie/dublin www.bbc.com/weather news.example.org/weather" { |
| 278 | t.Errorf("read %s", got) |
| 279 | } |
| 280 | var res struct { |
| 281 | Code string `json:"code"` |
| 282 | Sources int `json:"sources"` |
| 283 | Text string `json:"text"` |
| 284 | } |
| 285 | if json.Unmarshal(out, &res) != nil || res.Code != wire.CodeLookupShown || res.Sources != 3 || res.Text != toolLookupShown { |
| 286 | t.Errorf("result %s", out) |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | // What the Assistant gets back never holds the page's text or the answer. |
| 291 | func TestAssistantNeverSeesWebText(t *testing.T) { |
| 292 | r := newLookupRig(t) |
| 293 | r.answer = "Rain. " + pageSentinel |
| 294 | r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met " + pageSentinel, URL: "https://www.met.ie/dublin", Snippet: pageSentinel}} |
| 295 | out, err := r.lookup(r.ask("Weather in Dublin?", wire.TurnPerson), `{}`) |
| 296 | if err != nil || strings.Contains(string(out), pageSentinel) || strings.Contains(string(out), "Rain") { |
| 297 | t.Errorf("%s %v", out, err) |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | // Addresses the person typed are read instead of searching; one of |
| 302 | // their own Oficina or Base apps is refused, typed or reached by a |
| 303 | // redirect. |
| 304 | func TestTypedAddressesRefusedOrSkipped(t *testing.T) { |
| 305 | r := newLookupRig(t) |
| 306 | r.web.pages["news.example.org/jump"] = func(w http.ResponseWriter, _ *http.Request) { |
| 307 | w.Header().Set("Location", "https://cal.oficina.works/events") |
| 308 | w.WriteHeader(http.StatusFound) |
| 309 | } |
| 310 | call := r.ask("What does https://shop.paul.example.org/menu and https://news.example.org/jump and https://www.met.ie/today say?", wire.TurnPerson) |
| 311 | if _, err := r.lookup(call, `{}`); err != nil { |
| 312 | t.Fatal(err) |
| 313 | } |
| 314 | if r.search.Asked() != 0 { |
| 315 | t.Error("searched though addresses were typed") |
| 316 | } |
| 317 | got := strings.Join(r.web.requests(), " ") |
| 318 | if strings.Contains(got, "shop.paul") || strings.Contains(got, "cal.oficina") || !strings.Contains(got, "news.example.org/jump") || !strings.Contains(got, "www.met.ie/today") { |
| 319 | t.Errorf("read %s", got) |
| 320 | } |
| 321 | if reads := r.row(call).Reads; !strings.Contains(reads, guard.RuleDenied) { |
| 322 | t.Errorf("reads %s", reads) |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | func TestOficinaAppOriginRefused(t *testing.T) { |
| 327 | r := newLookupRig(t) |
| 328 | r.search.Results["dublin weather"] = []websearch.Result{{Title: "Calendar", URL: "https://cal.oficina.works/today"}} |
| 329 | call := r.ask("Weather?", wire.TurnPerson) |
| 330 | if _, err := r.lookup(call, `{}`); err != nil && codeOf(err) != wire.CodeNothingFound && codeOf(err) != wire.CodeLookupFailed { |
| 331 | t.Fatal(err) |
| 332 | } |
| 333 | if len(r.web.requests()) != 0 { |
| 334 | t.Errorf("an app was read: %v", r.web.requests()) |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | // With the person's app addresses not to be had, the lookup fails and |
| 339 | // nothing is read. |
| 340 | func TestDenyUnavailableFailsClosed(t *testing.T) { |
| 341 | r := newLookupRig(t) |
| 342 | r.apps.fail = true |
| 343 | r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/dublin"}} |
| 344 | if _, err := r.lookup(r.ask("Weather?", wire.TurnPerson), `{}`); codeOf(err) != wire.CodeLookupFailed || len(r.web.requests()) != 0 || r.search.Asked() != 0 { |
| 345 | t.Errorf("%v, read %v", err, r.web.requests()) |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | // Two lookups in a turn; a third is refused; so is the 101st in a day. |
| 350 | func TestLookupCaps(t *testing.T) { |
| 351 | r := newLookupRig(t) |
| 352 | r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/dublin"}} |
| 353 | call := r.ask("Weather?", wire.TurnPerson) |
| 354 | for i := range 3 { |
| 355 | call.CallID = "cap" + itoa64(int64(i)) |
| 356 | _, err := r.lookup(call, `{}`) |
| 357 | if want := i == 2; (codeOf(err) == wire.CodeLookupLimit) != want { |
| 358 | t.Errorf("lookup %d: %v", i+1, err) |
| 359 | } |
| 360 | } |
| 361 | // The turn's next attempt has no more (round 2, P2). |
| 362 | call.CallID, call.Attempt = "cap-retry", 2 |
| 363 | if _, err := r.lookup(call, `{}`); codeOf(err) != wire.CodeLookupLimit { |
| 364 | t.Errorf("a retry of the turn: %v", err) |
| 365 | } |
| 366 | r = newLookupRig(t) |
| 367 | for i := range 100 { |
| 368 | if err := r.h.s.db.G.Create(&lookupRecord{ID: "old" + itoa64(int64(i)), Person: abPerson, TurnID: "x", Attempt: 1, Seq: int64(i), CallID: "o" + itoa64(int64(i)), State: lookupShown, CreatedAt: r.h.now().Add(-time.Hour)}).Error; err != nil { |
| 369 | t.Fatal(err) |
| 370 | } |
| 371 | } |
| 372 | if _, err := r.lookup(r.ask("Weather?", wire.TurnPerson), `{}`); codeOf(err) != wire.CodeLookupLimit { |
| 373 | t.Errorf("the 101st: %v", err) |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | func TestSecretLookingQueryRefused(t *testing.T) { |
| 378 | r := newLookupRig(t) |
| 379 | r.queries = []string{"sk-proj-abcdefghijklmnopqrstuvwxyz0123456789ABCD"} |
| 380 | if _, err := r.lookup(r.ask("Weather?", wire.TurnPerson), `{}`); codeOf(err) != wire.CodeLookupFailed || r.search.Asked() != 0 { |
| 381 | t.Errorf("%v, searched %d", err, r.search.Asked()) |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | // Page text is never stored: the lookup's row holds numbers, the answer |
| 386 | // and its sources. |
| 387 | func TestLookupPageTextNotStored(t *testing.T) { |
| 388 | r := newLookupRig(t) |
| 389 | r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/dublin", Snippet: "snippet " + pageSentinel}} |
| 390 | call := r.ask("Weather?", wire.TurnPerson) |
| 391 | if _, err := r.lookup(call, `{}`); err != nil { |
| 392 | t.Fatal(err) |
| 393 | } |
| 394 | row := r.row(call) |
| 395 | raw, _ := json.Marshal(row) |
| 396 | if strings.Contains(string(raw), pageSentinel) || row.State != lookupShown || !strings.Contains(row.Reads, "sha256") || !strings.Contains(row.Queries, `"backend":"kagi"`) { |
| 397 | t.Errorf("row %s", raw) |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | // The audit names the person, the numbers and the domains: never the |
| 402 | // query or the answer. |
| 403 | func TestLookupAuditNoQuery(t *testing.T) { |
| 404 | r := newLookupRig(t) |
| 405 | r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/dublin"}} |
| 406 | if _, err := r.lookup(r.ask("Weather?", wire.TurnPerson), `{}`); err != nil { |
| 407 | t.Fatal(err) |
| 408 | } |
| 409 | var line string |
| 410 | for _, a := range r.h.audits { |
| 411 | if strings.HasPrefix(a, auditLookup+" ") { |
| 412 | line = a |
| 413 | } |
| 414 | } |
| 415 | if line == "" || strings.Contains(line, "dublin weather") || strings.Contains(line, "Rain") || !strings.Contains(line, "domains=met.ie") || !strings.Contains(line, "code=shown") { |
| 416 | t.Errorf("audit %q", line) |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | // The answer step fits the runner's frame, the lowest-ranked page cut |
| 421 | // first, and says it was cut. |
| 422 | func TestAnswerStepBudget(t *testing.T) { |
| 423 | big := strings.Repeat("é", 8<<10) |
| 424 | s := wire.LookupStep{Stage: wire.LookupStageAnswer, Pages: []wire.LookupPage{{Text: big}, {Text: big}, {Text: big}, {Text: big}}} |
| 425 | out, cut := fitAnswerStep(s) |
| 426 | raw, _ := json.Marshal(out) |
| 427 | if !cut || len(raw) > wire.MaxLookupStepBytes || out.Pages[0].Text != big || len(out.Pages[3].Text) >= len(big) { |
| 428 | t.Errorf("%d bytes, cut %v", len(raw), cut) |
| 429 | } // One result too big on its own still fits (Astra phase 3 round 1, P2). |
| 430 | huge := wire.LookupStep{Person: abPerson, Stage: wire.LookupStageAnswer, Results: []wire.SearchResult{{Title: strings.Repeat("x", 60<<10)}}, Pages: []wire.LookupPage{{Text: big}}} |
| 431 | out, cut = fitAnswerStep(huge) |
| 432 | raw, _ = json.Marshal(out) |
| 433 | if !cut || len(raw) > wire.MaxLookupStepBytes-lookupNonceRoom { |
| 434 | t.Errorf("one result: %d bytes", len(raw)) |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | // web turned off after the search: the page reads that would follow are |
| 439 | // refused before anything is sent, and the refusal is the answer. |
| 440 | func TestRevokedMidLookupStopsNextRequest(t *testing.T) { |
| 441 | r := newLookupRig(t) |
| 442 | r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/dublin"}} |
| 443 | r.search.Hook = func(context.Context, string) error { r.webOff(); return nil } |
| 444 | if _, err := r.lookup(r.ask("Weather?", wire.TurnPerson), `{}`); codeOf(err) != wire.CodeAbilityOff || len(r.web.requests()) != 0 { |
| 445 | t.Errorf("%v, read %v", err, r.web.requests()) |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | // web turned off while the first hop's 302 comes back: its target |
| 450 | // receives nothing. |
| 451 | func TestRevokedDuringRedirectStops(t *testing.T) { |
| 452 | r := newLookupRig(t) |
| 453 | r.web.pages["news.example.org/jump"] = func(w http.ResponseWriter, _ *http.Request) { |
| 454 | r.webOff() |
| 455 | w.Header().Set("Location", "https://other.example.org/next") |
| 456 | w.WriteHeader(http.StatusFound) |
| 457 | } |
| 458 | if _, err := r.lookup(r.ask("Read https://news.example.org/jump please", wire.TurnPerson), `{}`); codeOf(err) != wire.CodeAbilityOff { |
| 459 | t.Errorf("%v", err) |
| 460 | } |
| 461 | for _, got := range r.web.requests() { |
| 462 | if strings.HasPrefix(got, "other.example.org") { |
| 463 | t.Errorf("the redirect's target was read") |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | // A request to a host waits for a second after the last one to it. |
| 469 | func TestSearchPacedAfterDNS(t *testing.T) { |
| 470 | var p hostPacer |
| 471 | start := time.Now() |
| 472 | var wg sync.WaitGroup |
| 473 | for range 2 { |
| 474 | wg.Add(1) |
| 475 | go func() { defer wg.Done(); _ = p.wait(context.Background(), "kagi.com") }() |
| 476 | } |
| 477 | wg.Wait() |
| 478 | if time.Since(start) < time.Second { |
| 479 | t.Errorf("two requests to one host within %s", time.Since(start)) |
| 480 | } |
| 481 | start = time.Now() |
| 482 | _ = p.wait(context.Background(), "www.mojeek.com") |
| 483 | if time.Since(start) > 200*time.Millisecond { |
| 484 | t.Error("another host waited") |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | func TestSameHostRedirectPaced(t *testing.T) { |
| 489 | r := newLookupRig(t) |
| 490 | r.web.pages["news.example.org/jump"] = func(w http.ResponseWriter, _ *http.Request) { |
| 491 | w.Header().Set("Location", "https://news.example.org/landed") |
| 492 | w.WriteHeader(http.StatusFound) |
| 493 | } |
| 494 | start := time.Now() |
| 495 | if _, err := r.lookup(r.ask("Read https://news.example.org/jump", wire.TurnPerson), `{}`); err != nil { |
| 496 | t.Fatal(err) |
| 497 | } |
| 498 | if time.Since(start) < time.Second { |
| 499 | t.Errorf("the same host's redirect wasn't paced: %s", time.Since(start)) |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | // web_lookup isn't listed for an older runner, a Base that can't draw |
| 504 | // answers, an unconfirmed inventory, or no backend. |
| 505 | func TestLookupUnsupported(t *testing.T) { |
| 506 | ctx := context.Background() |
| 507 | listed := func(r *lookupRig) bool { |
| 508 | ops, _ := r.h.s.WebProvider().List(ctx, abPerson) |
| 509 | return len(ops) == 1 |
| 510 | } |
| 511 | r := newLookupRig(t) |
| 512 | if !listed(r) { |
| 513 | t.Fatal("not listed when it can run") |
| 514 | } |
| 515 | r.detach() |
| 516 | _, old := r.h.s.attachLive("RUNNER1", wire.Protocol35, func(context.Context, wire.Frame) error { return nil }) |
| 517 | defer old() |
| 518 | if listed(r) { |
| 519 | t.Error("listed on protocol 35") |
| 520 | } |
| 521 | r = newLookupRig(t) |
| 522 | if err := r.h.s.SetCapabilities(ctx, abPerson, ""); err != nil { |
| 523 | t.Fatal(err) |
| 524 | } |
| 525 | if listed(r) { |
| 526 | t.Error("listed for a Base that can't draw answers") |
| 527 | } |
| 528 | r = newLookupRig(t) |
| 529 | cfg := *r.h.s.lookups.cfg.Load() |
| 530 | cfg.Inventory = readyInv{false} |
| 531 | r.h.s.SetLookups(&cfg) |
| 532 | if listed(r) { |
| 533 | t.Error("listed with the inventory unconfirmed") |
| 534 | } |
| 535 | r.h.s.SetLookups(nil) |
| 536 | if listed(r) { |
| 537 | t.Error("listed with no backend") |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | func TestLookupExemptFromOutboundRule(t *testing.T) { |
| 542 | t.Skip("MCP Task 27 (the outbound rule) has not landed") |
| 543 | } |
| 544 | |
| 545 | // An outcome that doesn't commit (its audit failing) is an error, never |
| 546 | // a shown answer the reply would lack (Astra phase 3 round 1, P1). |
| 547 | func TestLookupNotShownUnlessStored(t *testing.T) { |
| 548 | r := newLookupRig(t) |
| 549 | r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/dublin"}} |
| 550 | r.h.failAudit = auditLookup |
| 551 | call := r.ask("Weather?", wire.TurnPerson) |
| 552 | if out, err := r.lookup(call, `{}`); err == nil || strings.Contains(string(out), wire.CodeLookupShown) { |
| 553 | t.Errorf("%s %v", out, err) |
| 554 | } |
| 555 | if row := r.row(call); row.State == lookupShown { |
| 556 | t.Errorf("stored shown: %+v", row) |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | // Addresses that aren't pages get an honest code, never a search and |
| 561 | // never a request: another scheme, an IP address (http tried as https), |
| 562 | // a port, an address over 2 KiB (Astra phase 3 round 1, P2). |
| 563 | func TestTypedAddressesNotPages(t *testing.T) { |
| 564 | for _, words := range []string{"What's on ftp://files.example.org/x", "Open http://192.168.1.1/admin", "Read news.example.org:8080/today", "Read https://news.example.org/" + strings.Repeat("a", 2100), "Read news.example.org/" + strings.Repeat("b", 2100)} { |
| 565 | r := newLookupRig(t) |
| 566 | r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/dublin"}} |
| 567 | call := r.ask(words, wire.TurnPerson) |
| 568 | if _, err := r.lookup(call, `{}`); codeOf(err) != wire.CodeNothingFound { |
| 569 | t.Errorf("%.60q: %v", words, err) |
| 570 | } |
| 571 | if r.search.Asked() != 0 || len(r.web.requests()) != 0 { |
| 572 | t.Errorf("%.60q: searched %d, read %v", words, r.search.Asked(), r.web.requests()) |
| 573 | } |
| 574 | if row := r.row(call); !strings.Contains(row.Reads, `"code"`) { |
| 575 | t.Errorf("%.60q: no refusal recorded: %s", words, row.Reads) |
| 576 | } |
| 577 | } |
| 578 | // An address past where the pack is cut is read as typed, not |
| 579 | // searched for (round 3, P2). |
| 580 | r := newLookupRig(t) |
| 581 | if _, err := r.lookup(r.ask(strings.Repeat("Please ", 700)+"read https://www.met.ie/today", wire.TurnPerson), `{}`); err != nil || r.search.Asked() != 0 || strings.Join(r.web.requests(), " ") != "www.met.ie/today" { |
| 582 | t.Errorf("%v, searched %d, read %v", err, r.search.Asked(), r.web.requests()) |
| 583 | } |
| 584 | if got := typedAddresses("See www.met.ie first, then example.org:8080/x please."); len(got) != 2 || got[0] != "https://www.met.ie/" || got[1] != "https://example.org:8080/x" { |
| 585 | t.Errorf("typed %v", got) |
| 586 | } |
| 587 | // A bare address keeps its query (round 4, P2), and one too long |
| 588 | // through its query is kept whole, to be refused. |
| 589 | if got := typedAddresses("What does news.example.org?item=123 say?"); len(got) != 1 || got[0] != "https://news.example.org?item=123" { |
| 590 | t.Errorf("query: %v", got) |
| 591 | } |
| 592 | if got := typedAddresses("Open news.example.org?q=" + strings.Repeat("c", 2100)); len(got) != 1 || len(got[0]) < 2100 { |
| 593 | t.Errorf("long query kept %d", len(got)) |
| 594 | } |
| 595 | // Two pages on one host are two addresses (round 2, P2). |
| 596 | if got := typedAddresses("Compare example.org/a with example.org/b"); len(got) != 2 || got[0] == got[1] { |
| 597 | t.Errorf("one host's pages: %v", got) |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | // Nothing of a lookup reaches the SQL log, even at its most verbose: its |
| 602 | // queries, addresses and answer are written with logging off (Astra |
| 603 | // phase 3 round 2, P1). |
| 604 | func TestLookupNotInSQLLog(t *testing.T) { |
| 605 | r := newLookupRig(t) |
| 606 | var buf bytes.Buffer |
| 607 | r.h.s.db.G.Logger = gormlogger.New(log.New(&buf, "", 0), gormlogger.Config{LogLevel: gormlogger.Info}) |
| 608 | r.queries = []string{"dublin " + strings.ToLower(pageSentinel)} |
| 609 | r.search.Results[r.queries[0]] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/" + pageSentinel}} |
| 610 | r.answer = "Rain. " + pageSentinel |
| 611 | if _, err := r.lookup(r.ask("Weather?", wire.TurnPerson), `{}`); err != nil { |
| 612 | t.Fatal(err) |
| 613 | } |
| 614 | if strings.Contains(strings.ToLower(buf.String()), strings.ToLower(pageSentinel)) { |
| 615 | t.Errorf("the SQL log holds the lookup: %.300s", buf.String()) |
| 616 | } |
| 617 | if !strings.Contains(buf.String(), "SELECT") { |
| 618 | t.Error("the log captured nothing: the test proves nothing") |
| 619 | } |
| 620 | } |
| 621 | |
| 622 | // A base_apps answer that leaves anything out isn't an empty list: the |
| 623 | // lookup fails, and a list fetched earlier stands only while it may |
| 624 | // (Astra phase 3 round 2, P1). |
| 625 | func TestDenyListMustBeWhole(t *testing.T) { |
| 626 | for _, apps := range []string{`{}`, `null`, `{"installed":[]}`, `{"installed":[],"oficina":[{"name":"Cal"}]}`, `{"installed":[{"address":"not a url"}],"oficina":[]}`} { |
| 627 | r := newLookupRig(t) |
| 628 | r.apps.apps = apps |
| 629 | r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/dublin"}} |
| 630 | if _, err := r.lookup(r.ask("Weather?", wire.TurnPerson), `{}`); codeOf(err) != wire.CodeLookupFailed || len(r.web.requests()) != 0 { |
| 631 | t.Errorf("%s: %v, read %v", apps, err, r.web.requests()) |
| 632 | } |
| 633 | } |
| 634 | r := newLookupRig(t) |
| 635 | if hosts, err := r.h.s.lookupDeny(context.Background(), abPerson); err != nil || len(hosts) != 2 { |
| 636 | t.Fatalf("%v %v", hosts, err) |
| 637 | } |
| 638 | r.apps.apps = `{}` |
| 639 | if hosts, err := r.h.s.lookupDeny(context.Background(), abPerson); err != nil || len(hosts) != 2 { |
| 640 | t.Errorf("a fresh list was replaced: %v %v", hosts, err) |
| 641 | } |
| 642 | } |
| 643 | |