hub/internal/suggest/suggest_test.go
trvon 0d7a219c5d
Some checks failed
release / build (push) Failing after 2m13s
hub: operator CLI with signed self-update
2026-11-10 20:32:32 -07:00

327 lines
11 KiB
Go

// SPDX-License-Identifier: GPL-3.0-or-later
package suggest_test
import (
"os"
"path/filepath"
"strings"
"testing"
"git.trevon.dev/trevon/hub/internal/inventory"
"git.trevon.dev/trevon/hub/internal/probe"
"git.trevon.dev/trevon/hub/internal/suggest"
)
const (
fixtures = "../../probe/fixtures"
)
// Inventory lines in the shape of an Ansible INI inventory; oldBetaInventory has the address before a rebuild.
const inventoryText = `[managed_admin]
beta-ci ansible_user=admin ansible_host=100.64.0.12 ansible_port=22 syslog_hostname=beta
alpha ansible_user=admin ansible_host=100.64.0.11 ansible_port=22 syslog_hostname=alpha
[ci]
beta-ci
[protected_services]
alpha
`
const oldBetaInventory = `[managed_admin]
beta-ci ansible_user=admin ansible_host=100.64.0.13 ansible_port=22 syslog_hostname=beta
`
func profile(t *testing.T, name string) *probe.Profile {
t.Helper()
raw, err := os.ReadFile(filepath.Join(fixtures, name))
if err != nil {
t.Fatal(err)
}
p, err := probe.Parse(raw)
if err != nil {
t.Fatal(err)
}
return p
}
func build(t *testing.T, invText, host, fixture string) *suggest.Suggestion {
t.Helper()
inv, err := inventory.Parse(strings.NewReader(invText))
if err != nil {
t.Fatal(err)
}
h, ok := inv.Host(host)
if !ok {
t.Fatalf("host %s not in inventory", host)
}
salted, err := suggest.SaltManagedPaths("")
if err != nil {
t.Fatal(err)
}
return suggest.Build(host, h, profile(t, fixture), salted)
}
func ids(f []suggest.Finding) []string {
out := make([]string, len(f))
for i, x := range f {
out[i] = x.ID
}
return out
}
func find(f []suggest.Finding, id string) *suggest.Finding {
for i := range f {
if f[i].ID == id {
return &f[i]
}
}
return nil
}
func eqStrings(a, b []string) bool { return strings.Join(a, "\x00") == strings.Join(b, "\x00") }
func TestGoldenExpectedAlpha(t *testing.T) {
s := build(t, inventoryText, "alpha", "expected-alpha.json")
if len(s.ComposeProjects) != 2 {
t.Fatalf("projects = %+v", s.ComposeProjects)
}
f, o := s.ComposeProjects[0], s.ComposeProjects[1]
if f.Name != "forgejo" || !eqStrings(f.Services, []string{"forgejo", "caddy"}) {
t.Errorf("forgejo project = %+v", f)
}
if got := f.AllowedPorts; len(got) != 3 || got[0] != 80 || got[1] != 443 || got[2] != 2222 {
t.Errorf("allowed_ports = %v, want [80 443 2222] (3000 is loopback, :: twin collapsed)", got)
}
if o.Name != "forgejo-onion" || !eqStrings(o.Services, []string{"tor"}) || o.AllowedPorts == nil || len(o.AllowedPorts) != 0 {
t.Errorf("onion project = %+v (allowed_ports must be an empty list, not absent)", o)
}
if f.ForbidRoot || o.ForbidRoot {
t.Error("alpha runs root containers: forbid_root must not be suggested")
}
b := find(s.Blockers, "sshd-allowusers")
if b == nil || !strings.Contains(b.Message, "admin") {
t.Errorf("AllowUsers blocker missing: %v", s.Blockers)
}
if !eqStrings(ids(s.Blockers), []string{"sshd-allowusers"}) {
t.Errorf("blockers = %v, want only sshd-allowusers", ids(s.Blockers))
}
c := find(s.Candidates, "script")
if c == nil || !strings.Contains(c.Message, "/srv/forgejo/update-forgejo.sh") || !strings.Contains(c.Message, "root:root") ||
!strings.Contains(c.Message, "a04444330f4a7d32cd82c92655929117d9fb0a74169cd508f8e180710a6c4ae2") {
t.Errorf("update-forgejo.sh candidate = %v", c)
}
if find(s.Candidates, "fail2ban") == nil || find(s.Candidates, "firewall") == nil {
t.Errorf("candidates = %v", ids(s.Candidates))
}
if find(s.Candidates, "unit") != nil {
t.Errorf("forgejo-update units are installed by salt/security_hub/forgejo_maintenance.sls: %v", s.Candidates)
}
for _, want := range []string{
" - name: forgejo\n services: [forgejo, caddy]\n allowed_ports: [80, 443, 2222]\n",
" - name: forgejo-onion\n services: [tor]\n allowed_ports: []\n",
"security_hub:\n audit:\n expected_nopasswd_users:\n - admin\n",
} {
if !strings.Contains(s.Pillar, want) {
t.Errorf("pillar lacks:\n%s\nhave:\n%s", want, s.Pillar)
}
}
if strings.Contains(s.Pillar, "forbid_root") {
t.Error("forbid_root rendered for alpha")
}
groups := map[string]bool{}
for _, g := range s.Groups {
groups[g.Name] = g.Present
}
if !groups["managed_admin"] || !groups["protected_services"] || groups["ci"] {
t.Errorf("groups = %+v", s.Groups)
}
}
func TestGoldenExpectedBeta(t *testing.T) {
s := build(t, inventoryText, "beta-ci", "expected-beta.json")
if len(s.ComposeProjects) != 1 {
t.Fatalf("projects = %+v", s.ComposeProjects)
}
p := s.ComposeProjects[0]
if p.Name != "challenges" || !eqStrings(p.Services, []string{"lab-a", "lab-b", "lab-c", "lab-d"}) {
t.Errorf("project = %+v", p)
}
if !p.ForbidRoot {
t.Error("all beta containers are non-root: forbid_root expected")
}
if p.AllowedPorts != nil || !strings.Contains(p.PortsNote, "open lab") {
t.Errorf("24 published lab ports must not become an allowed_ports list: %+v", p)
}
if !strings.Contains(s.Pillar, "forbid_root: true") || strings.Contains(s.Pillar, "allowed_ports: [") {
t.Errorf("pillar:\n%s", s.Pillar)
}
if len(s.Blockers) != 0 {
t.Errorf("blockers = %v, want none with the current address", s.Blockers)
}
if find(s.Candidates, "script") != nil {
t.Errorf("/usr/local/bin/forgejo-runner is installed by Salt, not a takeover candidate: %v", s.Candidates)
}
// Collapsed ranges: udp 8500-8519 is one line.
var udp *suggest.Finding
for i, c := range s.Candidates {
if strings.Contains(c.Message, "udp port 8500-8519") {
udp = &s.Candidates[i]
}
}
if udp == nil {
t.Errorf("udp range not collapsed: %v", s.Candidates)
}
}
func TestBetaOldAddressIsABlocker(t *testing.T) {
s := build(t, oldBetaInventory, "beta-ci", "expected-beta.json")
b := find(s.Blockers, "address")
if b == nil || !strings.Contains(b.Message, "100.64.0.13") || !strings.Contains(b.Message, "100.64.0.12") {
t.Fatalf("address blocker = %v (all: %v)", b, s.Blockers)
}
}
func TestBlockerMatrix(t *testing.T) {
inv := "[x]\nhost1 ansible_host=100.64.0.11 ansible_user=admin syslog_hostname=other\n"
s := build(t, inv, "host1", "expected-alpha.json")
got := ids(s.Blockers)
// minion id "alpha" != inventory name "host1"; hostname "alpha" != syslog "other"; AllowUsers is set.
for _, want := range []string{"minion-id", "hostname", "sshd-allowusers"} {
if find(s.Blockers, want) == nil {
t.Errorf("blocker %s missing in %v", want, got)
}
}
p := profile(t, "expected-alpha.json")
p.Sections.Access.SudoNopasswd = false
p.Sections.Access.Sshd.AllowUsers = nil
inventoryParsed, _ := inventory.Parse(strings.NewReader(inventoryText))
h, _ := inventoryParsed.Host("alpha")
s2 := suggest.Build("alpha", h, p, nil)
if find(s2.Blockers, "sudo") == nil || find(s2.Blockers, "sshd-allowusers-unknown") == nil {
t.Errorf("blockers = %v", ids(s2.Blockers))
}
if len(s2.ExpectedNopasswdUsers) != 0 {
t.Errorf("no sudo, no expected_nopasswd_users: %v", s2.ExpectedNopasswdUsers)
}
}
func TestRealGit(t *testing.T) {
s := build(t, inventoryText, "alpha", "real-alpha.json")
b := find(s.Blockers, "sshd-allowusers")
if b == nil || !strings.Contains(b.Message, "backup@100.64.0.1") {
t.Errorf("real AllowUsers blocker = %v", s.Blockers)
}
if !eqStrings(ids(s.Blockers), []string{"sshd-allowusers"}) {
t.Errorf("blockers = %v", ids(s.Blockers))
}
if find(s.Candidates, "fail2ban") != nil || find(s.Candidates, "firewall") != nil {
t.Errorf("fail2ban and ufw are active on the real alpha: %v", s.Candidates)
}
if c := find(s.Candidates, "script"); c == nil || !strings.Contains(c.Message, "update-forgejo.sh") {
t.Errorf("candidates = %v", s.Candidates)
}
if len(s.ComposeProjects) != 2 || !eqStrings(s.ComposeProjects[0].Services, []string{"forgejo", "caddy"}) ||
!eqStrings(s.ComposeProjects[1].Services, []string{"tor"}) {
t.Errorf("projects = %+v", s.ComposeProjects)
}
if got := s.ComposeProjects[0].AllowedPorts; len(got) != 3 || got[2] != 2222 {
t.Errorf("v4/v6 twins must collapse: %v", got)
}
for _, c := range s.Candidates {
if strings.Contains(c.Message, "security-hub-monthly-reboot") {
t.Errorf("hub-managed unit listed: %v", c)
}
}
}
func TestRealBetaCI(t *testing.T) {
s := build(t, inventoryText, "beta-ci", "real-beta-ci.json")
if len(s.ComposeProjects) != 1 || s.ComposeProjects[0].Name != "challenges" {
t.Fatalf("CI job container (no compose label) must be ignored: %+v", s.ComposeProjects)
}
if !eqStrings(s.ComposeProjects[0].Services, []string{"lab-a", "lab-b", "lab-c", "lab-d"}) {
t.Errorf("services = %v", s.ComposeProjects[0].Services)
}
if !s.ComposeProjects[0].ForbidRoot {
t.Error("forbid_root expected (the CI job container has no compose project and does not count)")
}
for _, id := range []string{"sshd-password-login", "sshd-root-login", "fail2ban"} {
if find(s.Candidates, id) == nil {
t.Errorf("candidate %s missing: %v", id, ids(s.Candidates))
}
}
if find(s.Candidates, "script") != nil || find(s.Candidates, "unit") != nil {
t.Errorf("forgejo-runner is Salt-installed: %v", s.Candidates)
}
if find(s.Candidates, "firewall") != nil {
t.Error("ufw is active on beta-ci")
}
if len(s.Blockers) != 0 {
t.Errorf("blockers = %v", s.Blockers)
}
// IPv4 and IPv6 twins collapse into one line per port.
n := 0
for _, c := range s.Candidates {
if strings.Contains(c.Message, "tcp port 8420 ") {
n++
}
}
if n != 1 {
t.Errorf("tcp 8420 listed %d times", n)
}
}
func TestSaltManagedPaths(t *testing.T) {
salted, err := suggest.SaltManagedPaths("")
if err != nil {
t.Fatal(err)
}
for _, p := range []string{"/usr/local/bin/forgejo-runner", "/etc/systemd/system/forgejo-update.service", "/usr/local/libexec/security-hub-ctf-watch"} {
if !salted[p] {
t.Errorf("%s missing from the built-in default list", p)
}
}
for _, p := range []string{"/srv/forgejo/update-forgejo.sh", "saltutil.sync_modules"} {
if salted[p] {
t.Errorf("%s must not count as salt-managed", p)
}
}
}
func TestSaltManagedPathsFile(t *testing.T) {
dir := t.TempDir()
good := filepath.Join(dir, "paths.txt")
if err := os.WriteFile(good, []byte("# mine\n\n/opt/app/run.sh\n /etc/app.conf \n"), 0o644); err != nil {
t.Fatal(err)
}
salted, err := suggest.SaltManagedPaths(good)
if err != nil {
t.Fatal(err)
}
if len(salted) != 2 || !salted["/opt/app/run.sh"] || !salted["/etc/app.conf"] {
t.Errorf("file paths = %v", salted)
}
if salted["/usr/local/bin/forgejo-runner"] {
t.Error("a configured file replaces the default list")
}
for name, body := range map[string]string{"empty": "# nothing\n", "relative": "bin/run.sh\n", "jinja": "/etc/{{ x }}\n"} {
p := filepath.Join(dir, name)
_ = os.WriteFile(p, []byte(body), 0o644)
if _, err := suggest.SaltManagedPaths(p); err == nil {
t.Errorf("%s file must be an error, not an empty or partial set", name)
}
}
if _, err := suggest.SaltManagedPaths(filepath.Join(dir, "absent")); err == nil {
t.Error("an unreadable file must be an error")
}
}
func TestRenderSections(t *testing.T) {
s := build(t, inventoryText, "alpha", "expected-alpha.json")
out := suggest.Render(s)
for _, want := range []string{"GROUPS (suggested)", "PILLAR (review, then paste)", "BLOCKERS (1)", "CANDIDATES (", "[sshd-allowusers]", "allowed_ports: [80, 443, 2222]"} {
if !strings.Contains(out, want) {
t.Errorf("render lacks %q:\n%s", want, out)
}
}
}