232 lines
9.6 KiB
Go
232 lines
9.6 KiB
Go
package services
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestStatusUsesAuthenticatedReadOnlyCommand(t *testing.T) {
|
|
requestCount := 0
|
|
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
|
if request.Header.Get("Authorization") != "Bearer test-token" {
|
|
t.Fatalf("authorization header was not set")
|
|
}
|
|
|
|
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 != "status" || len(payload.Args) != 2 || payload.Args[0] != "all" || payload.Args[1] != "--json" {
|
|
t.Fatalf("unexpected command payload: %#v", payload)
|
|
}
|
|
response.WriteHeader(http.StatusAccepted)
|
|
_, _ = response.Write([]byte(`{"id":"status-1","status":"queued"}`))
|
|
case "/v1/executions/status-1":
|
|
requestCount++
|
|
_ = json.NewEncoder(response).Encode(RemoteExecution{
|
|
ID: "status-1",
|
|
Status: "failed",
|
|
Output: strings.Repeat("bounded diagnostic output\n", 600) + `{"title":"Jeannie Status: all","mode":"fast","cluster":{"profile":"k3s","runtime":"k3s"},"rows":[{"status":"fail","area":"Kubernetes apps","check":"n8n","summary":"health=Progressing","detail":"private detail"}]}`,
|
|
})
|
|
default:
|
|
http.NotFound(response, request)
|
|
}
|
|
}))
|
|
defer server.Close()
|
|
|
|
client := NewJeannieClient(server.URL, "test-token")
|
|
client.PollInterval = time.Millisecond
|
|
snapshot, err := client.Status(context.Background())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if requestCount != 1 || snapshot.Cluster.Profile != "k3s" || len(snapshot.Rows) != 1 {
|
|
t.Fatalf("unexpected snapshot: %#v", snapshot)
|
|
}
|
|
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) {
|
|
client := NewJeannieClient("http://127.0.0.1:8787", "")
|
|
if _, err := client.Status(context.Background()); err == nil {
|
|
t.Fatal("expected missing token to fail")
|
|
}
|
|
}
|
|
|
|
func TestDecodeStatusOutputRejectsNonJSON(t *testing.T) {
|
|
if _, err := decodeStatusOutput("status unavailable"); err == nil {
|
|
t.Fatal("expected invalid output to fail")
|
|
}
|
|
}
|
|
|
|
func TestDecodeStatusOutputUsesFinalCompleteJSONObject(t *testing.T) {
|
|
output := "probe emitted {\"message\":\"broken\nline\"}\n" +
|
|
`{"title":"Jeannie Status: all","mode":"fast","cluster":{"profile":"k3s","runtime":"k3s"},"rows":[{"status":"ok","area":"Kubernetes","check":"API readiness","summary":"ok"}]}`
|
|
snapshot, err := decodeStatusOutput(output)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if snapshot.Title != "Jeannie Status: all" || len(snapshot.Rows) != 1 || snapshot.Rows[0].Check != "API readiness" {
|
|
t.Fatalf("unexpected snapshot: %#v", snapshot)
|
|
}
|
|
}
|
|
|
|
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 incident.Proposal.Status != "blocked" || incident.Proposal.ReadyForApproval || incident.Proposal.Action != "./jeannie doctor cluster n8n --ai" {
|
|
t.Fatalf("unexpected remediation proposal: %#v", incident.Proposal)
|
|
}
|
|
if len(incident.Proposal.EvidenceIDs) != 1 || incident.Proposal.EvidenceIDs[0] != "C01" {
|
|
t.Fatalf("proposal did not retain its evidence reference: %#v", incident.Proposal.EvidenceIDs)
|
|
}
|
|
if _, err := client.Doctor(context.Background(), "cluster", "n8n;shutdown"); err == nil {
|
|
t.Fatal("expected unsafe target to be rejected")
|
|
}
|
|
if !ValidDoctorTarget("opi5", "k3s-storage") || ValidDoctorTarget("opi5", "docker") || ValidDoctorTarget("debian", "docker") {
|
|
t.Fatal("Doctor target allowlist does not match the supported cluster and K3s storage routes")
|
|
}
|
|
}
|
|
|
|
func TestK3sStorageEvidenceBuildsOnlyTheGuardedRepair(t *testing.T) {
|
|
proposal := buildRemediationProposal(IncidentSnapshot{
|
|
Scope: "opi5",
|
|
Target: "k3s-storage",
|
|
Evidence: []IncidentEvidence{{
|
|
ID: "C01", Status: "fail", Area: "Orange Pi diagnostics", Check: "K3s storage evidence",
|
|
Summary: "Stale read-only K3s mount; the mounted device is no longer detected",
|
|
}},
|
|
})
|
|
if proposal.Action != "./jeannie doctor opi5 --repair-k3s" || proposal.Status != "blocked" {
|
|
t.Fatalf("unexpected K3s storage proposal: %#v", proposal)
|
|
}
|
|
arguments, ok := RemediationArguments("opi5", "k3s-storage")
|
|
if !ok || !ValidRemediationArguments("opi5", "k3s-storage", arguments) || ValidRemediationArguments("opi5", "k3s-storage", []string{"opi5", "--ai"}) {
|
|
t.Fatalf("unexpected K3s remediation arguments: %#v", arguments)
|
|
}
|
|
}
|
|
|
|
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 {
|
|
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" || strings.Join(payload.Args, " ") != "opi5 --json" {
|
|
t.Fatalf("unexpected K3s Doctor payload: %#v", payload)
|
|
}
|
|
response.WriteHeader(http.StatusAccepted)
|
|
_, _ = response.Write([]byte(`{"id":"doctor-k3s","status":"queued"}`))
|
|
case "/v1/executions/doctor-k3s":
|
|
_ = json.NewEncoder(response).Encode(RemoteExecution{
|
|
ID: "doctor-k3s", Status: "failed",
|
|
Output: `{"title":"Jeannie Doctor: opi5","rows":[{"status":"fail","area":"Orange Pi diagnostics","check":"K3s storage evidence","summary":"Stale read-only K3s mount; the mounted device is no longer detected"}]}`,
|
|
})
|
|
default:
|
|
http.NotFound(response, request)
|
|
}
|
|
}))
|
|
defer server.Close()
|
|
|
|
client := NewJeannieClient(server.URL, "test-token")
|
|
client.PollInterval = time.Millisecond
|
|
incident, err := client.Doctor(context.Background(), "opi5", "k3s-storage")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if incident.NextCommand != "./jeannie doctor opi5 --details" || incident.Proposal.Action != "./jeannie doctor opi5 --repair-k3s" {
|
|
t.Fatalf("unexpected K3s incident: %#v", incident)
|
|
}
|
|
}
|
|
|
|
func TestProposalIsNotNeededWithoutProblemEvidence(t *testing.T) {
|
|
proposal := buildRemediationProposal(IncidentSnapshot{
|
|
Scope: "cluster",
|
|
Target: "grafana",
|
|
ExecutionID: "doctor-ok",
|
|
NextCommand: "./jeannie doctor cluster grafana --details",
|
|
Evidence: []IncidentEvidence{{ID: "C01", Status: "ok"}},
|
|
})
|
|
if proposal.Status != "not-needed" || proposal.Action != "" || proposal.ReadyForApproval {
|
|
t.Fatalf("healthy evidence must not create an action: %#v", proposal)
|
|
}
|
|
}
|