oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package plan3test
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "net/http"
9 "net/http/httptest"
10 "os"
11 "path/filepath"
12 "reflect"
13 "regexp"
14 "slices"
15 "strings"
16 "testing"
17 "time"
18
19 "amadan.net/oficina/equipo/internal/equipo"
20 "amadan.net/oficina/equipo/internal/equipo/chat"
21 "amadan.net/oficina/equipo/internal/equipo/personapi"
22 "amadan.net/oficina/equipo/internal/wire/wireschema"
23 "github.com/go-chi/chi/v5"
24)
25
26// deviceShared says how each path the engine shares with the earlier
27// person API picks its answer (chat.HTTP.Mount, thinOr): by the
28// Authorization header, by the id's prefix, or not at all (replaced).
29var deviceShared = map[string]string{
30 "GET /tasks": "device", "GET /needs-you": "device", "GET /runners": "device", "GET /connections": "device", "GET /specialists": "device",
31 "GET /cards/{id}": "c_", "GET /tasks/{id}": "tk", "POST /tasks/{id}/cancel": "tk", "GET /questions/{id}": "q_",
32 "GET /connections/{id}": "cn_", "DELETE /connections/{id}": "cn_",
33 "GET /projects": "replaced", "POST /projects": "replaced",
34}
35
36// deviceFixtures are the native apps' captured device answers
37// (internal/thintest TestNativeFixtures): the operation and status each
38// came from.
39var deviceFixtures = map[string]string{
40 "snapshot": "GET /snapshot 200", "tasks": "GET /tasks 200", "needs-you": "GET /needs-you 200",
41 "projects": "GET /projects 200", "task": "GET /tasks/{id} 200", "messages": "GET /messages 200",
42 "sent": "POST /messages 201", "answered": "POST /cards/{id}/answer 200",
43 "card-conflict": "POST /cards/{id}/answer 409", "thread-entry": "POST /tasks/{id}/thread 200",
44 "events": "GET /events 200",
45}
46
47// deviceEngineRoutes are the routes chat.HTTP.Mount adds, the Assistant's
48// Oficina connect included.
49func deviceEngineRoutes(t *testing.T, f *fixture) map[string]bool {
50 t.Helper()
51 h := &chat.HTTP{Store: f.Store.Chat(),
52 OficinaConnect: func(context.Context, string, string) (string, error) { return "", nil },
53 OficinaFinish: func(context.Context, string, string, string) (string, error) { return "", nil }}
54 r := chi.NewRouter()
55 h.Mount(r)
56 out := map[string]bool{}
57 must(t, chi.Walk(r, func(method, path string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {
58 out[method+" "+path] = true
59 return nil
60 }))
61 return out
62}
63
64// TestPersonAPIDeviceContract holds docs/api/equipo-v1.openapi.json to
65// what a device bearer is answered with: every engine route documented
66// with the wire types its handler writes, every schema generated from
67// internal/wire, every captured device answer valid against its
68// operation's schema with nothing unknown, and every error code the
69// engine writes in Error.
70func TestPersonAPIDeviceContract(t *testing.T) {
71 raw, err := os.ReadFile("../../docs/api/equipo-v1.openapi.json")
72 must(t, err)
73 var doc map[string]any
74 must(t, json.Unmarshal(raw, &doc))
75 schemas := doc["components"].(map[string]any)["schemas"].(map[string]any)
76 generated := wireschema.Generate()
77 for name, s := range generated {
78 if want := deviceJSON(t, s); !reflect.DeepEqual(schemas[name], want) {
79 var pretty bytes.Buffer
80 _ = json.Indent(&pretty, s, "", " ")
81 t.Errorf("schema %s differs from internal/wire; want:\n%s", name, pretty.String())
82 }
83 }
84 for name, s := range schemas {
85 if _, ok := s.(map[string]any)["x-go-type"]; ok && generated[name] == nil {
86 t.Errorf("schema %s names a Go type no device operation reaches", name)
87 }
88 }
89
90 f := newFixture(t)
91 engine := deviceEngineRoutes(t, f)
92 required := personAPIRoutes()
93 paths := doc["paths"].(map[string]any)
94 documented := 0
95 for _, methods := range paths {
96 documented += len(methods.(map[string]any))
97 }
98 all := map[string]bool{"POST /native/oficina-id": true, "POST /tasks/{id}/preview-pass": true}
99 for key := range engine {
100 all[key] = true
101 }
102 for path, methods := range required {
103 for _, m := range strings.Fields(methods) {
104 all[m+" "+path] = true
105 }
106 }
107 if documented != len(all) {
108 t.Errorf("the document has %d operations; the person API and the engine serve %d", documented, len(all))
109 }
110 for key, spec := range wireschema.NativeOps {
111 method, path, _ := strings.Cut(key, " ")
112 op := paths[path].(map[string]any)[strings.ToLower(method)].(map[string]any)
113 deviceOperation(t, key, op, spec)
114 want := `[{"browserSession":[]}]`
115 if path == "/native/oficina-id" {
116 want = `[]`
117 if !reflect.DeepEqual(op["servers"], []any{map[string]any{"url": "/"}}) {
118 t.Error("exchange must use instance root")
119 }
120 }
121 security, _ := json.Marshal(op["security"])
122 if string(security) != want {
123 t.Error("native authentication contract", key, string(security))
124 }
125 }
126 for key := range wireschema.Ops {
127 if !engine[key] {
128 t.Errorf("%s is documented but the engine does not serve it", key)
129 }
130 }
131 for key := range engine {
132 method, path, _ := strings.Cut(key, " ")
133 methods, _ := paths[path].(map[string]any)
134 op, _ := methods[strings.ToLower(method)].(map[string]any)
135 if op == nil {
136 t.Errorf("missing OpenAPI operation %s", key)
137 continue
138 }
139 security, _ := json.Marshal(op["security"])
140 want := `[{"personBearer":[]}]`
141 if key == "GET /events" {
142 want = `[{"personBearer":[]},{"browserSession":[]}]`
143 }
144 if string(security) != want {
145 t.Errorf("%s: security %s, want %s", key, security, want)
146 }
147 if strings.HasPrefix(path, "/assistant/") {
148 continue
149 }
150 spec, ok := wireschema.Ops[key]
151 if !ok {
152 t.Errorf("%s: an engine route with no entry in wireschema.Ops", key)
153 continue
154 }
155 deviceOperation(t, key, op, spec)
156 rule, shared := deviceShared[key]
157 if _, inPerson := required[path]; shared != (inPerson && strings.Contains(" "+required[path]+" ", " "+method+" ")) {
158 t.Errorf("%s: shared with the earlier person API is %v in deviceShared", key, shared)
159 }
160 earlier, _ := op["x-earlierPersonAPI"].(map[string]any)
161 switch {
162 case shared && rule != "replaced" && (earlier == nil || earlier["operation"] == nil):
163 t.Errorf("%s: a shared path needs x-earlierPersonAPI", key)
164 case (!shared || rule == "replaced") && earlier != nil:
165 t.Errorf("%s: no other answer is served here", key)
166 case shared && rule != "device" && rule != "replaced" && !strings.Contains(op["description"].(string), "`"+rule+"`"):
167 t.Errorf("%s: the description must name the id prefix %s", key, rule)
168 }
169 }
170 deviceSharedServed(t, f)
171
172 for name, from := range deviceFixtures {
173 fields := strings.Fields(from)
174 op := paths[fields[1]].(map[string]any)[strings.ToLower(fields[0])].(map[string]any)
175 var schema map[string]any
176 for _, c := range op["responses"].(map[string]any)[fields[2]].(map[string]any)["content"].(map[string]any) {
177 schema = c.(map[string]any)["schema"].(map[string]any)
178 }
179 raw, err := os.ReadFile("../../native/apple/Tests/EquipoKitTests/Fixtures/thin/" + name + ".json")
180 must(t, err)
181 var value any
182 must(t, json.Unmarshal(raw, &value))
183 values := []any{value}
184 if name == "events" {
185 values = value.([]any)
186 }
187 for _, v := range values {
188 if name == "events" {
189 // Each event against the schema of its type and resource,
190 // one of StreamEvent's.
191 e, _ := v.(map[string]any)
192 variant := wireschema.EventName(fmt.Sprint(e["type"], " ", e["resource"]))
193 stream, _ := json.Marshal(schemas["StreamEvent"])
194 if !strings.Contains(string(stream), `"#/components/schemas/`+variant+`"`) {
195 t.Errorf("events.json: no %s in StreamEvent", variant)
196 continue
197 }
198 schema = map[string]any{"$ref": "#/components/schemas/" + variant}
199 }
200 if err := wireschema.Validate(schemas, v, schema, "$"); err != nil {
201 t.Errorf("%s.json does not match %s: %v", name, from, err)
202 }
203 }
204 }
205
206 // The stream's event types are the Event schema's, and a ping.
207 types := append(slices.Clone(schemas["Event"].(map[string]any)["properties"].(map[string]any)["type"].(map[string]any)["enum"].([]any)), "ping")
208 listed := paths["/events"].(map[string]any)["get"].(map[string]any)["x-eventTypes"].([]any)
209 byText := func(a, b any) int { return strings.Compare(a.(string), b.(string)) }
210 slices.SortFunc(types, byText)
211 slices.SortFunc(listed, byText)
212 if !reflect.DeepEqual(types, listed) {
213 t.Errorf("GET /events x-eventTypes %v, want %v", listed, types)
214 }
215 // Every schema is some operation's, the earlier ones included.
216 reached := map[string]bool{}
217 var walk func(any)
218 walk = func(v any) {
219 switch x := v.(type) {
220 case map[string]any:
221 for k, item := range x {
222 if ref, ok := item.(string); ok && k == "$ref" && strings.HasPrefix(ref, "#/components/schemas/") {
223 if name := strings.TrimPrefix(ref, "#/components/schemas/"); !reached[name] {
224 reached[name] = true
225 walk(schemas[name])
226 }
227 } else {
228 walk(item)
229 }
230 }
231 case []any:
232 for _, item := range x {
233 walk(item)
234 }
235 }
236 }
237 walk(paths)
238 walk(doc["components"].(map[string]any)["responses"])
239 for name := range schemas {
240 if !reached[name] {
241 t.Errorf("schema %s is no operation's", name)
242 }
243 }
244
245 codes := schemas["Error"].(map[string]any)["properties"].(map[string]any)["code"].(map[string]any)["enum"].([]any)
246 sources, _ := filepath.Glob("../equipo/chat/*.go")
247 written := regexp.MustCompile(`WriteError\(w, r, [^,]+, "([a-z_]+)"`)
248 for _, file := range sources {
249 if strings.HasSuffix(file, "_test.go") {
250 continue
251 }
252 src, err := os.ReadFile(file)
253 must(t, err)
254 for _, m := range written.FindAllStringSubmatch(string(src), -1) {
255 if !slices.Contains(codes, any(m[1])) {
256 t.Errorf("%s writes error code %s, missing from Error", filepath.Base(file), m[1])
257 }
258 }
259 }
260}
261
262// deviceOperation checks one documented engine operation's bodies
263// against the wire types in wireschema.Ops.
264func deviceOperation(t *testing.T, key string, op map[string]any, spec wireschema.Op) {
265 t.Helper()
266 body, _ := op["requestBody"].(map[string]any)
267 switch {
268 case spec.In == nil && body != nil:
269 t.Errorf("%s reads no body", key)
270 case spec.In != nil && body == nil:
271 t.Errorf("%s: missing request body", key)
272 case spec.In != nil:
273 content := body["content"].(map[string]any)
274 if _, bytes := spec.In.(wireschema.Bytes); !bytes && !reflect.DeepEqual(content["application/json"], map[string]any{"schema": deviceJSON(t, wireschema.RequestBody(spec.In))}) {
275 t.Errorf("%s: request body differs from %T", key, spec.In)
276 }
277 }
278 responses := op["responses"].(map[string]any)
279 for status := range responses {
280 if _, ok := spec.Out[status]; !ok && status[0] == '2' {
281 t.Errorf("%s: %s is not an answer the handler writes", key, status)
282 }
283 }
284 for status, v := range spec.Out {
285 r, _ := responses[status].(map[string]any)
286 if r == nil {
287 t.Errorf("%s: missing response %s", key, status)
288 continue
289 }
290 content, _ := r["content"].(map[string]any)
291 switch v.(type) {
292 case nil:
293 if content != nil {
294 t.Errorf("%s: %s has no body", key, status)
295 }
296 case wireschema.Bytes:
297 if content == nil || content["application/json"] != nil {
298 t.Errorf("%s: %s is a file", key, status)
299 }
300 default:
301 want := map[string]any{"schema": deviceJSON(t, wireschema.Body(v))}
302 if !reflect.DeepEqual(content["application/json"], want) && !reflect.DeepEqual(content["text/event-stream"], want) {
303 t.Errorf("%s: %s differs from %T", key, status, v)
304 }
305 }
306 }
307}
308
309// deviceSharedServed checks each rule in deviceShared against the
310// router: a browser session gets the earlier answer only where the
311// rule says so.
312func deviceSharedServed(t *testing.T, f *fixture) {
313 t.Helper()
314 for key, rule := range deviceShared {
315 method, path, _ := strings.Cut(key, " ")
316 earlier := strings.ReplaceAll(path, "{id}", "EARLIER")
317 thin := strings.ReplaceAll(path, "{id}", rule+"thin")
318 cases := map[string]bool{earlier: rule != "replaced"}
319 if rule != "device" && rule != "replaced" {
320 cases[thin] = false
321 }
322 for p, served := range cases {
323 w := apiRequest(t, f, owner, method, "/api/v1"+p, "{}", "shared-"+rule, `"1"`)
324 if (w.Code != http.StatusUnauthorized) != served {
325 t.Errorf("%s %s with a browser session = %d; earlier answer expected %v", method, p, w.Code, served)
326 }
327 }
328 }
329}
330
331// deviceJSON is v as encoding/json reads it back.
332func deviceJSON(t *testing.T, v any) any {
333 t.Helper()
334 raw, err := json.Marshal(v)
335 must(t, err)
336 var out any
337 must(t, json.Unmarshal(raw, &out))
338 return out
339}
340
341// TestPersonAPIDeviceProbes asks a new instance, with no runner, task or
342// project yet, what a freshly paired device first reads, and checks
343// each answer against its operation's documented schema; and checks
344// the documented query bounds against the handlers'.
345//
346// What stays unchecked against a live answer: the engine's writes and
347// most reads of populated resources. Their statuses and wire types are
348// read from the handlers' source (wireschema TestOpsAreWhatTheHandlersWrite)
349// and their schemas generated from those types; where the native apps
350// captured an answer, it is checked here too. The event stream's data
351// is checked by its fixtures and by TestEventDataIsWhatTheEngineAppends,
352// which reads each event's type and resource but not its data's type.
353func TestPersonAPIDeviceProbes(t *testing.T) {
354 raw, err := os.ReadFile("../../docs/api/equipo-v1.openapi.json")
355 must(t, err)
356 var doc map[string]any
357 must(t, json.Unmarshal(raw, &doc))
358 paths := doc["paths"].(map[string]any)
359 schemas := doc["components"].(map[string]any)["schemas"].(map[string]any)
360 f := newFixture(t)
361 apiRouter(t, f, func(_ context.Context, token string) (personapi.PersonPrincipal, error) {
362 if token != "device-probe" {
363 return personapi.PersonPrincipal{}, equipo.ErrForbidden
364 }
365 return personapi.PersonPrincipal{Address: owner.Address, CredentialID: "device-probe", SessionEpoch: time.Now().Unix()}, nil
366 })
367 get := func(path string) *httptest.ResponseRecorder {
368 r := httptest.NewRequest("GET", "/api/v1"+path, nil)
369 r.Header.Set("Authorization", "Bearer device-probe")
370 w := httptest.NewRecorder()
371 f.Handler.ServeHTTP(w, r)
372 return w
373 }
374 param := func(path, name string) map[string]any {
375 for _, p := range paths[path].(map[string]any)["get"].(map[string]any)["parameters"].([]any) {
376 if p.(map[string]any)["name"] == name {
377 return p.(map[string]any)["schema"].(map[string]any)
378 }
379 }
380 t.Fatalf("GET %s documents no %s", path, name)
381 return nil
382 }
383 probes := []string{"/snapshot", "/messages", "/tasks", "/needs-you", "/projects", "/runners", "/connections", "/notebook",
384 "/thinking", "/connections/preference", "/specialists", "/housekeeping", "/housekeeping/actions", "/advice"}
385 for _, by := range param("/usage", "by")["enum"].([]any) {
386 for _, period := range param("/usage", "period")["enum"].([]any) {
387 probes = append(probes, fmt.Sprintf("/usage?period=%s&by=%s", period, by))
388 }
389 }
390 for _, path := range []string{"/messages", "/housekeeping/actions"} {
391 limit := param(path, "limit")
392 for _, n := range []any{limit["minimum"], limit["maximum"]} {
393 probes = append(probes, fmt.Sprintf("%s?limit=%v", path, n))
394 }
395 for _, n := range []float64{limit["minimum"].(float64) - 1, limit["maximum"].(float64) + 1} {
396 if w := get(fmt.Sprintf("%s?limit=%v", path, n)); w.Code != http.StatusUnprocessableEntity {
397 t.Errorf("GET %s?limit=%v = %d, outside the documented bounds", path, n, w.Code)
398 }
399 }
400 }
401 for _, q := range []string{"period=year", "by=colour"} {
402 if w := get("/usage?" + q); w.Code != http.StatusUnprocessableEntity {
403 t.Errorf("GET /usage?%s = %d, outside the documented enum", q, w.Code)
404 }
405 }
406 for _, path := range probes {
407 w := get(path)
408 route, _, _ := strings.Cut(path, "?")
409 if w.Code != http.StatusOK {
410 t.Errorf("GET %s = %d: %s", path, w.Code, w.Body.String())
411 continue
412 }
413 schema := paths[route].(map[string]any)["get"].(map[string]any)["responses"].(map[string]any)["200"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)
414 var value any
415 must(t, json.Unmarshal(w.Body.Bytes(), &value))
416 if err := wireschema.Validate(schemas, value, schema, "$"); err != nil {
417 t.Errorf("GET %s on a new instance does not match its schema: %v", path, err)
418 }
419 }
420}
421