diff --git a/server/docs/openapi.yaml b/server/docs/openapi.yaml index 7a091edb..e7a92f14 100644 --- a/server/docs/openapi.yaml +++ b/server/docs/openapi.yaml @@ -441,7 +441,12 @@ paths: get: tags: [Setup] summary: Health check - description: Returns the health status of the database and OIDC subsystem. Used by the container health check. + description: | + Returns a bounded local operator health summary. It reads the database, + persisted configuration, node freshness, and in-process MCP state; it + does not make network calls to OIDC, AI, webhook, notification, or MCP + endpoints. The response does not contain secrets. Used by the + container health check. responses: "200": description: OK @@ -449,8 +454,14 @@ paths: application/json: schema: type: object - required: [database, oidc, oidc_enabled] + required: [version, commit, database, oidc, oidc_enabled, mcp, ai, nodes, notifications, webhooks] properties: + version: + type: string + description: Server version set at build time. + commit: + type: string + description: Server commit identifier set at build time. database: type: string enum: [ok, error] @@ -459,6 +470,66 @@ paths: enum: [ok, disabled, unavailable, error] oidc_enabled: type: boolean + mcp: + type: object + required: [enabled, token_configured, running] + properties: + enabled: + type: boolean + token_configured: + type: boolean + description: Whether an MCP token exists; the token is never returned. + running: + type: boolean + ai: + type: object + required: [provider, configured, testable, api_key_configured, mode] + properties: + provider: + type: string + configured: + type: boolean + description: Whether provider, URL, and model are present in local settings. + testable: + type: boolean + description: Whether the stored provider settings can be sent to the separate AI test endpoint; no probe is made here. + api_key_configured: + type: boolean + mode: + type: string + nodes: + type: object + required: [total, online, offline, stale] + properties: + total: + type: integer + online: + type: integer + offline: + type: integer + stale: + type: integer + description: Nodes whose last heartbeat is older than the server offline threshold. + notifications: + type: object + required: [configured, total, enabled] + properties: + configured: + type: boolean + total: + type: integer + enabled: + type: integer + webhooks: + type: object + required: [configured, total, enabled] + properties: + configured: + type: boolean + total: + type: integer + enabled: + type: integer # ── Auth ────────────────────────────────────────────────────────────────── diff --git a/server/internal/handlers/health_test.go b/server/internal/handlers/health_test.go index 4d27492d..aa933340 100644 --- a/server/internal/handlers/health_test.go +++ b/server/internal/handlers/health_test.go @@ -4,12 +4,16 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "strings" "testing" + "time" "blackbox/server/internal/auth" "blackbox/server/internal/db" "blackbox/server/internal/handlers" + bbmcp "blackbox/server/internal/mcp" "blackbox/server/internal/models" + "github.com/oklog/ulid/v2" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -97,6 +101,98 @@ func TestHealthCheck_DBError_Returns503(t *testing.T) { assert.Equal(t, "error", resp["database"]) } +func TestHealthCheck_RichLocalSummaryDoesNotExposeSecretsOrProbeProviders(t *testing.T) { + database := newTestDB(t) + registry := auth.NewOIDCRegistry(database) + mcpManager := bbmcp.NewMCPManager(database) + require.NoError(t, mcpManager.ApplySettings(true, "mcp-health-secret")) + + now := time.Now().UTC() + require.NoError(t, database.Create(&models.AppSetting{Key: "ai_provider", Value: "openai_compat"}).Error) + require.NoError(t, database.Create(&models.AppSetting{Key: "ai_url", Value: "http://127.0.0.1:1"}).Error) + require.NoError(t, database.Create(&models.AppSetting{Key: "ai_model", Value: "local-model"}).Error) + require.NoError(t, database.Create(&models.AppSetting{Key: "ai_api_key", Value: "ai-health-secret"}).Error) + require.NoError(t, database.Create(&models.AppSetting{Key: "mcp_enabled", Value: "true"}).Error) + require.NoError(t, database.Create(&models.AppSetting{Key: "mcp_auth_token", Value: "mcp-health-secret"}).Error) + require.NoError(t, database.Create(&models.NotificationDest{ + ID: "notification-1", Name: "Ops", Type: "slack", URL: "https://hooks.example/notification-secret", Enabled: true, + }).Error) + require.NoError(t, database.Create(&models.DataSourceInstance{ + ID: ulid.Make().String(), Type: "webhook_uptime_kuma", Scope: models.ScopeServer, + Name: "Uptime Kuma", Config: `{"secret":"webhook-health-secret"}`, Enabled: true, + }).Error) + require.NoError(t, database.Create(&models.DataSourceInstance{ + ID: ulid.Make().String(), Type: "webhook_watchtower", Scope: models.ScopeServer, + Name: "Watchtower", Config: `{"secret":"disabled-webhook-secret"}`, Enabled: false, + }).Error) + require.NoError(t, database.Create(&models.Node{ID: "node-online", Name: "online", LastSeen: now, Status: "online"}).Error) + require.NoError(t, database.Create(&models.Node{ID: "node-stale", Name: "stale", LastSeen: now.Add(-10 * time.Minute), Status: "online"}).Error) + require.NoError(t, database.Create(&models.Node{ID: "node-offline", Name: "offline", LastSeen: now, Status: "offline"}).Error) + + req := httptest.NewRequest(http.MethodGet, "/api/setup/health", nil) + w := httptest.NewRecorder() + handlers.HealthCheckWithBuildInfo(database, registry, mcpManager, "1.2.3", "abc123")(w, req) + + assert.Equal(t, http.StatusOK, w.Code) + body := w.Body.String() + for _, secret := range []string{"mcp-health-secret", "ai-health-secret", "webhook-health-secret", "disabled-webhook-secret", "notification-secret"} { + assert.NotContains(t, body, secret) + } + + var resp struct { + Version string `json:"version"` + Commit string `json:"commit"` + MCP struct { + Enabled bool `json:"enabled"` + TokenConfigured bool `json:"token_configured"` + Running bool `json:"running"` + } `json:"mcp"` + AI struct { + Provider string `json:"provider"` + Configured bool `json:"configured"` + Testable bool `json:"testable"` + APIKeyConfigured bool `json:"api_key_configured"` + } `json:"ai"` + Nodes struct { + Total int64 `json:"total"` + Online int64 `json:"online"` + Offline int64 `json:"offline"` + Stale int64 `json:"stale"` + } `json:"nodes"` + Notifications struct { + Configured bool `json:"configured"` + Total int64 `json:"total"` + Enabled int64 `json:"enabled"` + } `json:"notifications"` + Webhooks struct { + Configured bool `json:"configured"` + Total int64 `json:"total"` + Enabled int64 `json:"enabled"` + } `json:"webhooks"` + } + require.NoError(t, json.NewDecoder(w.Body).Decode(&resp)) + assert.Equal(t, "1.2.3", resp.Version) + assert.Equal(t, "abc123", resp.Commit) + assert.True(t, resp.MCP.Enabled) + assert.True(t, resp.MCP.TokenConfigured) + assert.True(t, resp.MCP.Running) + assert.Equal(t, "openai_compat", resp.AI.Provider) + assert.True(t, resp.AI.Configured) + assert.True(t, resp.AI.Testable) + assert.True(t, resp.AI.APIKeyConfigured) + assert.Equal(t, int64(3), resp.Nodes.Total) + assert.Equal(t, int64(1), resp.Nodes.Online) + assert.Equal(t, int64(2), resp.Nodes.Offline) + assert.Equal(t, int64(1), resp.Nodes.Stale) + assert.True(t, resp.Notifications.Configured) + assert.Equal(t, int64(1), resp.Notifications.Total) + assert.Equal(t, int64(1), resp.Notifications.Enabled) + assert.True(t, resp.Webhooks.Configured) + assert.Equal(t, int64(2), resp.Webhooks.Total) + assert.Equal(t, int64(1), resp.Webhooks.Enabled) + assert.False(t, strings.Contains(body, "127.0.0.1:1")) +} + func setRegistryProvider(t *testing.T, registry *auth.OIDCRegistry, id string, provider *auth.OIDCProvider) { t.Helper() registry.SetProvider(id, provider) diff --git a/server/internal/handlers/setup.go b/server/internal/handlers/setup.go index 669c81a6..c56805f3 100644 --- a/server/internal/handlers/setup.go +++ b/server/internal/handlers/setup.go @@ -5,6 +5,8 @@ import ( "fmt" "log" "net/http" + "strings" + "time" "blackbox/server/internal/auth" "blackbox/server/internal/models" @@ -25,17 +27,89 @@ func SetupStatus(database *gorm.DB) http.HandlerFunc { } } +type healthMCPRuntime interface { + IsRunning() bool +} + +type healthConfigSummary struct { + Configured bool `json:"configured"` + Total int64 `json:"total"` + Enabled int64 `json:"enabled"` +} + +type healthMCPStatus struct { + Enabled bool `json:"enabled"` + TokenConfigured bool `json:"token_configured"` + Running bool `json:"running"` +} + +type healthAIStatus struct { + Provider string `json:"provider"` + Configured bool `json:"configured"` + Testable bool `json:"testable"` + APIKeyConfigured bool `json:"api_key_configured"` + Mode string `json:"mode"` +} + +type healthNodeSummary struct { + Total int64 `json:"total"` + Online int64 `json:"online"` + Offline int64 `json:"offline"` + Stale int64 `json:"stale"` +} + +type healthResponse struct { + Version string `json:"version"` + Commit string `json:"commit"` + Database string `json:"database"` + OIDC string `json:"oidc"` + OIDCEnabled bool `json:"oidc_enabled"` + MCP healthMCPStatus `json:"mcp"` + AI healthAIStatus `json:"ai"` + Nodes healthNodeSummary `json:"nodes"` + Notifications healthConfigSummary `json:"notifications"` + Webhooks healthConfigSummary `json:"webhooks"` +} + +// HealthCheck preserves the original handler contract for callers that do not +// have access to build metadata or the live MCP manager. func HealthCheck(database *gorm.DB, registry *auth.OIDCRegistry) http.HandlerFunc { + return HealthCheckWithBuildInfo(database, registry, nil, "dev", "unknown") +} + +// HealthCheckWithBuildInfo returns a bounded, local-only operator health view. +// It reads persisted configuration and in-process state but never contacts an +// OIDC, AI, webhook, notification, or MCP endpoint. +func HealthCheckWithBuildInfo(database *gorm.DB, registry *auth.OIDCRegistry, mcpRuntime healthMCPRuntime, version, commit string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + resp := healthResponse{ + Version: version, + Commit: commit, + Database: "ok", + OIDC: "disabled", + AI: healthAIStatus{ + Provider: "ollama", + Mode: "analysis", + }, + } + if mcpRuntime != nil { + resp.MCP.Running = mcpRuntime.IsRunning() + } + dbStatus := "ok" if err := database.Exec("SELECT 1").Error; err != nil { dbStatus = "error" } + resp.Database = dbStatus + if dbStatus != "ok" { + writeHealthResponse(w, http.StatusServiceUnavailable, resp) + return + } oidcStatus := "disabled" oidcEnabled := false var providers []models.OIDCProviderConfig - if err := database.Where("enabled = ?", true).Find(&providers).Error; err != nil { + if err := database.Where("enabled = ?", true).Limit(64).Find(&providers).Error; err != nil { log.Printf("health: OIDC provider query failed: %v", err) oidcEnabled = true oidcStatus = "error" @@ -51,23 +125,99 @@ func HealthCheck(database *gorm.DB, registry *auth.OIDCRegistry) http.HandlerFun } } } + resp.OIDC = oidcStatus + resp.OIDCEnabled = oidcEnabled - if dbStatus != "ok" { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusServiceUnavailable) - _ = json.NewEncoder(w).Encode(map[string]interface{}{ - "database": dbStatus, - "oidc": oidcStatus, - "oidc_enabled": oidcEnabled, - }) - return + mcpSettings, err := getMCPSettings(database) + if err != nil { + log.Printf("health: MCP settings query failed: %v", err) + } else { + resp.MCP.Enabled = mcpSettings.enabled + resp.MCP.TokenConfigured = mcpSettings.tokenSet } - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(map[string]interface{}{ - "database": dbStatus, - "oidc": oidcStatus, - "oidc_enabled": oidcEnabled, - }) + aiSettings, err := getAISettings(database) + if err != nil { + log.Printf("health: AI settings query failed: %v", err) + } else { + resp.AI.Provider = aiSettings.provider + resp.AI.APIKeyConfigured = aiSettings.apiKeySet + resp.AI.Mode = aiSettings.mode + resp.AI.Configured = strings.TrimSpace(aiSettings.url) != "" && strings.TrimSpace(aiSettings.model) != "" + resp.AI.Testable = resp.AI.Configured && (aiSettings.provider == "ollama" || aiSettings.provider == "openai_compat") + } + + var nodeStats struct { + Total int64 `gorm:"column:total"` + Online int64 `gorm:"column:online"` + Stale int64 `gorm:"column:stale"` + } + cutoff := time.Now().UTC().Add(-nodeOfflineAfter) + if err := database.Model(&models.Node{}).Select( + "COUNT(*) AS total, COALESCE(SUM(CASE WHEN status <> ? AND last_seen > ? THEN 1 ELSE 0 END), 0) AS online, COALESCE(SUM(CASE WHEN last_seen <= ? THEN 1 ELSE 0 END), 0) AS stale", + nodeStatusOffline, cutoff, cutoff, + ).Scan(&nodeStats).Error; err != nil { + log.Printf("health: node summary query failed: %v", err) + } else { + resp.Nodes = healthNodeSummary{ + Total: nodeStats.Total, + Online: nodeStats.Online, + Offline: nodeStats.Total - nodeStats.Online, + Stale: nodeStats.Stale, + } + } + + resp.Notifications = notificationHealthSummary(database) + resp.Webhooks = webhookHealthSummary(database) + + writeHealthResponse(w, http.StatusOK, resp) + } +} + +func notificationHealthSummary(database *gorm.DB) healthConfigSummary { + return configHealthSummary(database, &models.NotificationDest{}) +} + +func webhookHealthSummary(database *gorm.DB) healthConfigSummary { + var summary healthConfigSummary + var row struct { + Total int64 `gorm:"column:total"` + Enabled int64 `gorm:"column:enabled"` + } + if err := database.Model(&models.DataSourceInstance{}). + Where("scope = ? AND type LIKE ?", models.ScopeServer, "webhook_%"). + Select("COUNT(*) AS total, COALESCE(SUM(CASE WHEN enabled = ? THEN 1 ELSE 0 END), 0) AS enabled", true). + Scan(&row).Error; err != nil { + log.Printf("health: webhook summary query failed: %v", err) + return summary } + summary.Total = row.Total + summary.Enabled = row.Enabled + summary.Configured = row.Total > 0 + return summary +} + +func configHealthSummary(database *gorm.DB, model interface{}) healthConfigSummary { + var summary healthConfigSummary + var row struct { + Total int64 `gorm:"column:total"` + Enabled int64 `gorm:"column:enabled"` + } + if err := database.Model(model). + Select("COUNT(*) AS total, COALESCE(SUM(CASE WHEN enabled = ? THEN 1 ELSE 0 END), 0) AS enabled", true). + Scan(&row).Error; err != nil { + log.Printf("health: configuration summary query failed: %v", err) + return summary + } + summary.Total = row.Total + summary.Enabled = row.Enabled + summary.Configured = row.Total > 0 + return summary +} + +func writeHealthResponse(w http.ResponseWriter, status int, resp healthResponse) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(resp) } diff --git a/server/main.go b/server/main.go index 2343147d..26c3a348 100644 --- a/server/main.go +++ b/server/main.go @@ -192,7 +192,7 @@ func main() { r.Use(middleware.SecurityHeaders()) r.Get("/api/setup/status", handlers.SetupStatus(database)) - r.Get("/api/setup/health", handlers.HealthCheck(database, registry)) + r.Get("/api/setup/health", handlers.HealthCheckWithBuildInfo(database, registry, mcpMgr, Version, Commit)) r.Get("/api/openapi.yaml", handlers.OpenAPISpec(openapiSpec)) r.Get("/api/docs", handlers.APIDocs()) r.Group(func(r chi.Router) { diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 7c088705..55c91079 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -13,9 +13,39 @@ export interface SessionUser { } export interface HealthStatus { + version: string + commit: string database: 'ok' | 'error' oidc: 'ok' | 'unavailable' | 'disabled' oidc_enabled: boolean + mcp: { + enabled: boolean + token_configured: boolean + running: boolean + } + ai: { + provider: string + configured: boolean + testable: boolean + api_key_configured: boolean + mode: string + } + nodes: { + total: number + online: number + offline: number + stale: number + } + notifications: { + configured: boolean + total: number + enabled: number + } + webhooks: { + configured: boolean + total: number + enabled: number + } } export interface Entry { diff --git a/web/src/pages/DiagnosticsPage.tsx b/web/src/pages/DiagnosticsPage.tsx index 73e6864e..16467057 100644 --- a/web/src/pages/DiagnosticsPage.tsx +++ b/web/src/pages/DiagnosticsPage.tsx @@ -36,11 +36,51 @@ export default function DiagnosticsPage() { }, []) function statusColor(status: string) { - if (status === 'ok' || status === 'online') return 'var(--success)' - if (status === 'disabled') return 'var(--muted)' + if (status === 'ok' || status === 'online' || status === 'ready') return 'var(--success)' + if (status === 'disabled' || status === 'unconfigured') return 'var(--muted)' + if (status === 'warning') return '#F59E0B' return '#FF4444' } + function healthRows(current: HealthStatus) { + const mcpStatus = !current.mcp.enabled + ? 'disabled' + : !current.mcp.token_configured + ? 'error' + : current.mcp.running + ? 'ok' + : 'warning' + const mcpValue = !current.mcp.enabled + ? 'disabled' + : !current.mcp.token_configured + ? 'token missing' + : current.mcp.running + ? 'enabled / running' + : 'enabled / not running' + const aiStatus = !current.ai.configured ? 'unconfigured' : current.ai.testable ? 'ok' : 'error' + const aiValue = !current.ai.configured + ? 'unconfigured' + : current.ai.testable + ? `${current.ai.provider} / configured (no probe)` + : `${current.ai.provider} / not testable` + const nodeStatus = current.nodes.offline > 0 ? 'warning' : 'ok' + const nodeValue = `${current.nodes.online} online / ${current.nodes.total} total · ${current.nodes.stale} stale` + const configValue = (summary: HealthStatus['notifications'] | HealthStatus['webhooks']) => ( + summary.configured ? `${summary.enabled} enabled / ${summary.total} configured` : 'unconfigured' + ) + + return [ + { label: 'SERVER', value: `${current.version} / ${current.commit}`, status: 'ok' }, + { label: 'DATABASE', value: current.database, status: current.database }, + { label: 'OIDC', value: current.oidc_enabled ? current.oidc : 'disabled', status: current.oidc_enabled ? current.oidc : 'disabled' }, + { label: 'MCP', value: mcpValue, status: mcpStatus }, + { label: 'AI PROVIDER', value: aiValue, status: aiStatus }, + { label: 'NODES', value: nodeValue, status: nodeStatus }, + { label: 'NOTIFICATIONS', value: configValue(current.notifications), status: current.notifications.configured ? 'ok' : 'unconfigured' }, + { label: 'WEBHOOKS', value: configValue(current.webhooks), status: current.webhooks.configured ? 'ok' : 'unconfigured' }, + ] + } + return (
checking...
) : health ? (
- {[ - { label: 'DATABASE', value: health.database }, - ...(health.oidc_enabled ? [{ label: 'OIDC', value: health.oidc }] : []), - ].map(row => { - const ok = row.value === 'ok' + {healthRows(health).map(row => { + const ok = row.status === 'ok' return (
{ok ? : }