Files
meshcore-analyzer/internal/users/users.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

289 lines
8.1 KiB
Go

package users
import (
"database/sql"
"errors"
"strings"
"time"
)
type Role string
const (
RoleUser Role = "user"
RoleAdmin Role = "admin"
)
// Valid reports whether r is a known role.
func (r Role) Valid() bool { return r == RoleUser || r == RoleAdmin }
type Status string
const (
StatusPending Status = "pending"
StatusActive Status = "active"
StatusDisabled Status = "disabled"
)
// User is one account. PasswordHash never leaves the server.
type User struct {
ID int64
Email string
DisplayName string
PasswordHash string
Role Role
Status Status
CreatedAt time.Time
ActivatedAt *time.Time
ActivatedBy *int64 // admin who activated manually; nil = activated by link
LastLoginAt *time.Time
EmailBouncing bool
}
const userCols = `id, email, display_name, password_hash, role, status, created_at, activated_at, activated_by, last_login_at, email_bouncing`
func scanUser(row rowScanner) (*User, error) {
var u User
var role, status string
var created int64
var activatedAt, activatedBy, lastLogin sql.NullInt64
var bouncing int
if err := row.Scan(&u.ID, &u.Email, &u.DisplayName, &u.PasswordHash, &role, &status,
&created, &activatedAt, &activatedBy, &lastLogin, &bouncing); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
u.Role, u.Status = Role(role), Status(status)
u.CreatedAt = fromUnix(created)
u.ActivatedAt = fromNullUnix(activatedAt)
if activatedBy.Valid {
v := activatedBy.Int64
u.ActivatedBy = &v
}
u.LastLoginAt = fromNullUnix(lastLogin)
u.EmailBouncing = bouncing != 0
return &u, nil
}
// CreatePending inserts a new pending user. email must already be normalized.
func (s *Store) CreatePending(email, displayName, passwordHash string) (*User, error) {
res, err := s.db.Exec(`INSERT INTO users (email, display_name, password_hash, role, status, created_at)
VALUES (?, ?, ?, 'user', 'pending', ?)`, email, displayName, passwordHash, unix(s.now()))
if err != nil {
if isUniqueViolation(err) {
return nil, ErrEmailTaken
}
return nil, err
}
id, err := res.LastInsertId()
if err != nil {
return nil, err
}
return s.GetByID(id)
}
func (s *Store) GetByID(id int64) (*User, error) {
return scanUser(s.db.QueryRow(`SELECT `+userCols+` FROM users WHERE id = ?`, id))
}
// GetByEmail looks up a normalized address.
func (s *Store) GetByEmail(email string) (*User, error) {
return scanUser(s.db.QueryRow(`SELECT `+userCols+` FROM users WHERE email = ?`, email))
}
// Activate moves a pending user to active with role. by is the admin who
// activated manually, nil for link activation. ErrNotFound if not pending.
func (s *Store) Activate(id int64, role Role, by *int64) error {
return expectOne(s.db.Exec(`UPDATE users SET status = 'active', role = ?, activated_at = ?, activated_by = ?
WHERE id = ? AND status = 'pending'`, string(role), unix(s.now()), nullInt(by), id))
}
func (s *Store) SetStatus(id int64, st Status) error {
return expectOne(s.db.Exec(`UPDATE users SET status = ? WHERE id = ?`, string(st), id))
}
func (s *Store) SetRole(id int64, r Role) error {
return expectOne(s.db.Exec(`UPDATE users SET role = ? WHERE id = ?`, string(r), id))
}
func (s *Store) SetPassword(id int64, hash string) error {
return expectOne(s.db.Exec(`UPDATE users SET password_hash = ? WHERE id = ?`, hash, id))
}
func (s *Store) SetDisplayName(id int64, name string) error {
return expectOne(s.db.Exec(`UPDATE users SET display_name = ? WHERE id = ?`, name, id))
}
// SetEmail changes the address (normalized) and clears the bounce flag.
func (s *Store) SetEmail(id int64, email string) error {
err := expectOne(s.db.Exec(`UPDATE users SET email = ?, email_bouncing = 0 WHERE id = ?`, email, id))
if isUniqueViolation(err) {
return ErrEmailTaken
}
return err
}
func (s *Store) SetEmailBouncing(id int64, v bool) error {
b := 0
if v {
b = 1
}
return expectOne(s.db.Exec(`UPDATE users SET email_bouncing = ? WHERE id = ?`, b, id))
}
func (s *Store) TouchLogin(id int64) error {
return expectOne(s.db.Exec(`UPDATE users SET last_login_at = ? WHERE id = ?`, unix(s.now()), id))
}
// Delete removes a user; sessions and tokens cascade. Mail-log rows survive
// for delivery forensics, with the address replaced by HashedEmail.
func (s *Store) Delete(id int64) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
var exists int
if err := tx.QueryRow(`SELECT 1 FROM users WHERE id = ?`, id).Scan(&exists); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
return err
}
if err := hashMailLogTx(tx, id); err != nil {
return err
}
if _, err := tx.Exec(`DELETE FROM users WHERE id = ?`, id); err != nil {
return err
}
return tx.Commit()
}
// ListFilter narrows List. Zero values mean "any".
type ListFilter struct {
Status Status
Role Role
Query string // substring of email or display name, case-insensitive
}
// List returns at most 1000 users, newest first. SQLite lower()/LIKE fold
// ASCII only, so a non-ASCII search is case-sensitive.
func (s *Store) List(f ListFilter) ([]User, error) {
q := `SELECT ` + userCols + ` FROM users WHERE 1=1`
var args []any
if f.Status != "" {
q += ` AND status = ?`
args = append(args, string(f.Status))
}
if f.Role != "" {
q += ` AND role = ?`
args = append(args, string(f.Role))
}
if t := strings.TrimSpace(f.Query); t != "" {
like := "%" + escapeLike(strings.ToLower(t)) + "%"
q += ` AND (email LIKE ? ESCAPE '\' OR lower(display_name) LIKE ? ESCAPE '\')`
args = append(args, like, like)
}
q += ` ORDER BY created_at DESC, id DESC LIMIT 1000`
rows, err := s.db.Query(q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []User
for rows.Next() {
u, err := scanUser(rows)
if err != nil {
return nil, err
}
out = append(out, *u)
}
return out, rows.Err()
}
func escapeLike(s string) string {
return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)
}
// CountActiveAdmins counts admins whose status is active.
func (s *Store) CountActiveAdmins() (int, error) {
var n int
err := s.db.QueryRow(`SELECT COUNT(*) FROM users WHERE role = 'admin' AND status = 'active'`).Scan(&n)
return n, err
}
// PruneStalePending deletes pending accounts older than maxAge that have no
// unused, unexpired activation token left.
func (s *Store) PruneStalePending(maxAge time.Duration) (int64, error) {
now := unix(s.now())
tx, err := s.db.Begin()
if err != nil {
return 0, err
}
defer tx.Rollback()
rows, err := tx.Query(`SELECT id FROM users WHERE status = 'pending' AND created_at < ?
AND NOT EXISTS (SELECT 1 FROM tokens t WHERE t.user_id = users.id AND t.purpose = 'activate'
AND t.used_at IS NULL AND t.expires_at > ?)`, now-int64(maxAge/time.Second), now)
if err != nil {
return 0, err
}
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
rows.Close()
return 0, err
}
ids = append(ids, id)
}
rows.Close()
if err := rows.Err(); err != nil {
return 0, err
}
for _, id := range ids {
if err := hashMailLogTx(tx, id); err != nil {
return 0, err
}
if _, err := tx.Exec(`DELETE FROM users WHERE id = ?`, id); err != nil {
return 0, err
}
}
return int64(len(ids)), tx.Commit()
}
// hashMailLogTx replaces the plaintext address of every mail_log row of the
// user with HashedEmail of that row's own address (rows may predate an email
// change). Rows already hashed are skipped. The cursor is closed before any
// UPDATE because the store uses a single connection.
func hashMailLogTx(tx *sql.Tx, userID int64) error {
rows, err := tx.Query(`SELECT id, to_email FROM mail_log WHERE user_id = ? AND to_email NOT LIKE 'sha256:%'`, userID)
if err != nil {
return err
}
type row struct {
id int64
email string
}
var list []row
for rows.Next() {
var r row
if err := rows.Scan(&r.id, &r.email); err != nil {
rows.Close()
return err
}
list = append(list, r)
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for _, r := range list {
if _, err := tx.Exec(`UPDATE mail_log SET to_email = ? WHERE id = ?`, HashedEmail(r.email), r.id); err != nil {
return err
}
}
return nil
}