| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "log/slog" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/equipo/assist" |
| 19 | "amadan.net/oficina/equipo/internal/wire" |
| 20 | "amadan.net/rastrillo/rastrillo/db" |
| 21 | "gorm.io/gorm" |
| 22 | ) |
| 23 | |
| 24 | // fakeBoardBase is a person's Base as Equipo fetches their board from it |
| 25 | // (GET /api/v1/abilities) and, for a Base older than the board, its |
| 26 | // operations (GET /api/v1/operations), both with the member's host token. |
| 27 | // Each route answers its scripted status; 200 on the board serves board. |
| 28 | type fakeBoardBase struct { |
| 29 | srv *httptest.Server |
| 30 | |
| 31 | mu sync.Mutex |
| 32 | token string |
| 33 | board wire.AbilityBoard |
| 34 | status int // the board's status (200 by default) |
| 35 | raw string // when set, the board's 200 body as it is |
| 36 | opsStatus int // the operations' status (200 by default) |
| 37 | boardCalls int |
| 38 | opsCalls int |
| 39 | tokens []string |
| 40 | // hold, when set, keeps the next board request until it is closed; |
| 41 | // entered is closed when that request arrives. |
| 42 | hold, entered chan struct{} |
| 43 | } |
| 44 | |
| 45 | func startBoardBase(t *testing.T, token string) *fakeBoardBase { |
| 46 | t.Helper() |
| 47 | f := &fakeBoardBase{token: token, status: 200, opsStatus: 200, |
| 48 | board: wire.AbilityBoard{Revision: 1, Ask: "Paul", Abilities: map[string]bool{"web": true, "apps_read": true, "apps_write": true, "build": true, "go_live": true, "services": true, "services_add": true}}} |
| 49 | f.srv = httptest.NewServer(http.HandlerFunc(f.serve)) // 127.0.0.1 only |
| 50 | t.Cleanup(f.srv.Close) |
| 51 | return f |
| 52 | } |
| 53 | |
| 54 | func (f *fakeBoardBase) origin() string { return f.srv.URL } |
| 55 | |
| 56 | func (f *fakeBoardBase) serve(w http.ResponseWriter, r *http.Request) { |
| 57 | f.mu.Lock() |
| 58 | f.tokens = append(f.tokens, r.Header.Get("Authorization")) |
| 59 | authorized := r.Header.Get("Authorization") == "Bearer "+f.token |
| 60 | var status int |
| 61 | var body any |
| 62 | hold, entered := f.hold, f.entered |
| 63 | switch r.URL.Path { |
| 64 | case "/api/v1/abilities": |
| 65 | f.boardCalls++ |
| 66 | status, body = f.status, f.board |
| 67 | f.hold, f.entered = nil, nil |
| 68 | case "/api/v1/operations": |
| 69 | f.opsCalls++ |
| 70 | status, body, hold = f.opsStatus, map[string]any{"operations": []any{}}, nil |
| 71 | default: |
| 72 | status, hold = 404, nil |
| 73 | } |
| 74 | f.mu.Unlock() |
| 75 | if hold != nil { |
| 76 | close(entered) |
| 77 | <-hold |
| 78 | } |
| 79 | if !authorized { |
| 80 | status = 401 |
| 81 | } |
| 82 | w.Header().Set("Content-Type", "application/json") |
| 83 | w.WriteHeader(status) |
| 84 | f.mu.Lock() |
| 85 | raw := f.raw |
| 86 | f.mu.Unlock() |
| 87 | if status == 200 && raw != "" && r.URL.Path == "/api/v1/abilities" { |
| 88 | _, _ = io.WriteString(w, raw) |
| 89 | } else if status == 200 { |
| 90 | _ = json.NewEncoder(w).Encode(body) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | func (f *fakeBoardBase) set(fn func(f *fakeBoardBase)) { |
| 95 | f.mu.Lock() |
| 96 | defer f.mu.Unlock() |
| 97 | fn(f) |
| 98 | } |
| 99 | |
| 100 | func (f *fakeBoardBase) counts() (board, ops int) { |
| 101 | f.mu.Lock() |
| 102 | defer f.mu.Unlock() |
| 103 | return f.boardCalls, f.opsCalls |
| 104 | } |
| 105 | |
| 106 | // holdNext keeps the next board request until release; entered is |
| 107 | // closed when it arrives. |
| 108 | func (f *fakeBoardBase) holdNext() (entered <-chan struct{}, release func()) { |
| 109 | f.mu.Lock() |
| 110 | defer f.mu.Unlock() |
| 111 | f.hold, f.entered = make(chan struct{}), make(chan struct{}) |
| 112 | hold := f.hold |
| 113 | var once sync.Once |
| 114 | return f.entered, func() { once.Do(func() { close(hold) }) } |
| 115 | } |
| 116 | |
| 117 | // abilitiesHarness is a chat Store whose people's Bases are allowed hosts, |
| 118 | // with a clock the test moves and an audit it reads. |
| 119 | type abilitiesHarness struct { |
| 120 | s *Store |
| 121 | auth Authority |
| 122 | mu sync.Mutex |
| 123 | at time.Time |
| 124 | audits []string |
| 125 | // failAudit, when set, is an audit kind whose writing fails. |
| 126 | failAudit string |
| 127 | } |
| 128 | |
| 129 | const abPerson = "member@example.com" |
| 130 | |
| 131 | // goneMember is a person removed from the roster. |
| 132 | const goneMember = "gone@example.com" |
| 133 | |
| 134 | func newAbilitiesHarness(t *testing.T, hosts ...string) *abilitiesHarness { |
| 135 | t.Helper() |
| 136 | src, err := hkTemplatePath() |
| 137 | if err != nil { |
| 138 | t.Fatal(err) |
| 139 | } |
| 140 | raw, err := os.ReadFile(src) |
| 141 | if err != nil { |
| 142 | t.Fatal(err) |
| 143 | } |
| 144 | path := filepath.Join(t.TempDir(), "abilities.db") |
| 145 | if err := os.WriteFile(path, raw, 0o600); err != nil { |
| 146 | t.Fatal(err) |
| 147 | } |
| 148 | d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 149 | if err != nil { |
| 150 | t.Fatal(err) |
| 151 | } |
| 152 | t.Cleanup(func() { _ = d.Close() }) |
| 153 | h := &abilitiesHarness{at: time.Date(2026, 11, 28, 12, 0, 0, 0, time.UTC)} |
| 154 | lowered := make([]string, len(hosts)) |
| 155 | for i, o := range hosts { |
| 156 | lowered[i] = strings.ToLower(o) |
| 157 | } |
| 158 | h.auth = Authority{ |
| 159 | CurrentPerson: func(context.Context, *gorm.DB) error { return nil }, |
| 160 | PrimaryRunner: func(*gorm.DB, string) (string, error) { return "RUNNER1", nil }, |
| 161 | Audit: func(_ *gorm.DB, actor, kind, record string) error { |
| 162 | if kind == h.failAudit { |
| 163 | return errors.New("audit failed") |
| 164 | } |
| 165 | h.mu.Lock() |
| 166 | h.audits = append(h.audits, kind+" "+actor+" "+record) |
| 167 | h.mu.Unlock() |
| 168 | return nil |
| 169 | }, |
| 170 | Copy: func(key string) string { |
| 171 | if name, ok := abilityNames[key]; ok { |
| 172 | return name |
| 173 | } |
| 174 | return key |
| 175 | }, |
| 176 | Me: func(_ *gorm.DB, address string) (wire.Me, error) { |
| 177 | if address == goneMember { |
| 178 | return wire.Me{}, ErrForbidden |
| 179 | } |
| 180 | role := "member" |
| 181 | if address == "owner@example.com" { |
| 182 | role = "owner" |
| 183 | } |
| 184 | return wire.Me{Address: address, Role: role, Person: wire.Person{Address: address, Active: true}}, nil |
| 185 | }, |
| 186 | AssistantHosts: lowered, |
| 187 | Seal: func(_ string, v any) (string, error) { |
| 188 | raw, err := json.Marshal(v) |
| 189 | return string(raw), err |
| 190 | }, |
| 191 | Open: func(_ string, sealed string, v any) error { return json.Unmarshal([]byte(sealed), v) }, |
| 192 | } |
| 193 | h.s = NewStore(d, h.auth, nil) |
| 194 | h.s.SetClock(h.now) |
| 195 | return h |
| 196 | } |
| 197 | |
| 198 | // withHosts is another store on the same database whose operator allows |
| 199 | // only hosts, sharing the clock and the audit. |
| 200 | func (h *abilitiesHarness) withHosts(hosts ...string) *abilitiesHarness { |
| 201 | auth := h.auth |
| 202 | auth.AssistantHosts = nil |
| 203 | for _, o := range hosts { |
| 204 | auth.AssistantHosts = append(auth.AssistantHosts, strings.ToLower(o)) |
| 205 | } |
| 206 | h2 := &abilitiesHarness{auth: auth, at: h.now()} |
| 207 | h2.s = NewStore(h.s.db, auth, nil) |
| 208 | h2.s.SetClock(h2.now) |
| 209 | return h2 |
| 210 | } |
| 211 | |
| 212 | func (h *abilitiesHarness) now() time.Time { |
| 213 | h.mu.Lock() |
| 214 | defer h.mu.Unlock() |
| 215 | return h.at |
| 216 | } |
| 217 | |
| 218 | func (h *abilitiesHarness) advance(d time.Duration) { |
| 219 | h.mu.Lock() |
| 220 | h.at = h.at.Add(d) |
| 221 | h.mu.Unlock() |
| 222 | } |
| 223 | |
| 224 | func (h *abilitiesHarness) audited(kind string) []string { |
| 225 | h.mu.Lock() |
| 226 | defer h.mu.Unlock() |
| 227 | var out []string |
| 228 | for _, a := range h.audits { |
| 229 | if strings.HasPrefix(a, kind+" ") { |
| 230 | out = append(out, a) |
| 231 | } |
| 232 | } |
| 233 | return out |
| 234 | } |
| 235 | |
| 236 | // register stores origin and token as the person's Base host, as PUT host |
| 237 | // left it, without asking Base. |
| 238 | func (h *abilitiesHarness) register(t *testing.T, person, origin, token string) { |
| 239 | t.Helper() |
| 240 | sealed, _ := json.Marshal(token) |
| 241 | rec := assistantHostRecord{Person: person, Origin: strings.ToLower(origin), Token: string(sealed), Revision: 1, UpdatedAt: h.now()} |
| 242 | if err := h.s.db.G.Save(&rec).Error; err != nil { |
| 243 | t.Fatal(err) |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | // row is the person's stored board at origin. |
| 248 | func (h *abilitiesHarness) row(t *testing.T, person, origin string) abilitiesRecord { |
| 249 | t.Helper() |
| 250 | var r abilitiesRecord |
| 251 | if err := h.s.db.G.Where("person = ? AND origin = ?", person, strings.ToLower(origin)).Limit(1).Find(&r).Error; err != nil { |
| 252 | t.Fatal(err) |
| 253 | } |
| 254 | return r |
| 255 | } |
| 256 | |
| 257 | // switchesOf reads the person's switches in a transaction of their own. |
| 258 | func (h *abilitiesHarness) switchesOf(t *testing.T, person string) Switches { |
| 259 | t.Helper() |
| 260 | var sw Switches |
| 261 | if err := h.s.tx(context.Background(), func(tx *txn) error { |
| 262 | var err error |
| 263 | sw, err = tx.switches(person) |
| 264 | return err |
| 265 | }); err != nil { |
| 266 | t.Fatal(err) |
| 267 | } |
| 268 | return sw |
| 269 | } |
| 270 | |
| 271 | // refusalCode is err's assist.Refusal code, "" for none. |
| 272 | func refusalCode(err error) string { |
| 273 | var r assist.Refusal |
| 274 | if errors.As(err, &r) { |
| 275 | return r.Code |
| 276 | } |
| 277 | return "" |
| 278 | } |
| 279 | |
| 280 | // abilityNames are Equipo's copy for the abilities' plain names (Paul's |
| 281 | // approved review of 2026-11-28, Base's abilities.<key>.name). |
| 282 | var abilityNames = map[string]string{ |
| 283 | "assistant.ability.web.name": "Look things up on the web", |
| 284 | "assistant.ability.apps_read.name": "Read their Oficina apps", |
| 285 | "assistant.ability.apps_write.name": "Create and edit in Oficina apps", |
| 286 | "assistant.ability.build.name": "Build sites and apps", |
| 287 | "assistant.ability.go_live.name": "Put things live", |
| 288 | "assistant.ability.services.name": "Connect outside services", |
| 289 | "assistant.ability.services_add.name": "Add services for everyone", |
| 290 | } |
| 291 | |