Files
meshcore-analyzer/cmd/server/auth_service.go
T
efitenandClaude Opus 5.5 e149568c6c feat(observer-logins): personal MQTT logins for observers (#2306)
Observers publish to the broker with one shared MQTT login. Anyone who
has that login can publish under any observer's topic, and the ingestor
takes the observer id from the topic (`cmd/ingestor/main.go:1009`), so
the data in the analyzer DB is only as trustworthy as the shared
password. This PR gives each user a personal MQTT login, generated and
mailed by CoreScope, and lets the broker ask CoreScope whether a login
may connect and publish.

Closes #2319.

The feature is optional and off by default
(`userManagement.observerLogins.enabled`). It needs
`userManagement.enabled`. With it off, nothing changes.

## Changes in this PR

**Broker hooks.** `POST /api/mqtt-hook/emqx/authn` and `/authz`, for the
EMQX HTTP authenticator and authorizer.
- They check a shared secret header, `X-CoreScope-Hook-Secret`, in
constant time.
- A username CoreScope does not know gets `ignore`, so EMQX falls
through to its built-in database and existing users keep working.
- A personal login may only publish `meshcore/<iata>/<pubkey>/<type>`,
with a 64-hex pubkey that is unbound or bound to the same user.
- The first publish for an unbound pubkey binds that observer to the
user (first come wins), until the user owns 20 observers (admin
assignments count too).
- An admin can rebind any observer.

**Credentials.**
- Username `obs_` + 12 random `[a-z0-9]`, password 32 random
`[A-Za-z0-9]`, both from `crypto/rand`.
- The password is stored twice: SHA-256 for the auth check, and sealed
with AES-256-GCM (key from config or `CORESCOPE_OBSERVER_KEY`) so the
user can ask for the same credentials again.
- The UI and the API never show the password. It leaves the server only
in the mail.

**Mail.** One mail with four formats:
- the meshcoretomqtt TOML;
- the observer firmware CLI commands (Gessaman or Dutch-MeshCore, same
`mqttN` CLI), on slot 4: slots 1-2 (Gessaman, Let's Mesh US/EU) and 1-3
(Dutch-MeshCore, `MQTTDefaults.h:19-34`) hold default broker presets on
a fresh install, slot 4 is empty on both. `set mqtt4.server` gets the
bare host: the firmware picks the scheme from the port
(`MQTTBridge.cpp:2094-2145`), and builds before merge 32dd8ad
(2026-10-19) do not accept a scheme there (read from the source, not
tested on a device). A scheme is written only when the port would pick
the wrong one, for example TLS on 8884;
- the Home Assistant meshcore-ha broker form fields;
- the plain values.

Each block starts with a numbered title and one line on where it goes.
The account page can resend the mail, at most 3 times per 24 h.

**Account and admin UI.**
- The account page gets an "Observer MQTT login" section
(`#/account?section=observers`) with the username, the bound observers
and the resend button.
- The admin page gets an "Observer logins" tab
(`#/admin?tab=observer-logins`) that lists logins with revoke and
reissue, and every observer with its owner, "not migrated" or
"orphaned", with a reassign control.

**Notifications.** Creating a login adds `observer.offline.own` ("My
observers go offline") to the owner's notification events; mails go out
once the user has notifications switched on, and the user can untick it.

**Storage.** users.db schema v7 adds `mqtt_logins` and
`observer_bindings`. The server still writes only users.db through
`internal/users`, and the analyzer DB stays read-only.

**Docs.** `docs/observer-mqtt-logins.md` covers the EMQX setup (authn
and authz chains, the hook body templates, the closing `^obs_` deny rule
and why it is needed), how to enable it on a running EMQX through the
REST API step by step, with a check and a rollback per step, and how to
migrate observers off a shared login. `config.example.json` has the
block with placeholder values.

## Enabling it on an instance

Full steps in `docs/observer-mqtt-logins.md`. In short:

1. **CoreScope:** add `userManagement.observerLogins` to `config.json`
with `enabled: true`, a `hookSecret` (`openssl rand -hex 32`), an
`encryptionKey` (`openssl rand -base64 32`) and the `broker` host, port,
transport and TLS that observers should use. Restart. Keep the key safe:
without it, mails cannot be resent and logins must be reissued.
2. **EMQX, authorization:** add a file source with `{deny, {username,
{re, "^obs_"}}, all, ["#"]}.` and move it to the end, then add the HTTP
authorizer pointing at `/api/mqtt-hook/emqx/authz` (it lands at the
front).
3. **EMQX, authentication:** add the HTTP authenticator pointing at
`/api/mqtt-hook/emqx/authn` and move it to the front, before the
built-in database.
4. **Check:** the shared login still connects, an unknown `obs_` login
is refused, and `metrics.deny` on the authorizer stays 0 for existing
clients.
5. **Owners:** they request a login on their account page and paste the
block for their uploader. Each observer binds to them on its first
publish. An uploader that was refused before step 3 may need a restart.
6. **Later:** remove the shared login from the broker once enough
observers moved.

## Who can claim an observer

Any active account can request a login, and its first publish under an
unbound pubkey binds that observer, also when CoreScope already knew it
from the shared login (first come wins, a deliberate choice: owners
migrate without waiting for an admin). Observer pubkeys are public, and
registration cannot be closed, so with this feature on anyone with a
mail address can claim up to 20 unbound observers per account. Before,
publishing needed the shared password.

What limits it: each claim of a known observer mails the admins, an
admin can unbind or reassign it and revoke the login, and a bound
observer cannot be claimed by another login. The doc spells this out and
suggests assigning known observers to their owners before announcing the
feature. A stricter mode (admin approval of logins, or no auto-bind for
known observers) is not in this PR.

## Performance

`authorize()` runs for every publish that misses the EMQX authz cache.
It takes two short read locks, does map lookups and one topic split.
`BenchmarkAuthorizeBound` (2000 observers, 500 logins): 533.5 ns/op, 96
B/op, 2 allocs/op. The admin observers table renders once per load and
updates single rows after a change.

## Verification

- All 16 Go modules: `bash scripts/allmod.sh test ./...` green.
- Skipped `TestSaveGeoFilterPreservesFileMode` and
`TestWriteStatsAtomic_SymlinkAtDestIsReplaced`: both fail on Windows on
a clean master too.
- `sh test-all.sh` green.
- `tests/e2e/test-user-management-e2e.js` 36/36 locally. It covers:
request, mail, resend, revoke, reissue, reassign, no password in the
page or API body, and axe. The CI job for this suite gets the
`observerLogins` block with fake values in `deploy.yml`.
- Local EMQX 5.8.6 in Docker against a local CoreScope:
- a personal login connects and publishes, which binds the observer; a
second personal login is denied on that observer's topic, and subscribe
is denied;
- with CoreScope stopped, the built-in users still connect and publish,
and new personal-login connects are refused;
- the `^obs_` deny rule blocks an already-connected personal login while
CoreScope is down; without the rule, the same publish was delivered.

- Production: running on an EMQX 5.8.9 broker with about 50 clients
since 2026-10-25, set up through the REST API as in the doc. After the
hooks went in, the authorizer answered `ignore` for every existing login
(0 denies, 0 dropped messages), and 4 observers were bound to their
owners through personal logins on the same evening, with the shared
login still in use by the rest.

## Known behaviour

EMQX's HTTP client can mark the hook resource down for one health-check
interval (15 s measured) when CoreScope closes an idle keep-alive
connection just as a health check runs. During that window new
personal-login connects are refused and the uploader reconnects. I saw
it 3 times in about 25 minutes of runs with a forced 1-5 s idle timeout,
and could not trigger it on demand. EMQX 5.8.6 has no setting for it,
and 5.10.5 ships the same client code. The doc describes it and the
alarm to watch for.

## Not in this PR

- mosquitto (mosquitto-go-auth). EMQX only.
- A websocket path field: the mail does not carry one, the doc tells
operators to match the listener path.
- Disabling the shared login. That is an operator step after migration,
described in the doc.
- Tested on EMQX 5.8.6 (Docker) and 5.8.9 (production) only.

Note on cb9f4ff3: its message says the scheme problem was reported by an
operator. That report turned out to come from before the broker used the
hook, so it does not show this cause; the change rests on the firmware
source only.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:50:20 +01:00

286 lines
8.8 KiB
Go

package main
import (
"log"
"os"
"path/filepath"
"sync"
"sync/atomic"
"time"
"github.com/meshcore-analyzer/mailer"
"github.com/meshcore-analyzer/users"
)
// authService is the optional user-management layer. Server.auth is nil
// unless userManagement.enabled, and nothing in this file runs then.
type authService struct {
st *users.Store
mail mailer.Mailer
set *userMgmtSettings
ipr *wsLimiter // only its clientIP rule is used
login *rateLimiter
signup *rateLimiter // register, forgot, self-service resend
hook *rateLimiter
settingsPut *rateLimiter // PUT /api/account/settings, per user
companion *rateLimiter // companion challenge + link, per IP and per user
// approved is the snapshot of approved hashtag channel names, filled at
// construction and reloaded from users.db after every proposal decision.
// approvedMu serialises the reloads so an older read never replaces a
// newer one.
approvedMu sync.Mutex
approved atomic.Pointer[[]string]
// notify evaluates node notifications; nil unless
// userManagement.notifications.enabled.
notify *notifier
// obsIdx answers the broker hooks; nil unless observerLogins.enabled
// (or when its load failed, see newAuthService).
obsIdx *observerLoginIndex
touches authTouches
// sealbox seals and opens the stored observer passwords; nil when the
// feature is off or the key is unusable.
sealbox *users.SecretBox
now func() time.Time
warnIndistinct sync.Once
stop chan struct{}
stopOnce sync.Once
wg sync.WaitGroup // the janitor and the notifier
auditWG sync.WaitGroup // in-flight auditAsync writes
}
func newAuthService(set *userMgmtSettings, st *users.Store, m mailer.Mailer) *authService {
a := &authService{
st: st, mail: m, set: set,
ipr: &wsLimiter{trustedProxies: set.trustedProxies},
login: newRateLimiter(10, 15*time.Minute),
signup: newRateLimiter(5, time.Hour),
hook: newRateLimiter(600, time.Minute),
settingsPut: newRateLimiter(60, time.Hour),
companion: newRateLimiter(60, time.Hour),
stop: make(chan struct{}),
now: time.Now,
}
a.refreshApproved()
if set.observerLogins.enabled {
// No error return here: a failed load leaves obsIdx nil, the hook
// routes answer 503 and the broker falls back to its own users.
idx, err := newObserverLoginIndex(st)
if err != nil {
log.Printf("[observer-logins] load logins: %v", err)
} else {
a.obsIdx = idx
}
if a.sealbox, err = users.NewSecretBox(set.observerLogins.key); err != nil {
log.Printf("[observer-logins] secret box: %v", err)
a.sealbox = nil
}
}
return a
}
// initUserManagement builds s.auth when the feature is on. Call it after
// NewServer and before RegisterRoutes. measurementDBPath is passed to
// users.Open as a forbidden path, so users.db can never be the analyzer DB.
func (s *Server) initUserManagement(measurementDBPath string) error {
if !s.cfg.UserManagementEnabled() {
if s.cfg.ClientRxRequireLinkedCompanionSet() {
log.Printf("[users] clientRxCoverage.requireLinkedCompanion is set but userManagement is off: the setting is ignored")
}
return nil
}
set, err := resolveUserManagement(s.cfg.UserManagement, measurementDBPath, os.Getenv)
if err != nil {
return err
}
st, err := users.Open(set.dbPath, measurementDBPath)
if err != nil {
return err
}
var m mailer.Mailer
switch set.provider {
case "fake":
m = &mailer.Fake{}
case "postal":
m = mailer.NewPostal(set.postalBaseURL, set.postalAPIKey, set.fromEmail, set.fromName)
default:
m = mailer.NewBrevo(set.brevoAPIKey, set.fromEmail, set.fromName)
}
s.auth = newAuthService(set, st, m)
s.auth.logStartup()
s.auth.wg.Add(1)
go func() {
defer s.auth.wg.Done()
s.auth.janitor(time.Hour)
}()
if set.notify.enabled {
s.auth.notify = newNotifier(s.auth, serverNotifySource{s: s}, time.Now)
s.auth.wg.Add(1)
go func() {
defer s.auth.wg.Done()
s.auth.notify.loop(s.auth.stop, set.notify.interval)
}()
log.Printf("[notify] node notifications enabled: every %s, at most %d mails per user and %d in total per 24 hours",
set.notify.interval, set.notify.perUserPerDay, set.notify.maxMailsPerDay)
}
return nil
}
// closeUserManagement stops the janitor and closes users.db. Safe when off.
func (s *Server) closeUserManagement() {
if s.auth == nil {
return
}
s.auth.stopOnce.Do(func() {
close(s.auth.stop)
s.auth.wg.Wait()
s.auth.waitAudits()
if err := s.auth.st.Close(); err != nil {
log.Printf("[users] close: %v", err)
}
})
}
func (a *authService) logStartup() {
log.Printf("[users] user management enabled: db=%s, %d config admin(s), webhook=%v",
absForLog(a.set.dbPath), len(a.set.adminEmails), a.set.webhookSecret != "")
admins, err := a.st.List(users.ListFilter{Role: users.RoleAdmin})
if err != nil {
log.Printf("[users] list admins: %v", err)
return
}
for _, u := range admins {
if !a.isConfigAdmin(u.Email) {
log.Printf("[users] note: admin #%d is not in adminEmails (promoted in the UI, or removed from config)", u.ID)
}
}
}
func (a *authService) janitor(every time.Duration) {
t := time.NewTicker(every)
defer t.Stop()
for {
a.prune()
a.maybeBackup(time.Now())
select {
case <-a.stop:
return
case <-t.C:
}
}
}
func (a *authService) prune() {
if _, err := a.st.PruneStalePending(48 * time.Hour); err != nil {
log.Printf("[users] prune pending: %v", err)
}
if _, err := a.st.PruneExpiredSessions(); err != nil {
log.Printf("[users] prune sessions: %v", err)
}
if _, err := a.st.PruneLinkChallenges(); err != nil {
log.Printf("[users] prune link challenges: %v", err)
}
if _, err := a.st.PruneTokens(7 * 24 * time.Hour); err != nil {
log.Printf("[users] prune tokens: %v", err)
}
if _, err := a.st.PruneMail(90 * 24 * time.Hour); err != nil {
log.Printf("[users] prune mail log: %v", err)
}
// Login rows only; every other audit action is kept (admin-dashboard spec).
if _, err := a.st.PruneAudit([]string{"user.login", "user.login.failed"}, 90*24*time.Hour); err != nil {
log.Printf("[users] prune login audit: %v", err)
}
if _, err := a.st.PruneProposals(proposalRetention); err != nil {
log.Printf("[users] prune proposals: %v", err)
}
a.login.gc()
a.signup.gc()
a.hook.gc()
a.settingsPut.gc()
a.companion.gc()
}
func (a *authService) isConfigAdmin(email string) bool { return a.set.adminEmails[email] }
// refreshApproved reloads the approved hashtag channel names from users.db,
// oldest approval first and capped at maxApproved like the ingestor. The
// mutex spans the read and the store, so concurrent decisions cannot leave
// an older read in place. A failure is logged and keeps the previous
// snapshot. No-op with proposals off.
func (a *authService) refreshApproved() {
if !a.set.proposals.enabled {
return
}
a.approvedMu.Lock()
defer a.approvedMu.Unlock()
list, err := a.st.ApprovedSubjects(users.KindHashtagChannel, a.set.proposals.maxApproved)
if err != nil {
log.Printf("[users] load approved channels: %v", err)
return
}
a.approved.Store(&list)
}
// approvedChannels returns the current snapshot; never nil.
func (a *authService) approvedChannels() []string {
if p := a.approved.Load(); p != nil {
return *p
}
return []string{}
}
// roleFor is the role an address gets on activation.
func (a *authService) roleFor(email string) users.Role {
if a.isConfigAdmin(email) {
return users.RoleAdmin
}
return users.RoleUser
}
func (a *authService) audit(actor *int64, action string, target *int64, detail map[string]string) {
if err := a.st.Audit(actor, action, target, detail); err != nil {
log.Printf("[users] audit %s: %v", action, err)
}
}
// auditAsync writes an audit row in the background, so neither the write
// nor a locked users.db delays the response. Best-effort: a failure is
// logged by a.audit, and a row is lost if the process stops first.
func (a *authService) auditAsync(actor *int64, action string, target *int64, detail map[string]string) {
a.auditWG.Add(1)
go func() {
defer a.auditWG.Done()
a.audit(actor, action, target, detail)
}()
}
// waitAudits blocks until every auditAsync write has finished.
func (a *authService) waitAudits() { a.auditWG.Wait() }
func idPtr(id int64) *int64 { return &id }
// invalidateTokens burns uid's outstanding links of each purpose. A failure
// is logged (user id only) and returned; callers answer 500.
func (a *authService) invalidateTokens(op string, uid int64, ps ...users.Purpose) error {
for _, p := range ps {
if err := a.st.InvalidateTokens(uid, p); err != nil {
log.Printf("[users] %s: invalidate %s tokens for user #%d: %v", op, p, uid, err)
return err
}
}
return nil
}
// absForLog resolves path for a log line, so a relative users.db path shows
// which file it means; the path as given when it cannot be resolved.
func absForLog(path string) string {
if abs, err := filepath.Abs(path); err == nil {
return abs
}
return path
}