// SPDX-License-Identifier: GPL-3.0-or-later package probe_test import ( "context" "errors" "os" "path/filepath" "strings" "testing" "time" "git.trevon.dev/trevon/hub/internal/probe" ) const fixtures = "../../probe/fixtures" func fixture(t *testing.T, name string) []byte { t.Helper() raw, err := os.ReadFile(filepath.Join(fixtures, name)) if err != nil { t.Fatal(err) } return raw } func load(t *testing.T, name string) *probe.Profile { t.Helper() p, err := probe.Parse(fixture(t, name)) if err != nil { t.Fatalf("%s: %v", name, err) } return p } // fakeSSH installs an `ssh` script first on PATH. It records its arguments and stdin, then runs body. func fakeSSH(t *testing.T, body string) (argsFile, stdinFile string) { t.Helper() dir := t.TempDir() argsFile, stdinFile = filepath.Join(dir, "args"), filepath.Join(dir, "stdin") script := "#!/bin/sh\nprintf '%s\\n' \"$@\" > '" + argsFile + "'\ncat > '" + stdinFile + "'\n" + body + "\n" if err := os.WriteFile(filepath.Join(dir, "ssh"), []byte(script), 0o755); err != nil { t.Fatal(err) } t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) return argsFile, stdinFile } func oneLine(t *testing.T, name string) string { t.Helper() p := filepath.Join(t.TempDir(), "reply") // The probe prints one compact line. if err := os.WriteFile(p, append(minify(t, fixture(t, name)), '\n'), 0o644); err != nil { t.Fatal(err) } return p } func TestRunSendsProbeOnStdinWithExactSSHArgs(t *testing.T) { reply := oneLine(t, "expected-alpha.json") argsFile, stdinFile := fakeSSH(t, "echo 'Welcome banner' ; cat '"+reply+"'") script := []byte("print('probe script')\n") p, raw, err := probe.Run(context.Background(), probe.Target{User: "admin", Addr: "100.64.0.11", Port: 2200}, script, probe.Options{}) if err != nil { t.Fatal(err) } if p.Sections.Identity.Hostname != "alpha" || len(raw) == 0 || raw[0] != '{' { t.Errorf("profile = %+v", p.Sections.Identity) } args, _ := os.ReadFile(argsFile) want := "-o\nBatchMode=yes\n-o\nConnectTimeout=10\n-p\n2200\nadmin@100.64.0.11\npython3\n-\n" if string(args) != want { t.Errorf("ssh args:\n%q\nwant\n%q", args, want) } stdin, _ := os.ReadFile(stdinFile) if string(stdin) != string(script) { t.Errorf("stdin = %q", stdin) } } func TestRunTimeout(t *testing.T) { fakeSSH(t, "exec sleep 30") start := time.Now() _, _, err := probe.Run(context.Background(), probe.Target{Addr: "1.2.3.4", Port: 22}, []byte("x"), probe.Options{Timeout: 300 * time.Millisecond}) if !errors.Is(err, probe.ErrTimeout) { t.Fatalf("err = %v, want timeout", err) } if time.Since(start) > 10*time.Second { t.Errorf("took %s", time.Since(start)) } } func TestRunOutputCap(t *testing.T) { fakeSSH(t, "exec yes 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'") _, _, err := probe.Run(context.Background(), probe.Target{Addr: "1.2.3.4", Port: 22}, []byte("x"), probe.Options{MaxOutput: 4096, Timeout: 20 * time.Second}) if !errors.Is(err, probe.ErrTooLarge) { t.Fatalf("err = %v, want too large", err) } } func TestRunOutputCapFiniteOutput(t *testing.T) { // Output that ends by itself, only slightly over the cap, must still be refused (not parsed, not "no JSON"). fakeSSH(t, "head -c 10000 /dev/zero | tr '\\0' x; echo") _, _, err := probe.Run(context.Background(), probe.Target{Addr: "1.2.3.4", Port: 22}, []byte("x"), probe.Options{MaxOutput: 4096}) if !errors.Is(err, probe.ErrTooLarge) { t.Fatalf("err = %v, want too large", err) } } func TestRunFailures(t *testing.T) { cases := map[string]struct{ body, want string }{ "ssh failure": {"echo 'Permission denied (publickey).' >&2; exit 255", "Permission denied"}, "no json": {"echo hello", "no JSON"}, "bad schema": {`echo '{"schema":2,"probed_at":"x","sections":{}}'`, "unsupported profile schema 2"}, "no sections": {`echo '{"schema":1,"probed_at":"x","sections":{"identity":{}}}'`, `section "access" missing`}, } for name, c := range cases { t.Run(name, func(t *testing.T) { fakeSSH(t, c.body) _, _, err := probe.Run(context.Background(), probe.Target{Addr: "1.2.3.4", Port: 22}, []byte("x"), probe.Options{}) if err == nil || !strings.Contains(err.Error(), c.want) { t.Fatalf("err = %v, want %q", err, c.want) } }) } } func TestParseFixturesAndNullability(t *testing.T) { for _, n := range []string{"expected-alpha.json", "expected-beta.json", "real-alpha.json", "real-beta-ci.json"} { p := load(t, n) if p.Schema != 1 || p.Sections.Identity.MachineIDSHA256Prefix == "" { t.Errorf("%s: %+v", n, p.Schema) } } beta := load(t, "expected-beta.json") if beta.Sections.Access.Sshd.AllowUsers == nil || len(beta.Sections.Access.Sshd.AllowUsers) != 0 { t.Error("allowusers [] must stay non-nil and empty (readable and unset)") } unknown := strings.Replace(string(fixture(t, "expected-alpha.json")), `"allowusers": [ "admin" ]`, `"allowusers": null`, 1) p, err := probe.Parse([]byte(unknown)) if err != nil { t.Fatal(err) } if p.Sections.Access.Sshd.AllowUsers != nil { t.Error("allowusers null must be nil (unknown)") } if _, err := probe.Parse([]byte(`[]`)); err == nil { t.Error("array accepted") } } func TestSaveWritesDatedAndLatest0600(t *testing.T) { dir := filepath.Join(t.TempDir(), "local", "profiles") raw := minify(t, fixture(t, "expected-alpha.json")) now := time.Date(2026, 11, 8, 12, 30, 5, 0, time.UTC) path, err := probe.Save(dir, "alpha", raw, now) if err != nil { t.Fatal(err) } if filepath.Base(path) != "alpha-20261108T123005Z.json" { t.Errorf("path = %s", path) } for _, f := range []string{path, filepath.Join(dir, "alpha-latest.json")} { st, err := os.Stat(f) if err != nil || st.Mode().Perm() != 0o600 { t.Errorf("%s: %v %v", f, st, err) } } if st, _ := os.Stat(dir); st.Mode().Perm() != 0o700 { t.Errorf("dir mode %v", st.Mode().Perm()) } if _, err := probe.Save(dir, "alpha", raw, now); err == nil { t.Error("a dated profile must never be overwritten") } for _, bad := range []string{"../x", "a/b", "", "-x"} { if _, err := probe.Save(dir, bad, raw, now); err == nil { t.Errorf("host %q accepted", bad) } } _, _ = probe.Save(dir, "alpha", raw, now.Add(time.Hour)) _, _ = probe.Save(dir, "alpha-extra", raw, now.Add(2*time.Hour)) // must not be picked up for "alpha" files, err := probe.List(dir, "alpha") if err != nil || len(files) != 2 || files[0].Stamp >= files[1].Stamp { t.Errorf("list = %+v %v", files, err) } } func TestCompareRebuildDetection(t *testing.T) { base := load(t, "expected-alpha.json") same := probe.Compare(base, load(t, "expected-alpha.json")) if same.Rebuild || !same.Empty() { t.Errorf("identical profiles: %+v", same) } machine := load(t, "expected-alpha.json") machine.Sections.Identity.MachineIDSHA256Prefix = "ffffffffffffffff" if d := probe.Compare(base, machine); !d.Rebuild || !strings.Contains(strings.Join(d.RebuildReasons, ";"), "machine-id") { t.Errorf("machine-id change not a rebuild: %+v", d) } keys := load(t, "expected-alpha.json") keys.Sections.Identity.SSHHostKeys[0].Fingerprint = "SHA256:different" if d := probe.Compare(base, keys); !d.Rebuild || !strings.Contains(strings.Join(d.RebuildReasons, ";"), "host keys") { t.Errorf("host key change not a rebuild: %+v", d) } other := probe.Compare(load(t, "expected-alpha.json"), load(t, "expected-beta.json")) if !other.Rebuild || len(other.RebuildReasons) != 2 { t.Errorf("different machines: %+v", other) } } func TestCompareDrift(t *testing.T) { oldP, newP := load(t, "expected-alpha.json"), load(t, "expected-alpha.json") newP.Sections.Containers = append(newP.Sections.Containers[:1], newP.Sections.Containers[2:]...) // drop the forgejo container (index 1) newP.Sections.Containers = append(newP.Sections.Containers, probe.Container{Name: "new-one", Image: "x:1", Project: "p"}) newP.Sections.Listening = newP.Sections.Listening[:len(newP.Sections.Listening)-1] sum := "0000" newP.Sections.Candidates[0].SHA256 = &sum newP.Sections.Services = newP.Sections.Services[:1] newP.Sections.Access.Sshd.PasswordAuthentication = "yes" d := probe.Compare(oldP, newP) if d.Rebuild { t.Error("drift alone is not a rebuild") } got := map[string]bool{} for _, c := range d.Drift { got[c.Section+" "+c.Kind+" "+c.Item] = true } for _, want := range []string{ "containers removed forgejo-forgejo-1", "containers added new-one", "listening removed tcp/100.64.0.11:41641", "candidates changed /srv/forgejo/update-forgejo.sh", "services removed forgejo-update.timer", "access changed sshd passwordauth", } { if !got[want] { t.Errorf("missing drift %q; have %v", want, got) } } text := probe.Compare(oldP, newP).Render("alpha", "A", "B") if !strings.Contains(text, "- containers forgejo-forgejo-1") || strings.Contains(text, "REBUILD") { t.Errorf("render:\n%s", text) } }