| 1 | package assist |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "strings" |
| 8 | "sync" |
| 9 | "testing" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/equipo/oficina/oficinatest" |
| 12 | ) |
| 13 | |
| 14 | // conn is a Connection with one token, or none. |
| 15 | type conn struct { |
| 16 | mu sync.Mutex |
| 17 | origin string |
| 18 | tokens []string // handed out in turn; the last one repeats |
| 19 | rejected int |
| 20 | none bool |
| 21 | } |
| 22 | |
| 23 | func (c *conn) Host(context.Context, string) (string, string, bool, error) { |
| 24 | c.mu.Lock() |
| 25 | defer c.mu.Unlock() |
| 26 | if c.none { |
| 27 | return "", "", false, nil |
| 28 | } |
| 29 | tok := c.tokens[0] |
| 30 | if len(c.tokens) > 1 { |
| 31 | c.tokens = c.tokens[1:] |
| 32 | } |
| 33 | return c.origin, tok, true, nil |
| 34 | } |
| 35 | |
| 36 | func (c *conn) Rejected(string) { |
| 37 | c.mu.Lock() |
| 38 | c.rejected++ |
| 39 | c.mu.Unlock() |
| 40 | } |
| 41 | |
| 42 | func oficinaRig(t *testing.T, teams ...string) (*oficinatest.Connect, *conn, *Registry) { |
| 43 | t.Helper() |
| 44 | fake := oficinatest.Start(t) |
| 45 | c := &conn{origin: fake.URL, tokens: []string{fake.Grant(teams...)}} |
| 46 | return fake, c, NewRegistry(NewOficinaProvider("oficina", c, nil, nil)) |
| 47 | } |
| 48 | |
| 49 | // TestOficinaKeyedWrites: an agent-access write whose input requires a |
| 50 | // 36-character string client_id is keyed at client_id, and the model is |
| 51 | // not shown the field; a write without one, or not idempotent, stays |
| 52 | // unsupported. The same descriptor from any other HTTP provider keeps |
| 53 | // R4: no key is inferred there. |
| 54 | func TestOficinaKeyedWrites(t *testing.T) { |
| 55 | _, _, r := oficinaRig(t, "acme") |
| 56 | ctx := allowAll(context.Background()) |
| 57 | want := map[string]struct { |
| 58 | key string |
| 59 | run bool |
| 60 | code string |
| 61 | }{ |
| 62 | "calendar_free_busy": {"", true, ""}, |
| 63 | "calendar_create_event": {"client_id", true, ""}, |
| 64 | "docs_append": {"", false, "write_not_supported"}, |
| 65 | "docs_delete": {"client_id", false, "not_yet"}, |
| 66 | "calls_invite": {"client_id", false, "not_yet"}, |
| 67 | } |
| 68 | for name, w := range want { |
| 69 | op, err := r.Describe(ctx, "p", name) |
| 70 | if err != nil { |
| 71 | t.Fatal(name, err) |
| 72 | } |
| 73 | run, code := Decide(op) |
| 74 | if op.KeyField != w.key || run != w.run || code != w.code { |
| 75 | t.Errorf("%s: key %q run %v code %q, want %q %v %q", name, op.KeyField, run, code, w.key, w.run, w.code) |
| 76 | } |
| 77 | if op.App == "" || op.Provider != "oficina" { |
| 78 | t.Errorf("%s: app %q provider %q", name, op.App, op.Provider) |
| 79 | } |
| 80 | if op.KeyField != "" && strings.Contains(string(op.Input), "client_id") { |
| 81 | t.Errorf("%s: the model is shown client_id: %s", name, op.Input) |
| 82 | } |
| 83 | } |
| 84 | if op, _ := r.Describe(ctx, "p", "calendar_create_event"); op.App != "Calendar" { |
| 85 | t.Errorf("app from the scope: %q", op.App) |
| 86 | } |
| 87 | |
| 88 | // Any other HTTP provider: the same descriptors, no key inferred. |
| 89 | fake := oficinatest.Start(t) |
| 90 | tok := fake.Grant("acme") |
| 91 | base := NewRegistry(NewHTTPProvider("base", func(context.Context, string) (string, string, bool, error) { return fake.URL, tok, true, nil }, nil)) |
| 92 | op, err := base.Describe(ctx, "p", "calendar_create_event") |
| 93 | if err != nil { |
| 94 | t.Fatal(err) |
| 95 | } |
| 96 | if run, code := Decide(op); op.KeyField != "" || run || code != "write_not_supported" { |
| 97 | t.Errorf("base provider widened: key %q run %v code %q", op.KeyField, run, code) |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | // TestOficinaClientIDKeyed: the inference reads the schema exactly. |
| 102 | func TestOficinaClientIDKeyed(t *testing.T) { |
| 103 | schema := func(prop, required string) json.RawMessage { |
| 104 | return json.RawMessage(`{"type":"object","required":[` + required + `],"properties":{"client_id":` + prop + `}}`) |
| 105 | } |
| 106 | cases := []struct { |
| 107 | name string |
| 108 | op Operation |
| 109 | want bool |
| 110 | }{ |
| 111 | {"length 36", Operation{Idempotent: true, Input: schema(oficinatest.UUIDSchema, `"client_id"`)}, true}, |
| 112 | {"format uuid", Operation{Idempotent: true, Input: schema(`{"type":"string","format":"uuid"}`, `"client_id"`)}, true}, |
| 113 | {"not required", Operation{Idempotent: true, Input: schema(oficinatest.UUIDSchema, ``)}, false}, |
| 114 | {"not idempotent", Operation{Input: schema(oficinatest.UUIDSchema, `"client_id"`)}, false}, |
| 115 | {"read", Operation{ReadOnly: true, Idempotent: true, Input: schema(oficinatest.UUIDSchema, `"client_id"`)}, false}, |
| 116 | {"any string", Operation{Idempotent: true, Input: schema(`{"type":"string"}`, `"client_id"`)}, false}, |
| 117 | {"integer", Operation{Idempotent: true, Input: schema(`{"type":"integer","maxLength":36}`, `"client_id"`)}, false}, |
| 118 | {"no schema", Operation{Idempotent: true}, false}, |
| 119 | } |
| 120 | for _, c := range cases { |
| 121 | if got := clientIDKeyed(c.op); got != c.want { |
| 122 | t.Errorf("%s: %v", c.name, got) |
| 123 | } |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | // TestOficinaInvoke: a write reaches connect with the bearer, the |
| 128 | // person's one team filled in and client_id the UUIDv5 of the ledger |
| 129 | // key, the same on a retry with that key; a read gets no client_id. |
| 130 | func TestOficinaInvoke(t *testing.T) { |
| 131 | fake, c, r := oficinaRig(t, "acme") |
| 132 | ctx := allowAll(context.Background()) |
| 133 | for range 2 { |
| 134 | if _, err := r.Invoke(ctx, "p", "calendar_create_event", json.RawMessage(`{"title":"Lunch","start_local":"2026-11-20T13:00"}`), "turn\x00calendar_create_event\x00h"); err != nil { |
| 135 | t.Fatal(err) |
| 136 | } |
| 137 | } |
| 138 | if _, err := r.Invoke(ctx, "p", "calendar_free_busy", json.RawMessage(`{"start":"a","end":"b"}`), ""); err != nil { |
| 139 | t.Fatal(err) |
| 140 | } |
| 141 | calls := fake.Calls() |
| 142 | if len(calls) != 3 { |
| 143 | t.Fatalf("calls: %+v", calls) |
| 144 | } |
| 145 | key := Key("turn\x00calendar_create_event\x00h") |
| 146 | for _, call := range calls[:2] { |
| 147 | if call.Input["client_id"] != key || call.Input["team"] != "acme" || call.Input["title"] != "Lunch" || call.Bearer != c.tokens[0] { |
| 148 | t.Errorf("write: %+v, want client_id %s", call, key) |
| 149 | } |
| 150 | } |
| 151 | if _, has := calls[2].Input["client_id"]; has || calls[2].Input["team"] != "acme" { |
| 152 | t.Errorf("read: %+v", calls[2]) |
| 153 | } |
| 154 | // The model's own team stands. |
| 155 | if _, err := r.Invoke(ctx, "p", "calendar_free_busy", json.RawMessage(`{"team":"other","start":"a","end":"b"}`), ""); err == nil { |
| 156 | t.Error("a team outside the connection was accepted") |
| 157 | } |
| 158 | if got := fake.Calls(); got[len(got)-1].Input["team"] != "other" { |
| 159 | t.Errorf("model's team replaced: %+v", got[len(got)-1]) |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | // TestOficinaTeamsToChoose: with more than one team the model is shown |
| 164 | // them in describe and must choose; nothing is sent without a team. |
| 165 | func TestOficinaTeamsToChoose(t *testing.T) { |
| 166 | fake, _, r := oficinaRig(t, "acme", "zeta") |
| 167 | ctx := allowAll(context.Background()) |
| 168 | op, err := r.Describe(ctx, "p", "calendar_free_busy") |
| 169 | if err != nil { |
| 170 | t.Fatal(err) |
| 171 | } |
| 172 | raw, _ := json.Marshal(op) |
| 173 | if len(op.Teams) != 2 || !strings.Contains(string(raw), `"teams":["acme","zeta"]`) || !strings.Contains(string(op.Input), `"required":["team"`) { |
| 174 | t.Errorf("describe: %s", raw) |
| 175 | } |
| 176 | _, err = r.Invoke(ctx, "p", "calendar_free_busy", json.RawMessage(`{"start":"a","end":"b"}`), "") |
| 177 | var f Failure |
| 178 | if !errors.As(err, &f) || f.Code != "team_needed" || !strings.Contains(f.Message, "acme") || !strings.Contains(f.Message, "zeta") { |
| 179 | t.Errorf("no team: %v", err) |
| 180 | } |
| 181 | if n := len(fake.Calls()); n != 0 { |
| 182 | t.Errorf("sent without a team: %d calls", n) |
| 183 | } |
| 184 | if _, err = r.Invoke(ctx, "p", "calendar_free_busy", json.RawMessage(`{"team":"zeta","start":"a","end":"b"}`), ""); err != nil { |
| 185 | t.Fatal(err) |
| 186 | } |
| 187 | |
| 188 | // One team: required no more, and no list. |
| 189 | _, _, one := oficinaRig(t, "acme") |
| 190 | op, _ = one.Describe(ctx, "p", "calendar_free_busy") |
| 191 | if len(op.Teams) != 0 || strings.Contains(string(op.Input), `"team"]`) || strings.Contains(string(op.Input), `["team"`) { |
| 192 | t.Errorf("one team: teams %v input %s", op.Teams, op.Input) |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | // TestOficinaRefusesDestructiveAndExternal: neither reaches connect. |
| 197 | func TestOficinaRefusesDestructiveAndExternal(t *testing.T) { |
| 198 | fake, _, r := oficinaRig(t, "acme") |
| 199 | for _, name := range []string{"docs_delete", "calls_invite"} { |
| 200 | _, err := r.Invoke(allowAll(context.Background()), "p", name, json.RawMessage(`{"id":"1","email":"a@b.c"}`), "k") |
| 201 | var f Failure |
| 202 | if !errors.As(err, &f) || f.Code != "not_yet" { |
| 203 | t.Errorf("%s: %v", name, err) |
| 204 | } |
| 205 | } |
| 206 | if n := len(fake.Calls()); n != 0 { |
| 207 | t.Errorf("refused operations reached connect: %d", n) |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | // TestOficinaRejectedTokenRetried: connect refusing the access token |
| 212 | // tells the connection, and the call is made once more with the next. |
| 213 | func TestOficinaRejectedTokenRetried(t *testing.T) { |
| 214 | fake := oficinatest.Start(t) |
| 215 | c := &conn{origin: fake.URL, tokens: []string{"stale-" + strings.Repeat("x", 20), fake.Grant("acme")}} |
| 216 | r := NewRegistry(NewOficinaProvider("oficina", c, nil, nil)) |
| 217 | if _, err := r.Describe(context.Background(), "p", "calendar_free_busy"); err != nil { |
| 218 | t.Fatal(err) |
| 219 | } |
| 220 | if c.rejected != 1 { |
| 221 | t.Errorf("rejected %d times", c.rejected) |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | // TestOficinaHintWhenNotConnected: look for something an Oficina app |
| 226 | // does, by a person not connected, carries the provider's hint and calls |
| 227 | // the hook once per look; a look for something else does neither. |
| 228 | func TestOficinaHintWhenNotConnected(t *testing.T) { |
| 229 | c := &conn{none: true} |
| 230 | r := NewRegistry(&fake{name: "base", ops: map[string][]Operation{"p": {{Name: "base_weather", App: "Weather", ReadOnly: true}}}}, NewOficinaProvider("oficina", c, nil, nil)) |
| 231 | var hooked []string |
| 232 | raised := true |
| 233 | r.OnUnconnected(func(_ context.Context, person, provider string) bool { |
| 234 | hooked = append(hooked, person+"/"+provider) |
| 235 | return raised |
| 236 | }) |
| 237 | ctx := allowAll(context.Background()) |
| 238 | for _, q := range []string{"", "calendar", "Docs", "meeting"} { |
| 239 | hooked = nil |
| 240 | out, err := r.Look(ctx, "p", q) |
| 241 | if err != nil { |
| 242 | t.Fatal(err) |
| 243 | } |
| 244 | if !strings.Contains(out, "(oficina)") || !strings.Contains(out, "not connected") || !strings.Contains(out, "once they connect their Oficina apps") { |
| 245 | t.Errorf("%q: no hint:\n%s", q, out) |
| 246 | } |
| 247 | // The model is led to say what connecting lets it do, in its own |
| 248 | // words, and is told of no card, connections or machinery it |
| 249 | // would repeat to the person. |
| 250 | for _, word := range []string{"card", "connection", "equipo", "oficina-connect", "oficina connect", "button", "link"} { |
| 251 | if strings.Contains(strings.ToLower(out), word) { |
| 252 | t.Errorf("%q: the note mentions %q:\n%s", q, word, out) |
| 253 | } |
| 254 | } |
| 255 | if len(hooked) != 1 || hooked[0] != "p/oficina" { |
| 256 | t.Errorf("%q: hook %v", q, hooked) |
| 257 | } |
| 258 | } |
| 259 | // No card raised: the model is not told there is one. |
| 260 | raised = false |
| 261 | if out, _ := r.Look(ctx, "p", "calendar"); strings.Contains(out, "card") || !strings.Contains(out, "needs connecting") { |
| 262 | t.Errorf("no card:\n%s", out) |
| 263 | } |
| 264 | hooked = nil |
| 265 | out, _ := r.Look(ctx, "p", "weather") |
| 266 | if strings.Contains(out, "oficina") || len(hooked) != 0 { |
| 267 | t.Errorf("weather: hint or hook:\n%s %v", out, hooked) |
| 268 | } |
| 269 | |
| 270 | // Connected: no hint, no hook. |
| 271 | _, _, connected := oficinaRig(t, "acme") |
| 272 | connected.OnUnconnected(func(context.Context, string, string) bool { hooked = append(hooked, "x"); return true }) |
| 273 | out, _ = connected.Look(ctx, "p", "calendar") |
| 274 | if strings.Contains(out, "not connected") || !strings.Contains(out, "calendar_free_busy") || len(hooked) != 0 { |
| 275 | t.Errorf("connected look:\n%s %v", out, hooked) |
| 276 | } |
| 277 | } |
| 278 | |