Files
meshcore-analyzer/cmd/server/auth_handlers.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

284 lines
9.0 KiB
Go

package main
import (
"errors"
"log"
"net/http"
"strconv"
"time"
"github.com/meshcore-analyzer/mailer"
"github.com/meshcore-analyzer/users"
)
const (
msgCheckMail = "If the address can receive mail, a message is on its way. Check your inbox."
msgBadLogin = "incorrect email or password"
msgMailFailed = "mail could not be sent, try again later"
)
func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
a := s.auth
var req registerRequest
if !decodeJSON(w, r, &req) {
return
}
email, err := users.NormalizeEmail(req.Email)
if writeValidation(w, err) {
return
}
name, err := users.ValidateDisplayName(req.DisplayName)
if writeValidation(w, err) {
return
}
if writeValidation(w, users.ValidatePassword(req.Password)) {
return
}
if !a.allow(w, r, a.signup, "email:"+email) {
return
}
// Hash before the lookup so new and existing addresses cost the same.
hash, err := users.HashPassword(req.Password)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
if existing, err := a.st.GetByEmail(email); err == nil {
// Identical response either way (no account enumeration).
if existing.Status == users.StatusPending {
// Newest registration wins: the account takes the password and
// name of the latest request, and activation demands that
// password, so a squatter cannot plant credentials and the owner
// can recover a squatted address. Failures stay invisible to the
// client (same response as every other branch).
if err := a.st.SetPassword(existing.ID, hash); err != nil {
log.Printf("[users] register: update pending user #%d: %v", existing.ID, err)
} else if err := a.st.SetDisplayName(existing.ID, name); err != nil {
log.Printf("[users] register: update pending user #%d: %v", existing.ID, err)
} else {
existing.DisplayName = name
_ = a.mailToken(r.Context(), existing, users.PurposeActivate, 48*time.Hour, "", "activate",
func(tok string) mailer.Message { return a.activationMail(existing, tok) })
}
} else {
_ = a.sendMail(r.Context(), existing, "register-notice", a.registerNoticeMail(existing))
}
writeJSON(w, okResponse{OK: true, Message: msgCheckMail})
return
}
u, err := a.st.CreatePending(email, name, hash)
if errors.Is(err, users.ErrEmailTaken) { // lost a race with a concurrent register
writeJSON(w, okResponse{OK: true, Message: msgCheckMail})
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
err = a.mailToken(r.Context(), u, users.PurposeActivate, 48*time.Hour, "", "activate",
func(tok string) mailer.Message { return a.activationMail(u, tok) })
if err != nil {
if derr := a.st.Delete(u.ID); derr != nil {
log.Printf("[users] rollback of user #%d failed: %v", u.ID, derr)
}
writeError(w, http.StatusServiceUnavailable, msgMailFailed)
return
}
a.audit(nil, "user.register", idPtr(u.ID), nil)
writeJSON(w, okResponse{OK: true, Message: msgCheckMail})
}
// handleActivate needs the token and the account password: a re-register
// of a pending address replaces the password, so whoever clicks must prove
// they know the newest one (a squatter's link cannot log the owner into an
// account carrying the squatter's password).
func (s *Server) handleActivate(w http.ResponseWriter, r *http.Request) {
a := s.auth
var req activateRequest
if !decodeJSON(w, r, &req) {
return
}
uid, err := a.st.TokenUser(req.Token, users.PurposeActivate)
if err != nil {
writeTokenError(w, err)
return
}
if !a.allow(w, r, a.login, "activate:#"+strconv.FormatInt(uid, 10)) {
return
}
u, err := a.st.GetByID(uid)
if err != nil && !errors.Is(err, users.ErrNotFound) {
log.Printf("[users] activate: load user #%d: %v", uid, err)
writeError(w, http.StatusInternalServerError, "internal error")
return
}
if err != nil || u.Status != users.StatusPending {
writeError(w, http.StatusGone, "this account is already activated, log in instead")
return
}
ok, err := users.VerifyPassword(u.PasswordHash, req.Password)
if err != nil {
log.Printf("[users] activate: verify password for user #%d: %v", u.ID, err)
writeError(w, http.StatusInternalServerError, "internal error")
return
}
if !ok {
writeError(w, http.StatusUnauthorized, "wrong password for this account")
return
}
// Activate only on the hash that was just verified: a re-register in
// between replaces it, and the newest password must be proven.
switch err := a.st.ActivateWithToken(req.Token, u.ID, a.roleFor(u.Email), u.PasswordHash); {
case err == nil:
case errors.Is(err, users.ErrAccountChanged):
writeError(w, http.StatusConflict, "account changed, try again")
return
case errors.Is(err, users.ErrTokenInvalid), errors.Is(err, users.ErrTokenExpired):
writeTokenError(w, err)
return
default:
log.Printf("[users] activate user #%d: %v", u.ID, err)
writeError(w, http.StatusInternalServerError, "internal error")
return
}
a.audit(nil, "user.activate", idPtr(u.ID), nil)
if u, err = a.st.GetByID(u.ID); err != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
a.startSession(w, r, u)
}
// startSession creates a session, sets the cookie and answers with /me.
func (a *authService) startSession(w http.ResponseWriter, r *http.Request, u *users.User) {
raw, sess, err := a.st.CreateSession(u.ID, a.set.sessionTTL, r.UserAgent())
if err != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
_ = a.st.TouchLogin(u.ID)
a.setSessionCookie(w, raw, sess.ExpiresAt)
writeJSON(w, meFrom(u, sess))
}
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
a := s.auth
var req loginRequest
if !decodeJSON(w, r, &req) {
return
}
email, emailErr := users.NormalizeEmail(req.Email)
key := "email:" + email
if emailErr != nil {
key = "email:invalid"
}
if !a.allow(w, r, a.login, key) {
return
}
var u *users.User
if emailErr == nil {
u, _ = a.st.GetByEmail(email)
}
if u == nil {
users.BurnPasswordCheck(req.Password)
writeError(w, http.StatusUnauthorized, msgBadLogin)
return
}
ok, err := users.VerifyPassword(u.PasswordHash, req.Password)
if err != nil || !ok || u.Status != users.StatusActive {
writeError(w, http.StatusUnauthorized, msgBadLogin)
return
}
// Config wins: an address in adminEmails is always admin.
if a.isConfigAdmin(u.Email) && u.Role != users.RoleAdmin {
if err := a.st.SetRole(u.ID, users.RoleAdmin); err == nil {
u.Role = users.RoleAdmin
a.audit(nil, "user.role.config", idPtr(u.ID), map[string]string{"role": "admin"})
}
}
a.startSession(w, r, u)
}
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
if c, err := r.Cookie(sessionCookieName); err == nil && c.Value != "" {
_ = s.auth.st.DeleteSessionByToken(c.Value)
}
s.auth.clearSessionCookie(w)
writeJSON(w, okResponse{OK: true})
}
func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) {
u, sess := s.auth.currentUser(w, r)
if u == nil {
writeError(w, http.StatusUnauthorized, "not logged in")
return
}
writeJSON(w, meFrom(u, sess))
}
func (s *Server) handleForgot(w http.ResponseWriter, r *http.Request) {
a := s.auth
var req emailRequest
if !decodeJSON(w, r, &req) {
return
}
email, err := users.NormalizeEmail(req.Email)
if err != nil {
writeJSON(w, okResponse{OK: true, Message: msgCheckMail})
return
}
if !a.allow(w, r, a.signup, "email:"+email) {
return
}
u, err := a.st.GetByEmail(email)
if err != nil || u.Status != users.StatusActive {
writeJSON(w, okResponse{OK: true, Message: msgCheckMail})
return
}
err = a.mailToken(r.Context(), u, users.PurposeReset, time.Hour, "", "reset",
func(tok string) mailer.Message { return a.resetMail(u, tok) })
if err != nil {
writeError(w, http.StatusServiceUnavailable, msgMailFailed)
return
}
writeJSON(w, okResponse{OK: true, Message: msgCheckMail})
}
func (s *Server) handleReset(w http.ResponseWriter, r *http.Request) {
a := s.auth
var req resetRequest
if !decodeJSON(w, r, &req) {
return
}
if writeValidation(w, users.ValidatePassword(req.Password)) {
return
}
uid, _, err := a.st.ConsumeToken(req.Token, users.PurposeReset)
if err != nil {
writeTokenError(w, err)
return
}
hash, err := users.HashPassword(req.Password)
if err == nil {
err = a.st.SetPassword(uid, hash)
}
if err != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
// Sessions first: a token-store failure below must not leave an
// attacker's session alive.
if err := a.st.DeleteUserSessions(uid, 0); err != nil {
log.Printf("[users] reset: end sessions for user #%d: %v", uid, err)
writeError(w, http.StatusInternalServerError, "internal error")
return
}
// A pending email change must not survive the owner's recovery.
if err := a.invalidateTokens("reset", uid, users.PurposeEmailChange); err != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
a.audit(idPtr(uid), "user.password.reset", idPtr(uid), nil)
writeJSON(w, okResponse{OK: true, Message: "Password changed. Log in with your new password."})
}