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>
162 lines
4.9 KiB
Go
162 lines
4.9 KiB
Go
// Pass 4 follow-up — event pruner unit tests.
|
|
//
|
|
// Covers runPrune correctness (cutoff calculation + error path) and the
|
|
// StartEventPruner goroutine lifecycle (nil store short-circuit, ctx
|
|
// cancellation, startup-delay-bounded-by-interval behaviour introduced
|
|
// in the Copilot review fix).
|
|
package ws
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/owncord/server/db"
|
|
)
|
|
|
|
// fakeEventStore is a minimal EventStore stub that records every prune
|
|
// call and optionally returns a canned error. Only the methods actually
|
|
// exercised by the pruner are implemented; the rest panic so an accidental
|
|
// code path change is noisy.
|
|
type fakeEventStore struct {
|
|
mu sync.Mutex
|
|
pruneCalls int
|
|
lastCutoff time.Time
|
|
pruneReturn int64
|
|
pruneErr error
|
|
pruneSignal chan struct{} // closed (via atomic swap) once a prune happens
|
|
pruneDone atomic.Bool
|
|
}
|
|
|
|
func (f *fakeEventStore) PruneEventsOlderThan(_ context.Context, cutoff time.Time) (int64, error) {
|
|
f.mu.Lock()
|
|
f.pruneCalls++
|
|
f.lastCutoff = cutoff
|
|
ret := f.pruneReturn
|
|
err := f.pruneErr
|
|
f.mu.Unlock()
|
|
if !f.pruneDone.Swap(true) && f.pruneSignal != nil {
|
|
close(f.pruneSignal)
|
|
}
|
|
return ret, err
|
|
}
|
|
|
|
func (f *fakeEventStore) Calls() int {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.pruneCalls
|
|
}
|
|
|
|
func (f *fakeEventStore) LastCutoff() time.Time {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.lastCutoff
|
|
}
|
|
|
|
// Stubs for the rest of the EventStore interface — not exercised here.
|
|
func (*fakeEventStore) PersistEvent(context.Context, int64, string, int64, []byte) error {
|
|
panic("unused")
|
|
}
|
|
|
|
func (*fakeEventStore) GetEventsSince(context.Context, int64, int) ([]db.PersistedEvent, error) {
|
|
panic("unused")
|
|
}
|
|
|
|
func (*fakeEventStore) GetEventsSinceForChannels(context.Context, int64, []int64, int) ([]db.PersistedEvent, error) {
|
|
panic("unused")
|
|
}
|
|
|
|
func (*fakeEventStore) GetMaxEventSeq(context.Context) (int64, error) {
|
|
panic("unused")
|
|
}
|
|
|
|
func TestRunPruneCutoffCalculation(t *testing.T) {
|
|
s := &fakeEventStore{pruneReturn: 3}
|
|
retention := 24 * time.Hour
|
|
|
|
before := time.Now()
|
|
runPrune(context.Background(), s, retention)
|
|
after := time.Now()
|
|
|
|
if s.Calls() != 1 {
|
|
t.Fatalf("expected 1 prune call, got %d", s.Calls())
|
|
}
|
|
cutoff := s.LastCutoff()
|
|
// cutoff must be in the window [before - retention, after - retention].
|
|
minCutoff := before.Add(-retention)
|
|
maxCutoff := after.Add(-retention)
|
|
if cutoff.Before(minCutoff) || cutoff.After(maxCutoff) {
|
|
t.Errorf("cutoff %v not in expected window [%v, %v]", cutoff, minCutoff, maxCutoff)
|
|
}
|
|
}
|
|
|
|
func TestRunPruneErrorDoesNotPanic(t *testing.T) {
|
|
s := &fakeEventStore{pruneErr: errors.New("boom")}
|
|
// Must not panic, must not propagate — error is logged and swallowed
|
|
// so the background goroutine keeps ticking.
|
|
runPrune(context.Background(), s, time.Hour)
|
|
if s.Calls() != 1 {
|
|
t.Fatalf("expected 1 prune call even on error, got %d", s.Calls())
|
|
}
|
|
}
|
|
|
|
func TestStartEventPrunerNilStoreIsNoop(t *testing.T) {
|
|
// Should not spawn a goroutine, should not panic.
|
|
ctx := t.Context()
|
|
StartEventPruner(ctx, nil, time.Hour, time.Hour)
|
|
// If the nil check were missing, calling PruneEventsOlderThan on nil
|
|
// would panic inside the goroutine — but since we don't spawn one,
|
|
// there's nothing to assert beyond "we got here".
|
|
}
|
|
|
|
func TestStartEventPrunerContextCancellation(t *testing.T) {
|
|
s := &fakeEventStore{pruneSignal: make(chan struct{})}
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
// Short interval so startup delay is bounded to the interval (50ms).
|
|
StartEventPruner(ctx, s, time.Hour, 50*time.Millisecond)
|
|
|
|
// Wait for the first prune to happen so we know the goroutine started.
|
|
select {
|
|
case <-s.pruneSignal:
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("pruner did not run within 2s")
|
|
}
|
|
|
|
// Cancel and give the goroutine a moment to exit. There's no direct
|
|
// handle to join on, but we can verify no further prunes happen after
|
|
// a grace period.
|
|
cancel()
|
|
time.Sleep(150 * time.Millisecond)
|
|
callsAfterCancel := s.Calls()
|
|
time.Sleep(200 * time.Millisecond)
|
|
if s.Calls() != callsAfterCancel {
|
|
t.Errorf("pruner kept running after ctx cancel: %d -> %d calls", callsAfterCancel, s.Calls())
|
|
}
|
|
}
|
|
|
|
func TestStartEventPrunerStartupDelayBoundedByInterval(t *testing.T) {
|
|
// With interval=20ms and the uncapped startup delay of 1 minute, the
|
|
// test would have to wait a full minute for the first prune. The
|
|
// Copilot-review fix caps the startup delay at min(interval, 1min),
|
|
// so with interval=20ms the first prune happens within ~20ms.
|
|
s := &fakeEventStore{pruneSignal: make(chan struct{})}
|
|
ctx := t.Context()
|
|
|
|
start := time.Now()
|
|
StartEventPruner(ctx, s, time.Hour, 20*time.Millisecond)
|
|
|
|
select {
|
|
case <-s.pruneSignal:
|
|
elapsed := time.Since(start)
|
|
if elapsed > 500*time.Millisecond {
|
|
t.Errorf("startup delay not bounded by interval: first prune took %v", elapsed)
|
|
}
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("pruner did not run within 2s — startup delay likely not bounded")
|
|
}
|
|
}
|