SPB Git

Repository Public

executor_test.go 6.6 KB 186 lines go

1package executor23import (4	"context"5	"encoding/json"6	"os"7	"path/filepath"8	"strings"9	"sync"10	"testing"11	"time"1213	"clustr.spboucher.ai/mcc/internal/agent/policy"14	"clustr.spboucher.ai/mcc/internal/protocol"15)1617type sink struct {18	mu    sync.Mutex19	lines []protocol.CommandOutput20}2122func (s *sink) add(o protocol.CommandOutput) {23	s.mu.Lock()24	s.lines = append(s.lines, o)25	s.mu.Unlock()26}27func (s *sink) text() string {28	s.mu.Lock()29	defer s.mu.Unlock()30	var b strings.Builder31	for _, l := range s.lines {32		b.WriteString(l.Stream + ":" + l.Data + "\n")33	}34	return b.String()35}3637func TestPurgeCacheNeverLeavesTheDirectory(t *testing.T) {38	base, _ := filepath.EvalSymlinks(t.TempDir())39	cache := filepath.Join(base, "caches", "app")40	precious := filepath.Join(base, "precious")41	os.MkdirAll(filepath.Join(cache, "sub", "deep"), 0o755)42	os.MkdirAll(precious, 0o755)43	os.WriteFile(filepath.Join(precious, "keep.txt"), []byte("keep"), 0o600)44	os.WriteFile(filepath.Join(cache, "a.bin"), []byte("12345"), 0o600)45	os.WriteFile(filepath.Join(cache, "sub", "deep", "b.bin"), []byte("123"), 0o600)46	os.Symlink(precious, filepath.Join(cache, "link-out"))                     // directory link pointing out47	os.Symlink(filepath.Join(precious, "keep.txt"), filepath.Join(cache, "f")) // file link pointing out48	os.Symlink("../../precious", filepath.Join(cache, "sub", "rel-out"))4950	var sk sink51	oc := purgeCache(context.Background(), NewOutput(sk.add), "app", cache)52	if oc.Status != "succeeded" {53		t.Fatalf("%+v", oc)54	}55	if left, _ := os.ReadDir(cache); len(left) != 0 {56		t.Errorf("cache not emptied: %v", left)57	}58	if _, err := os.Stat(cache); err != nil {59		t.Error("the cache directory itself must remain")60	}61	if b, err := os.ReadFile(filepath.Join(precious, "keep.txt")); err != nil || string(b) != "keep" {62		t.Fatalf("a symlink was followed out of the cache: %v", err)63	}64}6566func prep(t *testing.T, pol *policy.Policy, typ, params string) (*Plan, error) {67	t.Helper()68	e := New(Deps{OwnLabel: "ai.spboucher.mcc-agent"})69	return e.Prepare(context.Background(), &protocol.Command{ID: "c1", Type: typ, Params: json.RawMessage(params), TimeoutS: 10}, pol)70}7172func TestPrepareRefusals(t *testing.T) {73	def := policy.Default()74	for _, c := range [][2]string{75		{"service.restart", `{"manager":"pm2","name":"api"}`},76		{"cache.purge", `{"cache":"npm"}`},77		{"job.run", `{"template":"x"}`},78		{"system.reboot", `{}`},79		{"agent.restart", `{}`},80		{"shell.exec", `{"cmd":"id"}`},81		{"diagnostic.run", `{"profile":"everything"}`},82		{"diagnostic.run", `{"profile":"basic","cmd":"id"}`},83		{"service.logs.tail", `{"manager":"pm2","name":"api","lines":100000}`},84		{"service.health_check", `{"manager":"pm2","name":"../../etc/passwd"}`},85		{"service.health_check", `{"manager":"pm2","name":"-rf"}`},86		{"service.health_check", `{"manager":"cron","name":"x"}`},87	} {88		if _, err := prep(t, def, c[0], c[1]); err == nil {89			t.Errorf("%s %s accepted by the default policy", c[0], c[1])90		} else if _, ok := err.(*Refusal); !ok {91			t.Errorf("%s: not a refusal: %v", c[0], err)92		}93	}94	pol, _ := policy.Parse([]byte(`{"allow":["service.restart","service.stop"],"services":{"launchd":["io.example.*","ai.spboucher.*"]}}`))95	if _, err := prep(t, pol, "service.restart", `{"manager":"launchd","name":"io.other"}`); err == nil {96		t.Error("service outside the allowlist accepted")97	}98	if _, err := prep(t, pol, "service.stop", `{"manager":"launchd","name":"ai.spboucher.mcc-agent"}`); err == nil {99		t.Error("stopping the agent's own service accepted")100	}101	if p, err := prep(t, pol, "service.restart", `{"manager":"launchd","name":"io.example.web"}`); err != nil || p.Target != "service:launchd/io.example.web" {102		t.Errorf("%v", err)103	}104	if _, err := prep(t, def, "diagnostic.run", ``); err != nil {105		t.Errorf("default profile: %v", err)106	}107}108109func TestRunStreamingEnvTimeoutCancel(t *testing.T) {110	t.Setenv("MCC_SUPER_SECRET", "leak-me-not")111	var sk sink112	out := NewOutput(sk.add)113	res := runStreaming(context.Background(), out, time.Second, "", []string{"DECLARED=yes"}, "/usr/bin/env")114	if res.Status != "succeeded" {115		t.Fatalf("%+v", res)116	}117	txt := sk.text()118	if strings.Contains(txt, "leak-me-not") || strings.Contains(txt, "MCC_SUPER_SECRET") {119		t.Fatal("the agent's environment leaked into a child")120	}121	if !strings.Contains(txt, "DECLARED=yes") || !strings.Contains(txt, "PATH=") {122		t.Fatalf("declared env missing: %s", txt)123	}124	// Non-zero exit.125	if res := runStreaming(context.Background(), NewOutput(sk.add), time.Second, "", nil, "/bin/sh", "-c", "exit 3"); res.Status != "failed" || res.ExitCode != 3 {126		t.Fatalf("%+v", res)127	}128	// Timeout: SIGTERM is ignored by the child, so SIGKILL must follow the grace period; the whole group dies.129	ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)130	start := time.Now()131	res = runStreaming(ctx, NewOutput(sk.add), 400*time.Millisecond, "", nil, "/bin/sh", "-c", "trap '' TERM; sleep 30 & wait")132	cancel()133	if res.Status != "timed_out" || time.Since(start) > 8*time.Second {134		t.Fatalf("%+v after %s", res, time.Since(start))135	}136	// Cooperative cancel.137	cctx, ccancel := context.WithCancelCause(context.Background())138	go func() { time.Sleep(200 * time.Millisecond); ccancel(CancelCause()) }()139	if res = runStreaming(cctx, NewOutput(sk.add), time.Second, "", nil, "/bin/sleep", "30"); res.Status != "cancelled" {140		t.Fatalf("%+v", res)141	}142}143144func TestOutputCapAndRedaction(t *testing.T) {145	var sk sink146	out := NewOutput(sk.add)147	out.Limit(5, 1<<20)148	out.Line("stdout", "API_TOKEN=abcdef123456 ok")149	out.Line("stdout", "-----BEGIN RSA PRIVATE KEY-----")150	out.Line("stdout", "short")151	out.Line("stdout", "-----END RSA PRIVATE KEY-----")152	for i := 0; i < 20; i++ {153		out.Line("stdout", "line")154	}155	txt := sk.text()156	if strings.Contains(txt, "abcdef123456") || strings.Contains(txt, "short") {157		t.Fatalf("not redacted: %s", txt)158	}159	if !out.Truncated() || len(sk.lines) != 6 || !strings.Contains(sk.lines[5].Data, "truncated") {160		t.Fatalf("cap: %d lines, truncated=%v", len(sk.lines), out.Truncated())161	}162}163164func TestTailFile(t *testing.T) {165	f := filepath.Join(t.TempDir(), "x.log")166	var b strings.Builder167	for i := 0; i < 1000; i++ {168		b.WriteString("entry ")169		b.WriteString(strings.Repeat("z", 20))170		b.WriteString("\n")171	}172	b.WriteString("last PASSWORD=hunter2\n")173	os.WriteFile(f, []byte(b.String()), 0o600)174	var sk sink175	out := NewOutput(sk.add)176	if err := tailFile(out, "stdout", f, 10, 1024); err != nil {177		t.Fatal(err)178	}179	if len(sk.lines) != 10 || strings.Contains(sk.text(), "hunter2") || !strings.Contains(sk.lines[9].Data, "last") {180		t.Fatalf("%d lines: %s", len(sk.lines), sk.text())181	}182	if err := tailFile(out, "stdout", filepath.Dir(f), 10, 1024); err == nil {183		t.Error("directory accepted")184	}185}186
Files main
Menu

Theme