Sign-in:
- Google, GitHub, Microsoft and any OpenID Connect provider, set up in the
admin panel (secrets are write-only). PocketBase talks to the provider,
and docwell-server keeps the state and PKCE verifier. Accounts a
provider creates follow the sign-up switch and the domain list; refused
ones are removed again.
- Two-step sign-in with an authenticator app (TOTP), set up under "Your
account", with ten single-use recovery codes. After any first factor
(password, email code, provider) the session is held behind a
five-minute challenge: five tries, each code works once. Turning it off
needs a code. Managers can reset it for someone who lost their phone.
Both the web app and the admin panel ask for the code.
Integrations:
- Personal API tokens ("dw_…") that act as their owner, read-only or
read-write, with optional expiry. Only a hash is stored, and the token is
shown once. Tokens cannot manage tokens or two-step sign-in. Admins see
and can revoke their organization's tokens.
- Workspace webhooks for page, comment and space events. Deliveries are
HMAC-SHA256 signed and retried (10 s, 1 min, 5 min), with a 30-day log
and a test button. Loopback and link-local addresses are refused
(DOCWELL_WEBHOOKS_ALLOW_LOCAL is for development).
Audit log: sign-ins (including failures and second steps, filed under the
account's organization) and every successful change request, by route and
path ids, never bodies. Superadmins see everything and org admins their
organization. It is searchable and exportable as CSV in the admin panel's
new Security page, and kept for DOCWELL_AUDIT_RETENTION_DAYS (365).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
315 lines
10 KiB
Go
315 lines
10 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/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
|
|
}
|
|
|
|
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/users/records/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
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("GET /api/docwell/auth/verify", 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 {
|
|
// Like the real hook, the verify route expands the organization.
|
|
out := map[string]any{}
|
|
for k, v := range rec {
|
|
out[k] = v
|
|
}
|
|
if org, _ := rec["organization"].(string); org != "" {
|
|
out["expand"] = map[string]any{"organization": map[string]any{"name": "Org " + org}}
|
|
}
|
|
reply(w, 200, out)
|
|
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("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 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)
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|