mirror of
https://github.com/Kpa-clawbot/meshcore-analyzer.git
synced 2026-10-11 17:57:49 +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>
126 lines
3.3 KiB
Go
126 lines
3.3 KiB
Go
package main
|
|
|
|
import (
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/meshcore-analyzer/users"
|
|
)
|
|
|
|
func TestRateLimiterBurstAndRefill(t *testing.T) {
|
|
now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
|
|
l := newRateLimiter(3, time.Minute)
|
|
l.now = func() time.Time { return now }
|
|
for i := 0; i < 3; i++ {
|
|
if ok, _ := l.take("k"); !ok {
|
|
t.Fatalf("take %d refused within burst", i)
|
|
}
|
|
}
|
|
ok, wait := l.take("k")
|
|
if ok || wait <= 0 || wait > 20*time.Second {
|
|
t.Fatalf("4th take = %v, wait %v", ok, wait)
|
|
}
|
|
if ok, _ := l.take("other"); !ok {
|
|
t.Fatal("keys are not independent")
|
|
}
|
|
now = now.Add(21 * time.Second) // one token per 20s
|
|
if ok, _ := l.take("k"); !ok {
|
|
t.Fatal("no refill after 21s")
|
|
}
|
|
now = now.Add(time.Hour)
|
|
l.gc()
|
|
l.mu.Lock()
|
|
n := len(l.buckets)
|
|
l.mu.Unlock()
|
|
if n != 0 {
|
|
t.Fatalf("gc kept %d full buckets", n)
|
|
}
|
|
}
|
|
|
|
func TestRateLimiterBucketCap(t *testing.T) {
|
|
now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
|
|
l := newRateLimiter(3, time.Minute)
|
|
l.now = func() time.Time { return now }
|
|
l.maxBuckets = 2
|
|
l.take("a")
|
|
l.take("b")
|
|
// both buckets are partly drained, so the inline sweep frees nothing
|
|
ok, wait := l.take("c")
|
|
if ok || wait <= 0 {
|
|
t.Fatalf("new key at the cap = %v, wait %v; want refused", ok, wait)
|
|
}
|
|
if ok, _ := l.take("a"); !ok {
|
|
t.Fatal("existing key refused at the cap")
|
|
}
|
|
// once the old buckets have refilled, the sweep makes room
|
|
now = now.Add(time.Hour)
|
|
if ok, _ := l.take("c"); !ok {
|
|
t.Fatal("new key refused after buckets refilled")
|
|
}
|
|
l.mu.Lock()
|
|
n := len(l.buckets)
|
|
l.mu.Unlock()
|
|
if n > 2 {
|
|
t.Fatalf("buckets = %d, cap 2", n)
|
|
}
|
|
}
|
|
|
|
func TestAllowKeysOnForwardedIP(t *testing.T) {
|
|
a, _ := newTestAuthService(t)
|
|
a.ipr.trustedProxies = parseCIDRList([]string{"10.0.0.0/8"}, "test")
|
|
l := newRateLimiter(1, time.Hour)
|
|
try := func(xff string) bool {
|
|
r := httptest.NewRequest("POST", "/x", nil)
|
|
r.RemoteAddr = "10.0.0.1:4000"
|
|
r.Header.Set("X-Forwarded-For", xff)
|
|
return a.allow(httptest.NewRecorder(), r, l)
|
|
}
|
|
if !try("198.51.100.7") {
|
|
t.Fatal("first request refused")
|
|
}
|
|
if try("198.51.100.7") {
|
|
t.Fatal("same forwarded IP not limited")
|
|
}
|
|
if !try("198.51.100.8") {
|
|
t.Fatal("different forwarded IP shares a bucket")
|
|
}
|
|
}
|
|
|
|
func TestCloseUserManagementWaitsForJanitor(t *testing.T) {
|
|
a, _ := newTestAuthService(t)
|
|
srv := &Server{auth: a}
|
|
release := make(chan struct{})
|
|
a.wg.Add(1)
|
|
go func() {
|
|
defer a.wg.Done()
|
|
<-a.stop
|
|
<-release // janitor still busy after stop was signalled
|
|
}()
|
|
done := make(chan struct{})
|
|
go func() { srv.closeUserManagement(); close(done) }()
|
|
select {
|
|
case <-done:
|
|
t.Fatal("close returned while the janitor was still running")
|
|
case <-time.After(100 * time.Millisecond):
|
|
}
|
|
close(release)
|
|
select {
|
|
case <-done:
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("close did not return after the janitor exited")
|
|
}
|
|
}
|
|
|
|
func TestAdminRowConfigAdminNeedsAdminRole(t *testing.T) {
|
|
a, _ := newTestAuthService(t, "boss@example.org")
|
|
pending := users.User{Email: "boss@example.org", Role: users.RoleUser, Status: users.StatusPending}
|
|
if a.adminRow(pending, nil).ConfigAdmin {
|
|
t.Fatal("pending squatter on a config address reported as config admin")
|
|
}
|
|
admin := users.User{Email: "boss@example.org", Role: users.RoleAdmin, Status: users.StatusActive}
|
|
if !a.adminRow(admin, nil).ConfigAdmin {
|
|
t.Fatal("real config admin not reported")
|
|
}
|
|
}
|