Files
Docwell/Server/internal/httpapi/auth_test.go
T
tajniak81andClaude Opus 5.5 0640004895
CI / go (Server) (push) Failing after 4m38s
CI / go (Web-App) (push) Successful in 12m18s
Docs / build (push) Canceled after 0s
Docs / deploy (push) Canceled after 0s
CI / frontend (push) Failing after 7m49s
CI / desktop (ubuntu-latest) (push) Successful in 1h25m30s
CI / mobile (push) Failing after 5m14s
CI / docker (push) Successful in 39m26s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Add database relations and rollups, full-page records, and translate the admin panel and phone app
Databases (ADR-13 follow-ups):
- Relation properties link records to another database, on the same page
  or on any page the reader can open (read live and read-only, like synced
  pages). Cells list the linked titles; clicking one opens the record.
- Rollup properties work out counts, sums, averages, medians, min/max,
  ranges, earliest/latest dates and checked counts over related records.
  Neither is stored: views compute them before drawing (linked.ts), so they
  follow both databases live, and rollups sort and filter as numbers.
- Exports (Markdown, HTML, PDF, Word) resolve them for same-page databases.
- A record opens as a full page at /p/<page>/r/<database>/<record>, with
  "Open as full page" on the side panel and "Back to the page".

Edgeless mode (ADR-14 follow-ups):
- History previews show a version's canvas and count canvas changes.
- Comments can be anchored to canvas elements (anchor {element}); elements
  with open threads show a badge that opens the thread.
- Workspaces choose how new pages open (workspaces.default_page_mode); the
  per-device choice now defaults to following the workspace.
- Phones edit the canvas once a page is opened for editing; the page note
  shows the page title.

Languages:
- The admin panel speaks English, Polish, German, French and Spanish, with
  a picker sharing the web app's setting and a key parity test.
- The phone app speaks the same five, follows the phone's language (and
  Android's per-app language setting), and has its own parity test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 17:11:47 +01:00

191 lines
6.3 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package httpapi
import (
"context"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/auth"
"docwell/server/internal/directory"
)
// fakeAuth implements the AuthService calls these tests reach; the embedded
// nil interface panics on anything else.
type fakeAuth struct {
AuthService
}
var (
alice = auth.User{ID: "u1", Email: "alice@docwell.test", Name: "Alice", Status: "active", Role: "user", Organization: "acme"}
admin = auth.User{ID: "u2", Email: "root@docwell.test", Name: "Root", Status: "active", Role: "admin", Organization: "acme"}
)
func (fakeAuth) Verify(_ context.Context, token string) (auth.User, error) {
switch token {
case "alice":
return alice, nil
case "admin":
return admin, nil
case "disabled":
return auth.User{}, auth.ErrAccountDisabled
}
return auth.User{}, auth.ErrUnauthorized
}
func (fakeAuth) Login(_ context.Context, email, password, mfaID string) (auth.Session, error) {
switch {
case email == "mfa@docwell.test" && mfaID == "":
return auth.Session{}, &auth.MFARequiredError{MFAID: "m1"}
case email == alice.Email && password == "password123":
return auth.Session{Token: "alice", User: alice}, nil
}
return auth.Session{}, auth.ErrInvalidCredentials
}
func (fakeAuth) Signup(_ context.Context, in auth.SignupInput) (auth.Session, error) {
return auth.Session{}, &auth.ValidationError{Fields: map[string]string{"password": "too short"}}
}
// fakeDir records the caller each call was made for.
type fakeDir struct {
DirectoryService
seen *access.Caller
}
func (f fakeDir) ListUsers(_ context.Context, c access.Caller, _ directory.ListUsersInput) (directory.UserList, error) {
*f.seen = c
return directory.UserList{Items: []auth.User{alice, admin}, TotalItems: 2}, nil
}
func (f fakeDir) CreateOrg(_ context.Context, c access.Caller, name string) (directory.Org, error) {
*f.seen = c
if name == "Taken" {
return directory.Org{}, apperr.Conflict("an organization with this name already exists")
}
return directory.Org{ID: "o1", Name: name}, nil
}
func (f fakeDir) DeleteOrg(context.Context, access.Caller, string) error {
return apperr.Forbidden("you can only delete your own organization")
}
func (f fakeDir) UpdateWorkspace(context.Context, access.Caller, string, directory.UpdateWorkspaceInput) (directory.Workspace, error) {
return directory.Workspace{}, apperr.NotFound("workspace not found")
}
func (f fakeDir) CreateUser(context.Context, access.Caller, directory.CreateUserInput) (auth.User, error) {
return auth.User{}, apperr.InvalidFields(map[string]string{"email": "A valid email is required."})
}
var lastCaller access.Caller
func authRouter() http.Handler {
return NewRouter(Deps{
Version: "test",
DB: fakeDB{},
Auth: fakeAuth{},
Directory: fakeDir{seen: &lastCaller},
Log: authRouterLog(),
})
}
func authRouterLog() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
func send(h http.Handler, method, path, token, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func TestLoginResponses(t *testing.T) {
h := authRouter()
cases := []struct {
body string
wantStatus int
wantBody string
}{
{`{"email":"alice@docwell.test","password":"password123"}`, 200, `"token":"alice"`},
{`{"email":"alice@docwell.test","password":"nope"}`, 401, `"invalid_credentials"`},
{`{"email":"mfa@docwell.test","password":"x"}`, 401, `"mfaId":"m1"`},
{`not json`, 400, `"invalid_json"`},
}
for _, c := range cases {
rec := send(h, "POST", "/api/v1/auth/login", "", c.body)
if rec.Code != c.wantStatus || !strings.Contains(rec.Body.String(), c.wantBody) {
t.Errorf("login %s = %d %s", c.body, rec.Code, rec.Body)
}
}
}
func TestSignupValidationError(t *testing.T) {
rec := send(authRouter(), "POST", "/api/v1/auth/signup", "", `{"email":"a@b.c","password":"x","name":"A"}`)
if rec.Code != 400 || !strings.Contains(rec.Body.String(), `"fields":{"password":"too short"}`) {
t.Errorf("signup = %d %s", rec.Code, rec.Body)
}
}
func TestMeRequiresValidToken(t *testing.T) {
h := authRouter()
if rec := send(h, "GET", "/api/v1/auth/me", "", ""); rec.Code != 401 {
t.Errorf("no token = %d", rec.Code)
}
if rec := send(h, "GET", "/api/v1/auth/me", "disabled", ""); rec.Code != 403 {
t.Errorf("disabled = %d", rec.Code)
}
rec := send(h, "GET", "/api/v1/auth/me", "alice", "")
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"email":"alice@docwell.test"`) {
t.Errorf("me = %d %s", rec.Code, rec.Body)
}
}
func TestUsersRequiresManager(t *testing.T) {
h := authRouter()
if rec := send(h, "GET", "/api/v1/users", "", ""); rec.Code != 401 {
t.Errorf("anonymous = %d", rec.Code)
}
if rec := send(h, "GET", "/api/v1/users", "alice", ""); rec.Code != 403 {
t.Errorf("plain user = %d", rec.Code)
}
rec := send(h, "GET", "/api/v1/users?perPage=5000", "admin", "")
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"totalItems":2`) {
t.Errorf("admin = %d %s", rec.Code, rec.Body)
}
if lastCaller != (access.Caller{ID: "u2", Role: "admin", OrgID: "acme"}) {
t.Errorf("caller passed to directory = %+v", lastCaller)
}
}
func TestDirectoryErrorMapping(t *testing.T) {
h := authRouter()
cases := []struct {
method, path, token, body string
status int
want string
}{
{"POST", "/api/v1/orgs", "alice", `{"name":"Acme"}`, 201, `"name":"Acme"`},
{"POST", "/api/v1/orgs", "alice", `{"name":"Taken"}`, 409, `"error":"conflict"`},
{"POST", "/api/v1/orgs", "", `{"name":"Acme"}`, 401, `"unauthorized"`},
{"DELETE", "/api/v1/orgs/o2", "admin", ``, 403, `"message":"you can only delete your own organization"`},
{"PATCH", "/api/v1/workspaces/w1", "alice", `{"name":"X"}`, 404, `"error":"not_found"`},
{"POST", "/api/v1/users", "admin", `{}`, 400, `"fields":{"email":"A valid email is required."}`},
}
for _, c := range cases {
rec := send(h, c.method, c.path, c.token, c.body)
if rec.Code != c.status || !strings.Contains(rec.Body.String(), c.want) {
t.Errorf("%s %s = %d %s", c.method, c.path, rec.Code, rec.Body)
}
}
}