Repository navigation
feat(mask-scan): fail pull requests that add masked values #16
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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())) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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" | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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", "--", | ||
| ) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.