CI / go (Media) (push) Successful in 17m6s
CI / go (Server) (push) Failing after 14m0s
CI / go (Web-App) (push) Successful in 10m3s
CI / frontend (push) Failing after 9m40s
CI / desktop (ubuntu-latest) (push) Successful in 52m25s
CI / mobile (push) Failing after 5m0s
CI / docker (push) Failing after 14m55s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
The two-step sign-in check reads the user with docwell-server's own PocketBase superuser. When those credentials were wrong, PocketBase's 401/403 was mapped to "unauthorized", so a correct password showed "Your session has expired" and nothing was logged. totpRecord and ResetTOTP now pass superuser failures through (logged, answered 500); a missing user on reset is "not found". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
414 lines
14 KiB
Go
414 lines
14 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package auth
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"docwell/server/internal/authmail"
|
|
"docwell/server/internal/i18n"
|
|
"docwell/server/internal/store/pocketbase"
|
|
)
|
|
|
|
// fakePB is a tiny in-memory stand-in for the PocketBase endpoints auth uses.
|
|
type fakePB struct {
|
|
mu sync.Mutex
|
|
users map[string]map[string]any // email -> record
|
|
passwords map[string]string
|
|
verifyCalls atomic.Int32
|
|
mfaFor string // email that requires MFA
|
|
// rejectSuperuser makes superuser reads of a user fail as PocketBase does
|
|
// when docwell-server's own credentials are wrong.
|
|
rejectSuperuser bool
|
|
// resetSubject is the users collection's reset subject now; sentWith
|
|
// collects it at each password-reset request.
|
|
resetSubject string
|
|
sentWith []string
|
|
}
|
|
|
|
func newFakePB(t *testing.T) (*fakePB, *pocketbase.Client) {
|
|
t.Helper()
|
|
f := &fakePB{users: map[string]map[string]any{}, passwords: map[string]string{}}
|
|
mux := http.NewServeMux()
|
|
reply := func(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
json.NewEncoder(w).Encode(v)
|
|
}
|
|
decode := func(r *http.Request) map[string]any {
|
|
var m map[string]any
|
|
json.NewDecoder(r.Body).Decode(&m)
|
|
return m
|
|
}
|
|
|
|
mux.HandleFunc("POST /api/collections/_superusers/auth-with-password", func(w http.ResponseWriter, r *http.Request) {
|
|
reply(w, 200, map[string]string{"token": "su"})
|
|
})
|
|
mux.HandleFunc("GET /api/collections/users/records", func(w http.ResponseWriter, r *http.Request) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
items := []map[string]any{}
|
|
for _, u := range f.users {
|
|
items = append(items, u)
|
|
}
|
|
reply(w, 200, map[string]any{"page": 1, "perPage": 30, "totalItems": len(items), "items": items})
|
|
})
|
|
mux.HandleFunc("POST /api/collections/users/records", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Header.Get("Authorization") != "su" {
|
|
reply(w, 403, map[string]any{"status": 403, "message": "Only superusers"})
|
|
return
|
|
}
|
|
body := decode(r)
|
|
email := body["email"].(string)
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
if _, ok := f.users[email]; ok {
|
|
reply(w, 400, map[string]any{"status": 400, "message": "fail", "data": map[string]any{"email": map[string]string{"code": "validation_not_unique", "message": "Value must be unique."}}})
|
|
return
|
|
}
|
|
rec := map[string]any{"id": "u" + email, "email": email, "name": body["name"], "status": body["status"], "role": body["role"]}
|
|
f.users[email] = rec
|
|
f.passwords[email] = body["password"].(string)
|
|
reply(w, 200, rec)
|
|
})
|
|
// By id, as the two-step check and its updates use them.
|
|
byID := func(id string) map[string]any {
|
|
for _, u := range f.users {
|
|
if u["id"] == id {
|
|
return u
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
mux.HandleFunc("GET /api/collections/organizations/records/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
reply(w, 200, map[string]any{"id": r.PathValue("id"), "name": "Org " + r.PathValue("id")})
|
|
})
|
|
mux.HandleFunc("GET /api/collections/users/records/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
if f.rejectSuperuser {
|
|
reply(w, 403, map[string]any{"status": 403, "message": "Only superusers can perform this action."})
|
|
return
|
|
}
|
|
if u := byID(r.PathValue("id")); u != nil {
|
|
reply(w, 200, u)
|
|
return
|
|
}
|
|
reply(w, 404, map[string]any{"status": 404, "message": "not found"})
|
|
})
|
|
mux.HandleFunc("PATCH /api/collections/users/records/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
body := decode(r)
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
u := byID(r.PathValue("id"))
|
|
if u == nil {
|
|
reply(w, 404, map[string]any{"status": 404, "message": "not found"})
|
|
return
|
|
}
|
|
for k, v := range body {
|
|
u[k] = v
|
|
}
|
|
reply(w, 200, u)
|
|
})
|
|
mux.HandleFunc("POST /api/collections/users/auth-with-password", func(w http.ResponseWriter, r *http.Request) {
|
|
body := decode(r)
|
|
email := body["identity"].(string)
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
rec, ok := f.users[email]
|
|
if !ok || f.passwords[email] != body["password"] {
|
|
reply(w, 400, map[string]any{"status": 400, "message": "Failed to authenticate.", "data": map[string]any{}})
|
|
return
|
|
}
|
|
if rec["status"] == "disabled" {
|
|
reply(w, 403, map[string]any{"status": 403, "message": "The request doesn't satisfy the collection requirements to authenticate."})
|
|
return
|
|
}
|
|
if email == f.mfaFor && body["mfaId"] == nil {
|
|
reply(w, 401, map[string]any{"mfaId": "mfa123"})
|
|
return
|
|
}
|
|
reply(w, 200, map[string]any{"token": "tok:" + email, "record": rec})
|
|
})
|
|
mux.HandleFunc("POST /api/collections/users/auth-refresh", func(w http.ResponseWriter, r *http.Request) {
|
|
f.verifyCalls.Add(1)
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
for email, rec := range f.users {
|
|
if r.Header.Get("Authorization") == "tok:"+email {
|
|
// No expand: organizations is superuser-only, so PocketBase would
|
|
// not expand it for the user's own token.
|
|
reply(w, 200, map[string]any{"token": "tok:" + email, "record": rec})
|
|
return
|
|
}
|
|
}
|
|
reply(w, 401, map[string]any{"status": 401, "message": "The request requires valid record authorization token."})
|
|
})
|
|
mux.HandleFunc("POST /api/collections/users/request-verification", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(204)
|
|
})
|
|
mux.HandleFunc("PATCH /api/collections/users", func(w http.ResponseWriter, r *http.Request) {
|
|
var body struct {
|
|
Reset struct {
|
|
Subject string `json:"subject"`
|
|
} `json:"resetPasswordTemplate"`
|
|
}
|
|
json.NewDecoder(r.Body).Decode(&body)
|
|
f.mu.Lock()
|
|
f.resetSubject = body.Reset.Subject
|
|
f.mu.Unlock()
|
|
reply(w, 200, map[string]any{})
|
|
})
|
|
mux.HandleFunc("POST /api/collections/users/request-password-reset", func(w http.ResponseWriter, r *http.Request) {
|
|
f.mu.Lock()
|
|
f.sentWith = append(f.sentWith, f.resetSubject)
|
|
f.mu.Unlock()
|
|
w.WriteHeader(204)
|
|
})
|
|
mux.HandleFunc("POST /api/collections/users/confirm-password-reset", func(w http.ResponseWriter, r *http.Request) {
|
|
reply(w, 400, map[string]any{"status": 400, "message": "fail", "data": map[string]any{"token": map[string]string{"code": "validation_invalid_token", "message": "Invalid or expired token."}}})
|
|
})
|
|
|
|
srv := httptest.NewServer(mux)
|
|
t.Cleanup(srv.Close)
|
|
return f, pocketbase.New(srv.URL, "su@docwell.test", "x")
|
|
}
|
|
|
|
var ctx = context.Background()
|
|
|
|
func TestFirstSignupBecomesSuperadminThenSignupIsClosed(t *testing.T) {
|
|
_, pb := newFakePB(t)
|
|
s := NewService(pb, Options{SignupEnabled: false})
|
|
|
|
sess, err := s.Signup(ctx, SignupInput{Email: " ann@docwell.test ", Password: "password123", Name: "Ann"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if sess.User.Role != "superadmin" || sess.Token != "tok:ann@docwell.test" {
|
|
t.Errorf("first user = %+v", sess)
|
|
}
|
|
|
|
_, err = s.Signup(ctx, SignupInput{Email: "bob@docwell.test", Password: "password123", Name: "Bob"})
|
|
if !errors.Is(err, ErrSignupDisabled) {
|
|
t.Errorf("second signup err = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestEnsureSuperadminOnlyOnEmptyInstance(t *testing.T) {
|
|
f, pb := newFakePB(t)
|
|
s := NewService(pb, Options{SignupEnabled: false})
|
|
|
|
var verr *ValidationError
|
|
if _, err := s.EnsureSuperadmin(ctx, "root@docwell.test", "short", ""); !errors.As(err, &verr) {
|
|
t.Errorf("short password err = %v", err)
|
|
}
|
|
|
|
created, err := s.EnsureSuperadmin(ctx, " root@docwell.test ", "password123", "")
|
|
if err != nil || !created {
|
|
t.Fatalf("first run = %v, %v", created, err)
|
|
}
|
|
if rec := f.users["root@docwell.test"]; rec["role"] != "superadmin" || rec["name"] != "Admin" {
|
|
t.Errorf("created = %+v", rec)
|
|
}
|
|
sess, err := s.Login(ctx, "root@docwell.test", "password123", "")
|
|
if err != nil || sess.User.Role != "superadmin" {
|
|
t.Errorf("login = %+v, %v", sess.User, err)
|
|
}
|
|
|
|
// A restart with another password changes nothing.
|
|
created, err = s.EnsureSuperadmin(ctx, "root@docwell.test", "different123", "Root")
|
|
if err != nil || created || f.passwords["root@docwell.test"] != "password123" {
|
|
t.Errorf("second run = %v, %v, password %q", created, err, f.passwords["root@docwell.test"])
|
|
}
|
|
// Nor does a different address once someone exists.
|
|
if created, err := s.EnsureSuperadmin(ctx, "other@docwell.test", "password123", ""); err != nil || created {
|
|
t.Errorf("other address = %v, %v", created, err)
|
|
}
|
|
if _, ok := f.users["other@docwell.test"]; ok {
|
|
t.Error("created a second superadmin")
|
|
}
|
|
// And the next signup is an ordinary one (closed here).
|
|
if _, err := s.Signup(ctx, SignupInput{Email: "bob@docwell.test", Password: "password123", Name: "Bob"}); !errors.Is(err, ErrSignupDisabled) {
|
|
t.Errorf("signup after bootstrap err = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestSignupDomainsAndValidation(t *testing.T) {
|
|
_, pb := newFakePB(t)
|
|
s := NewService(pb, Options{SignupEnabled: true, SignupDomains: []string{"docwell.test"}})
|
|
|
|
if _, err := s.Signup(ctx, SignupInput{Email: "ann@docwell.test", Password: "password123", Name: "Ann"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := s.Signup(ctx, SignupInput{Email: "eve@evil.test", Password: "password123", Name: "Eve"}); !errors.Is(err, ErrDomainNotAllowed) {
|
|
t.Errorf("foreign domain err = %v", err)
|
|
}
|
|
|
|
sess, err := s.Signup(ctx, SignupInput{Email: "bob@DOCWELL.test", Password: "password123", Name: "Bob"})
|
|
if err != nil || sess.User.Role != "user" || sess.User.Organization != "" {
|
|
t.Errorf("second user = %+v, %v", sess.User, err)
|
|
}
|
|
|
|
var verr *ValidationError
|
|
if _, err := s.Signup(ctx, SignupInput{Email: "c@docwell.test", Password: "short"}); !errors.As(err, &verr) || verr.Fields["password"] == "" || verr.Fields["name"] == "" {
|
|
t.Errorf("weak input err = %v", err)
|
|
}
|
|
if _, err := s.Signup(ctx, SignupInput{Email: "ann@docwell.test", Password: "password123", Name: "Ann"}); !errors.As(err, &verr) || verr.Fields["email"] == "" {
|
|
t.Errorf("duplicate email err = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestLogin(t *testing.T) {
|
|
f, pb := newFakePB(t)
|
|
s := NewService(pb, Options{SignupEnabled: true})
|
|
s.Signup(ctx, SignupInput{Email: "ann@docwell.test", Password: "password123", Name: "Ann"})
|
|
|
|
if _, err := s.Login(ctx, "ann@docwell.test", "wrong", ""); !errors.Is(err, ErrInvalidCredentials) {
|
|
t.Errorf("bad password err = %v", err)
|
|
}
|
|
|
|
f.mu.Lock()
|
|
f.users["ann@docwell.test"]["status"] = "disabled"
|
|
f.mu.Unlock()
|
|
if _, err := s.Login(ctx, "ann@docwell.test", "password123", ""); !errors.Is(err, ErrAccountDisabled) {
|
|
t.Errorf("disabled login err = %v", err)
|
|
}
|
|
f.mu.Lock()
|
|
f.users["ann@docwell.test"]["status"] = "active"
|
|
f.mu.Unlock()
|
|
|
|
f.mfaFor = "ann@docwell.test"
|
|
var mfa *MFARequiredError
|
|
if _, err := s.Login(ctx, "ann@docwell.test", "password123", ""); !errors.As(err, &mfa) || mfa.MFAID != "mfa123" {
|
|
t.Errorf("mfa err = %v", err)
|
|
}
|
|
if _, err := s.Login(ctx, "ann@docwell.test", "password123", "mfa123"); err != nil {
|
|
t.Errorf("mfa second step err = %v", err)
|
|
}
|
|
f.mfaFor = ""
|
|
|
|
// Right password, but the server's own PocketBase superuser is rejected:
|
|
// that is a server fault, not the person's expired session.
|
|
f.rejectSuperuser = true
|
|
_, err := s.Login(ctx, "ann@docwell.test", "password123", "")
|
|
var pbErr *pocketbase.Error
|
|
if err == nil || errors.Is(err, ErrUnauthorized) || !errors.As(err, &pbErr) || pbErr.Status != 403 {
|
|
t.Errorf("superuser rejected err = %v, want the PocketBase 403 passed through", err)
|
|
}
|
|
}
|
|
|
|
func TestVerifyCachesAndRejectsDisabled(t *testing.T) {
|
|
f, pb := newFakePB(t)
|
|
s := NewService(pb, Options{SignupEnabled: true, CacheTTL: time.Minute})
|
|
now := time.Now()
|
|
s.now = func() time.Time { return now }
|
|
s.Signup(ctx, SignupInput{Email: "ann@docwell.test", Password: "password123", Name: "Ann"})
|
|
|
|
for range 3 {
|
|
u, err := s.Verify(ctx, "tok:ann@docwell.test")
|
|
if err != nil || u.Email != "ann@docwell.test" {
|
|
t.Fatalf("verify = %+v, %v", u, err)
|
|
}
|
|
}
|
|
if n := f.verifyCalls.Load(); n != 1 {
|
|
t.Errorf("PocketBase verify calls = %d, want 1 (cached)", n)
|
|
}
|
|
|
|
if _, err := s.Verify(ctx, "garbage"); !errors.Is(err, ErrUnauthorized) {
|
|
t.Errorf("bad token err = %v", err)
|
|
}
|
|
|
|
f.mu.Lock()
|
|
f.users["ann@docwell.test"]["status"] = "disabled"
|
|
f.mu.Unlock()
|
|
now = now.Add(2 * time.Minute)
|
|
if _, err := s.Verify(ctx, "tok:ann@docwell.test"); !errors.Is(err, ErrAccountDisabled) {
|
|
t.Errorf("disabled err = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestConfirmPasswordResetBadToken(t *testing.T) {
|
|
_, pb := newFakePB(t)
|
|
s := NewService(pb, Options{})
|
|
if err := s.ConfirmPasswordReset(ctx, "bad", "password123"); !errors.Is(err, ErrInvalidToken) {
|
|
t.Errorf("err = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestBearerToken(t *testing.T) {
|
|
r := httptest.NewRequest("GET", "/", nil)
|
|
r.Header.Set("Authorization", "Bearer abc ")
|
|
if BearerToken(r) != "abc" {
|
|
t.Error("bearer token not parsed")
|
|
}
|
|
r.Header.Set("Authorization", "abc")
|
|
if BearerToken(r) != "" {
|
|
t.Error("non-bearer header must be ignored")
|
|
}
|
|
}
|
|
|
|
func TestForgetDropsCachedTokens(t *testing.T) {
|
|
f, pb := newFakePB(t)
|
|
s := NewService(pb, Options{SignupEnabled: true, CacheTTL: time.Hour})
|
|
sess, _ := s.Signup(ctx, SignupInput{Email: "ann@docwell.test", Password: "password123", Name: "Ann"})
|
|
|
|
s.Verify(ctx, sess.Token)
|
|
s.Verify(ctx, sess.Token)
|
|
if n := f.verifyCalls.Load(); n != 1 {
|
|
t.Fatalf("verify calls = %d, want 1", n)
|
|
}
|
|
s.Forget(sess.User.ID)
|
|
s.Verify(ctx, sess.Token)
|
|
if n := f.verifyCalls.Load(); n != 2 {
|
|
t.Errorf("after Forget verify calls = %d, want 2", n)
|
|
}
|
|
}
|
|
|
|
func TestLoginFillsOrganizationName(t *testing.T) {
|
|
f, pb := newFakePB(t)
|
|
s := NewService(pb, Options{SignupEnabled: true})
|
|
s.Signup(ctx, SignupInput{Email: "ann@docwell.test", Password: "password123", Name: "Ann"})
|
|
|
|
f.mu.Lock()
|
|
f.users["ann@docwell.test"]["organization"] = "o1"
|
|
f.mu.Unlock()
|
|
|
|
sess, err := s.Login(ctx, "ann@docwell.test", "password123", "")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if sess.User.Organization != "o1" || sess.User.OrganizationName != "Org o1" {
|
|
t.Errorf("user = %+v", sess.User)
|
|
}
|
|
}
|
|
|
|
// Password-reset emails are written in the person's stored language, else
|
|
// the request's.
|
|
func TestPasswordResetInRecipientLanguage(t *testing.T) {
|
|
f, pb := newFakePB(t)
|
|
svc := NewService(pb, Options{Mail: authmail.New(pb)})
|
|
ctx := i18n.WithLang(context.Background(), "de")
|
|
|
|
if err := svc.RequestPasswordReset(ctx, "nobody@example.com"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
f.mu.Lock()
|
|
f.users["ola@example.com"] = map[string]any{"id": "u1", "email": "ola@example.com", "locale": "pl"}
|
|
f.mu.Unlock()
|
|
if err := svc.RequestPasswordReset(ctx, "ola@example.com"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
want := []string{"Setze dein Passwort für {APP_NAME} zurück", "Zresetuj hasło do {APP_NAME}"}
|
|
if len(f.sentWith) != 2 || f.sentWith[0] != want[0] || f.sentWith[1] != want[1] {
|
|
t.Fatalf("sent with %q, want %q", f.sentWith, want)
|
|
}
|
|
}
|