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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
security: fix AI OAuth scope bypass, approval replay attacks, and approval endpoint scope gating
rcourtman69e3286e5efa
diff --git a/internal/ai/approval/store.go b/internal/ai/approval/store.goindex 58d71309c0..0b1ec763d1 100644--- a/internal/ai/approval/store.go+++ b/internal/ai/approval/store.go@@ -2,6 +2,8 @@ package approvalimport ("context"+ "crypto/sha256"+ "encoding/hex""encoding/json""fmt""os"@@ -50,6 +52,10 @@ type ApprovalRequest struct {DecidedAt *time.Time `json:"decidedAt,omitempty"`DecidedBy string `json:"decidedBy,omitempty"`DenyReason string `json:"denyReason,omitempty"`+ // CommandHash is a SHA256 hash of command+targetType+targetID for replay protection+ CommandHash string `json:"commandHash,omitempty"`+ // Consumed marks whether this approval has been used (single-use protection)+ Consumed bool `json:"consumed,omitempty"`}// ExecutionState stores the AI conversation state for resumption after approval.@@ -152,6 +158,11 @@ func (s *Store) CreateApproval(req *ApprovalRequest) error {req.RiskLevel = AssessRiskLevel(req.Command, req.TargetType)}+ // Compute command hash for replay protection if not already set+ if req.CommandHash == "" {+ req.CommandHash = ComputeCommandHash(req.Command, req.TargetType, req.TargetID)+ }+s.approvals[req.ID] = req// Persist asynchronously@@ -291,6 +302,55 @@ func (s *Store) Deny(id, username, reason string) (*ApprovalRequest, error) {return req, nil}+// ConsumeApproval validates and consumes an approval for a specific command.+// It verifies the command hash matches and marks the approval as consumed (single-use).+// Returns the approval if valid, or an error if invalid/already consumed.+func (s *Store) ConsumeApproval(id, command, targetType, targetID string) (*ApprovalRequest, error) {+ s.mu.Lock()+ defer s.mu.Unlock()++ req, ok := s.approvals[id]+ if !ok {+ return nil, fmt.Errorf("approval request not found: %s", id)+ }++ if req.Status != StatusApproved {+ return nil, fmt.Errorf("approval request is not approved (status: %s)", req.Status)+ }++ if req.Consumed {+ return nil, fmt.Errorf("approval request has already been consumed")+ }++ if time.Now().After(req.ExpiresAt) {+ req.Status = StatusExpired+ s.saveAsync()+ return nil, fmt.Errorf("approval request has expired")+ }++ // Verify command hash matches+ expectedHash := ComputeCommandHash(command, targetType, targetID)+ if req.CommandHash != "" && req.CommandHash != expectedHash {+ log.Warn().+ Str("id", id).+ Str("expected_hash", req.CommandHash).+ Str("actual_hash", expectedHash).+ Msg("Approval command hash mismatch - possible replay attack")+ return nil, fmt.Errorf("approval command mismatch - this approval is for a different command/target")+ }++ // Mark as consumed (single-use)+ req.Consumed = true+ s.saveAsync()++ log.Info().+ Str("id", id).+ Str("command", truncateCommand(command, 50)).+ Msg("Approval consumed successfully")++ return req, nil+}+// StoreExecution saves an execution state for later resumption.func (s *Store) StoreExecution(state *ExecutionState) error {s.mu.Lock()@@ -629,6 +689,18 @@ func truncateCommand(cmd string, maxLen int) string {return cmd[:maxLen] + "..."}+// ComputeCommandHash computes a SHA256 hash of command+targetType+targetID for replay protection.+// This ensures an approved ID can only be used to execute the exact command it was approved for.+func ComputeCommandHash(command, targetType, targetID string) string {+ h := sha256.New()+ h.Write([]byte(command))+ h.Write([]byte("|"))+ h.Write([]byte(targetType))+ h.Write([]byte("|"))+ h.Write([]byte(targetID))+ return hex.EncodeToString(h.Sum(nil))+}+// Global store instancevar (globalStore *Storediff --git a/internal/ai/tools/tools_control.go b/internal/ai/tools/tools_control.goindex 08b20b6520..569c2ea9ba 100644--- a/internal/ai/tools/tools_control.go+++ b/internal/ai/tools/tools_control.go@@ -114,9 +114,6 @@ func (e *PulseToolExecutor) executeRunCommand(ctx context.Context, args map[stri// Note: Control level read_only check is now centralized in registry.Execute()- // Check if this is a pre-approved execution (agentic loop re-executing after user approval)- preApproved := isPreApproved(args)-// Check security policy (skip block check - blocks cannot be pre-approved)decision := agentexec.PolicyAllowif e.policy != nil {@@ -133,12 +130,18 @@ func (e *PulseToolExecutor) executeRunCommand(ctx context.Context, args map[stri}}+ // Determine target type for approval validation+ targetType := "container"+ if runOnHost {+ targetType = "host"+ }++ // Check if this is a pre-approved execution with command hash validation+ // This validates the approval matches this exact command+target and marks it as consumed+ preApproved := consumeApprovalWithValidation(args, command, targetType, e.targetID)+// Skip approval checks if pre-approved or in autonomous modeif !preApproved && !e.isAutonomous && e.controlLevel == ControlLevelControlled {- targetType := "container"- if runOnHost {- targetType = "host"- }approvalID := createApprovalRecord(command, targetType, e.targetID, targetHost, "Control level requires approval")return NewTextResult(formatApprovalNeeded(command, "Control level requires approval", approvalID)), nil}@@ -149,10 +152,6 @@ func (e *PulseToolExecutor) executeRunCommand(ctx context.Context, args map[striMsg("Auto-approving command for autonomous investigation")}if !preApproved && decision == agentexec.PolicyRequireApproval && !e.isAutonomous {- targetType := "container"- if runOnHost {- targetType = "host"- }approvalID := createApprovalRecord(command, targetType, e.targetID, targetHost, "Security policy requires approval")return NewTextResult(formatApprovalNeeded(command, "Security policy requires approval", approvalID)), nil}@@ -968,6 +967,7 @@ func createApprovalRecord(command, targetType, targetID, targetName, context str// isPreApproved checks if the args contain a valid, approved approval_id.// This is used when the agentic loop re-executes a tool after user approval.+// DEPRECATED: Use consumeApprovalWithValidation instead for replay protection.func isPreApproved(args map[string]interface{}) bool {approvalID, ok := args["_approval_id"].(string)if !ok || approvalID == "" {@@ -994,6 +994,29 @@ func isPreApproved(args map[string]interface{}) bool {return false}+// consumeApprovalWithValidation validates and consumes an approval for a specific command.+// It verifies the command hash matches the approval and marks it as consumed (single-use).+// Returns true if the approval is valid and was consumed, false otherwise.+func consumeApprovalWithValidation(args map[string]interface{}, command, targetType, targetID string) bool {+ approvalID, ok := args["_approval_id"].(string)+ if !ok || approvalID == "" {+ return false+ }++ store := approval.GetStore()+ if store == nil {+ return false+ }++ _, err := store.ConsumeApproval(approvalID, command, targetType, targetID)+ if err != nil {+ log.Warn().Err(err).Str("approval_id", approvalID).Msg("Failed to consume approval")+ return false+ }++ return true+}+// Formatting helpers for control toolsfunc formatApprovalNeeded(command, reason, approvalID string) string {diff --git a/internal/api/router.go b/internal/api/router.goindex 1cc979a22b..371a0eb4a4 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -1398,10 +1398,11 @@ func (r *Router) setupRoutes() {r.mux.HandleFunc("/api/ai/cost/reset", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleResetAICostHistory)))r.mux.HandleFunc("/api/ai/cost/export", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.aiSettingsHandler.HandleExportAICostHistory)))// OAuth endpoints for Claude Pro/Max subscription authentication- r.mux.HandleFunc("/api/ai/oauth/start", RequireAdmin(r.config, r.aiSettingsHandler.HandleOAuthStart))- r.mux.HandleFunc("/api/ai/oauth/exchange", RequireAdmin(r.config, r.aiSettingsHandler.HandleOAuthExchange)) // Manual code input- r.mux.HandleFunc("/api/ai/oauth/callback", r.aiSettingsHandler.HandleOAuthCallback) // Public - receives redirect from Anthropic- r.mux.HandleFunc("/api/ai/oauth/disconnect", RequireAdmin(r.config, r.aiSettingsHandler.HandleOAuthDisconnect))+ // Require settings:write scope to prevent low-privilege tokens from modifying OAuth credentials+ r.mux.HandleFunc("/api/ai/oauth/start", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleOAuthStart)))+ r.mux.HandleFunc("/api/ai/oauth/exchange", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleOAuthExchange))) // Manual code input+ r.mux.HandleFunc("/api/ai/oauth/callback", r.aiSettingsHandler.HandleOAuthCallback) // Public - receives redirect from Anthropic+ r.mux.HandleFunc("/api/ai/oauth/disconnect", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleOAuthDisconnect)))// AI Patrol routes for background monitoring// Note: Status remains accessible so UI can show license/upgrade state@@ -1545,8 +1546,9 @@ func (r *Router) setupRoutes() {r.mux.HandleFunc("/api/ai/sessions/", RequireAuth(r.config, RequireScope(config.ScopeAIChat, r.routeAISessions)))// AI approval endpoints - for command approval workflow- r.mux.HandleFunc("/api/ai/approvals", RequireAuth(r.config, r.aiSettingsHandler.HandleListApprovals))- r.mux.HandleFunc("/api/ai/approvals/", RequireAuth(r.config, r.routeApprovals))+ // Require ai:execute scope to prevent low-privilege tokens from enumerating or denying approvals+ r.mux.HandleFunc("/api/ai/approvals", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleListApprovals)))+ r.mux.HandleFunc("/api/ai/approvals/", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.routeApprovals)))// AI question endpointsr.mux.HandleFunc("/api/ai/question/", RequireAuth(r.config, r.routeQuestions))