package services import ( "bytes" "context" "crypto/sha256" "encoding/json" "errors" "fmt" "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"` Check string `json:"check"` Summary string `json:"summary"` IncidentPath string `json:"incidentPath,omitempty"` } type ClusterIdentity struct { Profile string `json:"profile"` Runtime string `json:"runtime"` } type StatusSnapshot struct { Title string `json:"title"` Mode string `json:"mode"` Rows []StatusRow `json:"rows"` Cluster ClusterIdentity `json:"cluster"` 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"` Proposal RemediationProposal `json:"proposal"` CollectedAt string `json:"collectedAt"` } type RemediationProposal struct { ID string `json:"id"` Status string `json:"status"` Summary string `json:"summary"` Action string `json:"action"` RiskLevel string `json:"riskLevel"` EvidenceIDs []string `json:"evidenceIds"` Preconditions []string `json:"preconditions"` RiskNotes []string `json:"riskNotes"` Rollback string `json:"rollback"` Validation []string `json:"validation"` ReadyForApproval bool `json:"readyForApproval"` } type JeannieClient struct { BaseURL string Token string HTTPClient *http.Client PollInterval time.Duration } func NewJeannieClient(baseURL string, token string) *JeannieClient { return &JeannieClient{ BaseURL: strings.TrimRight(baseURL, "/"), Token: token, HTTPClient: &http.Client{Timeout: 10 * time.Second}, PollInterval: 250 * time.Millisecond, } } func NewJeannieClientFromEnv() *JeannieClient { return NewJeannieClient( os.Getenv("OPSPROOF_JEANNIE_URL"), os.Getenv("OPSPROOF_JEANNIE_TOKEN"), ) } func (client *JeannieClient) Status(ctx context.Context) (StatusSnapshot, error) { if client.BaseURL == "" || client.Token == "" { return StatusSnapshot{}, errors.New("Jeannie API connection is not configured") } completed, err := client.execute(ctx, "status", []string{"all", "--json"}, 30*time.Second) if err != nil { return StatusSnapshot{}, err } snapshot, err := decodeStatusOutput(completed.Output) 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) { 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") } completed, err := client.execute(ctx, "doctor", policy.DoctorArguments, 60*time.Second) if err != nil { return IncidentSnapshot{}, err } snapshot, err := decodeDoctorOutput(completed.Output) if err != nil { return IncidentSnapshot{}, err } snapshot.Scope = scope snapshot.Target = target snapshot.ExecutionID = completed.ID 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", Summary: "No warning or failing evidence supports a remediation proposal.", RiskLevel: "none", EvidenceIDs: []string{}, Preconditions: []string{}, RiskNotes: []string{}, Rollback: "No change is proposed, so no rollback is required.", Validation: []string{incident.NextCommand, "./jeannie status cluster"}, } 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 } proposal.Status = "blocked" 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 { _, ok := incidentPolicyFor(scope, target) return ok } func RemediationArguments(scope string, target string) ([]string, bool) { policy, ok := incidentPolicyFor(scope, target) if !ok || len(policy.RemediationArguments) == 0 { return nil, false } return policy.RemediationArguments, true } func ValidRemediationArguments(scope string, target string, arguments []string) bool { expected, ok := RemediationArguments(scope, target) if !ok || len(arguments) != len(expected) { return false } for index := range expected { if arguments[index] != expected[index] { return false } } return true } type execution struct { ID string `json:"id"` Status string `json:"status"` Output string `json:"output"` Error string `json:"error"` } type RemoteExecution struct { ID string `json:"id"` Status string `json:"status"` Output string `json:"output"` Error string `json:"error"` } func (client *JeannieClient) CommandAllowed(ctx context.Context, command string) (bool, error) { var response struct { Commands []string `json:"commands"` } if err := client.request(ctx, http.MethodGet, "/v1/commands", nil, &response); err != nil { return false, err } for _, allowed := range response.Commands { if allowed == command { return true, nil } } return false, nil } func (client *JeannieClient) Submit(ctx context.Context, command string, args []string) (RemoteExecution, error) { payload, err := json.Marshal(map[string]any{"command": command, "args": args}) if err != nil { return RemoteExecution{}, err } var submitted RemoteExecution if err := client.request(ctx, http.MethodPost, "/v1/execute", bytes.NewReader(payload), &submitted); err != nil { return RemoteExecution{}, err } if submitted.ID == "" { return RemoteExecution{}, errors.New("Jeannie API returned an empty execution ID") } return submitted, nil } func (client *JeannieClient) Execution(ctx context.Context, id string) (RemoteExecution, error) { return client.execution(ctx, id, true) } func (client *JeannieClient) execution(ctx context.Context, id string, bounded bool) (RemoteExecution, error) { if !kubernetesApplicationName.MatchString(id) { return RemoteExecution{}, errors.New("invalid Jeannie execution ID") } var current RemoteExecution if err := client.request(ctx, http.MethodGet, "/v1/executions/"+id, nil, ¤t); err != nil { return RemoteExecution{}, err } if bounded { current.Output = cleanExcerpt(current.Output, 12000) } current.Error = cleanExcerpt(current.Error, 1200) return current, nil } func EvidenceFingerprint(incident IncidentSnapshot) (string, error) { payload, err := json.Marshal(struct { Scope string `json:"scope"` Target string `json:"target"` Evidence []IncidentEvidence `json:"evidence"` }{incident.Scope, incident.Target, incident.Evidence}) if err != nil { return "", err } hash := sha256.Sum256(payload) return fmt.Sprintf("%x", hash[:]), nil } func (client *JeannieClient) execute(ctx context.Context, command string, args []string, timeout time.Duration) (execution, error) { ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() submitted, err := client.Submit(ctx, command, args) if err != nil { return execution{}, fmt.Errorf("submit %s request: %w", command, err) } for { remote, err := client.execution(ctx, submitted.ID, false) if err != nil { return execution{}, fmt.Errorf("read %s execution: %w", command, err) } current := execution(remote) 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 { return err } request.Header.Set("Authorization", "Bearer "+client.Token) if body != nil { request.Header.Set("Content-Type", "application/json") } response, err := client.HTTPClient.Do(request) if err != nil { return err } defer response.Body.Close() if response.StatusCode < 200 || response.StatusCode >= 300 { _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096)) return fmt.Errorf("Jeannie API returned HTTP %d", response.StatusCode) } if err := json.NewDecoder(io.LimitReader(response.Body, maxJeannieResponseBytes)).Decode(target); err != nil { return fmt.Errorf("decode Jeannie API response: %w", err) } return nil } func decodeStatusOutput(output string) (StatusSnapshot, error) { var snapshot StatusSnapshot if err := decodeFinalJSONObject(output, &snapshot); err != nil { return StatusSnapshot{}, fmt.Errorf("decode Jeannie status output: %w", err) } if snapshot.Rows == nil { return StatusSnapshot{}, errors.New("Jeannie status output did not contain rows") } 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"` } if err := decodeFinalJSONObject(output, &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 decodeFinalJSONObject(output string, target any) error { searchEnd := len(output) for searchEnd > 0 { start := strings.LastIndex(output[:searchEnd], "{") if start < 0 { break } candidate := strings.TrimSpace(output[start:]) var raw json.RawMessage decoder := json.NewDecoder(strings.NewReader(candidate)) if err := decoder.Decode(&raw); err == nil { var trailing any if err := decoder.Decode(&trailing); errors.Is(err, io.EOF) { if err := json.Unmarshal(raw, target); err == nil { return nil } } } searchEnd = start } return errors.New("output did not contain a complete JSON object") } 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]" }