package plan3test import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "reflect" "regexp" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/chat" "amadan.net/oficina/equipo/internal/equipo/personapi" "amadan.net/oficina/equipo/internal/wire/wireschema" "github.com/go-chi/chi/v5" ) // deviceShared says how each path the engine shares with the earlier // person API picks its answer (chat.HTTP.Mount, thinOr): by the // Authorization header, by the id's prefix, or not at all (replaced). var deviceShared = map[string]string{ "GET /tasks": "device", "GET /needs-you": "device", "GET /runners": "device", "GET /connections": "device", "GET /specialists": "device", "GET /cards/{id}": "c_", "GET /tasks/{id}": "tk", "POST /tasks/{id}/cancel": "tk", "GET /questions/{id}": "q_", "GET /connections/{id}": "cn_", "DELETE /connections/{id}": "cn_", "GET /projects": "replaced", "POST /projects": "replaced", } // deviceFixtures are the native apps' captured device answers // (internal/thintest TestNativeFixtures): the operation and status each // came from. var deviceFixtures = map[string]string{ "snapshot": "GET /snapshot 200", "tasks": "GET /tasks 200", "needs-you": "GET /needs-you 200", "projects": "GET /projects 200", "task": "GET /tasks/{id} 200", "messages": "GET /messages 200", "sent": "POST /messages 201", "answered": "POST /cards/{id}/answer 200", "card-conflict": "POST /cards/{id}/answer 409", "thread-entry": "POST /tasks/{id}/thread 200", "events": "GET /events 200", } // deviceEngineRoutes are the routes chat.HTTP.Mount adds, the Assistant's // Oficina connect included. func deviceEngineRoutes(t *testing.T, f *fixture) map[string]bool { t.Helper() h := &chat.HTTP{Store: f.Store.Chat(), OficinaConnect: func(context.Context, string, string) (string, error) { return "", nil }, OficinaFinish: func(context.Context, string, string, string) (string, error) { return "", nil }} r := chi.NewRouter() h.Mount(r) out := map[string]bool{} must(t, chi.Walk(r, func(method, path string, _ http.Handler, _ ...func(http.Handler) http.Handler) error { out[method+" "+path] = true return nil })) return out } // TestPersonAPIDeviceContract holds docs/api/equipo-v1.openapi.json to // what a device bearer is answered with: every engine route documented // with the wire types its handler writes, every schema generated from // internal/wire, every captured device answer valid against its // operation's schema with nothing unknown, and every error code the // engine writes in Error. func TestPersonAPIDeviceContract(t *testing.T) { raw, err := os.ReadFile("../../docs/api/equipo-v1.openapi.json") must(t, err) var doc map[string]any must(t, json.Unmarshal(raw, &doc)) schemas := doc["components"].(map[string]any)["schemas"].(map[string]any) generated := wireschema.Generate() for name, s := range generated { if want := deviceJSON(t, s); !reflect.DeepEqual(schemas[name], want) { var pretty bytes.Buffer _ = json.Indent(&pretty, s, "", " ") t.Errorf("schema %s differs from internal/wire; want:\n%s", name, pretty.String()) } } for name, s := range schemas { if _, ok := s.(map[string]any)["x-go-type"]; ok && generated[name] == nil { t.Errorf("schema %s names a Go type no device operation reaches", name) } } f := newFixture(t) engine := deviceEngineRoutes(t, f) required := personAPIRoutes() paths := doc["paths"].(map[string]any) documented := 0 for _, methods := range paths { documented += len(methods.(map[string]any)) } all := map[string]bool{"POST /native/oficina-id": true, "POST /tasks/{id}/preview-pass": true} for key := range engine { all[key] = true } for path, methods := range required { for _, m := range strings.Fields(methods) { all[m+" "+path] = true } } if documented != len(all) { t.Errorf("the document has %d operations; the person API and the engine serve %d", documented, len(all)) } for key, spec := range wireschema.NativeOps { method, path, _ := strings.Cut(key, " ") op := paths[path].(map[string]any)[strings.ToLower(method)].(map[string]any) deviceOperation(t, key, op, spec) want := `[{"browserSession":[]}]` if path == "/native/oficina-id" { want = `[]` if !reflect.DeepEqual(op["servers"], []any{map[string]any{"url": "/"}}) { t.Error("exchange must use instance root") } } security, _ := json.Marshal(op["security"]) if string(security) != want { t.Error("native authentication contract", key, string(security)) } } for key := range wireschema.Ops { if !engine[key] { t.Errorf("%s is documented but the engine does not serve it", key) } } for key := range engine { method, path, _ := strings.Cut(key, " ") methods, _ := paths[path].(map[string]any) op, _ := methods[strings.ToLower(method)].(map[string]any) if op == nil { t.Errorf("missing OpenAPI operation %s", key) continue } security, _ := json.Marshal(op["security"]) want := `[{"personBearer":[]}]` if key == "GET /events" { want = `[{"personBearer":[]},{"browserSession":[]}]` } if string(security) != want { t.Errorf("%s: security %s, want %s", key, security, want) } if strings.HasPrefix(path, "/assistant/") { continue } spec, ok := wireschema.Ops[key] if !ok { t.Errorf("%s: an engine route with no entry in wireschema.Ops", key) continue } deviceOperation(t, key, op, spec) rule, shared := deviceShared[key] if _, inPerson := required[path]; shared != (inPerson && strings.Contains(" "+required[path]+" ", " "+method+" ")) { t.Errorf("%s: shared with the earlier person API is %v in deviceShared", key, shared) } earlier, _ := op["x-earlierPersonAPI"].(map[string]any) switch { case shared && rule != "replaced" && (earlier == nil || earlier["operation"] == nil): t.Errorf("%s: a shared path needs x-earlierPersonAPI", key) case (!shared || rule == "replaced") && earlier != nil: t.Errorf("%s: no other answer is served here", key) case shared && rule != "device" && rule != "replaced" && !strings.Contains(op["description"].(string), "`"+rule+"`"): t.Errorf("%s: the description must name the id prefix %s", key, rule) } } deviceSharedServed(t, f) for name, from := range deviceFixtures { fields := strings.Fields(from) op := paths[fields[1]].(map[string]any)[strings.ToLower(fields[0])].(map[string]any) var schema map[string]any for _, c := range op["responses"].(map[string]any)[fields[2]].(map[string]any)["content"].(map[string]any) { schema = c.(map[string]any)["schema"].(map[string]any) } raw, err := os.ReadFile("../../native/apple/Tests/EquipoKitTests/Fixtures/thin/" + name + ".json") must(t, err) var value any must(t, json.Unmarshal(raw, &value)) values := []any{value} if name == "events" { values = value.([]any) } for _, v := range values { if name == "events" { // Each event against the schema of its type and resource, // one of StreamEvent's. e, _ := v.(map[string]any) variant := wireschema.EventName(fmt.Sprint(e["type"], " ", e["resource"])) stream, _ := json.Marshal(schemas["StreamEvent"]) if !strings.Contains(string(stream), `"#/components/schemas/`+variant+`"`) { t.Errorf("events.json: no %s in StreamEvent", variant) continue } schema = map[string]any{"$ref": "#/components/schemas/" + variant} } if err := wireschema.Validate(schemas, v, schema, "$"); err != nil { t.Errorf("%s.json does not match %s: %v", name, from, err) } } } // The stream's event types are the Event schema's, and a ping. types := append(slices.Clone(schemas["Event"].(map[string]any)["properties"].(map[string]any)["type"].(map[string]any)["enum"].([]any)), "ping") listed := paths["/events"].(map[string]any)["get"].(map[string]any)["x-eventTypes"].([]any) byText := func(a, b any) int { return strings.Compare(a.(string), b.(string)) } slices.SortFunc(types, byText) slices.SortFunc(listed, byText) if !reflect.DeepEqual(types, listed) { t.Errorf("GET /events x-eventTypes %v, want %v", listed, types) } // Every schema is some operation's, the earlier ones included. reached := map[string]bool{} var walk func(any) walk = func(v any) { switch x := v.(type) { case map[string]any: for k, item := range x { if ref, ok := item.(string); ok && k == "$ref" && strings.HasPrefix(ref, "#/components/schemas/") { if name := strings.TrimPrefix(ref, "#/components/schemas/"); !reached[name] { reached[name] = true walk(schemas[name]) } } else { walk(item) } } case []any: for _, item := range x { walk(item) } } } walk(paths) walk(doc["components"].(map[string]any)["responses"]) for name := range schemas { if !reached[name] { t.Errorf("schema %s is no operation's", name) } } codes := schemas["Error"].(map[string]any)["properties"].(map[string]any)["code"].(map[string]any)["enum"].([]any) sources, _ := filepath.Glob("../equipo/chat/*.go") written := regexp.MustCompile(`WriteError\(w, r, [^,]+, "([a-z_]+)"`) for _, file := range sources { if strings.HasSuffix(file, "_test.go") { continue } src, err := os.ReadFile(file) must(t, err) for _, m := range written.FindAllStringSubmatch(string(src), -1) { if !slices.Contains(codes, any(m[1])) { t.Errorf("%s writes error code %s, missing from Error", filepath.Base(file), m[1]) } } } } // deviceOperation checks one documented engine operation's bodies // against the wire types in wireschema.Ops. func deviceOperation(t *testing.T, key string, op map[string]any, spec wireschema.Op) { t.Helper() body, _ := op["requestBody"].(map[string]any) switch { case spec.In == nil && body != nil: t.Errorf("%s reads no body", key) case spec.In != nil && body == nil: t.Errorf("%s: missing request body", key) case spec.In != nil: content := body["content"].(map[string]any) if _, bytes := spec.In.(wireschema.Bytes); !bytes && !reflect.DeepEqual(content["application/json"], map[string]any{"schema": deviceJSON(t, wireschema.RequestBody(spec.In))}) { t.Errorf("%s: request body differs from %T", key, spec.In) } } responses := op["responses"].(map[string]any) for status := range responses { if _, ok := spec.Out[status]; !ok && status[0] == '2' { t.Errorf("%s: %s is not an answer the handler writes", key, status) } } for status, v := range spec.Out { r, _ := responses[status].(map[string]any) if r == nil { t.Errorf("%s: missing response %s", key, status) continue } content, _ := r["content"].(map[string]any) switch v.(type) { case nil: if content != nil { t.Errorf("%s: %s has no body", key, status) } case wireschema.Bytes: if content == nil || content["application/json"] != nil { t.Errorf("%s: %s is a file", key, status) } default: want := map[string]any{"schema": deviceJSON(t, wireschema.Body(v))} if !reflect.DeepEqual(content["application/json"], want) && !reflect.DeepEqual(content["text/event-stream"], want) { t.Errorf("%s: %s differs from %T", key, status, v) } } } } // deviceSharedServed checks each rule in deviceShared against the // router: a browser session gets the earlier answer only where the // rule says so. func deviceSharedServed(t *testing.T, f *fixture) { t.Helper() for key, rule := range deviceShared { method, path, _ := strings.Cut(key, " ") earlier := strings.ReplaceAll(path, "{id}", "EARLIER") thin := strings.ReplaceAll(path, "{id}", rule+"thin") cases := map[string]bool{earlier: rule != "replaced"} if rule != "device" && rule != "replaced" { cases[thin] = false } for p, served := range cases { w := apiRequest(t, f, owner, method, "/api/v1"+p, "{}", "shared-"+rule, `"1"`) if (w.Code != http.StatusUnauthorized) != served { t.Errorf("%s %s with a browser session = %d; earlier answer expected %v", method, p, w.Code, served) } } } } // deviceJSON is v as encoding/json reads it back. func deviceJSON(t *testing.T, v any) any { t.Helper() raw, err := json.Marshal(v) must(t, err) var out any must(t, json.Unmarshal(raw, &out)) return out } // TestPersonAPIDeviceProbes asks a new instance, with no runner, task or // project yet, what a freshly paired device first reads, and checks // each answer against its operation's documented schema; and checks // the documented query bounds against the handlers'. // // What stays unchecked against a live answer: the engine's writes and // most reads of populated resources. Their statuses and wire types are // read from the handlers' source (wireschema TestOpsAreWhatTheHandlersWrite) // and their schemas generated from those types; where the native apps // captured an answer, it is checked here too. The event stream's data // is checked by its fixtures and by TestEventDataIsWhatTheEngineAppends, // which reads each event's type and resource but not its data's type. func TestPersonAPIDeviceProbes(t *testing.T) { raw, err := os.ReadFile("../../docs/api/equipo-v1.openapi.json") must(t, err) var doc map[string]any must(t, json.Unmarshal(raw, &doc)) paths := doc["paths"].(map[string]any) schemas := doc["components"].(map[string]any)["schemas"].(map[string]any) f := newFixture(t) apiRouter(t, f, func(_ context.Context, token string) (personapi.PersonPrincipal, error) { if token != "device-probe" { return personapi.PersonPrincipal{}, equipo.ErrForbidden } return personapi.PersonPrincipal{Address: owner.Address, CredentialID: "device-probe", SessionEpoch: time.Now().Unix()}, nil }) get := func(path string) *httptest.ResponseRecorder { r := httptest.NewRequest("GET", "/api/v1"+path, nil) r.Header.Set("Authorization", "Bearer device-probe") w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) return w } param := func(path, name string) map[string]any { for _, p := range paths[path].(map[string]any)["get"].(map[string]any)["parameters"].([]any) { if p.(map[string]any)["name"] == name { return p.(map[string]any)["schema"].(map[string]any) } } t.Fatalf("GET %s documents no %s", path, name) return nil } probes := []string{"/snapshot", "/messages", "/tasks", "/needs-you", "/projects", "/runners", "/connections", "/notebook", "/thinking", "/connections/preference", "/specialists", "/housekeeping", "/housekeeping/actions", "/advice"} for _, by := range param("/usage", "by")["enum"].([]any) { for _, period := range param("/usage", "period")["enum"].([]any) { probes = append(probes, fmt.Sprintf("/usage?period=%s&by=%s", period, by)) } } for _, path := range []string{"/messages", "/housekeeping/actions"} { limit := param(path, "limit") for _, n := range []any{limit["minimum"], limit["maximum"]} { probes = append(probes, fmt.Sprintf("%s?limit=%v", path, n)) } for _, n := range []float64{limit["minimum"].(float64) - 1, limit["maximum"].(float64) + 1} { if w := get(fmt.Sprintf("%s?limit=%v", path, n)); w.Code != http.StatusUnprocessableEntity { t.Errorf("GET %s?limit=%v = %d, outside the documented bounds", path, n, w.Code) } } } for _, q := range []string{"period=year", "by=colour"} { if w := get("/usage?" + q); w.Code != http.StatusUnprocessableEntity { t.Errorf("GET /usage?%s = %d, outside the documented enum", q, w.Code) } } for _, path := range probes { w := get(path) route, _, _ := strings.Cut(path, "?") if w.Code != http.StatusOK { t.Errorf("GET %s = %d: %s", path, w.Code, w.Body.String()) continue } 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) var value any must(t, json.Unmarshal(w.Body.Bytes(), &value)) if err := wireschema.Validate(schemas, value, schema, "$"); err != nil { t.Errorf("GET %s on a new instance does not match its schema: %v", path, err) } } }