Files
OwnCord/Server/ws/pubsub_test.go
T
J3vbandClaude Opus 4.8 58005c9c6f feat(auth): revocable API tokens, introspect MCP server, and a Go 1.26 idiom pass (#1266)
* feat(auth): add revocable API tokens (bot/service auth)

Add long-lived, revocable API tokens so headless clients (the introspection
MCP tool, bots, CI) can authenticate without a password. Presented as
"Authorization: Bearer <token>", a token authenticates as a specific user,
inheriting that user's role and permissions.

- migration 018 + dedicated api_tokens table (kept separate from sessions so
  bulk logout and the per-user session cap never touch these); only the
  SHA-256 hash is stored, raw token shown once at creation
- auth.ResolveTokenHash: one shared bearer resolver that both AuthMiddleware
  and adminAuthMiddleware now call. Sessions are matched first so existing
  login behavior is unchanged; API tokens are a fallback only on session miss.
  A DB outage is returned wrapped, never mistaken for a bad token.
- `server token create|list|revoke` CLI: mints directly against the DB with no
  HTTP and no login — the password-free bootstrap path
- tests: resolver (8 cases incl. outage-not-fallthrough), db queries (6),
  api middleware integration (valid + revoked token)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(tools): add owncord-introspect MCP server

A local MCP dev tool that lets Claude Code introspect a running OwnCord
instance: read its logs, query any REST endpoint, and tail the desktop
client's log file. It is a thin wrapper over the existing API plus the
client log — no new product surface.

- tools/mcp-introspect/index.mjs (Node/ESM, one dep: @modelcontextprotocol/sdk)
  exposes api_request (full read-write passthrough), server_logs (admin SSE
  ring-buffer stream), client_logs (reads the desktop log file)
- authenticates with an API token (OWNCORD_API_TOKEN); pins the self-signed
  cert and skips hostname checks (the cert has no SAN)
- registered in .mcp.json (secret-free ${OWNCORD_API_TOKEN})
- un-ignore tools/mcp-introspect/ so this shared dev tool is committed, while
  tools/livekit-server.exe and node_modules stay ignored
- docs/mcp-introspect.md: how it works, tool reference, setup, troubleshooting

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(dependencies): update and add various crate versions in Cargo.lock

* feat(admin): manage API tokens from the admin panel

Add Owner-gated HTTP endpoints and a UI card to create, list, and revoke
API tokens from the web admin panel. Previously only the `server token`
CLI could manage them, which requires shell access to the host.

- POST|GET|DELETE /admin/api/tokens in admin/handlers_tokens.go, wired in
  admin/api.go. All three are Owner-only (ownerOnlyMiddleware, like
  backups/updates): an HTTP token-mint endpoint is a network-reachable
  credential-minting surface, and API tokens deliberately survive password
  change + bulk logout, so a hijacked admin session must not mint one.
- Reuses the same db.*APIToken calls as the CLI; create sources the actor
  from request context (audits who clicked, not the bound user); the raw
  token is returned once in the 201 body, never stored.
- Add json tags to db.APITokenListItem for snake_case wire consistency.
- Admin panel: "API Tokens" nav item + create modal, show-once reveal,
  revoke confirm in admin/static/index.html.
- Tests: 7 in admin/api_test.go (+api_tokens table in the in-memory schema).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor: modernize to Go 1.26 idioms + enable modernize linter

Apply `golangci-lint modernize` autofixes across the server and enable the
linter in .golangci.yml so these stop re-accumulating (they built up only
because modernize was never in the config).

Production code: slices.Contains for hand-rolled membership loops (api
router, ws origin, db/account, plugin manifest); strings.SplitSeq for
allocation-free line/segment iteration (db/migrate, updater, livekit_proxy);
strings.Cut (config); fmt.Appendf (dm_handler); min() (event_pruner);
any (ws client). Tests: range-over-int, t.Context(), WaitGroup.Go,
slices.Sort, maps.Copy, new(expr), interface{}->any.

- plugin/manifest.go parent-traversal check applied by hand: modernize
  skipped it (two conflicting rewrites); used the slices.Contains form.
- Removed the now-dead ptr() test helper after newexpr inlined its callers.
- Dropped dangling sort imports left by the sort.Slice->slices.Sort rewrite.

No behavior change. All four tag variants build, full test suite is green,
and golangci-lint (with modernize enabled) reports 0 issues.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-29 13:25:46 +02:00

310 lines
7.8 KiB
Go

package ws
import (
"bytes"
"slices"
"sync"
"testing"
"time"
)
func newTestPubSub() *PubSub {
return NewPubSub()
}
func makeTestClient(userID int64) *Client {
return &Client{
userID: userID,
send: make(chan []byte, 16),
sendHigh: make(chan []byte, 16),
sendLow: make(chan []byte, 16),
}
}
// ─── Subscribe / Unsubscribe ─────────────────────────────────────────────────
func TestPubSub_Subscribe(t *testing.T) {
ps := newTestPubSub()
c := makeTestClient(1)
ps.Subscribe(c, "channel:42")
if n := ps.SubscriberCount("channel:42"); n != 1 {
t.Fatalf("SubscriberCount = %d, want 1", n)
}
}
func TestPubSub_SubscribeIdempotent(t *testing.T) {
ps := newTestPubSub()
c := makeTestClient(1)
ps.Subscribe(c, "channel:42")
ps.Subscribe(c, "channel:42") // duplicate
if n := ps.SubscriberCount("channel:42"); n != 1 {
t.Fatalf("SubscriberCount = %d after double subscribe, want 1", n)
}
}
func TestPubSub_Unsubscribe(t *testing.T) {
ps := newTestPubSub()
c := makeTestClient(1)
ps.Subscribe(c, "channel:42")
ps.Unsubscribe(c, "channel:42")
if n := ps.SubscriberCount("channel:42"); n != 0 {
t.Fatalf("SubscriberCount = %d after unsubscribe, want 0", n)
}
}
func TestPubSub_UnsubscribeNonExistent(t *testing.T) {
ps := newTestPubSub()
c := makeTestClient(1)
// Should not panic.
ps.Unsubscribe(c, "channel:99")
}
func TestPubSub_UnsubscribeAll(t *testing.T) {
ps := newTestPubSub()
c := makeTestClient(1)
ps.Subscribe(c, "channel:1")
ps.Subscribe(c, "channel:2")
ps.Subscribe(c, TopicGlobal)
ps.UnsubscribeAll(c)
if n := ps.SubscriberCount("channel:1"); n != 0 {
t.Fatalf("channel:1 still has %d subscribers", n)
}
if n := ps.SubscriberCount("channel:2"); n != 0 {
t.Fatalf("channel:2 still has %d subscribers", n)
}
if n := ps.SubscriberCount(TopicGlobal); n != 0 {
t.Fatalf("global still has %d subscribers", n)
}
if topics := ps.TopicsForClient(1); len(topics) != 0 {
t.Fatalf("client still has topics: %v", topics)
}
}
func TestPubSub_UnsubscribeAllEmpty(t *testing.T) {
ps := newTestPubSub()
c := makeTestClient(99)
// Should not panic on client with no subscriptions.
ps.UnsubscribeAll(c)
}
// ─── Publish ─────────────────────────────────────────────────────────────────
func TestPubSub_Publish(t *testing.T) {
ps := newTestPubSub()
c1 := makeTestClient(1)
c2 := makeTestClient(2)
c3 := makeTestClient(3) // not subscribed
ps.Subscribe(c1, "channel:42")
ps.Subscribe(c2, "channel:42")
msg := []byte(`{"type":"chat"}`)
delivered := ps.Publish("channel:42", msg, 0)
if delivered != 2 {
t.Fatalf("delivered = %d, want 2", delivered)
}
assertChanMsg(t, c1.send, msg)
assertChanMsg(t, c2.send, msg)
assertChanEmpty(t, c3.send)
}
func TestPubSub_PublishExclude(t *testing.T) {
ps := newTestPubSub()
c1 := makeTestClient(1)
c2 := makeTestClient(2)
ps.Subscribe(c1, "channel:42")
ps.Subscribe(c2, "channel:42")
msg := []byte(`{"type":"typing"}`)
delivered := ps.Publish("channel:42", msg, 1) // exclude user 1
if delivered != 1 {
t.Fatalf("delivered = %d, want 1", delivered)
}
assertChanEmpty(t, c1.send)
assertChanMsg(t, c2.send, msg)
}
func TestPubSub_PublishEmptyTopic(t *testing.T) {
ps := newTestPubSub()
delivered := ps.Publish("channel:999", []byte(`{}`), 0)
if delivered != 0 {
t.Fatalf("delivered = %d for empty topic, want 0", delivered)
}
}
func TestPubSub_PublishGlobal(t *testing.T) {
ps := newTestPubSub()
c1 := makeTestClient(1)
c2 := makeTestClient(2)
ps.Subscribe(c1, TopicGlobal)
ps.Subscribe(c2, TopicGlobal)
msg := []byte(`{"type":"presence"}`)
delivered := ps.PublishGlobal(msg)
if delivered != 2 {
t.Fatalf("delivered = %d, want 2", delivered)
}
assertChanMsg(t, c1.send, msg)
assertChanMsg(t, c2.send, msg)
}
func TestPubSub_PublishLow(t *testing.T) {
ps := newTestPubSub()
c1 := makeTestClient(1)
// c2 has a tiny low-priority buffer that we pre-fill.
c2 := &Client{userID: 2, send: make(chan []byte, 16), sendHigh: make(chan []byte, 4), sendLow: make(chan []byte, 1)}
ps.Subscribe(c1, "channel:1")
ps.Subscribe(c2, "channel:1")
// Fill c2's low-priority buffer so it drops.
c2.sendLow <- []byte(`filler`)
msg := []byte(`{"type":"typing"}`)
delivered := ps.PublishLow("channel:1", msg, 0)
// Both get counted (sendLowMsg counts the attempt), but c2's message was dropped.
if delivered != 2 {
t.Fatalf("delivered = %d, want 2", delivered)
}
assertChanMsg(t, c1.sendLow, msg)
// c2's sendLow only has the filler, not the typing msg.
assertChanMsg(t, c2.sendLow, []byte(`filler`))
assertChanEmpty(t, c2.sendLow)
}
func TestPubSub_PublishHigh(t *testing.T) {
ps := newTestPubSub()
c1 := makeTestClient(1)
c2 := makeTestClient(2)
ps.Subscribe(c1, UserTopic(1))
ps.Subscribe(c2, UserTopic(1))
msg := []byte(`{"type":"dm"}`)
delivered := ps.PublishHigh(UserTopic(1), msg, 0)
if delivered != 2 {
t.Fatalf("delivered = %d, want 2", delivered)
}
assertChanMsg(t, c1.sendHigh, msg)
assertChanMsg(t, c2.sendHigh, msg)
}
// ─── TopicsForClient ─────────────────────────────────────────────────────────
func TestPubSub_TopicsForClient(t *testing.T) {
ps := newTestPubSub()
c := makeTestClient(1)
ps.Subscribe(c, TopicGlobal)
ps.Subscribe(c, "channel:10")
ps.Subscribe(c, UserTopic(1))
topics := ps.TopicsForClient(1)
slices.Sort(topics)
expected := []Topic{"channel:10", TopicGlobal, UserTopic(1)}
if len(topics) != len(expected) {
t.Fatalf("topics = %v, want %v", topics, expected)
}
for i := range expected {
if topics[i] != expected[i] {
t.Fatalf("topics[%d] = %q, want %q", i, topics[i], expected[i])
}
}
}
// ─── Topic helpers ───────────────────────────────────────────────────────────
func TestChannelTopic(t *testing.T) {
if got := ChannelTopic(42); got != "channel:42" {
t.Fatalf("ChannelTopic(42) = %q", got)
}
}
func TestVoiceTopic(t *testing.T) {
if got := VoiceTopic(7); got != "voice:7" {
t.Fatalf("VoiceTopic(7) = %q", got)
}
}
func TestUserTopic(t *testing.T) {
if got := UserTopic(123); got != "user:123" {
t.Fatalf("UserTopic(123) = %q", got)
}
}
// ─── Concurrency safety ─────────────────────────────────────────────────────
func TestPubSub_ConcurrentAccess(t *testing.T) {
ps := newTestPubSub()
const N = 50
var wg sync.WaitGroup
wg.Add(N * 3) // subscribe + publish + unsubscribe
for i := range N {
c := makeTestClient(int64(i))
go func() {
defer wg.Done()
ps.Subscribe(c, "channel:1")
}()
go func() {
defer wg.Done()
ps.Publish("channel:1", []byte(`{"x":1}`), 0)
}()
go func(c *Client) {
defer wg.Done()
ps.UnsubscribeAll(c)
}(c)
}
wg.Wait()
// No panics or data races = pass. (Run with -race.)
}
// ─── helpers ─────────────────────────────────────────────────────────────────
func assertChanMsg(t *testing.T, ch <-chan []byte, want []byte) {
t.Helper()
select {
case got := <-ch:
if !bytes.Equal(got, want) {
t.Errorf("got %q, want %q", got, want)
}
case <-time.After(100 * time.Millisecond):
t.Error("expected message but channel was empty")
}
}
func assertChanEmpty(t *testing.T, ch <-chan []byte) {
t.Helper()
select {
case msg := <-ch:
t.Errorf("expected empty channel but got %q", msg)
default:
// ok
}
}