diff --git a/.github/workflows/pr-size.yml b/.github/workflows/pr-size.yml index 29c55d0..96ec356 100644 --- a/.github/workflows/pr-size.yml +++ b/.github/workflows/pr-size.yml @@ -20,3 +20,13 @@ jobs: - uses: ./pr-size with: report-only: "true" + mask-scan: + name: Mask Scan + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 + persist-credentials: false + - uses: ./mask-scan diff --git a/README.md b/README.md index 90b2a9a..459c3a2 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,32 @@ starting with `Size exception:`, followed by a reason of at least 20 printable characters after trimming spaces. Set `report-only` to `"true"` to show the verdict without enforcing it. +## Mask scan + +The `mask-scan` action fails a pull request when an added line contains six +or more consecutive asterisks. This can happen when a tool's redacted view +is written back to a file. The action reports file paths and line numbers +without printing the matched text. + +Run it on `pull_request` with a read-only token and no secrets. Check out +the caller repo first with `fetch-depth: 0` and `persist-credentials: false`. +The action compares `HEAD` with its merge base on `origin/` and +does not fetch refs. By default, `base-ref` is the PR target branch. +Replace `` with the commit SHA to pin. + +```yaml + - uses: devsy-org/ci/mask-scan@ + with: + allow: | + docs/examples/ + fixtures/*.txt +``` + +Use `allow` for intentional runs, one repo-relative pattern per line. +Patterns ending in `/` match all paths under that prefix. Other patterns +use Go's `path.Match` syntax, where `*` does not match `/`. +Set `report-only: "true"` to report matches without failing the job. + ## Lint baseline The `lint-baseline` action runs golangci-lint and fails when a pull request diff --git a/cmd/mask-scan/main.go b/cmd/mask-scan/main.go new file mode 100644 index 0000000..46b4b47 --- /dev/null +++ b/cmd/mask-scan/main.go @@ -0,0 +1,26 @@ +package main + +import ( + "context" + "flag" + "os" + + "github.com/devsy-org/ci/internal/maskscan" +) + +func main() { + var opts maskscan.Options + flag.StringVar(&opts.BaseRef, "base-ref", "", "target branch name on origin") + flag.StringVar(&opts.Repo, "repo", ".", "path to the pull request checkout") + flag.BoolVar(&opts.ReportOnly, "report-only", false, "report without enforcing the verdict") + flag.Func( + "allow", + "exclude a glob or directory prefix (repeatable)", + func(pattern string) error { + opts.Allow = append(opts.Allow, pattern) + return nil + }, + ) + flag.Parse() + os.Exit(maskscan.Run(context.Background(), opts, flag.NArg())) +} diff --git a/internal/maskscan/diff.go b/internal/maskscan/diff.go new file mode 100644 index 0000000..c14bd47 --- /dev/null +++ b/internal/maskscan/diff.go @@ -0,0 +1,91 @@ +package maskscan + +import ( + "path" + "regexp" + "strconv" + "strings" +) + +type hit struct { + path string + line int +} + +type diffPosition struct { + path string + line int +} + +func scanDiff(diff string, allow []string) []hit { + mask := regexp.MustCompile(`\*{6,}`) + var pos diffPosition + var hits []hit + for line := range strings.SplitSeq(diff, "\n") { + if added := pos.advance(line, allow); added && mask.MatchString(line[1:]) { + hits = append(hits, hit{path: pos.path, line: pos.line - 1}) + } + } + return hits +} + +func (p *diffPosition) advance(line string, allow []string) bool { + switch { + case strings.HasPrefix(line, "diff --git "): + *p = diffPosition{} + case strings.HasPrefix(line, "@@ "): + p.line = hunkStart(line) + case p.line == 0: + if name, ok := strings.CutPrefix(line, "+++ "); ok { + p.path = addedPath(name, allow) + } + case strings.HasPrefix(line, "+"): + p.line++ + return p.path != "" + case strings.HasPrefix(line, " "): + p.line++ + } + return false +} + +func hunkStart(line string) int { + _, newRange, ok := strings.Cut(line, " +") + if !ok { + return 0 + } + start, _, _ := strings.Cut(newRange, " ") + start, _, _ = strings.Cut(start, ",") + n, _ := strconv.Atoi(start) + return n +} + +func addedPath(name string, allow []string) string { + name = strings.TrimSuffix(name, "\t") + if strings.HasPrefix(name, `"`) { + unquoted, err := strconv.Unquote(name) + if err != nil { + unquoted = strings.TrimPrefix(name, `"`) + } + name = unquoted + } + name, ok := strings.CutPrefix(name, "b/") + if !ok || allowed(name, allow) { + return "" + } + return name +} + +func allowed(name string, allow []string) bool { + for _, pattern := range allow { + if strings.HasSuffix(pattern, "/") { + if strings.HasPrefix(name, pattern) { + return true + } + continue + } + if matched, _ := path.Match(pattern, name); matched { + return true + } + } + return false +} diff --git a/internal/maskscan/diff_test.go b/internal/maskscan/diff_test.go new file mode 100644 index 0000000..4f79a3c --- /dev/null +++ b/internal/maskscan/diff_test.go @@ -0,0 +1,75 @@ +package maskscan + +import ( + "slices" + "strings" + "testing" +) + +func TestScanDiff(t *testing.T) { + t.Parallel() + mask := strings.Repeat("*", 6) + tests := []struct { + name string + diff string + allow []string + want []hit + }{ + { + name: "number added lines across hunks and files", + diff: patchHeader("one.txt") + + "@@ -2 +2,2 @@\n-old\n+plain\n+" + mask + "\n" + + "@@ -8 +9 @@\n-old\n+++ " + mask + "\n\\ No newline at end of file\n" + + patchHeader("two.txt") + + "@@ -0,0 +1 @@\n+" + strings.Repeat("*", 7) + "\n", + want: []hit{{"one.txt", 3}, {"one.txt", 9}, {"two.txt", 1}}, + }, + { + name: "ignore headers context removed lines and short runs", + diff: patchHeader(mask+".txt") + "@@ -1,2 +1,3 @@ " + mask + + "\n " + mask + "\n-" + mask + "\n+short " + strings.Repeat("*", 5) + + "\n+" + mask + "\n", + want: []hit{{mask + ".txt", 3}}, + }, + { + name: "quoted unicode path with space", + diff: "+++ \"b/spaced \\303\\251.txt\"\n@@ -0,0 +1 @@\n+" + mask + "\n", + want: []hit{{"spaced \u00e9.txt", 1}}, + }, + { + name: "keep a path git quoted in a way Go cannot unquote", + diff: "+++ \"b/odd\\q.txt\"\n@@ -0,0 +1 @@\n+" + mask + "\n", + want: []hit{{"odd\\q.txt\"", 1}}, + }, + { + name: "deleted and binary files", + diff: "+++ /dev/null\n@@ -1 +0,0 @@\n-" + mask + "\n" + + "diff --git a/image.bin b/image.bin\nBinary files a/image.bin and b/image.bin differ\n", + }, + { + name: "allow glob and prefix", + diff: maskedAddition("fixtures/sample.txt", mask) + + maskedAddition("fixtures/deep/sample.txt", mask) + + maskedAddition("docs/examples/deep/sample.txt", mask) + + maskedAddition("docs/examples-extra/sample.txt", mask), + allow: []string{"fixtures/*.txt", "docs/examples/"}, + want: []hit{{"fixtures/deep/sample.txt", 1}, {"docs/examples-extra/sample.txt", 1}}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if got := scanDiff(tt.diff, tt.allow); !slices.Equal(got, tt.want) { + t.Errorf("scanDiff() = %v; want %v", got, tt.want) + } + }) + } +} + +func maskedAddition(name, mask string) string { + return patchHeader(name) + "@@ -0,0 +1 @@\n+" + mask + "\n" +} + +func patchHeader(name string) string { + return "diff --git a/" + name + " b/" + name + "\n--- a/" + name + "\n+++ b/" + name + "\n" +} diff --git a/internal/maskscan/git.go b/internal/maskscan/git.go new file mode 100644 index 0000000..537a175 --- /dev/null +++ b/internal/maskscan/git.go @@ -0,0 +1,40 @@ +package maskscan + +import ( + "context" + "fmt" + "os/exec" + "strings" +) + +type gitFunc func(...string) (string, error) + +func gitRunner(ctx context.Context, repo string) gitFunc { + return func(args ...string) (string, error) { + //nolint:gosec // Invoke Git directly with arguments built for specific subcommands. + cmd := exec.CommandContext(ctx, "git", args...) + cmd.Dir = repo + output, err := cmd.Output() + if err != nil { + return "", fmt.Errorf("git %q: %w", args, err) + } + return string(output), nil + } +} + +func addedDiff(git gitFunc, baseRef string) (string, error) { + ref := "refs/remotes/origin/" + baseRef + remote, err := git("show-ref", "--verify", "--hash", ref) + if err != nil { + return "", fmt.Errorf("remote-tracking ref %s unavailable: %w", ref, err) + } + base, err := git("merge-base", strings.TrimSpace(remote), "HEAD") + if err != nil { + return "", fmt.Errorf("merge base for %s unavailable; check local ref: %w", ref, err) + } + return git( + "-c", "core.quotePath=false", "diff", "--no-ext-diff", "--no-textconv", + "--no-color", "--text", "--src-prefix=a/", "--dst-prefix=b/", "--no-renames", "-U0", + strings.TrimSpace(base), "HEAD", "--", + ) +} diff --git a/internal/maskscan/report.go b/internal/maskscan/report.go new file mode 100644 index 0000000..021e9a2 --- /dev/null +++ b/internal/maskscan/report.go @@ -0,0 +1,75 @@ +package maskscan + +import ( + "errors" + "fmt" + "os" + "strconv" + "strings" + "unicode" +) + +const hitMessage = "added line has a run of 6 or more asterisks" + +func renderLog(hits []hit) string { + var log strings.Builder + escape := strings.NewReplacer("%", "%25", "\r", "%0D", "\n", "%0A", ":", "%3A", ",", "%2C") + for _, h := range hits { + fmt.Fprintf(&log, "mask-scan: %s:%d: %s\n", displayPath(h.path), h.line, hitMessage) + fmt.Fprintf( + &log, + "::error file=%s,line=%d::%s\n", + escape.Replace(h.path), + h.line, + hitMessage, + ) + } + if len(hits) == 0 { + log.WriteString("PASS: no added lines with a run of 6 or more asterisks.\n") + } else { + fmt.Fprintf(&log, "FAIL: %d added line(s) with a run of 6 or more asterisks.\n", len(hits)) + } + return log.String() +} + +func displayPath(name string) string { + if strings.IndexFunc(name, func(r rune) bool { return !unicode.IsGraphic(r) }) >= 0 { + name = strconv.QuoteToGraphic(name) + } + // The runner's legacy command parser matches "##[" anywhere in a line. + return strings.ReplaceAll(name, "##[", `\x23\x23[`) +} + +func renderSummary(hits []hit) string { + var summary strings.Builder + fmt.Fprintf( + &summary, + "Mask scan: %d added line(s) with a run of 6 or more asterisks.\n", + len(hits), + ) + for _, h := range hits { + name := strings.ReplaceAll(displayPath(h.path), "`", `\x60`) + fmt.Fprintf(&summary, "\n- `%s`:%d", name, h.line) + } + summary.WriteString( + "\n\nMasked values usually come from writing a tool's redacted view back to a file. " + + "Restore the real text; if the run is real, add the path to `allow` in the workflow.\n", + ) + return summary.String() +} + +func writeSummary(path string, hits []hit) error { + if path == "" { + return nil + } + //nolint:gosec // The runner supplies the step summary path; the tool only appends to it. + summary, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) + if err != nil { + return fmt.Errorf("open GitHub step summary: %w", err) + } + _, err = summary.WriteString(renderSummary(hits)) + if err := errors.Join(err, summary.Close()); err != nil { + return fmt.Errorf("write GitHub step summary: %w", err) + } + return nil +} diff --git a/internal/maskscan/run.go b/internal/maskscan/run.go new file mode 100644 index 0000000..e11518e --- /dev/null +++ b/internal/maskscan/run.go @@ -0,0 +1,45 @@ +package maskscan + +import ( + "context" + "fmt" + "io" + "os" +) + +type Options struct { + BaseRef string + Repo string + ReportOnly bool + Allow []string +} + +func Run(ctx context.Context, opts Options, positional int) int { + if opts.BaseRef == "" || positional != 0 { + fmt.Fprintln(os.Stderr, "mask-scan: expected --base-ref and no positional arguments") + return 2 + } + code, err := run(ctx, opts, os.Stdout, os.Getenv("GITHUB_STEP_SUMMARY")) + if err != nil { + fmt.Fprintln(os.Stderr, "mask-scan:", err) + } + return code +} + +func run(ctx context.Context, opts Options, stdout io.Writer, summary string) (int, error) { + diff, err := addedDiff(gitRunner(ctx, opts.Repo), opts.BaseRef) + if err != nil { + return 2, err + } + hits := scanDiff(diff, opts.Allow) + if _, err := io.WriteString(stdout, renderLog(hits)); err != nil { + return 2, fmt.Errorf("write mask report: %w", err) + } + if err := writeSummary(summary, hits); err != nil { + return 2, err + } + if len(hits) > 0 && !opts.ReportOnly { + return 1, nil + } + return 0, nil +} diff --git a/internal/maskscan/run_test.go b/internal/maskscan/run_test.go new file mode 100644 index 0000000..d326993 --- /dev/null +++ b/internal/maskscan/run_test.go @@ -0,0 +1,171 @@ +package maskscan + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +const ( + fixtureBranch = "main" + summaryName = "summary.md" +) + +func TestRun(t *testing.T) { + t.Parallel() + dir := initFixture(t) + tests := []struct { + name string + base string + allow []string + reportOnly bool + want int + }{ + {name: "reject a hit", base: fixtureBranch, want: 1}, + {name: "report a hit", base: fixtureBranch, reportOnly: true}, + {name: "allow a hit", base: fixtureBranch, allow: []string{"*.txt", "*.dat"}}, + {name: "missing base ref", base: "missing", want: 2}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + var stdout strings.Builder + summaryDir := t.TempDir() + opts := Options{BaseRef: tt.base, Repo: dir, ReportOnly: tt.reportOnly, Allow: tt.allow} + code, err := run(t.Context(), opts, &stdout, filepath.Join(summaryDir, summaryName)) + if code != tt.want || (err != nil) != (tt.want == 2) { + t.Fatalf("run = %d, %v; want code %d", code, err, tt.want) + } + if err != nil || len(tt.allow) > 0 { + return + } + assertHitReport(t, stdout.String(), summaryDir) + }) + } +} + +func TestRunRequiresBaseRef(t *testing.T) { + t.Parallel() + if code := Run(t.Context(), Options{}, 0); code != 2 { + t.Errorf("Run with no base ref = %d; want 2", code) + } +} + +func TestRenderLogEscapesAnnotation(t *testing.T) { + t.Parallel() + log := renderLog([]hit{{path: "a%,:\r\n.txt", line: 12}}) + const want = "::error file=a%25%2C%3A%0D%0A.txt,line=12::" + hitMessage + if !strings.Contains(log, want) || strings.Count(log, "\n") != 3 { + t.Errorf("log should contain the escaped annotation on its own line: %q", log) + } +} + +func TestRenderLogKeepsPathsOffLineStart(t *testing.T) { + t.Parallel() + log := renderLog( + []hit{ + {path: " ::stop-commands::x", line: 1}, + {path: "bidi\u202e.txt", line: 2}, + {path: "##[stop-commands]pause.txt", line: 3}, + }, + ) + if !strings.Contains(log, `mask-scan: \x23\x23[stop-commands]pause.txt:3`) || + !strings.Contains(log, "::error file=##[stop-commands]pause.txt,line=3::") { + t.Errorf("legacy command prefix should be escaped in the plain line only: %q", log) + } + for line := range strings.SplitSeq(strings.TrimSuffix(log, "\n"), "\n") { + if !strings.HasPrefix(line, "mask-scan: ") && !strings.HasPrefix(line, "::error file=") && + !strings.HasPrefix(line, "FAIL: ") { + t.Errorf("log line starts with path text: %q", line) + } + } + if !strings.Contains(log, `mask-scan: "bidi\u202e.txt":2`) { + t.Errorf("non-graphic path should be quoted: %q", log) + } +} + +func assertHitReport(t *testing.T, stdout, summaryDir string) { + t.Helper() + const want = "mask-scan: masked.dat:1: " + hitMessage + "\n" + + "::error file=masked.dat,line=1::" + hitMessage + "\n" + + "mask-scan: with space.txt:2: " + hitMessage + "\n" + + "::error file=with space.txt,line=2::" + hitMessage + "\n" + + "FAIL: 2 added line(s) with a run of 6 or more asterisks.\n" + if stdout != want { + t.Errorf("unexpected stdout:\n%s", stdout) + } + root, err := os.OpenRoot(summaryDir) + if err != nil { + t.Fatal(err) + } + defer func() { + if err := root.Close(); err != nil { + t.Error(err) + } + }() + summary, err := root.ReadFile(summaryName) + if err != nil { + t.Fatal(err) + } + for _, item := range []string{"Mask scan: 2", "`with space.txt`:2", "add the path to `allow`"} { + if !strings.Contains(string(summary), item) { + t.Errorf("summary missing %q:\n%s", item, summary) + } + } +} + +func initFixture(t *testing.T) string { + t.Helper() + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git is unavailable") + } + dir := t.TempDir() + git := gitRunner(t.Context(), dir) + gitOutput(t, git, "init", "-b", fixtureBranch) + gitOutput(t, git, "config", "diff.noprefix", "true") + const name = "with space.txt" + writeFixture(t, dir, name, "original\n") + base := commitFixture(t, git, "") + gitOutput(t, git, "update-ref", "refs/remotes/origin/"+fixtureBranch, base) + writeFixture(t, dir, name, "original\nfixture "+strings.Repeat("*", 6)+"\n") + writeFixture(t, dir, ".gitattributes", "*.dat -diff\n") + writeFixture(t, dir, "masked.dat", strings.Repeat("*", 6)+"\n") + commitFixture(t, git, base) + return dir +} + +func gitOutput(t *testing.T, git gitFunc, args ...string) string { + t.Helper() + out, err := git(args...) + if err != nil { + t.Fatalf("git %q: %v", args, err) + } + return strings.TrimSpace(out) +} + +func commitFixture(t *testing.T, git gitFunc, parent string) string { + t.Helper() + gitOutput(t, git, "add", ".") + tree := gitOutput(t, git, "write-tree") + commit := "tree " + tree + "\n" + if parent != "" { + commit += "parent " + parent + "\n" + } + const stamp = "Fixture 1 +0000" + commit += fmt.Sprintf("author %s\ncommitter %s\n\nTest snapshot\n", stamp, stamp) + dir := t.TempDir() + writeFixture(t, dir, "commit", commit) + hash := gitOutput(t, git, "hash-object", "-w", "-t", "commit", filepath.Join(dir, "commit")) + gitOutput(t, git, "update-ref", "HEAD", hash) + return hash +} + +func writeFixture(t *testing.T, dir, name, contents string) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, name), []byte(contents), 0o600); err != nil { + t.Fatal(err) + } +} diff --git a/mask-scan/action.yml b/mask-scan/action.yml new file mode 100644 index 0000000..8363363 --- /dev/null +++ b/mask-scan/action.yml @@ -0,0 +1,39 @@ +name: Mask Scan +description: Check added lines in a pull request for masked values. +inputs: + base-ref: + description: Target branch name on origin. + default: ${{ github.event.pull_request.base.ref }} + report-only: + description: Report matches without failing the pull request. + default: "false" + allow: + description: Repo-relative glob patterns or directory prefixes, one per line. + default: "" +runs: + using: composite + steps: + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7 + with: + go-version-file: ${{ github.action_path }}/../go.mod + cache: false + - name: Check added lines for masked values + shell: bash + working-directory: ${{ github.action_path }}/.. + env: + BASE_REF: ${{ inputs.base-ref }} + REPORT_ONLY: ${{ inputs.report-only }} + ALLOW: ${{ inputs.allow }} + # Keep the caller's Go settings from changing how the tool builds. + GOFLAGS: -mod=readonly + GOTOOLCHAIN: local + GOWORK: "off" + run: | + args=() + while IFS= read -r pattern; do + if [[ -n "$pattern" ]]; then + args+=(--allow "$pattern") + fi + done <<< "$ALLOW" + go run ./cmd/mask-scan --repo "$GITHUB_WORKSPACE" --base-ref "$BASE_REF" \ + --report-only="$REPORT_ONLY" "${args[@]}"