Files
OwnCord/Server/api/metrics_handler_test.go
T
J3vb c3a8aa477c fix: resolve 20 code review bugs across Rust, TypeScript, and Go
Critical/High Rust (Tauri client):
- BUG-140: replace .run() with .build() + RunEvent::Exit handler; native error dialog on startup failure
- BUG-141: eliminate PTT thread TOCTOU race with Mutex critical section; add AtomicBool shutdown and catch_unwind
- BUG-144: fix TOFU cert store corruption — read-before-write rollback restores previous fingerprint on save failure (all 3 write sites)
- BUG-145: add VK code range guard (1..=254) in is_key_down; fix cast to (state as i16) < 0
- BUG-147: replace bare spawns with JoinSet; abort_all + drain on exit; unconditional closed event
- BUG-150: add CRLF guard in handle_connection before header rewriting
- BUG-151: wrap header read loop in tokio::time::timeout(10s)
- BUG-158: extract CERTS_STORE/SETTINGS_STORE to constants.rs (eliminate 3 duplicates)
- HIGH-2: PTT thread self-cleanup uses unwrap_or_else defensive pattern
- HIGH-4: ws_send distinguishes Full vs Closed errors; warn log on backpressure

Critical/High TypeScript (Tauri client):
- BUG-142: join-generation counter prevents stale connectAndSetup completions
- BUG-143: replace 8 mutable LiveKit session fields with discriminated union SessionState
- BUG-146: 60s token refresh deadline; cleared on reply or voice leave
- BUG-148: ResizeObserver hoisted to outer scope; disconnect() in destroy() before ac.abort()
- BUG-152: dismissSignal.aborted guard already present (no change needed)
- BUG-153: measureRendered split into two-pass read-then-write; eliminates per-message reflow
- BUG-154: WS dedup cache batch-evicts to 80% on overflow (amortised O(1))
- BUG-157: pendingUpdates replaced with coalesced function-composition slot (O(1) queue depth)

Go server:
- BUG-149: safe two-value type assertion in getOutboundIP with localhost fallback
- BUG-155: broadcast buffer 256→1024; broadcastDrops atomic counter exposed in /api/v1/metrics
- BUG-156: LiveKitHealthCheck and implementations accept ctx context.Context; all call sites pass r.Context() (12 files)
- BUG-159: MaxMessageBytes constant in config/constants.go; replaces 1<<20 literals in serve.go and updater.go
- HIGH-1: cert store rollback reads old value before write; restores previous cert on save failure

All validation passes: go build, go vet, cargo check, npm typecheck
2026-04-03 23:18:06 +02:00

119 lines
3.4 KiB
Go

package api_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/go-chi/chi/v5"
"github.com/owncord/server/api"
)
// buildMetricsRouter creates a chi router with the metrics endpoint behind AdminIPRestrict.
func buildMetricsRouter(allowedCIDRs []string) http.Handler {
r := chi.NewRouter()
r.With(api.AdminIPRestrict(allowedCIDRs, nil)).
Get("/api/v1/metrics", api.HandleMetricsForTest(
func() int { return 5 },
func() int { return 2 },
func() uint64 { return 0 },
func(_ context.Context) (bool, error) { return true, nil },
))
return r
}
func TestHandleMetrics_ReturnsExpectedFields(t *testing.T) {
router := buildMetricsRouter(nil) // no IP restriction
req := httptest.NewRequest(http.MethodGet, "/api/v1/metrics", nil)
req.RemoteAddr = "127.0.0.1:9999"
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", rr.Code, rr.Body.String())
}
var resp map[string]any
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
t.Fatalf("decode: %v", err)
}
requiredFields := []string{
"uptime", "uptime_seconds", "goroutines",
"heap_alloc_mb", "heap_sys_mb", "num_gc",
"connected_users", "voice_sessions", "broadcast_drops", "livekit_healthy",
}
for _, f := range requiredFields {
if _, ok := resp[f]; !ok {
t.Errorf("missing field %q in metrics response", f)
}
}
// Verify the callback values are reflected.
if int(resp["connected_users"].(float64)) != 5 {
t.Errorf("connected_users = %v, want 5", resp["connected_users"])
}
if int(resp["voice_sessions"].(float64)) != 2 {
t.Errorf("voice_sessions = %v, want 2", resp["voice_sessions"])
}
if resp["livekit_healthy"] != true {
t.Errorf("livekit_healthy = %v, want true", resp["livekit_healthy"])
}
}
func TestHandleMetrics_AdminIPRestrict_BlocksNonAdmin(t *testing.T) {
router := buildMetricsRouter([]string{"10.0.0.0/8"}) // only 10.x allowed
req := httptest.NewRequest(http.MethodGet, "/api/v1/metrics", nil)
req.RemoteAddr = "192.168.1.1:9999" // not in allowed CIDR
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusForbidden {
t.Errorf("status = %d, want 403; body: %s", rr.Code, rr.Body.String())
}
}
func TestHandleMetrics_AdminIPRestrict_AllowsAdmin(t *testing.T) {
router := buildMetricsRouter([]string{"127.0.0.0/8"})
req := httptest.NewRequest(http.MethodGet, "/api/v1/metrics", nil)
req.RemoteAddr = "127.0.0.1:9999"
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Errorf("status = %d, want 200; body: %s", rr.Code, rr.Body.String())
}
}
func TestHandleMetrics_WithoutLiveKitHealthCheck(t *testing.T) {
r := chi.NewRouter()
r.Get("/api/v1/metrics", api.HandleMetricsForTest(
func() int { return 0 },
func() int { return 0 },
func() uint64 { return 0 },
nil, // no livekit
))
req := httptest.NewRequest(http.MethodGet, "/api/v1/metrics", nil)
req.RemoteAddr = "127.0.0.1:9999"
rr := httptest.NewRecorder()
r.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", rr.Code, rr.Body.String())
}
var resp map[string]any
_ = json.NewDecoder(rr.Body).Decode(&resp)
// livekit_healthy should be absent when no health check is provided.
if _, ok := resp["livekit_healthy"]; ok {
t.Errorf("livekit_healthy should be omitted when health check is nil, got %v", resp["livekit_healthy"])
}
}