Files
summercms/modules/cabana/backend_screens_smoke_test.go
Jakub Zych 7340241f22 feat(19.6.1-01): Administrators screen and cross-controller record actions
- pact.HasAdminActionExtensions / AdminActionExtension: plugins add record
  actions to any admin controller by ID, merged at boot before permission
  validation (unknown target, no preview, duplicate name stop the boot)
- internal summercms.cabana pseudo-plugin, appended only when some plugin
  registers admin controllers: Administrators list and preview, settings
  link under System, backend.manage_users and backend.manage_roles with no
  role grants
- backend::lang user, user.role and permissions copy (en, pl)
- smoke tests: compile-time seam and settings, Postgres list/preview/action
2026-10-22 10:59:23 +02:00

261 lines
8.8 KiB
Go

package cabana_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"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/pact"
"git.golem15.com/golem15/summercms/modules/party"
"git.golem15.com/golem15/summercms/modules/phrasebook"
"git.golem15.com/golem15/summercms/modules/surf"
"gorm.io/gorm"
)
// pingSpy records the runs of the contributed acme_ping record action.
type pingSpy struct {
mu sync.Mutex
ids []uint64
withTx []bool
}
func (s *pingSpy) record(id uint64, tx bool) {
s.mu.Lock()
defer s.mu.Unlock()
s.ids = append(s.ids, id)
s.withTx = append(s.withTx, tx)
}
func (s *pingSpy) runs() ([]uint64, []bool) {
s.mu.Lock()
defer s.mu.Unlock()
return append([]uint64(nil), s.ids...), append([]bool(nil), s.withTx...)
}
// pingPlugin owns no admin controller; it only adds the acme_ping record
// action to the Administrators screen (pact.HasAdminActionExtensions).
type pingPlugin struct{ spy *pingSpy }
func (pingPlugin) ID() string { return "acme.pinger" }
func (pingPlugin) Requires() []string { return nil }
func (pingPlugin) Register(*backpack.App) error { return nil }
func (pingPlugin) Boot(*backpack.App) error { return nil }
func (pingPlugin) Permissions() []pact.Permission {
return []pact.Permission{{Code: "acme.pinger.ping"}}
}
func (p pingPlugin) AdminActionExtensions() []pact.AdminActionExtension {
return []pact.AdminActionExtension{{
Controller: cabana.AdministratorsControllerID,
RecordActions: []pact.AdminRecordAction{{
Name: "acme_ping", Label: "Ping", Permissions: []string{"acme.pinger.ping"},
Run: func(ctx context.Context, in pact.AdminRecordActionInput) (pact.AdminRecordActionResult, error) {
_, ok := cabana.TxFromContext(ctx)
if _, isUser := in.Record.(*cabana.BackendUser); !isUser {
return pact.AdminRecordActionResult{}, errors.New("acme_ping: record is not a backend user")
}
p.spy.record(in.RecordID, ok)
return pact.AdminRecordActionResult{Message: "Pinged"}, nil
},
}},
}}
}
// screensEnv is one assembled admin with the demo plugin, the pinger and the
// admin's own screens, on the shared Postgres.
type screensEnv struct {
h http.Handler
gdb *gorm.DB
stamp string
spy *pingSpy
}
func newScreensEnv(t *testing.T) *screensEnv {
t.Helper()
gdb := adminGorm(t)
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: cabana-screens\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)
}
for key, value := range map[string]any{"http.body_limits.default_bytes": 1048576, "http.body_limits.upload_bytes": 1048576, "admin.password.bcrypt_cost": 4} {
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)
}
spy := &pingSpy{}
plugins := []party.Plugin{demoPlugin{fsys: demoFS()}, pingPlugin{spy: spy}}
if err := phrasebook.Activate(app, plugins); err != nil {
t.Fatal(err)
}
h, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatal(err)
}
return &screensEnv{h: h, gdb: gdb, stamp: fmt.Sprintf("s%d", time.Now().UnixNano()), spy: spy}
}
// admin creates an activated administrator named name+stamp with the
// developer role (or a role holding rolePermissions JSON when it is not
// empty), optionally a superuser, signs it in and returns it with its token.
func (e *screensEnv) admin(t *testing.T, name string, superuser bool, rolePermissions string) (cabana.BackendUser, string) {
t.Helper()
login := name + "-" + e.stamp
user := insertAdmin(t, e.gdb, login, login+"@example.test", adminTestPassword, true, false)
if superuser {
if err := e.gdb.Exec(`UPDATE backend_users SET is_superuser = TRUE WHERE id = ?`, user.ID).Error; err != nil {
t.Fatal(err)
}
user.IsSuperuser = true
}
if rolePermissions != "" {
var roleID uint
if err := e.gdb.Raw(`INSERT INTO backend_user_roles (name, code, permissions, is_system, created_at, updated_at)
VALUES (?, ?, ?, FALSE, NOW(), NOW()) RETURNING id`, "Role "+login, "role-"+login, rolePermissions).Scan(&roleID).Error; err != nil || roleID == 0 {
t.Fatalf("role: id=%d err=%v", roleID, err)
}
if err := e.gdb.Exec(`UPDATE backend_users SET role_id = ? WHERE id = ?`, roleID, user.ID).Error; err != nil {
t.Fatal(err)
}
user.RoleID = &roleID
}
rec := postJSON(t, e.h, adminAPI("/auth/login"), map[string]string{"login": login, "password": adminTestPassword})
if rec.Code != http.StatusOK {
t.Fatalf("login %s status=%d body=%s", login, rec.Code, rec.Body.String())
}
return user, accessToken(t, rec.Body.Bytes())
}
// call runs one admin API request with a Bearer token.
func (e *screensEnv) call(t *testing.T, method, rel, token string, body any) *httptest.ResponseRecorder {
t.Helper()
var reader *bytes.Reader
if body != nil {
raw, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
reader = bytes.NewReader(raw)
} else {
reader = bytes.NewReader(nil)
}
req := httptest.NewRequest(method, adminAPI(rel), reader)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Accept-Language", "en")
req.Header.Set("Authorization", "Bearer "+token)
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
return rec
}
func (e *screensEnv) expect(t *testing.T, status int, method, rel, token string, body any) map[string]any {
t.Helper()
rec := e.call(t, method, rel, token, body)
if rec.Code != status {
t.Fatalf("%s %s status=%d want %d body=%s", method, rel, rec.Code, status, rec.Body.String())
}
var out map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("%s %s body %s: %v", method, rel, rec.Body.String(), err)
}
return out
}
// listIDs returns the ids of a list response's rows.
func listIDs(t *testing.T, body map[string]any) map[uint]bool {
t.Helper()
rows, _ := body["data"].([]any)
out := map[uint]bool{}
for _, row := range rows {
fields, _ := row.(map[string]any)
if id, ok := fields["id"].(float64); ok {
out[uint(id)] = true
}
}
return out
}
// recordActionNames returns the names of a show response's meta.actions.
func recordActionNames(body map[string]any) []string {
meta, _ := body["meta"].(map[string]any)
actions, _ := meta["actions"].([]any)
out := []string{}
for _, action := range actions {
if entry, ok := action.(map[string]any); ok {
name, _ := entry["name"].(string)
out = append(out, name)
}
}
return out
}
const usersPath = "/summercms/cabana/users"
func TestBackendScreensPostgresSmoke(t *testing.T) {
env := newScreensEnv(t)
root, rootToken := env.admin(t, "screens-root", true, "")
dev, devToken := env.admin(t, "screens-dev", false, "")
list := env.expect(t, http.StatusOK, http.MethodGet, usersPath+"?search="+env.stamp, rootToken, nil)
ids := listIDs(t, list)
if !ids[root.ID] || !ids[dev.ID] {
t.Fatalf("superuser list ids = %v, want %d and %d", ids, root.ID, dev.ID)
}
show := env.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("%s/%d", usersPath, dev.ID), rootToken, nil)
if names := recordActionNames(show); len(names) == 0 || names[len(names)-1] != "acme_ping" {
t.Fatalf("meta.actions = %v, want acme_ping last", names)
}
result := env.expect(t, http.StatusOK, http.MethodPost, fmt.Sprintf("%s/%d/actions/acme_ping", usersPath, dev.ID), rootToken, map[string]any{})
if data, _ := result["data"].(map[string]any); data["message"] != "Pinged" {
t.Fatalf("action result = %v", result)
}
runs, withTx := env.spy.runs()
if len(runs) != 1 || runs[0] != uint64(dev.ID) || !withTx[0] {
t.Fatalf("acme_ping runs = %v tx = %v", runs, withTx)
}
settings := env.expect(t, http.StatusOK, http.MethodGet, "/settings", rootToken, nil)
found := false
entries, _ := settings["data"].([]any)
for _, entry := range entries {
item, _ := entry.(map[string]any)
if item["code"] == "administrators" {
found = item["controller"] == cabana.AdministratorsControllerID && item["category"] == "System" && item["label"] == "Administrators"
}
}
if !found {
t.Fatalf("superuser settings = %v", entries)
}
if rec := env.call(t, http.MethodGet, usersPath, devToken, nil); rec.Code != http.StatusForbidden {
t.Fatalf("developer list status=%d body=%s", rec.Code, rec.Body.String())
}
settings = env.expect(t, http.StatusOK, http.MethodGet, "/settings", devToken, nil)
if strings.Contains(fmt.Sprint(settings["data"]), "administrators") {
t.Fatalf("developer settings list administrators: %v", settings["data"])
}
}