package thintest import ( "crypto/rand" "encoding/json" "io" "net" "net/http" "slices" "strings" "sync" "testing" "amadan.net/oficina/equipo/internal/equipo/assist" "amadan.net/oficina/equipo/internal/wire" ) // FakeBase is Base's operations endpoint as the Assistant's base provider // calls it (agent-access's contract): GET /api/v1/operations and POST // /api/v1/operations/{name}, each with a bearer token Base minted for one // member. It serves base_apps, base_people and base_settings, all reads, // and whatever Add gives it. The name "" is the listing itself. type FakeBase struct { Origin string // Token is one accepted bearer; Mint makes more. Token string // It also answers GET /api/v1/abilities (spec // 2026-11-26-assistant-abilities ยง5.3) with each member's board: // every ability on unless SetBoard says otherwise. Legacy makes it a // Base older than the board, which answers that route 404. mu sync.Mutex ops []assist.Operation tokens map[string]bool calls map[string][]fakeCall fail map[string]string hold map[string]chan struct{} output map[string]string // board is each token's board (boardFor), boardStatus what the board // route answers instead when set, legacy a Base without the route, // boardCalls the tokens it was asked with. board map[string]wire.AbilityBoard boardStatus int legacy bool boardCalls []string } type fakeCall struct{ token, key, input string } // StartFakeBase serves a fake Base on 127.0.0.1 until the test ends. func StartFakeBase(t testing.TB) *FakeBase { t.Helper() 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{}} f.tokens[f.Token] = true object := json.RawMessage(`{"type":"object","properties":{},"additionalProperties":false}`) f.ops = []assist.Operation{ {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}, {Name: "base_people", Description: "List the people on the person's team.", Scope: "base.read", ReadOnly: true, Idempotent: true, App: "Base", Input: object}, {Name: "base_settings", Description: "Read the person's Base settings.", Scope: "base.read", ReadOnly: true, Idempotent: true, App: "Base", Input: object}, } f.output["base_apps"] = `{"installed":[{"id":"shop","name":"Shop","address":"https://shop.example.com"}],"store":[],"oficina":[]}` f.output["base_people"] = `{"people":[{"name":"Owner"}]}` f.output["base_settings"] = `{"settings":{"language":"en"}}` l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } f.Origin = "http://" + l.Addr().String() srv := &http.Server{Handler: http.HandlerFunc(f.serve)} go srv.Serve(l) t.Cleanup(func() { f.mu.Lock() for name, c := range f.hold { close(c) delete(f.hold, name) } f.mu.Unlock() _ = srv.Close() }) return f } // Mint accepts and returns another bearer token, as Base mints one per // member. func (f *FakeBase) Mint() string { f.mu.Lock() defer f.mu.Unlock() token := "base-" + rand.Text() f.tokens[token] = true return token } // Add serves more operations: a write, one that deletes, one that reaches // outside, or one whose answer is large (Answer). func (f *FakeBase) Add(ops ...assist.Operation) { f.mu.Lock() defer f.mu.Unlock() f.ops = append(f.ops, ops...) } // Answer sets what an operation returns. func (f *FakeBase) Answer(name, output string) { f.mu.Lock() defer f.mu.Unlock() f.output[name] = output } // Calls is how many requests reached name ("" is the listing), with an // accepted token or not. func (f *FakeBase) Calls(name string) int { f.mu.Lock() defer f.mu.Unlock() return len(f.calls[name]) } // Keys are the Idempotency-Key headers name received, in order. func (f *FakeBase) Keys(name string) []string { return f.field(name, func(c fakeCall) string { return c.key }) } // Tokens are the bearer tokens name received, in order. func (f *FakeBase) Tokens(name string) []string { return f.field(name, func(c fakeCall) string { return c.token }) } // Inputs are the request bodies name received, in order. func (f *FakeBase) Inputs(name string) []string { return f.field(name, func(c fakeCall) string { return c.input }) } func (f *FakeBase) field(name string, get func(fakeCall) string) []string { f.mu.Lock() defer f.mu.Unlock() out := []string{} for _, c := range f.calls[name] { out = append(out, get(c)) } return out } // Fail makes name answer 422 with the error code from now on ("" clears). func (f *FakeBase) Fail(name, code string) { f.mu.Lock() defer f.mu.Unlock() f.fail[name] = code } // Hold keeps every request for name waiting, after it is counted, until // release (or the caller gives up). func (f *FakeBase) Hold(name string) (release func()) { f.mu.Lock() defer f.mu.Unlock() c := make(chan struct{}) f.hold[name] = c var once sync.Once return func() { once.Do(func() { f.mu.Lock() if f.hold[name] == c { delete(f.hold, name) } f.mu.Unlock() close(c) }) } } // Accept accepts token as a bearer, as if Base had minted it. func (f *FakeBase) Accept(token string) { f.mu.Lock() defer f.mu.Unlock() f.tokens[token] = true } // SetBoard is the board the member with token gets: off lists the // abilities turned off, at revision, with ask as who can change them. func (f *FakeBase) SetBoard(token string, revision int64, ask string, off ...string) { f.mu.Lock() defer f.mu.Unlock() b := wire.AbilityBoard{Revision: revision, Ask: ask, Abilities: map[string]bool{}} for _, k := range wire.Abilities { b.Abilities[k] = !slices.Contains(off, k) } f.board[token] = b } // SetLegacy makes the fake a Base older than the board (on), whose board // route answers 404, or a current one again (off). func (f *FakeBase) SetLegacy(on bool) { f.mu.Lock() defer f.mu.Unlock() f.legacy = on } // FailBoard makes the board route answer status (0 stops). func (f *FakeBase) FailBoard(status int) { f.mu.Lock() defer f.mu.Unlock() f.boardStatus = status } // BoardCalls are the tokens the board was asked with, in order. func (f *FakeBase) BoardCalls() []string { f.mu.Lock() defer f.mu.Unlock() return slices.Clone(f.boardCalls) } // Forget stops accepting token, as Base does once its member disconnects. func (f *FakeBase) Forget(token string) { f.mu.Lock() defer f.mu.Unlock() delete(f.tokens, token) } // serveBoard is GET /api/v1/abilities. func (f *FakeBase) serveBoard(w http.ResponseWriter, r *http.Request) { token, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") f.mu.Lock() f.boardCalls = append(f.boardCalls, token) accepted, legacy, status := f.tokens[token], f.legacy, f.boardStatus b, ok := f.board[token] f.mu.Unlock() if !ok { b = wire.AbilityBoard{Revision: 1, Ask: "Owner", Abilities: map[string]bool{}} for _, k := range wire.Abilities { b.Abilities[k] = true } } w.Header().Set("Content-Type", "application/json") switch { case legacy: http.NotFound(w, r) case !accepted: w.WriteHeader(http.StatusUnauthorized) case status != 0: w.WriteHeader(status) default: _ = json.NewEncoder(w).Encode(b) } } func (f *FakeBase) serve(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet && r.URL.Path == "/api/v1/abilities" { f.serveBoard(w, r) return } name, ok := "", false switch { case r.Method == http.MethodGet && r.URL.Path == "/api/v1/operations": ok = true case r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/api/v1/operations/"): name, ok = strings.TrimPrefix(r.URL.Path, "/api/v1/operations/"), true } if !ok { http.NotFound(w, r) return } body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)) token, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") f.mu.Lock() f.calls[name] = append(f.calls[name], fakeCall{token: token, key: r.Header.Get("Idempotency-Key"), input: string(body)}) accepted, held, code := f.tokens[token], f.hold[name], f.fail[name] ops := append([]assist.Operation(nil), f.ops...) output, known := f.output[name] for _, op := range ops { if op.Name == name && !known { output, known = `{"ok":true}`, true } } f.mu.Unlock() if held != nil { select { case <-held: case <-r.Context().Done(): return } } w.Header().Set("Content-Type", "application/json") switch { case !accepted: w.WriteHeader(http.StatusUnauthorized) _, _ = io.WriteString(w, `{"error":{"code":"unauthenticated","message":"Sign in again."}}`) case code != "": w.WriteHeader(http.StatusUnprocessableEntity) _ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"code": code, "message": "The fake was told to fail."}}) case name == "": _ = json.NewEncoder(w).Encode(map[string]any{"operations": ops}) case !known: w.WriteHeader(http.StatusNotFound) _, _ = io.WriteString(w, `{"error":{"code":"unknown_operation","message":"No such operation."}}`) default: _, _ = io.WriteString(w, output) } }