| 1 | package thintest |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "encoding/json" |
| 6 | "io" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | "testing" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/equipo/assist" |
| 15 | "amadan.net/oficina/equipo/internal/wire" |
| 16 | ) |
| 17 | |
| 18 | // FakeBase is Base's operations endpoint as the Assistant's base provider |
| 19 | // calls it (agent-access's contract): GET /api/v1/operations and POST |
| 20 | // /api/v1/operations/{name}, each with a bearer token Base minted for one |
| 21 | // member. It serves base_apps, base_people and base_settings, all reads, |
| 22 | // and whatever Add gives it. The name "" is the listing itself. |
| 23 | type FakeBase struct { |
| 24 | Origin string |
| 25 | // Token is one accepted bearer; Mint makes more. |
| 26 | Token string |
| 27 | // It also answers GET /api/v1/abilities (spec |
| 28 | // 2026-11-26-assistant-abilities §5.3) with each member's board: |
| 29 | // every ability on unless SetBoard says otherwise. Legacy makes it a |
| 30 | // Base older than the board, which answers that route 404. |
| 31 | |
| 32 | mu sync.Mutex |
| 33 | ops []assist.Operation |
| 34 | tokens map[string]bool |
| 35 | calls map[string][]fakeCall |
| 36 | fail map[string]string |
| 37 | hold map[string]chan struct{} |
| 38 | output map[string]string |
| 39 | // board is each token's board (boardFor), boardStatus what the board |
| 40 | // route answers instead when set, legacy a Base without the route, |
| 41 | // boardCalls the tokens it was asked with. |
| 42 | board map[string]wire.AbilityBoard |
| 43 | boardStatus int |
| 44 | legacy bool |
| 45 | boardCalls []string |
| 46 | } |
| 47 | |
| 48 | type fakeCall struct{ token, key, input string } |
| 49 | |
| 50 | // StartFakeBase serves a fake Base on 127.0.0.1 until the test ends. |
| 51 | func StartFakeBase(t testing.TB) *FakeBase { |
| 52 | t.Helper() |
| 53 | f := &FakeBase{Token: "base-" + rand.Text(), tokens: map[string]bool{}, calls: map[string][]fakeCall{}, fail: map[string]string{}, hold: map[string]chan struct{}{}, output: map[string]string{}, board: map[string]wire.AbilityBoard{}} |
| 54 | f.tokens[f.Token] = true |
| 55 | object := json.RawMessage(`{"type":"object","properties":{},"additionalProperties":false}`) |
| 56 | f.ops = []assist.Operation{ |
| 57 | {Name: "base_apps", Description: "List the person's apps and where each one lives.", Scope: "base.read", ReadOnly: true, Idempotent: true, App: "Base", Input: object}, |
| 58 | {Name: "base_people", Description: "List the people on the person's team.", Scope: "base.read", ReadOnly: true, Idempotent: true, App: "Base", Input: object}, |
| 59 | {Name: "base_settings", Description: "Read the person's Base settings.", Scope: "base.read", ReadOnly: true, Idempotent: true, App: "Base", Input: object}, |
| 60 | } |
| 61 | f.output["base_apps"] = `{"installed":[{"id":"shop","name":"Shop","address":"https://shop.example.com"}],"store":[],"oficina":[]}` |
| 62 | f.output["base_people"] = `{"people":[{"name":"Owner"}]}` |
| 63 | f.output["base_settings"] = `{"settings":{"language":"en"}}` |
| 64 | l, err := net.Listen("tcp", "127.0.0.1:0") |
| 65 | if err != nil { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | f.Origin = "http://" + l.Addr().String() |
| 69 | srv := &http.Server{Handler: http.HandlerFunc(f.serve)} |
| 70 | go srv.Serve(l) |
| 71 | t.Cleanup(func() { |
| 72 | f.mu.Lock() |
| 73 | for name, c := range f.hold { |
| 74 | close(c) |
| 75 | delete(f.hold, name) |
| 76 | } |
| 77 | f.mu.Unlock() |
| 78 | _ = srv.Close() |
| 79 | }) |
| 80 | return f |
| 81 | } |
| 82 | |
| 83 | // Mint accepts and returns another bearer token, as Base mints one per |
| 84 | // member. |
| 85 | func (f *FakeBase) Mint() string { |
| 86 | f.mu.Lock() |
| 87 | defer f.mu.Unlock() |
| 88 | token := "base-" + rand.Text() |
| 89 | f.tokens[token] = true |
| 90 | return token |
| 91 | } |
| 92 | |
| 93 | // Add serves more operations: a write, one that deletes, one that reaches |
| 94 | // outside, or one whose answer is large (Answer). |
| 95 | func (f *FakeBase) Add(ops ...assist.Operation) { |
| 96 | f.mu.Lock() |
| 97 | defer f.mu.Unlock() |
| 98 | f.ops = append(f.ops, ops...) |
| 99 | } |
| 100 | |
| 101 | // Answer sets what an operation returns. |
| 102 | func (f *FakeBase) Answer(name, output string) { |
| 103 | f.mu.Lock() |
| 104 | defer f.mu.Unlock() |
| 105 | f.output[name] = output |
| 106 | } |
| 107 | |
| 108 | // Calls is how many requests reached name ("" is the listing), with an |
| 109 | // accepted token or not. |
| 110 | func (f *FakeBase) Calls(name string) int { |
| 111 | f.mu.Lock() |
| 112 | defer f.mu.Unlock() |
| 113 | return len(f.calls[name]) |
| 114 | } |
| 115 | |
| 116 | // Keys are the Idempotency-Key headers name received, in order. |
| 117 | func (f *FakeBase) Keys(name string) []string { |
| 118 | return f.field(name, func(c fakeCall) string { return c.key }) |
| 119 | } |
| 120 | |
| 121 | // Tokens are the bearer tokens name received, in order. |
| 122 | func (f *FakeBase) Tokens(name string) []string { |
| 123 | return f.field(name, func(c fakeCall) string { return c.token }) |
| 124 | } |
| 125 | |
| 126 | // Inputs are the request bodies name received, in order. |
| 127 | func (f *FakeBase) Inputs(name string) []string { |
| 128 | return f.field(name, func(c fakeCall) string { return c.input }) |
| 129 | } |
| 130 | |
| 131 | func (f *FakeBase) field(name string, get func(fakeCall) string) []string { |
| 132 | f.mu.Lock() |
| 133 | defer f.mu.Unlock() |
| 134 | out := []string{} |
| 135 | for _, c := range f.calls[name] { |
| 136 | out = append(out, get(c)) |
| 137 | } |
| 138 | return out |
| 139 | } |
| 140 | |
| 141 | // Fail makes name answer 422 with the error code from now on ("" clears). |
| 142 | func (f *FakeBase) Fail(name, code string) { |
| 143 | f.mu.Lock() |
| 144 | defer f.mu.Unlock() |
| 145 | f.fail[name] = code |
| 146 | } |
| 147 | |
| 148 | // Hold keeps every request for name waiting, after it is counted, until |
| 149 | // release (or the caller gives up). |
| 150 | func (f *FakeBase) Hold(name string) (release func()) { |
| 151 | f.mu.Lock() |
| 152 | defer f.mu.Unlock() |
| 153 | c := make(chan struct{}) |
| 154 | f.hold[name] = c |
| 155 | var once sync.Once |
| 156 | return func() { |
| 157 | once.Do(func() { |
| 158 | f.mu.Lock() |
| 159 | if f.hold[name] == c { |
| 160 | delete(f.hold, name) |
| 161 | } |
| 162 | f.mu.Unlock() |
| 163 | close(c) |
| 164 | }) |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | // Accept accepts token as a bearer, as if Base had minted it. |
| 169 | func (f *FakeBase) Accept(token string) { |
| 170 | f.mu.Lock() |
| 171 | defer f.mu.Unlock() |
| 172 | f.tokens[token] = true |
| 173 | } |
| 174 | |
| 175 | // SetBoard is the board the member with token gets: off lists the |
| 176 | // abilities turned off, at revision, with ask as who can change them. |
| 177 | func (f *FakeBase) SetBoard(token string, revision int64, ask string, off ...string) { |
| 178 | f.mu.Lock() |
| 179 | defer f.mu.Unlock() |
| 180 | b := wire.AbilityBoard{Revision: revision, Ask: ask, Abilities: map[string]bool{}} |
| 181 | for _, k := range wire.Abilities { |
| 182 | b.Abilities[k] = !slices.Contains(off, k) |
| 183 | } |
| 184 | f.board[token] = b |
| 185 | } |
| 186 | |
| 187 | // SetLegacy makes the fake a Base older than the board (on), whose board |
| 188 | // route answers 404, or a current one again (off). |
| 189 | func (f *FakeBase) SetLegacy(on bool) { |
| 190 | f.mu.Lock() |
| 191 | defer f.mu.Unlock() |
| 192 | f.legacy = on |
| 193 | } |
| 194 | |
| 195 | // FailBoard makes the board route answer status (0 stops). |
| 196 | func (f *FakeBase) FailBoard(status int) { |
| 197 | f.mu.Lock() |
| 198 | defer f.mu.Unlock() |
| 199 | f.boardStatus = status |
| 200 | } |
| 201 | |
| 202 | // BoardCalls are the tokens the board was asked with, in order. |
| 203 | func (f *FakeBase) BoardCalls() []string { |
| 204 | f.mu.Lock() |
| 205 | defer f.mu.Unlock() |
| 206 | return slices.Clone(f.boardCalls) |
| 207 | } |
| 208 | |
| 209 | // Forget stops accepting token, as Base does once its member disconnects. |
| 210 | func (f *FakeBase) Forget(token string) { |
| 211 | f.mu.Lock() |
| 212 | defer f.mu.Unlock() |
| 213 | delete(f.tokens, token) |
| 214 | } |
| 215 | |
| 216 | // serveBoard is GET /api/v1/abilities. |
| 217 | func (f *FakeBase) serveBoard(w http.ResponseWriter, r *http.Request) { |
| 218 | token, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") |
| 219 | f.mu.Lock() |
| 220 | f.boardCalls = append(f.boardCalls, token) |
| 221 | accepted, legacy, status := f.tokens[token], f.legacy, f.boardStatus |
| 222 | b, ok := f.board[token] |
| 223 | f.mu.Unlock() |
| 224 | if !ok { |
| 225 | b = wire.AbilityBoard{Revision: 1, Ask: "Owner", Abilities: map[string]bool{}} |
| 226 | for _, k := range wire.Abilities { |
| 227 | b.Abilities[k] = true |
| 228 | } |
| 229 | } |
| 230 | w.Header().Set("Content-Type", "application/json") |
| 231 | switch { |
| 232 | case legacy: |
| 233 | http.NotFound(w, r) |
| 234 | case !accepted: |
| 235 | w.WriteHeader(http.StatusUnauthorized) |
| 236 | case status != 0: |
| 237 | w.WriteHeader(status) |
| 238 | default: |
| 239 | _ = json.NewEncoder(w).Encode(b) |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | func (f *FakeBase) serve(w http.ResponseWriter, r *http.Request) { |
| 244 | if r.Method == http.MethodGet && r.URL.Path == "/api/v1/abilities" { |
| 245 | f.serveBoard(w, r) |
| 246 | return |
| 247 | } |
| 248 | name, ok := "", false |
| 249 | switch { |
| 250 | case r.Method == http.MethodGet && r.URL.Path == "/api/v1/operations": |
| 251 | ok = true |
| 252 | case r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/api/v1/operations/"): |
| 253 | name, ok = strings.TrimPrefix(r.URL.Path, "/api/v1/operations/"), true |
| 254 | } |
| 255 | if !ok { |
| 256 | http.NotFound(w, r) |
| 257 | return |
| 258 | } |
| 259 | body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)) |
| 260 | token, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") |
| 261 | f.mu.Lock() |
| 262 | f.calls[name] = append(f.calls[name], fakeCall{token: token, key: r.Header.Get("Idempotency-Key"), input: string(body)}) |
| 263 | accepted, held, code := f.tokens[token], f.hold[name], f.fail[name] |
| 264 | ops := append([]assist.Operation(nil), f.ops...) |
| 265 | output, known := f.output[name] |
| 266 | for _, op := range ops { |
| 267 | if op.Name == name && !known { |
| 268 | output, known = `{"ok":true}`, true |
| 269 | } |
| 270 | } |
| 271 | f.mu.Unlock() |
| 272 | if held != nil { |
| 273 | select { |
| 274 | case <-held: |
| 275 | case <-r.Context().Done(): |
| 276 | return |
| 277 | } |
| 278 | } |
| 279 | w.Header().Set("Content-Type", "application/json") |
| 280 | switch { |
| 281 | case !accepted: |
| 282 | w.WriteHeader(http.StatusUnauthorized) |
| 283 | _, _ = io.WriteString(w, `{"error":{"code":"unauthenticated","message":"Sign in again."}}`) |
| 284 | case code != "": |
| 285 | w.WriteHeader(http.StatusUnprocessableEntity) |
| 286 | _ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"code": code, "message": "The fake was told to fail."}}) |
| 287 | case name == "": |
| 288 | _ = json.NewEncoder(w).Encode(map[string]any{"operations": ops}) |
| 289 | case !known: |
| 290 | w.WriteHeader(http.StatusNotFound) |
| 291 | _, _ = io.WriteString(w, `{"error":{"code":"unknown_operation","message":"No such operation."}}`) |
| 292 | default: |
| 293 | _, _ = io.WriteString(w, output) |
| 294 | } |
| 295 | } |
| 296 | |