package thin import ( "amadan.net/oficina/equipo/internal/wire" "context" "encoding/json" "fmt" "os" "path/filepath" "strings" "testing" ) func TestCollectChangeDiffs(t *testing.T) { dir, git := factsRepo(t) base := git("rev-parse", "HEAD") git("mv", "README.md", "read me 日本語.md") writeFile(t, dir, "clean.txt", "one\ntwo\n") writeFile(t, dir, "secret.txt", "token = ghp_"+strings.Repeat("aB3cD4", 6)+"\n") writeFile(t, dir, "large.txt", strings.Repeat("x", wire.MaxDiffBlobBytes+1)) writeFile(t, dir, "binary.dat", "\x00\xff") git("add", "-A") git("commit", "-qm", "candidate") sha := git("rev-parse", "HEAD") facts := changeFiles(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), base, sha) files := collectChangeDiffs(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), facts, nil) got := map[string]wire.FileDiff{} for _, f := range files { got[f.Path] = f } if !strings.Contains(got["clean.txt"].Patch, "+two\n") { t.Fatal("clean patch missing") } if got["secret.txt"].Reason != wire.DiffWithheld || got["secret.txt"].Patch != "" { t.Fatal("secret leaked") } if got["large.txt"].Reason != wire.DiffTooLarge { t.Fatal("large blob read") } if got["binary.dat"].Reason != wire.DiffBinary { t.Fatal("binary patch") } if !strings.Contains(got["read me 日本語.md"].Patch, "rename from README.md") { t.Fatal("rename missing") } ctx, cancel := context.WithCancel(context.Background()) cancel() for _, f := range collectChangeDiffs(ctx, "/usr/bin/git", filepath.Join(dir, ".git"), facts, nil) { if f.Patch != "" { t.Fatal("cancelled output") } } } func TestDisplayPatchClip(t *testing.T) { for _, input := range []string{strings.Repeat("+x\n", wire.MaxFileDiffLines+1), strings.Repeat("+"+strings.Repeat("é", 200)+"\n", 400)} { p, cut := clipDisplayPatch(input) if !cut || !wire.ValidFileDiff(wire.FileDiff{Path: "x", Patch: p, Truncated: cut}) { t.Fatal("bounds") } } } func TestDisplayBlobSafetyAndInputBudget(t *testing.T) { dir, git := factsRepo(t) writeFile(t, dir, "safe.txt", "hello\n") writeFile(t, dir, "large.txt", strings.Repeat("x", wire.MaxDiffBlobBytes+1)) if err := os.Symlink("safe.txt", filepath.Join(dir, "link")); err != nil { t.Fatal(err) } git("add", "-A") git("commit", "-qm", "modes") sha := git("rev-parse", "HEAD") gitDir := filepath.Join(dir, ".git") for _, tc := range []struct { path string budget int want string }{{"large.txt", 2 * wire.MaxDiffBlobBytes, wire.DiffTooLarge}, {"safe.txt", 5, wire.DiffTooLarge}, {"safe.txt", 6, ""}, {"link", 100, wire.DiffUnavailable}} { budget := tc.budget data, reason := displayBlob(context.Background(), "/usr/bin/git", gitDir, sha, tc.path, &budget) if reason != tc.want { t.Fatalf("%s: %s", tc.path, reason) } if reason != "" && data != "" { t.Fatal("refused bytes") } if reason == "" && budget != 0 { t.Fatal("aggregate budget not charged") } } // Initial commit is compared with the empty tree; long lines never leak a // clipped prefix, even when the scanner would find a secret at the end. root := strings.Fields(git("rev-list", "--max-parents=0", "HEAD"))[0] facts := changeFiles(context.Background(), "/usr/bin/git", gitDir, "", root) if got := collectChangeDiffs(context.Background(), "/usr/bin/git", gitDir, facts, nil); len(got) == 0 || got[0].Reason != "" { t.Fatal("initial commit unavailable") } } func TestCollectionScansBeforeAfterAndBeyondCut(t *testing.T) { dir, git := factsRepo(t) secret := "rk_live_" + "0123456789abcdefghijklmnop" writeFile(t, dir, "removed.txt", strings.Repeat("before-safe\n", 3000)+secret+"\n") writeFile(t, dir, "context.txt", secret+"\none\n") git("add", "-A") git("commit", "-qm", "base") base := git("rev-parse", "HEAD") git("rm", "removed.txt") writeFile(t, dir, "context.txt", secret+"\ntwo\n") writeFile(t, dir, "beyond-cut.txt", strings.Repeat("after-safe\n", 3000)+secret+"\n") git("add", "-A") git("commit", "-qm", "candidate") f := changeFiles(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), base, git("rev-parse", "HEAD")) for _, d := range collectChangeDiffs(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), f, nil) { if d.Reason != wire.DiffWithheld || d.Patch != "" { t.Fatalf("%s was not wholly withheld", d.Path) } } } func TestDisplayIgnoresRepositoryScannerAndDiffCommands(t *testing.T) { dir, git := factsRepo(t) base := git("rev-parse", "HEAD") marker := filepath.Join(t.TempDir(), "executed") driver := filepath.Join(t.TempDir(), "driver") if err := os.WriteFile(driver, []byte("#!/bin/sh\ntouch '"+marker+"'\n"), 0700); err != nil { t.Fatal(err) } git("config", "diff.evil.command", driver) git("config", "diff.evil.textconv", driver) writeFile(t, dir, ".gitattributes", "*.txt diff=evil\n") writeFile(t, dir, ".gitleaks.toml", "[allowlist]\nregexes = ['.*']\n") writeFile(t, dir, "secret.txt", "rk_live_"+"0123456789abcdefghijklmnop # gitleaks:allow\n") writeFile(t, dir, "safe.txt", "plain text\n") git("add", "-A") git("commit", "-qm", "hostile configuration") f := changeFiles(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), base, git("rev-parse", "HEAD")) found := false for _, d := range collectChangeDiffs(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), f, nil) { if d.Path == "secret.txt" { found = true if d.Reason != wire.DiffWithheld { t.Fatal("candidate weakened scanner") } } } if !found { t.Fatal("missing secret fixture") } if _, err := os.Stat(marker); !os.IsNotExist(err) { t.Fatal("candidate diff command ran") } } func TestDisplayLiteralPathspecAndCandidateCap(t *testing.T) { dir, git := factsRepo(t) base := git("rev-parse", "HEAD") writeFile(t, dir, "star*.txt", "literal only\n") writeFile(t, dir, "starOTHER.txt", "different file\n") // Thirty-four independently bounded patches exceed the candidate cap. for i := 0; i < 34; i++ { writeFile(t, dir, fmt.Sprintf("large-%02d.txt", i), strings.Repeat("x", 64000)+"\n") } git("add", "-A") git("commit", "-qm", "bounded files") facts := changeFiles(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), base, git("rev-parse", "HEAD")) files := collectChangeDiffs(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), facts, nil) total, large := 0, 0 for _, file := range files { total += len(file.Patch) if strings.HasPrefix(file.Path, "large-") && file.Reason == wire.DiffTooLarge { large++ } } if total > wire.MaxCandidateDiffBytes || large == 0 { t.Fatalf("candidate cap missing: bytes=%d withheld=%d", total, large) } // Test literal selection separately from the exhausted aggregate budget. budget := 100 text, reason := displayBlob(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), facts.SHA, "star*.txt", &budget) if reason != "" || text != "literal only\n" { t.Fatal("literal pathspec lost", reason) } patch, cut, err := displayGit(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), wire.MaxFileDiffBytes, "diff-tree", "-p", "-r", base, facts.SHA, "--", "star*.txt") if err != nil || cut || !strings.Contains(patch, "+literal only") || strings.Contains(patch, "+different file") { t.Fatal("diff pathspec expanded", err) } } func TestQueueDiffWithholdsOwnForgeCredentials(t *testing.T) { dir, git := factsRepo(t) base := git("rev-parse", "HEAD") writeFile(t, dir, "api.txt", "api-canary\n") writeFile(t, dir, "git.txt", "git-canary\n") writeFile(t, dir, "password.txt", "redis://:secret@repo.example.test/path\n") git("add", "-A") git("commit", "-qm", "credentials") facts := changeFiles(context.Background(), "/usr/bin/git", filepath.Join(dir, ".git"), base, git("rev-parse", "HEAD")) state, err := OpenState(context.Background(), t.TempDir()) if err != nil { t.Fatal(err) } defer state.Close() credential := filepath.Join(t.TempDir(), "credentials.json") if err = os.WriteFile(credential, []byte(`{"agent":"equipo~owner@example.test","repositories":{"amadan.net/ns/repo":{"api":"api-canary","git":"git-canary"}}}`), 0600); err != nil { t.Fatal(err) } engineer := Engineer{O: ClaudeOptions{State: state, Protocol: func() int { return wire.ProtocolCurrent }}} engineer.O.Runner.AmadanCredentialPath = credential facts, known := engineer.screenChangeFiles(context.Background(), "amadan.net/ns/repo", facts) if facts == nil { t.Fatal("the measurement was withheld") } if engineer.queueChangeDiffs(context.Background(), stepRow{DispatchCommand: wire.DispatchCommand{TaskID: "tk", StepID: "s", Attempt: 1, Repo: "amadan.net/ns/repo"}}, "/usr/bin/git", filepath.Join(dir, ".git"), facts, known) == "" { t.Fatal("no collection") } frames, _, err := state.Unacked(context.Background(), 0) if err != nil { t.Fatal(err) } if len(frames) != 3 { t.Fatalf("frames=%d", len(frames)) } for _, frame := range frames { var file wire.ChangeDiffUpload if err = json.Unmarshal(frame.Data, &file); err != nil { t.Fatal(err) } if file.Reason != wire.DiffWithheld || file.Data != "" { t.Fatal("credential bytes queued", file.Path) } } }