package thintest import ( "encoding/json" "errors" "io" "net/http" "net/url" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/oficina/oficinatest" "amadan.net/oficina/equipo/internal/wire" ) // oficinaRig is an Assistant rig whose instance has oficina-connect // configured: a fake connect that approves every consent itself. type oficinaRig struct { *opsRig fake *oficinatest.Connect } func newOficinaRig(t *testing.T) *oficinaRig { fake := oficinatest.Start(t) base := StartFakeBase(t) r := newRigWith(t, func(i *Instance) { i.AssistantHosts = []string{base.Origin} i.OficinaConnect, i.OficinaClientID = fake.URL, fake.ClientID fake.Redirect = i.URL + "/oficina/connect/callback" }) runner := r.dialAt(wire.ProtocolAssistant) o := &oficinaRig{opsRig: &opsRig{toolRig: &toolRig{rig: r, runner: runner}, base: base, a: r.client.Assistant(), protocol: wire.ProtocolAssistant}, fake: fake} o.connect(base.Token) return o } // viaBase connects as Base does it: the card's link is Base's route, // which asks the person API for connect's address with the person's // bearer and sends the browser there; connect's consent comes back to // the instance's callback, with no Equipo session, which hands the state // and code on to Base's return address, saving nothing; Base finishes // with the person's bearer. It returns the finish's status. func (o *oficinaRig) viaBase() string { o.t.Helper() state, code := o.handBack(o.base.Origin + "/ask?open=1") if n := o.rows("SELECT count(*) FROM oficina_connections"); n != 0 { o.t.Fatalf("the callback saved %d connections", n) } status, err := o.a.OficinaFinish(o.ctx, state, code) if err != nil { o.t.Fatalf("finish: %v", err) } return status } // handBack starts a consent for returnTo and follows it through // connect and the callback: the state and code the callback hands back. func (o *oficinaRig) handBack(returnTo string) (state, code string) { o.t.Helper() back := o.callback(returnTo) u, err := url.Parse(back) if err != nil || !strings.HasPrefix(back, strings.SplitN(returnTo, "?", 2)[0]+"?") || u.Query().Get("oficina_state") == "" || u.Query().Get("oficina_code") == "" { o.t.Fatalf("handed back: %q", back) } if ex, _ := o.fake.Counts(); ex != 0 { o.t.Fatalf("the callback exchanged the code") } return u.Query().Get("oficina_state"), u.Query().Get("oficina_code") } // callback starts a consent for returnTo and follows it to where the // callback sends the browser, with no session. func (o *oficinaRig) callback(returnTo string) string { o.t.Helper() authorize, err := o.a.OficinaConnect(o.ctx, returnTo) if err != nil || !strings.HasPrefix(authorize, o.fake.URL+"/oauth/authorize?") { o.t.Fatalf("start: %q %v", authorize, err) } status, callback, _ := o.browse(http.MethodGet, authorize) if status != http.StatusSeeOther || !strings.HasPrefix(callback, o.inst.URL+"/oficina/connect/callback?") { o.t.Fatalf("consent: %d %q", status, callback) } status, back, _ := o.anonymous(callback) if status != http.StatusSeeOther { o.t.Fatalf("callback: %d %q", status, back) } return back } // anonymous is a GET with no session at all. func (o *oficinaRig) anonymous(raw string) (int, string, string) { o.t.Helper() client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} res, err := client.Get(raw) if err != nil { o.t.Fatal(err) } defer res.Body.Close() body, _ := io.ReadAll(res.Body) return res.StatusCode, res.Header.Get("Location"), string(body) } // browse is one browser request with the owner's session, redirects not // followed: the status, Location and body. func (o *oficinaRig) browse(method, raw string) (int, string, string) { o.t.Helper() req, _ := http.NewRequest(method, raw, nil) if strings.HasPrefix(raw, o.inst.URL) { req.AddCookie(o.inst.Cookie()) if method == http.MethodPost { req.Header.Set("Origin", o.inst.URL) } } client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} res, err := client.Do(req) if err != nil { o.t.Fatal(err) } defer res.Body.Close() body, _ := io.ReadAll(res.Body) return res.StatusCode, res.Header.Get("Location"), string(body) } // consent follows the connect card's link through connect's consent // and back, as the person's browser does; it returns the last page. func (o *oficinaRig) consent(start string) string { o.t.Helper() status, authorize, _ := o.browse(http.MethodGet, start) if status != http.StatusSeeOther || !strings.HasPrefix(authorize, o.fake.URL+"/oauth/authorize?") { o.t.Fatalf("start: %d %q", status, authorize) } status, callback, _ := o.browse(http.MethodGet, authorize) if status != http.StatusSeeOther || !strings.HasPrefix(callback, o.inst.URL+"/oficina/connect/callback?") { o.t.Fatalf("consent: %d %q", status, callback) } status, done, _ := o.anonymous(callback) if status != http.StatusSeeOther || !strings.HasPrefix(done, "/oficina/connect/done?") || !strings.Contains(done, "oficina_state=") { o.t.Fatalf("callback: %d %q", status, done) } // Without the session that started it, nothing is finished. if _, to, _ := o.anonymous(o.inst.URL + done); strings.HasPrefix(to, "/oficina") { o.t.Fatalf("done without a session: %q", to) } if ex, _ := o.fake.Counts(); ex != 0 { o.t.Fatal("finished without the session") } status, _, page := o.browse(http.MethodGet, o.inst.URL+done) if status != http.StatusOK { o.t.Fatalf("done: %d %s", status, page) } return page } // connectCards are the person's connect cards in the Assistant lane. func (o *oficinaRig) connectCards() []wire.AssistantCard { o.t.Helper() snap, err := o.a.Snapshot(o.ctx) if err != nil { o.t.Fatal(err) } return slices.DeleteFunc(snap.Cards, func(c wire.AssistantCard) bool { return c.Kind != wire.CardConnect }) } // TestContractAssistantOficinaConnectCard: a look for something the // Oficina apps do, by a person who has not connected them, tells the // model so and raises one connect card, whose link starts connecting; a // look for anything else does neither. Connecting (PKCE, checked by the // fake) settles the card and the apps' operations are listed. func TestContractAssistantOficinaConnectCard(t *testing.T) { o := newOficinaRig(t) o.begin("Put lunch with Ana in my calendar on Friday.") for _, id := range []string{"l1", "l2"} { res := o.tool(id, wire.ToolLook, map[string]any{"query": "calendar"}) if res.IsError || !strings.Contains(res.Text, "not connected") || !strings.Contains(res.Text, "(oficina)") { t.Fatalf("look %s: %+v", id, res) } } if res := o.tool("l3", wire.ToolLook, map[string]any{"query": "weather"}); strings.Contains(res.Text, "oficina") { t.Errorf("weather: %+v", res) } cards := o.connectCards() if len(cards) != 1 { t.Fatalf("connect cards: %+v", cards) } c := cards[0] if c.State != wire.CardOpen || c.Question != "Connect your Oficina apps" || len(c.Links) != 1 || c.Links[0].URL != o.base.Origin+"/ask/oficina/connect" || c.Links[0].Rel != "oficina_connect" || c.Links[0].Label != "Connect" || c.Options == nil { t.Fatalf("card: %+v", c) } raw, _ := json.Marshal(c) var decoded any _ = json.Unmarshal(raw, &decoded) noMachinery(t, "k_none", []string{"/tasks/", "Equipo", "equipo"})("the connect card", decoded, false) if status := o.viaBase(); status != "connected" { t.Errorf("finish: %q", status) } if ex, _ := o.fake.Counts(); ex != 1 { t.Errorf("exchanges %d", ex) } cards = o.connectCards() if len(cards) != 1 || cards[0].State != wire.CardResolved || cards[0].Revision != c.Revision+1 { t.Errorf("after connecting: %+v", cards) } res := o.tool("l4", wire.ToolLook, map[string]any{"query": "calendar"}) if strings.Contains(res.Text, "not connected") || !strings.Contains(res.Text, "Calendar (oficina)") || !strings.Contains(res.Text, "calendar_create_event") { t.Errorf("connected look: %+v", res) } if n := len(o.connectCards()); n != 1 { t.Errorf("%d connect cards after connecting", n) } if ex, _ := o.fake.Counts(); ex != 1 { t.Errorf("exchanges %d", ex) } } // TestContractAssistantOficinaCallbackState (consent fixation): the // callback needs no session and saves nothing; it hands the state and // code back to Base. Only the person who started the consent finishes // it, once, with their bearer: another person's bearer is refused (403) // and uses the state up. A forged or finished state goes nowhere; // connect's consent refused, or from another issuer, goes back to Base // saying so. The return address must be on an allowed Base origin. func TestContractAssistantOficinaCallbackState(t *testing.T) { o := newOficinaRig(t) ana := o.other("ana@example.com") ana.connect(o.base.Mint()) state, code := o.handBack(o.base.Origin + "/ask") if n := o.rows("SELECT count(*) FROM oficina_connections"); n != 0 { t.Fatalf("the callback saved %d connections", n) } var s *ErrStatus if _, err := ana.a.OficinaFinish(o.ctx, state, code); !errors.As(err, &s) || s.Status != http.StatusForbidden || strings.Contains(string(s.Body), Owner) { t.Fatalf("another person's finish: %v", err) } if status, err := o.a.OficinaFinish(o.ctx, state, code); err != nil || status != "expired" { t.Errorf("after another person tried: %q %v", status, err) } if ex, _ := o.fake.Counts(); ex != 0 || o.rows("SELECT count(*) FROM oficina_connections") != 0 { t.Fatalf("exchanged %d", ex) } state, code = o.handBack(o.base.Origin + "/ask") if status, err := o.a.OficinaFinish(o.ctx, state, code); err != nil || status != "connected" { t.Fatalf("finish: %q %v", status, err) } if status, err := o.a.OficinaFinish(o.ctx, state, code); err != nil || status != "expired" { t.Errorf("replayed finish: %q %v", status, err) } if status, _, _ := o.anonymous(o.inst.URL + "/oficina/connect/callback?state=" + url.QueryEscape(state) + "&code=" + url.QueryEscape(code) + "&iss=" + url.QueryEscape(o.fake.URL)); status != http.StatusBadRequest { t.Errorf("a finished state's callback: %d", status) } if status, back, page := o.anonymous(o.inst.URL + "/oficina/connect/callback?state=" + strings.Repeat("A", 43) + "&code=x&iss=" + url.QueryEscape(o.fake.URL)); status != http.StatusBadRequest || back != "" || strings.Contains(page, "rst-shell") { t.Errorf("forged: %d %q", status, back) } if ex, _ := o.fake.Counts(); ex != 1 { t.Errorf("exchanges %d", ex) } // Another issuer: not handed on, and Base hears it expired. authorize, _ := o.a.OficinaConnect(o.ctx, o.base.Origin+"/ask") _, callback, _ := o.browse(http.MethodGet, authorize) u, _ := url.Parse(callback) q := u.Query() q.Set("iss", "https://elsewhere.example.com") u.RawQuery = q.Encode() if _, back, _ := o.anonymous(u.String()); back != o.base.Origin+"/ask?oficina=expired" { t.Errorf("another issuer: %q", back) } o.fake.Deny = true if back := o.callback(o.base.Origin + "/ask"); back != o.base.Origin+"/ask?oficina=denied" { t.Errorf("denied: %q", back) } for _, bad := range []string{"https://evil.example.com/ask", strings.Replace(o.base.Origin, "127.0.0.1", "localhost", 1) + "/ask", "/ask", o.base.Origin + "/ask#x", "", "javascript:alert(1)"} { if _, err := o.a.OficinaConnect(o.ctx, bad); !errors.As(err, &s) || s.Status != 422 { t.Errorf("return to %q: %v", bad, err) } } // A cookie is not the bearer these routes take. for _, path := range []string{"/api/v1/assistant/oficina/connect", "/api/v1/assistant/oficina/connect/finish"} { req, _ := http.NewRequest(http.MethodPost, o.inst.URL+path, strings.NewReader(`{"return_to":"`+o.base.Origin+`/ask"}`)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Origin", o.inst.URL) req.AddCookie(o.inst.Cookie()) if res, err := http.DefaultClient.Do(req); err != nil || res.StatusCode/100 == 2 { t.Errorf("%s: cookie accepted: %v", path, err) } } } // TestContractAssistantOficinaFromEquipo: a person who uses Equipo // directly connects through its own start, behind their session, and // lands on Equipo's page; with no Base host the card links there. func TestContractAssistantOficinaFromEquipo(t *testing.T) { fake := oficinatest.Start(t) r := newRigWith(t, func(i *Instance) { i.OficinaConnect, i.OficinaClientID = fake.URL, fake.ClientID fake.Redirect = i.URL + "/oficina/connect/callback" }) o := &oficinaRig{opsRig: &opsRig{toolRig: &toolRig{rig: r, runner: r.dialAt(wire.ProtocolAssistant)}, a: r.client.Assistant(), protocol: wire.ProtocolAssistant}, fake: fake} o.begin("Put lunch in my calendar.") o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}) link := o.connectCards()[0].Links[0] if link.URL != o.inst.URL+"/oficina/connect/start" || link.Rel != "oficina_connect" { t.Fatalf("link: %+v", link) } if page := o.consent(link.URL); !strings.Contains(page, "Your Oficina apps are connected.") { t.Errorf("page: %s", page) } if _, to, _ := o.anonymous(o.inst.URL + "/oficina/connect/start"); strings.HasPrefix(to, fake.URL) { t.Error("start without a session") } } // TestContractAssistantOficinaUse: through use, a read and a write // reach connect with a current bearer (refreshed, rotated, as each // expires) and the person's one team; the write's client_id is a UUIDv5 // of its ledger key, the same when a failed call is made again, and a // repeat is replayed. Destructive, external and unkeyed writes never // reach connect. Nothing stored or audited carries a token. func TestContractAssistantOficinaUse(t *testing.T) { o := newOficinaRig(t) o.fake.AccessTTL = time.Second o.begin("Book lunch.") o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}) o.viaBase() d := o.tool("d1", wire.ToolDescribe, map[string]any{"operation": "calendar_create_event"}) if d.IsError || strings.Contains(d.Text, "client_id") || strings.Contains(d.Text, `"teams"`) { t.Fatalf("describe: %+v", d) } if res := o.use("r1", "calendar_free_busy", map[string]any{"start": "2026-11-20T00:00:00Z", "end": "2026-11-21T00:00:00Z"}); res.IsError || res.Code != "used" { t.Fatalf("read: %+v", res) } o.fake.FailNext = true lunch := map[string]any{"title": "Lunch with Ana", "start_local": "2026-11-20T13:00"} if res := o.use("w1", "calendar_create_event", lunch); !res.IsError || res.Code != "unavailable" { t.Fatalf("failed write: %+v", res) } if res := o.use("w2", "calendar_create_event", lunch); res.IsError || res.Code != "used" || res.Replayed { t.Fatalf("write: %+v", res) } if res := o.use("w3", "calendar_create_event", lunch); res.IsError || !res.Replayed { t.Fatalf("repeat: %+v", res) } for op, code := range map[string]string{"docs_delete": "not_yet", "calls_invite": "not_yet", "docs_append": "write_not_supported"} { if res := o.use("x-"+op, op, map[string]any{"id": "d1", "email": "guest@example.com", "text": "hi"}); !res.IsError || res.Code != code { t.Errorf("%s: %+v", op, res) } } calls := o.fake.Calls() if len(calls) != 3 || calls[0].Name != "calendar_free_busy" || calls[1].Name != "calendar_create_event" || calls[2].Name != "calendar_create_event" { t.Fatalf("calls: %+v", calls) } key, _ := calls[1].Input["client_id"].(string) if !uuidV5.MatchString(key) || calls[2].Input["client_id"] != key { t.Errorf("client_id %q then %v", key, calls[2].Input["client_id"]) } for _, c := range calls { if c.Input["team"] != "acme" || c.Bearer == "" { t.Errorf("call %s: %+v", c.Name, c) } } if _, refreshes := o.fake.Counts(); refreshes == 0 { t.Error("expired access tokens were not refreshed") } // The refresh token is stored sealed; neither it nor any access // token is in the audit or the logs. var sealed string if err := o.inst.DB.Writer().QueryRow("SELECT refresh FROM oficina_connections WHERE person = ?", Owner).Scan(&sealed); err != nil { t.Fatal(err) } if o.fake.Live(sealed) { t.Error("the refresh token is stored as it is") } logs := o.inst.Logs() for _, c := range calls { if n := o.rows("SELECT count(*) FROM audit_events WHERE record_id LIKE ?", "%"+c.Bearer+"%"); n != 0 || strings.Contains(logs, c.Bearer) { t.Error("an access token in the audit or the logs") } } if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'oficina.connect' AND actor = ? AND record_id = ''", Owner); n != 1 { t.Errorf("connect audits %d", n) } } // TestContractAssistantOficinaDisconnect: the person's disconnect // revokes the connection at connect and forgets it; the next look for // the apps raises a connect card again. func TestContractAssistantOficinaDisconnect(t *testing.T) { o := newOficinaRig(t) o.begin("What is on Friday?") o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}) o.viaBase() if res := o.use("r1", "calendar_free_busy", map[string]any{"start": "a", "end": "b"}); res.IsError { t.Fatalf("read: %+v", res) } var sealed string if err := o.inst.DB.Writer().QueryRow("SELECT refresh FROM oficina_connections WHERE person = ?", Owner).Scan(&sealed); err != nil { t.Fatal(err) } status, _, page := o.browse(http.MethodPost, o.inst.URL+"/oficina/connect/disconnect") if status != http.StatusOK || !strings.Contains(page, "Your Oficina apps are disconnected.") { t.Fatalf("disconnect: %d %s", status, page) } if revoked := o.fake.Revoked(); len(revoked) != 1 || o.fake.Live(revoked[0]) { t.Errorf("revoked %v", revoked) } if n := o.rows("SELECT count(*) FROM oficina_connections"); n != 0 { t.Errorf("%d connections kept", n) } if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'oficina.disconnect' AND actor = ?", Owner); n != 1 { t.Errorf("disconnect audits %d", n) } if res := o.tool("l2", wire.ToolLook, map[string]any{"query": "calendar"}); !strings.Contains(res.Text, "not connected") { t.Errorf("look after disconnecting: %+v", res) } if res := o.use("r2", "calendar_free_busy", map[string]any{"start": "a", "end": "b"}); !res.IsError { t.Errorf("use after disconnecting: %+v", res) } cards := o.connectCards() if len(cards) != 2 || cards[0].State == cards[1].State { t.Errorf("cards after disconnecting: %+v", cards) } } // TestContractAssistantOficinaOffByDefault: without // EQUIPO_OFICINA_CONNECT_ORIGIN nothing changes: no hint, no card, no // routes. func TestContractAssistantOficinaOffByDefault(t *testing.T) { o := newOpsRig(t) o.begin("Put lunch in my calendar.") if res := o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}); strings.Contains(res.Text, "oficina") { t.Errorf("look: %+v", res) } snap, err := o.a.Snapshot(o.ctx) if err != nil { t.Fatal(err) } var s *ErrStatus if _, err := o.a.OficinaConnect(o.ctx, o.base.Origin+"/ask"); !errors.As(err, &s) || s.Status/100 == 2 { t.Errorf("connect API: %v", err) } if slices.ContainsFunc(snap.Cards, func(c wire.AssistantCard) bool { return c.Kind == wire.CardConnect }) { t.Errorf("a connect card: %+v", snap.Cards) } for _, path := range []string{"/oficina/connect/start", "/oficina/connect/callback"} { req, _ := http.NewRequest(http.MethodGet, o.inst.URL+path, nil) req.AddCookie(o.inst.Cookie()) res, err := (&http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}).Do(req) if err != nil { t.Fatal(err) } res.Body.Close() if res.StatusCode != http.StatusNotFound { t.Errorf("%s: %d", path, res.StatusCode) } } } // TestContractAssistantOficinaSettleChecksRoster: a person removed from // the roster has their connect card settled by nothing, in the same // transaction that would settle it. func TestContractAssistantOficinaSettleChecksRoster(t *testing.T) { o := newOficinaRig(t) ana := o.other("ana@example.com") ana.connect(o.base.Mint()) ana.begin("Put lunch in my calendar.") ana.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}) state := func() string { var s string if err := o.inst.DB.Writer().QueryRow("SELECT state FROM chat_cards WHERE person = ? AND kind = ?", "ana@example.com", wire.CardConnect).Scan(&s); err != nil { t.Fatal(err) } return s } if state() != wire.CardOpen { t.Fatal("no open card") } m, err := o.inst.Store.Member(o.ctx, "ana@example.com") if err != nil { t.Fatal(err) } if err := o.inst.Store.SetMember(o.ctx, equipo.Actor{Address: Owner}, "ana@example.com", equipo.RoleOwner, false, m.Revision); err != nil { t.Fatal(err) } if err := o.inst.Store.Chat().SettleConnect(o.ctx, "ana@example.com", "oficina"); err == nil { t.Error("settled for a removed member") } if s := state(); s != wire.CardOpen { t.Errorf("card %s", s) } if n := o.rows("SELECT count(*) FROM chat_turns WHERE person = ? AND kind = ?", "ana@example.com", wire.TurnTeamUpdate); n != 0 { t.Errorf("%d turns queued for a removed member", n) } }