From 277d17642eb5958ed5e435deca5e7a24cdcc87ad Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Sat, 5 Dec 2026 10:03:48 -0600 Subject: [PATCH] Generalize OpsProof incident policies --- apps/opsproof/README.md | 8 + .../overlay/resources/js/pages/Incident.tsx | 29 ++- .../overlay/resources/js/pages/Welcome.tsx | 15 +- .../overlay/services/incident_policy.go | 193 ++++++++++++++++++ apps/opsproof/overlay/services/jeannie.go | 102 +++------ .../opsproof/overlay/services/jeannie_test.go | 29 +++ docs/opsproof-architecture.md | 6 + .../jeannie/test_privacy_services_pipeline.py | 17 +- 8 files changed, 305 insertions(+), 94 deletions(-) create mode 100644 apps/opsproof/overlay/services/incident_policy.go diff --git a/apps/opsproof/README.md b/apps/opsproof/README.md index 5139de9..ff37fd8 100644 --- a/apps/opsproof/README.md +++ b/apps/opsproof/README.md @@ -74,6 +74,14 @@ Approval and execution revalidate the same evidence and fixed argument shape; the host-side recovery independently refuses busy mounts, ambiguous disks, filesystem identity mismatches, and pinned cluster identity mismatches. +Incident behavior is registered in the server-side policy catalog in +`overlay/services/incident_policy.go`. A policy declares its accepted route, +read-only Doctor arguments, evidence signature, exact remediation arguments, +risk and validation contract. Adding another supported incident therefore +adds a reviewed policy entry instead of adding route-specific conditionals to +the handlers. Evidence that does not match the selected policy remains visible +but cannot authorize that policy's action. + For warning or failing evidence, the same page now builds a proposal-only view model tied to the Doctor execution and evidence IDs. It shows the exact focused Jeannie/Holmes action, preconditions, risk, deterministic validation, diff --git a/apps/opsproof/overlay/resources/js/pages/Incident.tsx b/apps/opsproof/overlay/resources/js/pages/Incident.tsx index 05a94e3..14eac05 100644 --- a/apps/opsproof/overlay/resources/js/pages/Incident.tsx +++ b/apps/opsproof/overlay/resources/js/pages/Incident.tsx @@ -57,6 +57,23 @@ const tone: Record = { skip: 'border-slate-500/20 bg-slate-500/10 text-slate-400', }; +function desiredState(evidence: Evidence) { + if (evidence.status === 'ok') { + return 'The check passes without warning or failure.'; + } + if (evidence.status === 'skip') { + return 'The check is either not applicable or lacks enough evidence to assess.'; + } + return 'The check should be healthy or explicitly recorded as an intended exception.'; +} + +function rootCauseText(evidence: Evidence) { + if (evidence.status === 'ok' || evidence.status === 'skip') { + return 'No root-cause hypothesis is required for this evidence row.'; + } + return evidence.cause || 'Doctor did not establish a supported cause from this evidence.'; +} + export default function IncidentPage({ laravelVersion, view, operator }: Props) { const incident = view.incident; const [rollback, setRollback] = useState(''); @@ -131,16 +148,18 @@ export default function IncidentPage({ laravelVersion, view, operator }: Props)

Desired state

-

The declared check passes without warning or failure.

+

{desiredState(evidence)}

Observed state

{evidence.summary || 'No summary was returned.'}

Root-cause hypothesis

-

- {evidence.cause || 'Doctor did not establish a supported cause from this evidence.'} -

-

A hypothesis is not proof until deterministic validation succeeds.

+

{rootCauseText(evidence)}

+ {(evidence.status === 'warn' || evidence.status === 'fail') && ( +

+ A hypothesis is not proof until deterministic validation succeeds. +

+ )}
diff --git a/apps/opsproof/overlay/resources/js/pages/Welcome.tsx b/apps/opsproof/overlay/resources/js/pages/Welcome.tsx index 0130455..5708990 100644 --- a/apps/opsproof/overlay/resources/js/pages/Welcome.tsx +++ b/apps/opsproof/overlay/resources/js/pages/Welcome.tsx @@ -18,6 +18,7 @@ interface StatusRow { area: string; check: string; summary: string; + incidentPath?: string; } interface Overview { @@ -81,16 +82,6 @@ function doctorCommand(row: StatusRow) { return './jeannie doctor debian'; } -function incidentHref(row: StatusRow) { - if (row.area === 'Kubernetes apps') { - return `/incidents/cluster/${encodeURIComponent(row.check)}`; - } - if (row.area === 'Orange Pi' && (row.check === 'K3s runtime' || row.check === 'K3s storage mount')) { - return '/incidents/opi5/k3s-storage'; - } - return ''; -} - function LiveOverview({ overview }: { overview: Overview }) { const grouped = overview.rows.reduce>((areas, row) => { (areas[row.area] ??= []).push(row); @@ -171,9 +162,9 @@ function LiveOverview({ overview }: { overview: Overview }) { {doctorCommand(row)} - {incidentHref(row) && ( + {row.incidentPath && ( Open evidence → diff --git a/apps/opsproof/overlay/services/incident_policy.go b/apps/opsproof/overlay/services/incident_policy.go new file mode 100644 index 0000000..f824f09 --- /dev/null +++ b/apps/opsproof/overlay/services/incident_policy.go @@ -0,0 +1,193 @@ +package services + +import ( + "regexp" + "strings" +) + +type evidenceRule struct { + Area string + Check string + SummaryContains string + Statuses []string +} + +type statusRule struct { + Area string + Checks []string +} + +type incidentPolicy struct { + Scope string + Target string + TargetPattern *regexp.Regexp + DoctorArguments []string + NextCommand string + HealthySummary string + StatusRules []statusRule + EvidenceRules []evidenceRule + RemediationArguments []string + Action string + Summary string + RiskLevel string + Preconditions []string + RiskNotes []string + Rollback string + Validation []string +} + +var incidentPolicies = []incidentPolicy{ + { + Scope: "opi5", + Target: "k3s-storage", + DoctorArguments: []string{"opi5", "--json"}, + NextCommand: "./jeannie doctor opi5 --details", + HealthySummary: "SSD/K3s storage is healthy. No recovery action is applicable.", + StatusRules: []statusRule{{ + Area: "Orange Pi", Checks: []string{"K3s runtime", "K3s storage mount"}, + }}, + EvidenceRules: []evidenceRule{{ + Area: "Orange Pi diagnostics", Check: "K3s storage evidence", + SummaryContains: "Stale read-only K3s mount", Statuses: []string{"warn", "fail"}, + }}, + RemediationArguments: []string{"opi5", "--repair-k3s"}, + Action: "./jeannie doctor opi5 --repair-k3s", + Summary: "Recover the stale Orange Pi K3s runtime only after the guarded storage workflow revalidates the mounted device and pinned cluster identity.", + RiskLevel: "high", + Preconditions: []string{ + "Revalidate that the cited stale read-only mount evidence is current.", + "Require failed or inactive K3s and exactly one unmounted USB ext4 candidate.", + "Verify the candidate filesystem against the pinned K3s CA before replacing the mount.", + "Supply an operator-reviewed rollback procedure.", + }, + RiskNotes: []string{ + "The recovery stops private K3s workloads and changes host mount state.", + "A wrong storage identity could expose an unrelated filesystem, so device names are never trusted.", + "The workflow refuses busy mounts, ambiguous candidates, and cluster identity mismatches.", + }, + Rollback: "No automatic rollback is assumed. Keep K3s stopped and the candidate unmounted if any identity or readiness validation fails.", + Validation: []string{"./jeannie doctor opi5", "./jeannie status cluster"}, + }, + { + Scope: "cluster", + TargetPattern: kubernetesApplicationName, + DoctorArguments: []string{"cluster", "{target}", "--json"}, + NextCommand: "./jeannie doctor cluster {target} --details", + HealthySummary: "No warning or failing application evidence supports a remediation proposal.", + StatusRules: []statusRule{{Area: "Kubernetes apps"}}, + EvidenceRules: []evidenceRule{{Statuses: []string{"warn", "fail"}}}, + RemediationArguments: []string{"cluster", "{target}", "--ai"}, + Action: "./jeannie doctor cluster {target} --ai", + Summary: "Ask the focused Jeannie Doctor and Holmes workflow to diagnose, apply a supported targeted repair, and validate the result.", + RiskLevel: "high", + Preconditions: []string{ + "Authenticate an authorized operator.", + "Revalidate that the cited evidence execution is current.", + "Confirm Jeannie still advertises the exact Doctor command and arguments.", + "Establish a target-specific backup and rollback procedure.", + }, + RiskNotes: []string{ + "The Doctor/Holmes workflow can change Kubernetes runtime state.", + "AI root-cause hypotheses are not proof and may be incomplete.", + "The affected application may be temporarily unavailable during repair.", + }, + Rollback: "No target-specific rollback has been established automatically. Approval remains disabled until an operator supplies and validates one.", + Validation: []string{"./jeannie doctor cluster {target} --details", "./jeannie status cluster"}, + }, +} + +func incidentPathForStatus(row StatusRow) string { + for _, candidate := range incidentPolicies { + for _, rule := range candidate.StatusRules { + if row.Area != rule.Area || !statusCheckMatches(rule.Checks, row.Check) { + continue + } + target := candidate.Target + if target == "" && candidate.TargetPattern != nil && candidate.TargetPattern.MatchString(row.Check) { + target = row.Check + } + if target != "" { + return "/incidents/" + candidate.Scope + "/" + target + } + } + } + return "" +} + +func statusCheckMatches(checks []string, check string) bool { + if len(checks) == 0 { + return true + } + for _, candidate := range checks { + if candidate == check { + return true + } + } + return false +} + +func incidentPolicyFor(scope string, target string) (incidentPolicy, bool) { + for _, policy := range incidentPolicies { + if policy.Scope != scope { + continue + } + if policy.Target != "" && policy.Target == target { + return renderIncidentPolicy(policy, target), true + } + if policy.TargetPattern != nil && policy.TargetPattern.MatchString(target) { + return renderIncidentPolicy(policy, target), true + } + } + return incidentPolicy{}, false +} + +func renderIncidentPolicy(policy incidentPolicy, target string) incidentPolicy { + replace := func(value string) string { return strings.ReplaceAll(value, "{target}", target) } + renderSlice := func(values []string) []string { + rendered := make([]string, len(values)) + for index, value := range values { + rendered[index] = replace(value) + } + return rendered + } + policy.DoctorArguments = renderSlice(policy.DoctorArguments) + policy.RemediationArguments = renderSlice(policy.RemediationArguments) + policy.Validation = renderSlice(policy.Validation) + policy.NextCommand = replace(policy.NextCommand) + policy.Action = replace(policy.Action) + return policy +} + +func (rule evidenceRule) matches(evidence IncidentEvidence) bool { + if rule.Area != "" && evidence.Area != rule.Area { + return false + } + if rule.Check != "" && evidence.Check != rule.Check { + return false + } + if rule.SummaryContains != "" && !strings.Contains(evidence.Summary, rule.SummaryContains) { + return false + } + if len(rule.Statuses) == 0 { + return true + } + for _, status := range rule.Statuses { + if evidence.Status == status { + return true + } + } + return false +} + +func (policy incidentPolicy) matchingEvidenceIDs(evidence []IncidentEvidence) []string { + ids := []string{} + for _, item := range evidence { + for _, rule := range policy.EvidenceRules { + if rule.matches(item) { + ids = append(ids, item.ID) + break + } + } + } + return ids +} diff --git a/apps/opsproof/overlay/services/jeannie.go b/apps/opsproof/overlay/services/jeannie.go index 44fbc75..f747f22 100644 --- a/apps/opsproof/overlay/services/jeannie.go +++ b/apps/opsproof/overlay/services/jeannie.go @@ -20,10 +20,11 @@ const maxJeannieResponseBytes = 2 << 20 var kubernetesApplicationName = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?$`) type StatusRow struct { - Status string `json:"status"` - Area string `json:"area"` - Check string `json:"check"` - Summary string `json:"summary"` + Status string `json:"status"` + Area string `json:"area"` + Check string `json:"check"` + Summary string `json:"summary"` + IncidentPath string `json:"incidentPath,omitempty"` } type ClusterIdentity struct { @@ -111,25 +112,23 @@ func (client *JeannieClient) Status(ctx context.Context) (StatusSnapshot, error) if err != nil { return StatusSnapshot{}, err } + for index := range snapshot.Rows { + snapshot.Rows[index].IncidentPath = incidentPathForStatus(snapshot.Rows[index]) + } snapshot.CollectedAt = time.Now().UTC().Format(time.RFC3339) return snapshot, nil } func (client *JeannieClient) Doctor(ctx context.Context, scope string, target string) (IncidentSnapshot, error) { - if !ValidDoctorTarget(scope, target) { + policy, ok := incidentPolicyFor(scope, target) + if !ok { return IncidentSnapshot{}, errors.New("unsupported Doctor target") } if client.BaseURL == "" || client.Token == "" { return IncidentSnapshot{}, errors.New("Jeannie API connection is not configured") } - args := []string{scope, target, "--json"} - nextCommand := "./jeannie doctor cluster " + target + " --details" - if scope == "opi5" { - args = []string{"opi5", "--json"} - nextCommand = "./jeannie doctor opi5 --details" - } - completed, err := client.execute(ctx, "doctor", args, 60*time.Second) + completed, err := client.execute(ctx, "doctor", policy.DoctorArguments, 60*time.Second) if err != nil { return IncidentSnapshot{}, err } @@ -140,13 +139,14 @@ func (client *JeannieClient) Doctor(ctx context.Context, scope string, target st snapshot.Scope = scope snapshot.Target = target snapshot.ExecutionID = completed.ID - snapshot.NextCommand = nextCommand + snapshot.NextCommand = policy.NextCommand snapshot.Proposal = buildRemediationProposal(snapshot) snapshot.CollectedAt = time.Now().UTC().Format(time.RFC3339) return snapshot, nil } func buildRemediationProposal(incident IncidentSnapshot) RemediationProposal { + policy, ok := incidentPolicyFor(incident.Scope, incident.Target) proposal := RemediationProposal{ ID: "proposal-" + incident.ExecutionID, Status: "not-needed", @@ -158,78 +158,36 @@ func buildRemediationProposal(incident IncidentSnapshot) RemediationProposal { Rollback: "No change is proposed, so no rollback is required.", Validation: []string{incident.NextCommand, "./jeannie status cluster"}, } - for _, evidence := range incident.Evidence { - if evidence.Status == "warn" || evidence.Status == "fail" { - proposal.EvidenceIDs = append(proposal.EvidenceIDs, evidence.ID) - } + if !ok { + return proposal } + proposal.Summary = policy.HealthySummary + proposal.Validation = policy.Validation + proposal.EvidenceIDs = policy.matchingEvidenceIDs(incident.Evidence) if len(proposal.EvidenceIDs) == 0 { return proposal } - if incident.Scope == "opi5" { - storageFailure := false - for _, evidence := range incident.Evidence { - if evidence.Area == "Orange Pi diagnostics" && evidence.Check == "K3s storage evidence" && - (evidence.Status == "warn" || evidence.Status == "fail") && strings.Contains(evidence.Summary, "Stale read-only K3s mount") { - storageFailure = true - break - } - } - if !storageFailure { - return proposal - } - proposal.Status = "blocked" - proposal.Summary = "Recover the stale Orange Pi K3s runtime only after the guarded storage workflow revalidates the mounted device and pinned cluster identity." - proposal.Action = "./jeannie doctor opi5 --repair-k3s" - proposal.RiskLevel = "high" - proposal.Preconditions = []string{ - "Revalidate that the cited stale read-only mount evidence is current.", - "Require failed or inactive K3s and exactly one unmounted USB ext4 candidate.", - "Verify the candidate filesystem against the pinned K3s CA before replacing the mount.", - "Supply an operator-reviewed rollback procedure.", - } - proposal.RiskNotes = []string{ - "The recovery stops private K3s workloads and changes host mount state.", - "A wrong storage identity could expose an unrelated filesystem, so device names are never trusted.", - "The workflow refuses busy mounts, ambiguous candidates, and cluster identity mismatches.", - } - proposal.Rollback = "No automatic rollback is assumed. Keep K3s stopped and the candidate unmounted if any identity or readiness validation fails." - proposal.Validation = []string{"./jeannie doctor opi5", "./jeannie status cluster"} - return proposal - } - proposal.Status = "blocked" - proposal.Summary = "Ask the focused Jeannie Doctor and Holmes workflow to diagnose, apply a supported targeted repair, and validate the result." - proposal.Action = "./jeannie doctor cluster " + incident.Target + " --ai" - proposal.RiskLevel = "high" - proposal.Preconditions = []string{ - "Authenticate an authorized operator (not implemented in this slice).", - "Revalidate that the cited evidence execution is current.", - "Confirm Jeannie still advertises the exact Doctor command and arguments.", - "Establish a target-specific backup and rollback procedure.", - } - proposal.RiskNotes = []string{ - "The Doctor/Holmes workflow can change Kubernetes runtime state.", - "AI root-cause hypotheses are not proof and may be incomplete.", - "The affected application may be temporarily unavailable during repair.", - } - proposal.Rollback = "No target-specific rollback has been established automatically. Approval remains disabled until an operator supplies and validates one." + proposal.Summary = policy.Summary + proposal.Action = policy.Action + proposal.RiskLevel = policy.RiskLevel + proposal.Preconditions = policy.Preconditions + proposal.RiskNotes = policy.RiskNotes + proposal.Rollback = policy.Rollback return proposal } func ValidDoctorTarget(scope string, target string) bool { - return (scope == "cluster" && kubernetesApplicationName.MatchString(target)) || (scope == "opi5" && target == "k3s-storage") + _, ok := incidentPolicyFor(scope, target) + return ok } func RemediationArguments(scope string, target string) ([]string, bool) { - if scope == "cluster" && kubernetesApplicationName.MatchString(target) { - return []string{"cluster", target, "--ai"}, true + policy, ok := incidentPolicyFor(scope, target) + if !ok || len(policy.RemediationArguments) == 0 { + return nil, false } - if scope == "opi5" && target == "k3s-storage" { - return []string{"opi5", "--repair-k3s"}, true - } - return nil, false - + return policy.RemediationArguments, true } func ValidRemediationArguments(scope string, target string, arguments []string) bool { diff --git a/apps/opsproof/overlay/services/jeannie_test.go b/apps/opsproof/overlay/services/jeannie_test.go index 79734fb..433e1b9 100644 --- a/apps/opsproof/overlay/services/jeannie_test.go +++ b/apps/opsproof/overlay/services/jeannie_test.go @@ -56,6 +56,9 @@ func TestStatusUsesAuthenticatedReadOnlyCommand(t *testing.T) { if snapshot.Rows[0].Check != "n8n" || snapshot.Rows[0].Summary != "health=Progressing" { t.Fatalf("unexpected sanitized row: %#v", snapshot.Rows[0]) } + if snapshot.Rows[0].IncidentPath != "/incidents/cluster/n8n" { + t.Fatalf("policy catalog did not add the incident route: %#v", snapshot.Rows[0]) + } } func TestStatusFailsClosedWithoutCredentials(t *testing.T) { @@ -151,6 +154,31 @@ func TestK3sStorageEvidenceBuildsOnlyTheGuardedRepair(t *testing.T) { } } +func TestK3sStoragePolicyIgnoresUnrelatedWarnings(t *testing.T) { + proposal := buildRemediationProposal(IncidentSnapshot{ + Scope: "opi5", Target: "k3s-storage", ExecutionID: "healthy-storage", + Evidence: []IncidentEvidence{ + {ID: "C09", Status: "warn", Area: "Orange Pi OS", Check: "Systemd state", Summary: "degraded"}, + {ID: "C10", Status: "ok", Area: "Orange Pi diagnostics", Check: "K3s storage evidence", Summary: "No stale read-only K3s mount detected in this snapshot"}, + }, + }) + if proposal.Status != "not-needed" || proposal.Action != "" || len(proposal.EvidenceIDs) != 0 { + t.Fatalf("unrelated warnings must not become SSD remediation evidence: %#v", proposal) + } + if proposal.Summary != "SSD/K3s storage is healthy. No recovery action is applicable." { + t.Fatalf("unexpected healthy storage summary: %q", proposal.Summary) + } +} + +func TestPolicyCatalogDiscoversK3sStorageFromStatus(t *testing.T) { + if path := incidentPathForStatus(StatusRow{Area: "Orange Pi", Check: "K3s runtime"}); path != "/incidents/opi5/k3s-storage" { + t.Fatalf("unexpected K3s incident path: %q", path) + } + if path := incidentPathForStatus(StatusRow{Area: "Orange Pi OS", Check: "Systemd state"}); path != "" { + t.Fatalf("unrelated warning received an incident path: %q", path) + } +} + func TestDoctorCollectsFocusedK3sStorageEvidence(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { switch request.URL.Path { @@ -191,6 +219,7 @@ func TestDoctorCollectsFocusedK3sStorageEvidence(t *testing.T) { func TestProposalIsNotNeededWithoutProblemEvidence(t *testing.T) { proposal := buildRemediationProposal(IncidentSnapshot{ + Scope: "cluster", Target: "grafana", ExecutionID: "doctor-ok", NextCommand: "./jeannie doctor cluster grafana --details", diff --git a/docs/opsproof-architecture.md b/docs/opsproof-architecture.md index 437cbbd..c504a13 100644 --- a/docs/opsproof-architecture.md +++ b/docs/opsproof-architecture.md @@ -75,6 +75,12 @@ confirmed by deterministic validation. It may execute only the identity-pinned `doctor opi5 --repair-k3s` workflow when the API policy is enabled and current evidence has the exact stale read-only mount signature. +- Register supported incident types in the server-side policy catalog. Each + entry owns its route matcher, read-only collection arguments, evidence + signature, fixed remediation arguments, risk, rollback and validation + contract. Handlers consume the catalog and never construct commands from + arbitrary route input. Unmatched warnings stay visible but cannot authorize + an unrelated remediation. - Bind every remediation proposal to one Doctor execution and its evidence IDs. Keep the proposal blocked when identity, current-evidence validation, or a target-specific rollback is absent; rendering a command never grants the diff --git a/tests/jeannie/test_privacy_services_pipeline.py b/tests/jeannie/test_privacy_services_pipeline.py index e69e290..eedc62a 100644 --- a/tests/jeannie/test_privacy_services_pipeline.py +++ b/tests/jeannie/test_privacy_services_pipeline.py @@ -113,7 +113,7 @@ class OpsProofPipelineTests(unittest.TestCase): self.assertIn("Live read-only inventory", page) self.assertIn("Desired: declared intent satisfied", page) self.assertIn("bearer token retained server-side", page) - self.assertIn("/incidents/cluster/", page) + self.assertIn("row.incidentPath", page) self.assertIn("Open evidence", page) self.assertIn("./jeannie doctor opi5 --repair-k3s", page) @@ -122,7 +122,7 @@ class OpsProofPipelineTests(unittest.TestCase): ) self.assertIn('client.execute(ctx, "status"', client) self.assertIn('[]string{"all", "--json"}', client) - self.assertIn('[]string{scope, target, "--json"}', client) + self.assertIn("policy.DoctorArguments", client) self.assertIn("unsupported Doctor target", client) self.assertNotIn("Detail string", client) @@ -139,9 +139,16 @@ class OpsProofPipelineTests(unittest.TestCase): self.assertIn("ReadyForApproval bool", client) self.assertIn('proposal.Status = "blocked"', client) - self.assertIn('"./jeannie doctor cluster " + incident.Target + " --ai"', client) - self.assertIn('"./jeannie doctor opi5 --repair-k3s"', client) - self.assertIn('target == "k3s-storage"', client) + policy = (ROOT / "apps/opsproof/overlay/services/incident_policy.go").read_text( + encoding="utf-8" + ) + self.assertIn('"k3s-storage"', policy) + self.assertIn('"./jeannie doctor opi5 --repair-k3s"', policy) + self.assertIn("matchingEvidenceIDs", policy) + self.assertIn("incidentPolicies", policy) + self.assertIn("incidentPathForStatus", policy) + self.assertIn("SSD/K3s storage is healthy", policy) + self.assertIn("desiredState(evidence)", incident) auth_handler = ( ROOT / "apps/opsproof/overlay/handlers/authentication/authentication.go"