Files
OwnCord/Server/api/diagnostics_handler_test.go
T
Claude 46aeccc49b fix(phase-bc): address review findings — auth, SSRF, seq alignment
Phase B + C review pass: critical security and correctness fixes.

Security
- S1: plugin admin endpoints now require admin.RequireAdminAuth in addition
  to AdminIPRestrict. Previously a LAN attacker on the allowed CIDR could
  list/enable/disable/uninstall plugins without a session.
- S2: rewrite plugin HTTPDo allowlist with proper net/url parsing. Empty
  entries are ignored, suffix matches require a dot boundary, and a custom
  Dialer rejects loopback / RFC1918 / link-local addresses to close the
  DNS-rebinding TOCTOU window. Redirects re-validated.
- S3 + #9: manifest Name pinned to ^[a-z0-9][a-z0-9_-]{0,63}$, Entrypoint
  and UI tab assets validated against absolute / "..", NUL byte, backslash
  and non-canonical paths. Asset handler hardened with filepath.Rel check
  for symlink and prefix-without-separator escapes.
- S5: pluginBridge postMessage handler ignores the pluginId in the message
  body and uses an e.source -> contentWindow lookup instead, defeating
  spoofed messages from same-origin scripts.
- S8: HTTPDo body capped at 5 MiB via io.LimitReader, redirects bounded
  to 5 hops.

Correctness
- Critical seq alignment: PersistEvent now takes the hub-assigned seq as a
  required parameter so the events table row seq always matches the wrapped
  payload seq. Hub seeds its in-memory atomic counter from MAX(events.seq)
  on startup. Drops in the persister queue no longer mis-align row vs
  payload seq.
- #1: live plugin.Registry constructed in main.go BEFORE NewRouter and
  threaded through; admin handler is no longer wired with nil.
- #3: EventPersister.Stop is now safe to call without a prior Start by
  tracking a started flag — previously deadlocked waiting on done.

Wiring
- NewRouter signature gains *plugin.Registry; two test callers updated.
- admin.RequireAdminAuth exported as a thin wrapper over the existing
  package-private adminAuthMiddleware.
- sqlc query templates updated for the new PersistEvent + GetMaxEventSeq
  contracts (sqlite + postgres).

https://claude.ai/code/session_01UsBsQW2YiA2usk9pnJjAWk
2026-04-06 09:29:29 +00:00

130 lines
3.5 KiB
Go

package api_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/owncord/server/api"
"github.com/owncord/server/auth"
"github.com/owncord/server/config"
"github.com/owncord/server/db"
)
// setupDiagnosticsRouter creates a full router with an authenticated user for
// diagnostics testing.
func setupDiagnosticsRouter(t *testing.T) (http.Handler, string) {
t.Helper()
database, err := db.Open(":memory:")
if err != nil {
t.Fatalf("db.Open: %v", err)
}
if err := db.Migrate(database); err != nil {
t.Fatalf("db.Migrate: %v", err)
}
t.Cleanup(func() { _ = database.Close() })
cfg := &config.Config{
Server: config.ServerConfig{
Name: "Test Server",
Port: 8443,
},
}
handler, _, cleanup := api.NewRouter(cfg, database, "1.0.0-test", nil, nil)
t.Cleanup(cleanup)
// Create a user and session for authenticated requests.
uid, _ := database.CreateUser("diaguser", "$2a$12$fake", 1)
token := "diagtest-token-123"
hash := auth.HashToken(token)
_, _ = database.Exec(
`INSERT INTO sessions (user_id, token, device, ip_address, expires_at)
VALUES (?, ?, 'test', '127.0.0.1', '2099-01-01T00:00:00Z')`,
uid, hash,
)
return handler, token
}
func TestDiagnosticsConnectivity_ReturnsData(t *testing.T) {
router, token := setupDiagnosticsRouter(t)
req := httptest.NewRequest(http.MethodGet, "/api/v1/diagnostics/connectivity", nil)
req.Header.Set("Authorization", "Bearer "+token)
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)
}
// Verify top-level sections exist.
for _, section := range []string{"server", "voice", "client"} {
if _, ok := resp[section]; !ok {
t.Errorf("missing section %q in diagnostics response", section)
}
}
// Verify server section has expected fields.
server, _ := resp["server"].(map[string]any)
if server["version"] != "1.0.0-test" {
t.Errorf("server.version = %v, want 1.0.0-test", server["version"])
}
}
func TestDiagnosticsConnectivity_Unauthenticated(t *testing.T) {
router, _ := setupDiagnosticsRouter(t)
req := httptest.NewRequest(http.MethodGet, "/api/v1/diagnostics/connectivity", nil)
req.RemoteAddr = "127.0.0.1:9999"
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusUnauthorized {
t.Errorf("status = %d, want 401", rr.Code)
}
}
// ─── isPrivateIP tests ──────────────────────────────────────────────────────
func TestIsPrivateIP(t *testing.T) {
tests := []struct {
name string
ip string
want bool
}{
{"10.x.x.x", "10.0.0.1", true},
{"172.16.x.x", "172.16.0.1", true},
{"172.17.x.x", "172.17.5.5", true},
{"172.31.x.x", "172.31.255.255", true},
{"192.168.x.x", "192.168.1.1", true},
{"127.x.x.x", "127.0.0.1", true},
{"::1 loopback", "::1", true},
{"fc ULA", "fc00::1", true},
{"fd ULA", "fd12::1", true},
{"public 8.8.8.8", "8.8.8.8", false},
{"public 203.x", "203.0.113.1", false},
{"public 1.1.1.1", "1.1.1.1", false},
{"172.32 not private", "172.32.0.1", false},
{"empty string", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := api.IsPrivateIPForTest(tt.ip)
if got != tt.want {
t.Errorf("isPrivateIP(%q) = %v, want %v", tt.ip, got, tt.want)
}
})
}
}