diff --git a/apps/opsproof/README.md b/apps/opsproof/README.md index 0d2db0a..f957a8b 100644 --- a/apps/opsproof/README.md +++ b/apps/opsproof/README.md @@ -57,6 +57,14 @@ OpsProof fails closed and labels the overview unavailable instead of presenting stale data as current. Warning and failing checks show a read-only focused Doctor command but cannot submit it. +Unhealthy Kubernetes applications link to +`/incidents/cluster/{application}`. The incident page runs the exact focused +Doctor target with `--json`, assigns stable evidence IDs to the returned rows, +and presents bounded command-output excerpts, observed state, missing evidence, +and root-cause hypotheses. Route input is restricted to Kubernetes application +names and cannot become arbitrary Jeannie arguments. The page deliberately has +no mitigation control. + ## Security boundary OpsProof is not a shell console. @@ -79,7 +87,8 @@ Each slice should be a small, independently testable commit: 1. architecture decision and API contract; 2. Laravel Go/Inertia application shell and health page; 3. read-only homelab overview backed by Jeannie status; -4. incident evidence page backed by Doctor output; +4. incident evidence page backed by Doctor output (implemented for Kubernetes + applications); 5. remediation proposal with risk and rollback details; 6. Dex login and operator authorization; 7. approval-gated execution and live progress; diff --git a/apps/opsproof/overlay/handlers/incident/show.go b/apps/opsproof/overlay/handlers/incident/show.go new file mode 100644 index 0000000..66840e4 --- /dev/null +++ b/apps/opsproof/overlay/handlers/incident/show.go @@ -0,0 +1,41 @@ +package incident + +import ( + "log" + "net/http" + + laravel "go.laravel.com" + "go.laravel.com/inertia" + "go.laravel.com/web" + + "app/services" +) + +type view struct { + Available bool `json:"available"` + Message string `json:"message"` + Incident services.IncidentSnapshot `json:"incident"` +} + +func Show(request *web.Request) *web.Response { + scope := request.PathValue("scope") + target := request.PathValue("target") + if !services.ValidDoctorTarget(scope, target) { + return web.Abort(http.StatusNotFound) + } + + result := view{Message: "Focused Doctor evidence is temporarily unavailable."} + incident, err := services.From(request.Context()).Jeannie.Doctor(request.Context(), scope, target) + if err != nil { + log.Printf("OpsProof could not collect Doctor evidence for %s/%s: %v", scope, target, err) + } else { + result.Available = true + result.Message = "Read-only evidence collected by the focused Jeannie Doctor." + result.Incident = incident + } + + return inertia.Render("Incident", inertia.Props{ + "laravelVersion": laravel.Version, + "view": result, + }) +} diff --git a/apps/opsproof/overlay/resources/js/pages/Incident.tsx b/apps/opsproof/overlay/resources/js/pages/Incident.tsx new file mode 100644 index 0000000..e3a887c --- /dev/null +++ b/apps/opsproof/overlay/resources/js/pages/Incident.tsx @@ -0,0 +1,157 @@ +interface Evidence { + id: string; + status: string; + area: string; + check: string; + summary: string; + output: string; + cause: string; +} + +interface Incident { + scope: string; + target: string; + title: string; + executionId: string; + evidence: Evidence[]; + missingEvidence: string[]; + nextCommand: string; + collectedAt: string; +} + +interface Props { + laravelVersion: string; + view: { + available: boolean; + message: string; + incident: Incident; + }; +} + +const tone: Record = { + ok: 'border-emerald-300/20 bg-emerald-300/10 text-emerald-200', + warn: 'border-amber-300/20 bg-amber-300/10 text-amber-200', + fail: 'border-rose-300/20 bg-rose-300/10 text-rose-200', + skip: 'border-slate-500/20 bg-slate-500/10 text-slate-400', +}; + +export default function IncidentPage({ laravelVersion, view }: Props) { + const incident = view.incident; + + return ( +
+
+
+
+
+ + ← Homelab overview + +

OpsProof incident evidence

+
+ + Read-only investigation + +
+ + {!view.available ? ( +
+

Evidence unavailable

+

Doctor could not complete this investigation

+

{view.message}

+

+ OpsProof does not reuse stale evidence and cannot submit a mitigation from this page. +

+
+ ) : ( + <> +
+
+

+ {incident.scope} / {incident.target} +

+

+ {incident.title || 'Focused Doctor investigation'} +

+

{view.message}

+
+
+

EXECUTION {incident.executionId}

+

COLLECTED {incident.collectedAt}

+
+
+ +
+ {incident.evidence.map((evidence) => ( +
+
+
+ {evidence.id} +
+

{evidence.check}

+

{evidence.area}

+
+
+ + {evidence.status} + +
+
+
+

Desired state

+

The declared check passes without warning or failure.

+

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.

+
+
+
+

Command output excerpt

+
+                                            {evidence.output || 'No detailed output was returned for this evidence row.'}
+                                        
+
+
+ ))} +
+ +
+
+

Missing evidence

+ {incident.missingEvidence.length === 0 ? ( +

No empty deterministic evidence rows were detected.

+ ) : ( +
    + {incident.missingEvidence.map((item) => ( +
  • • {item}
  • + ))} +
+ )} +
+
+

Read-only next command

+ + {incident.nextCommand} + + +
+
+ + )} + +
+ Laravel Go {laravelVersion} · Jeannie evidence retained server-side. + Raw execution output is not exposed as an action surface. +
+
+
+ ); +} diff --git a/apps/opsproof/overlay/resources/js/pages/Welcome.tsx b/apps/opsproof/overlay/resources/js/pages/Welcome.tsx index f5595d8..79478d9 100644 --- a/apps/opsproof/overlay/resources/js/pages/Welcome.tsx +++ b/apps/opsproof/overlay/resources/js/pages/Welcome.tsx @@ -147,9 +147,19 @@ function LiveOverview({ overview }: { overview: Overview }) { {(row.status === 'warn' || row.status === 'fail') && ( - - {doctorCommand(row)} - +
+ + {doctorCommand(row)} + + {row.area === 'Kubernetes apps' && ( + + Open evidence → + + )} +
)} ))} diff --git a/apps/opsproof/overlay/routes/web.go b/apps/opsproof/overlay/routes/web.go new file mode 100644 index 0000000..a31ff42 --- /dev/null +++ b/apps/opsproof/overlay/routes/web.go @@ -0,0 +1,21 @@ +package routes + +import ( + "net/http" + + "go.laravel.com/config" + "go.laravel.com/routing" + "go.laravel.com/web" + + "app/handlers/incident" + "app/handlers/welcome" +) + +func Web(route *routing.Router, cfg *config.Config) { + route.Get("/", welcome.Show) + route.Get("/incidents/{scope}/{target}", incident.Show) + + route.Fallback(func(*web.Request) *web.Response { + return web.Abort(http.StatusNotFound) + }) +} diff --git a/apps/opsproof/overlay/services/jeannie.go b/apps/opsproof/overlay/services/jeannie.go index 041b563..66fbd81 100644 --- a/apps/opsproof/overlay/services/jeannie.go +++ b/apps/opsproof/overlay/services/jeannie.go @@ -9,12 +9,15 @@ import ( "io" "net/http" "os" + "regexp" "strings" "time" ) 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"` @@ -35,6 +38,27 @@ type StatusSnapshot struct { CollectedAt string `json:"collectedAt"` } +type IncidentEvidence struct { + ID string `json:"id"` + Status string `json:"status"` + Area string `json:"area"` + Check string `json:"check"` + Summary string `json:"summary"` + Output string `json:"output"` + Cause string `json:"cause"` +} + +type IncidentSnapshot struct { + Scope string `json:"scope"` + Target string `json:"target"` + Title string `json:"title"` + ExecutionID string `json:"executionId"` + Evidence []IncidentEvidence `json:"evidence"` + MissingEvidence []string `json:"missingEvidence"` + NextCommand string `json:"nextCommand"` + CollectedAt string `json:"collectedAt"` +} + type JeannieClient struct { BaseURL string Token string @@ -63,51 +87,44 @@ func (client *JeannieClient) Status(ctx context.Context) (StatusSnapshot, error) return StatusSnapshot{}, errors.New("Jeannie API connection is not configured") } - ctx, cancel := context.WithTimeout(ctx, 30*time.Second) - defer cancel() - - payload, err := json.Marshal(map[string]any{ - "command": "status", - "args": []string{"all", "--json"}, - }) + completed, err := client.execute(ctx, "status", []string{"all", "--json"}, 30*time.Second) if err != nil { - return StatusSnapshot{}, fmt.Errorf("encode status request: %w", err) + return StatusSnapshot{}, err + } + snapshot, err := decodeStatusOutput(completed.Output) + if err != nil { + return StatusSnapshot{}, err + } + 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 scope != "cluster" || !kubernetesApplicationName.MatchString(target) { + return IncidentSnapshot{}, errors.New("unsupported Doctor target") + } + if client.BaseURL == "" || client.Token == "" { + return IncidentSnapshot{}, errors.New("Jeannie API connection is not configured") } - var submitted execution - if err := client.request(ctx, http.MethodPost, "/v1/execute", bytes.NewReader(payload), &submitted); err != nil { - return StatusSnapshot{}, fmt.Errorf("submit status request: %w", err) + completed, err := client.execute(ctx, "doctor", []string{scope, target, "--json"}, 60*time.Second) + if err != nil { + return IncidentSnapshot{}, err } - if submitted.ID == "" { - return StatusSnapshot{}, errors.New("Jeannie API returned an empty execution ID") + snapshot, err := decodeDoctorOutput(completed.Output) + if err != nil { + return IncidentSnapshot{}, err } + snapshot.Scope = scope + snapshot.Target = target + snapshot.ExecutionID = completed.ID + snapshot.NextCommand = "./jeannie doctor cluster " + target + " --details" + snapshot.CollectedAt = time.Now().UTC().Format(time.RFC3339) + return snapshot, nil +} - for { - var current execution - if err := client.request(ctx, http.MethodGet, "/v1/executions/"+submitted.ID, nil, ¤t); err != nil { - return StatusSnapshot{}, fmt.Errorf("read status execution: %w", err) - } - - switch current.Status { - case "queued", "running": - timer := time.NewTimer(client.PollInterval) - select { - case <-ctx.Done(): - timer.Stop() - return StatusSnapshot{}, fmt.Errorf("wait for status execution: %w", ctx.Err()) - case <-timer.C: - } - case "succeeded", "failed": - snapshot, err := decodeStatusOutput(current.Output) - if err != nil { - return StatusSnapshot{}, err - } - snapshot.CollectedAt = time.Now().UTC().Format(time.RFC3339) - return snapshot, nil - default: - return StatusSnapshot{}, fmt.Errorf("Jeannie API returned unknown execution state %q", current.Status) - } - } +func ValidDoctorTarget(scope string, target string) bool { + return scope == "cluster" && kubernetesApplicationName.MatchString(target) } type execution struct { @@ -116,6 +133,44 @@ type execution struct { Output string `json:"output"` } +func (client *JeannieClient) execute(ctx context.Context, command string, args []string, timeout time.Duration) (execution, error) { + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + payload, err := json.Marshal(map[string]any{"command": command, "args": args}) + if err != nil { + return execution{}, fmt.Errorf("encode %s request: %w", command, err) + } + var submitted execution + if err := client.request(ctx, http.MethodPost, "/v1/execute", bytes.NewReader(payload), &submitted); err != nil { + return execution{}, fmt.Errorf("submit %s request: %w", command, err) + } + if submitted.ID == "" { + return execution{}, errors.New("Jeannie API returned an empty execution ID") + } + + for { + var current execution + if err := client.request(ctx, http.MethodGet, "/v1/executions/"+submitted.ID, nil, ¤t); err != nil { + return execution{}, fmt.Errorf("read %s execution: %w", command, err) + } + switch current.Status { + case "queued", "running": + timer := time.NewTimer(client.PollInterval) + select { + case <-ctx.Done(): + timer.Stop() + return execution{}, fmt.Errorf("wait for %s execution: %w", command, ctx.Err()) + case <-timer.C: + } + case "succeeded", "failed": + return current, nil + default: + return execution{}, fmt.Errorf("Jeannie API returned unknown execution state %q", current.Status) + } + } +} + func (client *JeannieClient) request(ctx context.Context, method string, path string, body io.Reader, target any) error { request, err := http.NewRequestWithContext(ctx, method, client.BaseURL+path, body) if err != nil { @@ -156,3 +211,62 @@ func decodeStatusOutput(output string) (StatusSnapshot, error) { } return snapshot, nil } + +func decodeDoctorOutput(output string) (IncidentSnapshot, error) { + type doctorRow struct { + Status string `json:"status"` + Area string `json:"area"` + Check string `json:"check"` + Summary string `json:"summary"` + Detail string `json:"detail"` + Cause string `json:"cause"` + } + var report struct { + Title string `json:"title"` + Rows []doctorRow `json:"rows"` + } + start := strings.Index(output, "{") + if start < 0 { + return IncidentSnapshot{}, errors.New("Jeannie Doctor output did not contain JSON") + } + if err := json.Unmarshal([]byte(output[start:]), &report); err != nil { + return IncidentSnapshot{}, fmt.Errorf("decode Jeannie Doctor output: %w", err) + } + if report.Rows == nil { + return IncidentSnapshot{}, errors.New("Jeannie Doctor output did not contain rows") + } + + snapshot := IncidentSnapshot{Title: report.Title, Evidence: make([]IncidentEvidence, 0, len(report.Rows))} + for index, row := range report.Rows { + snapshot.Evidence = append(snapshot.Evidence, IncidentEvidence{ + ID: fmt.Sprintf("C%02d", index+1), + Status: row.Status, + Area: row.Area, + Check: row.Check, + Summary: cleanExcerpt(row.Summary, 800), + Output: cleanExcerpt(row.Detail, 4000), + Cause: cleanExcerpt(row.Cause, 1200), + }) + if strings.TrimSpace(row.Detail) == "" { + snapshot.MissingEvidence = append(snapshot.MissingEvidence, fmt.Sprintf("C%02d has no detailed command output.", index+1)) + } + } + if len(report.Rows) == 0 { + snapshot.MissingEvidence = append(snapshot.MissingEvidence, "Doctor returned no evidence rows.") + } + return snapshot, nil +} + +func cleanExcerpt(value string, limit int) string { + value = strings.Map(func(character rune) rune { + if character == '\n' || character == '\t' || character >= 32 { + return character + } + return -1 + }, strings.TrimSpace(value)) + characters := []rune(value) + if len(characters) <= limit { + return value + } + return string(characters[:limit]) + "\n[excerpt truncated by OpsProof]" +} diff --git a/apps/opsproof/overlay/services/jeannie_test.go b/apps/opsproof/overlay/services/jeannie_test.go index 3c7254f..6216216 100644 --- a/apps/opsproof/overlay/services/jeannie_test.go +++ b/apps/opsproof/overlay/services/jeannie_test.go @@ -65,3 +65,47 @@ func TestDecodeStatusOutputRejectsNonJSON(t *testing.T) { t.Fatal("expected invalid output to fail") } } + +func TestDoctorNormalizesEvidenceAndRejectsArbitraryTargets(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { + switch request.URL.Path { + case "/v1/execute": + var payload struct { + Command string `json:"command"` + Args []string `json:"args"` + } + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Fatal(err) + } + if payload.Command != "doctor" || len(payload.Args) != 3 || payload.Args[0] != "cluster" || payload.Args[1] != "n8n" || payload.Args[2] != "--json" { + t.Fatalf("unexpected Doctor payload: %#v", payload) + } + response.WriteHeader(http.StatusAccepted) + _, _ = response.Write([]byte(`{"id":"doctor-1","status":"queued"}`)) + case "/v1/executions/doctor-1": + _, _ = response.Write([]byte(`{"id":"doctor-1","status":"failed","output":"config loaded\n{\"title\":\"Jeannie Doctor: cluster / n8n\",\"rows\":[{\"status\":\"fail\",\"area\":\"Kubernetes apps\",\"check\":\"n8n\",\"summary\":\"health=Progressing\",\"detail\":\"$ kubectl get pod\\nCrashLoopBackOff\",\"cause\":\"The container exits during startup.\",\"fix\":\"kubectl delete pod\"}]}"}`)) + default: + http.NotFound(response, request) + } + })) + defer server.Close() + + client := NewJeannieClient(server.URL, "test-token") + client.PollInterval = time.Millisecond + incident, err := client.Doctor(context.Background(), "cluster", "n8n") + if err != nil { + t.Fatal(err) + } + if incident.ExecutionID != "doctor-1" || incident.NextCommand != "./jeannie doctor cluster n8n --details" { + t.Fatalf("unexpected incident metadata: %#v", incident) + } + if len(incident.Evidence) != 1 || incident.Evidence[0].ID != "C01" || incident.Evidence[0].Cause == "" { + t.Fatalf("unexpected normalized evidence: %#v", incident.Evidence) + } + if _, err := client.Doctor(context.Background(), "cluster", "n8n;shutdown"); err == nil { + t.Fatal("expected unsafe target to be rejected") + } + if ValidDoctorTarget("debian", "docker") { + t.Fatal("only the cluster application drill-down is enabled in this slice") + } +} diff --git a/apps/opsproof/overlay/tests/feature/incident_test.go b/apps/opsproof/overlay/tests/feature/incident_test.go new file mode 100644 index 0000000..240fb38 --- /dev/null +++ b/apps/opsproof/overlay/tests/feature/incident_test.go @@ -0,0 +1,29 @@ +package feature_test + +import ( + "net/http" + "net/http/httptest" + "testing" + + "app/services" + "app/tests" +) + +func TestIncidentPageRendersDeterministicDoctorEvidence(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { + switch request.URL.Path { + case "/v1/execute": + response.WriteHeader(http.StatusAccepted) + _, _ = response.Write([]byte(`{"id":"doctor-1","status":"queued"}`)) + case "/v1/executions/doctor-1": + _, _ = response.Write([]byte(`{"id":"doctor-1","status":"failed","output":"{\"title\":\"Jeannie Doctor: cluster / n8n\",\"rows\":[{\"status\":\"fail\",\"area\":\"Kubernetes apps\",\"check\":\"n8n\",\"summary\":\"health=Progressing\",\"detail\":\"CrashLoopBackOff\",\"cause\":\"The container exits during startup.\"}]}"}`)) + default: + http.NotFound(response, request) + } + })) + defer server.Close() + + client := tests.New(t) + services.From(client.Context()).Jeannie = services.NewJeannieClient(server.URL, "test-token") + client.Get("/incidents/cluster/n8n").AssertOK().AssertInertia("Incident") +} diff --git a/docs/opsproof-architecture.md b/docs/opsproof-architecture.md index 0c9da56..39daea2 100644 --- a/docs/opsproof-architecture.md +++ b/docs/opsproof-architecture.md @@ -65,6 +65,9 @@ confirmed by deterministic validation. differs from the proposal. - Collect the overview through Jeannie's authenticated, read-only status command and expose only sanitized status fields to browser props. +- Constrain incident routes to known target types, collect focused Doctor JSON + server-side, and expose bounded evidence excerpts rather than executable + commands or the complete private response. ## Why not Laravel Rust now? diff --git a/tests/jeannie/test_privacy_services_pipeline.py b/tests/jeannie/test_privacy_services_pipeline.py index 82c8880..85e738d 100644 --- a/tests/jeannie/test_privacy_services_pipeline.py +++ b/tests/jeannie/test_privacy_services_pipeline.py @@ -107,15 +107,27 @@ 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("Open evidence", page) self.assertIn("./jeannie doctor opi5 --repair-k3s", page) client = (ROOT / "apps/opsproof/overlay/services/jeannie.go").read_text( encoding="utf-8" ) - self.assertIn('"command": "status"', client) + self.assertIn('client.execute(ctx, "status"', client) self.assertIn('[]string{"all", "--json"}', client) + self.assertIn('[]string{scope, target, "--json"}', client) + self.assertIn("unsupported Doctor target", client) self.assertNotIn("Detail string", client) + incident = (ROOT / "apps/opsproof/overlay/resources/js/pages/Incident.tsx").read_text( + encoding="utf-8" + ) + self.assertIn("Command output excerpt", incident) + self.assertIn("Root-cause hypothesis", incident) + self.assertIn("No mitigation in this slice", incident) + self.assertNotIn("fetch('/v1/execute", incident) + if __name__ == "__main__": unittest.main()