Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

feat(license): implement free Patrol / pro Auto-Fix tiering strategy

rcourtman44f9a36d5cd6
diff --git a/frontend-modern/src/components/Settings/ProLicensePanel.tsx b/frontend-modern/src/components/Settings/ProLicensePanel.tsx
index 62b610383c..5cb3c38d9b 100644
--- a/frontend-modern/src/components/Settings/ProLicensePanel.tsx
+++ b/frontend-modern/src/components/Settings/ProLicensePanel.tsx
@@ -154,7 +154,7 @@ export const ProLicensePanel: Component = () => {
<div class="space-y-6">
<SettingsPanel
title="Pulse Pro License"
- description="Activate your Pulse Pro license to unlock Pulse Patrol automation features."
+ description="Activate your Pulse Pro license to unlock auto-fix, alert-triggered AI, and advanced features."
action={
<button
class="inline-flex items-center gap-2 px-3 py-1.5 text-xs font-medium rounded-md border border-gray-300 dark:border-gray-700 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors disabled:opacity-60"
diff --git a/frontend-modern/src/stores/license.ts b/frontend-modern/src/stores/license.ts
index 3b2bdde40e..9868409557 100644
--- a/frontend-modern/src/stores/license.ts
+++ b/frontend-modern/src/stores/license.ts
@@ -27,7 +27,7 @@ export async function loadLicenseStatus(force = false): Promise<void> {
tier: 'free',
is_lifetime: false,
days_remaining: 0,
- features: [],
+ features: ['update_alerts', 'sso', 'ai_patrol'],
});
setLoaded(true);
} finally {
@@ -45,10 +45,11 @@ export const isPro = createMemo(() => {
/**
* Check if a specific feature is enabled by the current license.
+ * Free tier features (e.g., ai_patrol) are available even without a valid Pro license.
*/
export function hasFeature(feature: string): boolean {
const current = licenseStatus();
- if (!current?.valid) return false;
+ if (!current) return false;
return current.features.includes(feature);
}
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index f034411bad..05bcbe1794 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -266,6 +266,42 @@ func (h *AISettingsHandler) SetConfig(cfg *config.Config) {
h.legacyConfig = cfg
}
+// setSSECORSHeaders validates the request origin against the configured AllowedOrigins
+// and sets CORS headers only for allowed origins. This prevents arbitrary origin reflection.
+func (h *AISettingsHandler) setSSECORSHeaders(w http.ResponseWriter, r *http.Request) {
+ origin := r.Header.Get("Origin")
+ if origin == "" {
+ return
+ }
+
+ cfg := h.getConfig(r.Context())
+ if cfg == nil {
+ return
+ }
+
+ allowed := cfg.AllowedOrigins
+ if allowed == "" {
+ return
+ }
+
+ if allowed == "*" {
+ w.Header().Set("Access-Control-Allow-Origin", origin)
+ w.Header().Set("Access-Control-Allow-Credentials", "true")
+ } else {
+ for _, o := range strings.Split(allowed, ",") {
+ if strings.TrimSpace(o) == origin {
+ w.Header().Set("Access-Control-Allow-Origin", origin)
+ w.Header().Set("Access-Control-Allow-Credentials", "true")
+ break
+ }
+ }
+ }
+
+ w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
+ w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Accept, Cookie")
+ w.Header().Set("Vary", "Origin")
+}
+
// SetStateProvider sets the state provider for infrastructure context
func (h *AISettingsHandler) SetStateProvider(sp ai.StateProvider) {
h.stateProvider = sp
@@ -810,9 +846,22 @@ func (h *AISettingsHandler) setupInvestigationOrchestrator(orgID string, svc *ai
// Wire up Prometheus metrics for investigation outcomes and fix verification
adapter.SetMetricsCallback()
+ // Wire up license checker for defense-in-depth autonomy clamping
+ // This prevents auto-fix execution even if autonomy level was somehow set to assisted/full without Pro
+ adapter.SetLicenseChecker(&licenseCheckerForOrchestrator{svc: svc})
+
log.Info().Str("orgID", orgID).Msg("Investigation orchestrator configured for patrol service")
}
+// licenseCheckerForOrchestrator adapts *ai.Service to investigation.LicenseChecker
+type licenseCheckerForOrchestrator struct {
+ svc *ai.Service
+}
+
+func (l *licenseCheckerForOrchestrator) HasFeature(feature string) bool {
+ return l.svc.HasLicenseFeature(feature)
+}
+
// findingsStoreWrapper wraps *ai.FindingsStore to implement investigation.AIFindingsStore
type findingsStoreWrapper struct {
store *ai.FindingsStore
@@ -1123,18 +1172,6 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt
}
if req.UseProactiveThresholds != nil {
- // Proactive thresholds require Pro license with ai_patrol feature
- if *req.UseProactiveThresholds && !h.GetAIService(r.Context()).HasLicenseFeature(ai.FeatureAIPatrol) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusPaymentRequired)
- _ = json.NewEncoder(w).Encode(map[string]interface{}{
- "error": "license_required",
- "message": "Proactive Thresholds requires Pulse Pro",
- "feature": ai.FeatureAIPatrol,
- "upgrade_url": "https://pulserelay.pro/",
- })
- return
- }
settings.UseProactiveThresholds = *req.UseProactiveThresholds
}
@@ -1233,19 +1270,6 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt
return
}
- // Enabling background patrol requires Pro license
- if minutes > 0 && !h.GetAIService(r.Context()).HasLicenseFeature(ai.FeatureAIPatrol) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusPaymentRequired)
- _ = json.NewEncoder(w).Encode(map[string]interface{}{
- "error": "license_required",
- "message": "Background Pulse Patrol requires Pulse Pro",
- "feature": ai.FeatureAIPatrol,
- "upgrade_url": "https://pulserelay.pro/",
- })
- return
- }
-
settings.PatrolIntervalMinutes = minutes
settings.PatrolSchedulePreset = "" // Clear preset when using custom minutes
if minutes > 0 {
@@ -1258,18 +1282,6 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt
preset := strings.ToLower(strings.TrimSpace(*req.PatrolSchedulePreset))
switch preset {
case "15min", "1hr", "6hr", "12hr", "daily":
- // Enabling background patrol requires Pro license
- if !h.GetAIService(r.Context()).HasLicenseFeature(ai.FeatureAIPatrol) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusPaymentRequired)
- _ = json.NewEncoder(w).Encode(map[string]interface{}{
- "error": "license_required",
- "message": "Background Pulse Patrol requires Pulse Pro",
- "feature": ai.FeatureAIPatrol,
- "upgrade_url": "https://pulserelay.pro/",
- })
- return
- }
settings.PatrolSchedulePreset = preset
settings.PatrolIntervalMinutes = config.PresetToMinutes(preset)
settings.PatrolEnabled = true // Enable patrol when setting schedule preset
@@ -1731,18 +1743,6 @@ func (h *AISettingsHandler) HandleExecute(w http.ResponseWriter, r *http.Request
})
return
}
- } else if useCase == "patrol" {
- if !h.GetAIService(r.Context()).HasLicenseFeature(ai.FeatureAIPatrol) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusPaymentRequired)
- _ = json.NewEncoder(w).Encode(map[string]interface{}{
- "error": "license_required",
- "message": "Pulse Patrol reasoning requires Pulse Pro",
- "feature": ai.FeatureAIPatrol,
- "upgrade_url": "https://pulserelay.pro/",
- })
- return
- }
}
if strings.TrimSpace(req.Prompt) == "" {
@@ -1779,7 +1779,7 @@ func (h *AISettingsHandler) HandleExecute(w http.ResponseWriter, r *http.Request
})
if err != nil {
log.Error().Err(err).Msg("AI execution failed")
- http.Error(w, "Pulse Assistant request failed: "+err.Error(), http.StatusInternalServerError)
+ http.Error(w, "Pulse Assistant request failed", http.StatusInternalServerError)
return
}
@@ -1840,7 +1840,7 @@ func (h *AISettingsHandler) HandleAnalyzeKubernetesCluster(w http.ResponseWriter
return
default:
log.Error().Err(err).Str("cluster_id", req.ClusterID).Msg("Kubernetes AI analysis failed")
- http.Error(w, "Pulse Assistant request failed: "+err.Error(), http.StatusInternalServerError)
+ http.Error(w, "Pulse Assistant request failed", http.StatusInternalServerError)
return
}
}
@@ -1862,15 +1862,7 @@ func (h *AISettingsHandler) HandleAnalyzeKubernetesCluster(w http.ResponseWriter
// HandleExecuteStream executes an AI prompt with SSE streaming (POST /api/ai/execute/stream)
func (h *AISettingsHandler) HandleExecuteStream(w http.ResponseWriter, r *http.Request) {
// Handle CORS for dev mode (frontend on different port)
- origin := r.Header.Get("Origin")
- if origin != "" {
- // Must use specific origin (not *) when credentials are included
- w.Header().Set("Access-Control-Allow-Origin", origin)
- w.Header().Set("Access-Control-Allow-Credentials", "true")
- w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
- w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Accept, Cookie")
- w.Header().Set("Vary", "Origin")
- }
+ h.setSSECORSHeaders(w, r)
// Handle preflight
if r.Method == http.MethodOptions {
@@ -1917,18 +1909,6 @@ func (h *AISettingsHandler) HandleExecuteStream(w http.ResponseWriter, r *http.R
})
return
}
- } else if useCase == "patrol" {
- if !h.GetAIService(r.Context()).HasLicenseFeature(ai.FeatureAIPatrol) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusPaymentRequired)
- _ = json.NewEncoder(w).Encode(map[string]interface{}{
- "error": "license_required",
- "message": "Pulse Patrol reasoning requires Pulse Pro",
- "feature": ai.FeatureAIPatrol,
- "upgrade_url": "https://pulserelay.pro/",
- })
- return
- }
}
if strings.TrimSpace(req.Prompt) == "" {
@@ -2084,8 +2064,8 @@ func (h *AISettingsHandler) HandleExecuteStream(w http.ResponseWriter, r *http.R
if err != nil {
log.Error().Err(err).Msg("AI streaming execution failed")
- // Send error event
- errEvent := ai.StreamEvent{Type: "error", Data: err.Error()}
+ // Send error event — use generic message to avoid leaking internal details
+ errEvent := ai.StreamEvent{Type: "error", Data: "AI request failed. Please try again."}
data, _ := json.Marshal(errEvent)
safeWrite([]byte("data: " + string(data) + "\n\n"))
return
@@ -2510,14 +2490,7 @@ type AIInvestigateAlertRequest struct {
// This is a dedicated endpoint for one-click alert investigation from the UI
func (h *AISettingsHandler) HandleInvestigateAlert(w http.ResponseWriter, r *http.Request) {
// Handle CORS
- origin := r.Header.Get("Origin")
- if origin != "" {
- w.Header().Set("Access-Control-Allow-Origin", origin)
- w.Header().Set("Access-Control-Allow-Credentials", "true")
- w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
- w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Accept, Cookie")
- w.Header().Set("Vary", "Origin")
- }
+ h.setSSECORSHeaders(w, r)
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
@@ -2683,7 +2656,7 @@ func (h *AISettingsHandler) HandleInvestigateAlert(w http.ResponseWriter, r *htt
if err != nil {
log.Error().Err(err).Msg("AI alert investigation failed")
- errEvent := ai.StreamEvent{Type: "error", Data: err.Error()}
+ errEvent := ai.StreamEvent{Type: "error", Data: "Alert investigation failed. Please try again."}
data, _ := json.Marshal(errEvent)
safeWrite([]byte("data: " + string(data) + "\n\n"))
return
@@ -3124,8 +3097,8 @@ func (h *AISettingsHandler) HandleGetPatrolStatus(w http.ResponseWriter, r *http
// Determine license status for Pro feature gating
// GetLicenseState returns accurate state: none, active, expired, grace_period
licenseStatus, _ := h.GetAIService(r.Context()).GetLicenseState()
- // Check specifically for ai_patrol feature using canonical license constant
- hasPatrolFeature := h.GetAIService(r.Context()).HasLicenseFeature(license.FeatureAIPatrol)
+ // Check for auto-fix feature - patrol itself is free, auto-fix requires Pro
+ hasAutoFixFeature := h.GetAIService(r.Context()).HasLicenseFeature(license.FeatureAIAutoFix)
// Get fixed count from investigation orchestrator
fixedCount := 0
@@ -3147,10 +3120,10 @@ func (h *AISettingsHandler) HandleGetPatrolStatus(w http.ResponseWriter, r *http
FixedCount: fixedCount,
BlockedReason: status.BlockedReason,
BlockedAt: status.BlockedAt,
- LicenseRequired: !hasPatrolFeature,
+ LicenseRequired: !hasAutoFixFeature,
LicenseStatus: licenseStatus,
}
- if !hasPatrolFeature {
+ if !hasAutoFixFeature {
response.UpgradeURL = "https://pulserelay.pro/"
}
response.Summary.Critical = summary.Critical
@@ -3235,10 +3208,10 @@ func (h *AISettingsHandler) HandlePatrolStream(w http.ResponseWriter, r *http.Re
}
// Set SSE headers
+ h.setSSECORSHeaders(w, r)
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
- w.Header().Set("Access-Control-Allow-Origin", "*")
flusher, ok := w.(http.Flusher)
if !ok {
@@ -3276,99 +3249,6 @@ func (h *AISettingsHandler) HandlePatrolStream(w http.ResponseWriter, r *http.Re
}
}
-func previewTitle(category ai.FindingCategory) string {
- switch category {
- case ai.FindingCategoryPerformance:
- return "Performance issue detected"
- case ai.FindingCategoryCapacity:
- return "Capacity issue detected"
- case ai.FindingCategoryReliability:
- return "Reliability issue detected"
- case ai.FindingCategoryBackup:
- return "Backup issue detected"
- case ai.FindingCategorySecurity:
- return "Security issue detected"
- default:
- return "Potential issue detected"
- }
-}
-
-func previewResourceName(resourceType string) string {
- switch resourceType {
- case "node":
- return "Node"
- case "vm":
- return "VM"
- case "container", "oci_container":
- return "Container"
- case "docker_host":
- return "Docker host"
- case "docker_container":
- return "Docker container"
- case "storage":
- return "Storage"
- case "pbs":
- return "PBS server"
- case "pbs_datastore":
- return "PBS datastore"
- case "pbs_job":
- return "PBS job"
- case "host":
- return "Host"
- case "host_raid":
- return "RAID array"
- case "host_sensor":
- return "Host sensor"
- default:
- return "Resource"
- }
-}
-
-func redactFindingsForPreview(findings []*ai.Finding) []*ai.Finding {
- redacted := make([]*ai.Finding, 0, len(findings))
- for _, finding := range findings {
- if finding == nil {
- continue
- }
- copy := *finding
- copy.Key = ""
- copy.ResourceID = ""
- copy.ResourceName = previewResourceName(finding.ResourceType)
- copy.Node = ""
- copy.Title = previewTitle(finding.Category)
- copy.Description = "Upgrade to view full analysis."
- copy.Recommendation = ""
- copy.Evidence = ""
- copy.AlertID = ""
- copy.AcknowledgedAt = nil
- copy.SnoozedUntil = nil
- copy.ResolvedAt = nil
- copy.AutoResolved = false
- copy.DismissedReason = ""
- copy.UserNote = ""
- copy.TimesRaised = 0
- copy.Suppressed = false
- copy.Source = "preview"
- redacted = append(redacted, &copy)
- }
- return redacted
-}
-
-func redactPatrolRunHistory(runs []ai.PatrolRunRecord) []ai.PatrolRunRecord {
- redacted := make([]ai.PatrolRunRecord, len(runs))
- for i, run := range runs {
- copy := run
- copy.AIAnalysis = ""
- copy.InputTokens = 0
- copy.OutputTokens = 0
- copy.FindingIDs = nil
- copy.ToolCalls = nil
- copy.ToolCallCount = 0
- redacted[i] = copy
- }
- return redacted
-}
-
// HandleGetPatrolFindings returns all active findings (GET /api/ai/patrol/findings)
func (h *AISettingsHandler) HandleGetPatrolFindings(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
@@ -3394,12 +3274,6 @@ func (h *AISettingsHandler) HandleGetPatrolFindings(w http.ResponseWriter, r *ht
findings = patrol.GetAllFindings()
}
- if !h.GetAIService(r.Context()).HasLicenseFeature(license.FeatureAIPatrol) {
- w.Header().Set("X-License-Required", "true")
- w.Header().Set("X-License-Feature", license.FeatureAIPatrol)
- findings = redactFindingsForPreview(findings)
- }
-
if err := utils.WriteJSONResponse(w, findings); err != nil {
log.Error().Err(err).Msg("Failed to write patrol findings response")
}
@@ -4100,12 +3974,6 @@ func (h *AISettingsHandler) HandleGetFindingsHistory(w http.ResponseWriter, r *h
findings := patrol.GetFindingsHistory(startTime)
- if !h.GetAIService(r.Context()).HasLicenseFeature(license.FeatureAIPatrol) {
- w.Header().Set("X-License-Required", "true")
- w.Header().Set("X-License-Feature", license.FeatureAIPatrol)
- findings = redactFindingsForPreview(findings)
- }
-
if err := utils.WriteJSONResponse(w, findings); err != nil {
log.Error().Err(err).Msg("Failed to write findings history response")
}
@@ -4148,12 +4016,6 @@ func (h *AISettingsHandler) HandleGetPatrolRunHistory(w http.ResponseWriter, r *
}
}
- if !h.GetAIService(r.Context()).HasLicenseFeature(license.FeatureAIPatrol) {
- w.Header().Set("X-License-Required", "true")
- w.Header().Set("X-License-Feature", license.FeatureAIPatrol)
- runs = redactPatrolRunHistory(runs)
- }
-
if err := utils.WriteJSONResponse(w, runs); err != nil {
log.Error().Err(err).Msg("Failed to write patrol run history response")
}
@@ -5409,8 +5271,15 @@ func (h *AISettingsHandler) HandleGetPatrolAutonomy(w http.ResponseWriter, r *ht
return
}
+ autonomyLevel := cfg.GetPatrolAutonomyLevel()
+ // Clamp for free tier: assisted/full require Pro (ai_autofix)
+ hasAutoFix := aiService.HasLicenseFeature(license.FeatureAIAutoFix)
+ if !hasAutoFix && (autonomyLevel == config.PatrolAutonomyAssisted || autonomyLevel == config.PatrolAutonomyFull) {
+ autonomyLevel = config.PatrolAutonomyApproval
+ }
+
settings := PatrolAutonomyResponse{
- AutonomyLevel: cfg.GetPatrolAutonomyLevel(),
+ AutonomyLevel: autonomyLevel,
FullModeUnlocked: cfg.PatrolFullModeUnlocked,
InvestigationBudget: cfg.GetPatrolInvestigationBudget(),
InvestigationTimeoutSec: int(cfg.GetPatrolInvestigationTimeout().Seconds()),
@@ -5440,6 +5309,19 @@ func (h *AISettingsHandler) HandleUpdatePatrolAutonomy(w http.ResponseWriter, r
return
}
+ // License-based autonomy clamping: assisted/full require Pro (ai_autofix)
+ hasAutoFix := h.GetAIService(r.Context()).HasLicenseFeature(license.FeatureAIAutoFix)
+ if !hasAutoFix && (req.AutonomyLevel == config.PatrolAutonomyAssisted || req.AutonomyLevel == config.PatrolAutonomyFull) {
+ writeErrorResponse(w, http.StatusPaymentRequired, "license_required",
+ "Assisted and Full autonomy require Pulse Pro. Free tier supports Monitor and Approval modes.",
+ map[string]string{
+ "feature": license.FeatureAIAutoFix,
+ "upgrade_url": "https://pulserelay.pro/",
+ "allowed_modes": "monitor,approval",
+ })
+ return
+ }
+
// Validate budget (5-30)
if req.InvestigationBudget < 5 {
req.InvestigationBudget = 5
diff --git a/internal/api/ai_handlers_patrol_test.go b/internal/api/ai_handlers_patrol_test.go
index 57f96be8bd..2f04817c52 100644
--- a/internal/api/ai_handlers_patrol_test.go
+++ b/internal/api/ai_handlers_patrol_test.go
@@ -43,6 +43,9 @@ func (m *MockOrchestrator) CanStartInvestigation() bool {
func (m *MockOrchestrator) ReinvestigateFinding(ctx context.Context, findingID, autonomyLevel string) error {
return nil
}
+func (m *MockOrchestrator) Shutdown(ctx context.Context) error {
+ return nil
+}
func TestHandleGetPatrolStatus_Integration(t *testing.T) {
// Setup temporary persistence
diff --git a/internal/api/license_handlers_test.go b/internal/api/license_handlers_test.go
index efaf632e72..6b4ae0265f 100644
--- a/internal/api/license_handlers_test.go
+++ b/internal/api/license_handlers_test.go
@@ -67,13 +67,25 @@ func TestHandleLicenseFeatures_NoLicense(t *testing.T) {
t.Fatalf("expected upgrade_url to be set")
}
- expectedFeatures := []string{
+ // Patrol is in free tier, so it should be true even without a license
+ freeTierFeatures := []string{
license.FeatureAIPatrol,
+ }
+ for _, feature := range freeTierFeatures {
+ if value, ok := resp.Features[feature]; !ok {
+ t.Fatalf("expected feature %q in response", feature)
+ } else if !value {
+ t.Fatalf("expected feature %q to be true in free tier", feature)
+ }
+ }
+
+ // These Pro features should be false without a license
+ proOnlyFeatures := []string{
license.FeatureAIAlerts,
license.FeatureAIAutoFix,
license.FeatureKubernetesAI,
}
- for _, feature := range expectedFeatures {
+ for _, feature := range proOnlyFeatures {
if value, ok := resp.Features[feature]; !ok {
t.Fatalf("expected feature %q in response", feature)
} else if value {
@@ -419,7 +431,8 @@ func TestRequireLicenseFeature_NoLicense(t *testing.T) {
handler := createTestHandler(t)
handlerCalled := false
- wrappedHandler := RequireLicenseFeature(handler, license.FeatureAIPatrol, func(w http.ResponseWriter, r *http.Request) {
+ // Use a Pro-only feature (ai_autofix) to test that middleware blocks without license
+ wrappedHandler := RequireLicenseFeature(handler, license.FeatureAIAutoFix, func(w http.ResponseWriter, r *http.Request) {
handlerCalled = true
w.WriteHeader(http.StatusOK)
})
@@ -450,7 +463,8 @@ func TestRequireLicenseFeature_WithLicense(t *testing.T) {
}
handlerCalled := false
- wrappedHandler := RequireLicenseFeature(handler, license.FeatureAIPatrol, func(w http.ResponseWriter, r *http.Request) {
+ // Use a Pro-only feature (ai_autofix) to test that middleware passes with license
+ wrappedHandler := RequireLicenseFeature(handler, license.FeatureAIAutoFix, func(w http.ResponseWriter, r *http.Request) {
handlerCalled = true
w.WriteHeader(http.StatusOK)
})
@@ -476,7 +490,8 @@ func TestLicenseGatedEmptyResponse_NoLicense(t *testing.T) {
handler := createTestHandler(t)
handlerCalled := false
- wrappedHandler := LicenseGatedEmptyResponse(handler, license.FeatureAIPatrol, func(w http.ResponseWriter, r *http.Request) {
+ // Use a Pro-only feature (ai_autofix) to test gating without license
+ wrappedHandler := LicenseGatedEmptyResponse(handler, license.FeatureAIAutoFix, func(w http.ResponseWriter, r *http.Request) {
handlerCalled = true
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"data":"real"}`))
@@ -512,7 +527,8 @@ func TestLicenseGatedEmptyResponse_WithLicense(t *testing.T) {
}
handlerCalled := false
- wrappedHandler := LicenseGatedEmptyResponse(handler, license.FeatureAIPatrol, func(w http.ResponseWriter, r *http.Request) {
+ // Use a Pro-only feature (ai_autofix) to test gating with license
+ wrappedHandler := LicenseGatedEmptyResponse(handler, license.FeatureAIAutoFix, func(w http.ResponseWriter, r *http.Request) {
handlerCalled = true
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"data":"real"}`))
diff --git a/internal/api/router.go b/internal/api/router.go
index 8fd853a6ff..a786511767 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -1357,7 +1357,7 @@ func (r *Router) setupRoutes() {
// Read endpoints (findings, history, runs) return redacted preview data when unlicensed
// Mutation endpoints (run, acknowledge, dismiss, etc.) return 402 to prevent unauthorized actions
r.mux.HandleFunc("/api/ai/patrol/status", RequireAuth(r.config, r.aiSettingsHandler.HandleGetPatrolStatus))
- r.mux.HandleFunc("/api/ai/patrol/stream", RequireAuth(r.config, RequireLicenseFeature(r.licenseHandlers, license.FeatureAIPatrol, r.aiSettingsHandler.HandlePatrolStream)))
+ r.mux.HandleFunc("/api/ai/patrol/stream", RequireAuth(r.config, r.aiSettingsHandler.HandlePatrolStream))
r.mux.HandleFunc("/api/ai/patrol/findings", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {
switch req.Method {
case http.MethodGet:
@@ -1370,65 +1370,44 @@ func (r *Router) setupRoutes() {
}
}))
r.mux.HandleFunc("/api/ai/patrol/history", RequireAuth(r.config, r.aiSettingsHandler.HandleGetFindingsHistory))
- r.mux.HandleFunc("/api/ai/patrol/run", RequireAdmin(r.config, RequireLicenseFeature(r.licenseHandlers, license.FeatureAIPatrol, r.aiSettingsHandler.HandleForcePatrol)))
- r.mux.HandleFunc("/api/ai/patrol/acknowledge", RequireAuth(r.config, RequireLicenseFeature(r.licenseHandlers, license.FeatureAIPatrol, r.aiSettingsHandler.HandleAcknowledgeFinding)))
+ r.mux.HandleFunc("/api/ai/patrol/run", RequireAdmin(r.config, r.aiSettingsHandler.HandleForcePatrol))
+ r.mux.HandleFunc("/api/ai/patrol/acknowledge", RequireAuth(r.config, r.aiSettingsHandler.HandleAcknowledgeFinding))
// Dismiss and resolve don't require Pro license - users should be able to clear findings they can see
// This is especially important for users who accumulated findings before fixing the patrol-without-AI bug
r.mux.HandleFunc("/api/ai/patrol/dismiss", RequireAuth(r.config, r.aiSettingsHandler.HandleDismissFinding))
r.mux.HandleFunc("/api/ai/patrol/findings/note", RequireAuth(r.config, r.aiSettingsHandler.HandleSetFindingNote))
- r.mux.HandleFunc("/api/ai/patrol/suppress", RequireAuth(r.config, RequireLicenseFeature(r.licenseHandlers, license.FeatureAIPatrol, r.aiSettingsHandler.HandleSuppressFinding)))
- r.mux.HandleFunc("/api/ai/patrol/snooze", RequireAuth(r.config, RequireLicenseFeature(r.licenseHandlers, license.FeatureAIPatrol, r.aiSettingsHandler.HandleSnoozeFinding)))
+ r.mux.HandleFunc("/api/ai/patrol/suppress", RequireAuth(r.config, r.aiSettingsHandler.HandleSuppressFinding))
+ r.mux.HandleFunc("/api/ai/patrol/snooze", RequireAuth(r.config, r.aiSettingsHandler.HandleSnoozeFinding))
r.mux.HandleFunc("/api/ai/patrol/resolve", RequireAuth(r.config, r.aiSettingsHandler.HandleResolveFinding))
r.mux.HandleFunc("/api/ai/patrol/runs", RequireAuth(r.config, r.aiSettingsHandler.HandleGetPatrolRunHistory))
- // Suppression rules management (also Pro-only since they control LLM behavior)
- // GET returns empty array for unlicensed, POST returns 402
+ // Suppression rules management - free with patrol
r.mux.HandleFunc("/api/ai/patrol/suppressions", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {
switch req.Method {
case http.MethodGet:
- // GET: return empty array if unlicensed
- if err := r.licenseHandlers.Service(req.Context()).RequireFeature(license.FeatureAIPatrol); err != nil {
- w.Header().Set("Content-Type", "application/json")
- w.Header().Set("X-License-Required", "true")
- w.Header().Set("X-License-Feature", license.FeatureAIPatrol)
- w.Write([]byte("[]"))
- return
- }
r.aiSettingsHandler.HandleGetSuppressionRules(w, req)
case http.MethodPost:
- // POST: return 402 if unlicensed
- if err := r.licenseHandlers.Service(req.Context()).RequireFeature(license.FeatureAIPatrol); err != nil {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusPaymentRequired)
- json.NewEncoder(w).Encode(map[string]interface{}{
- "error": "license_required",
- "message": err.Error(),
- "feature": license.FeatureAIPatrol,
- "upgrade_url": "https://pulserelay.pro/",
- })
- return
- }
r.aiSettingsHandler.HandleAddSuppressionRule(w, req)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}))
- r.mux.HandleFunc("/api/ai/patrol/suppressions/", RequireAuth(r.config, RequireLicenseFeature(r.licenseHandlers, license.FeatureAIPatrol, r.aiSettingsHandler.HandleDeleteSuppressionRule)))
- r.mux.HandleFunc("/api/ai/patrol/dismissed", RequireAuth(r.config, LicenseGatedEmptyResponse(r.licenseHandlers, license.FeatureAIPatrol, r.aiSettingsHandler.HandleGetDismissedFindings)))
+ r.mux.HandleFunc("/api/ai/patrol/suppressions/", RequireAuth(r.config, r.aiSettingsHandler.HandleDeleteSuppressionRule))
+ r.mux.HandleFunc("/api/ai/patrol/dismissed", RequireAuth(r.config, r.aiSettingsHandler.HandleGetDismissedFindings))
- // Patrol Autonomy - autonomous investigation and remediation of findings (requires Pro license)
+ // Patrol Autonomy - monitor/approval free, assisted/full require Pro (enforced in handlers)
r.mux.HandleFunc("/api/ai/patrol/autonomy", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {
switch req.Method {
case http.MethodGet:
r.aiSettingsHandler.HandleGetPatrolAutonomy(w, req)
case http.MethodPut:
- RequireLicenseFeature(r.licenseHandlers, license.FeatureAIPatrol, r.aiSettingsHandler.HandleUpdatePatrolAutonomy)(w, req)
+ r.aiSettingsHandler.HandleUpdatePatrolAutonomy(w, req)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}))
- // Investigation endpoints - view and trigger investigations of findings
- r.mux.HandleFunc("/api/ai/findings/", RequireAuth(r.config, RequireLicenseFeature(r.licenseHandlers, license.FeatureAIPatrol, func(w http.ResponseWriter, req *http.Request) {
+ // Investigation endpoints - viewing and reinvestigation are free, fix execution (reapprove) requires Pro
+ r.mux.HandleFunc("/api/ai/findings/", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {
path := req.URL.Path
switch {
case strings.HasSuffix(path, "/investigation/messages"):
@@ -1438,11 +1417,12 @@ func (r *Router) setupRoutes() {
case strings.HasSuffix(path, "/reinvestigate"):
r.aiSettingsHandler.HandleReinvestigateFinding(w, req)
case strings.HasSuffix(path, "/reapprove"):
- r.aiSettingsHandler.HandleReapproveInvestigationFix(w, req)
+ // Fix execution requires Pro license
+ RequireLicenseFeature(r.licenseHandlers, license.FeatureAIAutoFix, r.aiSettingsHandler.HandleReapproveInvestigationFix)(w, req)
default:
http.Error(w, "Not found", http.StatusNotFound)
}
- })))
+ }))
// AI Intelligence endpoints - expose learned patterns, correlations, and predictions
// Unified intelligence endpoint - aggregates all AI subsystems into a single view
@@ -2471,6 +2451,12 @@ func (r *Router) ShutdownAIIntelligence() {
log.Debug().Msg("AI Intelligence: Alert bridge stopped")
}
+ // 2. Stop patrol service (waits for in-flight investigations, force-saves state)
+ if patrolSvc := r.aiSettingsHandler.GetAIService(context.Background()).GetPatrolService(); patrolSvc != nil {
+ patrolSvc.Stop()
+ log.Debug().Msg("AI Intelligence: Patrol service stopped")
+ }
+
// 3. Stop trigger manager (stop event-driven patrol scheduling)
if triggerManager := r.aiSettingsHandler.GetTriggerManager(); triggerManager != nil {
triggerManager.Stop()
diff --git a/internal/license/features.go b/internal/license/features.go
index e86075bcd5..29087a85a4 100644
--- a/internal/license/features.go
+++ b/internal/license/features.go
@@ -49,6 +49,7 @@ var TierFeatures = map[Tier][]string{
// Free tier includes update alerts (container image updates) - basic monitoring feature
FeatureUpdateAlerts,
FeatureSSO,
+ FeatureAIPatrol, // Patrol is free with BYOK - auto-fix requires Pro
},
TierPro: {
FeatureAIPatrol,
diff --git a/internal/license/license.go b/internal/license/license.go
index 7477a95863..23fa47bbf0 100644
--- a/internal/license/license.go
+++ b/internal/license/license.go
@@ -235,7 +235,8 @@ func (s *Service) HasFeature(feature string) bool {
defer s.mu.Unlock()
if s.license == nil {
- return false
+ // No license activated — still grant free tier features
+ return TierHasFeature(TierFree, feature)
}
if s.license.IsExpired() {
// If license just expired and grace period not yet set, set it now
@@ -247,7 +248,8 @@ func (s *Service) HasFeature(feature string) bool {
if s.license.GracePeriodEnd != nil && time.Now().Before(*s.license.GracePeriodEnd) {
return s.license.HasFeature(feature)
}
- return false
+ // License expired and grace period over — fall back to free tier
+ return TierHasFeature(TierFree, feature)
}
return s.license.HasFeature(feature)
}
@@ -357,6 +359,9 @@ func (s *Service) Status() *LicenseStatus {
status.InGracePeriod = true
graceEnd := s.license.GracePeriodEnd.Format(time.RFC3339)
status.GracePeriodEnd = &graceEnd
+ } else {
+ // Expired past grace — fall back to free tier features only
+ status.Features = TierFeatures[TierFree]
}
}
diff --git a/internal/license/license_test.go b/internal/license/license_test.go
index 4e88355ba2..fddcb179d3 100644
--- a/internal/license/license_test.go
+++ b/internal/license/license_test.go
@@ -21,7 +21,8 @@ func TestTierHasFeature(t *testing.T) {
feature string
expected bool
}{
- {"free has no AI patrol", TierFree, FeatureAIPatrol, false},
+ {"free has AI patrol (BYOK)", TierFree, FeatureAIPatrol, true},
+ {"free has no AI autofix", TierFree, FeatureAIAutoFix, false},
{"pro has AI patrol", TierPro, FeatureAIPatrol, true},
{"pro has AI alerts", TierPro, FeatureAIAlerts, true},
{"pro has AI autofix", TierPro, FeatureAIAutoFix, true},
@@ -178,9 +179,12 @@ func TestLicenseExpiration(t *testing.T) {
func TestServiceFeatureGating(t *testing.T) {
service := NewService()
- // No license - should not have features
- if service.HasFeature(FeatureAIPatrol) {
- t.Error("Should not have feature without license")
+ // No license - should have free tier features but not Pro features
+ if !service.HasFeature(FeatureAIPatrol) {
+ t.Error("Should have Patrol in free tier even without license")
+ }
+ if service.HasFeature(FeatureAIAutoFix) {
+ t.Error("Should not have auto-fix without license")
}
if service.IsValid() {
t.Error("Should not be valid without license")