package fleet import ( "context" "os" "os/exec" "path/filepath" "strings" "testing" "time" ) // localRunner exécute le script distant en local, avec un faux `docker` en tête du PATH. type localRunner struct{ bin string } func (l localRunner) Run(ctx context.Context, host string, port int, user string, args []string, onLine func(string)) error { cmd := exec.CommandContext(ctx, shell(), append([]string{"-c", remoteScript, "stackwatch"}, args...)...) cmd.Env = append(os.Environ(), "PATH="+l.bin+":"+os.Getenv("PATH")) out, err := cmd.Output() for _, ln := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") { if ln != "" { onLine(ln) } } return err } // Faux docker : le comportement dépend du nom du répertoire courant. // // uptodate : une image à jour ; outdated : une à jour et une en retard ; // stopped : aucun conteneur ; badpull : pull en échec ; empty : fichier vide ; broken : fichier invalide. const fakeDocker = `#!/bin/sh d=$(basename "$PWD") case "$1 $2" in "version -f") echo 27.0.0; exit 0 ;; "compose version") if [ "$3" = "--short" ]; then echo 2.29.0; else echo "Docker Compose version v2.29.0"; fi; exit 0 ;; "compose config") [ "$d" = empty ] && { echo "empty compose file" >&2; exit 1; } [ "$d" = broken ] && { echo "yaml: line 3: mapping values are not allowed" >&2; exit 1; } exit 0 ;; "compose ps") [ "$d" = stopped ] && exit 0; echo c1; [ "$d" = outdated ] && echo c2; exit 0 ;; "compose pull") [ "$d" = badpull ] && { echo "pull access denied" >&2; exit 1; }; exit 0 ;; "compose down"|"compose up") exit 0 ;; "inspect -f") case "$4" in c1) echo "sha256:aaaaaaaaaaaaaaaaaaaa|nginx:latest|web" ;; c2) echo "sha256:bbbbbbbbbbbbbbbbbbbb|redis:7|cache" ;; esac; exit 0 ;; "image inspect") case "$5" in nginx:latest) [ "$d" = outdated ] && echo sha256:aaaaaaaaaaaaaaaaaaaa || echo sha256:aaaaaaaaaaaaaaaaaaaa ;; redis:7) echo sha256:cccccccccccccccccccc ;; esac; exit 0 ;; esac exit 1 ` func setup(t *testing.T) (root string, r localRunner) { t.Helper() tmp := t.TempDir() bin := filepath.Join(tmp, "bin") os.MkdirAll(bin, 0o755) os.WriteFile(filepath.Join(bin, "docker"), []byte(fakeDocker), 0o755) root = filepath.Join(tmp, "home") for _, d := range []string{"uptodate", "outdated", "stopped", "badpull", "empty", "broken", "alice/deep", ".hidden", "nocompose"} { os.MkdirAll(filepath.Join(root, d), 0o755) } for d, f := range map[string]string{"uptodate": "compose.yaml", "outdated": "docker-compose.yml", "stopped": "compose.yml", "badpull": "compose.yaml", "empty": "compose.yaml", "broken": "compose.yaml", "alice/deep": "compose.yaml", ".hidden": "compose.yaml"} { os.WriteFile(filepath.Join(root, d, f), []byte("services: {}\n"), 0o644) } return root, localRunner{bin} } func scanOnce(t *testing.T, r Runner, depth string, roots ...string) *Scan { t.Helper() sc := &Scan{} p := newScanParser(sc) if err := r.Run(context.Background(), "h", 22, "u", append([]string{"scan", depth}, roots...), p.Line); err != nil { t.Fatal(err) } p.Finish() return sc } func TestScanScript(t *testing.T) { root, r := setup(t) sc := scanOnce(t, r, "1", root, root+"/missing") got := map[string]Stack{} for _, s := range sc.Stacks { got[s.Name] = s } want := map[string]string{"uptodate": StatusUpToDate, "outdated": StatusUpdates, "stopped": StatusStopped, "badpull": StatusError, "broken": StatusError} for n, st := range want { if got[n].Status != st { t.Errorf("%s : statut %q, attendu %q (%+v)", n, got[n].Status, st, got[n]) } } for _, n := range []string{"empty", ".hidden", "nocompose", "deep"} { if _, ok := got[n]; ok { t.Errorf("%s ne devrait pas être listée", n) } } if o, n := got["outdated"].Counts(); o != 1 || n != 2 { t.Errorf("outdated : %d/%d services en retard", o, n) } if !strings.Contains(got["badpull"].Error, "pull access denied") || !strings.Contains(got["broken"].Error, "invalide") { t.Errorf("messages d'erreur : %q / %q", got["badpull"].Error, got["broken"].Error) } if len(sc.Warnings) != 1 || !strings.Contains(sc.Warnings[0], "missing") { t.Errorf("avertissements : %v", sc.Warnings) } if sc.Docker != "27.0.0" || sc.Compose != "2.29.0" { t.Errorf("versions : %q %q", sc.Docker, sc.Compose) } // Profondeur 2 : alice/deep apparaît. sc = scanOnce(t, r, "2", root) found := false for _, s := range sc.Stacks { found = found || s.Dir == root+"/alice/deep" } if !found { t.Error("profondeur 2 : alice/deep absente") } } func TestManagerFlow(t *testing.T) { root, r := setup(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() m, err := Open(ctx, t.TempDir(), r, 2) if err != nil { t.Fatal(err) } srv, err := m.Add(Server{Name: "lab", Host: "10.0.0.1", Enabled: true, Targets: []Target{{User: "root", Roots: []string{root}}}}) if err != nil { t.Fatal(err) } if _, err := m.Check(srv.ID, ""); err != nil { t.Fatal(err) } wait := func() View { for i := 0; i < 200; i++ { v := m.Snapshot()[0] if sc, ok := v.Scans[srv.Targets[0].ID]; ok && !sc.Running { return v } time.Sleep(25 * time.Millisecond) } t.Fatal("analyse trop longue") return View{} } sc := wait().Scans[srv.Targets[0].ID] if sc.Error != "" || len(sc.Stacks) != 5 { t.Fatalf("analyse : erreur %q, %d stacks", sc.Error, len(sc.Stacks)) } if sum := m.Summary(); sum.Updates != 1 || sum.Errors != 2 || sum.Stopped != 1 { t.Errorf("résumé : %+v", sum) } // Mise à jour : seulement une stack connue. if err := m.Apply(srv.ID, srv.Targets[0].ID, "/etc", "me"); err == nil { t.Error("stack inconnue acceptée") } if err := m.Apply(srv.ID, srv.Targets[0].ID, root+"/outdated", "me"); err != nil { t.Fatal(err) } sc = wait().Scans[srv.Targets[0].ID] var out Stack for _, s := range sc.Stacks { if s.Name == "outdated" { out = s } } if out.Status != StatusUpToDate || out.Applied == nil || !out.Applied.OK { t.Errorf("après mise à jour : %+v", out) } // Rechargement depuis le disque. m2, err := Open(ctx, m.dir, r, 2) if err != nil || len(m2.Snapshot()) != 1 || len(m2.Snapshot()[0].Scans) != 1 { t.Fatalf("persistance : %v", err) } if err := m.Delete(srv.ID); err != nil || len(m.Snapshot()) != 0 { t.Errorf("suppression : %v", err) } } func TestValidate(t *testing.T) { bad := []Server{ {Name: "", Host: "h", Targets: []Target{{User: "u"}}}, {Name: "a", Host: "-oProxyCommand=x", Targets: []Target{{User: "u"}}}, {Name: "a", Host: "h", Targets: []Target{{User: "u; id"}}}, {Name: "a", Host: "h", Targets: []Target{{User: "u", Roots: []string{"/home/../etc"}}}}, {Name: "a", Host: "h", Targets: []Target{{User: "u", Roots: []string{"/home/a b"}}}}, {Name: "a", Host: "h", Targets: []Target{{User: "u", Roots: []string{"/home/'x"}}}}, {Name: "a", Host: "h", Targets: []Target{{User: "u", Roots: []string{"relatif"}}}}, {Name: "a", Host: "h"}, } for i, s := range bad { if err := s.Validate(); err == nil { t.Errorf("cas %d accepté", i) } } ok := Server{Name: "a", Host: "srv.example.org", Targets: []Target{{User: "alice", Roots: []string{"/home/alice/", "/srv/stacks"}}}} if err := ok.Validate(); err != nil || ok.Port != 22 || ok.Targets[0].Roots[0] != "/home/alice" || ok.Targets[0].ID == "" { t.Errorf("serveur valide refusé ou mal normalisé : %v %+v", err, ok) } } func TestQuote(t *testing.T) { if got := quote("a'b"); got != `'a'\''b'` { t.Errorf("quote : %s", got) } cmd := remoteCommand([]string{"scan", "1", "/home"}) if !strings.HasPrefix(cmd, "sh -c '") || !strings.HasSuffix(cmd, "stackwatch 'scan' '1' '/home'") { t.Errorf("commande distante : ...%s", cmd[max(0, len(cmd)-60):]) } } // shell : interpréteur du script distant (TEST_SH=dash pour vérifier la portabilité POSIX). func shell() string { if s := os.Getenv("TEST_SH"); s != "" { return s } return "sh" }