mirror of
https://github.com/Kpa-clawbot/meshcore-analyzer.git
synced 2026-11-11 12:37:33 +00:00
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>
352 lines
11 KiB
Go
352 lines
11 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/gorilla/mux"
|
|
"github.com/meshcore-analyzer/mailer"
|
|
"github.com/meshcore-analyzer/users"
|
|
)
|
|
|
|
// adminStoreFail answers a failed store call: ErrNotFound is 404, anything
|
|
// else is logged (user id only) and answered 500.
|
|
func adminStoreFail(w http.ResponseWriter, op string, id int64, err error) {
|
|
if errors.Is(err, users.ErrNotFound) {
|
|
writeError(w, http.StatusNotFound, "user not found")
|
|
return
|
|
}
|
|
log.Printf("[users] admin %s for user #%d: %v", op, id, err)
|
|
writeError(w, http.StatusInternalServerError, "internal error")
|
|
}
|
|
|
|
// adminTarget loads {id} from the path; writes 400/404/500 and returns nil
|
|
// on failure.
|
|
func (s *Server) adminTarget(w http.ResponseWriter, r *http.Request) *users.User {
|
|
id, err := strconv.ParseInt(mux.Vars(r)["id"], 10, 64)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid user id")
|
|
return nil
|
|
}
|
|
u, err := s.auth.st.GetByID(id)
|
|
if err != nil {
|
|
adminStoreFail(w, "load", id, err)
|
|
return nil
|
|
}
|
|
return u
|
|
}
|
|
|
|
// guardRemoval blocks disabling/deleting/demoting yourself (except a
|
|
// self-demotion, allowed via allowSelf), config admins, and the last active
|
|
// admin. Writes 409 (or 500 if the admin count fails) and returns false
|
|
// when blocked. Count-then-mutate is not atomic; two admins removing each
|
|
// other concurrently can still both pass.
|
|
func (s *Server) guardRemoval(w http.ResponseWriter, actor, target *users.User, allowSelf bool) bool {
|
|
if target.ID == actor.ID && !allowSelf {
|
|
writeError(w, http.StatusConflict, "use My account to change your own account")
|
|
return false
|
|
}
|
|
if target.Role == users.RoleAdmin && s.auth.isConfigAdmin(target.Email) {
|
|
writeError(w, http.StatusConflict, "this admin is listed in adminEmails; remove them from the config first")
|
|
return false
|
|
}
|
|
if target.Role == users.RoleAdmin && target.Status == users.StatusActive {
|
|
n, err := s.auth.st.CountActiveAdmins()
|
|
if err != nil {
|
|
log.Printf("[users] admin guard: count admins for user #%d: %v", target.ID, err)
|
|
writeError(w, http.StatusInternalServerError, "internal error")
|
|
return false
|
|
}
|
|
if n <= 1 {
|
|
writeError(w, http.StatusConflict, "this is the last admin; promote someone else first")
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (s *Server) writeAdminRow(w http.ResponseWriter, id int64) {
|
|
u, err := s.auth.st.GetByID(id)
|
|
if err != nil {
|
|
adminStoreFail(w, "reload", id, err)
|
|
return
|
|
}
|
|
last, err := s.auth.st.LatestMailByUser()
|
|
if err != nil {
|
|
log.Printf("[users] admin latest mail: %v", err)
|
|
}
|
|
writeJSON(w, s.auth.adminRow(*u, last))
|
|
}
|
|
|
|
func (s *Server) handleAdminUsers(w http.ResponseWriter, r *http.Request, _ *users.User, _ *users.Session) {
|
|
q := r.URL.Query()
|
|
f := users.ListFilter{Status: users.Status(q.Get("status")), Role: users.Role(q.Get("role")), Query: q.Get("q")}
|
|
switch f.Status {
|
|
case "", users.StatusPending, users.StatusActive, users.StatusDisabled:
|
|
default:
|
|
writeError(w, http.StatusBadRequest, "invalid status filter")
|
|
return
|
|
}
|
|
if f.Role != "" && !f.Role.Valid() {
|
|
writeError(w, http.StatusBadRequest, "invalid role filter")
|
|
return
|
|
}
|
|
switch q.Get("bouncing") {
|
|
case "":
|
|
case "1":
|
|
f.Bouncing = true
|
|
default:
|
|
writeError(w, http.StatusBadRequest, "invalid bouncing filter")
|
|
return
|
|
}
|
|
list, err := s.auth.st.List(f)
|
|
if err != nil {
|
|
log.Printf("[users] admin list: %v", err)
|
|
writeError(w, http.StatusInternalServerError, "internal error")
|
|
return
|
|
}
|
|
last, err := s.auth.st.LatestMailByUser()
|
|
if err != nil {
|
|
log.Printf("[users] admin latest mail: %v", err)
|
|
}
|
|
out := make([]adminUserJSON, 0, len(list))
|
|
for _, u := range list {
|
|
out = append(out, s.auth.adminRow(u, last))
|
|
}
|
|
writeJSON(w, out)
|
|
}
|
|
|
|
func (s *Server) handleAdminUserDetail(w http.ResponseWriter, r *http.Request, _ *users.User, _ *users.Session) {
|
|
u := s.adminTarget(w, r)
|
|
if u == nil {
|
|
return
|
|
}
|
|
a := s.auth
|
|
last, err := a.st.LatestMailByUser()
|
|
if err != nil {
|
|
log.Printf("[users] admin latest mail: %v", err)
|
|
}
|
|
d := adminUserDetailJSON{User: a.adminRow(*u, last), Sessions: []sessionJSON{}, Mail: []mailJSON{}, Audit: []auditJSON{}}
|
|
list, err := a.st.ListSessions(u.ID)
|
|
if err != nil {
|
|
adminStoreFail(w, "list sessions", u.ID, err)
|
|
return
|
|
}
|
|
for _, x := range list {
|
|
d.Sessions = append(d.Sessions, sessionToJSON(x, 0))
|
|
}
|
|
links, err := a.st.ListCompanionLinks(u.ID)
|
|
if err != nil {
|
|
adminStoreFail(w, "list companions", u.ID, err)
|
|
return
|
|
}
|
|
d.Companions = s.companionsJSON(links)
|
|
mails, err := a.st.MailForUser(u.ID, 50)
|
|
if err != nil {
|
|
adminStoreFail(w, "list mail", u.ID, err)
|
|
return
|
|
}
|
|
for _, m := range mails {
|
|
d.Mail = append(d.Mail, mailToJSON(m))
|
|
}
|
|
entries, err := a.st.AuditFor(u.ID, 100)
|
|
if err != nil {
|
|
adminStoreFail(w, "list audit", u.ID, err)
|
|
return
|
|
}
|
|
for _, e := range entries {
|
|
d.Audit = append(d.Audit, auditJSON{ID: e.ID, At: rfc3339(e.At), ActorUserID: e.ActorUserID,
|
|
Action: e.Action, TargetUserID: e.TargetUserID, Detail: e.Detail})
|
|
}
|
|
writeJSON(w, d)
|
|
}
|
|
|
|
func (s *Server) handleAdminDisable(w http.ResponseWriter, r *http.Request, actor *users.User, _ *users.Session) {
|
|
t := s.adminTarget(w, r)
|
|
if t == nil || !s.guardRemoval(w, actor, t, false) {
|
|
return
|
|
}
|
|
if t.Status != users.StatusActive {
|
|
writeError(w, http.StatusConflict, "only active accounts can be disabled; delete or activate a pending account instead")
|
|
return
|
|
}
|
|
if err := s.auth.invalidateTokens("disable", t.ID, users.PurposeActivate, users.PurposeReset, users.PurposeEmailChange); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal error")
|
|
return
|
|
}
|
|
if err := s.auth.st.SetStatus(t.ID, users.StatusDisabled); err != nil {
|
|
adminStoreFail(w, "disable", t.ID, err)
|
|
return
|
|
}
|
|
if err := s.auth.st.DeleteUserSessions(t.ID, 0); err != nil {
|
|
// currentUser rejects non-active users, so the sessions are dead
|
|
// anyway; keep going but leave a trace.
|
|
log.Printf("[users] disable: delete sessions for user #%d: %v", t.ID, err)
|
|
}
|
|
if s.auth.obsIdx != nil {
|
|
s.auth.obsIdx.setDisabled(t.ID, true)
|
|
}
|
|
s.auth.audit(idPtr(actor.ID), "user.disable", idPtr(t.ID), nil)
|
|
s.writeAdminRow(w, t.ID)
|
|
}
|
|
|
|
func (s *Server) handleAdminEnable(w http.ResponseWriter, r *http.Request, actor *users.User, _ *users.Session) {
|
|
t := s.adminTarget(w, r)
|
|
if t == nil {
|
|
return
|
|
}
|
|
if t.Status != users.StatusDisabled {
|
|
writeError(w, http.StatusConflict, "only disabled accounts can be enabled")
|
|
return
|
|
}
|
|
if err := s.auth.st.SetStatus(t.ID, users.StatusActive); err != nil {
|
|
adminStoreFail(w, "enable", t.ID, err)
|
|
return
|
|
}
|
|
if s.auth.obsIdx != nil {
|
|
s.auth.obsIdx.setDisabled(t.ID, false)
|
|
}
|
|
s.auth.audit(idPtr(actor.ID), "user.enable", idPtr(t.ID), nil)
|
|
s.writeAdminRow(w, t.ID)
|
|
}
|
|
|
|
func (s *Server) handleAdminDelete(w http.ResponseWriter, r *http.Request, actor *users.User, _ *users.Session) {
|
|
t := s.adminTarget(w, r)
|
|
if t == nil || !s.guardRemoval(w, actor, t, false) {
|
|
return
|
|
}
|
|
if err := s.auth.st.Delete(t.ID); err != nil {
|
|
adminStoreFail(w, "delete", t.ID, err)
|
|
return
|
|
}
|
|
if s.auth.obsIdx != nil {
|
|
s.auth.obsIdx.removeUser(t.ID)
|
|
}
|
|
s.auth.audit(idPtr(actor.ID), "user.delete", idPtr(t.ID), nil)
|
|
writeJSON(w, okResponse{OK: true})
|
|
}
|
|
|
|
func (s *Server) handleAdminRole(w http.ResponseWriter, r *http.Request, actor *users.User, _ *users.Session) {
|
|
t := s.adminTarget(w, r)
|
|
if t == nil {
|
|
return
|
|
}
|
|
var req roleRequest
|
|
if !decodeJSON(w, r, &req) {
|
|
return
|
|
}
|
|
if !req.Role.Valid() {
|
|
writeError(w, http.StatusBadRequest, "role must be user or admin")
|
|
return
|
|
}
|
|
// Activation sets the role from adminEmails, so a change now would be
|
|
// silently lost.
|
|
if t.Status == users.StatusPending {
|
|
writeError(w, http.StatusConflict, "activate the account first")
|
|
return
|
|
}
|
|
if req.Role == t.Role {
|
|
s.writeAdminRow(w, t.ID)
|
|
return
|
|
}
|
|
if req.Role == users.RoleUser && !s.guardRemoval(w, actor, t, true) {
|
|
return
|
|
}
|
|
if err := s.auth.st.SetRole(t.ID, req.Role); err != nil {
|
|
adminStoreFail(w, "set role", t.ID, err)
|
|
return
|
|
}
|
|
s.auth.audit(idPtr(actor.ID), "user.role", idPtr(t.ID), map[string]string{"role": string(req.Role)})
|
|
s.writeAdminRow(w, t.ID)
|
|
}
|
|
|
|
func (s *Server) handleAdminResendActivation(w http.ResponseWriter, r *http.Request, actor *users.User, _ *users.Session) {
|
|
a := s.auth
|
|
t := s.adminTarget(w, r)
|
|
if t == nil {
|
|
return
|
|
}
|
|
if t.Status != users.StatusPending {
|
|
writeError(w, http.StatusConflict, "only pending accounts need activation")
|
|
return
|
|
}
|
|
if err := a.mailToken(r.Context(), t, users.PurposeActivate, 48*time.Hour, "", "activate",
|
|
func(tok string) mailer.Message { return a.activationMail(t, tok) }); err != nil {
|
|
writeError(w, http.StatusServiceUnavailable, msgMailFailed)
|
|
return
|
|
}
|
|
a.audit(idPtr(actor.ID), "user.activation.resend", idPtr(t.ID), nil)
|
|
s.writeAdminRow(w, t.ID)
|
|
}
|
|
|
|
// handleAdminActivate activates a pending user without the mail link, for
|
|
// when mail keeps failing. The address stays unverified; activated_by and
|
|
// the audit row keep that visible.
|
|
func (s *Server) handleAdminActivate(w http.ResponseWriter, r *http.Request, actor *users.User, _ *users.Session) {
|
|
a := s.auth
|
|
t := s.adminTarget(w, r)
|
|
if t == nil {
|
|
return
|
|
}
|
|
if t.Status != users.StatusPending {
|
|
writeError(w, http.StatusConflict, "only pending accounts can be activated")
|
|
return
|
|
}
|
|
if err := a.st.InvalidateTokens(t.ID, users.PurposeActivate); err != nil {
|
|
log.Printf("[users] manual activate: invalidate tokens for user #%d: %v", t.ID, err)
|
|
writeError(w, http.StatusInternalServerError, "internal error")
|
|
return
|
|
}
|
|
if err := a.st.Activate(t.ID, a.roleFor(t.Email), idPtr(actor.ID)); err != nil {
|
|
adminStoreFail(w, "activate", t.ID, err)
|
|
return
|
|
}
|
|
a.audit(idPtr(actor.ID), "user.activate.manual", idPtr(t.ID), nil)
|
|
s.writeAdminRow(w, t.ID)
|
|
}
|
|
|
|
func (s *Server) handleAdminMailRefresh(w http.ResponseWriter, r *http.Request, actor *users.User, _ *users.Session) {
|
|
a := s.auth
|
|
t := s.adminTarget(w, r)
|
|
if t == nil {
|
|
return
|
|
}
|
|
mailID, err := strconv.ParseInt(mux.Vars(r)["mailId"], 10, 64)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid mail id")
|
|
return
|
|
}
|
|
rec, err := a.st.MailByID(mailID)
|
|
if err != nil && !errors.Is(err, users.ErrNotFound) {
|
|
log.Printf("[users] admin mail refresh: load mail %d for user #%d: %v", mailID, t.ID, err)
|
|
writeError(w, http.StatusInternalServerError, "internal error")
|
|
return
|
|
}
|
|
if err != nil || rec.UserID == nil || *rec.UserID != t.ID {
|
|
writeError(w, http.StatusNotFound, "mail not found")
|
|
return
|
|
}
|
|
if rec.ProviderMessageID == "" {
|
|
writeError(w, http.StatusConflict, "this mail has no provider message id")
|
|
return
|
|
}
|
|
evs, err := a.mail.Events(r.Context(), rec.ProviderMessageID)
|
|
if err != nil {
|
|
log.Printf("[users] admin mail refresh: provider events for user #%d: %s", t.ID, redactAddrs(err))
|
|
writeError(w, http.StatusBadGateway, "mail provider unavailable")
|
|
return
|
|
}
|
|
a.ingestMailEvents(evs)
|
|
a.audit(idPtr(actor.ID), "user.mail.refresh", idPtr(t.ID), nil)
|
|
rec, err = a.st.MailByID(mailID)
|
|
if err != nil {
|
|
log.Printf("[users] admin mail refresh: reload mail %d for user #%d: %v", mailID, t.ID, err)
|
|
writeError(w, http.StatusInternalServerError, "internal error")
|
|
return
|
|
}
|
|
writeJSON(w, mailToJSON(*rec))
|
|
}
|