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.7 KiB
Go
162 lines
4.7 KiB
Go
package updater
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// textAssetServer serves a fixed body at /asset and counts inbound requests.
|
|
// handler may be swapped to simulate an upstream outage.
|
|
func textAssetServer(t *testing.T, fail *atomic.Bool, hits *atomic.Int64) *httptest.Server {
|
|
t.Helper()
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/asset", func(w http.ResponseWriter, _ *http.Request) {
|
|
hits.Add(1)
|
|
if fail.Load() {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
fmt.Fprint(w, "asset-body")
|
|
})
|
|
srv := httptest.NewServer(mux)
|
|
t.Cleanup(srv.Close)
|
|
return srv
|
|
}
|
|
|
|
// A burst of concurrent misses must collapse into a single outbound fetch.
|
|
// Without singleflight each caller fetches independently (W3-1).
|
|
func TestFetchTextAssetCachedCoalescesConcurrentMisses(t *testing.T) {
|
|
var fail atomic.Bool
|
|
var hits atomic.Int64
|
|
srv := textAssetServer(t, &fail, &hits)
|
|
u := newTestUpdater(srv.URL, "1.0.0")
|
|
|
|
const callers = 25
|
|
var wg sync.WaitGroup
|
|
results := make([]string, callers)
|
|
errs := make([]error, callers)
|
|
start := make(chan struct{})
|
|
|
|
for i := range callers {
|
|
wg.Go(func() {
|
|
<-start // release all goroutines together to force a real burst
|
|
results[i], errs[i] = u.FetchTextAssetCached(context.Background(), srv.URL+"/asset")
|
|
})
|
|
}
|
|
close(start)
|
|
wg.Wait()
|
|
|
|
if got := hits.Load(); got != 1 {
|
|
t.Fatalf("outbound fetches = %d, want exactly 1 (singleflight should coalesce)", got)
|
|
}
|
|
for i := range callers {
|
|
if errs[i] != nil {
|
|
t.Fatalf("caller %d: unexpected error: %v", i, errs[i])
|
|
}
|
|
if results[i] != "asset-body" {
|
|
t.Fatalf("caller %d: content = %q, want %q", i, results[i], "asset-body")
|
|
}
|
|
}
|
|
}
|
|
|
|
// A failed fetch must be cached for errorCacheTTL so an upstream outage does
|
|
// not produce one outbound request per caller.
|
|
func TestFetchTextAssetCachedCachesFailures(t *testing.T) {
|
|
var fail atomic.Bool
|
|
var hits atomic.Int64
|
|
srv := textAssetServer(t, &fail, &hits)
|
|
fail.Store(true)
|
|
u := newTestUpdater(srv.URL, "1.0.0")
|
|
url := srv.URL + "/asset"
|
|
|
|
if _, err := u.FetchTextAssetCached(context.Background(), url); err == nil {
|
|
t.Fatal("first call: want error from failing upstream, got nil")
|
|
}
|
|
if _, err := u.FetchTextAssetCached(context.Background(), url); err == nil {
|
|
t.Fatal("second call: want cached error, got nil")
|
|
}
|
|
if got := hits.Load(); got != 1 {
|
|
t.Fatalf("outbound fetches = %d, want 1 (the failure should be cached)", got)
|
|
}
|
|
|
|
// Once the negative entry expires, the upstream is retried — a cached error
|
|
// must not be permanent.
|
|
u.mu.Lock()
|
|
entry := u.textAssetCache[url]
|
|
entry.expiry = time.Now().Add(-time.Second)
|
|
u.textAssetCache[url] = entry
|
|
u.mu.Unlock()
|
|
|
|
fail.Store(false)
|
|
content, err := u.FetchTextAssetCached(context.Background(), url)
|
|
if err != nil {
|
|
t.Fatalf("after negative-cache expiry: unexpected error: %v", err)
|
|
}
|
|
if content != "asset-body" {
|
|
t.Fatalf("content = %q, want %q", content, "asset-body")
|
|
}
|
|
if got := hits.Load(); got != 2 {
|
|
t.Fatalf("outbound fetches = %d, want 2 (retry after expiry)", got)
|
|
}
|
|
}
|
|
|
|
// Asset URLs carry a version, so stale keys must be evicted or the map grows by
|
|
// one entry per release for the process lifetime.
|
|
func TestFetchTextAssetCachedEvictsExpiredKeys(t *testing.T) {
|
|
var fail atomic.Bool
|
|
var hits atomic.Int64
|
|
srv := textAssetServer(t, &fail, &hits)
|
|
u := newTestUpdater(srv.URL, "1.0.0")
|
|
|
|
// A superseded entry from an earlier release, already past its expiry.
|
|
u.mu.Lock()
|
|
u.textAssetCache = map[string]textAssetCacheEntry{
|
|
"https://example.invalid/v0.9.0/chatserver.exe.sig": {
|
|
content: "stale",
|
|
expiry: time.Now().Add(-time.Hour),
|
|
},
|
|
}
|
|
u.mu.Unlock()
|
|
|
|
if _, err := u.FetchTextAssetCached(context.Background(), srv.URL+"/asset"); err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
|
|
u.mu.Lock()
|
|
defer u.mu.Unlock()
|
|
if _, ok := u.textAssetCache["https://example.invalid/v0.9.0/chatserver.exe.sig"]; ok {
|
|
t.Fatal("expired key survived a cache write; it should have been evicted")
|
|
}
|
|
if len(u.textAssetCache) != 1 {
|
|
t.Fatalf("cache size = %d, want 1 (only the fresh entry)", len(u.textAssetCache))
|
|
}
|
|
}
|
|
|
|
// A live cached entry must be served without any outbound request.
|
|
func TestFetchTextAssetCachedServesFromCache(t *testing.T) {
|
|
var fail atomic.Bool
|
|
var hits atomic.Int64
|
|
srv := textAssetServer(t, &fail, &hits)
|
|
u := newTestUpdater(srv.URL, "1.0.0")
|
|
url := srv.URL + "/asset"
|
|
|
|
for range 3 {
|
|
content, err := u.FetchTextAssetCached(context.Background(), url)
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
if content != "asset-body" {
|
|
t.Fatalf("content = %q, want %q", content, "asset-body")
|
|
}
|
|
}
|
|
if got := hits.Load(); got != 1 {
|
|
t.Fatalf("outbound fetches = %d, want 1 (subsequent calls should hit cache)", got)
|
|
}
|
|
}
|