Files
OwnCord/Server/ws/handler_v2_migration_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

152 lines
5.4 KiB
Go

package ws
// handler_v2_migration_test.go — unit tests for the three handlers ported from
// V1 to V2 in the dispatch-migration finish (audit A-2026-07-09 / backlog 11):
// chat_command, voice_join, voice_leave.
import (
"context"
"encoding/json"
"testing"
"github.com/owncord/server/auth"
)
// ── voice_join V2 ────────────────────────────────────────────────────────────
// The V2 handler is a thin gate: the constructor validates channel_id and the
// handler hands off to the hub's handleVoiceJoin routine via Result.JoinVoice.
func TestHandleVoiceJoinV2_SignalsJoin(t *testing.T) {
result := handleVoiceJoinV2(context.Background(), VoiceJoinCmd{userID: 1, channelID: 7}, ClientInfo{UserID: 1}, VoiceDeps{})
if result.Error != nil {
t.Fatalf("unexpected error: %v", result.Error)
}
if !result.JoinVoice {
t.Error("expected JoinVoice=true so the applier runs handleVoiceJoin")
}
if result.LeaveVoice {
t.Error("voice_join must not signal LeaveVoice")
}
}
// voice_join parse errors are surfaced by the constructor (before dispatch).
func TestVoiceJoinConstructor_Errors(t *testing.T) {
ctor, ok := getCommandConstructor(MsgTypeVoiceJoin)
if !ok {
t.Fatal("no constructor for voice_join")
}
for _, raw := range []string{`{"channel_id":"nope"}`, `{"channel_id":0}`, `{"channel_id":-3}`} {
if _, err := ctor(1, "r", json.RawMessage(raw)); err == nil {
t.Errorf("expected parse error for %s", raw)
}
}
cmd, err := ctor(1, "r", json.RawMessage(`{"channel_id":42}`))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if cmd.(VoiceJoinCmd).ChannelID() != 42 {
t.Errorf("ChannelID() = %d, want 42", cmd.(VoiceJoinCmd).ChannelID())
}
}
// ── voice_leave V2 ───────────────────────────────────────────────────────────
func TestHandleVoiceLeaveV2_SignalsLeave(t *testing.T) {
deps := VoiceDeps{Limiter: auth.NewRateLimiter()}
result := handleVoiceLeaveV2(context.Background(), VoiceLeaveCmd{userID: 1}, ClientInfo{UserID: 1}, deps)
if result.Error != nil {
t.Fatalf("unexpected error: %v", result.Error)
}
if !result.LeaveVoice {
t.Error("expected LeaveVoice=true so the applier runs handleVoiceLeave")
}
if result.JoinVoice {
t.Error("voice_leave must not signal JoinVoice")
}
}
// The rate-limit that used to live in the V1 dispatch wrapper now lives in the
// V2 handler; disconnect/switch callers of handleVoiceLeave bypass it entirely.
func TestHandleVoiceLeaveV2_RateLimited(t *testing.T) {
deps := VoiceDeps{Limiter: auth.NewRateLimiter()}
cmd := VoiceLeaveCmd{userID: 1}
info := ClientInfo{UserID: 1}
// voiceLeaveRateLimit (5) per voiceLeaveWindow (1s) — the 6th is rejected.
var limited bool
for range voiceLeaveRateLimit + 1 {
res := handleVoiceLeaveV2(context.Background(), cmd, info, deps)
if res.Error != nil {
ce, ok := res.Error.(ClientError)
if !ok || ce.Code != ErrCodeRateLimited {
t.Fatalf("expected rate-limit ClientError, got %v", res.Error)
}
limited = true
}
}
if !limited {
t.Error("expected voice_leave to be rate limited after the burst")
}
}
// ── chat_command V2 ──────────────────────────────────────────────────────────
func TestChatCommandConstructor_Errors(t *testing.T) {
ctor, ok := getCommandConstructor(MsgTypeChatCommand)
if !ok {
t.Fatal("no constructor for chat_command")
}
if _, err := ctor(1, "r", json.RawMessage(`"not-an-object"`)); err == nil {
t.Error("expected error for malformed payload")
}
if _, err := ctor(1, "r", json.RawMessage(`{"command":" "}`)); err == nil {
t.Error("expected error for empty command")
}
tooMany := make([]string, maxCommandArgs+1)
payload, _ := json.Marshal(map[string]any{"command": "/x", "args": tooMany})
if _, err := ctor(1, "r", payload); err == nil {
t.Error("expected error for too many args")
}
cmd, err := ctor(1, "req-9", json.RawMessage(`{"channel_id":5,"command":" /hi ","args":["a","b"]}`))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
cc := cmd.(ChatCommandCmd)
if cc.ChannelID() != 5 || cc.Command() != "/hi" || cc.ReqID() != "req-9" || len(cc.Args()) != 2 {
t.Errorf("unexpected command fields: %+v", cc)
}
}
func TestHandleChatCommandV2_NoRegistry(t *testing.T) {
deps := PluginDeps{Registry: nil, MessageSvc: nil}
cmd := ChatCommandCmd{userID: 1, channelID: 1, command: "/hi"}
result := handleChatCommandV2(context.Background(), cmd, ClientInfo{UserID: 1}, deps)
ce, ok := result.Error.(ClientError)
if !ok {
t.Fatalf("expected ClientError, got %T", result.Error)
}
if ce.Code != ErrCodeBadRequest {
t.Errorf("expected BAD_REQUEST, got %q", ce.Code)
}
if result.Reply != nil || len(result.Events) != 0 {
t.Error("no reply or events expected when no registry is wired")
}
}
// canPluginBroadcast fails closed when the posting-gate service is absent.
func TestCanPluginBroadcast_NilServiceFailsClosed(t *testing.T) {
gate := canPluginBroadcast(context.Background(), nil, 1, 2)
if gate == nil {
t.Fatal("expected a forbidden Result when MessageSvc is nil")
}
ce, ok := gate.Error.(ClientError)
if !ok || ce.Code != ErrCodeForbidden {
t.Errorf("expected FORBIDDEN ClientError, got %v", gate.Error)
}
}