my-homelab-configs/apps/opsproof/overlay/services/jeannie_test.go

130 lines
5.2 KiB
Go

package services
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"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++
_, _ = response.Write([]byte(`{"id":"status-1","status":"failed","output":"OCI config loaded\n{\"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])
}
}
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 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("debian", "docker") {
t.Fatal("only the cluster application drill-down is enabled in this slice")
}
}
func TestProposalIsNotNeededWithoutProblemEvidence(t *testing.T) {
proposal := buildRemediationProposal(IncidentSnapshot{
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)
}
}