// SPDX-License-Identifier: GPL-3.0-or-later package fleet_test import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "strings" "sync" "testing" "time" "unicode/utf8" "git.trevon.dev/trevon/hub/internal/fleet" ) // app is the display name the fixtures send in app.name. const app = "blog" const telHead = `{"generated_at":"2026-11-19T16:00:00Z","snapshot_age_seconds":5,"stale":false,"coverage_complete":true,"data":` // telHost builds one telemetry host object. reboot is "" (not required), "none" (required, no time) or a timestamp. func telHost(reboot, runStatus string, kev int) string { req, since := "false", "null" switch { case reboot == "none": req = "true" case reboot != "": req, since = "true", `"`+reboot+`"` } pkgs := "[]" if req == "true" { pkgs = `["linux-image-5.15.0-203-generic","libc6"]` } var list []string for i := 0; i < kev; i++ { list = append(list, fmt.Sprintf(`{"source":"linux","installed_version":"5.15.0-18%d.199","fixed_version":"5.15.0-200.210","cve":"CVE-2024-100%d","advisory":"USN-7000-%d"}`, i, i, i)) } return (`{"kernel":"5.15.0-203-generic","reboot_required":` + req + `,"reboot_required_since":` + since + `,"reboot_required_pkgs":` + pkgs + `,"last_report_at":"2026-11-19T15:55:00Z",` + `"app":{"name":"` + app + `","installed_version":"5.96.0","latest_version":"5.97.0","last_run":{"status":"` + runStatus + `","phase":"verify-update","completed_at":"2026-11-18T19:37:19Z"}},` + `"updates":{"apt_pending_count":4,"security_pending_count":1,"third_party_pending_count":0,"kept_back_count":2},` + `"vulns":{"status":"partial","finding_count":3,"fixable_finding_count":2,"high_urgency_finding_count":1,` + `"open_unrated_finding_count":0,"kev_count":` + fmt.Sprint(kev) + `,"kev":[` + strings.Join(list, ",") + `]}}`) } func telBody(hosts map[string]string) string { var parts []string for _, n := range []string{"alpha", "beta"} { if h, ok := hosts[n]; ok { parts = append(parts, `"`+n+`":`+h) } } return `{"status":"ok","source_mtime_utc":"2026-11-19T15:59:00Z","intel":{"age_seconds":3600,"oldest_fetched_at":"2026-11-19T15:00:00Z","feeds":{}},"hosts":{` + strings.Join(parts, ",") + `}}` } func ev(kind, ts, host, data string) string { return (`{"id":"ev-1","ts":"` + ts + `","kind":"` + kind + `","host":"` + host + `","subject":null,"data":` + data + `,"parent_ids":[],"hash":"x"}`) } // telAPI is a fake fleet API for the telemetry routes. A nil route answers 404; status overrides per path. type telAPI struct { mu sync.Mutex telemetry *string events *string series map[string]string // metric -> points JSON, e.g. [["t",1],["t",2]] status map[string]int queries []string // path?query of every request srv *httptest.Server } func newTelAPI(t *testing.T) *telAPI { t.Helper() a := &telAPI{series: map[string]string{}, status: map[string]int{}} a.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { a.mu.Lock() a.queries = append(a.queries, r.URL.Path+"?"+r.URL.RawQuery) a.mu.Unlock() if r.Header.Get("Authorization") != "Bearer "+secretToken { w.WriteHeader(http.StatusUnauthorized) return } if code := a.status[r.URL.Path]; code != 0 { w.WriteHeader(code) return } q := r.URL.Query() switch r.URL.Path { case "/v1/telemetry": if a.telemetry == nil { w.WriteHeader(http.StatusNotFound) return } _, _ = w.Write([]byte(telHead + *a.telemetry + "}")) case "/v1/history": if a.events == nil { w.WriteHeader(http.StatusNotFound) return } _, _ = w.Write([]byte(telHead + `{"total":1,"events":` + *a.events + `}}`)) case "/v1/series": pts, ok := a.series[q.Get("host")+"/"+q.Get("metric")] if !ok { pts, ok = a.series[q.Get("metric")] } if !ok { pts = "[]" } _, _ = w.Write([]byte(telHead + `{"host":"` + q.Get("host") + `","metric":"` + q.Get("metric") + `","total":0,"points":` + pts + `}}`)) default: w.WriteHeader(http.StatusNotFound) } })) t.Cleanup(a.srv.Close) return a } func (a *telAPI) setTelemetry(s string) { a.telemetry = &s } func (a *telAPI) setEvents(s string) { a.events = &s } func (a *telAPI) client(t *testing.T) *fleet.Client { return newClient(t, a.srv.URL, secretToken) } func (a *telAPI) count(path string) int { n := 0 for _, q := range a.queries { if strings.HasPrefix(q, path+"?") { n++ } } return n } func (a *telAPI) host(t *testing.T, host string, asJSON bool) (int, string, error) { t.Helper() var out bytes.Buffer code, err := fleet.HostView(context.Background(), a.client(t), &out, asJSON, host, "7d") if strings.Contains(out.String(), secretToken) { t.Fatal("token in output") } return code, out.String(), err } func (a *telAPI) trend(t *testing.T, metric, since string, asJSON bool) (int, string, error) { t.Helper() var out bytes.Buffer code, err := fleet.TrendView(context.Background(), a.client(t), &out, asJSON, metric, since) return code, out.String(), err } func pts(vals ...int) string { var p []string for i, v := range vals { p = append(p, fmt.Sprintf(`["2026-11-19T%02d:00:00Z",%d]`, i, v)) } return "[" + strings.Join(p, ",") + "]" } // alphaFixture: a reboot pending for 3 days, one known-exploited package, events and series. func alphaFixture(t *testing.T) *telAPI { a := newTelAPI(t) a.setTelemetry(telBody(map[string]string{"alpha": telHost("2026-11-16T04:00:00Z", "updated", 1), "beta": telHost("", "ok", 0)})) a.setEvents("[" + strings.Join([]string{ ev("app_run_finished", "2026-11-19T03:10:00Z", "alpha", `{"status":"updated","phase":"complete","completed_at":"x"}`), ev("flag_opened", "2026-11-19T03:00:00Z", "alpha", `{}`), ev("app_version_changed", "2026-11-19T02:59:00Z", "alpha", `{"from":"5.96.0","to":"5.97.0"}`), ev("reboot_required_cleared", "2026-11-18T04:05:00Z", "alpha", `{}`), ev("kernel_changed", "2026-11-18T04:04:00Z", "alpha", `{"from":"5.15.0-189","to":"5.15.0-203"}`), ev("reboot_required_set", "2026-11-16T04:00:00Z", "alpha", `{"pkgs":["linux-image-5.15.0-203-generic","libc6"]}`), }, ",") + "]") a.series["score"] = pts(1, 2, 3, 4, 5) a.series["vuln_findings"] = pts(3, 3, 3) a.series["vuln_kev"] = pts(1) return a } func TestHostViewGolden(t *testing.T) { a := alphaFixture(t) code, out, err := a.host(t, "alpha", false) if err != nil || code != fleet.ExitDrift { t.Fatalf("code=%d err=%v\n%s", code, err, out) } want := strings.NewReplacer("@@LABEL", fmt.Sprintf("%-10s", app), "@@", app).Replace(`alpha last report 5m ago (2026-11-19T15:55:00Z) kernel 5.15.0-203-generic reboot REQUIRED since 2026-11-16T04:00:00Z (3d12h) by linux-image-5.15.0-203-generic, libc6 @@LABEL 5.96.0 (latest 5.97.0) last run updated verify-update 2026-11-18T19:37:19Z updates 4 apt pending, 1 security, 0 third-party, 2 kept back vulns partial: 3 findings, 2 fixable, 1 high urgency, 1 known-exploited known-exploited linux 5.15.0-180.199 -> 5.15.0-200.210 CVE-2024-1000 USN-7000-0 changes (since 7d) 2026-11-19T03:10:00Z @@ run updated (complete) 2026-11-19T02:59:00Z @@ 5.96.0 -> 5.97.0 2026-11-18T04:05:00Z reboot cleared 2026-11-18T04:04:00Z kernel 5.15.0-189 -> 5.15.0-203 2026-11-16T04:00:00Z reboot required (linux-image-5.15.0-203-generic, libc6) trend (since 7d) score ▁▃▅▆█ last 5 vuln_findings ▁▁▁ last 3 vuln_kev ▁ last 1 updates_apt_pending_count no data attention: known-exploited vulnerable packages; reboot required for more than 2 days `) if out != want { t.Errorf("host view differs.\n--- got\n%s--- want\n%s", out, want) } for _, q := range []string{"/v1/telemetry?host=alpha", "/v1/history?host=alpha&limit=200&since=7d", "/v1/series?host=alpha&limit=2000&metric=score&since=7d"} { found := false for _, got := range a.queries { found = found || got == q } if !found { t.Errorf("no request %q in %v", q, a.queries) } } } func TestHostViewExitCodes(t *testing.T) { cases := []struct { name string reboot string runStatus string kev int code int reason string }{ {"clean", "", "ok", 0, 0, ""}, {"known-exploited culprit", "", "ok", 1, 1, "known-exploited"}, {"reboot pending 3 days", "2026-11-16T04:00:00Z", "ok", 0, 1, "reboot required for more than 2 days"}, {"reboot pending 1 day", "2026-11-18T16:00:00Z", "ok", 0, 0, ""}, {"reboot pending, no time", "none", "ok", 0, 0, ""}, {"run failed", "", "failed", 0, 1, app + " last run failed"}, {"run exit-code result", "", "exit-code", 0, 1, app + " last run failed"}, {"run updated", "", "updated", 0, 0, ""}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { a := newTelAPI(t) a.setTelemetry(telBody(map[string]string{"alpha": telHost(c.reboot, c.runStatus, c.kev)})) a.setEvents("[]") code, out, err := a.host(t, "alpha", false) if err != nil || code != c.code { t.Fatalf("code=%d err=%v want %d\n%s", code, err, c.code, out) } if c.reason != "" && !strings.Contains(out, "attention: ") || c.reason != "" && !strings.Contains(out, c.reason) { t.Errorf("attention line lacks %q:\n%s", c.reason, out) } if c.reason == "" && strings.Contains(out, "attention") { t.Errorf("unexpected attention:\n%s", out) } }) } } func TestOldServerWithoutTelemetryIsConfigError(t *testing.T) { a := newTelAPI(t) // no routes: every path 404 for name, call := range map[string]func() (int, error){ "host": func() (int, error) { code, _, err := a.host(t, "alpha", false); return code, err }, "trend": func() (int, error) { code, _, err := a.trend(t, "score", "7d", false) return code, err }, } { _, err := call() if err == nil || fleet.ExitCodeFor(err) != fleet.ExitConfig || err.Error() != "server does not provide /v1/telemetry (upgrade the fleet collector/API)" { t.Errorf("%s: err=%v exit=%d", name, err, fleet.ExitCodeFor(err)) } } // the history and series routes answer 404 on their own: same message shape, exit 2 a.setTelemetry(telBody(map[string]string{"alpha": telHost("", "ok", 0)})) _, _, err := a.host(t, "alpha", false) if err == nil || fleet.ExitCodeFor(err) != fleet.ExitConfig || !strings.Contains(err.Error(), "does not provide /v1/history") { t.Errorf("history 404: %v", err) } } func TestHostViewUnknownHostAndUnavailableTelemetry(t *testing.T) { a := newTelAPI(t) a.setTelemetry(telBody(map[string]string{"beta": telHost("", "ok", 0)})) _, _, err := a.host(t, "alpha", false) if err == nil || fleet.ExitCodeFor(err) != fleet.ExitConfig || !strings.Contains(err.Error(), `host "alpha" has no telemetry`) { t.Errorf("unknown host: %v", err) } a.setTelemetry(`{"status":"unavailable"}`) _, _, err = a.host(t, "alpha", false) if err == nil || fleet.ExitCodeFor(err) != fleet.ExitTransport { t.Errorf("unavailable: %v", err) } } func TestHostViewDegradesWhenHistoryIsUnavailable(t *testing.T) { a := alphaFixture(t) a.status["/v1/history"] = http.StatusServiceUnavailable a.status["/v1/series"] = http.StatusServiceUnavailable code, out, err := a.host(t, "alpha", false) if err != nil || code != fleet.ExitDrift { t.Fatalf("code=%d err=%v", code, err) } for _, w := range []string{"note: history unavailable (HTTP 503); no change events", "note: series score unavailable (HTTP 503)", "kernel 5.15.0-203-generic"} { if !strings.Contains(out, w) { t.Errorf("missing %q in:\n%s", w, out) } } } func TestHostViewEventsAreFilteredCappedAndNewestFirst(t *testing.T) { a := newTelAPI(t) a.setTelemetry(telBody(map[string]string{"alpha": telHost("", "ok", 0)})) var events []string for i := 0; i < 40; i++ { kind := "kernel_changed" if i%2 == 1 { kind = "flag_opened" } events = append(events, ev(kind, fmt.Sprintf("2026-11-19T%02d:%02d:00Z", 23-i/4, 59-i), "alpha", fmt.Sprintf(`{"from":"k%d","to":"k%d"}`, i, i+1))) } a.setEvents("[" + strings.Join(events, ",") + "]") _, out, err := a.host(t, "alpha", false) if err != nil { t.Fatal(err) } if n := strings.Count(out, " kernel k"); n != 15 { t.Errorf("%d event lines, want 15:\n%s", n, out) } if strings.Contains(out, "flag_opened") { t.Errorf("non-change event shown:\n%s", out) } if !strings.Contains(out, "kernel k0 -> k1\n") || strings.Contains(out, "kernel k30 -> k31") { t.Errorf("not newest first / not capped:\n%s", out) } } func TestHostViewJSONPassthrough(t *testing.T) { a := alphaFixture(t) code, out, err := a.host(t, "alpha", true) if err != nil || code != fleet.ExitDrift { t.Fatalf("code=%d err=%v", code, err) } var doc struct { Host string Telemetry map[string]any Events []any Series map[string]any Attention []string Notes []string } if err := json.Unmarshal([]byte(out), &doc); err != nil { t.Fatalf("not JSON: %v\n%s", err, out) } if doc.Host != "alpha" || doc.Telemetry["kernel"] != "5.15.0-203-generic" || len(doc.Events) != 5 || len(doc.Series) != 4 || len(doc.Attention) != 2 { t.Errorf("unexpected document: %+v", doc) } } func TestDescribeEventsThroughHostView(t *testing.T) { a := newTelAPI(t) a.setTelemetry(telBody(map[string]string{"alpha": telHost("", "ok", 0)})) a.setEvents("[" + strings.Join([]string{ ev("reboot_required_set", "2026-11-19T01:00:00Z", "alpha", `{"pkgs":[]}`), ev("app_run_finished", "2026-11-19T00:59:00Z", "alpha", `{"status":"failed","phase":"backup"}`), }, ",") + "]") _, out, _ := a.host(t, "alpha", false) for _, w := range []string{" 2026-11-19T01:00:00Z reboot required\n", " 2026-11-19T00:59:00Z " + app + " run failed (backup)\n"} { if !strings.Contains(out, w) { t.Errorf("missing %q in:\n%s", w, out) } } } func TestTrendRowsAndQuery(t *testing.T) { a := newTelAPI(t) a.setTelemetry(telBody(map[string]string{"alpha": telHost("", "ok", 0), "beta": telHost("", "ok", 0)})) a.series["alpha/score"] = pts(10, 20, 30) a.series["beta/score"] = "[]" code, out, err := a.trend(t, "score", "12h", false) if err != nil || code != fleet.ExitOK { t.Fatalf("code=%d err=%v", code, err) } want := "score since 12h\n" + "alpha " + fleet.Sparkline([]float64{10, 20, 30}) + " min 10 max 30 last 30\n" + "beta " + fleet.Sparkline(nil) + " no data\n" if out != want { t.Errorf("trend:\n%q\nwant\n%q", out, want) } if !strings.HasPrefix(fleet.Sparkline([]float64{10, 20, 30}), strings.Repeat(" ", 21)) { t.Error("sparkline not left padded") } found := false for _, q := range a.queries { found = found || q == "/v1/series?host=alpha&limit=2000&metric=score&since=12h" } if !found { t.Errorf("queries %v", a.queries) } } func TestTrendFleetMetricNeedsNoTelemetry(t *testing.T) { a := newTelAPI(t) // telemetry route absent a.series["intel_age_hours"] = pts(3, 5) code, out, err := a.trend(t, "intel_age_hours", "7d", false) if err != nil || code != 0 || !strings.Contains(out, "_fleet ") || !strings.Contains(out, "last 5") { t.Fatalf("code=%d err=%v\n%s", code, err, out) } if a.count("/v1/telemetry") != 0 { t.Error("telemetry requested for a _fleet metric") } } func TestTrendRejectsBadMetricAndSinceWithoutARequest(t *testing.T) { a := newTelAPI(t) for _, c := range []struct{ metric, since string }{{"nope", "7d"}, {"score; drop", "7d"}, {"score", "7"}, {"score", "0d"}, {"score", "-1d"}, {"score", ""}} { _, _, err := a.trend(t, c.metric, c.since, false) if err == nil || fleet.ExitCodeFor(err) != fleet.ExitConfig { t.Errorf("%+v: err=%v", c, err) } } if len(a.queries) != 0 { t.Errorf("requests were made: %v", a.queries) } _, _, err := a.trend(t, "nope", "7d", false) for _, m := range fleet.MetricNames { if !strings.Contains(err.Error(), m) { t.Errorf("error does not list %s: %v", m, err) } } } func TestTrendJSON(t *testing.T) { a := newTelAPI(t) a.setTelemetry(telBody(map[string]string{"alpha": telHost("", "ok", 0)})) a.series["score"] = pts(1, 2) _, out, err := a.trend(t, "score", "7d", true) var doc struct { Metric string Hosts map[string][][]any } if err != nil || json.Unmarshal([]byte(out), &doc) != nil || doc.Metric != "score" || len(doc.Hosts["alpha"]) != 2 { t.Errorf("err=%v doc=%+v\n%s", err, doc, out) } } func TestSparkline(t *testing.T) { blank := strings.Repeat(" ", fleet.SparkWidth) if got := fleet.Sparkline(nil); got != blank { t.Errorf("empty = %q", got) } if got := fleet.Sparkline([]float64{7}); got != strings.Repeat(" ", 23)+"▁" { t.Errorf("single = %q", got) } if got := fleet.Sparkline([]float64{4, 4, 4}); got != strings.Repeat(" ", 21)+"▁▁▁" { t.Errorf("flat = %q", got) } if got := fleet.Sparkline([]float64{0, 1, 2, 3, 4, 5, 6, 7}); got != strings.Repeat(" ", 16)+"▁▂▃▄▅▆▇█" { t.Errorf("rising = %q", got) } exact := make([]float64, 24) for i := range exact { exact[i] = float64(i) } if got := fleet.Sparkline(exact); utf8.RuneCountInString(got) != 24 || strings.Contains(got, " ") || !strings.HasPrefix(got, "▁") || !strings.HasSuffix(got, "█") { t.Errorf("24 points = %q", got) } long := make([]float64, 96) for i := range long { long[i] = float64(i) } got := fleet.Sparkline(long) if utf8.RuneCountInString(got) != 24 || !strings.HasPrefix(got, "▁") || !strings.HasSuffix(got, "█") || strings.Contains(got, " ") { t.Errorf("96 points = %q", got) } // bucketing averages: a spike inside one bucket does not move the neighbours spike := make([]float64, 48) spike[10] = 100 s := []rune(fleet.Sparkline(spike)) if len(s) != 24 || s[5] != '█' || s[0] != '▁' || s[23] != '▁' { t.Errorf("spike = %q", string(s)) } } func TestMetricAllowlist(t *testing.T) { if len(fleet.MetricNames) != 13 || !fleet.ValidMetric("vuln_kev") || !fleet.ValidMetric("intel_age_hours") || fleet.ValidMetric("") || fleet.ValidMetric("Score") { t.Errorf("allowlist wrong: %v", fleet.MetricNames) } for _, s := range []string{"7d", "12h", "400d"} { if !fleet.ValidSince(s) { t.Errorf("%s rejected", s) } } for _, s := range []string{"", "d", "7", "7w", "0d", "07d", "7d ", "1e3d"} { if fleet.ValidSince(s) { t.Errorf("%q accepted", s) } } } func TestStatusIntelLine(t *testing.T) { cases := []struct { name string intel string code int line string }{ {"fresh", "", 0, "intel oldest feed 4h0m (2026-11-08T08:00:00Z)\n"}, {"stale", `"intel":{"oldest_fetched_at":"2026-11-06T22:00:00Z","age_seconds":136800},`, 1, "intel STALE oldest feed 1d14h (2026-11-06T22:00:00Z), older than 36h\n"}, {"exactly 36h is fine", `"intel":{"oldest_fetched_at":"2026-11-07T00:00:00Z","age_seconds":129600},`, 0, "intel oldest feed 1d12h"}, {"one second over", `"intel":{"oldest_fetched_at":"2026-11-07T00:00:00Z","age_seconds":129601},`, 1, "intel STALE"}, {"missing member", "none", 1, "intel MISSING"}, {"null age", `"intel":{"oldest_fetched_at":null,"age_seconds":null},`, 1, "intel MISSING"}, {"failing feed with count and label", `"intel":{"oldest_fetched_at":"2026-11-08T08:00:00Z","age_seconds":14400,"failing":["ubuntu-noble"],"failing_detail":{"ubuntu-noble":{"error":"refresh_failed:URLError","consecutive_failures":3}}},`, 1, "intel oldest feed 4h0m (2026-11-08T08:00:00Z) failing: ubuntu-noble x3 (refresh_failed:URLError)\n"}, {"two failing feeds sorted, stale too", `"intel":{"oldest_fetched_at":"2026-11-06T22:00:00Z","age_seconds":136800,"failing":["kev","debian"],"failing_detail":{"kev":{"error":"refresh_interrupted","consecutive_failures":1},"debian":{"error":"refresh_failed:OSError","consecutive_failures":2}}},`, 1, "intel STALE oldest feed 1d14h (2026-11-06T22:00:00Z), older than 36h failing: debian x2 (refresh_failed:OSError), kev x1 (refresh_interrupted)\n"}, {"failing names only", `"intel":{"oldest_fetched_at":"2026-11-08T08:00:00Z","age_seconds":14400,"failing":["debian"]},`, 1, "failing: debian\n"}, {"control characters from the server are neutralised", `"intel":{"oldest_fetched_at":"2026-11-08T08:00:00Z","age_seconds":14400,"failing":["a"],"failing_detail":{"a":{"error":"x\u001b[31my","consecutive_failures":1}}},`, 1, "failing: a x1 (x?[31my)\n"}, {"empty failing list is healthy", `"intel":{"oldest_fetched_at":"2026-11-08T08:00:00Z","age_seconds":14400,"failing":[],"failing_detail":{}},`, 0, "intel oldest feed 4h0m (2026-11-08T08:00:00Z)\n"}, {"old server without the new fields", `"intel":{"oldest_fetched_at":"2026-11-08T08:00:00Z","age_seconds":14400},`, 0, "intel oldest feed 4h0m (2026-11-08T08:00:00Z)\n"}, {"age from timestamp", `"intel":{"oldest_fetched_at":"2026-11-08T11:00:00Z","age_seconds":null},`, 0, "intel oldest feed 1h0m"}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { a := &api{intel: c.intel} srv := httptest.NewServer(a.handler()) defer srv.Close() for _, asJSON := range []bool{false, true} { var out bytes.Buffer code, err := fleet.Status(context.Background(), newClient(t, srv.URL, secretToken), &out, asJSON) if err != nil || code != c.code { t.Fatalf("json=%v code=%d err=%v want %d\n%s", asJSON, code, err, c.code, out.String()) } if !asJSON && !strings.Contains(out.String(), c.line) { t.Errorf("missing %q in:\n%s", c.line, out.String()) } } }) } } // findings with a known-exploited flag const kevFlagName = "known_exploited_vulnerable_package" func findingsWithTelemetry(t *testing.T, flagged bool, telemetry *string, status int) (int, string, []string) { t.Helper() flags := `"updates_kept_back"` if flagged { flags = `"` + kevFlagName + `"` } a := newTelAPI(t) a.telemetry = telemetry if status != 0 { a.status["/v1/telemetry"] = status } inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/v1/posture": _, _ = w.Write([]byte(findingsHead + posture(ph("alpha", "high_priority", 9, false, flags, "")) + "}")) case "/v1/alerts": _, _ = w.Write([]byte(findingsHead + alertsEmpty + "}")) case "/v1/queue": _, _ = w.Write([]byte(findingsHead + queueEmpty + "}")) case "/v1/backups": _, _ = w.Write([]byte(findingsHead + backupsNone + "}")) default: a.srv.Config.Handler.ServeHTTP(w, r) } }) front := httptest.NewServer(inner) t.Cleanup(front.Close) var out bytes.Buffer code, err := fleet.FindingsView(context.Background(), newClient(t, front.URL, secretToken), &out, false, "", time.Now()) if err != nil { t.Fatal(err) } return code, out.String(), a.queries } func TestFindingsPrintsUpToThreeCulprits(t *testing.T) { body := telBody(map[string]string{"alpha": telHost("", "ok", 4)}) code, out, queries := findingsWithTelemetry(t, true, &body, 0) if code != 1 { t.Errorf("exit %d", code) } if n := strings.Count(out, " culprit "); n != 3 { t.Errorf("%d culprit lines, want 3:\n%s", n, out) } for _, w := range []string{" culprit linux 5.15.0-180.199 -> 5.15.0-200.210 CVE-2024-1000 USN-7000-0\n"} { if !strings.Contains(out, w) { t.Errorf("missing %q in:\n%s", w, out) } } if strings.Contains(out, "CVE-2024-1003") { t.Errorf("fourth culprit printed:\n%s", out) } if len(queries) != 1 || !strings.HasPrefix(queries[0], "/v1/telemetry") { t.Errorf("want exactly one telemetry request, got %v", queries) } // the culprit lines sit under the flag line, before actions if i, j := strings.Index(out, kevFlagName), strings.Index(out, " culprit"); i < 0 || j < i { t.Errorf("culprits not under the flag:\n%s", out) } } func TestFindingsWithoutTheFlagDoesNotAskForTelemetry(t *testing.T) { body := telBody(map[string]string{"alpha": telHost("", "ok", 4)}) code, out, queries := findingsWithTelemetry(t, false, &body, 0) if code != 1 || strings.Contains(out, "culprit") || len(queries) != 0 { t.Errorf("code=%d queries=%v\n%s", code, queries, out) } } func TestFindingsDegradesWhenTelemetryFails(t *testing.T) { for name, c := range map[string]struct { body *string status int note string }{ "old server": {nil, 0, "note: culprits: telemetry unavailable (server does not provide /v1/telemetry (upgrade the fleet collector/API)); no package lines"}, "http 500": {strPtr(telBody(nil)), 500, "note: culprits: telemetry unavailable (HTTP 500); no package lines"}, "status": {strPtr(`{"status":"unavailable"}`), 0, "note: culprits: telemetry status unavailable; no package lines"}, } { t.Run(name, func(t *testing.T) { code, out, _ := findingsWithTelemetry(t, true, c.body, c.status) if code != 1 || strings.Contains(out, "culprit ") || !strings.Contains(out, c.note+"\n") { t.Errorf("code=%d\n%s", code, out) } if !strings.Contains(out, kevFlagName) { t.Errorf("findings lost the flag:\n%s", out) } }) } } func strPtr(s string) *string { return &s } func TestAppLabelComesFromDataWithAppFallback(t *testing.T) { a := newTelAPI(t) host := strings.Replace(telHost("", "failed", 0), `"name":"`+app+`",`, "", 1) a.setTelemetry(telBody(map[string]string{"alpha": host})) a.setEvents("[" + ev("app_version_changed", "2026-11-19T01:00:00Z", "alpha", `{"from":"1.0.0","to":"1.1.0"}`) + "]") _, out, _ := a.host(t, "alpha", false) for _, w := range []string{"app 5.96.0 (latest 5.97.0)", " 2026-11-19T01:00:00Z app 1.0.0 -> 1.1.0\n", "attention: app last run failed"} { if !strings.Contains(out, w) { t.Errorf("missing %q in:\n%s", w, out) } } if strings.Contains(out, app) { t.Errorf("fixture name leaked without data:\n%s", out) } }