Files
summercms/modules/cabana/account_preferences_test.go
Jakub Zych 119f1f8d54 test(quick-261016-0fm): admin preference coverage
- Translator.Locales: sorted, prefix-scoped, nil-safe
- preferencesOf, validPreferences, refused keys, metadata writes and
  principalFrom's PreferredLocale (internal, Docker-free)
- Docker: refused keys and values leave the row alone, owner-only saves,
  personal tokens get interactive_only and keep the request locale, the
  cookie CSRF header, non-object metadata stays byte-identical
2026-10-16 11:44:32 +02:00

337 lines
13 KiB
Go

package cabana_test
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"git.golem15.com/golem15/summercms/modules/cabana"
"gorm.io/gorm"
)
// putPreferences sends PUT /account/preferences with a Bearer token.
func putPreferences(t *testing.T, h http.Handler, token string, body any) *httptest.ResponseRecorder {
t.Helper()
raw, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
return postAuth(t, h, http.MethodPut, adminAPI("/account/preferences"), token, raw)
}
// preferencesOf decodes an AdminPreferences envelope.
func preferencesOf(t *testing.T, raw []byte) cabana.AdminPreferences {
t.Helper()
var body cabana.Envelope[cabana.AdminPreferences]
if err := json.Unmarshal(raw, &body); err != nil {
t.Fatalf("preferences json: %v body=%s", err, raw)
}
return body.Data
}
// preferenceAdmin inserts and signs in a fresh admin on the account harness.
func preferenceAdmin(t *testing.T, gdb *gorm.DB, h http.Handler, prefix string) (cabana.BackendUser, string) {
t.Helper()
login := prefix + "-" + accountStamp()
user := insertAdmin(t, gdb, login, login+"@example.test", adminTestPassword, true, false)
return user, signIn(t, h, login)
}
// TestAccountPreferencesSmoke saves a theme, reads it back from GET
// /auth/me and GET /account/preferences, and keeps the stored subtitle.
func TestAccountPreferencesSmoke(t *testing.T) {
gdb := adminGorm(t)
h, _ := accountHandler(t, gdb, false, 1<<20)
user, token := preferenceAdmin(t, gdb, h, "prefs-smoke")
setMetadata(t, gdb, user.ID, `{"subtitle":"Rear admiral"}`)
res := putPreferences(t, h, token, map[string]any{"theme": "dark"})
if res.Code != http.StatusOK {
t.Fatalf("put status=%d body=%s", res.Code, res.Body.String())
}
if got := preferencesOf(t, res.Body.Bytes()); got.Theme != "dark" || got.Locale != "" {
t.Fatalf("put preferences = %+v", got)
}
me := getAuth(t, h, adminAPI("/auth/me"), token)
if me.Code != http.StatusOK {
t.Fatalf("me status=%d body=%s", me.Code, me.Body.String())
}
if got := profileOf(t, me.Body.Bytes()); got.Preferences.Theme != "dark" || got.Subtitle != "Rear admiral" {
t.Fatalf("me profile = %+v", got)
}
get := getAuth(t, h, adminAPI("/account/preferences"), token)
if get.Code != http.StatusOK {
t.Fatalf("get status=%d body=%s", get.Code, get.Body.String())
}
if got := preferencesOf(t, get.Body.Bytes()); got.Theme != "dark" || got.Locale != "" {
t.Fatalf("get preferences = %+v", got)
}
var meta map[string]string
row := rawUser(t, gdb, user.ID)
if err := json.Unmarshal([]byte(row.Metadata.String), &meta); err != nil || meta["subtitle"] != "Rear admiral" || meta["admin_theme"] != "dark" {
t.Fatalf("metadata = %q (%v)", row.Metadata.String, err)
}
}
// sendLocale sends a request with a Bearer token (when set), a JSON body
// (when set) and an Accept-Language header.
func sendLocale(t *testing.T, h http.Handler, method, path, token, acceptLanguage string, body any) *httptest.ResponseRecorder {
t.Helper()
var raw []byte
if body != nil {
var err error
if raw, err = json.Marshal(body); err != nil {
t.Fatal(err)
}
}
req := httptest.NewRequest(method, path, bytes.NewReader(raw))
if raw != nil {
req.Header.Set("Content-Type", "application/json")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
req.Header.Set("Accept-Language", acceptLanguage)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
// langMeta decodes the meta object of GET /lang.
func langMeta(t *testing.T, raw []byte) cabana.LangMeta {
t.Helper()
var body cabana.LangEnvelope
if err := json.Unmarshal(raw, &body); err != nil {
t.Fatalf("lang json: %v body=%s", err, raw)
}
return body.Meta
}
// TestAdminLocalePreference: a stored admin language overrides the request
// locale of guarded admin routes; unsupported codes are refused; GET /lang
// honours only a supported ?locale= and lists meta.locales.
func TestAdminLocalePreference(t *testing.T) {
gdb := adminGorm(t)
h, _ := accountHandler(t, gdb, false, 1<<20)
_, token := preferenceAdmin(t, gdb, h, "prefs-locale")
invalidTheme := func(t *testing.T) string {
t.Helper()
rec := sendLocale(t, h, http.MethodPut, adminAPI("/account/preferences"), token, "en", map[string]any{"theme": "blue"})
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("invalid theme status=%d body=%s", rec.Code, rec.Body.String())
}
return strings.Join(validationDetails(t, rec.Body.Bytes())["theme"], " ")
}
if got := invalidTheme(t); !strings.Contains(got, "selected") {
t.Fatalf("message before the preference = %q, want English", got)
}
res := putPreferences(t, h, token, map[string]any{"locale": "pl"})
if res.Code != http.StatusOK {
t.Fatalf("put locale status=%d body=%s", res.Code, res.Body.String())
}
if got := preferencesOf(t, res.Body.Bytes()); got.Locale != "pl" || got.Theme != "system" {
t.Fatalf("put preferences = %+v", got)
}
if got := invalidTheme(t); !strings.Contains(got, "Zaznaczony") {
t.Fatalf("message with the pl preference = %q, want Polish despite Accept-Language: en", got)
}
bad := putPreferences(t, h, token, map[string]any{"locale": "xx"})
if bad.Code != http.StatusUnprocessableEntity {
t.Fatalf("locale xx status=%d body=%s", bad.Code, bad.Body.String())
}
if _, ok := validationDetails(t, bad.Body.Bytes())["locale"]; !ok {
t.Fatalf("locale xx details = %s", bad.Body.String())
}
pl := sendLocale(t, h, http.MethodGet, adminAPI("/lang?locale=pl"), "", "en", nil)
if pl.Code != http.StatusOK {
t.Fatalf("lang pl status=%d", pl.Code)
}
if meta := langMeta(t, pl.Body.Bytes()); meta.Locale != "pl" || !slices.Contains(meta.Locales, "en") || !slices.Contains(meta.Locales, "pl") {
t.Fatalf("lang pl meta = %+v", meta)
}
xx := sendLocale(t, h, http.MethodGet, adminAPI("/lang?locale=xx"), "", "en", nil)
if meta := langMeta(t, xx.Body.Bytes()); meta.Locale != "en" || strings.Contains(xx.Body.String(), "xx") {
t.Fatalf("lang xx meta = %+v", meta)
}
cleared := putPreferences(t, h, token, map[string]any{"locale": ""})
if got := preferencesOf(t, cleared.Body.Bytes()); cleared.Code != http.StatusOK || got.Locale != "" {
t.Fatalf("clear locale status=%d body=%s", cleared.Code, cleared.Body.String())
}
if got := invalidTheme(t); !strings.Contains(got, "selected") {
t.Fatalf("message after clearing = %q, want English", got)
}
}
// metaLocale decodes meta.locale of a success envelope.
func metaLocale(t *testing.T, raw []byte) string {
t.Helper()
var body struct {
Meta struct {
Locale string `json:"locale"`
} `json:"meta"`
}
if err := json.Unmarshal(raw, &body); err != nil {
t.Fatalf("meta json: %v body=%s", err, raw)
}
return body.Meta.Locale
}
// personalToken creates a personal API token with the * scope for the
// signed-in admin and returns its plaintext.
func personalToken(t *testing.T, h http.Handler, jwt string) string {
t.Helper()
rec := postAuth(t, h, http.MethodPost, adminAPI("/account/tokens"), jwt, mustJSON(t, map[string]any{
"name": "prefs", "expires": "30d", "scopes": []string{"*"},
}))
if rec.Code != http.StatusCreated {
t.Fatalf("token create status=%d body=%s", rec.Code, rec.Body.String())
}
var created struct {
Data cabana.AdminAPITokenCreated `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &created); err != nil || created.Data.Token == "" {
t.Fatalf("token json: %v body=%s", err, rec.Body.String())
}
return created.Data.Token
}
// TestAccountPreferencesAuthorization covers T-261016-0fm-01..05 and -07:
// refused keys and values, owner-only writes, personal tokens, the CSRF
// header, non-object metadata and the token locale exemption.
func TestAccountPreferencesAuthorization(t *testing.T) {
gdb := adminGorm(t)
h, _ := accountHandler(t, gdb, false, 1<<20)
owner, token := preferenceAdmin(t, gdb, h, "prefs-owner")
other, otherToken := preferenceAdmin(t, gdb, h, "prefs-other")
setMetadata(t, gdb, owner.ID, `{"subtitle":"Owner","winter_key":[1,2]}`)
before := rawUser(t, gdb, owner.ID)
t.Run("unknown keys are refused and nothing is written", func(t *testing.T) {
rec := putPreferences(t, h, token, map[string]any{"theme": "dark", "id": other.ID, "backend_user_id": other.ID, "is_superuser": true})
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
details := validationDetails(t, rec.Body.Bytes())
for _, key := range []string{"id", "backend_user_id", "is_superuser"} {
if _, ok := details[key]; !ok {
t.Errorf("no detail on %s: %v", key, details)
}
}
if _, ok := details["theme"]; ok {
t.Errorf("theme was refused: %v", details)
}
if after := rawUser(t, gdb, owner.ID); after.Metadata != before.Metadata || after.IsSuperuser {
t.Fatalf("row changed: %+v", after)
}
})
t.Run("invalid values are refused", func(t *testing.T) {
for _, body := range []map[string]any{{"theme": "blue"}, {"theme": 1}, {"locale": 7}, {"locale": "xx"}} {
rec := putPreferences(t, h, token, body)
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("%v status=%d body=%s", body, rec.Code, rec.Body.String())
}
details := validationDetails(t, rec.Body.Bytes())
for key := range body {
if _, ok := details[key]; !ok {
t.Errorf("%v: no detail on %s", body, key)
}
}
}
if after := rawUser(t, gdb, owner.ID); after.Metadata != before.Metadata {
t.Fatalf("metadata changed: %q", after.Metadata.String)
}
})
t.Run("a save is visible only to its owner and keeps other keys", func(t *testing.T) {
rec := putPreferences(t, h, token, map[string]any{"theme": "light", "locale": "pl"})
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
mine := preferencesOf(t, getAuth(t, h, adminAPI("/account/preferences"), token).Body.Bytes())
if mine.Theme != "light" || mine.Locale != "pl" {
t.Fatalf("owner preferences = %+v", mine)
}
theirs := preferencesOf(t, getAuth(t, h, adminAPI("/account/preferences"), otherToken).Body.Bytes())
if theirs.Theme != "system" || theirs.Locale != "" {
t.Fatalf("other admin preferences = %+v", theirs)
}
if row := rawUser(t, gdb, other.ID); row.Metadata.Valid {
t.Fatalf("other admin metadata = %q", row.Metadata.String)
}
var meta map[string]json.RawMessage
row := rawUser(t, gdb, owner.ID)
if err := json.Unmarshal([]byte(row.Metadata.String), &meta); err != nil || string(meta["subtitle"]) != `"Owner"` || string(meta["winter_key"]) != `[1,2]` {
t.Fatalf("owner metadata = %q (%v)", row.Metadata.String, err)
}
if !row.UpdatedAt.Equal(before.UpdatedAt) {
t.Fatalf("updated_at moved: %v -> %v", before.UpdatedAt, row.UpdatedAt)
}
})
t.Run("personal API tokens are refused", func(t *testing.T) {
plain := personalToken(t, h, token)
for _, method := range []string{http.MethodGet, http.MethodPut} {
var body []byte
if method == http.MethodPut {
body = mustJSON(t, map[string]any{"theme": "dark"})
}
rec := postAuth(t, h, method, adminAPI("/account/preferences"), plain, body)
if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "interactive_only") {
t.Fatalf("%s status=%d body=%s", method, rec.Code, rec.Body.String())
}
}
// The owner chose pl, but an API-token request keeps its own locale.
nav := sendLocale(t, h, http.MethodGet, adminAPI("/navigation"), plain, "en", nil)
if nav.Code != http.StatusOK || metaLocale(t, nav.Body.Bytes()) != "en" {
t.Fatalf("token navigation status=%d body=%s", nav.Code, nav.Body.String())
}
session := sendLocale(t, h, http.MethodGet, adminAPI("/navigation"), token, "en", nil)
if session.Code != http.StatusOK || metaLocale(t, session.Body.Bytes()) != "pl" {
t.Fatalf("session navigation status=%d body=%s", session.Code, session.Body.String())
}
})
t.Run("a cookie PUT needs X-Requested-With", func(t *testing.T) {
cookie := cookieLogin(t, h, owner.Login)
rec := cookieRequest(t, h, http.MethodPut, adminAPI("/account/preferences"), cookie, map[string]any{"theme": "dark"}, false)
if rec.Code != http.StatusForbidden {
t.Fatalf("no header status=%d body=%s", rec.Code, rec.Body.String())
}
if got := preferencesOf(t, getAuth(t, h, adminAPI("/account/preferences"), token).Body.Bytes()); got.Theme != "light" {
t.Fatalf("theme after a refused cookie PUT = %q", got.Theme)
}
ok := cookieRequest(t, h, http.MethodPut, adminAPI("/account/preferences"), cookie, map[string]any{"theme": "dark"}, true)
if ok.Code != http.StatusOK {
t.Fatalf("with header status=%d body=%s", ok.Code, ok.Body.String())
}
})
t.Run("metadata that is not an object is never overwritten", func(t *testing.T) {
const legacy = `"legacy text"`
setMetadata(t, gdb, other.ID, legacy)
rec := putPreferences(t, h, otherToken, map[string]any{"theme": "dark"})
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
if _, ok := validationDetails(t, rec.Body.Bytes())["theme"]; !ok {
t.Fatalf("details = %s", rec.Body.String())
}
if row := rawUser(t, gdb, other.ID); row.Metadata.String != legacy {
t.Fatalf("metadata = %q, want %q", row.Metadata.String, legacy)
}
if got := preferencesOf(t, getAuth(t, h, adminAPI("/account/preferences"), otherToken).Body.Bytes()); got.Theme != "system" {
t.Fatalf("preferences of non-object metadata = %+v", got)
}
})
}