From 840da8953b5283ffc916bf0ed753ec1a32b08f03 Mon Sep 17 00:00:00 2001 From: Julian Blacher Date: Sat, 17 Oct 2026 17:22:16 -0300 Subject: [PATCH 1/2] Add SARIF and GitHub annotation output, and a GitHub Action Make findings show up where reviewers already look: on the pull request. Output formats: - --format selects text, json, sarif or github; --json stays as a shorthand for --format json and conflicts with any other format. - sarif writes a SARIF 2.1.0 log for GitHub code scanning. It carries every rule's metadata (PascalCase name, descriptions, default level, a category tag from the ID's hundreds digit) and maps severities to error/warning/note. Relative paths stay relative, which code scanning resolves against the repository root; absolute ones become file://. The exit code is unchanged so CI still fails while the report uploads. - github writes workflow commands that GitHub renders as annotations on the diff. Code scanning needs GitHub Advanced Security on private repositories; annotations work everywhere, so they are the action's default. Values are escaped exactly as @actions/core does. The formatter package takes rule metadata as input instead of importing the rules package, so it stays independent of it. GitHub Action (action.yml, composite): - Installs a release binary for the runner's OS and architecture with gh, verifies it against checksums.txt and puts it on PATH. "source" builds the checkout instead, so the action is testable before any release exists. - Records docker-lint's exit code instead of failing at once, writes the SARIF report, optionally uploads it (codeql-action/upload-sarif@v4), then fails with the original code. A Dockerfile that cannot be parsed yields no report rather than an empty one an upload would reject. - Inputs reach every script through env, never ${{ }} interpolation, so a crafted input cannot inject shell commands. - .github/workflows/action.yml runs the action on Linux, macOS and Windows for a clean, a failing and an unparseable Dockerfile. Verification: - SARIF for all 72 analyzable fixtures, plus stdin, quiet and absolute path cases, validates against the official SARIF 2.1.0 JSON schema. - The action's scripts were run locally through a harness for the same scenarios as the workflow. The release-download path, which CI cannot exercise before a release exists, was run against the GoReleaser snapshot with a stubbed gh: it resolves the tag, verifies and unpacks zip and tar.gz archives, and fails on a tampered checksum or a missing asset. - New files use the current action majors (checkout v7, setup-go v7, codeql-action v4), which run on Node 24. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/action.yml | 90 +++++++++++ CHANGELOG.md | 9 ++ README.md | 70 ++++++-- action.yml | 178 +++++++++++++++++++++ cmd/docker-lint/main.go | 89 ++++++++++- cmd/docker-lint/main_test.go | 60 +++++++ internal/formatter/github.go | 85 ++++++++++ internal/formatter/github_test.go | 66 ++++++++ internal/formatter/sarif.go | 256 ++++++++++++++++++++++++++++++ internal/formatter/sarif_test.go | 161 +++++++++++++++++++ 10 files changed, 1046 insertions(+), 18 deletions(-) create mode 100644 .github/workflows/action.yml create mode 100644 action.yml create mode 100644 internal/formatter/github.go create mode 100644 internal/formatter/github_test.go create mode 100644 internal/formatter/sarif.go create mode 100644 internal/formatter/sarif_test.go diff --git a/.github/workflows/action.yml b/.github/workflows/action.yml new file mode 100644 index 0000000..ccf4174 --- /dev/null +++ b/.github/workflows/action.yml @@ -0,0 +1,90 @@ +name: Action + +# Exercises the GitHub Action in this repository on every runner OS. It builds +# docker-lint from source ("version: source") because a pull request must be +# testable before any release exists. +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + test: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - name: Checkout repository + uses: actions/checkout@v7 + + - name: Set up Go + uses: actions/setup-go@v7 + with: + go-version-file: go.mod + cache: true + + - name: Lint a clean Dockerfile + id: clean + uses: ./ + with: + version: source + dockerfile: testdata/valid/minimal.Dockerfile + sarif-file: clean.sarif + + - name: Check the clean run + shell: bash + env: + EXIT_CODE: ${{ steps.clean.outputs.exit-code }} + SARIF_FILE: ${{ steps.clean.outputs.sarif-file }} + run: | + set -euo pipefail + test "$EXIT_CODE" = 0 + test "$SARIF_FILE" = clean.sarif + grep -q '"version": "2.1.0"' clean.sarif + + - name: Lint a Dockerfile Docker cannot build + id: broken + continue-on-error: true + uses: ./ + with: + version: source + dockerfile: testdata/invalid/no-from.Dockerfile + sarif-file: broken.sarif + + - name: Check the failing run + shell: bash + env: + OUTCOME: ${{ steps.broken.outcome }} + EXIT_CODE: ${{ steps.broken.outputs.exit-code }} + run: | + set -euo pipefail + test "$OUTCOME" = failure + test "$EXIT_CODE" = 1 + # The report is written even though the lint failed. + grep -q '"ruleId": "DKL001"' broken.sarif + + - name: Lint a Dockerfile that does not parse + id: fatal + continue-on-error: true + uses: ./ + with: + version: source + dockerfile: testdata/invalid/unknown-instruction.Dockerfile + sarif-file: fatal.sarif + + - name: Check the fatal run + shell: bash + env: + OUTCOME: ${{ steps.fatal.outcome }} + EXIT_CODE: ${{ steps.fatal.outputs.exit-code }} + SARIF_FILE: ${{ steps.fatal.outputs.sarif-file }} + run: | + set -euo pipefail + test "$OUTCOME" = failure + test "$EXIT_CODE" = 2 + # No empty report is left behind for an upload step to choke on. + test -z "$SARIF_FILE" + test ! -e fatal.sarif diff --git a/CHANGELOG.md b/CHANGELOG.md index 8521ebe..e691c14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Release pipeline: prebuilt binaries for Linux, macOS and Windows (amd64 and arm64) with checksums, built by GoReleaser from a tag into a draft release; CI builds a snapshot release on every pull request +- `--format` flag selecting `text`, `json`, `sarif` or `github`; `--json` stays as + a shorthand for `--format json` +- SARIF 2.1.0 output for GitHub code scanning and other security dashboards, + validated against the official schema +- GitHub annotations output, which shows findings on pull request diffs in any + repository, without code scanning +- GitHub Action (`uses: devblac/docker-lint@`) that installs a + checksum-verified release binary, annotates pull requests and can upload + SARIF to code scanning; tested on Linux, macOS and Windows runners ### Changed - **Breaking:** rule IDs move from `DLxxxx`, which collide with hadolint's IDs for diff --git a/README.md b/README.md index f492e03..ca262c0 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,8 @@ docker-lint [flags] [file] |------|-------|-------------| | `--help` | `-h` | Show help message | | `--version` | `-v` | Show version information | -| `--json` | `-j` | Output findings as JSON | +| `--format ` | `-f` | Output format: `text` (default), `json`, `sarif`, `github` | +| `--json` | `-j` | Shorthand for `--format json` | | `--quiet` | `-q` | Suppress informational messages (show only warnings and errors) | | `--strict` | `-s` | Treat warnings as errors (exit code 1 if any warnings) | | `--ignore ` | | Comma-separated list of rule IDs to ignore | @@ -175,11 +176,11 @@ Human-readable output with file path, line number, severity, rule ID, and messag ``` Dockerfile:1:1: [warning] DKL102: Using 'latest' tag for image 'ubuntu' is not recommended Suggestion: Pin to a specific version like 'ubuntu:' for reproducible builds -Dockerfile:3:1: [warning] DKL202: Found 2 consecutive RUN instructions that could be combined +Dockerfile:3:1: [info] DKL202: Found 2 consecutive RUN instructions that could be combined Suggestion: Combine RUN instructions using '&&' to reduce layers ``` -### JSON (`--json`) +### JSON (`--format json`) Machine-readable JSON output for CI/CD integration: @@ -205,22 +206,71 @@ Machine-readable JSON output for CI/CD integration: } ``` +### SARIF (`--format sarif`) + +[SARIF 2.1.0](https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html), the format GitHub code +scanning and other security dashboards ingest. The report carries every rule's metadata, so findings show +up with their name, description and severity. The exit code is unchanged, so CI still fails on errors while +the report is uploaded. + +### GitHub annotations (`--format github`) + +GitHub Actions workflow commands, which GitHub renders as annotations on the changed lines of a pull +request. They need no code scanning, so they work in private repositories without GitHub Advanced Security: + +``` +::warning file=Dockerfile,line=1,col=1,title=DKL102::Using 'latest' tag for image 'ubuntu' is not recommended +``` + ## CI/CD Integration The repository's CI workflow runs `go test ./... -cover`. Coverage uploads to Codecov are attempted only when a `CODECOV_TOKEN` secret is configured; otherwise the upload step is skipped while tests still gate the build. ### GitHub Actions +The docker-lint action installs a release binary (checksum-verified), lints a Dockerfile and annotates the +pull request diff with the findings: + +```yaml +- uses: actions/checkout@v7 +- uses: devblac/docker-lint@v0.1.0 + with: + dockerfile: Dockerfile +``` + +To also see findings in the repository's **Security** tab, upload SARIF to code scanning. This needs the +`security-events: write` permission, and GitHub Advanced Security on private repositories: + ```yaml -- name: Lint Dockerfile - run: | - docker-lint --strict --json Dockerfile > lint-results.json - if [ $? -ne 0 ]; then - cat lint-results.json - exit 1 - fi +permissions: + contents: read + security-events: write + +steps: + - uses: actions/checkout@v7 + - uses: devblac/docker-lint@v0.1.0 + with: + dockerfile: services/api/Dockerfile + strict: true + ignore: DKL404 + upload-sarif: true ``` +| Input | Default | Description | +|-------|---------|-------------| +| `dockerfile` | `Dockerfile` | Path to the Dockerfile, relative to the repository root | +| `version` | `latest` | docker-lint release to install, e.g. `v0.1.0` | +| `format` | `github` | Log output: `github` (annotations), `text`, `json` or `sarif` | +| `strict` | `false` | Fail on warnings, not only on errors | +| `quiet` | `false` | Hide informational findings | +| `ignore` | | Comma-separated rule IDs to ignore | +| `sarif-file` | | Also write a SARIF report here (`docker-lint.sarif` when uploading) | +| `upload-sarif` | `false` | Upload the SARIF report to GitHub code scanning | + +The action fails the step with docker-lint's exit code and exposes it as the `exit-code` output. A SARIF +report is still written and uploaded when the lint fails; a Dockerfile that cannot be parsed produces no +report rather than an empty one. + ### GitLab CI ```yaml diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..997c6e3 --- /dev/null +++ b/action.yml @@ -0,0 +1,178 @@ +name: docker-lint +description: Lint Dockerfiles for inefficiencies, anti-patterns and security issues, with pull request annotations and SARIF for code scanning +author: devblac +branding: + icon: check-square + color: blue + +inputs: + dockerfile: + description: Path to the Dockerfile to lint, relative to the repository root. + default: Dockerfile + version: + description: >- + docker-lint release to use: "latest" or a tag such as "v0.1.0". "source" + builds the action's own checkout instead (needs Go; used to test the action). + default: latest + format: + description: >- + Output format for the job log: "github" (annotations on the pull request + diff), "text", "json" or "sarif". + default: github + strict: + description: Fail on warnings, not only on errors. + default: "false" + quiet: + description: Hide informational findings. + default: "false" + ignore: + description: Comma-separated rule IDs to ignore, e.g. "DKL103,DKL404". + default: "" + sarif-file: + description: >- + Also write a SARIF report to this path. Defaults to docker-lint.sarif when + upload-sarif is enabled. + default: "" + upload-sarif: + description: >- + Upload the SARIF report to GitHub code scanning. Needs the + "security-events: write" permission, and GitHub Advanced Security on + private repositories. + default: "false" + github-token: + description: Token used to download the docker-lint release. + default: ${{ github.token }} + +outputs: + exit-code: + description: "docker-lint exit code: 0 clean, 1 lint errors (or warnings with strict), 2 fatal error." + value: ${{ steps.lint.outputs.exit-code }} + sarif-file: + description: Path of the SARIF report, when one was written. + value: ${{ steps.lint.outputs.sarif-file }} + +runs: + using: composite + steps: + # Inputs reach the scripts through env, never ${{ }} interpolation, so a + # crafted value cannot inject shell commands. + - name: Install docker-lint + shell: bash + env: + VERSION: ${{ inputs.version }} + GH_TOKEN: ${{ inputs.github-token }} + ACTION_PATH: ${{ github.action_path }} + run: | + set -euo pipefail + + case "$RUNNER_OS" in + Linux) os=linux ;; + macOS) os=darwin ;; + Windows) os=windows ;; + *) echo "::error::docker-lint: unsupported runner OS $RUNNER_OS"; exit 1 ;; + esac + case "$RUNNER_ARCH" in + X64) arch=amd64 ;; + ARM64) arch=arm64 ;; + *) echo "::error::docker-lint: unsupported runner architecture $RUNNER_ARCH"; exit 1 ;; + esac + exe="" + if [ "$os" = windows ]; then exe=".exe"; fi + + bin_dir="$RUNNER_TEMP/docker-lint-bin" + mkdir -p "$bin_dir" + + if [ "$VERSION" = source ]; then + (cd "$ACTION_PATH" && go build -o "$bin_dir/docker-lint$exe" ./cmd/docker-lint) + else + repo=devblac/docker-lint + tag="$VERSION" + if [ "$tag" = latest ]; then + tag="$(gh release view --repo "$repo" --json tagName --jq .tagName)" + fi + ext=tar.gz + if [ "$os" = windows ]; then ext=zip; fi + archive="docker-lint_${tag#v}_${os}_${arch}.${ext}" + + download="$RUNNER_TEMP/docker-lint-download" + rm -rf "$download" + mkdir -p "$download" + gh release download "$tag" --repo "$repo" --dir "$download" \ + --pattern "$archive" --pattern checksums.txt + + cd "$download" + grep " ${archive}\$" checksums.txt > expected.sha256 + if command -v sha256sum >/dev/null; then + sha256sum --check expected.sha256 + else + shasum -a 256 --check expected.sha256 + fi + + if [ "$ext" = zip ]; then + if command -v unzip >/dev/null; then unzip -q -o "$archive"; else 7z x -y "$archive" >/dev/null; fi + else + tar -xzf "$archive" + fi + mv "docker-lint$exe" "$bin_dir/" + fi + + echo "$bin_dir" >> "$GITHUB_PATH" + "$bin_dir/docker-lint$exe" --version + + - name: Lint Dockerfile + id: lint + shell: bash + env: + DOCKERFILE: ${{ inputs.dockerfile }} + FORMAT: ${{ inputs.format }} + STRICT: ${{ inputs.strict }} + QUIET: ${{ inputs.quiet }} + IGNORE: ${{ inputs.ignore }} + SARIF_FILE: ${{ inputs.sarif-file }} + UPLOAD_SARIF: ${{ inputs.upload-sarif }} + run: | + set -uo pipefail + + args=() + if [ "$STRICT" = true ]; then args+=(--strict); fi + if [ "$QUIET" = true ]; then args+=(--quiet); fi + if [ -n "$IGNORE" ]; then args+=(--ignore "$IGNORE"); fi + + # Record the exit code instead of failing here, so the SARIF report is + # still written and uploaded when the lint finds errors. + docker-lint "${args[@]}" --format "$FORMAT" "$DOCKERFILE" + code=$? + echo "exit-code=$code" >> "$GITHUB_OUTPUT" + + if [ "$UPLOAD_SARIF" = true ] && [ -z "$SARIF_FILE" ]; then + SARIF_FILE=docker-lint.sarif + fi + if [ -n "$SARIF_FILE" ]; then + # A fatal error (exit 2) writes nothing to stdout; an empty report + # would only make the upload fail with a confusing message. + docker-lint "${args[@]}" --format sarif "$DOCKERFILE" > "$SARIF_FILE" 2>/dev/null + if [ -s "$SARIF_FILE" ]; then + echo "sarif-file=$SARIF_FILE" >> "$GITHUB_OUTPUT" + else + rm -f "$SARIF_FILE" + echo "::warning::docker-lint: no SARIF report was written because the Dockerfile could not be analyzed" + fi + fi + + - name: Upload SARIF to code scanning + if: inputs.upload-sarif == 'true' && steps.lint.outputs.sarif-file != '' + uses: github/codeql-action/upload-sarif@v4 + with: + sarif_file: ${{ steps.lint.outputs.sarif-file }} + category: docker-lint + + - name: Report result + shell: bash + env: + EXIT_CODE: ${{ steps.lint.outputs.exit-code }} + run: | + case "$EXIT_CODE" in + 0) ;; + 1) echo "::error::docker-lint found errors (or warnings with strict enabled)"; exit 1 ;; + *) echo "::error::docker-lint could not analyze the Dockerfile (exit code $EXIT_CODE)"; exit "$EXIT_CODE" ;; + esac diff --git a/cmd/docker-lint/main.go b/cmd/docker-lint/main.go index 1f291e1..55bf64f 100644 --- a/cmd/docker-lint/main.go +++ b/cmd/docker-lint/main.go @@ -44,6 +44,7 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { versionFlg bool rulesFlag bool ignoreCSV string + formatFlag string ) fs := flag.NewFlagSet("docker-lint", flag.ContinueOnError) @@ -60,6 +61,8 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { fs.BoolVar(&versionFlg, "v", false, "") fs.BoolVar(&rulesFlag, "rules", false, "") fs.StringVar(&ignoreCSV, "ignore", "", "") + fs.StringVar(&formatFlag, "format", "", "") + fs.StringVar(&formatFlag, "f", "", "") if err := fs.Parse(args); err != nil { if errors.Is(err, flag.ErrHelp) { @@ -81,6 +84,12 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { return ExitSuccess } + outputFormat, err := resolveFormat(formatFlag, jsonOutput) + if err != nil { + fmt.Fprintf(stderr, "Error: %v\n", err) + return ExitFatal + } + positional := fs.Args() if len(positional) > 1 { fmt.Fprintln(stderr, "Error: too many arguments: only one Dockerfile path is supported") @@ -116,13 +125,7 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { anlzr := analyzer.NewWithDefaults(analyzer.Config{IgnoreRules: ignoreRules}) findings := anlzr.Analyze(dockerfile) - var formatErr error - if jsonOutput { - formatErr = formatter.NewJSONFormatter(filename, quiet).Format(findings, stdout) - } else { - formatErr = formatter.NewTextFormatter(filename, quiet).Format(findings, stdout) - } - if formatErr != nil { + if formatErr := newFormatter(outputFormat, filename, quiet).Format(findings, stdout); formatErr != nil { fmt.Fprintf(stderr, "Error: failed to format output: %v\n", formatErr) return ExitFatal } @@ -130,6 +133,75 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { return determineExitCode(findings, strict) } +// Output formats accepted by --format. +const ( + formatText = "text" + formatJSON = "json" + formatSARIF = "sarif" + formatGitHub = "github" +) + +// projectURL is reported as the tool's home page in SARIF output. +const projectURL = "https://github.com/devblac/docker-lint" + +// resolveFormat combines --format and its --json shorthand into one format. +func resolveFormat(format string, jsonOutput bool) (string, error) { + if jsonOutput { + if format != "" && format != formatJSON { + return "", fmt.Errorf("--json conflicts with --format %s", format) + } + return formatJSON, nil + } + + switch format { + case "": + return formatText, nil + case formatText, formatJSON, formatSARIF, formatGitHub: + return format, nil + default: + return "", fmt.Errorf("unknown output format %q (want text, json, sarif or github)", format) + } +} + +// findingFormatter writes findings in one output format. +type findingFormatter interface { + Format(findings []ast.Finding, w io.Writer) error +} + +// newFormatter returns the formatter for a resolved output format. +func newFormatter(format, filename string, quiet bool) findingFormatter { + switch format { + case formatJSON: + return formatter.NewJSONFormatter(filename, quiet) + case formatSARIF: + return formatter.NewSARIFFormatter(filename, quiet, toolInfo()) + case formatGitHub: + return formatter.NewGitHubFormatter(filename, quiet) + default: + return formatter.NewTextFormatter(filename, quiet) + } +} + +// toolInfo describes docker-lint and every built-in rule for SARIF output. +func toolInfo() formatter.ToolInfo { + all := rules.DefaultRegistry.All() + infos := make([]formatter.RuleInfo, 0, len(all)) + for _, rule := range all { + infos = append(infos, formatter.RuleInfo{ + ID: rule.ID(), + Name: rule.Name(), + Description: rule.Description(), + Severity: rule.Severity(), + }) + } + return formatter.ToolInfo{ + Name: "docker-lint", + Version: version, + InformationURI: projectURL, + Rules: infos, + } +} + // determineExitCode returns ExitLintErrors if any errors exist, or if warnings // exist in strict mode; otherwise ExitSuccess. func determineExitCode(findings []ast.Finding, strict bool) int { @@ -189,7 +261,8 @@ Reads from stdin when no file is given. Flags: -h, --help Show this help message -v, --version Show version information - -j, --json Output findings as JSON + -f, --format Output format: text (default), json, sarif, github + -j, --json Shorthand for --format json -q, --quiet Suppress informational messages (show only warnings and errors) -s, --strict Treat warnings as errors --ignore Comma-separated list of rule IDs to ignore diff --git a/cmd/docker-lint/main_test.go b/cmd/docker-lint/main_test.go index 729fd56..cea48fc 100644 --- a/cmd/docker-lint/main_test.go +++ b/cmd/docker-lint/main_test.go @@ -806,3 +806,63 @@ func TestNoFromIsLintError(t *testing.T) { t.Errorf("expected DKL001 error, got: %q", stdout.String()) } } + +// TestFormatFlag verifies each output format end to end through the CLI. +func TestFormatFlag(t *testing.T) { + path := createTempDockerfile(t, "FROM alpine\nUSER nobody\n") + + tests := []struct { + args []string + want string + }{ + {[]string{"--format", "text", path}, "[warning] DKL101"}, + {[]string{"--format", "json", path}, `"rule_id": "DKL101"`}, + {[]string{"-f", "sarif", path}, `"version": "2.1.0"`}, + {[]string{"--format", "github", path}, "::warning file="}, + {[]string{"--json", "--format", "json", path}, `"rule_id": "DKL101"`}, + } + + for _, tt := range tests { + t.Run(strings.Join(tt.args[:len(tt.args)-1], " "), func(t *testing.T) { + var stdout, stderr bytes.Buffer + if code := run(tt.args, nil, &stdout, &stderr); code != ExitSuccess { + t.Fatalf("exit code %d, stderr: %s", code, stderr.String()) + } + if !strings.Contains(stdout.String(), tt.want) { + t.Errorf("output missing %q:\n%s", tt.want, stdout.String()) + } + }) + } +} + +// TestFormatFlagErrors verifies invalid format combinations are fatal. +func TestFormatFlagErrors(t *testing.T) { + path := createTempDockerfile(t, "FROM alpine:3.20\n") + + for _, args := range [][]string{ + {"--format", "xml", path}, + {"--json", "--format", "sarif", path}, + } { + var stdout, stderr bytes.Buffer + if code := run(args, nil, &stdout, &stderr); code != ExitFatal { + t.Errorf("%v: exit code %d, want %d", args, code, ExitFatal) + } + if !strings.Contains(stderr.String(), "Error:") { + t.Errorf("%v: expected an error on stderr, got %q", args, stderr.String()) + } + } +} + +// TestSARIFKeepsExitCode verifies SARIF output does not change the exit code, +// so CI still fails on errors while the report is uploaded. +func TestSARIFKeepsExitCode(t *testing.T) { + path := createTempDockerfile(t, "RUN echo hi\n") + var stdout, stderr bytes.Buffer + + if code := run([]string{"--format", "sarif", path}, nil, &stdout, &stderr); code != ExitLintErrors { + t.Errorf("exit code %d, want %d", code, ExitLintErrors) + } + if !strings.Contains(stdout.String(), `"level": "error"`) { + t.Errorf("expected an error-level result:\n%s", stdout.String()) + } +} diff --git a/internal/formatter/github.go b/internal/formatter/github.go new file mode 100644 index 0000000..5da8d31 --- /dev/null +++ b/internal/formatter/github.go @@ -0,0 +1,85 @@ +package formatter + +import ( + "fmt" + "io" + "path/filepath" + "strings" + + "github.com/devblac/docker-lint/internal/ast" +) + +// GitHubFormatter writes findings as GitHub Actions workflow commands, which +// GitHub renders as annotations on the lines of a pull request's diff. +// +// Unlike SARIF upload, annotations need no code scanning (GitHub Advanced +// Security on private repositories), so they work in any repository. +type GitHubFormatter struct { + // Filename is the path of the analyzed file, relative to the repository root. + Filename string + // Quiet suppresses informational findings. + Quiet bool +} + +// NewGitHubFormatter creates a new GitHubFormatter. +func NewGitHubFormatter(filename string, quiet bool) *GitHubFormatter { + return &GitHubFormatter{Filename: filename, Quiet: quiet} +} + +// Format writes one workflow command per finding: +// ::warning file=Dockerfile,line=3,col=1,title=DKL101::message +func (f *GitHubFormatter) Format(findings []ast.Finding, w io.Writer) error { + file := strings.TrimPrefix(filepath.ToSlash(f.Filename), "./") + + for _, finding := range findings { + if f.Quiet && finding.Severity == ast.SeverityInfo { + continue + } + + message := finding.Message + if finding.Suggestion != "" { + message += "\nSuggestion: " + finding.Suggestion + } + + // Input read from stdin has no file to annotate; the command still + // shows up in the workflow run summary. + properties := "title=" + escapeProperty(finding.RuleID) + if file != "stdin" { + properties = fmt.Sprintf("file=%s,line=%d,col=%d,%s", + escapeProperty(file), max(finding.Line, 1), max(finding.Column, 1), properties) + } + + if _, err := fmt.Fprintf(w, "::%s %s::%s\n", + annotationLevel(finding.Severity), properties, escapeData(message)); err != nil { + return err + } + } + + return nil +} + +// annotationLevel maps a severity to a workflow command. +func annotationLevel(severity ast.Severity) string { + switch severity { + case ast.SeverityError: + return "error" + case ast.SeverityWarning: + return "warning" + default: + return "notice" + } +} + +// escapeData escapes a workflow command's message, as @actions/core does. +func escapeData(s string) string { + s = strings.ReplaceAll(s, "%", "%25") + s = strings.ReplaceAll(s, "\r", "%0D") + return strings.ReplaceAll(s, "\n", "%0A") +} + +// escapeProperty escapes a workflow command's property value, as @actions/core does. +func escapeProperty(s string) string { + s = escapeData(s) + s = strings.ReplaceAll(s, ":", "%3A") + return strings.ReplaceAll(s, ",", "%2C") +} diff --git a/internal/formatter/github_test.go b/internal/formatter/github_test.go new file mode 100644 index 0000000..abd570d --- /dev/null +++ b/internal/formatter/github_test.go @@ -0,0 +1,66 @@ +package formatter + +import ( + "bytes" + "strings" + "testing" + + "github.com/devblac/docker-lint/internal/ast" +) + +func TestGitHubFormatter(t *testing.T) { + findings := []ast.Finding{ + {RuleID: "DKL101", Severity: ast.SeverityWarning, Line: 3, Column: 1, Message: "Image 'alpine' has no tag", Suggestion: "Pin a version"}, + {RuleID: "DKL001", Severity: ast.SeverityError, Line: 1, Column: 1, Message: "RUN appears before FROM"}, + {RuleID: "DKL404", Severity: ast.SeverityInfo, Line: 9, Column: 1, Message: "No HEALTHCHECK"}, + } + + var buf bytes.Buffer + if err := NewGitHubFormatter("./services/api/Dockerfile", false).Format(findings, &buf); err != nil { + t.Fatalf("Format() error = %v", err) + } + + want := []string{ + "::warning file=services/api/Dockerfile,line=3,col=1,title=DKL101::Image 'alpine' has no tag%0ASuggestion: Pin a version", + "::error file=services/api/Dockerfile,line=1,col=1,title=DKL001::RUN appears before FROM", + "::notice file=services/api/Dockerfile,line=9,col=1,title=DKL404::No HEALTHCHECK", + } + got := strings.Split(strings.TrimSpace(buf.String()), "\n") + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("got:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) + } +} + +func TestGitHubFormatterEscaping(t *testing.T) { + findings := []ast.Finding{ + {RuleID: "DKL301", Severity: ast.SeverityWarning, Line: 2, Column: 1, Message: "100% sure: a,b\nnext"}, + } + + var buf bytes.Buffer + if err := NewGitHubFormatter("dir,with:odd/Dockerfile", false).Format(findings, &buf); err != nil { + t.Fatalf("Format() error = %v", err) + } + + // Properties escape ':' and ','; the message only escapes '%' and newlines. + want := "::warning file=dir%2Cwith%3Aodd/Dockerfile,line=2,col=1,title=DKL301::100%25 sure: a,b%0Anext\n" + if buf.String() != want { + t.Errorf("got %q\nwant %q", buf.String(), want) + } +} + +func TestGitHubFormatterStdinAndQuiet(t *testing.T) { + findings := []ast.Finding{ + {RuleID: "DKL404", Severity: ast.SeverityInfo, Line: 1, Column: 1, Message: "No HEALTHCHECK"}, + {RuleID: "DKL101", Severity: ast.SeverityWarning, Line: 1, Column: 1, Message: "No tag"}, + } + + var buf bytes.Buffer + if err := NewGitHubFormatter("stdin", true).Format(findings, &buf); err != nil { + t.Fatalf("Format() error = %v", err) + } + + // stdin has no file to annotate, and quiet mode drops the info finding. + if want := "::warning title=DKL101::No tag\n"; buf.String() != want { + t.Errorf("got %q, want %q", buf.String(), want) + } +} diff --git a/internal/formatter/sarif.go b/internal/formatter/sarif.go new file mode 100644 index 0000000..864238c --- /dev/null +++ b/internal/formatter/sarif.go @@ -0,0 +1,256 @@ +package formatter + +import ( + "encoding/json" + "io" + "net/url" + "path/filepath" + "strings" + + "github.com/devblac/docker-lint/internal/ast" +) + +// SARIF 2.1.0 is the version GitHub code scanning and most other consumers read. +const ( + sarifVersion = "2.1.0" + sarifSchema = "https://json.schemastore.org/sarif-2.1.0.json" +) + +// RuleInfo describes a lint rule for output formats that publish rule metadata. +type RuleInfo struct { + ID string + Name string + Description string + Severity ast.Severity +} + +// ToolInfo describes docker-lint itself in SARIF output. +type ToolInfo struct { + Name string + Version string + InformationURI string + Rules []RuleInfo +} + +// SARIFFormatter formats findings as a SARIF 2.1.0 log, the format GitHub code +// scanning ingests to show findings as alerts on pull requests. +type SARIFFormatter struct { + // Filename is the path of the analyzed file, reported as the artifact URI. + Filename string + // Quiet suppresses informational findings. + Quiet bool + // Tool carries the tool version and the metadata of every rule. + Tool ToolInfo +} + +// NewSARIFFormatter creates a new SARIFFormatter. +func NewSARIFFormatter(filename string, quiet bool, tool ToolInfo) *SARIFFormatter { + return &SARIFFormatter{Filename: filename, Quiet: quiet, Tool: tool} +} + +type sarifLog struct { + Schema string `json:"$schema"` + Version string `json:"version"` + Runs []sarifRun `json:"runs"` +} + +type sarifRun struct { + Tool sarifTool `json:"tool"` + Results []sarifResult `json:"results"` +} + +type sarifTool struct { + Driver sarifDriver `json:"driver"` +} + +type sarifDriver struct { + Name string `json:"name"` + Version string `json:"version,omitempty"` + InformationURI string `json:"informationUri,omitempty"` + Rules []sarifRule `json:"rules"` +} + +type sarifRule struct { + ID string `json:"id"` + Name string `json:"name"` + ShortDescription sarifMessage `json:"shortDescription"` + FullDescription sarifMessage `json:"fullDescription"` + HelpURI string `json:"helpUri,omitempty"` + DefaultConfiguration sarifConfiguration `json:"defaultConfiguration"` + Properties sarifRuleProperties `json:"properties"` +} + +type sarifRuleProperties struct { + Tags []string `json:"tags"` +} + +type sarifConfiguration struct { + Level string `json:"level"` +} + +type sarifMessage struct { + Text string `json:"text"` +} + +type sarifResult struct { + RuleID string `json:"ruleId"` + RuleIndex *int `json:"ruleIndex,omitempty"` + Level string `json:"level"` + Message sarifMessage `json:"message"` + Locations []sarifLocation `json:"locations"` +} + +type sarifLocation struct { + PhysicalLocation sarifPhysicalLocation `json:"physicalLocation"` +} + +type sarifPhysicalLocation struct { + ArtifactLocation sarifArtifactLocation `json:"artifactLocation"` + Region sarifRegion `json:"region"` +} + +type sarifArtifactLocation struct { + URI string `json:"uri"` +} + +type sarifRegion struct { + StartLine int `json:"startLine"` + StartColumn int `json:"startColumn,omitempty"` +} + +// Format writes the findings to w as a SARIF log with a single run. +func (f *SARIFFormatter) Format(findings []ast.Finding, w io.Writer) error { + rules := make([]sarifRule, 0, len(f.Tool.Rules)) + ruleIndex := make(map[string]int, len(f.Tool.Rules)) + for i, rule := range f.Tool.Rules { + ruleIndex[rule.ID] = i + rules = append(rules, sarifRule{ + ID: rule.ID, + Name: sarifRuleName(rule.Name), + ShortDescription: sarifMessage{Text: rule.Name}, + FullDescription: sarifMessage{Text: rule.Description}, + HelpURI: ruleHelpURI(f.Tool.InformationURI), + DefaultConfiguration: sarifConfiguration{Level: sarifLevel(rule.Severity)}, + Properties: sarifRuleProperties{Tags: []string{ruleCategory(rule.ID)}}, + }) + } + + uri := artifactURI(f.Filename) + results := make([]sarifResult, 0, len(findings)) + for _, finding := range findings { + if f.Quiet && finding.Severity == ast.SeverityInfo { + continue + } + + text := finding.Message + if finding.Suggestion != "" { + text += "\nSuggestion: " + finding.Suggestion + } + + result := sarifResult{ + RuleID: finding.RuleID, + Level: sarifLevel(finding.Severity), + Message: sarifMessage{Text: text}, + Locations: []sarifLocation{{ + PhysicalLocation: sarifPhysicalLocation{ + ArtifactLocation: sarifArtifactLocation{URI: uri}, + Region: sarifRegion{StartLine: max(finding.Line, 1), StartColumn: finding.Column}, + }, + }}, + } + if idx, ok := ruleIndex[finding.RuleID]; ok { + result.RuleIndex = &idx + } + results = append(results, result) + } + + log := sarifLog{ + Schema: sarifSchema, + Version: sarifVersion, + Runs: []sarifRun{{ + Tool: sarifTool{Driver: sarifDriver{ + Name: f.Tool.Name, + Version: f.Tool.Version, + InformationURI: f.Tool.InformationURI, + Rules: rules, + }}, + Results: results, + }}, + } + + encoder := json.NewEncoder(w) + encoder.SetIndent("", " ") + return encoder.Encode(log) +} + +// sarifLevel maps a severity to a SARIF result level. +func sarifLevel(severity ast.Severity) string { + switch severity { + case ast.SeverityError: + return "error" + case ast.SeverityWarning: + return "warning" + default: + return "note" + } +} + +// sarifRuleName turns a human rule name into the PascalCase identifier SARIF +// recommends for reportingDescriptor.name: "Using 'latest' tag" -> "UsingLatestTag". +func sarifRuleName(name string) string { + var b strings.Builder + for _, word := range strings.FieldsFunc(name, func(r rune) bool { + return !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9') + }) { + b.WriteString(strings.ToUpper(word[:1]) + word[1:]) + } + return b.String() +} + +// ruleCategory derives a rule's category tag from the hundreds digit of its ID. +func ruleCategory(id string) string { + if len(id) == 6 && strings.HasPrefix(id, "DKL") { + switch id[3] { + case '0': + return "correctness" + case '1': + return "base-image" + case '2': + return "efficiency" + case '3': + return "security" + case '4': + return "best-practice" + } + } + return "docker" +} + +// ruleHelpURI points at the rules reference in the project README. +func ruleHelpURI(informationURI string) string { + if informationURI == "" { + return "" + } + return strings.TrimSuffix(informationURI, "/") + "#rules" +} + +// artifactURI converts a file path to a SARIF artifact URI. Relative paths stay +// relative, which code scanning resolves against the repository root; absolute +// paths become file:// URIs. +func artifactURI(path string) string { + slashed := filepath.ToSlash(path) + + if filepath.IsAbs(path) || strings.HasPrefix(slashed, "/") { + if !strings.HasPrefix(slashed, "/") { + slashed = "/" + slashed // Windows drive paths: C:/x -> /C:/x + } + return (&url.URL{Scheme: "file", Path: slashed}).String() + } + + slashed = strings.TrimPrefix(slashed, "./") + segments := strings.Split(slashed, "/") + for i, segment := range segments { + segments[i] = url.PathEscape(segment) + } + return strings.Join(segments, "/") +} diff --git a/internal/formatter/sarif_test.go b/internal/formatter/sarif_test.go new file mode 100644 index 0000000..55e11f8 --- /dev/null +++ b/internal/formatter/sarif_test.go @@ -0,0 +1,161 @@ +package formatter + +import ( + "bytes" + "encoding/json" + "strings" + "testing" + + "github.com/devblac/docker-lint/internal/ast" +) + +func testToolInfo() ToolInfo { + return ToolInfo{ + Name: "docker-lint", + Version: "1.2.3", + InformationURI: "https://github.com/devblac/docker-lint", + Rules: []RuleInfo{ + {ID: "DKL101", Name: "Missing explicit image tag", Description: "Always tag images", Severity: ast.SeverityWarning}, + {ID: "DKL303", Name: "Final image runs as root", Description: "Set a non-root USER", Severity: ast.SeverityWarning}, + {ID: "DKL404", Name: "Missing HEALTHCHECK", Description: "Add a HEALTHCHECK", Severity: ast.SeverityInfo}, + {ID: "DKL001", Name: "Instruction before FROM", Description: "Start with FROM", Severity: ast.SeverityError}, + }, + } +} + +// decodeSARIF formats findings and decodes the result into a generic map. +func decodeSARIF(t *testing.T, f *SARIFFormatter, findings []ast.Finding) map[string]interface{} { + t.Helper() + var buf bytes.Buffer + if err := f.Format(findings, &buf); err != nil { + t.Fatalf("Format() error = %v", err) + } + var log map[string]interface{} + if err := json.Unmarshal(buf.Bytes(), &log); err != nil { + t.Fatalf("output is not valid JSON: %v\n%s", err, buf.String()) + } + return log +} + +func TestSARIFFormatterStructure(t *testing.T) { + findings := []ast.Finding{ + {RuleID: "DKL101", Severity: ast.SeverityWarning, Line: 3, Column: 1, Message: "Image 'alpine' has no tag", Suggestion: "Pin a version"}, + {RuleID: "DKL001", Severity: ast.SeverityError, Line: 1, Column: 1, Message: "RUN appears before FROM"}, + {RuleID: "DKL404", Severity: ast.SeverityInfo, Line: 9, Column: 1, Message: "No HEALTHCHECK"}, + } + + log := decodeSARIF(t, NewSARIFFormatter("services/api/Dockerfile", false, testToolInfo()), findings) + + if log["version"] != "2.1.0" { + t.Errorf("version = %v, want 2.1.0", log["version"]) + } + if log["$schema"] != sarifSchema { + t.Errorf("$schema = %v, want %s", log["$schema"], sarifSchema) + } + + runs := log["runs"].([]interface{}) + if len(runs) != 1 { + t.Fatalf("len(runs) = %d, want 1", len(runs)) + } + run := runs[0].(map[string]interface{}) + + driver := run["tool"].(map[string]interface{})["driver"].(map[string]interface{}) + if driver["name"] != "docker-lint" || driver["version"] != "1.2.3" { + t.Errorf("driver = %v", driver) + } + rules := driver["rules"].([]interface{}) + if len(rules) != 4 { + t.Fatalf("len(rules) = %d, want 4", len(rules)) + } + first := rules[0].(map[string]interface{}) + if first["id"] != "DKL101" || first["name"] != "MissingExplicitImageTag" { + t.Errorf("rules[0] = %v", first) + } + if first["helpUri"] != "https://github.com/devblac/docker-lint#rules" { + t.Errorf("helpUri = %v", first["helpUri"]) + } + + results := run["results"].([]interface{}) + if len(results) != 3 { + t.Fatalf("len(results) = %d, want 3", len(results)) + } + + wantLevels := []string{"warning", "error", "note"} + wantIndexes := []float64{0, 3, 2} + for i, r := range results { + result := r.(map[string]interface{}) + if result["level"] != wantLevels[i] { + t.Errorf("results[%d].level = %v, want %s", i, result["level"], wantLevels[i]) + } + if result["ruleIndex"] != wantIndexes[i] { + t.Errorf("results[%d].ruleIndex = %v, want %v", i, result["ruleIndex"], wantIndexes[i]) + } + } + + location := results[0].(map[string]interface{})["locations"].([]interface{})[0].(map[string]interface{})["physicalLocation"].(map[string]interface{}) + if uri := location["artifactLocation"].(map[string]interface{})["uri"]; uri != "services/api/Dockerfile" { + t.Errorf("uri = %v, want services/api/Dockerfile", uri) + } + if line := location["region"].(map[string]interface{})["startLine"]; line != float64(3) { + t.Errorf("startLine = %v, want 3", line) + } + + message := results[0].(map[string]interface{})["message"].(map[string]interface{})["text"].(string) + if !strings.Contains(message, "Image 'alpine' has no tag") || !strings.Contains(message, "Suggestion: Pin a version") { + t.Errorf("message = %q", message) + } +} + +func TestSARIFFormatterNoFindings(t *testing.T) { + var buf bytes.Buffer + if err := NewSARIFFormatter("Dockerfile", false, testToolInfo()).Format(nil, &buf); err != nil { + t.Fatalf("Format() error = %v", err) + } + // Consumers expect an empty array, not null, when nothing was found. + if !strings.Contains(buf.String(), `"results": []`) { + t.Errorf("expected an empty results array:\n%s", buf.String()) + } +} + +func TestSARIFFormatterQuiet(t *testing.T) { + findings := []ast.Finding{ + {RuleID: "DKL404", Severity: ast.SeverityInfo, Line: 1, Column: 1, Message: "No HEALTHCHECK"}, + {RuleID: "DKL101", Severity: ast.SeverityWarning, Line: 1, Column: 1, Message: "No tag"}, + } + log := decodeSARIF(t, NewSARIFFormatter("Dockerfile", true, testToolInfo()), findings) + results := log["runs"].([]interface{})[0].(map[string]interface{})["results"].([]interface{}) + if len(results) != 1 { + t.Fatalf("quiet mode: len(results) = %d, want 1", len(results)) + } +} + +func TestArtifactURI(t *testing.T) { + tests := []struct { + path string + want string + }{ + {"Dockerfile", "Dockerfile"}, + {"./Dockerfile", "Dockerfile"}, + {"services/api/Dockerfile", "services/api/Dockerfile"}, + {"my app/Dockerfile.prod", "my%20app/Dockerfile.prod"}, + {"/home/ci/repo/Dockerfile", "file:///home/ci/repo/Dockerfile"}, + } + for _, tt := range tests { + if got := artifactURI(tt.path); got != tt.want { + t.Errorf("artifactURI(%q) = %q, want %q", tt.path, got, tt.want) + } + } +} + +func TestSARIFRuleName(t *testing.T) { + tests := map[string]string{ + "Using 'latest' tag": "UsingLatestTag", + "ADD where COPY would suffice": "ADDWhereCOPYWouldSuffice", + "Wildcard in COPY/ADD source": "WildcardInCOPYADDSource", + } + for in, want := range tests { + if got := sarifRuleName(in); got != want { + t.Errorf("sarifRuleName(%q) = %q, want %q", in, got, want) + } + } +} From 4c47916524af5e68f2f402e610d48dacdd008391 Mon Sep 17 00:00:00 2001 From: Julian Blacher Date: Sun, 18 Oct 2026 02:20:37 -0300 Subject: [PATCH 2/2] Fix the action losing its exit code when docker-lint fails GitHub runs composite bash steps with -e, which "set -uo pipefail" does not undo, so a lint failure ended the step before the exit code and the SARIF report were recorded. Capture the exit code with "|| code=$?" instead, and expand the optional arguments safely for bash 3.2 on macOS. Co-Authored-By: Claude Opus 5.5 --- action.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/action.yml b/action.yml index 997c6e3..710dca0 100644 --- a/action.yml +++ b/action.yml @@ -131,6 +131,7 @@ runs: SARIF_FILE: ${{ inputs.sarif-file }} UPLOAD_SARIF: ${{ inputs.upload-sarif }} run: | + # The runner starts bash with -e; failures are handled explicitly below. set -uo pipefail args=() @@ -140,8 +141,8 @@ runs: # Record the exit code instead of failing here, so the SARIF report is # still written and uploaded when the lint finds errors. - docker-lint "${args[@]}" --format "$FORMAT" "$DOCKERFILE" - code=$? + code=0 + docker-lint ${args[@]+"${args[@]}"} --format "$FORMAT" "$DOCKERFILE" || code=$? echo "exit-code=$code" >> "$GITHUB_OUTPUT" if [ "$UPLOAD_SARIF" = true ] && [ -z "$SARIF_FILE" ]; then @@ -150,7 +151,7 @@ runs: if [ -n "$SARIF_FILE" ]; then # A fatal error (exit 2) writes nothing to stdout; an empty report # would only make the upload fail with a confusing message. - docker-lint "${args[@]}" --format sarif "$DOCKERFILE" > "$SARIF_FILE" 2>/dev/null + docker-lint ${args[@]+"${args[@]}"} --format sarif "$DOCKERFILE" > "$SARIF_FILE" 2>/dev/null || true if [ -s "$SARIF_FILE" ]; then echo "sarif-file=$SARIF_FILE" >> "$GITHUB_OUTPUT" else