package cabana_test import ( "bytes" "context" "crypto/rand" "encoding/base64" "encoding/json" "fmt" "image" "image/color" "image/png" "io" "io/fs" "mime/multipart" "net/http" "net/http/httptest" "os" "path/filepath" "runtime" "sort" "strings" "testing" "testing/fstest" "time" "git.golem15.com/golem15/summercms/modules/backpack" "git.golem15.com/golem15/summercms/modules/cabana" "git.golem15.com/golem15/summercms/modules/compass" "git.golem15.com/golem15/summercms/modules/lagoon" "git.golem15.com/golem15/summercms/modules/lagoon/attach" "git.golem15.com/golem15/summercms/modules/pact" "git.golem15.com/golem15/summercms/modules/party" "git.golem15.com/golem15/summercms/modules/phrasebook" "git.golem15.com/golem15/summercms/modules/postcard" "git.golem15.com/golem15/summercms/modules/signpost" "git.golem15.com/golem15/summercms/modules/surf" "gocloud.dev/blob" "gocloud.dev/blob/memblob" "gorm.io/gorm" ) // conformCase is one inventoried admin route called for real through the // assembled router. decode must accept the body with unknown fields // disallowed, and ref is the success schema admin.json documents. type conformCase struct { key string status int ref string call func(t *testing.T, env *conformEnv) *httptest.ResponseRecorder decode func(dec *json.Decoder) error // raw, when set, checks a binary response instead of decoding JSON; // admin.json must document the success as binary. raw func(t *testing.T, rec *httptest.ResponseRecorder) } // binaryFile checks a protected file response: status, content type and // the D-10 headers. func binaryFile(contentType string) func(t *testing.T, rec *httptest.ResponseRecorder) { return func(t *testing.T, rec *httptest.ResponseRecorder) { t.Helper() h := rec.Header() if h.Get("Content-Type") != contentType || h.Get("X-Content-Type-Options") != "nosniff" || h.Get("Cache-Control") != "private, no-store" || !strings.Contains(h.Get("Content-Security-Policy"), "sandbox") || rec.Body.Len() == 0 { t.Fatalf("protected file headers=%v len=%d", h, rec.Body.Len()) } } } func into[T any]() func(*json.Decoder) error { return func(dec *json.Decoder) error { var out T return dec.Decode(&out) } } // TestPhase10OpenAPIConformance calls every route of the admin inventory // against a PostgreSQL-backed fixture registry (acme names only), decodes // each real response into the Go type its annotation documents with unknown // fields disallowed, and checks admin/openapi/admin.json names that type for // the same path, method and status (D-15, D-16; Pitfall 8). func TestMLOpenAPIConformance(t *testing.T) { spec := conformSpec(t) if got := spec.ref("/{vendor}/{plugin}/{controller}/schema/form", "get", "200"); got != "cabana.Envelope-cabana_FormView" { t.Fatalf("form schema ref = %q", got) } _, file, _, ok := runtime.Caller(0) if !ok { t.Fatal("caller") } raw, err := os.ReadFile(filepath.Join(filepath.Dir(file), "..", "..", "admin", "openapi", "admin.json")) if err != nil { t.Fatal(err) } doc := string(raw) for _, name := range []string{"cabana.FormField", "cabana.FormView"} { if !strings.Contains(doc, `"`+name+`"`) { t.Fatalf("admin.json missing %s", name) } } schema, err := cabana.CompileForm("acme.demo", stubMLSchemaController{}, fstest.MapFS{ "controllers/widgets/config_form.yaml": {Data: []byte("name: posts\nform: ~/plugins/acme/demo/models/widget/fields.yaml\nmodelClass: Widget\n")}, "models/widget/fields.yaml": {Data: []byte(`fields: title: type: mltext label: Title excerpt: type: markdown label: Excerpt body: type: mlmarkdown label: Body `)}, }) if err != nil { t.Fatal(err) } got := map[string]string{} for _, field := range schema.Fields { got[field.Name] = field.Type } if got["title"] != "mltext" || got["excerpt"] != "markdown" || got["body"] != "mlmarkdown" { t.Fatalf("compiled types = %v", got) } } type stubMLSchemaController struct{} func (stubMLSchemaController) ID() string { return "acme.demo.widgets" } func (stubMLSchemaController) ModelName() string { return "Widget" } func (stubMLSchemaController) ConfigDir() string { return "controllers/widgets" } // TestPhase10ConformanceInventory checks without a database that every // inventoried admin route has exactly one conformance case, so a new admin // route without a case fails on any host (G-16.2-1). func TestPhase10ConformanceInventory(t *testing.T) { checkConformInventory(t, conformCases()) } // checkConformInventory fails once, listing in sorted order every // inventoried admin route without a conformance case, every case that names // no inventoried route and every duplicate case. func checkConformInventory(t *testing.T, cases []conformCase) { t.Helper() inventory := map[string]bool{} for _, key := range cabana.AdminAPIRoutes() { inventory[key] = true } seen := map[string]int{} for _, tc := range cases { seen[tc.key]++ } var missing, extra, duplicate []string for key := range inventory { if seen[key] == 0 { missing = append(missing, key) } } for key, n := range seen { if !inventory[key] { extra = append(extra, key) } if n > 1 { duplicate = append(duplicate, key) } } if len(missing)+len(extra)+len(duplicate) == 0 { return } sort.Strings(missing) sort.Strings(extra) sort.Strings(duplicate) var b strings.Builder for _, group := range []struct { title string keys []string }{ {"admin routes without a conformance case (add one to conformCases)", missing}, {"conformance cases that name no inventoried admin route", extra}, {"duplicate conformance cases", duplicate}, } { if len(group.keys) == 0 { continue } fmt.Fprintf(&b, "\n%s:", group.title) for _, key := range group.keys { fmt.Fprintf(&b, "\n %s", key) } } t.Fatalf("conformance inventory does not match the admin routes:%s", b.String()) } func TestPhase10OpenAPIConformance(t *testing.T) { cases := conformCases() checkConformInventory(t, cases) env := newConformEnv(t) spec := conformSpec(t) for _, tc := range cases { ok := t.Run(tc.key, func(t *testing.T) { rec := tc.call(t, env) if rec.Code != tc.status { t.Fatalf("status=%d want %d body=%s", rec.Code, tc.status, rec.Body.String()) } method, path, _ := strings.Cut(tc.key, " ") if tc.raw != nil { tc.raw(t, rec) if !spec.binary(path, strings.ToLower(method), fmt.Sprint(tc.status)) { t.Fatalf("admin.json does not document %s %d as binary", tc.key, tc.status) } return } dec := json.NewDecoder(bytes.NewReader(rec.Body.Bytes())) dec.DisallowUnknownFields() if err := tc.decode(dec); err != nil { t.Fatalf("body does not match its documented type: %v\n%s", err, rec.Body.String()) } got := spec.ref(path, strings.ToLower(method), fmt.Sprint(tc.status)) if got != tc.ref { t.Fatalf("admin.json documents %q for %s %d, the handler writes %s", got, tc.key, tc.status, tc.ref) } }) if !ok { t.FailNow() } } // The documented error answers of the Phase 17 routes, after a fresh // login (the last case logged out). if rec := env.send(t, http.MethodPost, "/auth/login", map[string]string{"login": env.login, "password": adminTestPassword}, false); rec.Code != http.StatusOK { t.Fatalf("re-login status=%d body=%s", rec.Code, rec.Body.String()) } // Phase 18 payloads on the acme.payments fixture. conformPhase18(t, spec) for _, tc := range companionsErrorCases() { t.Run(fmt.Sprintf("%s %d %s", tc.key, tc.status, tc.name), func(t *testing.T) { rec := tc.call(t, env) if rec.Code != tc.status { t.Fatalf("status=%d want %d body=%s", rec.Code, tc.status, rec.Body.String()) } dec := json.NewDecoder(bytes.NewReader(rec.Body.Bytes())) dec.DisallowUnknownFields() var body cabana.ErrorEnvelope if err := dec.Decode(&body); err != nil || body.Error.Code == "" { t.Fatalf("body is not an ErrorEnvelope: %v\n%s", err, rec.Body.String()) } if tc.code != "" && body.Error.Code != tc.code { t.Fatalf("error code = %q, want %q", body.Error.Code, tc.code) } method, path, _ := strings.Cut(tc.key, " ") if got := spec.ref(path, strings.ToLower(method), fmt.Sprint(tc.status)); got != "cabana.ErrorEnvelope" { t.Fatalf("admin.json documents %q for %s %d, the handler writes cabana.ErrorEnvelope", got, tc.key, tc.status) } }) } } // conformPhase18 checks the Phase 18 payload shapes against admin.json on // the acme.payments fixture (D-07, D-13): the settings GET and PUT with // meta.secrets, and a form schema with a money field, each decoded with // unknown fields disallowed into the type admin.json documents. func conformPhase18(t *testing.T, spec conformSpecDoc) { t.Helper() e := newPaymentsEnv(t) strict := func(t *testing.T, key string, rec *httptest.ResponseRecorder, out any, ref string) { t.Helper() if rec.Code != http.StatusOK { t.Fatalf("%s status=%d body=%s", key, rec.Code, rec.Body.String()) } dec := json.NewDecoder(bytes.NewReader(rec.Body.Bytes())) dec.DisallowUnknownFields() if err := dec.Decode(out); err != nil { t.Fatalf("%s body does not match its documented type: %v\n%s", key, err, rec.Body.String()) } method, path, _ := strings.Cut(key, " ") if got := spec.ref(path, strings.ToLower(method), "200"); got != ref { t.Fatalf("admin.json documents %q for %s 200, the handler writes %s", got, key, ref) } } t.Run("PUT /settings/{code} meta.secrets", func(t *testing.T) { var body cabana.Envelope[cabana.SettingsResult] strict(t, "PUT /settings/{code}", e.send(t, http.MethodPut, "/settings/vault", map[string]any{"api_key": "sk_conform", "notes": "
n
"}, true), &body, "cabana.Envelope-cabana_SettingsResult") if body.Data.Meta == nil || body.Data.Meta.Secrets["api_key"] != cabana.SecretStored || len(body.Data.Meta.Notices) != 1 { t.Fatalf("meta = %+v", body.Data.Meta) } }) t.Run("GET /settings/{code} meta.secrets", func(t *testing.T) { var body cabana.Envelope[cabana.SettingsResult] strict(t, "GET /settings/{code}", e.send(t, http.MethodGet, "/settings/vault", nil, true), &body, "cabana.Envelope-cabana_SettingsResult") if _, leaked := body.Data.Data["api_key"]; leaked || body.Data.Meta == nil || body.Data.Meta.Secrets["api_key"] != cabana.SecretStored || body.Data.Meta.Secrets["test_api_key"] != cabana.SecretEmpty { t.Fatalf("settings = %+v", body.Data) } }) t.Run("GET /{vendor}/{plugin}/{controller}/schema/form money", func(t *testing.T) { var body cabana.Envelope[cabana.FormView] strict(t, "GET /{vendor}/{plugin}/{controller}/schema/form", e.send(t, http.MethodGet, "/acme/payments/invoices/schema/form", nil, true), &body, "cabana.Envelope-cabana_FormView") found := 0 for _, f := range body.Data.Fields { switch f.Name { case "total": if f.Type != "money" || f.CurrencyFrom != "currency" || f.Scale != 4 || f.Max != "999999.9999" { t.Fatalf("total = %+v", f) } found++ case "fee": if f.Type != "money" || f.Currency != "EUR" || f.Scale != 2 { t.Fatalf("fee = %+v", f) } found++ } } if found != 2 { t.Fatalf("money fields = %+v", body.Data.Fields) } }) } // companionsErrorCase is one documented error answer of a Phase 17 route. type companionsErrorCase struct { key string status int name string code string call func(t *testing.T, env *conformEnv) *httptest.ResponseRecorder } // companionsErrorCases are the 404, 409 and 422 answers the dependent // options, reorder and singleton routes document, and the 404 of the list, // create and delete routes on a singleton controller. func companionsErrorCases() []companionsErrorCase { partitionLinks := func(t *testing.T, e *conformEnv) (uint, []uint) { t.Helper() group := companionsGroup{Title: "Errors " + e.stamp} if err := e.db.Create(&group).Error; err != nil { t.Fatal(err) } var ids []uint for i := range 2 { link := companionsLink{Title: fmt.Sprintf("err-%d-%s", i, e.stamp), GroupID: &group.ID, SortOrder: i + 1} if err := e.db.Create(&link).Error; err != nil { t.Fatal(err) } ids = append(ids, link.ID) } return group.ID, ids } profileID := func(t *testing.T, e *conformEnv) uint { t.Helper() return dataID(t, e.send(t, http.MethodGet, "/acme/companions/profiles/singleton", nil, true).Body.Bytes()) } return []companionsErrorCase{ {"GET /{vendor}/{plugin}/{controller}/fields/{field}/dependent-options", 404, "field without dependsOn", "not_found", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, dependentOptionsPath("title", "acme-page"), nil, true) }}, {"GET /{vendor}/{plugin}/{controller}/fields/{field}/dependent-options", 401, "anonymous", "", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, dependentOptionsPath("reference", "acme-page"), nil, false) }}, {"GET /{vendor}/{plugin}/{controller}/reorder", 404, "unknown partition", "not_found", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/acme/companions/links/reorder?partition=999999", nil, true) }}, {"GET /{vendor}/{plugin}/{controller}/reorder", 422, "partition not an id", "validation_failed", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/acme/companions/links/reorder?partition=abc", nil, true) }}, {"POST /{vendor}/{plugin}/{controller}/reorder", 409, "stale set", "reorder_stale", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { group, ids := partitionLinks(t, e) return e.send(t, http.MethodPost, "/acme/companions/links/reorder", map[string]any{"partition": group, "nodes": []any{reorderNode(ids[0], nil, 1)}}, true) }}, {"POST /{vendor}/{plugin}/{controller}/reorder", 422, "cycle", "validation_failed", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { group, ids := partitionLinks(t, e) return e.send(t, http.MethodPost, "/acme/companions/links/reorder", map[string]any{"partition": group, "nodes": []any{reorderNode(ids[0], &ids[1], 1), reorderNode(ids[1], &ids[0], 1)}}, true) }}, {"POST /{vendor}/{plugin}/{controller}/reorder", 404, "unknown partition", "not_found", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/acme/companions/links/reorder", map[string]any{"partition": 999999, "nodes": []any{}}, true) }}, {"GET /{vendor}/{plugin}/{controller}/singleton", 404, "not a singleton", "not_found", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/acme/companions/links/singleton", nil, true) }}, {"GET /{vendor}/{plugin}/{controller}", 404, "list of a singleton", "not_found", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/acme/companions/profiles", nil, true) }}, {"POST /{vendor}/{plugin}/{controller}", 404, "create on a singleton", "not_found", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/acme/companions/profiles", map[string]any{"title": "x"}, true) }}, {"DELETE /{vendor}/{plugin}/{controller}/{id}", 404, "delete on a singleton", "not_found", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodDelete, fmt.Sprintf("/acme/companions/profiles/%d", profileID(t, e)), nil, true) }}, } } // conformCases is the conformance case of every inventoried admin route, in // the order TestPhase10OpenAPIConformance calls them: later cases use the // records earlier ones create. func conformCases() []conformCase { return []conformCase{ {"POST /auth/login", 200, "cabana.Envelope-cabana_AdminLoginData", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/auth/login", map[string]string{"login": e.login, "password": adminTestPassword}, false) }, into[cabana.Envelope[cabana.AdminLoginData]](), nil}, {"POST /auth/refresh", 200, "cabana.Envelope-cabana_AdminLoginData", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodPost, "/auth/refresh", nil, true) e.token = accessToken(t, rec.Body.Bytes()) return rec }, into[cabana.Envelope[cabana.AdminLoginData]](), nil}, {"GET /auth/me", 200, "cabana.Envelope-cabana_AdminProfile", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/auth/me", nil, true) }, into[cabana.Envelope[cabana.AdminProfile]](), nil}, {"GET /lang", 200, "cabana.LangEnvelope", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/lang?locale=pl", nil, false) }, into[cabana.LangEnvelope](), nil}, {"GET /navigation", 200, "cabana.Envelope-array_cabana_NavigationEntry", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/navigation", nil, true) }, into[cabana.Envelope[[]cabana.NavigationEntry]](), nil}, {"GET /settings", 200, "cabana.Envelope-array_cabana_SettingsEntry", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/settings", nil, true) }, into[cabana.Envelope[[]cabana.SettingsEntry]](), nil}, {"GET /plugins", 200, "cabana.Envelope-cabana_PluginsOverview", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/plugins", nil, true) }, into[cabana.Envelope[cabana.PluginsOverview]](), nil}, {"GET /plugins/marketplace", 200, "cabana.MarketplaceResponse", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/plugins/marketplace?q=blog", nil, true) }, into[cabana.MarketplaceResponse](), nil}, {"GET /settings/{code}/schema", 200, "cabana.Envelope-cabana_FormView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/settings/conform/schema", nil, true) }, into[cabana.Envelope[cabana.FormView]](), nil}, {"GET /settings/{code}", 200, "cabana.Envelope-cabana_SettingsResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodGet, "/settings/conform", nil, true) // Phase 18 D-13: the password field is absent from data and // reported in meta.secrets. var body cabana.Envelope[cabana.SettingsResult] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { t.Fatal(err) } if _, leaked := body.Data.Data["api_key"]; leaked || body.Data.Meta == nil || body.Data.Meta.Secrets["api_key"] != cabana.SecretEmpty { t.Fatalf("settings secrets = %s", rec.Body.String()) } return rec }, into[cabana.Envelope[cabana.SettingsResult]](), nil}, {"PUT /settings/{code}", 200, "cabana.Envelope-cabana_SettingsResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPut, "/settings/conform", map[string]any{"enabled": true}, true) }, into[cabana.Envelope[cabana.SettingsResult]](), nil}, {"POST /markdown/preview", 200, "cabana.Envelope-cabana_AdminMarkdownPreviewResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/markdown/preview", map[string]string{"markdown": "# Conform"}, true) }, into[cabana.Envelope[cabana.AdminMarkdownPreviewResult]](), nil}, {"GET /mail/images", 200, "cabana.AdminMailImagesResponse", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/mail/images", nil, true) }, into[cabana.AdminMailImagesResponse](), nil}, {"POST /mail/images", 201, "cabana.Envelope-cabana_AdminMailImage", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { var buf bytes.Buffer mw := multipart.NewWriter(&buf) part, err := mw.CreateFormFile("file", "mail-badge.png") if err != nil { t.Fatal(err) } if _, err := part.Write(conformPNG(t)); err != nil { t.Fatal(err) } if err := mw.Close(); err != nil { t.Fatal(err) } rec := e.sendWith(t, http.MethodPost, "/mail/images", buf.Bytes(), mw.FormDataContentType(), map[string]string{"X-Requested-With": "XMLHttpRequest"}) var body cabana.Envelope[cabana.AdminMailImage] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { t.Fatalf("mail image upload: %v body=%s", err, rec.Body.String()) } e.mailImageID = body.Data.ID return rec }, into[cabana.Envelope[cabana.AdminMailImage]](), nil}, {"GET /mail/images/{id}", 200, "cabana.Envelope-cabana_AdminMailImage", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { if e.mailImageID == 0 { t.Fatal("mail image id unset; POST /mail/images must run first") } return e.send(t, http.MethodGet, fmt.Sprintf("/mail/images/%d", e.mailImageID), nil, true) }, into[cabana.Envelope[cabana.AdminMailImage]](), nil}, {"POST /mail/preview", 200, "cabana.Envelope-cabana_AdminMailPreviewResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/mail/preview", map[string]any{ "mode": "branding", "id": 0, "values": map[string]any{ "button_primary_bg": "#112233", }, }, true) }, into[cabana.Envelope[cabana.AdminMailPreviewResult]](), nil}, {"POST /mail/test-send", 200, "cabana.Envelope-cabana_AdminMailTestSendResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/mail/test-send", map[string]any{ "mode": "layout", "id": 0, "values": map[string]any{ "content_html": "{{ .Content }}", "content_text": "{{ .Content }}", "content_css": "", }, }, true) }, into[cabana.Envelope[cabana.AdminMailTestSendResult]](), nil}, {"POST /media/folders", 201, "cabana.Envelope-cabana_AdminMediaFolder", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodPost, "/media/folders", map[string]any{"name": "Conform " + e.stamp}, true) var body cabana.Envelope[cabana.AdminMediaFolder] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { t.Fatalf("media folder create: %v body=%s", err, rec.Body.String()) } e.mediaFolderID = body.Data.ID return rec }, into[cabana.Envelope[cabana.AdminMediaFolder]](), nil}, {"GET /media/folders", 200, "cabana.Envelope-array_cabana_AdminMediaFolder", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/media/folders", nil, true) }, into[cabana.Envelope[[]cabana.AdminMediaFolder]](), nil}, {"PUT /media/folders/{id}", 200, "cabana.Envelope-cabana_AdminMediaFolder", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPut, fmt.Sprintf("/media/folders/%d", e.mediaFolderID), map[string]any{"name": "Conform Renamed " + e.stamp}, true) }, into[cabana.Envelope[cabana.AdminMediaFolder]](), nil}, {"POST /media/items", 201, "cabana.Envelope-cabana_AdminMediaItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { var buf bytes.Buffer mw := multipart.NewWriter(&buf) part, err := mw.CreateFormFile("file", "media-conform.png") if err != nil { t.Fatal(err) } if _, err := part.Write(conformPNG(t)); err != nil { t.Fatal(err) } if err := mw.WriteField("folder_id", fmt.Sprintf("%d", e.mediaFolderID)); err != nil { t.Fatal(err) } if err := mw.Close(); err != nil { t.Fatal(err) } rec := e.sendWith(t, http.MethodPost, "/media/items", buf.Bytes(), mw.FormDataContentType(), map[string]string{"X-Requested-With": "XMLHttpRequest"}) var body cabana.Envelope[cabana.AdminMediaItem] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { t.Fatalf("media item upload: %v body=%s", err, rec.Body.String()) } e.mediaItemID = body.Data.ID return rec }, into[cabana.Envelope[cabana.AdminMediaItem]](), nil}, {"POST /media/items/base64", 201, "cabana.Envelope-cabana_AdminMediaItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodPost, "/media/items/base64", map[string]any{ "filename": "media-b64.png", "content_base64": base64.StdEncoding.EncodeToString(conformPNG(t)), "alt": "Conform b64", }, true) return rec }, into[cabana.Envelope[cabana.AdminMediaItem]](), nil}, {"GET /media/items", 200, "cabana.AdminMediaItemsResponse", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/media/items", nil, true) }, into[cabana.AdminMediaItemsResponse](), nil}, {"GET /media/items/{id}", 200, "cabana.Envelope-cabana_AdminMediaItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, fmt.Sprintf("/media/items/%d", e.mediaItemID), nil, true) }, into[cabana.Envelope[cabana.AdminMediaItem]](), nil}, {"PUT /media/items/{id}", 200, "cabana.Envelope-cabana_AdminMediaItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPut, fmt.Sprintf("/media/items/%d", e.mediaItemID), map[string]any{"alt": "Updated alt", "title": "Updated title"}, true) }, into[cabana.Envelope[cabana.AdminMediaItem]](), nil}, {"POST /media/uploads/prepare", 201, "cabana.Envelope-cabana_AdminMediaPrepareUploadResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/media/uploads/prepare", map[string]any{"filename": "prepared.png", "content_type": "image/png"}, true) }, into[cabana.Envelope[cabana.AdminMediaPrepareUploadResult]](), nil}, {"DELETE /media/items/{id}", 200, "cabana.Envelope-cabana_AdminMediaDeleteResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodDelete, fmt.Sprintf("/media/items/%d", e.mediaItemID), nil, true) }, into[cabana.Envelope[cabana.AdminMediaDeleteResult]](), nil}, {"DELETE /media/folders/{id}", 200, "cabana.Envelope-cabana_AdminMediaDeleteResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodDelete, fmt.Sprintf("/media/folders/%d", e.mediaFolderID), nil, true) }, into[cabana.Envelope[cabana.AdminMediaDeleteResult]](), nil}, {"GET /{vendor}/{plugin}/{controller}/schema/list", 200, "cabana.Envelope-cabana_ListSchema", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodGet, "/acme/conform/gadgets/schema/list", nil, true) var body cabana.Envelope[cabana.ListSchema] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { t.Fatalf("list schema: %v", err) } if len(body.Data.ToolbarActions) != 1 || body.Data.ToolbarActions[0].Name != "recount" { t.Fatalf("toolbarActions = %#v", body.Data.ToolbarActions) } if len(body.Data.Assets.Scripts) != 1 || len(body.Data.Assets.Styles) != 1 { t.Fatalf("assets = %#v", body.Data.Assets) } e.assertPluginAsset(t, body.Data.Assets.Scripts[0], "text/javascript; charset=utf-8") e.assertPluginAsset(t, body.Data.Assets.Styles[0], "text/css; charset=utf-8") return rec }, into[cabana.Envelope[cabana.ListSchema]](), nil}, {"GET /{vendor}/{plugin}/{controller}/schema/form", 200, "cabana.Envelope-cabana_FormView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/acme/conform/gadgets/schema/form", nil, true) }, into[cabana.Envelope[cabana.FormView]](), nil}, {"GET /{vendor}/{plugin}/{controller}/schema/relation/{name}", 200, "cabana.Envelope-cabana_RelationSchema", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/acme/conform/gadgets/schema/relation/members", nil, true) }, into[cabana.Envelope[cabana.RelationSchema]](), nil}, {"GET /{vendor}/{plugin}/{controller}/fields/{field}/options", 200, "cabana.ListEnvelope-array_cabana_RelationOption", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/acme/conform/gadgets/fields/group/options?search="+e.stamp, nil, true) }, into[cabana.ListEnvelope[[]cabana.RelationOption]](), nil}, {"GET /{vendor}/{plugin}/{controller}/fields/{field}/dependent-options", 200, "cabana.Envelope-cabana_AdminDependentOptionsResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, dependentOptionsPath("reference", "acme-page"), nil, true) }, into[cabana.Envelope[cabana.AdminDependentOptionsResult]](), nil}, {"GET /{vendor}/{plugin}/{controller}/reorder", 200, "cabana.Envelope-cabana_AdminReorderTree", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { group := companionsGroup{Title: "Conform " + e.stamp} if err := e.db.Create(&group).Error; err != nil { t.Fatal(err) } link := companionsLink{Title: "link-" + e.stamp, GroupID: &group.ID, SortOrder: 1} if err := e.db.Create(&link).Error; err != nil { t.Fatal(err) } return e.send(t, http.MethodGet, fmt.Sprintf("/acme/companions/links/reorder?partition=%d", group.ID), nil, true) }, into[cabana.Envelope[cabana.AdminReorderTree]](), nil}, {"POST /{vendor}/{plugin}/{controller}/reorder", 200, "cabana.Envelope-cabana_AdminReorderTree", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { tree := reorderTree(t, e.send(t, http.MethodGet, "/acme/companions/links/reorder", nil, true)) if tree.Partition == nil || tree.Partition.Value == nil || len(tree.Nodes) == 0 { t.Fatalf("reorder tree = %+v", tree) } nodes := make([]map[string]any, 0, len(tree.Nodes)) for i, node := range tree.Nodes { nodes = append(nodes, reorderNode(node.ID, nil, int64(i+1))) } return e.send(t, http.MethodPost, "/acme/companions/links/reorder", map[string]any{"partition": *tree.Partition.Value, "nodes": nodes}, true) }, into[cabana.Envelope[cabana.AdminReorderTree]](), nil}, {"GET /{vendor}/{plugin}/{controller}/singleton", 200, "cabana.Envelope-cabana_AdminSingletonResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/acme/companions/profiles/singleton", nil, true) }, into[cabana.Envelope[cabana.AdminSingletonResult]](), nil}, {"GET /{vendor}/{plugin}/{controller}/filters/{scope}/options", 200, "cabana.Envelope-array_cabana_FilterOption", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/acme/conform/gadgets/filters/grouped/options", nil, true) }, into[cabana.Envelope[[]cabana.FilterOption]](), nil}, {"GET /field-types", 200, "cabana.FieldTypesResponse", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodGet, "/field-types", nil, true) var body cabana.FieldTypesResponse if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { t.Fatalf("field types: %v\n%s", err, rec.Body.String()) } var found *cabana.FieldTypeAssets for i := range body.Data { if body.Data[i].Name == conformNoteType { found = &body.Data[i] } } if found == nil || found.Element != conformNoteElement || found.Translatable || len(found.Scripts) != 1 || len(found.Styles) != 0 { t.Fatalf("field types = %s, want %s with its element and one script", rec.Body.String(), conformNoteType) } e.assertPluginAsset(t, found.Scripts[0], "text/javascript; charset=utf-8") return rec }, into[cabana.FieldTypesResponse](), nil}, {"POST /{vendor}/{plugin}/{controller}/{id}/fields/{field}/upload", 201, "cabana.Envelope-cabana_FieldUploadResponse", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { var buf bytes.Buffer mw := multipart.NewWriter(&buf) part, err := mw.CreateFormFile("file", "note.txt") if err != nil { t.Fatal(err) } if _, err := part.Write([]byte("conform note " + e.stamp)); err != nil { t.Fatal(err) } if err := mw.Close(); err != nil { t.Fatal(err) } // {id} 0 is the create form: Upload receives no record. rec := e.sendWith(t, http.MethodPost, "/acme/conform/gadgets/0/fields/note/upload", buf.Bytes(), mw.FormDataContentType(), map[string]string{"X-Requested-With": "XMLHttpRequest"}) var body cabana.Envelope[cabana.FieldUploadResponse] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Data.URL != fmt.Sprintf("/media/conform/note.txt?bytes=%d&record=nil", len("conform note "+e.stamp)) { t.Fatalf("field upload body = %s (%v)", rec.Body.String(), err) } return rec }, into[cabana.Envelope[cabana.FieldUploadResponse]](), nil}, {"POST /{vendor}/{plugin}/{controller}/{id}/files/{field}", 201, "cabana.Envelope-cabana_FileItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.upload(t, 0, "photos", "photo.png", conformPNG(t), e.sessionKey) e.photoID = dataID(t, rec.Body.Bytes()) return rec }, into[cabana.Envelope[cabana.FileItem]](), nil}, {"GET /{vendor}/{plugin}/{controller}/{id}/files/{field}", 200, "cabana.Envelope-array_cabana_FileItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.sendWith(t, http.MethodGet, "/acme/conform/gadgets/0/files/photos", nil, "", map[string]string{cabana.SessionKeyHeader: e.sessionKey}) var body cabana.Envelope[[]cabana.FileItem] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || len(body.Data) != 1 || !body.Data[0].Pending || body.Data[0].URL == "" || body.Data[0].ThumbURL == "" { t.Fatalf("pending file list = %s (%v)", rec.Body.String(), err) } return rec }, into[cabana.Envelope[[]cabana.FileItem]](), nil}, {"POST /{vendor}/{plugin}/{controller}/{id}/files/{field}/reorder", 200, "cabana.Envelope-array_cabana_FileItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { body, _ := json.Marshal(map[string]any{"ids": []uint{e.photoID}}) return e.sendWith(t, http.MethodPost, "/acme/conform/gadgets/0/files/photos/reorder", body, "application/json", map[string]string{cabana.SessionKeyHeader: e.sessionKey}) }, into[cabana.Envelope[[]cabana.FileItem]](), nil}, {"DELETE /{vendor}/{plugin}/{controller}/{id}/files/{field}/{file}", 200, "cabana.Envelope-cabana_FileMutationResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.sendWith(t, http.MethodDelete, fmt.Sprintf("/acme/conform/gadgets/0/files/photos/%d", e.photoID), nil, "", map[string]string{cabana.SessionKeyHeader: e.sessionKey}) }, into[cabana.Envelope[cabana.FileMutationResult]](), nil}, {"POST /{vendor}/{plugin}/{controller}", 201, "cabana.RecordEnvelope", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodPost, "/acme/conform/gadgets", map[string]any{"name": "gadget-" + e.stamp, "active": true, "group": e.groupID, "released_on": "2026-10-02", "starts_at": "2026-10-02T12:30:00+02:00", "note": " note-" + e.stamp + " "}, true) e.gadgetID = dataID(t, rec.Body.Bytes()) // Decode trimmed the note before it was stored. var stored conformGadget if err := e.db.First(&stored, e.gadgetID).Error; err != nil || stored.Note == nil || *stored.Note != "note-"+e.stamp { t.Fatalf("stored note = %#v (%v), want the decoded value", stored.Note, err) } return rec }, into[cabana.RecordEnvelope](), nil}, {"PUT /{vendor}/{plugin}/{controller}/{id}/files/{field}/{file}", 200, "cabana.Envelope-cabana_FileItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { up := e.upload(t, e.gadgetID, "manual", "manual.png", conformPNG(t), e.sessionKey) if up.Code != http.StatusCreated { t.Fatalf("manual upload status=%d body=%s", up.Code, up.Body.String()) } e.manualID = dataID(t, up.Body.Bytes()) body, _ := json.Marshal(map[string]any{"title": "Manual " + e.stamp}) return e.sendWith(t, http.MethodPut, fmt.Sprintf("/acme/conform/gadgets/%d/files/manual/%d", e.gadgetID, e.manualID), body, "application/json", map[string]string{cabana.SessionKeyHeader: e.sessionKey}) }, into[cabana.Envelope[cabana.FileItem]](), nil}, {"GET /{vendor}/{plugin}/{controller}/{id}/files/{field}/{file}/download", 200, "", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.sendWith(t, http.MethodGet, fmt.Sprintf("/acme/conform/gadgets/%d/files/manual/%d/download", e.gadgetID, e.manualID), nil, "", map[string]string{cabana.SessionKeyHeader: e.sessionKey}) }, nil, binaryFile("image/png")}, {"GET /{vendor}/{plugin}/{controller}/{id}/files/{field}/{file}/thumb", 200, "", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.sendWith(t, http.MethodGet, fmt.Sprintf("/acme/conform/gadgets/%d/files/manual/%d/thumb", e.gadgetID, e.manualID), nil, "", map[string]string{cabana.SessionKeyHeader: e.sessionKey}) }, nil, binaryFile("image/png")}, {"POST /{vendor}/{plugin}/{controller}/widgets/{field}", 200, "cabana.Envelope-cabana_AdminActionResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodPost, "/acme/conform/gadgets/widgets/lookup", map[string]any{"record_id": e.gadgetID, "values": map[string]any{"name": "x", "active": false}}, true) // The fixture action also returns active, which is outside the // field's fill: the server filter must drop it. var body cabana.Envelope[cabana.AdminActionResult] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { t.Fatalf("widget action body: %v\n%s", err, rec.Body.String()) } if len(body.Data.Fill) != 1 || body.Data.Fill["name"] != "lookup-"+e.stamp { t.Fatalf("widget fill = %#v, want only name", body.Data.Fill) } return rec }, into[cabana.Envelope[cabana.AdminActionResult]](), nil}, {"GET /{vendor}/{plugin}/{controller}/partials/{name}", 200, "cabana.Envelope-cabana_PartialView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodGet, fmt.Sprintf("/acme/conform/gadgets/partials/summary?id=%d", e.gadgetID), nil, true) if !strings.Contains(rec.Body.String(), `"text":"gadget-`+e.stamp+`"`) { t.Fatalf("form partial did not render the scoped record: %s", rec.Body.String()) } header := e.send(t, http.MethodGet, "/acme/conform/gadgets/partials/stats", nil, true) if header.Code != http.StatusOK || !strings.Contains(header.Body.String(), `"class":"summer-stats"`) { t.Fatalf("header partial status=%d body=%s", header.Code, header.Body.String()) } return rec }, into[cabana.Envelope[cabana.PartialView]](), nil}, {"GET /{vendor}/{plugin}/{controller}", 200, "cabana.ListEnvelope-array_cabana_AdminRecord", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/acme/conform/gadgets?search="+e.stamp, nil, true) }, into[cabana.ListEnvelope[[]cabana.AdminRecord]](), nil}, {"GET /{vendor}/{plugin}/{controller}/{id}", 200, "cabana.RecordEnvelope", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodGet, fmt.Sprintf("/acme/conform/gadgets/%d", e.gadgetID), nil, true) if !strings.Contains(rec.Body.String(), `"note":"loaded:note-`+e.stamp+`"`) { t.Fatalf("show does not serve the note through Load: %s", rec.Body.String()) } return rec }, into[cabana.RecordEnvelope](), nil}, {"PUT /{vendor}/{plugin}/{controller}/{id}", 200, "cabana.RecordEnvelope", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPut, fmt.Sprintf("/acme/conform/gadgets/%d", e.gadgetID), map[string]any{"name": "gadget-" + e.stamp + "-renamed", "group": nil, "released_on": "2026-10-03", "starts_at": nil, "note": "note-" + e.stamp + "-renamed"}, true) }, into[cabana.RecordEnvelope](), nil}, {"GET /{vendor}/{plugin}/{controller}/{id}/relations/{name}/candidates", 200, "cabana.ListEnvelope-array_cabana_AdminRecord", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, fmt.Sprintf("/acme/conform/gadgets/%d/relations/members/candidates?search=%s", e.gadgetID, e.stamp), nil, true) }, into[cabana.ListEnvelope[[]cabana.AdminRecord]](), nil}, {"POST /{vendor}/{plugin}/{controller}/{id}/relations/{name}/link", 200, "cabana.Envelope-cabana_RelationMutationResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, fmt.Sprintf("/acme/conform/gadgets/%d/relations/members/link", e.gadgetID), map[string]any{"ids": []uint{e.memberID}}, true) }, into[cabana.Envelope[cabana.RelationMutationResult]](), nil}, {"GET /{vendor}/{plugin}/{controller}/{id}/relations/{name}/pivot/{child}", 200, "cabana.Envelope-cabana_AdminRecord", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, fmt.Sprintf("/acme/conform/gadgets/%d/relations/members/pivot/%d", e.gadgetID, e.memberID), nil, true) }, into[cabana.Envelope[cabana.AdminRecord]](), nil}, {"PUT /{vendor}/{plugin}/{controller}/{id}/relations/{name}/pivot/{child}", 200, "cabana.Envelope-cabana_AdminRecord", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPut, fmt.Sprintf("/acme/conform/gadgets/%d/relations/members/pivot/%d", e.gadgetID, e.memberID), map[string]any{"note": "note-" + e.stamp}, true) }, into[cabana.Envelope[cabana.AdminRecord]](), nil}, {"GET /{vendor}/{plugin}/{controller}/{id}/relations/{name}", 200, "cabana.ListEnvelope-array_cabana_AdminRecord", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, fmt.Sprintf("/acme/conform/gadgets/%d/relations/members", e.gadgetID), nil, true) }, into[cabana.ListEnvelope[[]cabana.AdminRecord]](), nil}, {"POST /{vendor}/{plugin}/{controller}/{id}/relations/{name}/unlink", 200, "cabana.Envelope-cabana_RelationMutationResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, fmt.Sprintf("/acme/conform/gadgets/%d/relations/members/unlink", e.gadgetID), map[string]any{"ids": []uint{e.memberID}}, true) }, into[cabana.Envelope[cabana.RelationMutationResult]](), nil}, {"POST /{vendor}/{plugin}/{controller}/{id}/relations/{name}/records", 201, "cabana.RecordEnvelope", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodPost, fmt.Sprintf("/acme/conform/gadgets/%d/relations/parts/records", e.gadgetID), map[string]any{"label": "part-" + e.stamp}, true) e.partID = dataID(t, rec.Body.Bytes()) return rec }, into[cabana.RecordEnvelope](), nil}, {"GET /{vendor}/{plugin}/{controller}/{id}/relations/{name}/records/{child}", 200, "cabana.RecordEnvelope", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, fmt.Sprintf("/acme/conform/gadgets/%d/relations/parts/records/%d", e.gadgetID, e.partID), nil, true) }, into[cabana.RecordEnvelope](), nil}, {"POST /{vendor}/{plugin}/{controller}/{id}/relations/{name}/records/{child}/files/{field}", 201, "cabana.Envelope-cabana_FileItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.childUpload(t, e.gadgetID, e.partID, "images", "part.png", conformPNG(t), e.childKey) e.partFileID = dataID(t, rec.Body.Bytes()) return rec }, into[cabana.Envelope[cabana.FileItem]](), nil}, {"GET /{vendor}/{plugin}/{controller}/{id}/relations/{name}/records/{child}/files/{field}", 200, "cabana.Envelope-array_cabana_FileItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.sendWith(t, http.MethodGet, e.childFilePath(""), nil, "", map[string]string{cabana.ChildSessionKeyHeader: e.childKey}) var body cabana.Envelope[[]cabana.FileItem] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || len(body.Data) != 1 || !body.Data[0].Pending || body.Data[0].URL != "" { t.Fatalf("pending child file list = %s (%v)", rec.Body.String(), err) } return rec }, into[cabana.Envelope[[]cabana.FileItem]](), nil}, {"POST /{vendor}/{plugin}/{controller}/{id}/relations/{name}/records/{child}/files/{field}/reorder", 200, "cabana.Envelope-array_cabana_FileItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { body, _ := json.Marshal(map[string]any{"ids": []uint{e.partFileID}}) return e.sendWith(t, http.MethodPost, e.childFilePath("/reorder"), body, "application/json", map[string]string{cabana.ChildSessionKeyHeader: e.childKey}) }, into[cabana.Envelope[[]cabana.FileItem]](), nil}, {"PUT /{vendor}/{plugin}/{controller}/{id}/relations/{name}/records/{child}/files/{field}/{file}", 200, "cabana.Envelope-cabana_FileItem", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { body, _ := json.Marshal(map[string]any{"title": "Part " + e.stamp}) return e.sendWith(t, http.MethodPut, e.childFilePath(fmt.Sprintf("/%d", e.partFileID)), body, "application/json", map[string]string{cabana.ChildSessionKeyHeader: e.childKey}) }, into[cabana.Envelope[cabana.FileItem]](), nil}, {"GET /{vendor}/{plugin}/{controller}/{id}/relations/{name}/records/{child}/files/{field}/{file}/download", 200, "", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.sendWith(t, http.MethodGet, e.childFilePath(fmt.Sprintf("/%d/download", e.partFileID)), nil, "", map[string]string{cabana.ChildSessionKeyHeader: e.childKey}) }, nil, binaryFile("image/png")}, {"GET /{vendor}/{plugin}/{controller}/{id}/relations/{name}/records/{child}/files/{field}/{file}/thumb", 200, "", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.sendWith(t, http.MethodGet, e.childFilePath(fmt.Sprintf("/%d/thumb", e.partFileID)), nil, "", map[string]string{cabana.ChildSessionKeyHeader: e.childKey}) }, nil, binaryFile("image/png")}, {"DELETE /{vendor}/{plugin}/{controller}/{id}/relations/{name}/records/{child}/files/{field}/{file}", 200, "cabana.Envelope-cabana_FileMutationResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.sendWith(t, http.MethodDelete, e.childFilePath(fmt.Sprintf("/%d", e.partFileID)), nil, "", map[string]string{cabana.ChildSessionKeyHeader: e.childKey}) }, into[cabana.Envelope[cabana.FileMutationResult]](), nil}, {"PUT /{vendor}/{plugin}/{controller}/{id}/relations/{name}/records/{child}", 200, "cabana.RecordEnvelope", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPut, fmt.Sprintf("/acme/conform/gadgets/%d/relations/parts/records/%d", e.gadgetID, e.partID), map[string]any{"label": "part-" + e.stamp + "-renamed"}, true) }, into[cabana.RecordEnvelope](), nil}, {"POST /{vendor}/{plugin}/{controller}/{id}/relations/{name}/delete", 200, "cabana.Envelope-cabana_BulkResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, fmt.Sprintf("/acme/conform/gadgets/%d/relations/parts/delete", e.gadgetID), map[string]any{"ids": []uint{e.partID}}, true) }, into[cabana.Envelope[cabana.BulkResult]](), nil}, {"POST /{vendor}/{plugin}/{controller}/toolbar/{action}", 200, "cabana.Envelope-cabana_AdminActionResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/acme/conform/gadgets/toolbar/recount", map[string]any{}, true) }, into[cabana.Envelope[cabana.AdminActionResult]](), nil}, {"POST /{vendor}/{plugin}/{controller}/bulk-delete", 200, "cabana.Envelope-cabana_BulkResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { spare := e.send(t, http.MethodPost, "/acme/conform/gadgets", map[string]any{"name": "spare-" + e.stamp}, true) return e.send(t, http.MethodPost, "/acme/conform/gadgets/bulk-delete", map[string]any{"ids": []uint{dataID(t, spare.Body.Bytes())}}, true) }, into[cabana.Envelope[cabana.BulkResult]](), nil}, {"POST /{vendor}/{plugin}/{controller}/{id}/actions/{action}", 200, "cabana.Envelope-cabana_AdminActionResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { shown := e.send(t, http.MethodGet, fmt.Sprintf("/acme/conform/gadgets/%d", e.gadgetID), nil, true) if !strings.Contains(shown.Body.String(), `"actions":[{"name":"ping","label":"Ping"}]`) { t.Fatalf("show does not offer the record action: %s", shown.Body.String()) } rec := e.send(t, http.MethodPost, fmt.Sprintf("/acme/conform/gadgets/%d/actions/ping", e.gadgetID), map[string]any{}, true) var body cabana.Envelope[cabana.AdminActionResult] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Data.Message != "Pinged" || body.Data.Fill == nil || len(body.Data.Fill) != 0 { t.Fatalf("record action body = %s (%v)", rec.Body.String(), err) } return rec }, into[cabana.Envelope[cabana.AdminActionResult]](), nil}, {"POST /{vendor}/{plugin}/{controller}/bulk/{action}", 200, "cabana.Envelope-cabana_BulkActionResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodPost, "/acme/conform/gadgets/bulk/touch", map[string]any{"ids": []uint{e.gadgetID}}, true) var body cabana.Envelope[cabana.BulkActionResult] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Data.Affected != 1 || body.Data.Message != "Touched" { t.Fatalf("bulk action body = %s (%v)", rec.Body.String(), err) } return rec }, into[cabana.Envelope[cabana.BulkActionResult]](), nil}, {"DELETE /{vendor}/{plugin}/{controller}/{id}", 200, "cabana.Envelope-cabana_BulkResult", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodDelete, fmt.Sprintf("/acme/conform/gadgets/%d", e.gadgetID), nil, true) }, into[cabana.Envelope[cabana.BulkResult]](), nil}, {"PUT /account", 200, "cabana.Envelope-cabana_AdminProfile", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { // No password: a password change would end the token the later // cases still use. rec := e.send(t, http.MethodPut, "/account", map[string]any{"first_name": "Conform", "last_name": "Admin", "email": e.login + "@example.test", "subtitle": "Conformance"}, true) var body cabana.Envelope[cabana.AdminProfile] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Data.FirstName != "Conform" || body.Data.Subtitle != "Conformance" { t.Fatalf("account body = %s (%v)", rec.Body.String(), err) } return rec }, into[cabana.Envelope[cabana.AdminProfile]](), nil}, {"PUT /account/preferences", 200, "cabana.Envelope-cabana_AdminPreferences", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodPut, "/account/preferences", map[string]any{"theme": "dark"}, true) var body cabana.Envelope[cabana.AdminPreferences] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Data.Theme != "dark" { t.Fatalf("preferences body = %s (%v)", rec.Body.String(), err) } return rec }, into[cabana.Envelope[cabana.AdminPreferences]](), nil}, {"GET /account/preferences", 200, "cabana.Envelope-cabana_AdminPreferences", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/account/preferences", nil, true) }, into[cabana.Envelope[cabana.AdminPreferences]](), nil}, {"POST /account/avatar", 200, "cabana.Envelope-cabana_AdminProfile", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { var buf bytes.Buffer mw := multipart.NewWriter(&buf) part, err := mw.CreateFormFile("file_data", "avatar.png") if err != nil { t.Fatal(err) } if _, err := part.Write(conformPNG(t)); err != nil { t.Fatal(err) } if err := mw.Close(); err != nil { t.Fatal(err) } rec := e.sendWith(t, http.MethodPost, "/account/avatar", buf.Bytes(), mw.FormDataContentType(), nil) var body cabana.Envelope[cabana.AdminProfile] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Data.Avatar == nil || body.Data.Avatar.URL == "" { t.Fatalf("avatar upload body = %s (%v)", rec.Body.String(), err) } return rec }, into[cabana.Envelope[cabana.AdminProfile]](), nil}, {"DELETE /account/avatar", 200, "cabana.Envelope-cabana_AdminProfile", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.sendWith(t, http.MethodDelete, "/account/avatar", nil, "", nil) var body cabana.Envelope[cabana.AdminProfile] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Data.Avatar != nil { t.Fatalf("avatar remove body = %s (%v)", rec.Body.String(), err) } return rec }, into[cabana.Envelope[cabana.AdminProfile]](), nil}, {"POST /account/tokens", 201, "cabana.Envelope-cabana_AdminAPITokenCreated", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { rec := e.send(t, http.MethodPost, "/account/tokens", map[string]any{"name": "conform", "expires": "90d", "scopes": []string{"*"}}, true) var body cabana.Envelope[cabana.AdminAPITokenCreated] if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Data.Token == "" || body.Data.ID == 0 { t.Fatalf("token create body = %s (%v)", rec.Body.String(), err) } e.tokenID = body.Data.ID return rec }, into[cabana.Envelope[cabana.AdminAPITokenCreated]](), nil}, {"GET /account/tokens", 200, "cabana.Envelope-array_cabana_AdminAPIToken", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/account/tokens", nil, true) }, into[cabana.Envelope[[]cabana.AdminAPIToken]](), nil}, {"GET /account/tokens/scopes", 200, "cabana.Envelope-array_cabana_AdminAPITokenScope", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/account/tokens/scopes", nil, true) }, into[cabana.Envelope[[]cabana.AdminAPITokenScope]](), nil}, {"DELETE /account/tokens/{id}", 200, "cabana.Envelope-cabana_AdminAPIToken", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { if e.tokenID == 0 { t.Fatal("token id missing from create case") } return e.send(t, http.MethodDelete, fmt.Sprintf("/account/tokens/%d", e.tokenID), nil, true) }, into[cabana.Envelope[cabana.AdminAPIToken]](), nil}, {"GET /account/contributions", 200, "cabana.Envelope-array_cabana_AccountContributionView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/account/contributions", nil, true) }, into[cabana.Envelope[[]cabana.AccountContributionView]](), nil}, {"POST /account/contributions/{name}/actions/{action}", 200, "cabana.Envelope-cabana_AccountActionResultView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/account/contributions/conform_link/actions/open", nil, true) }, into[cabana.Envelope[cabana.AccountActionResultView]](), nil}, {"POST /account/contribution-items/{name}/{item}/actions/{action}", 200, "cabana.Envelope-cabana_AccountActionResultView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/account/contribution-items/conform_link/conform-item/actions/forget", nil, true) }, into[cabana.Envelope[cabana.AccountActionResultView]](), nil}, {"GET /mcp/consent/{request}", 200, "cabana.Envelope-cabana_MCPConsentView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodGet, "/mcp/consent/conform-request", nil, true) }, into[cabana.Envelope[cabana.MCPConsentView]](), nil}, {"POST /mcp/consent/{request}", 200, "cabana.Envelope-cabana_MCPConsentDecisionView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/mcp/consent/conform-request", map[string]any{"decision": "allow", "scopes": []string{"admin:read"}, "offline_access": true}, true) }, into[cabana.Envelope[cabana.MCPConsentDecisionView]](), nil}, {"POST /auth/logout", 200, "cabana.Envelope-cabana_AdminLogoutData", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder { return e.send(t, http.MethodPost, "/auth/logout", nil, true) }, into[cabana.Envelope[cabana.AdminLogoutData]](), nil}, } } type conformSpecDoc struct { Paths map[string]map[string]struct { Responses map[string]struct { Content map[string]struct { Schema struct { Ref string `json:"$ref"` Type string `json:"type"` Format string `json:"format"` } `json:"schema"` } `json:"content"` } `json:"responses"` } `json:"paths"` } func (d conformSpecDoc) binary(path, method, status string) bool { schema := d.Paths[path][method].Responses[status].Content["application/octet-stream"].Schema return schema.Type == "string" && schema.Format == "binary" } func (d conformSpecDoc) ref(path, method, status string) string { ref := d.Paths[path][method].Responses[status].Content["application/json"].Schema.Ref return strings.TrimPrefix(ref, "#/components/schemas/") } func conformSpec(t *testing.T) conformSpecDoc { t.Helper() _, file, _, ok := runtime.Caller(0) if !ok { t.Fatal("caller") } raw, err := os.ReadFile(filepath.Join(filepath.Dir(file), "..", "..", "admin", "openapi", "admin.json")) if err != nil { t.Fatal(err) } var doc conformSpecDoc if err := json.Unmarshal(raw, &doc); err != nil { t.Fatal(err) } return doc } type conformEnv struct { h http.Handler db *gorm.DB bucket *blob.Bucket login string token string stamp string sessionKey string photoID uint manualID uint groupID uint memberID uint gadgetID uint partID uint partFileID uint childKey string tokenID uint mailImageID uint mediaFolderID uint mediaItemID uint } // sendWith sends a raw body with extra headers through the assembled router. func (e *conformEnv) sendWith(t *testing.T, method, rel string, body []byte, contentType string, headers map[string]string) *httptest.ResponseRecorder { t.Helper() req := httptest.NewRequest(method, adminAPI(rel), bytes.NewReader(body)) if contentType != "" { req.Header.Set("Content-Type", contentType) } req.Header.Set("Authorization", "Bearer "+e.token) for k, v := range headers { req.Header.Set(k, v) } rec := httptest.NewRecorder() e.h.ServeHTTP(rec, req) return rec } // upload posts one multipart file_data part to a gadget's file field. func (e *conformEnv) upload(t *testing.T, id uint, field, name string, data []byte, key string) *httptest.ResponseRecorder { t.Helper() var buf bytes.Buffer mw := multipart.NewWriter(&buf) part, err := mw.CreateFormFile("file_data", name) if err != nil { t.Fatal(err) } if _, err := part.Write(data); err != nil { t.Fatal(err) } if err := mw.Close(); err != nil { t.Fatal(err) } headers := map[string]string{} if key != "" { headers[cabana.SessionKeyHeader] = key } return e.sendWith(t, http.MethodPost, fmt.Sprintf("/acme/conform/gadgets/%d/files/%s", id, field), buf.Bytes(), mw.FormDataContentType(), headers) } // childFilePath is the conformance part's file route under the gadget's // parts relation, with rest appended. func (e *conformEnv) childFilePath(rest string) string { return fmt.Sprintf("/acme/conform/gadgets/%d/relations/parts/records/%d/files/images%s", e.gadgetID, e.partID, rest) } // childUpload posts one multipart file_data part to a part's file field // under a gadget's parts relation (child 0 is the part being created). func (e *conformEnv) childUpload(t *testing.T, gadget, part uint, field, name string, data []byte, childKey string, extra ...string) *httptest.ResponseRecorder { t.Helper() var buf bytes.Buffer mw := multipart.NewWriter(&buf) w, err := mw.CreateFormFile("file_data", name) if err != nil { t.Fatal(err) } if _, err := w.Write(data); err != nil { t.Fatal(err) } if err := mw.Close(); err != nil { t.Fatal(err) } headers := map[string]string{cabana.ChildSessionKeyHeader: childKey} if len(extra) > 0 { headers[cabana.SessionKeyHeader] = extra[0] } return e.sendWith(t, http.MethodPost, fmt.Sprintf("/acme/conform/gadgets/%d/relations/parts/records/%d/files/%s", gadget, part, field), buf.Bytes(), mw.FormDataContentType(), headers) } // conformPNG is a small valid PNG. func conformPNG(t *testing.T) []byte { t.Helper() img := image.NewRGBA(image.Rect(0, 0, 4, 3)) for x := 0; x < 4; x++ { img.Set(x, 1, color.RGBA{R: 200, A: 255}) } var buf bytes.Buffer if err := png.Encode(&buf, img); err != nil { t.Fatal(err) } return buf.Bytes() } // newSessionKey is a random form session key as the SPA makes one. func newSessionKey(t *testing.T) string { t.Helper() raw := make([]byte, 32) if _, err := rand.Read(raw); err != nil { t.Fatal(err) } return base64.RawURLEncoding.EncodeToString(raw) } func (e *conformEnv) send(t *testing.T, method, rel string, body any, auth bool) *httptest.ResponseRecorder { t.Helper() var payload []byte if body != nil { raw, err := json.Marshal(body) if err != nil { t.Fatal(err) } payload = raw } req := httptest.NewRequest(method, adminAPI(rel), bytes.NewReader(payload)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept-Language", "pl") if auth { req.Header.Set("Authorization", "Bearer "+e.token) } rec := httptest.NewRecorder() e.h.ServeHTTP(rec, req) if method == http.MethodPost && rel == "/auth/login" && rec.Code == http.StatusOK { e.token = accessToken(t, rec.Body.Bytes()) } return rec } // assertPluginAsset fetches a schema asset URL through the assembled router // and checks the D-16 headers; an undeclared file under the same directory // must fall through to the SPA's 404. func (e *conformEnv) assertPluginAsset(t *testing.T, url, contentType string) { t.Helper() path, version, ok := strings.Cut(url, "?v=") if !ok || !strings.HasPrefix(path, cabana.DefaultAdminPrefix+"/assets/acme/conform/") || len(version) != 12 { t.Fatalf("asset url %q", url) } rec := httptest.NewRecorder() e.h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, url, nil)) h := rec.Header() if rec.Code != http.StatusOK || h.Get("Content-Type") != contentType || h.Get("X-Content-Type-Options") != "nosniff" || h.Get("Cross-Origin-Resource-Policy") != "same-origin" || h.Get("Cache-Control") != "no-cache" || !strings.HasPrefix(h.Get("ETag"), `"`+version) || !strings.Contains(h.Get("Content-Security-Policy"), "script-src 'self'") { t.Fatalf("asset %s status=%d headers=%v", url, rec.Code, h) } miss := httptest.NewRecorder() e.h.ServeHTTP(miss, httptest.NewRequest(http.MethodGet, cabana.DefaultAdminPrefix+"/assets/acme/conform/../controllers/gadgets/config_list.yaml", nil)) if miss.Code == http.StatusOK && strings.Contains(miss.Body.String(), "modelClass") { t.Fatalf("plugin YAML leaked through the asset route") } undeclared := httptest.NewRecorder() e.h.ServeHTTP(undeclared, httptest.NewRequest(http.MethodGet, cabana.DefaultAdminPrefix+"/assets/acme/conform/js/other.js", nil)) if undeclared.Code != http.StatusNotFound { t.Fatalf("undeclared asset status=%d", undeclared.Code) } } func dataID(t *testing.T, raw []byte) uint { t.Helper() var body struct { Data struct { ID uint `json:"id"` } `json:"data"` } if err := json.Unmarshal(raw, &body); err != nil || body.Data.ID == 0 { t.Fatalf("no data.id in %s: %v", raw, err) } return body.Data.ID } func newConformEnv(t *testing.T) *conformEnv { t.Helper() gdb := adminGorm(t) models := []any{&conformGadget{}, &conformGroup{}, &conformMember{}, &conformGadgetMember{}, &conformPart{}, &conformSettings{}} if err := gdb.Migrator().DropTable(models...); err != nil { t.Fatal(err) } if err := gdb.AutoMigrate(models...); err != nil { t.Fatal(err) } resetCompanions(t, gdb) // Gadget ids restart with the recreated table: drop the files and // bindings an earlier run left for them. if err := gdb.Exec(`DELETE FROM system_files WHERE attachment_type IN ('acme.conform.gadget', 'acme.conform.part') OR attachment_id IS NULL OR attachment_id = ''`).Error; err != nil { t.Fatal(err) } if err := gdb.Exec(`DELETE FROM deferred_bindings WHERE master_type IN ('acme.conform.gadget', 'acme.conform.part')`).Error; err != nil { t.Fatal(err) } stamp := fmt.Sprintf("c%d", time.Now().UnixNano()) group := conformGroup{Title: "Group " + stamp} member := conformMember{Email: "member-" + stamp + "@example.test"} if err := gdb.Create(&group).Error; err != nil { t.Fatal(err) } if err := gdb.Create(&member).Error; err != nil { t.Fatal(err) } login := "conform-" + stamp insertAdmin(t, gdb, login, login+"@example.test", adminTestPassword, true, false) // The Plugins screen needs backend.view_plugins, which no role holds. // Mail image routes need either mail permission (conform is not a superuser). if err := gdb.Exec(`UPDATE backend_users SET permissions = ? WHERE login = ?`, `{"backend.view_plugins":1,"system.manage_mail_templates":1,"system.manage_mail_layouts":1}`, login).Error; err != nil { t.Fatal(err) } dir := t.TempDir() if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: cabana-conform\nlocale: en\nfallback_locale: en\n"), 0o644); err != nil { t.Fatal(err) } cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{"SUMMER_ENV=development", "SUMMER_ADMIN__JWT__SECRET=" + adminTestSecret}}) if err != nil { t.Fatal(err) } // plugins.registry_url "" keeps GET /plugins from calling a registry. for key, value := range map[string]any{ "http.body_limits.default_bytes": 1048576, "http.body_limits.upload_bytes": 8388608, "plugins.registry_url": "", "app.url": "https://conform.example.test", } { if err := cfg.Set(key, value); err != nil { t.Fatal(err) } } app := backpack.New(cfg) if err := lagoon.Publish(app, adminSQL, gdb); err != nil { t.Fatal(err) } if err := gdb.AutoMigrate(&cabana.MailImageLibrary{}); err != nil { t.Fatal(err) } bucket := memblob.OpenBucket(nil) t.Cleanup(func() { _ = bucket.Close() }) if err := attach.Publish(app, bucket); err != nil { t.Fatal(err) } mailer := postcard.NewMailer(nil, postcard.NewMemoryDriver(), postcard.Options{ From: "noreply@example.test", Overrides: postcard.NewDBSource(app), }) if err := app.Publish[postcard.Mailer](mailer); err != nil { t.Fatal(err) } // The MCP consent routes serve a fake administrator-only consent provider. if err := app.Publish[pact.MCPAdminConsent](conformConsent{}); err != nil { t.Fatal(err) } // The acme.companions fixture serves the Phase 17 routes (dependent // options) next to the gadgets. plugins := []party.Plugin{conformPlugin{stamp: stamp}, companionsPlugin{app: app}} if err := phrasebook.Activate(app, plugins); err != nil { t.Fatal(err) } if err := signpost.Activate(app, plugins); err != nil { t.Fatal(err) } h, err := surf.Assemble(app, plugins) if err != nil { t.Fatal(err) } return &conformEnv{h: h, db: gdb, bucket: bucket, login: login, stamp: stamp, sessionKey: newSessionKey(t), childKey: newSessionKey(t), groupID: group.ID, memberID: member.ID} } type conformGadget struct { ID uint `gorm:"column:id;primaryKey"` Name string `gorm:"column:name"` Active bool `gorm:"column:active"` GroupID *uint `gorm:"column:group_id"` // ReleasedOn and StartsAt are the date and datetime datepicker columns. ReleasedOn lagoon.Date `gorm:"column:released_on;type:date"` StartsAt *time.Time `gorm:"column:starts_at"` // Note is the plugin-typed field (conformNoteType). Note *string `gorm:"column:note"` Members []conformMember `gorm:"-"` Parts []conformPart `gorm:"-"` CreatedAt time.Time `gorm:"column:created_at"` UpdatedAt time.Time `gorm:"column:updated_at"` } func (conformGadget) TableName() string { return "cabana_conform_gadgets" } func (conformGadget) MorphName() string { return "acme.conform.gadget" } func (conformGadget) AttachRelations() []attach.Relation { return []attach.Relation{{Name: "photos", Many: true, Public: true}, {Name: "manual"}} } func (conformGadget) Fillable() []string { return []string{"name", "active", "released_on", "starts_at", "note"} } func (conformGadget) Rules() map[string]string { return map[string]string{"name": "required"} } func (conformGadget) FilterScopes() []string { return []string{"filterByGroup"} } func (conformGadget) FilterScope(_ string, db *gorm.DB, value any) *gorm.DB { return db.Where("group_id = ?", value) } func (conformGadget) FilterOptions(string) []pact.Option { return []pact.Option{{Value: "1", Label: "backend::lang.form.none"}, {Value: "2", Label: "Second"}} } type conformGroup struct { ID uint `gorm:"column:id;primaryKey"` Title string `gorm:"column:title"` } func (conformGroup) TableName() string { return "cabana_conform_groups" } type conformMember struct { ID uint `gorm:"column:id;primaryKey"` Email string `gorm:"column:email"` } func (conformMember) TableName() string { return "cabana_conform_members" } type conformGadgetMember struct { ID uint `gorm:"column:id;primaryKey"` GadgetID uint `gorm:"column:gadget_id"` MemberID uint `gorm:"column:member_id"` Note string `gorm:"column:note"` // Stamp is a hook column RelationBeforeLink writes. Stamp string `gorm:"column:stamp"` } func (conformGadgetMember) TableName() string { return "cabana_conform_gadget_members" } // conformPart is the hasMany child of a gadget; its nullable gadget_id makes // the parts relation deferrable. type conformPart struct { ID uint `gorm:"column:id;primaryKey"` GadgetID *uint `gorm:"column:gadget_id"` Label string `gorm:"column:label"` CreatedAt time.Time `gorm:"column:created_at"` UpdatedAt time.Time `gorm:"column:updated_at"` } func (conformPart) TableName() string { return "cabana_conform_parts" } func (conformPart) MorphName() string { return "acme.conform.part" } func (conformPart) Fillable() []string { return []string{"label"} } func (conformPart) Rules() map[string]string { return map[string]string{"label": "required"} } // AttachRelations declares the part form's protected attachMany images. func (conformPart) AttachRelations() []attach.Relation { return []attach.Relation{{Name: "images", Many: true}} } type conformSettings struct { ID uint `gorm:"column:id;primaryKey"` Enabled bool `gorm:"column:enabled"` APIKey lagoon.Encrypted `gorm:"column:api_key;type:text"` } func (conformSettings) TableName() string { return "cabana_conform_settings" } func (conformSettings) Fillable() []string { return []string{"enabled", "api_key"} } func (conformSettings) Rules() map[string]string { return map[string]string{} } // conformConsent is the fake pact.MCPAdminConsent of the conformance // suite: one pending request asking for admin:read and offline access. type conformConsent struct{} func (conformConsent) MCPAdminConsentShow(_ context.Context, _ uint, requestID string) (pact.MCPAdminConsentRequest, error) { if requestID != "conform-request" { return pact.MCPAdminConsentRequest{}, pact.ErrMCPConsentNotFound } return pact.MCPAdminConsentRequest{ RequestID: requestID, ClientID: "oas_conform", ClientName: "Conform agent", RedirectURI: "https://agent.example.test/callback", Scopes: []string{"admin:read"}, OfflineAccess: true, ConsentRequired: true, ExpiresAt: time.Now().Add(10 * time.Minute), }, nil } func (conformConsent) MCPAdminConsentDecide(_ context.Context, _ uint, requestID string, decision pact.MCPAdminConsentDecision) (string, error) { if requestID != "conform-request" { return "", pact.ErrMCPConsentNotFound } if len(decision.Scopes) == 0 && decision.Allow { return "", pact.ErrMCPConsentNoScopes } return "https://agent.example.test/callback?code=conform", nil } type conformPlugin struct{ stamp string } func (conformPlugin) ID() string { return "acme.conform" } func (conformPlugin) Requires() []string { return nil } func (conformPlugin) Register(*backpack.App) error { return nil } func (conformPlugin) Boot(*backpack.App) error { return nil } func (p conformPlugin) AdminControllers() []pact.AdminController { return []pact.AdminController{conformController{stamp: p.stamp}} } // Models lists the models deferred:purge may delete; the parts relation // creates parts under deferral, so cabana's boot requires conformPart here. func (conformPlugin) Models() []any { return []any{&conformGadget{}, &conformPart{}} } // AccountContributions is the My account section the conformance cases of // GET /account/contributions and its action route exercise. func (conformPlugin) AccountContributions() []pact.AccountContribution { return []pact.AccountContribution{{ Name: "conform_link", Label: "Conformance link", Description: "A section the conformance suite contributes.", Status: func(context.Context, uint) (string, error) { return "linked", nil }, Actions: []pact.AccountAction{{ Name: "open", Label: "Open", Run: func(_ context.Context, in pact.AccountActionInput) (pact.AccountActionResult, error) { return pact.AccountActionResult{Message: "Opened", URL: "https://conform.example.test/link"}, nil }, }}, Items: func(context.Context, uint) ([]pact.AccountItem, error) { return []pact.AccountItem{{ID: "conform-item", Title: "Conform item", Subtitle: "A row", Meta: []string{"2026-11-21"}}}, nil }, ItemActions: []pact.AccountItemAction{{ Name: "forget", Label: "Forget", Confirm: "Forget :title?", Danger: true, Run: func(context.Context, pact.AccountItemActionInput) (pact.AccountActionResult, error) { return pact.AccountActionResult{Message: "Forgotten"}, nil }, }}, ItemsEmpty: "No rows.", }} } func (conformPlugin) Permissions() []pact.Permission { return []pact.Permission{{Code: "acme.conform.access", Roles: []string{"developer"}}} } func (conformPlugin) Navigation() []pact.NavigationItem { return []pact.NavigationItem{{Code: "conform", Label: "Conform", Icon: "box", Order: 10, Controller: "acme.conform.gadgets", Permissions: []string{"acme.conform.access"}, SideMenu: []pact.NavigationItem{{Code: "gadgets", Label: "Gadgets", Icon: "box", Controller: "acme.conform.gadgets", Permissions: []string{"acme.conform.access"}}}}} } func (conformPlugin) Settings() []pact.SettingsItem { return []pact.SettingsItem{{Code: "conform", Label: "Conform", Description: "Conform settings", Category: "Acme", Icon: "settings", Model: "ConformSettings", Order: 10, Permissions: []string{"acme.conform.access"}, Form: "models/settings/fields.yaml", NewModel: func() any { return &conformSettings{} }}} } func (conformPlugin) AdminFS() fs.FS { return conformFS() } const ( // conformNoteType is the fixture plugin's field type alias. conformNoteType = "conformnote" // conformNoteElement is its custom element, under the acme-conform- prefix. conformNoteElement = "acme-conform-note" ) // FormFieldTypes registers one plugin field type, so GET /field-types lists // it and the gadget form's note field can upload: Decode trims the value, // Load prefixes "loaded:", Upload answers a URL naming the bytes it read. func (conformPlugin) FormFieldTypes() []pact.FormFieldType { return []pact.FormFieldType{{ Name: conformNoteType, Element: conformNoteElement, Scripts: []string{"assets/js/lookup.js"}, Decode: func(_ context.Context, in pact.FormFieldValue) (pact.FormFieldDecoded, error) { text, ok := in.Value.(string) if !ok { return pact.FormFieldDecoded{Value: in.Value}, nil } return pact.FormFieldDecoded{Value: strings.TrimSpace(text)}, nil }, Load: func(_ context.Context, in pact.FormFieldValue) (any, error) { switch v := in.Value.(type) { case string: return "loaded:" + v, nil case *string: if v != nil { return "loaded:" + *v, nil } } return in.Value, nil }, Upload: func(_ context.Context, in pact.FormFieldUpload) (pact.FormFieldUploadResult, error) { body, err := io.ReadAll(in.Body) if err != nil { return pact.FormFieldUploadResult{}, err } record := "nil" if in.Record != nil { record = "set" } return pact.FormFieldUploadResult{URL: fmt.Sprintf("/media/conform/%s?bytes=%d&record=%s", in.Filename, len(body), record)}, nil }, }} } var _ pact.HasFormFieldTypes = conformPlugin{} type conformController struct{ stamp string } func (conformController) ID() string { return "acme.conform.gadgets" } func (conformController) ModelName() string { return "Gadget" } func (conformController) ConfigDir() string { return "controllers/gadgets" } func (conformController) RequiredPermissions() []string { return []string{"acme.conform.access"} } func (conformController) NewRecord() any { return &conformGadget{} } func (conformController) AdminRelationContracts() []cabana.RelationContract { return []cabana.RelationContract{{ Name: "members", NewRelated: func() any { return &conformMember{} }, NewPivot: func() any { return &conformGadgetMember{} }, ParentForeignKey: "gadget_id", RelatedForeignKey: "member_id", Columns: map[string]string{"email": "email"}, HookPivotColumns: []string{"stamp"}, // A gadget named exclude-{{ .Data.Name }}
`), "controllers/gadgets/config_filter.yaml": file(`scopes: grouped: label: Group modelClass: Group nameFrom: title scope: filterByGroup active: label: Active type: switch column: active `), "controllers/gadgets/config_form.yaml": file(`name: New gadget form: ~/plugins/acme/conform/models/gadget/fields.yaml modelClass: Gadget defaultRedirect: acme/conform/gadgets create: redirect: acme/conform/gadgets/update/:id redirectClose: acme/conform/gadgets update: redirect: acme/conform/gadgets redirectClose: acme/conform/gadgets recordActions: [ping] preview: {} `), "controllers/gadgets/config_relation.yaml": file(`members: label: Members view: list: columns: email: label: Email toolbarButtons: link|unlink showSearch: true manage: list: columns: email: label: Email showSearch: true pivot: form: models/member/pivot_fields.yaml parts: label: Parts view: list: columns: label: label: Label toolbarButtons: create|update|delete|link|unlink manage: form: $/acme/conform/models/part/fields.yaml list: columns: label: label: Label `), "models/gadget/columns.yaml": file(`columns: name: label: Name searchable: true active: label: Active type: switch released_on: label: Released on type: date `), "models/gadget/fields.yaml": file(`fields: name: label: Name type: text required: true span: left active: label: Active type: switch default: false group: label: Group type: relation nameFrom: title emptyOption: backend::lang.form.none members: type: relation-manager relation: members parts: type: relation-manager relation: parts lookup: label: Lookup type: widget widget: acme-conform-lookup action: lookup fill: [name] summary: label: Summary type: partial path: summary photos: label: Photos type: fileupload mode: image maxFiles: 5 maxFilesize: 0.5 thumbOptions: mode: crop released_on: label: Released on type: datepicker mode: date minDate: 2000-01-01 firstDay: 1 starts_at: label: Starts at type: datepicker format: d.m.Y H:i yearRange: [2000, 2040] manual: label: Manual type: fileupload fileTypes: [pdf, png, svg, txt] useCaption: true context: update note: label: Note type: conformnote `), "models/member/pivot_fields.yaml": file(`fields: pivot[note]: label: Note type: text `), "models/part/fields.yaml": file(`fields: label: label: Label type: text required: true images: label: Images type: fileupload mode: image useCaption: true `), "models/settings/fields.yaml": file(`fields: enabled: label: Enabled type: switch default: 0 api_key: label: API key type: password `), } }