mirror of
https://github.com/Kpa-clawbot/meshcore-analyzer.git
synced 2026-10-12 11:17:19 +00:00
Part 2 of 3 for #2173 (companion linking): the server routes, bearer auth and the link handshake. Builds on #2174 (merged); `upstream/master` is merged in, so the diff shows only this part. Everything here is behind `userManagement.enabled` and answers 404 with it off. ## Changes in this PR **Device tokens and bearer auth** - `POST /api/auth/device-token`: email + password returns a bearer token, stored as a `kind = 'device'` session with a label. Same failure answers and the same rate limit as login. - Server-enforced scope for a bearer token: `/api/auth/me`, `/api/auth/logout`, `/api/account/companions*`, `/api/account/settings`. Everything else answers 403. - A bearer header only counts when there is no session cookie, so an auth proxy that adds its own `Authorization` header does not hide a logged-in browser. Cookies never accept a device token. - The sessions list on the account API carries `kind` and `label`; logout with a bearer token revokes that device. **Linking a companion** - `POST /api/account/companions/challenge` `{pubkey}` returns `{challenge, expiresAt, host}`: 32 random bytes, single use, 5 minutes, bound to the caller and the pubkey. - `POST /api/account/companions` `{pubkey, challenge, signature, name}`: the signature is the companion's Ed25519 signature over `corescope-link:<host>:<challenge>` (`internal/sigvalidate.VerifyMessage`). The challenge is consumed in every case. - A companion linked to another account moves to the caller (the newest proof wins). Both users get a `companion.transfer` audit row and the previous owner a mail. That mail is a security notice: it is sent whatever the node notification settings are. - `GET /api/account/companions` (with `lastSeenAt` from `client_receptions`) and `DELETE /api/account/companions/{pubkey}`. - Linking does not touch the synced `meshcore-my-nodes`: a companion is not a node to monitor. - Admin user detail lists linked companions; the account data export includes companions and device sessions. **Coverage and config** - `GET /api/rx-coverage?mine=1`: only coverage of the caller's linked companions (401 when logged out, 403 for a device token). With `gaps=1` (#2172) the reply carries no `gaps` member under `mine=1`, because the track query takes one companion and cannot narrow to a set yet (`TestRxCoverageMineOmitsGaps`). - `clientRxCoverage.requireLinkedCompanion` (default off) is read and reported in `/api/config/client`, which also announces `userManagement.companionLinking`, so CoreDrive RX shows its login only where linking exists. The ingestor side is part 3. - CORS: for origins in `corsAllowedOrigins`, the device-token routes alone also allow POST/PUT/DELETE and the `Authorization` and `Content-Type` headers. No credentialed CORS. Documented in `config.example.json`. - OpenAPI and `docs/api-spec.md` cover the new routes. ## Verification - 26 new tests in `cmd/server` and `internal/sigvalidate`, among them: `TestCompanionLinkFlow`, `TestCompanionLinkRejections` (signature by another key, malformed signature, challenge bound to another pubkey, unknown challenge; reuse and expiry are covered by the store tests in #2174), `TestCompanionTransfer`, `TestCompanionTransferMailIgnoresNotificationSettings`, `TestBearerScopedRoutes`, `TestBearerIgnoredWithCookie`, `TestDeviceTokenSharesLoginRateLimit`, `TestCORSBearerRoutes`, `TestCompanionRoutesAbsentWhenOff`, `TestRxCoverageMine`, `TestRxCoverageMineOmitsGaps` (fails without the `mine == nil` guard), `TestVerifyMessage`. - `cmd/server`, `internal/sigvalidate` and `internal/users`: `go vet` and `go test ./...` green, `gofmt` clean. - The linking flow runs on analyzer.on8ar.eu since 9 October 2026 with CoreDrive RX v1.19.0 (a real companion linked through the signed challenge). ## Not in this PR - The ingestor's linked-only filter, the account page (Devices, Companions), the "My coverage" toggle and the user docs: part 3. - Per-user broker credentials and per-user API keys (non-goals in the spec). --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
103 lines
3.6 KiB
Go
103 lines
3.6 KiB
Go
package main
|
|
|
|
import (
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
func TestUserManagementOffIsUnchanged(t *testing.T) {
|
|
srv, router := setupTestServer(t)
|
|
if srv.auth != nil {
|
|
t.Fatal("auth built without config")
|
|
}
|
|
for _, p := range []string{"/api/auth/me", "/api/admin/users", "/api/admin/audit", "/api/admin/stats", "/api/account/sessions", "/api/account/settings", "/api/account/export", "/api/admin/users-backup"} {
|
|
w := httptest.NewRecorder()
|
|
router.ServeHTTP(w, httptest.NewRequest("GET", p, nil))
|
|
if w.Code != 404 {
|
|
t.Errorf("%s = %d with the feature off; want 404", p, w.Code)
|
|
}
|
|
}
|
|
base := httptest.NewRecorder()
|
|
router.ServeHTTP(base, httptest.NewRequest("GET", "/api/config/client", nil))
|
|
if strings.Contains(base.Body.String(), "userManagement") {
|
|
t.Fatal("client config mentions userManagement while off")
|
|
}
|
|
// An explicit {"enabled": false} block is byte-identical to no block.
|
|
dir := t.TempDir()
|
|
srv.cfg.UserManagement = &UserManagementConfig{Enabled: false}
|
|
if err := srv.initUserManagement(filepath.Join(dir, "meshcore.db")); err != nil || srv.auth != nil {
|
|
t.Fatalf("initUserManagement off: auth=%v err=%v", srv.auth, err)
|
|
}
|
|
off := httptest.NewRecorder()
|
|
router.ServeHTTP(off, httptest.NewRequest("GET", "/api/config/client", nil))
|
|
if off.Body.String() != base.Body.String() {
|
|
t.Fatal("client config differs between absent and disabled block")
|
|
}
|
|
if _, err := os.Stat(filepath.Join(dir, "users.db")); !os.IsNotExist(err) {
|
|
t.Fatalf("users.db created next to the measurement DB with the feature off: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestClientConfigAdvertisesUserManagement(t *testing.T) {
|
|
srv, router := setupTestServer(t)
|
|
a, _ := newTestAuthService(t)
|
|
srv.auth = a
|
|
w := httptest.NewRecorder()
|
|
router.ServeHTTP(w, httptest.NewRequest("GET", "/api/config/client", nil))
|
|
if !strings.Contains(w.Body.String(), `"userManagement":{"enabled":true,"companionLinking":true}`) {
|
|
t.Fatalf("client config = %s", w.Body.String())
|
|
}
|
|
}
|
|
|
|
// Through the real router (RegisterRoutes, feature on): auth responses must
|
|
// never be cached by a CDN or browser.
|
|
func TestAuthRoutesThroughRealRouterAreNoStore(t *testing.T) {
|
|
srv, _ := setupTestServer(t)
|
|
a, _ := newTestAuthService(t)
|
|
srv.auth = a
|
|
router := mux.NewRouter()
|
|
srv.RegisterRoutes(router)
|
|
w := httptest.NewRecorder()
|
|
router.ServeHTTP(w, httptest.NewRequest("GET", "/api/auth/me", nil))
|
|
if w.Code == 404 {
|
|
t.Fatalf("/api/auth/me = 404 with the feature on")
|
|
}
|
|
if got := w.Header().Get("Cache-Control"); got != "no-store" {
|
|
t.Fatalf("Cache-Control = %q; want no-store", got)
|
|
}
|
|
}
|
|
|
|
func TestInitUserManagementRefusesMeasurementDB(t *testing.T) {
|
|
dir := t.TempDir()
|
|
measurement := filepath.Join(dir, "meshcore.db")
|
|
os.WriteFile(measurement, nil, 0o644)
|
|
srv := &Server{cfg: &Config{UserManagement: &UserManagementConfig{
|
|
Enabled: true, DBPath: measurement, PublicBaseURL: testBase,
|
|
Mail: UserMailConfig{BrevoAPIKey: "k", FromEmail: "noreply@example.org"},
|
|
}}}
|
|
err := srv.initUserManagement(measurement)
|
|
if err == nil || !strings.Contains(err.Error(), "measurement database") {
|
|
t.Fatalf("err = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestInitUserManagementCreatesUsersDB(t *testing.T) {
|
|
dir := t.TempDir()
|
|
srv := &Server{cfg: &Config{UserManagement: &UserManagementConfig{
|
|
Enabled: true, PublicBaseURL: testBase,
|
|
Mail: UserMailConfig{BrevoAPIKey: "k", FromEmail: "noreply@example.org"},
|
|
}}}
|
|
if err := srv.initUserManagement(filepath.Join(dir, "meshcore.db")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer srv.closeUserManagement()
|
|
if _, err := os.Stat(filepath.Join(dir, "users.db")); err != nil {
|
|
t.Fatalf("users.db not created next to the measurement DB: %v", err)
|
|
}
|
|
}
|