// SPDX-License-Identifier: AGPL-3.0-or-later package authmail import ( "context" "encoding/json" "net/http" "net/http/httptest" "regexp" "slices" "strings" "sync" "testing" "time" "docwell/server/internal/i18n" "docwell/server/internal/store/pocketbase" ) func TestCheck(t *testing.T) { if err := Check(); err != nil { t.Fatal(err) } } var placeholder = regexp.MustCompile(`\{[A-Z_]+\}`) // Every translation keeps the English template's placeholders and links. func TestTranslationsKeepPlaceholders(t *testing.T) { en, err := Templates(i18n.Default) if err != nil { t.Fatal(err) } pairs := func(s Set) map[string]Template { return map[string]Template{"verification": s.Verification, "reset": s.ResetPassword, "emailChange": s.ConfirmEmailChange, "otp": s.OTP, "authAlert": s.AuthAlert} } set := func(s string) []string { got := placeholder.FindAllString(s, -1) slices.Sort(got) return slices.Compact(got) } hrefs := regexp.MustCompile(`href="[^"]*"`) for _, lang := range i18n.Supported[1:] { tr, err := Templates(lang) if err != nil { t.Fatal(err) } for name, want := range pairs(en) { got := pairs(tr)[name] if !slices.Equal(set(got.Subject), set(want.Subject)) || !slices.Equal(set(got.Body), set(want.Body)) { t.Errorf("%s %s: placeholders %v / %v, want %v / %v", lang, name, set(got.Subject), set(got.Body), set(want.Subject), set(want.Body)) } if !slices.Equal(hrefs.FindAllString(got.Body, -1), hrefs.FindAllString(want.Body, -1)) { t.Errorf("%s %s: links differ from English", lang, name) } if got.Subject == want.Subject { t.Errorf("%s %s: subject not translated", lang, name) } } } } type fakePB struct { mu sync.Mutex patches []map[string]any locale map[string]string // email -> locale sending bool overlap bool } func newFake(t *testing.T) (*fakePB, *pocketbase.Client) { f := &fakePB{locale: map[string]string{}} mux := http.NewServeMux() reply := func(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(v) } 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("PATCH /api/collections/users", func(w http.ResponseWriter, r *http.Request) { var body map[string]any json.NewDecoder(r.Body).Decode(&body) f.mu.Lock() f.patches = append(f.patches, body) f.mu.Unlock() reply(w, map[string]any{}) }) mux.HandleFunc("GET /api/collections/users/records", func(w http.ResponseWriter, r *http.Request) { m := regexp.MustCompile(`email:lower = '([^']*)'`).FindStringSubmatch(r.URL.Query().Get("filter")) items := []map[string]string{} if m != nil { if l, ok := f.locale[m[1]]; ok { items = append(items, map[string]string{"locale": l}) } } reply(w, map[string]any{"page": 1, "perPage": 1, "items": items}) }) srv := httptest.NewServer(mux) t.Cleanup(srv.Close) return f, pocketbase.New(srv.URL, "su@test", "pw") } func subject(p map[string]any) string { return p["verificationTemplate"].(map[string]any)["subject"].(string) } func TestSendSwapsOnlyWhenLanguageChanges(t *testing.T) { f, pb := newFake(t) m := New(pb) ctx := context.Background() sent := 0 send := func() error { sent++; return nil } for _, lang := range []string{"pl", "pl", "de", "xx", "en"} { if err := m.Send(ctx, lang, send); err != nil { t.Fatal(err) } } if sent != 5 { t.Fatalf("sent %d, want 5", sent) } // pl, de, en (xx falls back to English); the second pl and the final en // need no write. if len(f.patches) != 3 { t.Fatalf("%d patches, want 3", len(f.patches)) } if !strings.Contains(subject(f.patches[0]), "Potwierdź") || !strings.Contains(subject(f.patches[1]), "Bestätige") || !strings.HasPrefix(subject(f.patches[2]), "Verify") { t.Errorf("subjects: %q, %q, %q", subject(f.patches[0]), subject(f.patches[1]), subject(f.patches[2])) } otp := f.patches[0]["otp"].(map[string]any) if len(otp) != 1 || otp["emailTemplate"] == nil { t.Errorf("otp patch touches more than its template: %v", otp) } } func TestSendsDoNotOverlap(t *testing.T) { f, pb := newFake(t) m := New(pb) var wg sync.WaitGroup for _, lang := range []string{"pl", "de", "fr", "es", "en", "pl", "de", "fr"} { wg.Add(1) go func() { defer wg.Done() m.Send(context.Background(), lang, func() error { f.mu.Lock() if f.sending { f.overlap = true } f.sending = true f.mu.Unlock() time.Sleep(2 * time.Millisecond) f.mu.Lock() f.sending = false f.mu.Unlock() return nil }) }() } wg.Wait() if f.overlap { t.Fatal("two sends ran at once") } } func TestLangFor(t *testing.T) { f, pb := newFake(t) f.locale["ana@example.com"] = "es" f.locale["old@example.com"] = "" m := New(pb) ctx := i18n.WithLang(context.Background(), "fr") for addr, want := range map[string]string{ "Ana@Example.com ": "es", // stored locale, any case "old@example.com": "fr", // no locale: the request's "new@example.com": "fr", // no account: the request's "x'@example.com": "fr", // never reaches a filter } { if got := m.LangFor(ctx, addr); got != want { t.Errorf("LangFor(%q) = %q, want %q", addr, got, want) } } if got := m.LangFor(context.Background(), "new@example.com"); got != i18n.Default { t.Errorf("no request language: %q", got) } }