Files
meshcore-analyzer/cmd/server/auth_fixture_test.go
T
efitenandClaude Opus 5.5 d232072f85 feat: optional user accounts (part A: foundation) (#2129)
Part A of #2128: optional, off-by-default user accounts. With the
feature off nothing changes; with it on, visitors can register and log
in, and admins manage users and use the operator actions without the API
key.

PR #2130 (settings sync) builds on this one. The two are meant to be
merged together.

## The situation

- Operator actions (geofilter save and prune, backup, perf reset) need
the shared `apiKey`. There is no per-person right.
- Nothing in CoreScope knows who a visitor is, so the requests in #2128
that need that (#1835, #2092, #1508, #730) have nothing to build on.

## What this PR adds

**Two new Go modules**
- `internal/users`: a separate `users.db` (SQLite through
`modernc.org/sqlite`) with users, sessions, single-use tokens, an audit
log and a mail log. Passwords use argon2id.
- `internal/mailer`: a `Mailer` interface with a Brevo client (send,
delivery events, webhook parsing) and an in-memory fake for tests.

**Server (`cmd/server`)**, active only with `userManagement.enabled`
- 24 routes, all documented in OpenAPI under the `users` tag
([`auth_routes.go`](https://github.com/efiten/CoreScope/blob/feat/user-management/cmd/server/auth_routes.go)):
  - auth: register, activate, login, logout, me, forgot, reset;
- account: profile, password, email change with confirmation, sessions,
self-delete;
- admin: list, detail, disable, enable, delete, role, resend activation,
manual activation, mail status refresh;
  - a Brevo webhook, registered only when `mail.webhookSecret` is set.
- `requireAdmin` replaces `requireAPIKey` at the 7 operator call sites:
the API key **or** an admin session. With the feature off it is the old
API-key gate (`TestRequireAdminWithoutUserManagementIsAPIKeyGate`).
- `/api/config/client` gets `userManagement: {enabled: true}` only when
the service started; with the feature off the response is
byte-identical.

**Frontend**
- `auth.js` (header account control, request helper that adds the CSRF
header), `account.js` (login, register, activate, forgot, reset, confirm
email, my account), `admin-users.js` (`#/admin/users`, deep-linked
filters), `account.css` (theme tokens only).
- On phones the top-bar control is hidden, so a conditional entry goes
into the bottom-nav "More" sheet and the nav drawer.
- The customizer geofilter tab and the Perf "Reset stats" button use the
admin session when there is one.

**Config.** A `userManagement` block (`config.example.json`,
[`docs/user-guide/accounts.md`](https://github.com/efiten/CoreScope/blob/feat/user-management/docs/user-guide/accounts.md)).
The Brevo key can come from `CORESCOPE_BREVO_API_KEY`. The server
refuses to start when the block is enabled but incomplete.

## Security choices

- Session cookie `cs_session`: HttpOnly, SameSite=Lax, Secure when
`publicBaseUrl` is https. Every cookie-authenticated state change needs
the `X-CS-CSRF` header and a matching Origin.
- Activation needs the token **and** the account password. Without the
password, an attacker who keeps re-registering a known address could get
the owner to activate an account that carries the attacker's password.
- Register, forgot and email change answer identically for known and
unknown addresses. A password reset ends all sessions, a password change
ends all other sessions, and both end outstanding email-change links.
- Rate limits: login 10 per 15 minutes, register and forgot 5 per hour,
per IP and per address. The bucket count is capped. `trustedProxies`
makes the per-IP limits see real client IPs behind a proxy.
- Server logs carry `#<user id>`, never addresses, tokens or passwords;
mail-provider error texts are redacted before logging.

## Performance

No change to an existing hot path with the feature off. With it on:
- One `users.db` lookup per authenticated request (session by token
hash).
- The admin user table rebuilds its `tbody` on each filter change.
`users.List` caps the result at 1000 rows (`internal/users/users.go`),
which bounds the rebuild.
- `map[string]interface{}` in `openapi.go`: 79 before, 78 after.

## Verification

- `internal/users`, `internal/mailer` and `cmd/server`: `go vet` and `go
test -race` pass locally. 121 new Go tests.
- `cmd/server` with `-tags e2etest`: vet and the e2e hook tests pass.
- `sh test-all.sh` exits 0. `tests/unit/test-user-management-ui.js`: 67
passing (vm, real modules).
- `tests/e2e/test-user-management-e2e.js` (6 steps) passed locally
against an `e2etest` build with the fake mailer and against a
feature-off build. CI builds the `e2etest` binary and runs the suite on
a second server (`deploy.yml`).
- On a staging instance with a real Brevo key: register, activation mail
delivered, activate, admin table, "Refresh status" showing sent,
deferred, delivered, opened and clicked.

## Not in this PR

- Settings sync (#2130), the admin dashboard, approval flows and
notifications (parts B to E of #2128).
- A `requireReadAuth` mode (#1835). Sessions from this PR are what such
a mode would accept.
- Binary size and build time with `modernc.org/sqlite` linked next to
`mattn/go-sqlite3` were not measured. Their driver names do not collide.
#1992 discusses the driver choice.
- No Brevo webhook was configured on staging; delivery status there came
from "Refresh status".

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 09:25:29 +02:00

216 lines
5.8 KiB
Go

package main
import (
"bytes"
"database/sql"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"regexp"
"testing"
"time"
"github.com/gorilla/mux"
"github.com/meshcore-analyzer/mailer"
"github.com/meshcore-analyzer/users"
)
const (
testBase = "https://scope.example.org"
testAPIKey = "test-secret-key-strong-enough"
testHook = "webhook-secret-0123456789"
)
type authFixture struct {
srv *Server
router *mux.Router
fake *mailer.Fake
st *users.Store
}
// client is a browser: its session cookie and CSRF token.
type client struct {
cookie *http.Cookie
csrf string
me meResponse
}
func newTestAuthService(t *testing.T, adminEmails ...string) (*authService, *mailer.Fake) {
t.Helper()
set := &userMgmtSettings{
dbPath: filepath.Join(t.TempDir(), "users.db"), adminEmails: map[string]bool{},
sessionTTL: 30 * 24 * time.Hour, provider: "fake",
fromEmail: "noreply@example.org", fromName: "CoreScope", webhookSecret: testHook,
}
set.baseURL, _ = url.Parse(testBase)
set.secureCookie = true
for _, e := range adminEmails {
set.adminEmails[e] = true
}
st, err := users.Open(set.dbPath)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { st.Close() })
fake := &mailer.Fake{}
return newAuthService(set, st, fake), fake
}
// newAuthFixture builds a Server with auth on and only the auth routes.
func newAuthFixture(t *testing.T, adminEmails ...string) *authFixture {
t.Helper()
a, fake := newTestAuthService(t, adminEmails...)
srv := &Server{cfg: &Config{APIKey: testAPIKey}, perfStats: NewPerfStats(), auth: a}
r := mux.NewRouter()
srv.registerAuthRoutes(r)
return &authFixture{srv: srv, router: r, fake: fake, st: a.st}
}
type reqMod func(*http.Request)
func as(c *client) reqMod {
return func(r *http.Request) {
if c.cookie != nil {
r.AddCookie(c.cookie)
}
if c.csrf != "" {
r.Header.Set(csrfHeader, c.csrf)
}
}
}
func header(k, v string) reqMod { return func(r *http.Request) { r.Header.Set(k, v) } }
func fromIP(ip string) reqMod { return func(r *http.Request) { r.RemoteAddr = ip + ":5555" } }
func (f *authFixture) do(method, path string, body any, mods ...reqMod) *httptest.ResponseRecorder {
var rd io.Reader
if body != nil {
b, _ := json.Marshal(body)
rd = bytes.NewReader(b)
}
req := httptest.NewRequest(method, path, rd)
req.RemoteAddr = "203.0.113.10:5555"
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if !isSafeMethod(method) {
req.Header.Set("Origin", testBase)
}
for _, m := range mods {
m(req)
}
w := httptest.NewRecorder()
f.router.ServeHTTP(w, req)
return w
}
func decode[T any](t *testing.T, w *httptest.ResponseRecorder) T {
t.Helper()
var v T
if err := json.Unmarshal(w.Body.Bytes(), &v); err != nil {
t.Fatalf("decode %T from %q: %v", v, w.Body.String(), err)
}
return v
}
func expectStatus(t *testing.T, w *httptest.ResponseRecorder, code int) {
t.Helper()
if w.Code != code {
t.Fatalf("status = %d, want %d; body: %s", w.Code, code, w.Body.String())
}
}
var tokenRE = regexp.MustCompile(`token=([A-Za-z0-9_%\-]+)`)
// lastToken extracts the token from the newest fake mail's link.
func (f *authFixture) lastToken(t *testing.T) string {
t.Helper()
m, _, ok := f.fake.Last()
if !ok {
t.Fatal("no mail was sent")
}
sm := tokenRE.FindStringSubmatch(m.Text)
if sm == nil {
t.Fatalf("no token in mail text: %q", m.Text)
}
tok, _ := url.QueryUnescape(sm[1])
return tok
}
func sessionFrom(t *testing.T, w *httptest.ResponseRecorder) *http.Cookie {
t.Helper()
for _, c := range w.Result().Cookies() {
if c.Name == sessionCookieName && c.Value != "" {
return c
}
}
t.Fatalf("no %s cookie in response", sessionCookieName)
return nil
}
// registerAndActivate runs the link flow and returns the logged-in client.
func (f *authFixture) registerAndActivate(t *testing.T, email, name, password string) *client {
t.Helper()
w := f.do("POST", "/api/auth/register", registerRequest{Email: email, DisplayName: name, Password: password})
expectStatus(t, w, 200)
w = f.do("POST", "/api/auth/activate", activateRequest{Token: f.lastToken(t), Password: password})
expectStatus(t, w, 200)
me := decode[meResponse](t, w)
return &client{cookie: sessionFrom(t, w), csrf: me.CSRFToken, me: me}
}
func (f *authFixture) login(t *testing.T, email, password string) *client {
t.Helper()
w := f.do("POST", "/api/auth/login", loginRequest{Email: email, Password: password})
expectStatus(t, w, 200)
me := decode[meResponse](t, w)
return &client{cookie: sessionFrom(t, w), csrf: me.CSRFToken, me: me}
}
// breakTable renames a users.db table behind the store's back, so the next
// store call that touches it fails with a DB error (not ErrNotFound).
func (f *authFixture) breakTable(t *testing.T, table string) {
t.Helper()
db, err := sql.Open("sqlite", f.srv.auth.set.dbPath)
if err != nil {
t.Fatal(err)
}
defer db.Close()
if _, err := db.Exec(`ALTER TABLE ` + table + ` RENAME TO ` + table + `_broken`); err != nil {
t.Fatal(err)
}
}
// unusedTokens counts uid's outstanding links of purpose p, read straight
// from users.db (the raw tokens are not observable when no mail left).
func (f *authFixture) unusedTokens(t *testing.T, uid int64, p users.Purpose) int {
t.Helper()
db, err := sql.Open("sqlite", f.srv.auth.set.dbPath)
if err != nil {
t.Fatal(err)
}
defer db.Close()
var n int
if err := db.QueryRow(`SELECT COUNT(*) FROM tokens WHERE user_id = ? AND purpose = ? AND used_at IS NULL`, uid, string(p)).Scan(&n); err != nil {
t.Fatal(err)
}
return n
}
// execDB runs raw SQL on users.db behind the store's back (triggers that
// simulate a concurrent writer or a failing statement).
func (f *authFixture) execDB(t *testing.T, stmt string) {
t.Helper()
db, err := sql.Open("sqlite", f.srv.auth.set.dbPath)
if err != nil {
t.Fatal(err)
}
defer db.Close()
if _, err := db.Exec(stmt); err != nil {
t.Fatal(err)
}
}