| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "net/netip" |
| 8 | "slices" |
| 9 | "strings" |
| 10 | "sync/atomic" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/websource/guard" |
| 14 | "amadan.net/oficina/equipo/internal/websource/hostaddrs" |
| 15 | "amadan.net/oficina/equipo/internal/wire" |
| 16 | "gorm.io/gorm" |
| 17 | "gorm.io/gorm/clause" |
| 18 | ) |
| 19 | |
| 20 | // The instance inventory (spec 2026-11-26-assistant-abilities §4.3; MCP |
| 21 | // plan Task 7): the network the instance itself is on, which no request |
| 22 | // to the public web may reach. The operator lists its prefixes |
| 23 | // (EQUIPO_INSTANCE_PREFIXES); the instance scans its own interfaces' |
| 24 | // public addresses at start and hourly (websource/hostaddrs: netlink, or |
| 25 | // procfs where it is refused, as on CARLOS); an Equipo owner confirms. |
| 26 | // Until every listed prefix is confirmed and every address seen is inside |
| 27 | // one, the inventory isn't ready, and nothing that needs it (lookups, |
| 28 | // services) runs; each change asks every owner once, on an |
| 29 | // instance_inventory card. |
| 30 | |
| 31 | // instancePrefixRecord is a prefix an owner confirmed: who, when, on |
| 32 | // which card. Never removed. |
| 33 | type instancePrefixRecord struct { |
| 34 | Prefix string `gorm:"primaryKey"` |
| 35 | ConfirmedBy string |
| 36 | ConfirmedAt time.Time |
| 37 | CardID string |
| 38 | } |
| 39 | |
| 40 | func (instancePrefixRecord) TableName() string { return "instance_prefixes" } |
| 41 | |
| 42 | // instanceAddressRecord is an address the latest scan saw on one of the |
| 43 | // instance's interfaces. |
| 44 | type instanceAddressRecord struct { |
| 45 | Address string `gorm:"primaryKey"` |
| 46 | SeenAt time.Time |
| 47 | } |
| 48 | |
| 49 | func (instanceAddressRecord) TableName() string { return "instance_addresses" } |
| 50 | |
| 51 | // instanceInventoryCardRecord binds an instance_inventory card to what |
| 52 | // it shows: the prefixes listed and the addresses seen (JSON, in order). |
| 53 | // Confirm confirms exactly those prefixes. |
| 54 | type instanceInventoryCardRecord struct { |
| 55 | CardID string `gorm:"primaryKey"` |
| 56 | Prefixes string |
| 57 | Addresses string |
| 58 | CreatedAt time.Time |
| 59 | } |
| 60 | |
| 61 | func (instanceInventoryCardRecord) TableName() string { return "chat_instance_inventory" } |
| 62 | |
| 63 | // Audit kind of an owner's Confirm. |
| 64 | const auditInstanceInventory = "services.inventory_confirmed" |
| 65 | |
| 66 | // inventorySnap is what Inside reads, kept in memory: the prefixes |
| 67 | // listed and confirmed, and the addresses the latest scan saw. |
| 68 | type inventorySnap struct { |
| 69 | prefixes []netip.Prefix |
| 70 | addrs []netip.Addr |
| 71 | } |
| 72 | |
| 73 | // instanceNet is the store's inventory state outside the database. |
| 74 | type instanceNet struct { |
| 75 | listed atomic.Pointer[[]netip.Prefix] |
| 76 | snap atomic.Pointer[inventorySnap] |
| 77 | // scanned: this process's latest scan succeeded and committed. Until |
| 78 | // then, and after one fails, the inventory isn't ready. |
| 79 | scanned atomic.Bool |
| 80 | } |
| 81 | |
| 82 | // ParseInstancePrefixes reads EQUIPO_INSTANCE_PREFIXES: comma-separated |
| 83 | // prefixes, as 203.0.113.0/24. |
| 84 | func ParseInstancePrefixes(raw string) ([]netip.Prefix, error) { |
| 85 | var out []netip.Prefix |
| 86 | for _, f := range strings.Split(raw, ",") { |
| 87 | if f = strings.TrimSpace(f); f == "" { |
| 88 | continue |
| 89 | } |
| 90 | p, err := netip.ParsePrefix(f) |
| 91 | if err != nil { |
| 92 | return nil, errors.New("instance prefixes: " + f + " is not a prefix") |
| 93 | } |
| 94 | out = append(out, p.Masked()) |
| 95 | } |
| 96 | return out, nil |
| 97 | } |
| 98 | |
| 99 | // SetInstancePrefixes sets the operator's prefixes (ParseInstancePrefixes). |
| 100 | // Empty, the inventory is never ready. |
| 101 | func (s *Store) SetInstancePrefixes(raw string) error { |
| 102 | out, err := ParseInstancePrefixes(raw) |
| 103 | if err != nil { |
| 104 | return err |
| 105 | } |
| 106 | s.instance.listed.Store(&out) |
| 107 | return nil |
| 108 | } |
| 109 | |
| 110 | func (s *Store) listedPrefixes() []netip.Prefix { |
| 111 | if p := s.instance.listed.Load(); p != nil { |
| 112 | return *p |
| 113 | } |
| 114 | return nil |
| 115 | } |
| 116 | |
| 117 | // InstanceInventory is the inventory the guarded client checks. |
| 118 | func (s *Store) InstanceInventory() guard.Inventory { return instanceInventory{s} } |
| 119 | |
| 120 | type instanceInventory struct{ s *Store } |
| 121 | |
| 122 | // Ready is nil once prefixes are listed, each is confirmed, and every |
| 123 | // address the latest scan saw is inside a confirmed one. |
| 124 | func (i instanceInventory) Ready(ctx context.Context) error { |
| 125 | listed := i.s.listedPrefixes() |
| 126 | if len(listed) == 0 || !i.s.instance.scanned.Load() { |
| 127 | return guard.ErrInventoryUnconfirmed |
| 128 | } |
| 129 | var ready bool |
| 130 | err := i.s.read(ctx, func(tx *gorm.DB) error { |
| 131 | var err error |
| 132 | ready, err = inventoryReady(tx, listed) |
| 133 | return err |
| 134 | }) |
| 135 | if err != nil { |
| 136 | return err |
| 137 | } |
| 138 | if !ready { |
| 139 | return guard.ErrInventoryUnconfirmed |
| 140 | } |
| 141 | return nil |
| 142 | } |
| 143 | |
| 144 | // Inside reports whether a is on the instance's network: in a prefix |
| 145 | // listed or confirmed, or an address the latest scan saw. |
| 146 | func (i instanceInventory) Inside(a netip.Addr) bool { |
| 147 | a = a.Unmap() |
| 148 | for _, p := range i.s.listedPrefixes() { |
| 149 | if p.Contains(a) { |
| 150 | return true |
| 151 | } |
| 152 | } |
| 153 | snap := i.s.instance.snap.Load() |
| 154 | if snap == nil { |
| 155 | return false |
| 156 | } |
| 157 | return slices.ContainsFunc(snap.prefixes, func(p netip.Prefix) bool { return p.Contains(a) }) || slices.Contains(snap.addrs, a) |
| 158 | } |
| 159 | |
| 160 | // inventoryReady: every listed prefix confirmed, every address seen |
| 161 | // inside a confirmed prefix. |
| 162 | func inventoryReady(tx *gorm.DB, listed []netip.Prefix) (bool, error) { |
| 163 | confirmed, addrs, err := inventoryRows(tx) |
| 164 | if err != nil { |
| 165 | return false, err |
| 166 | } |
| 167 | for _, p := range listed { |
| 168 | if !slices.Contains(confirmed, p) { |
| 169 | return false, nil |
| 170 | } |
| 171 | } |
| 172 | for _, a := range addrs { |
| 173 | if !slices.ContainsFunc(confirmed, func(p netip.Prefix) bool { return p.Contains(a) }) { |
| 174 | return false, nil |
| 175 | } |
| 176 | } |
| 177 | return true, nil |
| 178 | } |
| 179 | |
| 180 | // inventoryRows are the confirmed prefixes and the addresses seen. |
| 181 | func inventoryRows(tx *gorm.DB) ([]netip.Prefix, []netip.Addr, error) { |
| 182 | var ps, as []string |
| 183 | if err := tx.Model(&instancePrefixRecord{}).Order("prefix").Pluck("prefix", &ps).Error; err != nil { |
| 184 | return nil, nil, err |
| 185 | } |
| 186 | if err := tx.Model(&instanceAddressRecord{}).Order("address").Pluck("address", &as).Error; err != nil { |
| 187 | return nil, nil, err |
| 188 | } |
| 189 | var prefixes []netip.Prefix |
| 190 | for _, s := range ps { |
| 191 | if p, err := netip.ParsePrefix(s); err == nil { |
| 192 | prefixes = append(prefixes, p) |
| 193 | } |
| 194 | } |
| 195 | var addrs []netip.Addr |
| 196 | for _, s := range as { |
| 197 | if a, err := netip.ParseAddr(s); err == nil { |
| 198 | addrs = append(addrs, a) |
| 199 | } |
| 200 | } |
| 201 | return prefixes, addrs, nil |
| 202 | } |
| 203 | |
| 204 | // ScanInstanceAddresses records the public addresses of the instance's |
| 205 | // interfaces (hostaddrs.Public: netlink, or procfs where it is refused, |
| 206 | // at start and hourly) and, when the inventory isn't ready with prefixes |
| 207 | // listed, asks every owner to confirm it: once per change in what the |
| 208 | // card shows. Addresses that can't be listed leave it not ready. |
| 209 | func (s *Store) ScanInstanceAddresses(ctx context.Context) error { |
| 210 | seen, err := hostaddrs.Public(s.ifaceAddrs, s.procNet) |
| 211 | if err != nil { |
| 212 | s.instance.scanned.Store(false) |
| 213 | return err |
| 214 | } |
| 215 | listed := s.listedPrefixes() |
| 216 | var snap *inventorySnap |
| 217 | err = s.tx(ctx, func(t *txn) error { |
| 218 | now := t.now() |
| 219 | if err := t.db.Where("1 = 1").Delete(&instanceAddressRecord{}).Error; err != nil { |
| 220 | return err |
| 221 | } |
| 222 | for _, a := range seen { |
| 223 | if err := t.db.Create(&instanceAddressRecord{Address: a.String(), SeenAt: now}).Error; err != nil { |
| 224 | return err |
| 225 | } |
| 226 | } |
| 227 | confirmed, _, err := inventoryRows(t.db) |
| 228 | if err != nil { |
| 229 | return err |
| 230 | } |
| 231 | snap = &inventorySnap{prefixes: confirmed, addrs: seen} |
| 232 | if len(listed) == 0 { |
| 233 | return nil |
| 234 | } |
| 235 | ready, err := inventoryReady(t.db, listed) |
| 236 | if err != nil || ready { |
| 237 | return err |
| 238 | } |
| 239 | return t.askInventory(listed, seen) |
| 240 | }) |
| 241 | // Published only once committed; a scan that failed leaves the |
| 242 | // inventory not ready until one succeeds. |
| 243 | if err != nil { |
| 244 | s.instance.scanned.Store(false) |
| 245 | return err |
| 246 | } |
| 247 | s.instance.snap.Store(snap) |
| 248 | s.instance.scanned.Store(true) |
| 249 | return nil |
| 250 | } |
| 251 | |
| 252 | // askInventory asks every owner to confirm the listed prefixes and the |
| 253 | // addresses seen, unless their open card shows exactly that already. A |
| 254 | // card showing something else is withdrawn for the new one. |
| 255 | func (t *txn) askInventory(listed []netip.Prefix, seen []netip.Addr) error { |
| 256 | ps := make([]string, len(listed)) |
| 257 | for i, p := range listed { |
| 258 | ps[i] = p.String() |
| 259 | } |
| 260 | as := make([]string, len(seen)) |
| 261 | for i, a := range seen { |
| 262 | as[i] = a.String() |
| 263 | } |
| 264 | prefixes, _ := json.Marshal(ps) |
| 265 | addrs, _ := json.Marshal(as) |
| 266 | var owners []string |
| 267 | if err := t.db.Raw("SELECT address FROM members WHERE active = 1 AND role = ? ORDER BY address", "owner").Scan(&owners).Error; err != nil { |
| 268 | return err |
| 269 | } |
| 270 | options, _ := json.Marshal([]string{wire.ChoiceConfirm}) |
| 271 | for _, o := range owners { |
| 272 | if err := t.isOwner(o); errors.Is(err, ErrForbidden) { |
| 273 | continue |
| 274 | } else if err != nil { |
| 275 | return err |
| 276 | } |
| 277 | var open []cardRecord |
| 278 | if err := t.db.Where("person = ? AND kind = ? AND state = ?", o, wire.CardInstanceInventory, wire.CardOpen).Find(&open).Error; err != nil { |
| 279 | return err |
| 280 | } |
| 281 | same := false |
| 282 | for i := range open { |
| 283 | var rec instanceInventoryCardRecord |
| 284 | if err := t.db.Where("card_id = ?", open[i].ID).Limit(1).Find(&rec).Error; err != nil { |
| 285 | return err |
| 286 | } |
| 287 | if rec.Prefixes == string(prefixes) && rec.Addresses == string(addrs) { |
| 288 | same = true |
| 289 | continue |
| 290 | } |
| 291 | open[i].State = wire.CardResolved |
| 292 | if err := t.saveCard(&open[i]); err != nil { |
| 293 | return err |
| 294 | } |
| 295 | } |
| 296 | if same { |
| 297 | continue |
| 298 | } |
| 299 | now := t.now() |
| 300 | c := cardRecord{ID: newID("c_"), Person: o, Kind: wire.CardInstanceInventory, State: wire.CardOpen, Question: t.words("services.inventory.question"), Options: string(options), Revision: 1, CreatedAt: now, UpdatedAt: now} |
| 301 | if err := t.db.Create(&c).Error; err != nil { |
| 302 | return err |
| 303 | } |
| 304 | if err := t.db.Create(&instanceInventoryCardRecord{CardID: c.ID, Prefixes: string(prefixes), Addresses: string(addrs), CreatedAt: now}).Error; err != nil { |
| 305 | return err |
| 306 | } |
| 307 | if err := t.cardEvent(c); err != nil { |
| 308 | return err |
| 309 | } |
| 310 | } |
| 311 | return nil |
| 312 | } |
| 313 | |
| 314 | // instanceInventoryView is what an instance_inventory card shows: the |
| 315 | // prefixes listed, then the addresses seen. |
| 316 | func (t *txn) instanceInventoryView(c cardRecord) (*wire.CardInventoryView, []string, error) { |
| 317 | var rec instanceInventoryCardRecord |
| 318 | if err := t.db.Where("card_id = ?", c.ID).First(&rec).Error; err != nil { |
| 319 | return nil, nil, err |
| 320 | } |
| 321 | var prefixes, addrs []string |
| 322 | if err := json.Unmarshal([]byte(rec.Prefixes), &prefixes); err != nil { |
| 323 | return nil, nil, err |
| 324 | } |
| 325 | if err := json.Unmarshal([]byte(rec.Addresses), &addrs); err != nil { |
| 326 | return nil, nil, err |
| 327 | } |
| 328 | return &wire.CardInventoryView{Addresses: append(append([]string{}, prefixes...), addrs...)}, prefixes, nil |
| 329 | } |
| 330 | |
| 331 | // answerInstanceInventory is an owner's Confirm on an instance_inventory |
| 332 | // card: only Confirm, open and at its revision, by the card's person, an |
| 333 | // owner now. It records the prefixes the card shows with who and when, |
| 334 | // audits it, and answers every owner's card showing the same. |
| 335 | func (t *txn) answerInstanceInventory(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| 336 | v, err := t.cardView(c) |
| 337 | if err != nil { |
| 338 | return wire.Card{}, wire.Card{}, err |
| 339 | } |
| 340 | if in.Choice != wire.ChoiceConfirm { |
| 341 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 342 | } |
| 343 | if c.State != wire.CardOpen || c.Revision != in.Revision { |
| 344 | return wire.Card{}, v, ErrCardConflict |
| 345 | } |
| 346 | if c.Person != person { |
| 347 | return wire.Card{}, wire.Card{}, ErrForbidden |
| 348 | } |
| 349 | if err := t.isOwner(person); err != nil { |
| 350 | return wire.Card{}, wire.Card{}, err |
| 351 | } |
| 352 | _, prefixes, err := t.instanceInventoryView(c) |
| 353 | if err != nil { |
| 354 | return wire.Card{}, wire.Card{}, err |
| 355 | } |
| 356 | now := t.now() |
| 357 | for _, p := range prefixes { |
| 358 | row := instancePrefixRecord{Prefix: p, ConfirmedBy: person, ConfirmedAt: now, CardID: c.ID} |
| 359 | if err := t.db.Clauses(clause.OnConflict{DoNothing: true}).Create(&row).Error; err != nil { |
| 360 | return wire.Card{}, wire.Card{}, err |
| 361 | } |
| 362 | } |
| 363 | if t.s.authority.Audit != nil { |
| 364 | if err := t.s.authority.Audit(t.db, person, auditInstanceInventory, strings.Join(prefixes, ",")); err != nil { |
| 365 | return wire.Card{}, wire.Card{}, err |
| 366 | } |
| 367 | } |
| 368 | var shown instanceInventoryCardRecord |
| 369 | if err := t.db.Where("card_id = ?", c.ID).First(&shown).Error; err != nil { |
| 370 | return wire.Card{}, wire.Card{}, err |
| 371 | } |
| 372 | var others []cardRecord |
| 373 | if err := t.db.Where("kind = ? AND state = ? AND id <> ? AND id IN (SELECT card_id FROM chat_instance_inventory WHERE prefixes = ? AND addresses = ?)", wire.CardInstanceInventory, wire.CardOpen, c.ID, shown.Prefixes, shown.Addresses).Find(&others).Error; err != nil { |
| 374 | return wire.Card{}, wire.Card{}, err |
| 375 | } |
| 376 | for i := range others { |
| 377 | others[i].State = wire.CardResolved |
| 378 | if err := t.saveCard(&others[i]); err != nil { |
| 379 | return wire.Card{}, wire.Card{}, err |
| 380 | } |
| 381 | } |
| 382 | c.State, c.Choice = wire.CardAnswered, in.Choice |
| 383 | if err := t.saveCard(&c); err != nil { |
| 384 | return wire.Card{}, wire.Card{}, err |
| 385 | } |
| 386 | confirmed, addrs, err := inventoryRows(t.db) |
| 387 | if err != nil { |
| 388 | return wire.Card{}, wire.Card{}, err |
| 389 | } |
| 390 | t.s.instance.snap.Store(&inventorySnap{prefixes: confirmed, addrs: addrs}) |
| 391 | out, err := t.cardView(c) |
| 392 | return out, wire.Card{}, err |
| 393 | } |
| 394 | |