Files
OwnCord/Server/api/router_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

199 lines
4.7 KiB
Go

package api_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/owncord/server/api"
"github.com/owncord/server/config"
"github.com/owncord/server/db"
)
// setupRouter creates a test router with an in-memory database.
func setupRouter(t *testing.T) http.Handler {
t.Helper()
database, err := db.Open(":memory:")
if err != nil {
t.Fatalf("db.Open error: %v", err)
}
if err := db.Migrate(database); err != nil {
t.Fatalf("db.Migrate error: %v", err)
}
t.Cleanup(func() { _ = database.Close() })
cfg := &config.Config{
Server: config.ServerConfig{
Name: "Test Server",
Port: 8443,
},
}
handler, _, cleanup := api.NewRouter(cfg, database, "test", nil, nil)
t.Cleanup(cleanup)
return handler
}
func TestHealthEndpointReturns200(t *testing.T) {
router := setupRouter(t)
req := httptest.NewRequest(http.MethodGet, "/health", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("GET /health status = %d, want 200", rec.Code)
}
}
func TestHealthEndpointReturnsJSON(t *testing.T) {
router := setupRouter(t)
req := httptest.NewRequest(http.MethodGet, "/health", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
contentType := rec.Header().Get("Content-Type")
if !strings.Contains(contentType, "application/json") {
t.Errorf("Content-Type = %q, want application/json", contentType)
}
var body map[string]any
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
t.Fatalf("response body is not valid JSON: %v", err)
}
}
func TestHealthEndpointStatusOK(t *testing.T) {
router := setupRouter(t)
req := httptest.NewRequest(http.MethodGet, "/health", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
var body map[string]any
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
t.Fatalf("JSON decode error: %v", err)
}
if body["status"] != "ok" {
t.Errorf("status = %v, want 'ok'", body["status"])
}
}
func TestHealthEndpointOmitsVersion(t *testing.T) {
router := setupRouter(t)
req := httptest.NewRequest(http.MethodGet, "/health", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
var body map[string]any
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
t.Fatalf("JSON decode error: %v", err)
}
// C-2: Version must NOT be exposed on unauthenticated endpoints.
if _, exists := body["version"]; exists {
t.Error("health response must not contain 'version' field (prevents fingerprinting)")
}
}
func TestAPIV1InfoEndpoint(t *testing.T) {
router := setupRouter(t)
req := httptest.NewRequest(http.MethodGet, "/api/v1/info", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("GET /api/v1/info status = %d, want 200", rec.Code)
}
}
func TestAPIV1InfoReturnsServerName(t *testing.T) {
router := setupRouter(t)
req := httptest.NewRequest(http.MethodGet, "/api/v1/info", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
var body map[string]any
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
t.Fatalf("JSON decode error: %v", err)
}
if body["name"] != "Test Server" {
t.Errorf("name = %v, want 'Test Server'", body["name"])
}
}
func TestAPIV1InfoOmitsVersion(t *testing.T) {
router := setupRouter(t)
req := httptest.NewRequest(http.MethodGet, "/api/v1/info", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
var body map[string]any
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
t.Fatalf("JSON decode error: %v", err)
}
// C-2: Version must NOT be exposed to prevent fingerprinting.
if _, exists := body["version"]; exists {
t.Error("info response must not contain 'version' field (prevents fingerprinting)")
}
}
func TestUnknownRouteReturns404(t *testing.T) {
router := setupRouter(t)
req := httptest.NewRequest(http.MethodGet, "/api/v1/nonexistent", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
t.Errorf("GET /api/v1/nonexistent status = %d, want 404", rec.Code)
}
}
func TestRequestIDMiddleware(t *testing.T) {
router := setupRouter(t)
req := httptest.NewRequest(http.MethodGet, "/health", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
// Request ID header should be set by middleware.
requestID := rec.Header().Get("X-Request-Id")
if requestID == "" {
t.Error("X-Request-Id header not set by middleware")
}
}
func TestHealthMethodNotAllowed(t *testing.T) {
router := setupRouter(t)
req := httptest.NewRequest(http.MethodPost, "/health", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusMethodNotAllowed {
t.Errorf("POST /health status = %d, want 405", rec.Code)
}
}