// SPDX-License-Identifier: GPL-3.0-or-later package fleet import ( "context" "encoding/json" "fmt" "math" "net/url" "regexp" "strconv" "strings" ) // FleetHost is the pseudo host that carries fleet-wide series (intel_age_hours). const FleetHost = "_fleet" // MetricNames is the server's /v1/series allowlist (scripts/fleet_history.py METRIC_NAMES). The only copy here. var MetricNames = []string{ "score", "flags_open", "vuln_findings", "vuln_fixable", "vuln_high_urgency", "vuln_kev", "vuln_open_unrated", "updates_apt_pending_count", "updates_security_pending_count", "updates_third_party_pending_count", "updates_kept_back_count", "reboot_required", "intel_age_hours", } // ValidMetric reports whether name is in MetricNames. func ValidMetric(name string) bool { for _, m := range MetricNames { if m == name { return true } } return false } var sinceRe = regexp.MustCompile(`^[1-9][0-9]{0,3}[hd]$`) // ValidSince accepts the relative form the API takes: 12h, 7d. func ValidSince(s string) bool { return sinceRe.MatchString(s) } // seriesLimit is the API maximum for /v1/series, so 7 days of 5-minute samples fit. const seriesLimit = 2000 func missingRoute(path string) error { return &ConfigError{"server does not provide " + path + " (upgrade the fleet collector/API)"} } // Telemetry is GET /v1/telemetry?host=. An older server answers 404; that becomes a ConfigError (exit 2). func (c *Client) Telemetry(ctx context.Context, host string) (*Envelope, error) { env, err := c.Get(ctx, "/v1/telemetry", url.Values{"host": {host}}) if isNotFound(err) { return nil, missingRoute("/v1/telemetry") } return env, err } // Series is GET /v1/series?host=&metric=&since=&limit=. func (c *Client) Series(ctx context.Context, host, metric, since string, limit int) (*Envelope, error) { q := url.Values{"host": {host}, "metric": {metric}, "since": {since}} if limit > 0 { q.Set("limit", strconv.Itoa(limit)) } env, err := c.Get(ctx, "/v1/series", q) if isNotFound(err) { return nil, missingRoute("/v1/series") } return env, err } // History is GET /v1/history?host=&kind=&since=&limit=, newest first. func (c *Client) History(ctx context.Context, host, kind, since string, limit int) (*Envelope, error) { q := url.Values{"host": {host}, "kind": {kind}, "since": {since}} if limit > 0 { q.Set("limit", strconv.Itoa(limit)) } env, err := c.Get(ctx, "/v1/history", q) if isNotFound(err) { return nil, missingRoute("/v1/history") } return env, err } // SparkWidth is the fixed width of every sparkline. const SparkWidth = 24 var sparkRunes = []rune("▁▂▃▄▅▆▇█") // Sparkline draws values (oldest first) as SparkWidth characters. Fewer values than SparkWidth are drawn one per // character and padded on the left with spaces; more are averaged into SparkWidth buckets by sample order. No // values: blanks. A flat series is drawn at the lowest level. func Sparkline(values []float64) string { n := len(values) if n == 0 { return strings.Repeat(" ", SparkWidth) } pts := values if n > SparkWidth { pts = make([]float64, SparkWidth) for b := range pts { lo, hi := b*n/SparkWidth, (b+1)*n/SparkWidth sum := 0.0 for _, v := range values[lo:hi] { sum += v } pts[b] = sum / float64(hi-lo) } } lo, hi := pts[0], pts[0] for _, v := range pts { lo, hi = math.Min(lo, v), math.Max(hi, v) } var b strings.Builder b.WriteString(strings.Repeat(" ", SparkWidth-len(pts))) for _, v := range pts { level := 0 if hi > lo { level = int((v-lo)/(hi-lo)*float64(len(sparkRunes)-1) + 0.5) } b.WriteRune(sparkRunes[level]) } return b.String() } func fmtNum(f float64) string { return strconv.FormatFloat(math.Round(f*100)/100, 'f', -1, 64) } // seriesValues returns the point values of a /v1/series envelope, oldest first. func seriesValues(env *Envelope) []float64 { var out []float64 points, _ := obj(env.Raw["data"])["points"].([]any) for _, p := range points { pair, _ := p.([]any) if len(pair) != 2 { continue } switch v := pair[1].(type) { case json.Number: if f, err := v.Float64(); err == nil { out = append(out, f) } case float64: out = append(out, v) } } return out } // minMaxLast summarizes values; ok is false for none. func minMaxLast(values []float64) (lo, hi, last float64, ok bool) { if len(values) == 0 { return 0, 0, 0, false } lo, hi = values[0], values[0] for _, v := range values { lo, hi = math.Min(lo, v), math.Max(hi, v) } return lo, hi, values[len(values)-1], true } // Culprit is one known-exploited package finding from /v1/telemetry (vulns.kev). type Culprit struct { Source string `json:"source"` Installed string `json:"installed_version"` Fixed string `json:"fixed_version"` CVE string `json:"cve"` Advisory string `json:"advisory"` } func (cu Culprit) String() string { return fmt.Sprintf("%s %s -> %s %s %s", dash(nilIfEmpty(cu.Source)), dash(nilIfEmpty(cu.Installed)), dash(nilIfEmpty(cu.Fixed)), dash(nilIfEmpty(cu.CVE)), dash(nilIfEmpty(cu.Advisory))) } func nilIfEmpty(s string) any { if s == "" { return nil } return s } // culprits reads vulns.kev of one telemetry host object. func culprits(host map[string]any) []Culprit { var out []Culprit list, _ := obj(host["vulns"])["kev"].([]any) for _, it := range list { m := obj(it) cu := Culprit{} cu.Source, _ = m["source"].(string) cu.Installed, _ = m["installed_version"].(string) cu.Fixed, _ = m["fixed_version"].(string) cu.CVE, _ = m["cve"].(string) cu.Advisory, _ = m["advisory"].(string) out = append(out, cu) } return out } // IntelStaleSeconds is the age of the oldest intel feed beyond which `hub status` warns (36 hours). const IntelStaleSeconds = 36 * 3600 // intelFailing lists the feeds the server reports as failing: from `failing_detail` ({name: {error, // consecutive_failures}}) when present, else from the bare `failing` names (older servers send neither). func intelFailing(intel map[string]any) []string { detail := obj(intel["failing_detail"]) names := map[string]bool{} if list, ok := intel["failing"].([]any); ok { for _, it := range list { if n, ok := it.(string); ok { names[n] = true } } } for n := range detail { names[n] = true } var out []string for _, n := range sortedKeys(boolKeys(names)) { row := obj(detail[n]) item := printable(n) if f, ok := row["consecutive_failures"].(json.Number); ok { item += " x" + printable(f.String()) } if label, ok := row["error"].(string); ok && label != "" { item += " (" + printable(label) + ")" } out = append(out, item) } return out } func boolKeys(m map[string]bool) map[string]any { out := make(map[string]any, len(m)) for k := range m { out[k] = true } return out } // printable keeps server-supplied text on one terminal line: anything outside printable ASCII becomes '?'. func printable(s string) string { b := []byte(s) for i, c := range b { if c < 0x20 || c > 0x7e { b[i] = '?' } } return string(b) } // intelCheck renders the intel line for /v1/summary and says whether it is a problem (missing, older than 36h, or any // feed failing). func intelCheck(env *Envelope) (line string, bad bool) { line, bad = intelAge(env) if failing := intelFailing(obj(env.Raw["intel"])); len(failing) > 0 { line += " failing: " + strings.Join(failing, ", ") bad = true } return line, bad } // intelAge is the age half of the intel line (missing or older than 36h is a problem). func intelAge(env *Envelope) (line string, bad bool) { intel := obj(env.Raw["intel"]) oldest, _ := intel["oldest_fetched_at"].(string) var secs float64 have := false if n, ok := intel["age_seconds"].(json.Number); ok { if f, err := n.Float64(); err == nil { secs, have = f, true } } if !have { if t, ok := parseTime(oldest); ok { if g, ok := parseTime(env.Raw["generated_at"]); ok { secs, have = g.Sub(t).Seconds(), true } } } if !have { return "intel MISSING: the server reports no feed age", true } line = fmt.Sprintf("intel oldest feed %s (%s)", HumanDuration(int64(secs)), dashStr(oldest)) if secs > IntelStaleSeconds { return strings.Replace(line, "intel ", "intel STALE ", 1) + ", older than 36h", true } return line, false }