| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | "net/netip" |
| 8 | "slices" |
| 9 | "strings" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | "amadan.net/rastrillo/rastrillo/carlos" |
| 14 | "amadan.net/rastrillo/rastrillo/clientip" |
| 15 | "gorm.io/gorm" |
| 16 | "gorm.io/gorm/clause" |
| 17 | ) |
| 18 | |
| 19 | // Research's site inventory (Research spec §3.3; decision R4 as refined, |
| 20 | // slice R3). Equipo detects each primary's own addresses itself: the |
| 21 | // global addresses its hello reports (Capabilities.Research) and the |
| 22 | // address the instance saw its stream connection come from. A Research |
| 23 | // step is dispatched only when every address detected now is inside a |
| 24 | // prefix an owner confirmed; until then it waits (waiting_inventory) and |
| 25 | // one card per primary asks an owner to confirm the list. The dispatch |
| 26 | // carries the confirmed prefixes, which the fetcher refuses to reach. |
| 27 | |
| 28 | // Where a detected address came from. |
| 29 | const ( |
| 30 | addressInterface = "interface" |
| 31 | addressObserved = "observed" |
| 32 | ) |
| 33 | |
| 34 | // researchAddressRecord is one address detected for a runner now: an |
| 35 | // interface address from its latest hello that said, or the address its |
| 36 | // current stream connection was seen from. |
| 37 | type researchAddressRecord struct { |
| 38 | RunnerID string `gorm:"primaryKey"` |
| 39 | Source string `gorm:"primaryKey"` |
| 40 | Address string `gorm:"primaryKey"` |
| 41 | SeenAt time.Time |
| 42 | } |
| 43 | |
| 44 | func (researchAddressRecord) TableName() string { return "chat_research_addresses" } |
| 45 | |
| 46 | // researchPrefixRecord is one confirmed site inventory prefix of a |
| 47 | // runner: who confirmed it, when, on which card. Never removed. |
| 48 | type researchPrefixRecord struct { |
| 49 | RunnerID string `gorm:"primaryKey"` |
| 50 | Prefix string `gorm:"primaryKey"` |
| 51 | ConfirmedBy string |
| 52 | ConfirmedAt time.Time |
| 53 | CardID string |
| 54 | } |
| 55 | |
| 56 | func (researchPrefixRecord) TableName() string { return "chat_research_prefixes" } |
| 57 | |
| 58 | // researchInventoryRecord binds a research_inventory card to its runner |
| 59 | // and the exact list of addresses it shows (JSON, in order). A change to |
| 60 | // the list moves the card's revision, so Confirm confirms what was shown. |
| 61 | type researchInventoryRecord struct { |
| 62 | CardID string `gorm:"primaryKey"` |
| 63 | RunnerID string `gorm:"index:chat_research_inventory_runner"` |
| 64 | Addresses string |
| 65 | CreatedAt time.Time |
| 66 | UpdatedAt time.Time |
| 67 | } |
| 68 | |
| 69 | func (researchInventoryRecord) TableName() string { return "chat_research_inventory" } |
| 70 | |
| 71 | // Audit kind of an owner's Confirm. |
| 72 | const auditInventoryConfirmed = "research.inventory_confirmed" |
| 73 | |
| 74 | // SetForwardedHops sets how many proxies the runner stream trusts in |
| 75 | // X-Forwarded-For (tests: an edge in front). Without it the stream |
| 76 | // trusts the CARLOS edge when it runs on CARLOS and nothing otherwise. |
| 77 | func (s *Store) SetForwardedHops(n int) { s.hops.Store(&n) } |
| 78 | |
| 79 | func (s *Store) forwardedHops() int { |
| 80 | if p := s.hops.Load(); p != nil { |
| 81 | return *p |
| 82 | } |
| 83 | if carlos.Running() { |
| 84 | return clientip.DefaultHops |
| 85 | } |
| 86 | return 0 |
| 87 | } |
| 88 | |
| 89 | // ObservedAddress is the address a runner's stream request came from, |
| 90 | // for the site inventory: the element of X-Forwarded-For that the |
| 91 | // proxies in front of the instance wrote (counted from the right, as |
| 92 | // clientip reads it; never one the client wrote), or the connection's |
| 93 | // own address when nothing is in front. "" unless it is a valid global |
| 94 | // address (wire.ValidResearchAddress). |
| 95 | func (s *Store) ObservedAddress(r *http.Request) string { |
| 96 | a, err := netip.ParseAddr(strings.TrimSpace(clientip.From(r, s.forwardedHops()))) |
| 97 | if err != nil { |
| 98 | return "" |
| 99 | } |
| 100 | a = a.Unmap() |
| 101 | if !wire.ValidResearchAddress(a.String()) { |
| 102 | return "" |
| 103 | } |
| 104 | return a.String() |
| 105 | } |
| 106 | |
| 107 | // helloAddresses are the valid addresses a hello reports, in order and |
| 108 | // once each, at most wire.MaxResearchAddresses; ok is false when the |
| 109 | // hello does not say (no Research capability: the first hello before |
| 110 | // the welcome, or a runner below protocol 13), and then nothing changes. |
| 111 | func helloAddresses(h wire.Hello) (out []string, ok bool) { |
| 112 | if h.Capabilities == nil || h.Capabilities.Research == nil { |
| 113 | return nil, false |
| 114 | } |
| 115 | for _, a := range h.Capabilities.Research.Addresses { |
| 116 | if len(out) == wire.MaxResearchAddresses { |
| 117 | break |
| 118 | } |
| 119 | if wire.ValidResearchAddress(a) && !slices.Contains(out, a) { |
| 120 | out = append(out, a) |
| 121 | } |
| 122 | } |
| 123 | return out, true |
| 124 | } |
| 125 | |
| 126 | // setAddresses replaces the runner's detected addresses of one source |
| 127 | // with list, reporting whether anything changed. |
| 128 | func (t *txn) setAddresses(runnerID, source string, list []string) (bool, error) { |
| 129 | var have []string |
| 130 | if err := t.db.Model(&researchAddressRecord{}).Where("runner_id = ? AND source = ?", runnerID, source).Pluck("address", &have).Error; err != nil { |
| 131 | return false, err |
| 132 | } |
| 133 | slices.Sort(have) |
| 134 | want := slices.Clone(list) |
| 135 | slices.Sort(want) |
| 136 | if slices.Equal(have, want) { |
| 137 | return false, nil |
| 138 | } |
| 139 | if err := t.db.Where("runner_id = ? AND source = ? AND address NOT IN ?", runnerID, source, append(want, "")).Delete(&researchAddressRecord{}).Error; err != nil { |
| 140 | return false, err |
| 141 | } |
| 142 | now := t.now() |
| 143 | for _, a := range want { |
| 144 | if slices.Contains(have, a) { |
| 145 | continue |
| 146 | } |
| 147 | if err := t.db.Create(&researchAddressRecord{RunnerID: runnerID, Source: source, Address: a, SeenAt: now}).Error; err != nil { |
| 148 | return false, err |
| 149 | } |
| 150 | } |
| 151 | return true, nil |
| 152 | } |
| 153 | |
| 154 | // recordAddresses records what a primary's hello and connection say |
| 155 | // about its addresses (observed only on a new connection: nil keeps it) |
| 156 | // and, when that changed or the connection is new, looks again at the |
| 157 | // person's Research steps waiting for the inventory. |
| 158 | func (t *txn) recordAddresses(l Lease, hello wire.Hello, observed *string) error { |
| 159 | changed := false |
| 160 | if list, ok := helloAddresses(hello); ok { |
| 161 | c, err := t.setAddresses(l.Runner.RunnerID, addressInterface, list) |
| 162 | if err != nil { |
| 163 | return err |
| 164 | } |
| 165 | changed = changed || c |
| 166 | } |
| 167 | if observed != nil { |
| 168 | var list []string |
| 169 | if *observed != "" { |
| 170 | list = []string{*observed} |
| 171 | } |
| 172 | c, err := t.setAddresses(l.Runner.RunnerID, addressObserved, list) |
| 173 | if err != nil { |
| 174 | return err |
| 175 | } |
| 176 | changed = changed || c |
| 177 | } |
| 178 | if !changed && observed == nil { |
| 179 | // Nothing changed. Still, a hello that says the runner has no |
| 180 | // address at all (with none observed) ends the Research steps |
| 181 | // waiting for its inventory, so they are looked at again. |
| 182 | if _, ok := helloAddresses(hello); !ok { |
| 183 | return nil |
| 184 | } |
| 185 | if detected, err := t.detectedAddresses(l.Runner.RunnerID); err != nil || len(detected) > 0 { |
| 186 | return err |
| 187 | } |
| 188 | } |
| 189 | return t.inventoryChanged(l.Runner.RunnerID, l.Runner.Person) |
| 190 | } |
| 191 | |
| 192 | // detectedAddresses are the runner's detected addresses, once each, in |
| 193 | // address order. |
| 194 | func (t *txn) detectedAddresses(runnerID string) ([]string, error) { |
| 195 | var raw []string |
| 196 | if err := t.db.Model(&researchAddressRecord{}).Where("runner_id = ?", runnerID).Distinct().Pluck("address", &raw).Error; err != nil { |
| 197 | return nil, err |
| 198 | } |
| 199 | var addrs []netip.Addr |
| 200 | for _, s := range raw { |
| 201 | if a, err := netip.ParseAddr(s); err == nil && wire.ValidResearchAddress(s) { |
| 202 | addrs = append(addrs, a) |
| 203 | } |
| 204 | } |
| 205 | slices.SortFunc(addrs, netip.Addr.Compare) |
| 206 | out := []string{} |
| 207 | for _, a := range slices.Compact(addrs) { |
| 208 | out = append(out, a.String()) |
| 209 | } |
| 210 | return out, nil |
| 211 | } |
| 212 | |
| 213 | // researchInventory is the runner's confirmed site inventory (spec |
| 214 | // §3.3): its confirmed prefixes, in order, and the addresses detected |
| 215 | // for it now. ok only when at least one address is detected and every |
| 216 | // detected address is inside a confirmed prefix; otherwise no Research |
| 217 | // step is dispatched to it. |
| 218 | func (t *txn) researchInventory(runnerID string) (prefixes, detected []string, ok bool, err error) { |
| 219 | if detected, err = t.detectedAddresses(runnerID); err != nil { |
| 220 | return nil, nil, false, err |
| 221 | } |
| 222 | if err = t.db.Model(&researchPrefixRecord{}).Where("runner_id = ?", runnerID).Order("prefix").Pluck("prefix", &prefixes).Error; err != nil { |
| 223 | return nil, nil, false, err |
| 224 | } |
| 225 | var parsed []netip.Prefix |
| 226 | for _, s := range prefixes { |
| 227 | if p, err := netip.ParsePrefix(s); err == nil { |
| 228 | parsed = append(parsed, p) |
| 229 | } |
| 230 | } |
| 231 | return prefixes, detected, len(detected) > 0 && len(uncovered(detected, parsed)) == 0, nil |
| 232 | } |
| 233 | |
| 234 | // uncovered are the addresses in no prefix. |
| 235 | func uncovered(addrs []string, prefixes []netip.Prefix) []string { |
| 236 | var out []string |
| 237 | for _, s := range addrs { |
| 238 | a, err := netip.ParseAddr(s) |
| 239 | if err != nil || !slices.ContainsFunc(prefixes, func(p netip.Prefix) bool { return p.Contains(a) }) { |
| 240 | out = append(out, s) |
| 241 | } |
| 242 | } |
| 243 | return out |
| 244 | } |
| 245 | |
| 246 | // openInventoryCard is the runner's open research_inventory card, if any. |
| 247 | func (t *txn) openInventoryCard(runnerID string) (cardRecord, researchInventoryRecord, bool, error) { |
| 248 | var inv researchInventoryRecord |
| 249 | var c cardRecord |
| 250 | err := t.db.Model(&researchInventoryRecord{}).Joins("JOIN chat_cards ON chat_cards.id = chat_research_inventory.card_id").Where("chat_research_inventory.runner_id = ? AND chat_cards.state = ?", runnerID, wire.CardOpen).Order("chat_research_inventory.created_at").First(&inv).Error |
| 251 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 252 | return c, inv, false, nil |
| 253 | } else if err != nil { |
| 254 | return c, inv, false, err |
| 255 | } |
| 256 | if err := t.db.Where("id = ?", inv.CardID).First(&c).Error; err != nil { |
| 257 | return c, inv, false, err |
| 258 | } |
| 259 | return c, inv, true, nil |
| 260 | } |
| 261 | |
| 262 | // raiseInventory asks an owner to confirm the runner's detected |
| 263 | // addresses, when some are outside the confirmed prefixes: one open card |
| 264 | // per runner, to the task's creator while they are an owner, else to an |
| 265 | // owner. A card already open shows the list as it is now (a changed list |
| 266 | // moves its revision). With nothing detected there is nothing to ask. |
| 267 | func (t *txn) raiseInventory(k *taskRecord, s *stepRecord, runnerID string, detected []string) error { |
| 268 | if len(detected) == 0 { |
| 269 | return nil |
| 270 | } |
| 271 | list, _ := json.Marshal(detected) |
| 272 | c, inv, open, err := t.openInventoryCard(runnerID) |
| 273 | if err != nil { |
| 274 | return err |
| 275 | } |
| 276 | if open { |
| 277 | if inv.Addresses == string(list) { |
| 278 | return nil |
| 279 | } |
| 280 | inv.Addresses, inv.UpdatedAt = string(list), t.now() |
| 281 | if err := t.db.Model(&researchInventoryRecord{}).Where("card_id = ?", inv.CardID).Select("addresses", "updated_at").Updates(&inv).Error; err != nil { |
| 282 | return err |
| 283 | } |
| 284 | return t.saveCard(&c) |
| 285 | } |
| 286 | owner, err := t.inventoryOwner(k.Creator) |
| 287 | if err != nil || owner == "" { |
| 288 | return err |
| 289 | } |
| 290 | question := t.words("chat.card.research_inventory") |
| 291 | if question == "" { |
| 292 | question = "Research fetches from these addresses." |
| 293 | } |
| 294 | options, _ := json.Marshal([]string{wire.ChoiceConfirm}) |
| 295 | now := t.now() |
| 296 | // The card is in the lane of the turn that asked for the research, or |
| 297 | // else the task's when the creator is asked (J4). |
| 298 | turn, lane := "", "" |
| 299 | switch { |
| 300 | case owner == s.Person && s.RequestTurn != "": |
| 301 | turn = s.RequestTurn |
| 302 | if lane, err = t.turnLane(owner, turn); err != nil { |
| 303 | return err |
| 304 | } |
| 305 | case owner == k.Creator: |
| 306 | lane = k.Lane |
| 307 | } |
| 308 | c = cardRecord{ID: newID("c_"), Person: owner, Kind: wire.CardResearchInventory, State: wire.CardOpen, TurnID: turn, TaskID: k.ID, Question: question, Options: string(options), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: lane} |
| 309 | if err := t.db.Create(&c).Error; err != nil { |
| 310 | return err |
| 311 | } |
| 312 | if err := t.db.Create(&researchInventoryRecord{CardID: c.ID, RunnerID: runnerID, Addresses: string(list), CreatedAt: now, UpdatedAt: now}).Error; err != nil { |
| 313 | return err |
| 314 | } |
| 315 | return t.cardEvent(c) |
| 316 | } |
| 317 | |
| 318 | // inventoryOwner is who is asked: the task's creator while an owner, |
| 319 | // else the first active owner; "" when there is none. |
| 320 | func (t *txn) inventoryOwner(creator string) (string, error) { |
| 321 | if err := t.isOwner(creator); err == nil { |
| 322 | return creator, nil |
| 323 | } else if !errors.Is(err, ErrForbidden) { |
| 324 | return "", err |
| 325 | } |
| 326 | var owners []string |
| 327 | if err := t.db.Raw("SELECT address FROM members WHERE active = 1 AND role = ? ORDER BY address", "owner").Scan(&owners).Error; err != nil { |
| 328 | return "", err |
| 329 | } |
| 330 | for _, o := range owners { |
| 331 | if err := t.isOwner(o); err == nil { |
| 332 | return o, nil |
| 333 | } else if !errors.Is(err, ErrForbidden) { |
| 334 | return "", err |
| 335 | } |
| 336 | } |
| 337 | return "", nil |
| 338 | } |
| 339 | |
| 340 | // inventoryView is what an inventory card shows. |
| 341 | func (t *txn) inventoryView(c cardRecord) (*wire.CardInventoryView, error) { |
| 342 | var inv researchInventoryRecord |
| 343 | if err := t.db.Where("card_id = ?", c.ID).First(&inv).Error; err != nil { |
| 344 | return nil, err |
| 345 | } |
| 346 | v := &wire.CardInventoryView{RunnerID: inv.RunnerID, Addresses: []string{}} |
| 347 | if err := json.Unmarshal([]byte(inv.Addresses), &v.Addresses); err != nil { |
| 348 | return nil, err |
| 349 | } |
| 350 | return v, nil |
| 351 | } |
| 352 | |
| 353 | // answerResearchInventory is an owner's Confirm on an inventory card: |
| 354 | // only Confirm; open and at its current revision, else a conflict with |
| 355 | // the card as it stands; the card's person, an owner now (read in this |
| 356 | // transaction). In this one transaction it records the prefixes of every |
| 357 | // address the card shows (the address, and an IPv6 address's /64) with |
| 358 | // who and when, audits it, and dispatches every Research step whose |
| 359 | // inventory is now complete. |
| 360 | func (t *txn) answerResearchInventory(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| 361 | v, err := t.cardView(c) |
| 362 | if err != nil { |
| 363 | return wire.Card{}, wire.Card{}, err |
| 364 | } |
| 365 | if in.Choice != wire.ChoiceConfirm { |
| 366 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 367 | } |
| 368 | if c.State != wire.CardOpen || c.Revision != in.Revision { |
| 369 | return wire.Card{}, v, ErrCardConflict |
| 370 | } |
| 371 | if c.Person != person { |
| 372 | return wire.Card{}, wire.Card{}, ErrForbidden |
| 373 | } |
| 374 | if err := t.isOwner(person); err != nil { |
| 375 | return wire.Card{}, wire.Card{}, err |
| 376 | } |
| 377 | shown, err := t.inventoryView(c) |
| 378 | if err != nil { |
| 379 | return wire.Card{}, wire.Card{}, err |
| 380 | } |
| 381 | now := t.now() |
| 382 | var confirmed []string |
| 383 | for _, a := range shown.Addresses { |
| 384 | for _, p := range wire.ResearchPrefixes(a) { |
| 385 | row := researchPrefixRecord{RunnerID: shown.RunnerID, Prefix: p, ConfirmedBy: person, ConfirmedAt: now, CardID: c.ID} |
| 386 | if err := t.db.Clauses(clause.OnConflict{DoNothing: true}).Create(&row).Error; err != nil { |
| 387 | return wire.Card{}, wire.Card{}, err |
| 388 | } |
| 389 | confirmed = append(confirmed, p) |
| 390 | } |
| 391 | } |
| 392 | if t.s.authority.Audit != nil { |
| 393 | if err := t.s.authority.Audit(t.db, person, auditInventoryConfirmed, shown.RunnerID+" "+strings.Join(confirmed, ",")); err != nil { |
| 394 | return wire.Card{}, wire.Card{}, err |
| 395 | } |
| 396 | } |
| 397 | c.State, c.Choice = wire.CardAnswered, in.Choice |
| 398 | if err := t.saveCard(&c); err != nil { |
| 399 | return wire.Card{}, wire.Card{}, err |
| 400 | } |
| 401 | if err := t.recheckInventory(""); err != nil { |
| 402 | return wire.Card{}, wire.Card{}, err |
| 403 | } |
| 404 | out, err := t.cardView(c) |
| 405 | return out, wire.Card{}, err |
| 406 | } |
| 407 | |
| 408 | // inventoryChanged follows a change in a runner's detected addresses (or |
| 409 | // a new connection): its open card shows the list as it is now, and the |
| 410 | // person's Research steps waiting for the inventory are looked at again |
| 411 | // (dispatched when it is complete, ended on a runner below protocol 13). |
| 412 | func (t *txn) inventoryChanged(runnerID, person string) error { |
| 413 | if _, _, open, err := t.openInventoryCard(runnerID); err != nil { |
| 414 | return err |
| 415 | } else if open { |
| 416 | _, detected, ok, err := t.researchInventory(runnerID) |
| 417 | if err != nil { |
| 418 | return err |
| 419 | } |
| 420 | if !ok { |
| 421 | // The k and s only matter for a new card; this one is open. |
| 422 | if err := t.raiseInventory(&taskRecord{}, &stepRecord{}, runnerID, detected); err != nil { |
| 423 | return err |
| 424 | } |
| 425 | } |
| 426 | } |
| 427 | return t.recheckInventory(person) |
| 428 | } |
| 429 | |
| 430 | // recheckInventory runs dispatch again for the Research steps waiting |
| 431 | // for the inventory (the person's, or everyone's for ""), saving those |
| 432 | // that moved on. |
| 433 | func (t *txn) recheckInventory(person string) error { |
| 434 | q := t.db.Where("specialist = ? AND state = ? AND placement = ?", wire.SpecialistResearch, wire.StepQueued, wire.PlacementInventory) |
| 435 | if person != "" { |
| 436 | q = q.Where("person = ?", person) |
| 437 | } |
| 438 | var rows []stepRecord |
| 439 | if err := q.Order("created_at, id").Find(&rows).Error; err != nil { |
| 440 | return err |
| 441 | } |
| 442 | for i := range rows { |
| 443 | s := &rows[i] |
| 444 | k, err := t.loadTask(s.TaskID) |
| 445 | if err != nil { |
| 446 | return err |
| 447 | } |
| 448 | if wire.FinalStage(k.Stage) || k.CancelRequested { |
| 449 | continue |
| 450 | } |
| 451 | if err := t.dispatchStep(&k, s); err != nil { |
| 452 | return err |
| 453 | } |
| 454 | if s.State == wire.StepQueued && s.Placement == wire.PlacementInventory { |
| 455 | continue |
| 456 | } |
| 457 | if err := t.saveStep(s, &k); err != nil { |
| 458 | return err |
| 459 | } |
| 460 | } |
| 461 | return nil |
| 462 | } |
| 463 | |