mirror of
https://github.com/Kpa-clawbot/meshcore-analyzer.git
synced 2026-10-13 18:17:15 +00:00
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>
223 lines
8.2 KiB
Go
223 lines
8.2 KiB
Go
package users
|
|
|
|
import (
|
|
"errors"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestTokenConsumeOnce(t *testing.T) {
|
|
st, _ := newTestStore(t)
|
|
u := mustCreate(t, st, "t@example.org", "Tok")
|
|
raw, err := st.IssueToken(u.ID, PurposeActivate, time.Hour, "")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
uid, newEmail, err := st.ConsumeToken(raw, PurposeActivate)
|
|
if err != nil || uid != u.ID || newEmail != "" {
|
|
t.Fatalf("ConsumeToken = %d, %q, %v", uid, newEmail, err)
|
|
}
|
|
if _, _, err := st.ConsumeToken(raw, PurposeActivate); !errors.Is(err, ErrTokenInvalid) {
|
|
t.Fatalf("second consume err = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestTokenPurposeMismatchDoesNotConsume(t *testing.T) {
|
|
st, _ := newTestStore(t)
|
|
u := mustCreate(t, st, "m@example.org", "Mis")
|
|
raw, _ := st.IssueToken(u.ID, PurposeReset, time.Hour, "")
|
|
if _, _, err := st.ConsumeToken(raw, PurposeActivate); !errors.Is(err, ErrTokenInvalid) {
|
|
t.Fatalf("mismatch err = %v", err)
|
|
}
|
|
if _, _, err := st.ConsumeToken(raw, PurposeReset); err != nil {
|
|
t.Fatalf("token was consumed by the mismatched attempt: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestTokenExpiry(t *testing.T) {
|
|
st, clk := newTestStore(t)
|
|
u := mustCreate(t, st, "e@example.org", "Exp")
|
|
raw, _ := st.IssueToken(u.ID, PurposeReset, time.Hour, "")
|
|
clk.Advance(time.Hour)
|
|
if _, _, err := st.ConsumeToken(raw, PurposeReset); !errors.Is(err, ErrTokenExpired) {
|
|
t.Fatalf("expired err = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestNewTokenInvalidatesOlderSamePurpose(t *testing.T) {
|
|
st, _ := newTestStore(t)
|
|
u := mustCreate(t, st, "n@example.org", "New")
|
|
old, _ := st.IssueToken(u.ID, PurposeActivate, time.Hour, "")
|
|
keep, _ := st.IssueToken(u.ID, PurposeReset, time.Hour, "")
|
|
fresh, _ := st.IssueToken(u.ID, PurposeActivate, time.Hour, "")
|
|
if _, _, err := st.ConsumeToken(old, PurposeActivate); !errors.Is(err, ErrTokenInvalid) {
|
|
t.Fatalf("old activation link still works: %v", err)
|
|
}
|
|
if _, _, err := st.ConsumeToken(fresh, PurposeActivate); err != nil {
|
|
t.Fatalf("fresh link: %v", err)
|
|
}
|
|
if _, _, err := st.ConsumeToken(keep, PurposeReset); err != nil {
|
|
t.Fatalf("other purpose was invalidated: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestEmailChangeTokenCarriesNewEmail(t *testing.T) {
|
|
st, _ := newTestStore(t)
|
|
u := mustCreate(t, st, "c@example.org", "Chg")
|
|
raw, _ := st.IssueToken(u.ID, PurposeEmailChange, time.Hour, "new@example.org")
|
|
_, ne, err := st.ConsumeToken(raw, PurposeEmailChange)
|
|
if err != nil || ne != "new@example.org" {
|
|
t.Fatalf("ConsumeToken = %q, %v", ne, err)
|
|
}
|
|
}
|
|
|
|
func TestInvalidateAndPruneTokens(t *testing.T) {
|
|
st, clk := newTestStore(t)
|
|
u := mustCreate(t, st, "i@example.org", "Inv")
|
|
raw, _ := st.IssueToken(u.ID, PurposeActivate, time.Hour, "")
|
|
if err := st.InvalidateTokens(u.ID, PurposeActivate); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, _, err := st.ConsumeToken(raw, PurposeActivate); !errors.Is(err, ErrTokenInvalid) {
|
|
t.Fatalf("invalidated token still works: %v", err)
|
|
}
|
|
clk.Advance(8 * 24 * time.Hour)
|
|
if n, err := st.PruneTokens(7 * 24 * time.Hour); err != nil || n != 1 {
|
|
t.Fatalf("PruneTokens = %d, %v", n, err)
|
|
}
|
|
}
|
|
|
|
func TestPruneStalePending(t *testing.T) {
|
|
st, clk := newTestStore(t)
|
|
stale := mustCreate(t, st, "stale@example.org", "Stale")
|
|
st.IssueToken(stale.ID, PurposeActivate, 48*time.Hour, "")
|
|
fresh := mustCreate(t, st, "fresh@example.org", "Fresh")
|
|
_ = fresh
|
|
clk.Advance(49 * time.Hour)
|
|
resent := mustCreate(t, st, "resent@example.org", "Resent")
|
|
_ = resent
|
|
n, err := st.PruneStalePending(48 * time.Hour)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// stale: old + token expired → pruned. fresh: old, no token → pruned.
|
|
// resent: created after the advance → kept.
|
|
if n != 2 {
|
|
t.Fatalf("pruned %d; want 2", n)
|
|
}
|
|
if _, err := st.GetByEmail("resent@example.org"); err != nil {
|
|
t.Fatalf("recent pending pruned: %v", err)
|
|
}
|
|
// An old pending account with a live (re-sent) token survives.
|
|
old := mustCreate(t, st, "old@example.org", "Old")
|
|
clk.Advance(49 * time.Hour)
|
|
st.IssueToken(old.ID, PurposeActivate, 48*time.Hour, "")
|
|
if n, _ := st.PruneStalePending(48 * time.Hour); n != 1 { // only "resent" goes now
|
|
t.Fatalf("second prune = %d; want 1", n)
|
|
}
|
|
if _, err := st.GetByEmail("old@example.org"); err != nil {
|
|
t.Fatal("pending user with a live token was pruned")
|
|
}
|
|
}
|
|
|
|
func TestTokenUserDoesNotConsume(t *testing.T) {
|
|
st, clk := newTestStore(t)
|
|
u := mustCreate(t, st, "look@example.org", "Look")
|
|
raw, _ := st.IssueToken(u.ID, PurposeActivate, time.Hour, "")
|
|
for i := 0; i < 2; i++ {
|
|
uid, err := st.TokenUser(raw, PurposeActivate)
|
|
if err != nil || uid != u.ID {
|
|
t.Fatalf("TokenUser #%d = %d, %v", i, uid, err)
|
|
}
|
|
}
|
|
if _, err := st.TokenUser(raw, PurposeReset); !errors.Is(err, ErrTokenInvalid) {
|
|
t.Fatalf("purpose mismatch err = %v", err)
|
|
}
|
|
if _, err := st.TokenUser("not-a-token", PurposeActivate); !errors.Is(err, ErrTokenInvalid) {
|
|
t.Fatalf("unknown token err = %v", err)
|
|
}
|
|
if uid, _, err := st.ConsumeToken(raw, PurposeActivate); err != nil || uid != u.ID {
|
|
t.Fatalf("token burned by TokenUser: %d, %v", uid, err)
|
|
}
|
|
if _, err := st.TokenUser(raw, PurposeActivate); !errors.Is(err, ErrTokenInvalid) {
|
|
t.Fatalf("used token err = %v", err)
|
|
}
|
|
exp, _ := st.IssueToken(u.ID, PurposeReset, time.Hour, "")
|
|
clk.Advance(time.Hour)
|
|
if _, err := st.TokenUser(exp, PurposeReset); !errors.Is(err, ErrTokenExpired) {
|
|
t.Fatalf("expired err = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestActivateWithTokenActivatesAndBurns(t *testing.T) {
|
|
st, _ := newTestStore(t)
|
|
u := mustCreate(t, st, "act@example.org", "Act")
|
|
raw, _ := st.IssueToken(u.ID, PurposeActivate, time.Hour, "")
|
|
if err := st.ActivateWithToken(raw, u.ID, RoleAdmin, u.PasswordHash); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, _ := st.GetByID(u.ID)
|
|
if got.Status != StatusActive || got.Role != RoleAdmin || got.ActivatedAt == nil || got.ActivatedBy != nil {
|
|
t.Fatalf("after ActivateWithToken: %+v", got)
|
|
}
|
|
if _, err := st.TokenUser(raw, PurposeActivate); !errors.Is(err, ErrTokenInvalid) {
|
|
t.Fatalf("token still usable after activation: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestActivateWithTokenHashChangedIsAccountChanged(t *testing.T) {
|
|
st, _ := newTestStore(t)
|
|
u := mustCreate(t, st, "race@example.org", "Race")
|
|
raw, _ := st.IssueToken(u.ID, PurposeActivate, time.Hour, "")
|
|
verified := u.PasswordHash
|
|
if err := st.SetPassword(u.ID, "$argon2id$replaced"); err != nil { // a re-register in between
|
|
t.Fatal(err)
|
|
}
|
|
if err := st.ActivateWithToken(raw, u.ID, RoleUser, verified); !errors.Is(err, ErrAccountChanged) {
|
|
t.Fatalf("err = %v, want ErrAccountChanged", err)
|
|
}
|
|
if got, _ := st.GetByID(u.ID); got.Status != StatusPending {
|
|
t.Fatalf("activated with a stale hash: %+v", got)
|
|
}
|
|
if _, err := st.TokenUser(raw, PurposeActivate); err != nil {
|
|
t.Fatalf("token burned although nothing was activated: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestActivateWithTokenNotPendingIsAccountChanged(t *testing.T) {
|
|
st, _ := newTestStore(t)
|
|
u := mustCreate(t, st, "manual@example.org", "Manual")
|
|
raw, _ := st.IssueToken(u.ID, PurposeActivate, time.Hour, "")
|
|
if err := st.Activate(u.ID, RoleUser, nil); err != nil { // an admin activated in between
|
|
t.Fatal(err)
|
|
}
|
|
if err := st.ActivateWithToken(raw, u.ID, RoleAdmin, u.PasswordHash); !errors.Is(err, ErrAccountChanged) {
|
|
t.Fatalf("err = %v, want ErrAccountChanged", err)
|
|
}
|
|
if got, _ := st.GetByID(u.ID); got.Role != RoleUser {
|
|
t.Fatalf("role changed on an active account: %+v", got)
|
|
}
|
|
}
|
|
|
|
func TestActivateWithTokenRejectsBadTokens(t *testing.T) {
|
|
st, clk := newTestStore(t)
|
|
u := mustCreate(t, st, "bad@example.org", "Bad")
|
|
other := mustCreate(t, st, "other@example.org", "Other")
|
|
reset, _ := st.IssueToken(u.ID, PurposeReset, time.Hour, "")
|
|
if err := st.ActivateWithToken(reset, u.ID, RoleUser, u.PasswordHash); !errors.Is(err, ErrTokenInvalid) {
|
|
t.Fatalf("reset token: err = %v, want ErrTokenInvalid", err)
|
|
}
|
|
foreign, _ := st.IssueToken(other.ID, PurposeActivate, time.Hour, "")
|
|
if err := st.ActivateWithToken(foreign, u.ID, RoleUser, u.PasswordHash); !errors.Is(err, ErrTokenInvalid) {
|
|
t.Fatalf("other user's token: err = %v, want ErrTokenInvalid", err)
|
|
}
|
|
raw, _ := st.IssueToken(u.ID, PurposeActivate, time.Hour, "")
|
|
clk.Advance(2 * time.Hour)
|
|
if err := st.ActivateWithToken(raw, u.ID, RoleUser, u.PasswordHash); !errors.Is(err, ErrTokenExpired) {
|
|
t.Fatalf("expired token: err = %v, want ErrTokenExpired", err)
|
|
}
|
|
if got, _ := st.GetByID(u.ID); got.Status != StatusPending {
|
|
t.Fatalf("activated by a bad token: %+v", got)
|
|
}
|
|
}
|