Files
meshcore-analyzer/cmd/server/bearer_auth_test.go
T
efitenandClaude Opus 5.5 b2cda21a27 feat(server): companion linking routes, device tokens and bearer auth (#2175)
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>
2026-10-10 18:20:49 +02:00

117 lines
5.0 KiB
Go

package main
import (
"errors"
"net/http"
"testing"
"time"
"github.com/meshcore-analyzer/users"
)
func TestBearerScopedRoutes(t *testing.T) {
f := newAuthFixture(t)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
tok := f.deviceToken(t, "alice@example.org", pw, "Pixel").Token
foreign := header("Origin", rxOrigin)
w := f.do("GET", "/api/auth/me", nil, bearer(tok))
expectStatus(t, w, http.StatusOK)
if me := decode[meResponse](t, w); me.ID != alice.me.ID || me.CSRFToken != "" {
t.Fatalf("me via bearer = %+v", me)
}
// A write from another origin without any CSRF header: allowed for a bearer.
w = f.do("PUT", "/api/account/settings", settingsPutRequest{Doc: &settingsDoc{V: 1, Keys: map[string]string{"meshcore-theme": "dark"}}},
bearer(tok), foreign)
expectStatus(t, w, http.StatusOK)
expectStatus(t, f.do("GET", "/api/account/settings", nil, bearer(tok)), http.StatusOK)
for _, c := range []struct{ method, path string }{
{"GET", "/api/account/sessions"},
{"PATCH", "/api/account"},
{"POST", "/api/account/password"},
{"DELETE", "/api/account"},
{"GET", "/api/admin/users"},
} {
if w := f.do(c.method, c.path, nil, bearer(tok), foreign); w.Code != http.StatusForbidden {
t.Errorf("%s %s with a device token = %d, want 403", c.method, c.path, w.Code)
}
}
if _, err := f.st.GetByID(alice.me.ID); err != nil {
t.Fatalf("account touched by an out-of-scope request: %v", err)
}
}
func TestBearerRejectsWebAndBadTokens(t *testing.T) {
f := newAuthFixture(t)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
// alice.cookie.Value is a web session token; as a bearer it would skip CSRF.
for _, tok := range []string{alice.cookie.Value, "nonsense", ""} {
if w := f.do("GET", "/api/auth/me", nil, bearer(tok)); w.Code != http.StatusUnauthorized {
t.Errorf("bearer %q = %d, want 401", tok, w.Code)
}
}
}
// A bearer header only counts without a session cookie: an auth proxy that
// adds its own Authorization: Bearer must not break cookie logins.
func TestBearerIgnoredWithCookie(t *testing.T) {
f := newAuthFixture(t, "admin@example.org")
admin := f.registerAndActivate(t, "admin@example.org", "Admin", pw)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
proxy := bearer("id-token-from-a-proxy")
w := f.do("GET", "/api/auth/me", nil, as(alice), proxy)
expectStatus(t, w, http.StatusOK)
if me := decode[meResponse](t, w); me.ID != alice.me.ID || me.CSRFToken == "" {
t.Fatalf("me with cookie + foreign bearer = %+v", me)
}
expectStatus(t, f.do("GET", "/api/account/sessions", nil, as(alice), proxy), http.StatusOK)
expectStatus(t, f.do("GET", "/api/admin/users", nil, as(admin), proxy), http.StatusOK)
// Writes take the cookie path, so the CSRF check applies.
put := settingsPutRequest{Doc: &settingsDoc{V: 1, Keys: map[string]string{"meshcore-theme": "dark"}}}
expectStatus(t, f.do("PUT", "/api/account/settings", put, as(alice), proxy), http.StatusOK)
noCSRF := &client{cookie: alice.cookie}
expectStatus(t, f.do("PUT", "/api/account/settings", put, as(noCSRF), proxy), http.StatusForbidden)
// A device token next to a cookie is not used either: the cookie decides.
tok := f.deviceToken(t, "alice@example.org", pw, "Pixel").Token
expired := &client{cookie: &http.Cookie{Name: sessionCookieName, Value: "stale"}}
expectStatus(t, f.do("GET", "/api/auth/me", nil, as(expired), bearer(tok)), http.StatusUnauthorized)
// Logout ends the cookie session and leaves the device token alone.
expectStatus(t, f.do("POST", "/api/auth/logout", nil, as(alice), bearer(tok)), http.StatusOK)
expectStatus(t, f.do("GET", "/api/auth/me", nil, as(alice)), http.StatusUnauthorized)
expectStatus(t, f.do("GET", "/api/auth/me", nil, bearer(tok)), http.StatusOK)
}
func TestBearerLogoutRevokesDevice(t *testing.T) {
f := newAuthFixture(t)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
tok := f.deviceToken(t, "alice@example.org", pw, "Pixel").Token
expectStatus(t, f.do("POST", "/api/auth/logout", nil, bearer(tok), header("Origin", rxOrigin)), http.StatusOK)
if _, err := f.st.LookupSession(tok); !errors.Is(err, users.ErrNotFound) {
t.Fatalf("device token survived logout: %v", err)
}
expectStatus(t, f.do("GET", "/api/auth/me", nil, bearer(tok)), http.StatusUnauthorized)
expectStatus(t, f.do("GET", "/api/auth/me", nil, as(alice)), http.StatusOK)
// The cookie logout keeps its origin check.
expectStatus(t, f.do("POST", "/api/auth/logout", nil, as(alice), header("Origin", rxOrigin)), http.StatusForbidden)
}
func TestBearerSlidingExpiry(t *testing.T) {
f := newAuthFixture(t)
f.registerAndActivate(t, "alice@example.org", "Alice", pw)
f.st.SetClock(func() time.Time { return time.Now().Add(-80 * 24 * time.Hour) })
tok := f.deviceToken(t, "alice@example.org", pw, "Pixel").Token
f.st.SetClock(time.Now)
expectStatus(t, f.do("GET", "/api/auth/me", nil, bearer(tok)), http.StatusOK)
sess, err := f.st.LookupSession(tok)
if err != nil || sess.ExpiresAt.Before(time.Now().Add(users.DeviceSessionTTL-time.Hour)) {
t.Fatalf("device token not extended on use: %+v, %v", sess, err)
}
}