Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .github/workflows/pr-size.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<base-ref>` and
does not fetch refs. By default, `base-ref` is the PR target branch.
Replace `<sha>` with the commit SHA to pin.

```yaml
- uses: devsy-org/ci/mask-scan@<sha>
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
Expand Down
26 changes: 26 additions & 0 deletions cmd/mask-scan/main.go
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()))
}
91 changes: 91 additions & 0 deletions internal/maskscan/diff.go
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
}
75 changes: 75 additions & 0 deletions internal/maskscan/diff_test.go
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"
}
40 changes: 40 additions & 0 deletions internal/maskscan/git.go
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", "--",
)
}
75 changes: 75 additions & 0 deletions internal/maskscan/report.go
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)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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
}
Loading