diff --git a/.goreleaser.yaml b/.goreleaser.yaml index f59b4f0..69a443d 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -4,7 +4,7 @@ # goreleaser check # goreleaser release --snapshot --clean # -# Releases are cut by pushing a vX.Y.Z tag; see "Releasing" in CONTRIBUTING.md. +# Releases are cut by pushing a vX.Y.Z tag; see "Releasing" in docs/maintaining.md. version: 2 project_name: docker-lint diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5c87759..a4961b8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,131 +1,9 @@ -# Contributing to docker-lint +# Contributing -Thank you for your interest in contributing to docker-lint! +docker-lint does not accept pull requests, and pull requests will be closed without review. -## Development Setup +Bug reports and suggestions are welcome as [issues](https://github.com/devblac/docker-lint/issues). For a +false positive or a missed problem, include the Dockerfile (or the smallest part of it that shows the +problem), the command you ran and the output of `docker-lint --version`. -### Prerequisites - -- Go 1.22.x or later (matches the `go 1.22.0` directive in `go.mod`) -- Git - -### Getting Started - -1. Fork and clone the repository: - ```bash - git clone https://github.com/[username]/docker-lint.git - cd docker-lint - ``` - -2. Install dependencies: - ```bash - go mod download - ``` - -3. Build the project: - ```bash - go build -o docker-lint ./cmd/docker-lint - ``` - -4. Run tests: - ```bash - go test ./... - ``` - -## Project Structure - -``` -docker-lint/ -├── cmd/docker-lint/ # CLI entry point -├── internal/ -│ ├── ast/ # AST data structures -│ ├── parser/ # BuildKit parse result -> AST conversion -│ ├── rules/ # Lint rule implementations -│ ├── analyzer/ # Rule orchestration -│ └── formatter/ # Output formatters -└── testdata/ # Test fixtures -``` - -## Testing Guidelines - -- Write unit tests for new functionality -- Write property-based tests for universal properties -- Use table-driven tests where appropriate -- Include test fixtures in `testdata/` -- After changing a rule or the parser, regenerate the real-world corpus snapshots - with `go test ./internal/analyzer -run TestCorpus -update-corpus` and review the - diff: every changed line is a finding that appeared, disappeared or moved on a real - Dockerfile (see `testdata/corpus/SOURCES.md`) - -### Running Tests - -```bash -# Run all tests -go test ./... - -# Run tests with coverage -go test -cover ./... - -# Run specific package tests -go test ./internal/parser/ -``` - -## Code Style - -- Follow standard Go conventions -- Run `go fmt` before committing -- Run `go vet` to catch common issues -- Keep functions small and focused - -## Pull Request Process - -1. Create a feature branch from `main` -2. Make your changes with clear commit messages -3. Ensure all tests pass -4. Update documentation if needed -5. Submit a pull request with a clear description - -## Adding New Rules - -1. Create or update a file in `internal/rules/` -2. Implement the `Rule` interface -3. Register the rule in `registry.go` -4. Add unit tests for the rule -5. Update README.md with rule documentation - -## Releasing - -Releases are built by GoReleaser from a pushed tag and land as a **draft** GitHub -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, update the comparison links at the bottom, point - the `docker-lint-docker` hook in `.pre-commit-hooks.yaml` and the version examples - in `README.md` at the new version, and merge that change to `main`. The Release - workflow fails if the hook names another version's image. -3. Tag the merge commit and push the tag: - - ```bash - git tag -a vX.Y.Z -m "docker-lint vX.Y.Z" - git push origin vX.Y.Z - ``` - -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: 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. -6. Publishing the release runs the Image workflow, which pushes - `ghcr.io/devblac/docker-lint` for linux/amd64 and linux/arm64. The first time, - make the package public in its settings on GitHub; packages start out private. - It also runs the Version tags workflow, which moves the major and minor tags - (`v0`, `v0.1`) to the release when it is the newest in their line. Never push - those tags by hand. - -## Questions? - -Open an issue for questions or discussions. +docker-lint is MIT licensed, so you are free to fork it. diff --git a/README.md b/README.md index 2ea4f24..d295041 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,44 @@ # docker-lint -[![CI](https://img.shields.io/github/actions/workflow/status/devblac/docker-lint/ci.yml?branch=main&logo=github)](https://github.com/devblac/docker-lint/actions/workflows/ci.yml) [![Go Report Card](https://goreportcard.com/badge/github.com/devblac/docker-lint)](https://goreportcard.com/report/github.com/devblac/docker-lint) [![Go Reference](https://pkg.go.dev/badge/github.com/devblac/docker-lint.svg)](https://pkg.go.dev/github.com/devblac/docker-lint) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![Release](https://img.shields.io/github/v/release/devblac/docker-lint?display_name=release&sort=semver)](https://github.com/devblac/docker-lint/releases) +[![CI](https://img.shields.io/github/actions/workflow/status/devblac/docker-lint/ci.yml?branch=main&logo=github)](https://github.com/devblac/docker-lint/actions/workflows/ci.yml) +[![Release](https://img.shields.io/github/v/release/devblac/docker-lint?sort=semver)](https://github.com/devblac/docker-lint/releases) +[![Go Reference](https://pkg.go.dev/badge/github.com/devblac/docker-lint.svg)](https://pkg.go.dev/github.com/devblac/docker-lint) +[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) + +docker-lint checks Dockerfiles for problems that make images larger, slower to build or less secure. It +reads files only and never runs a build. Dockerfiles are parsed with BuildKit, the same parser `docker build` +uses, so heredocs, parser directives and `RUN --mount` are read the way Docker reads them. + +```console +$ docker-lint Dockerfile +Dockerfile:1:1: [warning] DKL103: Image 'node' is a large base image for the final image + Suggestion: Consider using node:*-slim or node:*-alpine for smaller image size +Dockerfile:3:1: [warning] DKL203: 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 +Dockerfile:5:1: [warning] DKL301: ENV instruction contains key 'API_TOKEN' which may contain a secret + Suggestion: Use Docker secrets, build-time secrets (--secret), or runtime environment variables instead +``` -A minimal, production-grade CLI tool for statically analyzing Dockerfiles to detect common inefficiencies, anti-patterns, and security issues. +It runs as a single static binary, a container image, a GitHub Action or a pre-commit hook, and writes text, +JSON, SARIF or GitHub annotations. -## Features +## Contents -- **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 <__`, with `.zip` for Windows and -`.tar.gz` elsewhere. +Archives are named `docker-lint___`, with `.zip` for Windows and `.tar.gz` elsewhere. + +**Go** 1.22 or later: -### Docker +```bash +go install github.com/devblac/docker-lint/cmd/docker-lint@latest +``` -A 2.5 MB image (static binary on distroless, running as a non-root user) for linux/amd64 and linux/arm64: +**Docker**: a 2.5 MB distroless image for linux/amd64 and linux/arm64 that runs as a non-root user: ```bash -# Lint from standard input docker run --rm -i ghcr.io/devblac/docker-lint:0.1.2 < Dockerfile - -# Lint every Dockerfile in the current directory docker run --rm -v "$PWD:/work" ghcr.io/devblac/docker-lint:0.1.2 . ``` -### pre-commit - -Add to `.pre-commit-config.yaml` to lint staged Dockerfiles before each commit: +**pre-commit**: add to `.pre-commit-config.yaml`: ```yaml repos: @@ -58,213 +70,124 @@ repos: rev: v0.1.2 hooks: - id: docker-lint # builds docker-lint with Go - # - id: docker-lint-docker # or runs the container image (needs Docker, not Go) + # - id: docker-lint-docker # runs the container image instead (needs Docker, not Go) ``` Both hooks read the project's `.docker-lint.yaml` and skip Dockerfile templates. -### From Source - -Requires Go 1.22 or later (as specified in `go.mod`). +## Usage -```bash -go install github.com/devblac/docker-lint/cmd/docker-lint@latest +``` +docker-lint [flags] [path ...] ``` -### Build from Repository +A path can be a file, a directory or a glob pattern: ```bash -git clone https://github.com/devblac/docker-lint.git -cd docker-lint -go build -o docker-lint ./cmd/docker-lint +docker-lint Dockerfile # one file +docker-lint . # every Dockerfile in the repository +docker-lint 'services/**/Dockerfile' # a pattern; quote it so every shell passes it unchanged +docker-lint < Dockerfile # standard input, also with - ``` -## Usage +Directories are searched recursively for `Dockerfile`, `Containerfile`, `Dockerfile.*` and `*.Dockerfile`. +`.git` and `node_modules` are skipped, and so are templates, backups and docs such as `Dockerfile.j2`, +`Dockerfile.template` or `Dockerfile.bak`; name one explicitly to lint it. A directory or pattern that matches +no Dockerfile is an error, so a CI job cannot pass without linting anything. -```bash -docker-lint [flags] [path ...] -``` +| Flag | Description | +|------|-------------| +| `-f`, `--format ` | Output format: `text` (default), `json`, `sarif` or `github` | +| `-j`, `--json` | Same as `--format json` | +| `-s`, `--strict` | Fail on warnings as well as errors | +| `-q`, `--quiet` | Hide informational findings | +| `--ignore ` | Comma-separated rule IDs to skip | +| `-c`, `--config ` | Configuration file (default: the nearest `.docker-lint.yaml`) | +| `--no-config` | Do not read a configuration file | +| `--rules` | List the rules | +| `-v`, `--version` | Print the version | +| `-h`, `--help` | Print help | -Each path is a Dockerfile, a directory, or a glob pattern. A directory is searched recursively for files named -`Dockerfile`, `Containerfile`, `Dockerfile.*` or `*.Dockerfile` (skipping `.git` and `node_modules`, and templates, -backups and docs such as `Dockerfile.template`, `Dockerfile.j2` or `Dockerfile.bak`, which name a file explicitly -to lint). Patterns -support `**` for any number of directories and are expanded by docker-lint itself, so quote them to make them -work the same in every shell, including on Windows. A directory or pattern that matches no Dockerfile is a fatal -error, so a CI job cannot pass without linting anything. With no path, or with `-`, docker-lint reads from stdin. -Flags may come before or after the paths; use `--` before a path that starts with `-`. - -### Flags - -| Flag | Short | Description | -|------|-------|-------------| -| `--help` | `-h` | Show help message | -| `--version` | `-v` | Show version information | -| `--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 | -| `--config ` | `-c` | Configuration file (default: the nearest `.docker-lint.yaml`) | -| `--no-config` | | Do not read a configuration file | -| `--rules` | | List all available rules with descriptions | - -### Examples +Flags may come before or after the paths. Use `--` before a path that starts with `-`. -```bash -# Analyze a Dockerfile -docker-lint Dockerfile +### Exit codes -# Analyze every Dockerfile in a repository -docker-lint . +| Code | Meaning | +|------|---------| +| 0 | No errors (warnings are allowed unless `--strict` is set) | +| 1 | Errors found, or warnings with `--strict` | +| 2 | Invalid arguments or configuration, or a file that cannot be read or parsed | -# Analyze Dockerfiles matching a pattern -docker-lint 'services/**/Dockerfile' +When several files are linted, a file that cannot be read or parsed is reported, the rest are still linted, +and the exit code is 2. -# Analyze from stdin -cat Dockerfile | docker-lint +## Configuration -# JSON output for CI integration -docker-lint --json Dockerfile > results.json +docker-lint reads `.docker-lint.yaml` (or `.docker-lint.yml`) from the current directory or the nearest parent +directory, up to the repository root: -# Strict mode for CI (fail on warnings) -docker-lint --strict Dockerfile +```yaml +ignore: # rules that are never reported + - DKL103 -# Ignore specific rules -docker-lint --ignore DKL101,DKL103 Dockerfile +severity: # error, warning, info, or off to disable the rule + DKL303: error + DKL404: off -# Suppress informational messages -docker-lint --quiet Dockerfile +strict: true # same as --strict +quiet: false # same as --quiet -# List all available rules -docker-lint --rules +exclude: # files skipped when a directory or pattern is expanded + - vendor # without a slash: a file or directory name anywhere, as in .gitignore + - "examples/**" # relative to this file's directory ``` -### Inline Ignores +Command-line flags take precedence: `--strict=false` overrides `strict: true`, and `--ignore` adds to the +ignored rules. Unknown keys and invalid severities are errors, so a typo cannot silently disable a setting. +A file named on the command line is linted even if it matches `exclude`. -Disable specific rules for the next line using comments: +To skip a rule on a single instruction, put a comment on the line above it: ```dockerfile # docker-lint ignore: DKL102 FROM ubuntu:latest - -# docker-lint ignore: DKL303 -# No USER instruction needed for this build stage -``` - -### Configuration File - -docker-lint reads `.docker-lint.yaml` (or `.docker-lint.yml`) from the current directory, or from the nearest -parent directory up to the repository root. Use `--config` to pick another file and `--no-config` to read none. - -```yaml -# Rules that are never reported. -ignore: - - DKL103 - -# Change a rule's severity: error, warning, info, or off to disable it. -severity: - DKL303: error # fail the build when the final image runs as root - DKL404: off # disable the rule - -# Fail on warnings too (same as --strict). -strict: true - -# Hide informational findings (same as --quiet). -quiet: false - -# Skip matching files when a directory or pattern is expanded. Patterns are -# relative to this file's directory; one without a slash matches a file or -# directory name anywhere, as in .gitignore. -exclude: - - vendor - - "examples/**" ``` -Command-line flags win over the file: `--strict=false` turns off `strict: true`, and `--ignore` adds to the -ignored rules. Unknown keys and invalid severities are fatal errors, so a typo does not silently disable the -configuration. A file named explicitly on the command line is always linted, even if it matches `exclude`. - -## Exit Codes - -| Code | Meaning | -|------|---------| -| 0 | Success - no errors found (warnings allowed in non-strict mode) | -| 1 | Lint errors found, or warnings found in strict mode | -| 2 | Fatal error - invalid arguments or configuration, file not found, or parse error | - -When several files are linted, one that cannot be read or parsed is reported and the others are still linted; -the exit code is then 2. - ## Rules -docker-lint includes 18 built-in rules. Rule IDs use the `DKL` prefix and are grouped by category in hundreds: -`DKL0xx` structure, `DKL1xx` base image, `DKL2xx` layers, `DKL3xx` security, `DKL4xx` best practices. - -> **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. - -### Structure Rules - -| ID | Severity | Name | Description | -|----|----------|------|-------------| -| DKL001 | Error | Instruction before FROM | Every build must start with FROM; only ARG may appear before the first FROM. Docker fails to build such a file | - -### Base Image Rules - -| ID | Severity | Name | Description | -|----|----------|------|-------------| -| DKL101 | Warning | Missing explicit image tag | Always tag the version of an image explicitly to ensure reproducible builds | -| DKL102 | Warning | Using 'latest' tag | Using 'latest' tag can lead to unpredictable builds as the image may change | -| DKL103 | Warning | Large base image | Consider a smaller variant (slim, alpine) for the base of the final image. Build stages are not checked; a final stage built on one is | - -### Layer Optimization Rules - -| ID | Severity | Name | Description | -|----|----------|------|-------------| -| 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, 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 - -| ID | Severity | Name | Description | -|----|----------|------|-------------| -| 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 | 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 - -| ID | Severity | Name | Description | -|----|----------|------|-------------| -| DKL401 | Warning | Multiple CMD instructions | Only the last CMD instruction takes effect; multiple CMD instructions are likely a mistake | -| DKL402 | Warning | Multiple ENTRYPOINT instructions | Only the last ENTRYPOINT instruction takes effect; multiple ENTRYPOINT instructions are likely a mistake | -| DKL403 | Warning | WORKDIR with relative path | Use absolute paths in WORKDIR to avoid confusion about the current directory | -| DKL404 | Info | Missing HEALTHCHECK | Add a HEALTHCHECK instruction to enable container health monitoring (Kubernetes ignores it and uses its own probes) | -| DKL405 | Info | Wildcard in COPY/ADD source | Wildcard patterns in COPY/ADD may include unnecessary files, increasing build context size | - -## Output Formats - -### Text (default) - -Human-readable output with file path, line number, severity, rule ID, and message: - -``` -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: [info] DKL202: Found 2 consecutive RUN instructions that could be combined - Suggestion: Combine RUN instructions using '&&' to reduce layers -``` - -### JSON (`--format json`) - -Machine-readable JSON output for CI/CD integration. A single file (or stdin) produces one object; several files -produce an array with one such object per file: +Rule IDs are grouped by category: `DKL0xx` structure, `DKL1xx` base images, `DKL2xx` layers, `DKL3xx` +security and `DKL4xx` best practices. + +| ID | Default | Checks for | +|----|---------|------------| +| DKL001 | error | An instruction other than `ARG` before the first `FROM`, which Docker refuses to build | +| DKL101 | warning | A base image without a tag | +| DKL102 | warning | A base image tagged `latest` | +| DKL103 | warning | A large base image (such as `ubuntu` or `node`) in the final stage, where a slim or alpine variant exists | +| DKL201 | warning | A package install that leaves the package manager's cache in the layer. `apt-get dist-clean`, `PIP_NO_CACHE_DIR` and cache mounts count as cleaning it | +| DKL202 | info | Consecutive `RUN` instructions that could be one layer | +| DKL203 | warning | Source files copied before dependencies are installed, which reruns the install on every change. Copying only the manifests (`package.json`, `go.mod`, `requirements.txt`, ...) first is fine | +| DKL204 | warning | A package index update without an install in the same `RUN` | +| DKL301 | warning | An `ENV` whose name suggests a secret. The value is never printed | +| DKL302 | warning | An `ARG` whose name suggests a secret | +| DKL303 | warning | A final stage that runs as root. Build stages are not checked | +| DKL304 | warning | `ADD` of a URL without `--checksum`. Git repositories are allowed | +| DKL305 | warning | `ADD` of a local file that is not an archive, where `COPY` is enough | +| DKL401 | warning | More than one `CMD` in a stage; only the last one applies | +| DKL402 | warning | More than one `ENTRYPOINT` in a stage; only the last one applies | +| DKL403 | warning | A relative `WORKDIR` path | +| DKL404 | info | No `HEALTHCHECK`. Kubernetes ignores it in favor of its own probes; disable the rule there | +| DKL405 | info | A wildcard in a `COPY` or `ADD` source, other than one that selects only dependency manifests | + +Versions before v0.1.1 used `DLxxxx` IDs, which clash with [hadolint](https://github.com/hadolint/hadolint)'s. +They are no longer accepted; passing one to `--ignore` prints its replacement, and the +[changelog](CHANGELOG.md) has the full mapping. + +## Output formats + +**text** is the default, shown above. + +**json** prints one object per file, or an array of them when several files are linted: ```json { @@ -279,49 +202,26 @@ produce an array with one such object per file: "suggestion": "Pin to a specific version like 'ubuntu:' for reproducible builds" } ], - "summary": { - "total": 1, - "errors": 0, - "warnings": 1, - "info": 0 - } + "summary": { "total": 1, "errors": 0, "warnings": 1, "info": 0 } } ``` -### SARIF (`--format sarif`) +**sarif** writes [SARIF 2.1.0](https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html) with the +metadata of every rule, for GitHub code scanning and other dashboards. -[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** prints workflow commands that GitHub shows as annotations on the pull request diff. Unlike code +scanning, they need no GitHub Advanced Security on private repositories. -### GitHub annotations (`--format github`) +## GitHub Action -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 your Dockerfiles and annotates -the pull request diff with the findings: +The action downloads a release binary, verifies its checksum, lints and annotates the pull request: ```yaml - uses: actions/checkout@v7 - uses: devblac/docker-lint@v0.1.2 - 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: +To also send the findings to the repository's Security tab: ```yaml permissions: @@ -336,80 +236,53 @@ steps: Dockerfile services/**/Dockerfile strict: true - ignore: DKL404 upload-sarif: true ``` | Input | Default | Description | |-------|---------|-------------| -| `dockerfile` | `Dockerfile` | Files, directories or glob patterns to lint, one per line | -| `config` | | Configuration file (default: `.docker-lint.yaml` at the repository root) | -| `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, `@v0` the newest v0.x.y), or the latest release when the action is used from a branch. Also `latest`, a tag such as `v0.1.1` or a line such as `v0` | -| `format` | `github` | Log output: `github` (annotations), `text`, `json` or `sarif` | -| `strict` | `false` | Fail on warnings, not only on errors | +| `dockerfile` | `Dockerfile` | Files, directories or patterns to lint, one per line | +| `config` | | Configuration file (default: `.docker-lint.yaml` at the repository root, if present) | +| `version` | the action's tag | docker-lint release to install: a tag such as `v0.1.2`, a line such as `v0`, or `latest` | +| `format` | `github` | Log output: `github`, `text`, `json` or `sarif` | +| `strict` | `false` | Fail on warnings as well as 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 | +| `ignore` | | Comma-separated rule IDs to skip | +| `sarif-file` | | Also write a SARIF report to this path (`docker-lint.sarif` when uploading) | +| `upload-sarif` | `false` | Upload the SARIF report to code scanning | +| `github-token` | `github.token` | Token used to download the 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 | +| `exit-code` | docker-lint's exit code | +| `sarif-file` | Path of the SARIF report, if one was written | + +The action's tag selects the linter version: `@v0.1.2` installs docker-lint 0.1.2, and `@v0` or `@v0.1` +install the newest release in that line. A floating tag picks up new rules, which can fail a build that passed +before. If you pin the action to a commit SHA, set `version` too; otherwise it installs the latest release. -Pinning the action pins the linter: `@v0.1.1` installs docker-lint v0.1.1. To get fixes and new rules -without editing the workflow, use `@v0` (or `@v0.1` for fixes only): these tags follow the newest release in -their line, and the action installs that release. Bear in mind that a new rule can fail a build that passed -before. When you pin the action to a commit SHA, also set `version` to the matching tag; otherwise the latest -release is installed. +The step fails with docker-lint's exit code. The SARIF report is still written and uploaded when it does. -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; -when none could, no report is written rather than an empty one. +## Other CI systems -### GitLab CI +Install a release binary as shown above, or use `go install`, then run docker-lint like any other command. +In GitLab CI, for example: ```yaml -lint-dockerfile: +docker-lint: + image: golang:1.22 script: - - docker-lint --strict Dockerfile - allow_failure: false + - go install github.com/devblac/docker-lint/cmd/docker-lint@v0.1.2 + - docker-lint --strict . ``` -### Jenkins Pipeline - -```groovy -stage('Lint Dockerfile') { - steps { - sh 'docker-lint --strict Dockerfile' - } -} -``` +The container image has no shell, so it suits `docker run` but not CI systems that run scripts inside the +job's image. ## Contributing -See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, testing guidelines, and contribution process. - -### Quick Start for Contributors - -```bash -# Clone the repository -git clone https://github.com/devblac/docker-lint.git -cd docker-lint - -# Install dependencies -go mod download - -# Run tests -go test ./... - -# Build -go build -o docker-lint ./cmd/docker-lint - -# Run linter on itself (the repository's own Dockerfile builds the image) -./docker-lint Dockerfile -``` +docker-lint does not accept pull requests. Bug reports and suggestions are welcome as +[issues](https://github.com/devblac/docker-lint/issues). ## License diff --git a/docs/maintaining.md b/docs/maintaining.md new file mode 100644 index 0000000..aa4b9df --- /dev/null +++ b/docs/maintaining.md @@ -0,0 +1,72 @@ +# Maintaining docker-lint + +## Development + +Go 1.22 or later (the `go` directive in `go.mod`). + +```bash +go build -o docker-lint ./cmd/docker-lint +go test ./... +go vet ./... +gofmt -l . +``` + +``` +cmd/docker-lint/ CLI entry point +internal/ast/ Dockerfile model +internal/parser/ BuildKit parse result to model +internal/rules/ rule implementations and registry +internal/analyzer/ runs the rules over a Dockerfile +internal/config/ .docker-lint.yaml +internal/files/ path, directory and pattern expansion +internal/formatter/ text, JSON, SARIF and GitHub output +testdata/ fixtures and the real-world corpus +``` + +### Tests + +- Unit tests are table-driven; parser and rule invariants also have property-based tests (gopter). +- `internal/analyzer/detection_test.go` holds one real-world example per rule that the rule must report. +- `testdata/corpus` holds real Dockerfiles with snapshots of their findings, to catch false positives. After + changing a rule or the parser, regenerate them and review the diff, where every changed line is a finding + that appeared, disappeared or moved: + + ```bash + go test ./internal/analyzer -run TestCorpus -update-corpus + ``` + + The sources are listed in `testdata/corpus/SOURCES.md`. + +### Adding a rule + +1. Implement the `Rule` interface in `internal/rules/`, in the file for its category. +2. Register it in `internal/rules/registry.go`. +3. Add unit tests, an entry in `detection_test.go`, and regenerate the corpus snapshots. +4. Document it in the README's rule table and in `CHANGELOG.md`. + +## Releasing + +GoReleaser builds a release from a pushed tag as a **draft**, so nothing is public until it is published. + +1. Make sure `main` is green. CI also runs `goreleaser release --snapshot --clean` on every pull request. +2. In `CHANGELOG.md`, rename `## [Unreleased]` to `## [X.Y.Z] - YYYY-MM-DD` (the day the tag will be + pushed), add an empty `## [Unreleased]` above it and update the links at the bottom. Point the + `docker-lint-docker` hook in `.pre-commit-hooks.yaml` and the version examples in `README.md` at the new + version. Merge that to `main`. The Release workflow fails if the hook names another version's image. +3. Tag the merge commit and push the tag: + + ```bash + git tag -a vX.Y.Z -m "vX.Y.Z" + git push origin vX.Y.Z + ``` + +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: check its notes, download an archive and verify it against `checksums.txt`. Edit the + draft itself rather than creating a new release from the tag, then publish it. Tick "Publish this Action + to the GitHub Marketplace" (categories: Code quality, Security). Do not run `go install ...@vX.Y.Z` + before publishing: the Go module proxy caches a tag permanently, so it can no longer be moved. +6. Publishing runs two workflows: + - **Image** pushes `ghcr.io/devblac/docker-lint` for linux/amd64 and linux/arm64. + - **Version tags** moves `vX` and `vX.Y` to the release when it is the newest in its line. Never push + those tags by hand.