mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
* 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>
164 lines
5.6 KiB
Go
164 lines
5.6 KiB
Go
package ws_test
|
|
|
|
// reconnect_db_test.go — buffer-miss → DB cold-tier replay integration test.
|
|
//
|
|
// The hub's ring buffer holds 1000 events. When a reconnecting client's
|
|
// last_seq is older than the buffer's oldest entry, EventsSinceFiltered returns
|
|
// nil and handleReconnect falls back to the EventStore. This file verifies that
|
|
// code path end-to-end against a real httptest WebSocket server.
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/coder/websocket"
|
|
|
|
"github.com/owncord/server/auth"
|
|
"github.com/owncord/server/db"
|
|
"github.com/owncord/server/ws"
|
|
)
|
|
|
|
// openEventStoreDB opens an in-memory database with the full migration set so
|
|
// the events table exists. *db.DB satisfies the hub's EventStore interface
|
|
// (D3 removed the store abstraction and its MemStore fake).
|
|
func openEventStoreDB(t *testing.T) *db.DB {
|
|
t.Helper()
|
|
database, err := db.Open(":memory:")
|
|
if err != nil {
|
|
t.Fatalf("db.Open: %v", err)
|
|
}
|
|
t.Cleanup(func() { _ = database.Close() })
|
|
if err := db.Migrate(database); err != nil {
|
|
t.Fatalf("db.Migrate: %v", err)
|
|
}
|
|
return database
|
|
}
|
|
|
|
// TestReconnect_BufferMiss_FallsBackToDBTier verifies that when a client
|
|
// reconnects with a last_seq that is older than the ring buffer's oldest entry,
|
|
// the hub falls back to the EventStore (DB tier) and sends the missed events.
|
|
//
|
|
// Setup:
|
|
// - Ring buffer size = 1000; push seqs 501..1500 → oldestSeq = 501.
|
|
// - The DB event store contains 100 global events at seqs 501..600.
|
|
// - Client reconnects with last_seq = 500.
|
|
// - Buffer: 500 <= 501 → returns nil.
|
|
// - DB: returns seqs > 500 with channelID = 0 (global, no permission filter).
|
|
//
|
|
// Asserts:
|
|
// - auth_ok is received with replay_source = "db".
|
|
// - hub.ReconnectTierStats() db counter = 1.
|
|
func TestReconnect_BufferMiss_FallsBackToDBTier(t *testing.T) {
|
|
database := openServeTestDB(t)
|
|
limiter := auth.NewRateLimiter()
|
|
|
|
// Create a user. role_id=1 intentionally does not exist in the test DB so
|
|
// computeAllowedChannels returns an empty channel set — but events with
|
|
// channelID=0 (global) bypass the per-channel filter in the DB event store
|
|
// and in EventsSinceFiltered, so they are always returned.
|
|
userID, err := database.CreateUser(context.Background(), "reconnect-db-user", "hash", 1)
|
|
if err != nil {
|
|
t.Fatalf("CreateUser: %v", err)
|
|
}
|
|
token, err := auth.GenerateToken()
|
|
if err != nil {
|
|
t.Fatalf("GenerateToken: %v", err)
|
|
}
|
|
if _, err := database.CreateSession(context.Background(), userID, auth.HashToken(token), "test", "127.0.0.1"); err != nil {
|
|
t.Fatalf("CreateSession: %v", err)
|
|
}
|
|
|
|
// Pre-populate the event store with 100 global events (seqs 501..600).
|
|
// channelID=0 means "global broadcast" — the DB event store's
|
|
// GetEventsSinceForChannels returns them regardless of the allowed-channel
|
|
// filter.
|
|
eventStore := openEventStoreDB(t)
|
|
bgCtx := context.Background()
|
|
for seq := int64(501); seq <= 600; seq++ {
|
|
payload := fmt.Appendf(nil, `{"seq":%d,"type":"broadcast"}`, seq)
|
|
if err := eventStore.PersistEvent(bgCtx, seq, "broadcast", 0, payload); err != nil {
|
|
t.Fatalf("PersistEvent seq=%d: %v", seq, err)
|
|
}
|
|
}
|
|
|
|
// Build hub, attach the DB event store as the cold-tier read path.
|
|
hub := ws.NewHub(database, limiter, nil)
|
|
hub.SetEventStore(eventStore)
|
|
go hub.Run()
|
|
defer hub.Stop()
|
|
|
|
// Fill the ring buffer with seqs 501..1500 (exactly 1000 entries).
|
|
// After 1000 pushes into a 1000-slot buffer, oldestSeq = 501 (the first
|
|
// entry pushed). A client with last_seq=500 satisfies 500 <= 501, so
|
|
// EventsSinceFiltered returns nil and the DB tier is invoked.
|
|
rb := hub.ReplayBuffer()
|
|
dummyPayload := []byte(`{"type":"broadcast"}`)
|
|
for seq := uint64(501); seq <= 1500; seq++ {
|
|
rb.Push(seq, 0, dummyPayload)
|
|
}
|
|
if oldest := rb.OldestSeq(); oldest != 501 {
|
|
t.Fatalf("pre-condition: expected oldestSeq=501, got %d", oldest)
|
|
}
|
|
|
|
// Spin up a real HTTP+WS server.
|
|
handler := ws.ServeWS(hub, database, []string{"*"})
|
|
srv := httptest.NewServer(handler)
|
|
defer srv.Close()
|
|
|
|
wsURL := "ws" + strings.TrimPrefix(srv.URL, "http")
|
|
dialCtx, cancel := context.WithTimeout(bgCtx, 10*time.Second)
|
|
defer cancel()
|
|
|
|
// Dial and authenticate with last_seq=500 — this triggers the reconnect
|
|
// path (handleReconnect) rather than the fresh-connect path.
|
|
conn, dialResp, dialErr := websocket.Dial(dialCtx, wsURL, nil)
|
|
if dialResp != nil && dialResp.Body != nil {
|
|
_ = dialResp.Body.Close()
|
|
}
|
|
if dialErr != nil {
|
|
t.Fatalf("websocket.Dial: %v", dialErr)
|
|
}
|
|
defer func() { _ = conn.Close(websocket.StatusNormalClosure, "") }()
|
|
|
|
authMsg := map[string]any{
|
|
"type": "auth",
|
|
"payload": map[string]any{
|
|
"token": token,
|
|
"last_seq": uint64(500),
|
|
},
|
|
}
|
|
raw, _ := json.Marshal(authMsg)
|
|
if err := conn.Write(dialCtx, websocket.MessageText, raw); err != nil {
|
|
t.Fatalf("write auth: %v", err)
|
|
}
|
|
|
|
// The first message back must be auth_ok with replay_source="db".
|
|
_, msg, err := conn.Read(dialCtx)
|
|
if err != nil {
|
|
t.Fatalf("read auth_ok: %v", err)
|
|
}
|
|
var resp map[string]any
|
|
if err := json.Unmarshal(msg, &resp); err != nil {
|
|
t.Fatalf("unmarshal response: %v; raw=%s", err, msg)
|
|
}
|
|
if resp["type"] != "auth_ok" {
|
|
t.Fatalf("expected type=auth_ok, got %v; raw=%s", resp["type"], msg)
|
|
}
|
|
payloadField, _ := resp["payload"].(map[string]any)
|
|
if payloadField["replay_source"] != "db" {
|
|
t.Fatalf("expected replay_source=db, got %v", payloadField["replay_source"])
|
|
}
|
|
|
|
// hub.reconnectTierDB is incremented before auth_ok is sent, so the
|
|
// counter is stable by the time we read auth_ok.
|
|
_, dbTier, _ := hub.ReconnectTierStats()
|
|
if dbTier != 1 {
|
|
t.Fatalf("expected db tier count=1, got %d", dbTier)
|
|
}
|
|
}
|