// SPDX-License-Identifier: AGPL-3.0-or-later package settings import ( "context" "encoding/json" "errors" "net/http" "net/http/httptest" "sync" "testing" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/mail" "docwell/server/internal/store/pocketbase" ) // fakePB stores instance_settings records and PocketBase settings in memory. type fakePB struct { mu sync.Mutex kv map[string]json.RawMessage settings map[string]map[string]any otp bool } func newFake(t *testing.T) (*fakePB, *pocketbase.Client) { t.Helper() f := &fakePB{kv: map[string]json.RawMessage{}, settings: map[string]map[string]any{ "meta": {"appName": "Docwell", "senderName": "Docwell", "senderAddress": "no-reply@x.test"}, "smtp": {"enabled": false, "host": "", "port": 587, "username": "", "tls": false}, "s3": {"enabled": false}, }} reply := func(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(v) } mux := http.NewServeMux() mux.HandleFunc("POST /api/collections/_superusers/auth-with-password", func(w http.ResponseWriter, r *http.Request) { reply(w, map[string]string{"token": "su"}) }) mux.HandleFunc("GET /api/collections/instance_settings/records", func(w http.ResponseWriter, r *http.Request) { f.mu.Lock() defer f.mu.Unlock() items := []kvRecord{} for k, v := range f.kv { if r.URL.Query().Get("filter") == "key = '"+k+"'" { items = append(items, kvRecord{ID: "id_" + k, Key: k, Value: v}) } } reply(w, map[string]any{"items": items, "totalItems": len(items), "totalPages": 1}) }) save := func(w http.ResponseWriter, r *http.Request) { var rec kvRecord _ = json.NewDecoder(r.Body).Decode(&rec) f.mu.Lock() f.kv[rec.Key] = rec.Value f.mu.Unlock() reply(w, rec) } mux.HandleFunc("POST /api/collections/instance_settings/records", save) mux.HandleFunc("PATCH /api/collections/instance_settings/records/{id}", save) mux.HandleFunc("GET /api/collections/users", func(w http.ResponseWriter, r *http.Request) { reply(w, map[string]any{"otp": map[string]any{"enabled": f.otp}}) }) mux.HandleFunc("PATCH /api/collections/users", func(w http.ResponseWriter, r *http.Request) { var body struct{ OTP struct{ Enabled bool } } _ = json.NewDecoder(r.Body).Decode(&body) f.mu.Lock() f.otp = body.OTP.Enabled f.mu.Unlock() reply(w, map[string]any{}) }) mux.HandleFunc("GET /api/settings", func(w http.ResponseWriter, r *http.Request) { f.mu.Lock() defer f.mu.Unlock() reply(w, f.settings) }) mux.HandleFunc("PATCH /api/settings", func(w http.ResponseWriter, r *http.Request) { var patch map[string]map[string]any _ = json.NewDecoder(r.Body).Decode(&patch) f.mu.Lock() defer f.mu.Unlock() for section, values := range patch { for k, v := range values { f.settings[section][k] = v } } reply(w, f.settings) }) srv := httptest.NewServer(mux) t.Cleanup(srv.Close) return f, pocketbase.New(srv.URL, "su@x.test", "pw") } type sentMail struct{ got []mail.Message } func (s *sentMail) Send(_ context.Context, m mail.Message) error { s.got = append(s.got, m) return nil } var ( super = access.Caller{ID: "s", Role: access.RoleSuperadmin} admin = access.Caller{ID: "a", Role: access.RoleAdmin, OrgID: "o"} ) func TestSignupDefaultsUntilSaved(t *testing.T) { _, pb := newFake(t) s := New(pb, Signup{Enabled: false, Domains: []string{"env.test"}}, &sentMail{}) ctx := context.Background() got, err := s.Signup(ctx) if err != nil || got.Enabled || len(got.Domains) != 1 { t.Fatalf("defaults = %+v, %v", got, err) } _, err = s.Apply(ctx, super, Update{Signup: &Signup{Enabled: true, Domains: []string{" @Example.COM", "example.com", "b.test"}}}) if err != nil { t.Fatal(err) } got, _ = s.Signup(ctx) if !got.Enabled || len(got.Domains) != 2 || got.Domains[0] != "example.com" { t.Errorf("saved = %+v", got) } } func TestOnlySuperadmins(t *testing.T) { _, pb := newFake(t) s := New(pb, Signup{}, &sentMail{}) ctx := context.Background() for name, err := range map[string]error{ "get": func() error { _, err := s.Get(ctx, admin); return err }(), "apply": func() error { _, err := s.Apply(ctx, admin, Update{}); return err }(), "mail": s.TestEmail(ctx, admin, "x@y.test"), } { if e, ok := apperr.As(err); !ok || e.Kind != apperr.KindForbidden { t.Errorf("%s by an org admin = %v", name, err) } } } func TestBrandingAndSMTP(t *testing.T) { f, pb := newFake(t) s := New(pb, Signup{}, &sentMail{}) ctx := context.Background() _, err := s.Apply(ctx, super, Update{Branding: &Branding{AppName: "Acme", AccentColor: "red"}}) if e, ok := apperr.As(err); !ok || e.Fields["branding.accentColor"] == "" { t.Errorf("bad colour = %v", err) } pw := "secret" up := Update{Branding: &Branding{AppName: " Acme Wiki ", AccentColor: "#112233"}} up.SMTP = &struct { SMTP Password *string `json:"password"` }{SMTP: SMTP{Enabled: true, Host: "smtp.x.test", Port: 465, Username: "me", TLS: true, SenderAddress: "wiki@x.test"}, Password: &pw} got, err := s.Apply(ctx, super, up) if err != nil { t.Fatal(err) } if got.Branding.AppName != "Acme Wiki" || !got.SMTP.Enabled || got.SMTP.Port != 465 || got.SMTP.Password != "" || !got.SMTP.PasswordSet { t.Errorf("after apply = %+v", got) } if f.settings["meta"]["appName"] != "Acme Wiki" || f.settings["smtp"]["password"] != "secret" { t.Errorf("pocketbase settings = %v", f.settings) } // Leaving the password out keeps the stored one. up.SMTP.Password = nil if _, err := s.Apply(ctx, super, Update{SMTP: up.SMTP}); err != nil { t.Fatal(err) } if f.settings["smtp"]["password"] != "secret" { t.Error("password must survive an update without one") } pub, err := s.Public(ctx) if err != nil || pub.AppName != "Acme Wiki" || pub.AccentColor != "#112233" { t.Errorf("public = %+v, %v", pub, err) } } func TestMagicLink(t *testing.T) { f, pb := newFake(t) s := New(pb, Signup{}, &sentMail{}) got, err := s.Apply(context.Background(), super, Update{Auth: &Auth{MagicLink: true}}) if err != nil || !got.Auth.MagicLink || !f.otp { t.Fatalf("enable = %+v, %v (otp %v)", got.Auth, err, f.otp) } if pub, _ := s.Public(context.Background()); !pub.MagicLink { t.Error("public settings must announce magic links") } } func TestTestEmail(t *testing.T) { _, pb := newFake(t) sent := &sentMail{} s := New(pb, Signup{}, sent) if err := s.TestEmail(context.Background(), super, "nope"); err == nil { t.Error("invalid address must fail") } if err := s.TestEmail(context.Background(), super, "me@x.test"); err != nil { t.Fatal(err) } if len(sent.got) != 1 || sent.got[0].To != "me@x.test" || sent.got[0].Subject != "Docwell test email" { t.Errorf("sent = %+v", sent.got) } } func TestCleanDomains(t *testing.T) { if _, err := CleanDomains([]string{"not a domain"}); err == nil { t.Error("spaces must be rejected") } got, err := CleanDomains([]string{"", "A.b"}) if err != nil || len(got) != 1 || got[0] != "a.b" { t.Errorf("got %v, %v", got, err) } var e *apperr.Error _, err = CleanDomains([]string{"x"}) if !errors.As(err, &e) { t.Errorf("single label = %v", err) } } func TestOAuthBody(t *testing.T) { body, err := oauthBody([]OAuthProvider{ {Name: "github", ClientID: " id ", ClientSecret: "s"}, {Name: "oidc", ClientID: "kc", AuthURL: "https://sso/auth", TokenURL: "https://sso/token", UserInfoURL: "https://sso/me"}, }) if err != nil { t.Fatal(err) } list := body["providers"].([]map[string]any) if body["enabled"] != true || len(list) != 2 || list[0]["clientId"] != "id" || list[0]["clientSecret"] != "s" { t.Fatalf("body = %v", body) } if _, has := list[1]["clientSecret"]; has || list[1]["displayName"] != "Single sign-on" { t.Fatalf("oidc entry = %v", list[1]) } if body, _ := oauthBody(nil); body["enabled"] != false { t.Fatalf("empty list should turn OAuth2 off: %v", body) } for _, bad := range [][]OAuthProvider{ {{Name: "myspace", ClientID: "x"}}, {{Name: "github"}}, {{Name: "github", ClientID: "a"}, {Name: "github", ClientID: "b"}}, {{Name: "oidc", ClientID: "x", AuthURL: "sso/auth"}}, } { if _, err := oauthBody(bad); err == nil { t.Errorf("oauthBody(%v) should fail", bad) } } }