package thin import ( "context" "crypto/sha256" "fmt" "net" "os" "os/exec" "path/filepath" "sync" "testing" "amadan.net/oficina/equipo/internal/runner" ) var scannerBuild struct { sync.Mutex binary, pin string } func previewScannerFixture(t *testing.T) string { t.Helper() scannerBuild.Lock() defer scannerBuild.Unlock() if scannerBuild.binary == "" { dir, err := os.MkdirTemp(os.Getenv("TMPDIR"), "equipo-scanner-test-") if err != nil { t.Fatal(err) } // Re-execute the already compiled test binary's pinned gitleaks command. // No compiler, module cache or network is used to prepare the scanner. binary := copySelf(t, dir, "gitleaks") raw, err := os.ReadFile(binary) if err != nil { t.Fatal(err) } scannerBuild.binary = binary scannerBuild.pin = fmt.Sprintf("%x", sha256.Sum256(raw)) } old := previewScannerTool previewScannerTool = func(c runner.Config) (string, string) { return filepath.Join(filepath.Dir(c.Executable), "gitleaks"), scannerBuild.pin } t.Cleanup(func() { previewScannerTool = old }) return filepath.Join(filepath.Dir(scannerBuild.binary), "equipo-runner") } func TestPreviewScannerSandboxDeniesNetworkAndHostFiles(t *testing.T) { root := t.TempDir() outside, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } defer outside.Close() secret := filepath.Join(root, "host-only.txt") if err := os.WriteFile(secret, []byte("host data"), 0600); err != nil { t.Fatal(err) } source := fmt.Sprintf(`package main import("os";"net";"time") func main(){ found:=false if c,e:=net.DialTimeout("tcp",%q,300*time.Millisecond);e==nil{found=true;c.Close()} if _,e:=os.ReadFile(%q);e==nil{found=true} report:="";for i,a:=range os.Args{if a=="--report-path"{report=os.Args[i+1]}} body:="[]";if found{body="[{}]"};if os.WriteFile(report,[]byte(body),0600)!=nil{os.Exit(2)} }`, outside.Addr().String(), secret) file := filepath.Join(root, "scanner.go") if err := os.WriteFile(file, []byte(source), 0600); err != nil { t.Fatal(err) } binary := filepath.Join(root, "scanner") cmd := exec.Command("go", "build", "-o", binary, file) cmd.Env = append(os.Environ(), "CGO_ENABLED=0") if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("fixture build: %v %s", err, out) } raw, err := os.ReadFile(binary) if err != nil { t.Fatal(err) } old := previewScannerTool t.Cleanup(func() { previewScannerTool = old }) previewScannerTool = func(runner.Config) (string, string) { return binary, fmt.Sprintf("%x", sha256.Sum256(raw)) } stage := filepath.Join(root, "export") if err := os.Mkdir(stage, 0700); err != nil { t.Fatal(err) } if why := (&Engineer{}).scanPreview(context.Background(), stage); why != "" { t.Fatal("scanner reached network or host files:", why) } }