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
This commit is contained in:
139
modules/cabana/account_preferences_internal_test.go
Normal file
139
modules/cabana/account_preferences_internal_test.go
Normal file
@@ -0,0 +1,139 @@
|
||||
package cabana
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
)
|
||||
|
||||
// preferencesTranslator has admin strings in en and pl, and a non-admin key
|
||||
// in de, so Locales(adminLangPrefix) is en and pl.
|
||||
func preferencesTranslator(t *testing.T) *phrasebook.Translator {
|
||||
t.Helper()
|
||||
cat := phrasebook.NewCatalog()
|
||||
if err := cat.Load("backend", fstest.MapFS{
|
||||
"lang/en/lang.yaml": {Data: []byte("nav:\n settings: Settings\n")},
|
||||
"lang/pl/lang.yaml": {Data: []byte("nav:\n settings: Ustawienia\n")},
|
||||
"lang/de/other.yaml": {Data: []byte("nav: Navigation\n")},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return phrasebook.NewTranslator(cat, phrasebook.Options{Locale: "en", Fallback: "en"})
|
||||
}
|
||||
|
||||
func TestPreferencesOf(t *testing.T) {
|
||||
tr := preferencesTranslator(t)
|
||||
cases := []struct {
|
||||
name string
|
||||
metadata *string
|
||||
want AdminPreferences
|
||||
}{
|
||||
{"null metadata", nil, AdminPreferences{Theme: "system"}},
|
||||
{"empty array", strPtr("[]"), AdminPreferences{Theme: "system"}},
|
||||
{"malformed", strPtr("{not json"), AdminPreferences{Theme: "system"}},
|
||||
{"not an object", strPtr(`"text"`), AdminPreferences{Theme: "system"}},
|
||||
{"stored values", strPtr(`{"admin_theme":"dark","admin_locale":"pl"}`), AdminPreferences{Theme: "dark", Locale: "pl"}},
|
||||
{"light", strPtr(`{"admin_theme":"light"}`), AdminPreferences{Theme: "light"}},
|
||||
{"invalid theme", strPtr(`{"admin_theme":"blue"}`), AdminPreferences{Theme: "system"}},
|
||||
{"non-string theme", strPtr(`{"admin_theme":1}`), AdminPreferences{Theme: "system"}},
|
||||
{"unsupported locale", strPtr(`{"admin_locale":"de"}`), AdminPreferences{Theme: "system"}},
|
||||
{"unknown locale", strPtr(`{"admin_locale":"xx"}`), AdminPreferences{Theme: "system"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := preferencesOf(BackendUser{Metadata: tc.metadata}, tr); got != tc.want {
|
||||
t.Errorf("%s: preferencesOf = %+v, want %+v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
// Without a translator no locale is supported.
|
||||
if got := preferencesOf(BackendUser{Metadata: strPtr(`{"admin_locale":"pl"}`)}, nil); got.Locale != "" {
|
||||
t.Errorf("nil translator locale = %q", got.Locale)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidPreferences(t *testing.T) {
|
||||
tr := preferencesTranslator(t)
|
||||
ctx := context.Background()
|
||||
updates, details := validPreferences(ctx, tr, map[string]any{"theme": "dark", "locale": "pl"})
|
||||
if len(details) != 0 || updates[metadataAdminTheme] != "dark" || updates[metadataAdminLocale] != "pl" {
|
||||
t.Fatalf("valid: updates=%v details=%v", updates, details)
|
||||
}
|
||||
updates, details = validPreferences(ctx, tr, map[string]any{"theme": "system", "locale": ""})
|
||||
if len(details) != 0 || len(updates) != 2 || updates[metadataAdminTheme] != "" || updates[metadataAdminLocale] != "" {
|
||||
t.Fatalf("defaults: updates=%v details=%v", updates, details)
|
||||
}
|
||||
updates, details = validPreferences(ctx, tr, map[string]any{})
|
||||
if len(details) != 0 || len(updates) != 0 {
|
||||
t.Fatalf("empty body: updates=%v details=%v", updates, details)
|
||||
}
|
||||
for name, body := range map[string]map[string]any{
|
||||
"theme blue": {"theme": "blue"},
|
||||
"theme number": {"theme": json.Number("1")},
|
||||
"theme null": {"theme": nil},
|
||||
"locale xx": {"locale": "xx"},
|
||||
"locale de": {"locale": "de"},
|
||||
"locale number": {"locale": json.Number("1")},
|
||||
"locale bool": {"locale": true},
|
||||
} {
|
||||
_, details := validPreferences(ctx, tr, body)
|
||||
for key := range body {
|
||||
if _, ok := details[key]; !ok {
|
||||
t.Errorf("%s: no detail on %s (%v)", name, key, details)
|
||||
}
|
||||
}
|
||||
}
|
||||
if details := refusedPreferenceKeys(ctx, tr, map[string]any{"theme": "dark", "id": 1, "backend_user_id": 2, "is_superuser": true}); len(details) != 3 || details["theme"] != nil {
|
||||
t.Fatalf("refused keys = %v", details)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreferenceMetadataWrites(t *testing.T) {
|
||||
stored := strPtr(`{"subtitle":"Rear admiral","winter_key":{"a":1}}`)
|
||||
out, err := setMetadataString(stored, metadataAdminTheme, "dark")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err = setMetadataString(out, metadataAdminLocale, "pl")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var values map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(*out), &values); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(values["subtitle"]) != `"Rear admiral"` || string(values["winter_key"]) != `{"a":1}` || string(values["admin_theme"]) != `"dark"` || string(values["admin_locale"]) != `"pl"` {
|
||||
t.Fatalf("metadata = %s", *out)
|
||||
}
|
||||
|
||||
// The defaults remove their keys; metadata without keys is NULL.
|
||||
out, err = setMetadataString(strPtr(`{"admin_theme":"dark","admin_locale":"pl"}`), metadataAdminTheme, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err = setMetadataString(out, metadataAdminLocale, "")
|
||||
if err != nil || out != nil {
|
||||
t.Fatalf("cleared metadata = %v, %v; want nil", out, err)
|
||||
}
|
||||
|
||||
// Metadata that is not a JSON object is refused, never overwritten.
|
||||
if _, err := setMetadataString(strPtr(`"legacy text"`), metadataAdminTheme, "dark"); err != errMetadataNotObject {
|
||||
t.Fatalf("non-object metadata err = %v", err)
|
||||
}
|
||||
|
||||
if !sameMetadata(nil, nil) || sameMetadata(nil, strPtr("{}")) || !sameMetadata(strPtr("{}"), strPtr("{}")) {
|
||||
t.Fatal("sameMetadata")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrincipalFromPreferredLocale(t *testing.T) {
|
||||
if p := principalFrom(BackendUser{ID: 1, Metadata: strPtr(`{"admin_locale":"pl","subtitle":"x"}`)}); p.PreferredLocale != "pl" {
|
||||
t.Fatalf("PreferredLocale = %q, want pl", p.PreferredLocale)
|
||||
}
|
||||
for _, metadata := range []*string{nil, strPtr(`{"subtitle":"x"}`), strPtr("[]"), strPtr("{bad")} {
|
||||
if p := principalFrom(BackendUser{ID: 1, Metadata: metadata}); p.PreferredLocale != "" {
|
||||
t.Fatalf("PreferredLocale = %q for %v, want empty", p.PreferredLocale, metadata)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -170,3 +170,167 @@ func TestAdminLocalePreference(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -343,3 +343,31 @@ func TestCatalogBoundaries(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestTranslatorLocales(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fsys := fstest.MapFS{
|
||||
"lang/pl/lang.yaml": {Data: []byte("greeting: Cześć\n")},
|
||||
"lang/en/lang.yaml": {Data: []byte("greeting: Hello\n")},
|
||||
"lang/de/other.yaml": {Data: []byte("greeting: Hallo\n")},
|
||||
}
|
||||
cat := NewCatalog()
|
||||
if err := cat.Load("acme.blog", fsys); err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
tr := NewTranslator(cat, Options{})
|
||||
if got := tr.Locales("acme.blog::lang."); strings.Join(got, ",") != "en,pl" {
|
||||
t.Fatalf("Locales(lang) = %v, want [en pl]", got)
|
||||
}
|
||||
if got := tr.Locales("acme.blog::"); strings.Join(got, ",") != "de,en,pl" {
|
||||
t.Fatalf("Locales(namespace) = %v, want [de en pl]", got)
|
||||
}
|
||||
if got := tr.Locales("acme.shop::"); len(got) != 0 {
|
||||
t.Fatalf("Locales(unknown) = %v, want none", got)
|
||||
}
|
||||
var nilTr *Translator
|
||||
if got := nilTr.Locales("acme.blog::"); got != nil {
|
||||
t.Fatalf("nil translator Locales = %v, want nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user