diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 371d0d7..6652ea3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,6 +30,9 @@ jobs: exit 1 fi + - name: Vet + run: go vet ./... + - name: Run tests with coverage run: go test ./... -coverprofile=coverage.out -covermode=atomic diff --git a/CHANGELOG.md b/CHANGELOG.md index a5432f1..0cf9824 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -## [0.1.0] - 2026-10-24 +## [0.1.1] - 2026-10-24 -First release. The Changed, Removed and Fixed sections describe differences from -the unreleased code on `main` before this version, for anyone who built it from -source. +First published release. The Changed, Removed and Fixed sections describe +differences from the code on `main` before it, for anyone who built it from +source. Version 0.1.0 was tagged but never published. ### Added - Dockerfile parser with multi-stage build support @@ -53,7 +53,13 @@ source. - The GitHub Action lints several paths or patterns (one per line) and takes a `config` input - `--version` falls back to the version Go records in the binary, so builds from - `go install github.com/devblac/docker-lint/cmd/docker-lint@v0.1.0` report it + `go install github.com/devblac/docker-lint/cmd/docker-lint@v0.1.1` report it +- Flags may follow the paths (`docker-lint Dockerfile --json`), `--` ends the + flags, and `-` reads stdin +- The GitHub Action installs the docker-lint release matching the tag it is used + at (`@v0.1.1` installs v0.1.1), so pinning the action pins the linter +- Tests that every rule reports a real-world example of its problem, alongside + the corpus that guards against false positives ### Changed - **Breaking:** rule IDs move from `DLxxxx`, which collide with hadolint's IDs for @@ -79,6 +85,12 @@ source. - DKL404 (missing HEALTHCHECK) and DKL202 (consecutive RUN) are now `info`: on the corpus they fired on 51 and 39 of 52 files, and Kubernetes ignores HEALTHCHECK - DKL103 judges only the base of the final image +- DKL203 reports the whole build context copied before installing dependencies + (`COPY . .` then `npm ci`, `pip install -r` or `go mod download`), and + recognises many more installers (npm ci, pnpm, bun, yarn, uv, poetry, pipenv, + bundle, composer, cargo fetch, dotnet restore, mvn dependency:go-offline) +- Directory searches skip Dockerfile templates, backups and docs + (`Dockerfile.template`, `.j2`, `.bak`, `.md`); name such a file to lint it ### Removed - Hand-written Dockerfile lexer (`internal/parser/lexer.go`), superseded by BuildKit @@ -106,6 +118,18 @@ source. - DKL203 flagged the recommended pattern of copying dependency manifests first (`COPY go.mod go.sum ./`, `COPY package*.json ./`) because it inspected the destination instead of the sources +- DKL304 flagged `ADD --checksum=...`, which Docker recommends for remote files, + and `ADD` of a Git repository; DKL305 said COPY could replace `ADD git@...` +- DKL201 ignored `PIP_NO_CACHE_DIR` set with ENV or for the command +- `exclude` patterns are relative to the configuration file, so they also apply + when docker-lint runs from a subdirectory or is given absolute paths + +## [0.1.0] - 2026-10-24 + +Tagged but never published. A review of the draft release found the problems +fixed in 0.1.1, and the tag could not be moved because the Go module proxy had +already cached it. Use 0.1.1 instead. -[Unreleased]: https://github.com/devblac/docker-lint/compare/v0.1.0...HEAD -[0.1.0]: https://github.com/devblac/docker-lint/releases/tag/v0.1.0 +[Unreleased]: https://github.com/devblac/docker-lint/compare/v0.1.1...HEAD +[0.1.1]: https://github.com/devblac/docker-lint/releases/tag/v0.1.1 +[0.1.0]: https://github.com/devblac/docker-lint/tree/v0.1.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d7b70e6..3c30fa9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -101,7 +101,8 @@ release, so nothing is public until a maintainer publishes it. 1. Make sure `main` is green and `goreleaser release --snapshot --clean` builds locally (CI also runs it on every pull request). 2. In `CHANGELOG.md`, rename `## [Unreleased]` to `## [X.Y.Z] - YYYY-MM-DD`, add a new - empty `## [Unreleased]` above it, and merge that change to `main`. + empty `## [Unreleased]` above it, update the comparison links at the bottom, and + merge that change to `main`. 3. Tag the merge commit and push the tag: ```bash @@ -112,7 +113,10 @@ release, so nothing is public until a maintainer publishes it. 4. The Release workflow runs the tests, takes the release notes from the version's `CHANGELOG.md` section (it fails if there is none) and uploads the binaries and `checksums.txt` to a draft release. -5. Review the draft on the Releases page and publish it. +5. Review the draft on the Releases page: check its notes, download an archive and + verify it against `checksums.txt`, then publish it. Avoid `go install ...@vX.Y.Z` + before publishing: the Go module proxy caches a tag's contents permanently, so the + tag can no longer be moved if the release needs fixing. ## Questions? diff --git a/README.md b/README.md index fef60ab..86a3bc6 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,9 @@ A minimal, production-grade CLI tool for statically analyzing Dockerfiles to det - **Static Analysis**: Purely static analysis - never executes Docker builds - **Real Dockerfile Syntax**: Parsing is delegated to BuildKit, the parser `docker build` itself uses, so heredocs (`RUN < **Renamed rule IDs.** Before v0.1.0, rules used `DLxxxx` IDs, which collide with +> **Renamed rule IDs.** Before v0.1.1, the first release, rules used `DLxxxx` IDs, which collide with > [hadolint](https://github.com/hadolint/hadolint)'s IDs for different rules. The old IDs are not accepted; > passing one to `--ignore` prints its replacement. See the [CHANGELOG](CHANGELOG.md) for the full mapping. @@ -193,7 +198,7 @@ docker-lint includes 18 built-in rules. Rule IDs use the `DKL` prefix and are gr |----|----------|------|-------------| | DKL201 | Warning | Package manager cache not cleaned | Clean package manager cache in the same RUN instruction to reduce image size. `apt-get dist-clean` and `--mount=type=cache` count as clean | | DKL202 | Info | Consecutive RUN instructions | Combine consecutive RUN instructions to reduce the number of layers | -| DKL203 | Warning | Suboptimal layer ordering | Place instructions that change less frequently earlier to optimize layer caching | +| DKL203 | Warning | Suboptimal layer ordering | Place instructions that change less frequently earlier to optimize layer caching, e.g. copy only the dependency manifests before `npm ci`, `pip install -r` or `go mod download`, not the whole build context | | DKL204 | Warning | Package update without install | Combine package update with install in the same RUN instruction to avoid cache issues | ### Security Rules @@ -203,7 +208,7 @@ docker-lint includes 18 built-in rules. Rule IDs use the `DKL` prefix and are gr | DKL301 | Warning | Potential secret in ENV | Avoid storing secrets in ENV instructions as they persist in the image layers | | DKL302 | Warning | Potential secret in ARG | Avoid storing secrets in ARG instructions as they are visible in image history | | DKL303 | Warning | Final image runs as root | The final image should not run as root; set a non-root USER in the final stage. Build stages are not checked, and a USER inherited from an earlier stage counts | -| DKL304 | Warning | ADD with URL | Using ADD with URLs is discouraged; use curl or wget in RUN for better control | +| DKL304 | Warning | ADD with URL | An unverified download: pin it with `ADD --checksum=sha256:...` or fetch it in RUN. Git repositories (`ADD https://.../repo.git#ref`) are not reported | | DKL305 | Warning | ADD where COPY would suffice | Use COPY instead of ADD when not extracting archives or fetching URLs | ### Best Practice Rules @@ -283,7 +288,7 @@ the pull request diff with the findings: ```yaml - uses: actions/checkout@v7 -- uses: devblac/docker-lint@v0.1.0 +- uses: devblac/docker-lint@v0.1.1 with: dockerfile: Dockerfile ``` @@ -298,7 +303,7 @@ permissions: steps: - uses: actions/checkout@v7 - - uses: devblac/docker-lint@v0.1.0 + - uses: devblac/docker-lint@v0.1.1 with: dockerfile: | Dockerfile @@ -312,13 +317,22 @@ steps: |-------|---------|-------------| | `dockerfile` | `Dockerfile` | Files, directories or glob patterns to lint, one per line | | `config` | | Configuration file (default: `.docker-lint.yaml` at the repository root) | -| `version` | `latest` | docker-lint release to install, e.g. `v0.1.0` | +| `version` | action's tag | docker-lint release to install: by default the one matching the action's tag (`@v0.1.1` installs v0.1.1), or the latest release when the action is used from a branch. Also `latest` or a tag such as `v0.1.1` | | `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 | +| `github-token` | `github.token` | Token used to download the docker-lint release | + +| Output | Description | +|--------|-------------| +| `exit-code` | docker-lint's exit code: `0` clean, `1` lint errors (or warnings with `strict`), `2` fatal error | +| `sarif-file` | Path of the SARIF report, when one was written | + +Pinning the action pins the linter: `@v0.1.1` installs docker-lint v0.1.1. When you pin the action to a commit +SHA, also set `version` to the matching tag; otherwise the latest release is installed. 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, and covers every Dockerfile that could be parsed; diff --git a/action.yml b/action.yml index 6733e09..655da53 100644 --- a/action.yml +++ b/action.yml @@ -1,5 +1,5 @@ name: docker-lint -description: Lint Dockerfiles for inefficiencies, anti-patterns and security issues, with pull request annotations and SARIF for code scanning +description: Lint Dockerfiles for anti-patterns, inefficiencies and security issues; annotates pull requests and outputs SARIF author: devblac branding: icon: check-square @@ -19,9 +19,12 @@ inputs: default: "" 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 + docker-lint release to use. By default, the release matching the tag the + action is used at (uses: devblac/docker-lint@v1.2.3 installs v1.2.3), or + the latest release when the action is used from a branch or commit. Also + accepts "latest", a tag such as "v0.1.1", or "source" to build the + action's own checkout (needs Go; used to test the action). + default: "" format: description: >- Output format for the job log: "github" (annotations on the pull request @@ -70,6 +73,7 @@ runs: VERSION: ${{ inputs.version }} GH_TOKEN: ${{ inputs.github-token }} ACTION_PATH: ${{ github.action_path }} + ACTION_REF: ${{ github.action_ref }} run: | set -euo pipefail @@ -90,6 +94,20 @@ runs: bin_dir="$RUNNER_TEMP/docker-lint-bin" mkdir -p "$bin_dir" + # Pinning the action pins the linter: by default, install the release + # whose tag the action is used at. The runner checks the action out + # under .../_actions///, which also gives the ref when + # github.action_ref is empty, as it is in some nested composite actions. + if [ -z "$VERSION" ]; then + ref="${ACTION_REF:-$(basename "$ACTION_PATH")}" + if printf '%s' "$ref" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$'; then + VERSION="$ref" + else + VERSION=latest + fi + fi + echo "docker-lint: installing $VERSION" + if [ "$VERSION" = source ]; then (cd "$ACTION_PATH" && go build -o "$bin_dir/docker-lint$exe" ./cmd/docker-lint) else diff --git a/cmd/docker-lint/main.go b/cmd/docker-lint/main.go index 34e9341..7310aab 100644 --- a/cmd/docker-lint/main.go +++ b/cmd/docker-lint/main.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "os" + "path/filepath" "runtime/debug" "strings" @@ -72,7 +73,8 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { fs.StringVar(&configPath, "config", "", "") fs.StringVar(&configPath, "c", "", "") - if err := fs.Parse(args); err != nil { + paths, err := parseArgs(fs, args) + if err != nil { if errors.Is(err, flag.ErrHelp) { printUsage(stdout) return ExitSuccess @@ -134,7 +136,13 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { SeverityOverrides: cfg.SeverityOverrides(), }) - reports, single, fatal := lintInputs(fs.Args(), cfg.Exclude, stdin, anlzr, stderr) + // Exclude patterns are relative to the configuration file's directory. + exclude := files.Exclusions{Patterns: cfg.Exclude} + if cfgPath != "" { + exclude.Base = filepath.Dir(cfgPath) + } + + reports, single, fatal := lintInputs(paths, exclude, stdin, anlzr, stderr) out := output{format: outputFormat, quiet: quiet, tool: toolInfo(cfg)} if formatErr := out.write(reports, single, stdout); formatErr != nil { @@ -152,6 +160,28 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { return determineExitCode(all, strict) } +// parseArgs parses flags wherever they appear, so "docker-lint Dockerfile +// --json" works like "docker-lint --json Dockerfile", and returns the +// positional arguments in order. Everything after "--" is positional. +func parseArgs(fs *flag.FlagSet, args []string) ([]string, error) { + var positional []string + for { + if err := fs.Parse(args); err != nil { + return nil, err + } + rest := fs.Args() + if len(rest) == 0 { + return positional, nil + } + // flag stops at "--" (consuming it) or at the first non-flag argument. + if consumed := len(args) - len(rest); consumed > 0 && args[consumed-1] == "--" { + return append(positional, rest...), nil + } + positional = append(positional, rest[0]) + args = rest[1:] + } +} + // loadConfig returns the configuration to use: the file named by --config, // none with --no-config, or else the nearest .docker-lint.yaml. It also // returns the path the configuration came from, "" when there is none. @@ -177,7 +207,17 @@ func loadConfig(path string, disabled bool) (*config.Config, string, error) { // paths expand to. A file that cannot be read or parsed is reported on stderr // and skipped, and fatal is set; the other files are still linted. single is // true when the input is stdin or one file named directly. -func lintInputs(paths, exclude []string, stdin io.Reader, anlzr *analyzer.Analyzer, stderr io.Writer) (reports []formatter.Report, single, fatal bool) { +func lintInputs(paths []string, exclude files.Exclusions, stdin io.Reader, anlzr *analyzer.Analyzer, stderr io.Writer) (reports []formatter.Report, single, fatal bool) { + if len(paths) == 1 && paths[0] == "-" { + paths = nil + } + for _, p := range paths { + if p == "-" { + fmt.Fprintln(stderr, "Error: - (stdin) cannot be combined with other paths") + return nil, false, true + } + } + if len(paths) == 0 { if stdin == nil { stdin = os.Stdin @@ -381,7 +421,7 @@ Usage: Each path is a Dockerfile, a directory searched recursively for Dockerfiles, or a glob pattern such as "services/**/Dockerfile". Reads from stdin when no -path is given. +path (or -) is given. Flags may come before or after the paths. Flags: -h, --help Show this help message diff --git a/cmd/docker-lint/multi_test.go b/cmd/docker-lint/multi_test.go index 6a82f50..6268856 100644 --- a/cmd/docker-lint/multi_test.go +++ b/cmd/docker-lint/multi_test.go @@ -286,3 +286,60 @@ func TestConfigUnknownRuleWarns(t *testing.T) { } } } + +// TestFlagsAfterPaths verifies flags are accepted after the paths, the way +// most command-line tools allow. +func TestFlagsAfterPaths(t *testing.T) { + path := createTempDockerfile(t, warningDockerfile) + + tests := []struct { + args []string + code int + want string + }{ + {[]string{path, "--json"}, ExitSuccess, `"rule_id": "DKL101"`}, + {[]string{path, "-f", "github", "--strict"}, ExitLintErrors, "::warning file="}, + {[]string{"-q", path, "--ignore", "DKL101"}, ExitSuccess, ""}, + } + for _, tt := range tests { + var stdout, stderr bytes.Buffer + code := run(tt.args, nil, &stdout, &stderr) + if code != tt.code { + t.Errorf("%v: exit code %d, want %d; stderr: %s", tt.args, code, tt.code, stderr.String()) + } + if !strings.Contains(stdout.String(), tt.want) { + t.Errorf("%v: output missing %q:\n%s", tt.args, tt.want, stdout.String()) + } + if tt.want == "" && strings.Contains(stdout.String(), "DKL101") { + t.Errorf("%v: --ignore after the path was not applied:\n%s", tt.args, stdout.String()) + } + } +} + +// TestDoubleDashEndsFlags verifies a path that looks like a flag can follow "--". +func TestDoubleDashEndsFlags(t *testing.T) { + dir := writeTree(t, map[string]string{"--json": cleanDockerfile}) + chdir(t, dir) + + var stdout, stderr bytes.Buffer + if code := run([]string{"-q", "--", "--json"}, nil, &stdout, &stderr); code != ExitSuccess { + t.Errorf("exit code %d; stderr: %s", code, stderr.String()) + } + if strings.Contains(stdout.String(), `"file"`) { + t.Errorf("--json after -- should be a path, not a flag:\n%s", stdout.String()) + } +} + +func TestDashReadsStdin(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{"-", "--json"}, strings.NewReader(warningDockerfile), &stdout, &stderr) + if code != ExitSuccess || !strings.Contains(stdout.String(), `"file": "stdin"`) { + t.Errorf("exit code %d, output:\n%s\nstderr: %s", code, stdout.String(), stderr.String()) + } + + stdout.Reset() + path := createTempDockerfile(t, cleanDockerfile) + if code := run([]string{"-", path}, strings.NewReader(cleanDockerfile), &stdout, &stderr); code != ExitFatal { + t.Errorf("- with another path: exit code %d, want %d", code, ExitFatal) + } +} diff --git a/internal/analyzer/detection_test.go b/internal/analyzer/detection_test.go new file mode 100644 index 0000000..642ca1f --- /dev/null +++ b/internal/analyzer/detection_test.go @@ -0,0 +1,116 @@ +package analyzer + +import ( + "strings" + "testing" + + "github.com/devblac/docker-lint/internal/parser" + "github.com/devblac/docker-lint/internal/rules" +) + +// detectionCases are Dockerfiles each rule must report, written the way the +// problem shows up in real projects. The corpus test guards against false +// positives; these guard against a rule that quietly stops firing. +var detectionCases = map[string][]string{ + rules.RuleNoFrom: { + "RUN echo hi\nFROM alpine:3.20\n", + "# no FROM at all\nRUN echo hi\n", + }, + rules.RuleMissingTag: { + "FROM node\n", + "FROM registry.example.com:5000/team/app\n", + }, + rules.RuleLatestTag: { + "FROM node:latest\n", + }, + rules.RuleLargeBaseImage: { + "FROM ubuntu:24.04\n", + "FROM golang:1.23 AS build\nFROM build\n", + }, + rules.RuleCacheNotCleaned: { + "FROM debian:12-slim\nRUN apt-get update && apt-get install -y curl\n", + "FROM alpine:3.20\nRUN apk add curl\n", + "FROM python:3.12-slim\nRUN pip install flask\n", + }, + rules.RuleConsecutiveRun: { + "FROM alpine:3.20\nRUN echo a\nRUN echo b\n", + }, + rules.RuleSuboptimalOrdering: { + "FROM node:20-slim\nWORKDIR /app\nCOPY . .\nRUN npm ci\nRUN npm run build\n", + "FROM python:3.12-slim\nWORKDIR /app\nCOPY . .\nRUN pip install --no-cache-dir -r requirements.txt\n", + "FROM golang:1.23\nWORKDIR /src\nCOPY . .\nRUN go mod download\n", + }, + rules.RuleUpdateWithoutInstall: { + "FROM debian:12-slim\nRUN apt-get update\nRUN apt-get install -y curl && rm -rf /var/lib/apt/lists/*\n", + }, + rules.RuleSecretInEnv: { + "FROM alpine:3.20\nENV DB_PASSWORD=hunter2\n", + "FROM alpine:3.20\nENV AWS_SECRET_ACCESS_KEY=abc GITHUB_TOKEN=ghp_x\n", + }, + rules.RuleSecretInArg: { + "FROM alpine:3.20\nARG NPM_TOKEN\n", + "FROM alpine:3.20\nARG API_KEY=abc\n", + }, + rules.RuleNoUser: { + "FROM alpine:3.20\nRUN echo hi\n", + "FROM alpine:3.20\nUSER app\nUSER root\n", + "FROM alpine:3.20\nUSER 0:0\n", + }, + rules.RuleAddWithURL: { + "FROM alpine:3.20\nADD https://example.com/install.sh /install.sh\n", + }, + rules.RuleAddOverCopy: { + "FROM alpine:3.20\nADD app.py /app/app.py\n", + }, + rules.RuleMultipleCMD: { + "FROM alpine:3.20\nCMD [\"a\"]\nCMD [\"b\"]\n", + }, + rules.RuleMultipleEntrypoint: { + "FROM alpine:3.20\nENTRYPOINT [\"a\"]\nENTRYPOINT [\"b\"]\n", + }, + rules.RuleRelativeWorkdir: { + "FROM alpine:3.20\nWORKDIR app\n", + }, + rules.RuleMissingHealthcheck: { + "FROM alpine:3.20\nCMD [\"app\"]\n", + }, + rules.RuleWildcardCopy: { + "FROM alpine:3.20\nCOPY *.py /app/\n", + }, +} + +func TestEveryRuleDetectsItsCase(t *testing.T) { + analyzer := NewWithDefaults(Config{}) + + for _, rule := range rules.DefaultRegistry.All() { + id := rule.ID() + cases, ok := detectionCases[id] + if !ok || len(cases) == 0 { + t.Errorf("%s has no detection case; add one to detectionCases", id) + continue + } + for _, src := range cases { + df, err := parser.ParseString(src) + if err != nil { + t.Errorf("%s: case does not parse: %v\n%s", id, err, src) + continue + } + found := false + for _, f := range analyzer.Analyze(df) { + if f.RuleID == id { + found = true + break + } + } + if !found { + t.Errorf("%s did not report:\n%s", id, strings.TrimSpace(src)) + } + } + } + + for id := range detectionCases { + if rules.DefaultRegistry.Get(id) == nil { + t.Errorf("detectionCases lists %s, which is not a registered rule", id) + } + } +} diff --git a/internal/ast/ast.go b/internal/ast/ast.go index 8a308ee..461c05b 100644 --- a/internal/ast/ast.go +++ b/internal/ast/ast.go @@ -130,11 +130,12 @@ func (c *CopyInstruction) Type() InstructionType { return InstrCOPY } // AddInstruction represents an ADD instruction. type AddInstruction struct { - LineNum int - RawText string - Sources []string - Dest string - Chown string // --chown flag + LineNum int + RawText string + Sources []string + Dest string + Chown string // --chown flag + Checksum string // --checksum flag, which verifies a remote source } func (a *AddInstruction) Line() int { return a.LineNum } diff --git a/internal/files/files.go b/internal/files/files.go index f75663b..270bd00 100644 --- a/internal/files/files.go +++ b/internal/files/files.go @@ -27,7 +27,7 @@ import ( // // Paths found by expansion use forward slashes. The result has no duplicates // and keeps the order of the arguments. -func Expand(args []string, exclude []string) ([]string, error) { +func Expand(args []string, exclude Exclusions) ([]string, error) { var result []string seen := make(map[string]bool) add := func(p string) { @@ -76,14 +76,28 @@ func Expand(args []string, exclude []string) ([]string, error) { return result, nil } +// notDockerfileExtensions mark files named after a Dockerfile that are not one +// Docker can build: per-Dockerfile ignore files, templates rendered into a +// Dockerfile, editor and merge backups, and documentation. +var notDockerfileExtensions = []string{ + ".dockerignore", + ".template", ".tmpl", ".tpl", ".j2", ".jinja", ".jinja2", ".erb", ".mustache", ".in", + ".bak", ".orig", ".old", ".swp", ".rej", + ".md", ".txt", ".sample", ".example", +} + // IsDockerfile reports whether a file name follows a Dockerfile naming // convention: Dockerfile, Containerfile, Dockerfile. or -// .Dockerfile, in any letter case. Dockerfile-specific ignore files -// (Dockerfile.dockerignore) are not Dockerfiles. +// .Dockerfile, in any letter case. Names ending in a template, backup +// or documentation extension (Dockerfile.template, Dockerfile.bak) are not +// Dockerfiles; directory searches skip them, so one unrendered template does +// not fail the whole run. Name such a file explicitly to lint it anyway. func IsDockerfile(name string) bool { lower := strings.ToLower(name) - if strings.HasSuffix(lower, ".dockerignore") { - return false + for _, ext := range notDockerfileExtensions { + if strings.HasSuffix(lower, ext) { + return false + } } for _, base := range []string{"dockerfile", "containerfile"} { if lower == base || strings.HasPrefix(lower, base+".") || strings.HasSuffix(lower, "."+base) { @@ -93,7 +107,7 @@ func IsDockerfile(name string) bool { return false } -func expandDir(dir string, exclude []string) ([]string, error) { +func expandDir(dir string, exclude Exclusions) ([]string, error) { var found []string err := filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { if err != nil { @@ -106,7 +120,7 @@ func expandDir(dir string, exclude []string) ([]string, error) { } return nil } - if IsDockerfile(d.Name()) && !Excluded(rel, exclude) { + if IsDockerfile(d.Name()) && !exclude.excludes(rel) { found = append(found, rel) } return nil @@ -115,7 +129,7 @@ func expandDir(dir string, exclude []string) ([]string, error) { return found, err } -func expandPattern(pattern string, exclude []string) ([]string, error) { +func expandPattern(pattern string, exclude Exclusions) ([]string, error) { pattern = filepath.ToSlash(pattern) if _, err := path.Match(strings.ReplaceAll(pattern, "**", "*"), ""); err != nil { return nil, fmt.Errorf("%s: %w", pattern, err) @@ -137,7 +151,7 @@ func expandPattern(pattern string, exclude []string) ([]string, error) { } return nil } - if Match(pattern, rel) && !Excluded(rel, exclude) { + if Match(pattern, rel) && !exclude.excludes(rel) { found = append(found, rel) } return nil @@ -174,6 +188,40 @@ func skipDir(name string) bool { return name == ".git" || name == "node_modules" } +// Exclusions are exclude patterns and the directory they are written relative +// to: the directory of the configuration file that declares them. Matching +// against paths made relative to Base keeps a pattern such as "examples/**" +// working when docker-lint runs from a subdirectory or is given absolute paths. +type Exclusions struct { + Patterns []string + // Base is the directory patterns are relative to; "" means the current one. + Base string +} + +func (e Exclusions) excludes(p string) bool { + if len(e.Patterns) == 0 { + return false + } + return Excluded(relativeTo(e.Base, p), e.Patterns) +} + +// relativeTo returns p relative to base with forward slashes, or p unchanged +// when it lies outside base. +func relativeTo(base, p string) string { + if base == "" { + base = "." + } + absBase, errBase := filepath.Abs(base) + absPath, errPath := filepath.Abs(p) + if errBase == nil && errPath == nil { + rel, err := filepath.Rel(absBase, absPath) + if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return filepath.ToSlash(rel) + } + } + return filepath.ToSlash(p) +} + // Excluded reports whether a slash-separated path matches any exclude pattern. // A pattern without a slash matches a file or directory name anywhere in the // path, as in .gitignore; other patterns match the path from its start, and a diff --git a/internal/files/files_test.go b/internal/files/files_test.go index 2f305a5..b3b5c5c 100644 --- a/internal/files/files_test.go +++ b/internal/files/files_test.go @@ -18,6 +18,16 @@ func TestIsDockerfile(t *testing.T) { "api.dockerfile": true, "Containerfile.dev": true, "Dockerfile.dockerignore": false, + "Dockerfile.template": false, + "Dockerfile.tmpl": false, + "Dockerfile.j2": false, + "api.Dockerfile.in": false, + "Dockerfile.bak": false, + "Dockerfile.orig": false, + "Dockerfile.md": false, + "Dockerfile.main": true, // ends in "in", not ".in" + "Dockerfile.gold": true, // ends in "old", not ".old" + "Dockerfile.alpine": true, ".dockerignore": false, "Dockerfiles": false, "MyDockerfile": false, @@ -111,6 +121,7 @@ func TestExpand(t *testing.T) { "services/api/Dockerfile", "services/api/Dockerfile.dockerignore", "services/web/web.Dockerfile", + "services/web/Dockerfile.template", "services/web/node_modules/pkg/Dockerfile", ".devcontainer/Dockerfile", ".git/Dockerfile", @@ -148,7 +159,13 @@ func TestExpand(t *testing.T) { { name: "pattern below a fixed directory", args: []string{"services/*/*"}, - want: []string{"services/api/Dockerfile", "services/api/Dockerfile.dockerignore", "services/web/web.Dockerfile"}, + // An explicit pattern selects files by name only. + want: []string{"services/api/Dockerfile", "services/api/Dockerfile.dockerignore", "services/web/Dockerfile.template", "services/web/web.Dockerfile"}, + }, + { + name: "explicit template is linted", + args: []string{"services/web/Dockerfile.template"}, + want: []string{"services/web/Dockerfile.template"}, }, { name: "explicit file is linted whatever its name and excludes", @@ -164,7 +181,7 @@ func TestExpand(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := Expand(tt.args, tt.exclude) + got, err := Expand(tt.args, Exclusions{Patterns: tt.exclude}) if err != nil { t.Fatalf("Expand() error = %v", err) } @@ -189,9 +206,55 @@ func TestExpandErrors(t *testing.T) { {[]string{"Dockerfile", "[bad"}, "syntax error"}, } for _, tt := range tests { - _, err := Expand(tt.args, nil) + _, err := Expand(tt.args, Exclusions{}) if err == nil || !strings.Contains(err.Error(), tt.want) { t.Errorf("Expand(%q) error = %v, want it to mention %q", tt.args, err, tt.want) } } } + +// TestExclusionsAreRelativeToBase verifies exclude patterns apply to paths +// relative to the configuration's directory, however the paths were given. +func TestExclusionsAreRelativeToBase(t *testing.T) { + makeTree(t, + "vendor/repo/examples/demo/Dockerfile", + "vendor/repo/services/api/Dockerfile", + ) + root, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + repo := filepath.Join(root, "vendor", "repo") + exclude := Exclusions{Patterns: []string{"examples/**", "node_modules"}, Base: repo} + want := []string{"services/api/Dockerfile"} + + // From the repository root, from a subdirectory and with an absolute path. + for _, tt := range []struct { + dir, arg string + }{ + {repo, "."}, + {filepath.Join(repo, "services"), ".."}, + {root, repo}, + } { + if err := os.Chdir(tt.dir); err != nil { + t.Fatal(err) + } + got, err := Expand([]string{tt.arg}, exclude) + if err != nil { + t.Fatalf("Expand(%q) from %s: %v", tt.arg, tt.dir, err) + } + if len(got) != 1 || !strings.HasSuffix(got[0], want[0]) { + t.Errorf("Expand(%q) from %s = %q, want only .../%s", tt.arg, tt.dir, got, want[0]) + } + } + + // A directory above the base named like a pattern ("vendor") excludes + // nothing: only the part of the path below the base is matched. + if err := os.Chdir(repo); err != nil { + t.Fatal(err) + } + got, err := Expand([]string{"."}, Exclusions{Patterns: []string{"vendor"}, Base: repo}) + if err != nil || len(got) != 2 { + t.Errorf("Expand() = %q, %v; want both Dockerfiles", got, err) + } +} diff --git a/internal/parser/convert.go b/internal/parser/convert.go index 0cabeb1..c5c8b91 100644 --- a/internal/parser/convert.go +++ b/internal/parser/convert.go @@ -66,11 +66,12 @@ func convertCommand(cmd interface{}, line int, raw string) ([]ast.Instruction, e case *instructions.AddCommand: return one(&ast.AddInstruction{ - LineNum: line, - RawText: raw, - Sources: c.SourcePaths, - Dest: c.DestPath, - Chown: c.Chown, + LineNum: line, + RawText: raw, + Sources: c.SourcePaths, + Dest: c.DestPath, + Chown: c.Chown, + Checksum: c.Checksum, }), nil case *instructions.EnvCommand: diff --git a/internal/parser/modern_syntax_test.go b/internal/parser/modern_syntax_test.go index 746e72b..2264a9e 100644 --- a/internal/parser/modern_syntax_test.go +++ b/internal/parser/modern_syntax_test.go @@ -350,3 +350,59 @@ func TestParseInlineIgnoreAcrossBlankLines(t *testing.T) { t.Errorf("InlineIgnores[5] = %v, want [DKL102]", rules) } } + +func TestParseAddChecksum(t *testing.T) { + df, err := ParseString("FROM alpine:3.20\nADD --checksum=sha256:24454f830cdb571e2c4ad15481119c43b3cafd48dd869a9b2945d1036d1dc68d https://example.com/a.tar.gz /a\n") + if err != nil { + t.Fatalf("ParseString() error = %v", err) + } + add, ok := df.Instructions[1].(*ast.AddInstruction) + if !ok { + t.Fatalf("instruction 1 = %T, want *ast.AddInstruction", df.Instructions[1]) + } + if want := "sha256:24454f830cdb571e2c4ad15481119c43b3cafd48dd869a9b2945d1036d1dc68d"; add.Checksum != want { + t.Errorf("Checksum = %q, want %q", add.Checksum, want) + } +} + +// TestParseCRLFLineEndings verifies a Dockerfile with Windows line endings, +// as Git for Windows checks files out by default, parses like its LF version: +// continuations join, inline ignores attach, and no stray \r is left behind. +func TestParseCRLFLineEndings(t *testing.T) { + src := "FROM alpine:3.20\r\n" + + "# docker-lint ignore: DKL201\r\n" + + "RUN apt-get update && \\\r\n" + + " apt-get install -y curl\r\n" + + "ENV A=1 \\\r\n" + + " B=2\r\n" + + "RUN < 0 { - // Look ahead to see if there are more COPY/ADD after this RUN - hasMoreCopies := false - for j := i + 1; j < len(stage.Instructions); j++ { - switch stage.Instructions[j].(type) { - case *ast.CopyInstruction, *ast.AddInstruction: - hasMoreCopies = true - break - } + if len(copies) == 0 || !isPackageInstallCommand(v.Command) { + continue + } + moreCopiesLater := hasCopyAfter(stage.Instructions[i+1:]) + + for _, cp := range copies { + if flagged[cp.instr.Line()] { + continue + } + // Copying only dependency manifests before the install step is + // the recommended caching pattern. + if isDependencyManifestCopy(cp.sources) { + continue + } + // The RUN uses what this COPY brought in (a script, a config + // file), so the COPY has to stay before it. + if runReferencesCopy(v.Command, cp.sources) { + continue } - // If there are copies before package install and more copies after, - // the early copies might be suboptimal - if hasMoreCopies { - for _, cp := range copies { - // Copying only dependency manifests before the install - // step is the recommended caching pattern. - if isDependencyManifestCopy(cp.sources) { - continue - } - // The RUN uses what this COPY brought in (a script, a - // config file), so the COPY has to stay before it. - if runReferencesCopy(v.Command, cp.sources) { - continue - } - findings = append(findings, ast.Finding{ - RuleID: r.ID(), - Severity: r.Severity(), - Line: cp.instr.Line(), - Column: 1, - Message: "COPY/ADD before package installation may reduce cache efficiency", - Suggestion: "Move COPY/ADD after RUN instructions that don't depend on copied files", - }) - } + switch { + case copiesWholeContext(cp.sources): + // Any source change invalidates the install layer: the + // classic "COPY . ." before "npm ci". + flagged[cp.instr.Line()] = true + findings = append(findings, ast.Finding{ + RuleID: r.ID(), + Severity: r.Severity(), + Line: cp.instr.Line(), + Column: 1, + Message: "COPY/ADD of the whole build context before installing dependencies reruns the install on every source change", + Suggestion: "Copy only the dependency manifests first (e.g. package.json and its lock file), install, then copy the rest", + }) + case moreCopiesLater: + // Files copied early while others are copied after the + // install would be better copied after it too. + flagged[cp.instr.Line()] = true + findings = append(findings, ast.Finding{ + RuleID: r.ID(), + Severity: r.Severity(), + Line: cp.instr.Line(), + Column: 1, + Message: "COPY/ADD before package installation may reduce cache efficiency", + Suggestion: "Move COPY/ADD after RUN instructions that don't depend on copied files", + }) } } } @@ -314,6 +341,29 @@ func (r *SuboptimalOrderingRule) checkStage(stage ast.Stage) []ast.Finding { return findings } +// hasCopyAfter reports whether any of the instructions is a COPY or ADD. +func hasCopyAfter(instructions []ast.Instruction) bool { + for _, instr := range instructions { + switch instr.(type) { + case *ast.CopyInstruction, *ast.AddInstruction: + return true + } + } + return false +} + +// copiesWholeContext reports whether a COPY/ADD brings in the entire build +// context, as "COPY . ." or "COPY * ./" do. +func copiesWholeContext(sources []string) bool { + for _, source := range sources { + switch strings.TrimSuffix(strings.TrimPrefix(source, "./"), "/") { + case "", ".", "*": + return true + } + } + return false +} + // runReferencesCopy reports whether a command mentions a file brought in by a // COPY/ADD, which means the RUN depends on it. Only distinctive names count: // short names such as "." or "src" would match almost any command. @@ -330,15 +380,24 @@ func runReferencesCopy(command string, sources []string) bool { return false } -// isPackageInstallCommand checks if a command is a package manager install +// dependencyInstallPattern matches commands that install system packages or a +// project's dependencies: the steps worth caching ahead of the source code. +var dependencyInstallPattern = regexp.MustCompile(`(?m)` + + // System package managers. + `\b(apt-get|apt|yum|dnf|microdnf|zypper)\s+(-\S+\s+)*install\b|\bapk\s+(-\S+\s+)*(add|update)\b` + + // Python. + `|\bpip3?\s+install\b|\bpython3?\s+-m\s+pip\s+install\b|\buv\s+(sync|pip\s+install)\b` + + `|\bpoetry\s+install\b|\bpipenv\s+(install|sync)\b|\bconda\s+(install|env\s+(create|update))\b` + + // JavaScript. + `|\b(npm|pnpm|bun)\s+(install|ci|i)\b|\byarn(\s+install)?(\s+--\S+)*\s*($|&&|;|\|)` + + // Go, Ruby, PHP, Rust, .NET, JVM, Elixir. + `|\bgo\s+mod\s+download\b|\bbundle\s+install\b|\bcomposer\s+install\b|\bcargo\s+fetch\b` + + `|\bdotnet\s+restore\b|\bmvn\b[^\n]*\bdependency:(go-offline|resolve)\b|\bmix\s+deps\.get\b`) + +// isPackageInstallCommand reports whether a RUN command installs system +// packages or project dependencies. func isPackageInstallCommand(cmd string) bool { - return aptGetInstallPattern.MatchString(cmd) || - yumInstallPattern.MatchString(cmd) || - apkAddPattern.MatchString(cmd) || - pipInstallPattern.MatchString(cmd) || - strings.Contains(cmd, "npm install") || - strings.Contains(cmd, "yarn install") || - strings.Contains(cmd, "go mod download") + return dependencyInstallPattern.MatchString(cmd) } // packageFiles are dependency manifests and lock files, lower-cased. diff --git a/internal/rules/layer_test.go b/internal/rules/layer_test.go index 449783c..1ebab5c 100644 --- a/internal/rules/layer_test.go +++ b/internal/rules/layer_test.go @@ -374,6 +374,33 @@ func TestIsPackageInstallCommand(t *testing.T) { {"yarn install", true}, {"go mod download", true}, {"echo hello", false}, + // Dependency installers beyond the original list. + {"npm ci", true}, + {"npm i --omit=dev", true}, + {"pnpm install --frozen-lockfile", true}, + {"bun install", true}, + {"yarn", true}, + {"yarn --frozen-lockfile && yarn build", true}, + {"python -m pip install -r requirements.txt", true}, + {"uv sync --frozen", true}, + {"poetry install --no-root", true}, + {"pipenv install --deploy", true}, + {"bundle install", true}, + {"composer install --no-dev", true}, + {"cargo fetch", true}, + {"dotnet restore", true}, + {"mvn -B dependency:go-offline", true}, + {"apt install -y curl", true}, + {"apt-get -y --no-install-recommends install curl", true}, + {"microdnf install -y curl", true}, + // Commands that build or run the project rather than install into it. + {"npm run build", false}, + {"npm init -y", false}, + {"yarn build", false}, + {"go build ./...", false}, + {"cargo build --release", false}, + {"dotnet publish -c Release", false}, + {"mvn package", false}, } for _, tt := range tests { @@ -566,3 +593,129 @@ func TestRunReferencesCopy(t *testing.T) { } } } + +// TestSuboptimalOrderingWholeContext verifies the classic anti-pattern, the +// whole build context copied before the dependencies are installed, is caught +// even when nothing else is copied after the install. +func TestSuboptimalOrderingWholeContext(t *testing.T) { + rule := &SuboptimalOrderingRule{} + + stage := func(instrs ...ast.Instruction) *ast.Dockerfile { + return &ast.Dockerfile{Stages: []ast.Stage{{Index: 0, Instructions: instrs}}} + } + + tests := []struct { + name string + df *ast.Dockerfile + want int + }{ + { + name: "node: COPY . . then npm ci", + df: stage( + &ast.CopyInstruction{LineNum: 1, Sources: []string{"."}, Dest: "."}, + &ast.RunInstruction{LineNum: 2, Command: "npm ci"}, + &ast.RunInstruction{LineNum: 3, Command: "npm run build"}, + ), + want: 1, + }, + { + name: "python: COPY ./ /app/ then pip install -r", + df: stage( + &ast.CopyInstruction{LineNum: 1, Sources: []string{"./"}, Dest: "/app/"}, + &ast.RunInstruction{LineNum: 2, Command: "pip install --no-cache-dir -r requirements.txt"}, + ), + want: 1, + }, + { + name: "go: ADD * ./ then go mod download", + df: stage( + &ast.AddInstruction{LineNum: 1, Sources: []string{"*"}, Dest: "./"}, + &ast.RunInstruction{LineNum: 2, Command: "go mod download"}, + ), + want: 1, + }, + { + name: "reported once across several installs", + df: stage( + &ast.CopyInstruction{LineNum: 1, Sources: []string{"."}, Dest: "."}, + &ast.RunInstruction{LineNum: 2, Command: "apt-get install -y make"}, + &ast.RunInstruction{LineNum: 3, Command: "npm ci"}, + ), + want: 1, + }, + { + name: "manifests first, then the whole context after the install", + df: stage( + &ast.CopyInstruction{LineNum: 1, Sources: []string{"package.json", "package-lock.json"}, Dest: "./"}, + &ast.RunInstruction{LineNum: 2, Command: "npm ci"}, + &ast.CopyInstruction{LineNum: 3, Sources: []string{"."}, Dest: "."}, + &ast.RunInstruction{LineNum: 4, Command: "npm run build"}, + ), + want: 0, + }, + { + name: "whole context before a build step only", + df: stage( + &ast.CopyInstruction{LineNum: 1, Sources: []string{"."}, Dest: "."}, + &ast.RunInstruction{LineNum: 2, Command: "go build -o /app ./cmd/app"}, + ), + want: 0, + }, + { + name: "a single specific file before an install is not reported", + df: stage( + &ast.CopyInstruction{LineNum: 1, Sources: []string{"nginx.conf"}, Dest: "/etc/nginx/"}, + &ast.RunInstruction{LineNum: 2, Command: "apk add --no-cache curl"}, + ), + want: 0, + }, + { + name: "COPY --from is not the build context", + df: stage( + &ast.CopyInstruction{LineNum: 1, From: "builder", Sources: []string{"."}, Dest: "."}, + &ast.RunInstruction{LineNum: 2, Command: "npm ci"}, + ), + want: 0, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := rule.Check(tt.df); len(got) != tt.want { + t.Errorf("got %d findings, want %d: %+v", len(got), tt.want, got) + } + }) + } +} + +// TestCacheNotCleanedPipEnv verifies PIP_NO_CACHE_DIR in the environment +// counts as --no-cache-dir, within its own stage only. +func TestCacheNotCleanedPipEnv(t *testing.T) { + rule := &CacheNotCleanedRule{} + from := func(line int) *ast.FromInstruction { + return &ast.FromInstruction{LineNum: line, Image: "python", Tag: "3.12-slim"} + } + pip := func(line int, cmd string) *ast.RunInstruction { + return &ast.RunInstruction{LineNum: line, Command: cmd} + } + + tests := []struct { + name string + instrs []ast.Instruction + want int + }{ + {"ENV disables the cache", []ast.Instruction{from(1), &ast.EnvInstruction{LineNum: 2, Key: "PIP_NO_CACHE_DIR", Value: "1"}, pip(3, "pip install flask")}, 0}, + {"any non-empty value counts, as in pip", []ast.Instruction{from(1), &ast.EnvInstruction{LineNum: 2, Key: "PIP_NO_CACHE_DIR", Value: "off"}, pip(3, "pip install flask")}, 0}, + {"empty value does not", []ast.Instruction{from(1), &ast.EnvInstruction{LineNum: 2, Key: "PIP_NO_CACHE_DIR", Value: ""}, pip(3, "pip install flask")}, 1}, + {"set for the command", []ast.Instruction{from(1), pip(2, "PIP_NO_CACHE_DIR=1 pip install flask")}, 0}, + {"ENV of an earlier stage does not carry over", []ast.Instruction{from(1), &ast.EnvInstruction{LineNum: 2, Key: "PIP_NO_CACHE_DIR", Value: "1"}, from(3), pip(4, "pip install flask")}, 1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + df := &ast.Dockerfile{Instructions: tt.instrs} + if got := rule.Check(df); len(got) != tt.want { + t.Errorf("got %d findings, want %d", len(got), tt.want) + } + }) + } +} diff --git a/internal/rules/security.go b/internal/rules/security.go index 4b9912d..11a98d9 100644 --- a/internal/rules/security.go +++ b/internal/rules/security.go @@ -77,6 +77,16 @@ var metadataSuffixes = map[string]bool{ // urlPattern matches URLs in ADD sources var urlPattern = regexp.MustCompile(`^https?://`) +// gitSourcePattern matches the Git repositories ADD can fetch: git@host:repo, +// git:// and ssh:// URLs, and HTTP(S) URLs ending in .git with an optional #ref. +var gitSourcePattern = regexp.MustCompile(`^(git@|git://|ssh://)|^https?://\S+\.git(#\S*)?$`) + +// isRemoteSource reports whether an ADD source is fetched from the network +// rather than taken from the build context. +func isRemoteSource(source string) bool { + return urlPattern.MatchString(source) || gitSourcePattern.MatchString(source) +} + // archiveExtensions contains file extensions that indicate archive files var archiveExtensions = []string{ ".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", @@ -306,16 +316,23 @@ func (r *AddWithURLRule) Check(dockerfile *ast.Dockerfile) []ast.Finding { continue } - // Check if any source is a URL + // ADD --checksum verifies the download, which is what Docker now + // recommends for remote files instead of curl or wget. + if add.Checksum != "" { + continue + } + + // Check if any source is a plain URL. Git repositories are fetched at a + // pinned ref, which RUN curl cannot do. for _, source := range add.Sources { - if urlPattern.MatchString(source) { + if urlPattern.MatchString(source) && !gitSourcePattern.MatchString(source) { findings = append(findings, ast.Finding{ RuleID: r.ID(), Severity: r.Severity(), Line: add.Line(), Column: 1, Message: "ADD with URL source is not recommended", - Suggestion: "Use 'RUN curl -o ' or 'RUN wget -O ' for better caching and security", + Suggestion: "Pin the download with 'ADD --checksum=sha256: ', or fetch it with curl or wget in a RUN instruction", }) break // Only report once per ADD instruction } @@ -350,8 +367,8 @@ func (r *AddOverCopyRule) Check(dockerfile *ast.Dockerfile) []ast.Finding { hasArchive := false for _, source := range add.Sources { - // Check for URL - if urlPattern.MatchString(source) { + // Check for a URL or Git repository, which COPY cannot fetch + if isRemoteSource(source) { hasURL = true break } diff --git a/internal/rules/security_test.go b/internal/rules/security_test.go index 6c367de..7ef5997 100644 --- a/internal/rules/security_test.go +++ b/internal/rules/security_test.go @@ -555,3 +555,55 @@ func TestIsArchiveFile(t *testing.T) { }) } } + +// TestAddRemoteSources verifies DKL304 and DKL305 on the forms of ADD that +// fetch remote content: plain URLs, URLs pinned with --checksum, and Git +// repositories, which COPY cannot fetch either. +func TestAddRemoteSources(t *testing.T) { + tests := []struct { + name string + add *ast.AddInstruction + wantURL bool // DKL304 + wantCopyOver bool // DKL305 + }{ + { + name: "plain URL", + add: &ast.AddInstruction{LineNum: 1, Sources: []string{"https://example.com/tool.sh"}, Dest: "/tool.sh"}, + wantURL: true, + }, + { + name: "URL pinned with --checksum", + add: &ast.AddInstruction{LineNum: 1, Sources: []string{"https://example.com/tool.tar.gz"}, Dest: "/tool", + Checksum: "sha256:24454f830cdb571e2c4ad15481119c43b3cafd48dd869a9b2945d1036d1dc68d"}, + }, + { + name: "Git repository over HTTPS at a ref", + add: &ast.AddInstruction{LineNum: 1, Sources: []string{"https://github.com/moby/buildkit.git#v0.10.1"}, Dest: "/src"}, + }, + { + name: "Git repository over SSH", + add: &ast.AddInstruction{LineNum: 1, Sources: []string{"git@github.com:moby/buildkit.git"}, Dest: "/src"}, + }, + { + name: "local archive is extracted", + add: &ast.AddInstruction{LineNum: 1, Sources: []string{"app.tar.gz"}, Dest: "/app"}, + }, + { + name: "local file", + add: &ast.AddInstruction{LineNum: 1, Sources: []string{"app.py"}, Dest: "/app.py"}, + wantCopyOver: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + df := &ast.Dockerfile{Instructions: []ast.Instruction{tt.add}} + if got := len((&AddWithURLRule{}).Check(df)) > 0; got != tt.wantURL { + t.Errorf("DKL304 reported = %v, want %v", got, tt.wantURL) + } + if got := len((&AddOverCopyRule{}).Check(df)) > 0; got != tt.wantCopyOver { + t.Errorf("DKL305 reported = %v, want %v", got, tt.wantCopyOver) + } + }) + } +} diff --git a/testdata/corpus/apps/nginx-wsgi-flask_flask.Dockerfile.golden b/testdata/corpus/apps/nginx-wsgi-flask_flask.Dockerfile.golden index dfff17a..c2ecd78 100644 --- a/testdata/corpus/apps/nginx-wsgi-flask_flask.Dockerfile.golden +++ b/testdata/corpus/apps/nginx-wsgi-flask_flask.Dockerfile.golden @@ -1,6 +1,7 @@ 4:1 warning DKL201 pip install without --no-cache-dir increases image size 4:1 info DKL202 Found 6 consecutive RUN instructions that could be combined 7:1 warning DKL201 apk add without --no-cache increases image size +18:1 warning DKL203 COPY/ADD of the whole build context before installing dependencies reruns the install on every source change 26:1 info DKL202 Found 2 consecutive RUN instructions that could be combined 27:1 warning DKL201 pip install without --no-cache-dir increases image size 32:1 info DKL404 No HEALTHCHECK instruction found diff --git a/testdata/corpus/apps/vuejs_vuejs.Dockerfile.golden b/testdata/corpus/apps/vuejs_vuejs.Dockerfile.golden index 7a9b038..2bce67d 100644 --- a/testdata/corpus/apps/vuejs_vuejs.Dockerfile.golden +++ b/testdata/corpus/apps/vuejs_vuejs.Dockerfile.golden @@ -1,3 +1,4 @@ +7:1 warning DKL203 COPY/ADD of the whole build context before installing dependencies reruns the install on every source change 17:1 warning DKL201 apk add without --no-cache increases image size 17:1 info DKL202 Found 2 consecutive RUN instructions that could be combined 28:1 warning DKL303 No USER instruction in final stage 'dev-envs'; container will run as root