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

151 lines
6.5 KiB
Go

package main
import (
"context"
"html"
"log"
"net/url"
"regexp"
"strings"
"time"
"github.com/meshcore-analyzer/mailer"
"github.com/meshcore-analyzer/users"
)
type mailContent struct {
subject string
greeting string
paragraphs []string
actionLabel string
actionURL string
}
// link builds {publicBaseUrl}/#/account/{page}?token=… (never from the
// request Host, see the spec's Configuration section).
func (a *authService) link(page, token string) string {
return a.set.baseURL.String() + "/#/account/" + page + "?token=" + url.QueryEscape(token)
}
func (a *authService) render(to, toName, tag string, c mailContent) mailer.Message {
footer := "You received this because this address was used on " + a.set.baseURL.Host +
". If that was not you, you can ignore this mail."
var text, h strings.Builder
text.WriteString(c.greeting + "\n\n")
h.WriteString("<p>" + html.EscapeString(c.greeting) + "</p>")
for _, p := range c.paragraphs {
text.WriteString(p + "\n\n")
h.WriteString("<p>" + html.EscapeString(p) + "</p>")
}
if c.actionURL != "" {
text.WriteString(c.actionLabel + ":\n" + c.actionURL + "\n\n")
h.WriteString(`<p><a href="` + html.EscapeString(c.actionURL) + `">` + html.EscapeString(c.actionLabel) + `</a></p>`)
}
text.WriteString(footer + "\n")
h.WriteString(`<p style="color:#666;font-size:12px">` + html.EscapeString(footer) + `</p>`)
return mailer.Message{To: to, ToName: toName, Subject: "[" + a.set.fromName + "] " + c.subject,
HTML: h.String(), Text: text.String(), Tag: tag}
}
func (a *authService) activationMail(u *users.User, token string) mailer.Message {
return a.render(u.Email, u.DisplayName, "activate", mailContent{
subject: "Activate your account", greeting: "Hello " + u.DisplayName + ",",
paragraphs: []string{"Confirm your address to activate your account. The link works once and expires in 48 hours.",
"When you open the link, enter the password you chose when you registered."},
actionLabel: "Activate my account", actionURL: a.link("activate", token)})
}
func (a *authService) resetMail(u *users.User, token string) mailer.Message {
return a.render(u.Email, u.DisplayName, "reset", mailContent{
subject: "Reset your password", greeting: "Hello " + u.DisplayName + ",",
paragraphs: []string{"Someone asked to reset the password of your account. The link works once and expires in 1 hour. Using it logs out all your devices."},
actionLabel: "Choose a new password", actionURL: a.link("reset", token)})
}
func (a *authService) registerNoticeMail(u *users.User) mailer.Message {
return a.render(u.Email, u.DisplayName, "register-notice", mailContent{
subject: "Registration attempt with your address", greeting: "Hello " + u.DisplayName + ",",
paragraphs: []string{"Someone tried to register a new account with your address, but you already have one.",
"If it was you, log in, or use \"forgot password\" if you lost it."},
actionLabel: "Log in", actionURL: a.set.baseURL.String() + "/#/account/login"})
}
func (a *authService) emailChangeConfirmMail(u *users.User, newEmail, token string) mailer.Message {
return a.render(newEmail, u.DisplayName, "email-change", mailContent{
subject: "Confirm your new address", greeting: "Hello " + u.DisplayName + ",",
paragraphs: []string{"Confirm that this address should replace the one on your account. The link expires in 24 hours."},
actionLabel: "Confirm new address", actionURL: a.link("confirm-email", token)})
}
func (a *authService) emailChangeNoticeMail(u *users.User, newEmail string) mailer.Message {
return a.render(u.Email, u.DisplayName, "email-change-notice", mailContent{
subject: "Address change requested", greeting: "Hello " + u.DisplayName + ",",
paragraphs: []string{"A change of your account address to " + newEmail + " was requested. It takes effect only when confirmed from the new address.",
"If this was not you, change your password now."}})
}
// addrRE matches anything around an @ up to whitespace or a character that
// cannot appear unquoted in an address, so RFC 5322 atext specials and
// UTF-8 local parts and domains are covered.
var addrRE = regexp.MustCompile(`[^\s"<>()\[\],;:]+@[^\s"<>()\[\],;:]+`)
// redactAddrs renders a mailer/provider error for the server log with every
// email address replaced by <addr>: provider messages can echo the
// recipient, and addresses belong only in the audit and mail tables.
func redactAddrs(err error) string {
return addrRE.ReplaceAllString(err.Error(), "<addr>")
}
// sendMail sends msg and records it in the mail log. The error is logged
// (without tokens) and returned so the caller can answer 503.
func (a *authService) sendMail(ctx context.Context, u *users.User, purpose string, msg mailer.Message) error {
id, err := a.mail.Send(ctx, msg)
if err != nil {
log.Printf("[users] mail %s for user #%d failed: %s", purpose, u.ID, redactAddrs(err))
return err
}
if _, err := a.st.LogMail(idPtr(u.ID), msg.To, purpose, id); err != nil {
log.Printf("[users] mail log for user #%d: %v", u.ID, err)
}
return nil
}
// ingestMailEvents records provider events and flags undeliverable addresses.
// Shared by the webhook and the admin "refresh" pull.
func (a *authService) ingestMailEvents(evs []mailer.Event) {
for _, ev := range evs {
uid, found, err := a.st.RecordMailEvent(ev.MessageID, ev.Event, ev.At, ev.Reason)
if err != nil {
log.Printf("[users] record mail event: %v", err)
continue
}
if found && uid != nil && mailer.IsUndeliverable(ev.Event) {
if err := a.st.SetEmailBouncing(*uid, true); err != nil {
log.Printf("[users] flag bouncing for user #%d: %v", *uid, err)
}
}
}
}
// mailToken issues a one-time token for u, builds the mail around it and
// sends it. If issuing or sending fails the purpose's outstanding tokens are
// invalidated, so no usable link exists for a mail that never left; the
// caller answers 503. newEmail is stored only for users.PurposeEmailChange.
// mailPurpose is the label recorded in the mail log.
func (a *authService) mailToken(ctx context.Context, u *users.User, tokenPurpose users.Purpose,
ttl time.Duration, newEmail, mailPurpose string, build func(token string) mailer.Message) error {
tok, err := a.st.IssueToken(u.ID, tokenPurpose, ttl, newEmail)
if err != nil {
log.Printf("[users] issue %s token for user #%d: %v", tokenPurpose, u.ID, err)
} else {
err = a.sendMail(ctx, u, mailPurpose, build(tok))
}
if err != nil {
if ierr := a.st.InvalidateTokens(u.ID, tokenPurpose); ierr != nil {
log.Printf("[users] invalidate %s tokens for user #%d: %v", tokenPurpose, u.ID, ierr)
}
return err
}
return nil
}