Files
OwnCord/Server/api/diagnostics_handler_test.go
T
J3vbandClaude Fable 5 6afa9e974c refactor(server): thread context.Context through the db layer and all callers
Fixes all 109 golangci-lint findings (106 contextcheck, 1 gocritic,
2 gosec) that accumulated after D2 wired dbgen (whose queries take ctx)
under ctx-less db.DB wrappers while CI lint was quota-dead. No nolint
comments added; every finding fixed by genuinely threading context.

- db: all 138 hand-written db.DB methods take ctx first; the dbCtx()
  Background shim is deleted; raw Query/QueryRow/Exec/Begin use their
  Context variants; the four redundant ctx-less passthroughs removed.
  db.Auditor/WriteAudit gain ctx.
- Seams: permissions.Checker (DB iface, HasChannelPerm,
  RequireChannelAccess) and the service.Store interface mirror the new
  signatures (ws.EventStore and plugin.PluginStore already did).
- Callers: api/admin handlers use r.Context(); ws per-message paths use
  the connection ctx via DispatchV2; hub loops and startup wiring use
  context.Background(); service methods thread ctx where they have one
  and Background where no ctx exists. Public service surface reached by
  ctx-holding chains (PermissionService.HasChannelPerm/GetRoleForUser/
  RequireChannelAccess, message/dm/block/invite/profile methods) is now
  ctx-first.
- Detached (context.WithoutCancel) where cancellation would break an
  invariant, found by a 3-lens adversarial review of the diff:
  * voice-leave background retries (a dead webhook/connection ctx killed
    retry 2 before it ran, leaving ghost capacity-holding voice rows)
  * rollbackVoiceJoin's compensating delete (its trigger IS the cancel)
  * post-2FA-change DeleteOtherSessions and logout DeleteSession (the
    security tail of a committed change must not die with the request)
  * all api/ws audit writes (a banned user could suppress their own
    login_blocked_banned row by aborting the request mid-bcrypt)
  * admin backup VACUUM INTO (an interrupt left a truncated .db that
    the backup list presented as restorable)
  * post-commit message/edit refetches (a committed message must still
    fan out when the sender disconnects)
  * hub settings-cache refresh (one dead connection could pin stale
    values for the 30s TTL)
- gocritic rangeValCopy fixed (index iteration); gosec G306 excluded in
  config with justification (generated source must stay world-readable)
  instead of flipping genprotocol output to 0o600.

Verified: gofmt/vet, all four build-tag variants, full suite, deadlock
pass, full -race pass, golangci-lint 0 issues uncapped.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 17:03:52 +02:00

163 lines
4.8 KiB
Go

package api_test
import (
"context"
"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"
"github.com/owncord/server/permissions"
)
// setupDiagnosticsRouter creates a full router with an authenticated user for
// diagnostics testing.
func setupDiagnosticsRouter(t *testing.T) (http.Handler, string, *db.DB) {
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(context.Background(), "diaguser", "$2a$12$fake", 1)
token := "diagtest-token-123"
hash := auth.HashToken(token)
_, _ = database.ExecContext(context.Background(),
`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, database
}
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)
}
}
// TestDiagnosticsConnectivity_MemberForbidden locks the RequirePermission gate
// on the route. Without it, only 200-for-owner and 401-unauthenticated were
// covered, so deleting the ADMINISTRATOR gate broke no test while exposing the
// server's network topology to every member.
func TestDiagnosticsConnectivity_MemberForbidden(t *testing.T) {
router, _, database := setupDiagnosticsRouter(t)
uid, err := database.CreateUser(context.Background(), "diagmember", "$2a$12$fake", int(permissions.MemberRoleID))
if err != nil {
t.Fatalf("CreateUser: %v", err)
}
token := "diagtest-member-token"
if _, err := database.ExecContext(context.Background(),
`INSERT INTO sessions (user_id, token, device, ip_address, expires_at)
VALUES (?, ?, 'test', '127.0.0.1', '2099-01-01T00:00:00Z')`,
uid, auth.HashToken(token),
); err != nil {
t.Fatalf("insert session: %v", err)
}
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.StatusForbidden {
t.Errorf("status = %d, want 403; body: %s", rr.Code, rr.Body.String())
}
}
// ─── 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)
}
})
}
}