Files
Docwell/Server/internal/httpapi/auth_test.go
T
tajniak81andClaude Opus 5.5 ba394b8fac Finish Phase 0: lint, codegen, contributor docs and the two remaining spikes
Repository basics:
- CONTRIBUTING.md and CODE_OF_CONDUCT.md (Contributor Covenant 2.1)
- SPDX AGPL-3.0-or-later headers on all hand-written sources, checked in CI
- golangci-lint (shared .golangci.yml), ESLint and Prettier, all run in CI

API codegen from api/openapi.yaml (npm run generate, drift fails CI):
- Go types via oapi-codegen in Server/internal/api
- a contract test that the router and the spec list the same routes
- Dart models via Phone-App/tool/generate_api.dart; the app uses them

Spike: shared Tiptap editor in a Flutter WebView (ADR-4)
- @docwell/editor-bridge builds the editor into one HTML page with a
  versioned JSON protocol; Phone-App hosts it with webview_flutter and a
  native toolbar. Integration test passes on an Android API 35 emulator.
- flutter_inappwebview dropped: its Android plugin fails on AGP 9.

Spike: Wails v3 desktop (ADR-11)
- system tray, docwell:// deep links (page and space only) with
  single-instance hand-off, and the built-in updater with a required
  ed25519 signing key. Verified on Windows.
- regenerated build assets register the scheme and drop template
  placeholders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:11:07 +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) RenameWorkspace(context.Context, access.Caller, string, string) (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)
}
}
}