docked

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 21, 2024 License: Apache-2.0 Imports: 15 Imported by: 0

README

docked

A Dockerfile linting tool which aims to pull many best practices and recommendations from multiple sources:

  • OWASP
  • Docker Official Documentation
  • Community recommendations
  • Package manager bug trackers

Check out the currently supported rules.

Apache 2.0 License Go Version Go Build Docker Image Size (latest semver) Go Report Card

tldr;

docked analyze ./Dockerfile

Successful Outputs:

Failure Outputs:

And, it's customizable. You can ignore, re-prioritize, or add custom rules via regex. There's also JSON and HTML outputs.

Install

Binaries

Latest binary releases are available via GitHub Releases.

Homebrew
brew install jimschubert/tap/docked
Docker
docker pull jimschubert/docked:latest

When running the docker image, be sure to mount and reference the sources appropriately. For example:

Completions

After you've installed the binary either manually or via Homebrew, consider enabling completions for your shell.

For instructions, view help for your target shell.

zsh
docked completion zsh --help
bash
docked completion bash --help
fish
docked completion fish --help
powershell
docked completion powershell --help

Usage

$ docked analyze --help

Analyze a Dockerfile for issues
If not provided, FILE defaults to ./Dockerfile

Usage:
  docked analyze [FILE] [flags]

Flags:
  -h, --help                   help for analyze
  -i, --ignore strings         The lint ids to ignore
  -k, --no-buildkit-warnings   Whether to suppress Docker parser warnings
      --regex-engine string    The regex engine to use (regexp, regexp2) (default "regexp2")
      --report-type string     The type of reporting output (text, json, html) (default "text")

Global Flags:
      --config string   config file (default is $HOME/.docked.yaml)
      --viper           use Viper for configuration (default true)

Things to consider:

  • Buildkit warnings should be disabled when piping output (for example when using --report-type json), but this is not forced
  • The regexp2 engine is default because it supports full regular expression syntax. Compare differences in regexp2's README. Note that regexp2 patterns are not run in compatibility mode in docked, although that might change later.
  • viper configuration is work-in-progress. Feel free to contribute.

Configuration

The optional configuration file follows this example syntax:

ignore:
  - D7:tagged-latest
rule_overrides:
  'D5:secret-aws-access-key': low
custom_rules:
  - name: custom-name
    summary: Your custom summary
    details: Your additional rule details
    pattern: '.' # some regex pattern
    priority: critical
    command: add

Build

Build a local distribution for evaluation using goreleaser (easiest).

goreleaser release --skip-publish --snapshot --rm-dist

This will create an executable application for your os/architecture under dist:

dist
├── docked_darwin_amd64
│   └── docked
├── docked_linux_386
│   └── docked
├── docked_linux_amd64
│   └── docked
├── docked_linux_arm64
│   └── docked
├── docked_linux_arm_6
│   └── docked
└── docked_windows_amd64
    └── docked.exe

Build and execute locally using go:

  • Get dependencies
go get -d ./...
  • Build
go build -o docked ./cmd/docked/
  • Run
./docked --help

License

This project is licensed under Apache 2.0.

Documentation

Overview

Package docked provides types and functionality for analyzing and linting Dockerfiles.

docked uses the Docker buildkit parser to retrieve the AST of an input Dockerfile. It also provides a simple API for defining and registering rules for processing of the AST. All in-built rules are built upon this API. See those defined under the validations package.

Configuration

An external YAML configuration is supported by docked.Config. The configuration allows for ignoring in-built rules, overriding priority of in-built rules, as well as defining custom rules based on the validations.SimpleRegexRule structure.

Analysis

Invoking docked.Docked#Analysis will use the list of in-built validation rules, and return a docked.AnalysisResult. The result should be walked programmatically to generate a report. Please see reports under the reporting package for examples. The HTML and JSON reporters under the reporter package provide implementations for use in the accompanying cli tool for use in CI/CD pipelines.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AnalysisResult

type AnalysisResult struct {
	Evaluated    []validations.Validation `json:"evaluated"`
	NotEvaluated []validations.Validation `json:"not_evaluated"`
}

AnalysisResult holds final validations, separated in those which have been Evaluated and those which have not (NotEvaluated). A validations.Validation holds references to the rule and the result of validation to simplify reporting.

func (AnalysisResult) GoString added in v0.2.0

func (a AnalysisResult) GoString() string

GoString returns a string representation for formatter patterns %#v

type Config

type Config struct {
	// Ignore this collection of rule ids
	Ignore []string `yaml:"ignore"`
	// RuleOverrides allows users to override the ConfigRuleOverride.Priority of a specific rule by ConfigRuleOverride.ID
	RuleOverrides    *RuleOverrides                `yaml:"rule_overrides,omitempty"`
	CustomRules      []validations.SimpleRegexRule `yaml:"custom_rules,omitempty"`
	SkipDefaultRules bool                          `yaml:"skip_default_rules,omitempty"`
	// IncludeRules allows setting an approved list of rules to include when SkipDefaultRules is true
	IncludeRules []string `yaml:"include_rules,omitempty"`
}

Config represents the YAML config structure exposed to users

func (*Config) Load

func (c *Config) Load(path string) error

Load a Config from path with sorted members (by ID for rule overrides, by Name for custom rules)

type ConfigRuleOverride

type ConfigRuleOverride struct {
	// The rule id to override
	ID string `yaml:"id"`
	// The overridden priority
	Priority *model.Priority `yaml:"priority,omitempty"`
}

ConfigRuleOverride defines the id-priority override mapping used in a config file

type ConfiguredRules

type ConfiguredRules struct {
	Active   rules.RuleList
	Inactive rules.RuleList
}

ConfiguredRules partitions results into active and inactive lists

type Docked

type Docked struct {
	// Configuration for analysis
	Config Config
	// Suppress the underlying warnings presented by buildkit's parser. Use this if you want to pipe text summary to file.
	SuppressBuildKitWarnings bool
	// contains filtered or unexported fields
}

Docked is the main type for initializing Dockerfile linting/analysis

func (*Docked) Analyze

func (d *Docked) Analyze(location string) (AnalysisResult, error)

Analyze a dockerfile residing at location.

All known rules which are applicable to the Dockerfile contents are evaluated, allowing configuration-based ignores and manipulation of priority/severity of rules.

Returns the AnalysisResult or error.

Example

ExampleDocked_Analyze provides an example of programmatically invoking Docked.Analyze with default rules

c := Config{}
if err := c.Load("./testdata/config/example.yml"); err != nil {
	panic(err)
}

d := Docked{
	Config:                   c,
	SuppressBuildKitWarnings: true,
}

result, err := d.Analyze("./testdata/minimal.dockerfile")
if err != nil {
	panic("Failed to analyze dockerfile")
}

// programmatically consume array of evaluated and/or not-evaluated rules
printEvaluated(result.Evaluated)
Output:

D5:no-debian-frontend - Success
D5:secret-aws-access-key - Success
D5:secret-aws-secret-access-key - Success
DC:avoid-sudo - Success
DC:consider-multistage - Success
DC:curl-without-fail - Success
DC:gpg-without-batch - Success
DC:layered-ownership-change - Success
Example (WithCustomRules)

ExampleDocked_Analyze_withCustomRules provides an example of programmatically invoking Docked.Analyze with custom rules

c := Config{}
// The config file will define a rule named adding-full-directory
if err := c.Load("./testdata/config/example_custom.yml"); err != nil {
	panic(err)
}

d := Docked{
	Config:                   c,
	SuppressBuildKitWarnings: true,
}

result, err := d.Analyze("./testdata/minimal_custom.dockerfile")
if err != nil {
	panic("Failed to analyze dockerfile")
}

// programmatically consume array of evaluated and/or not-evaluated rules
printEvaluated(result.Evaluated)
Output:

D0:adding-full-directory - Failure * [ 7] ADD . /go/src/app
D5:no-debian-frontend - Success
D5:secret-aws-access-key - Success
D5:secret-aws-secret-access-key - Success
DC:avoid-sudo - Success
DC:consider-multistage - Success
DC:curl-without-fail - Success
DC:gpg-without-batch - Success
DC:layered-ownership-change - Success

func (*Docked) AnalyzeWithRuleList

func (d *Docked) AnalyzeWithRuleList(location string, configuredRules ConfiguredRules) (AnalysisResult, error)

AnalyzeWithRuleList is just like Analyze, but accepts an additional parameter of ConfiguredRules

This allows programmatic evaluation of rules without the ignore/priority overrides done as a default within Analyze.

Returns the AnalysisResult or error.

Example

ExampleDocked_AnalyzeWithRuleList provides an example of programmatically invoking Docked.AnalyzeWithRuleList with user-defined rules. See also reporter.TextReporter and reporter.HTMLReporter for in-built output formatters.

d := Docked{}

// user can extend default rule set or define their own
activeRules := rules.RuleList{}
myRule := validations.SimpleRegexRule{
	Name:     "no-distroless",
	Pattern:  `\bgcr\.io/distroless\b`,
	Priority: model.CriticalPriority,
	Command:  commands.From,
}
activeRules.AddRule(myRule)

result, err := d.AnalyzeWithRuleList("./testdata/minimal.dockerfile", ConfiguredRules{Active: activeRules})
if err != nil {
	panic("Failed to analyze dockerfile")
}

// programmatically consume array of evaluated and/or not-evaluated rules
printEvaluated(result.Evaluated)
Output:

D7:no-distroless - Success
D7:no-distroless - Failure * [13] FROM gcr.io/distroless/base-debian10

type RuleOverrides

type RuleOverrides []ConfigRuleOverride

RuleOverrides is a slice of ConfigRuleOverride. This type allows for simpler definitions and YAML parsing.

func (*RuleOverrides) UnmarshalYAML

func (r *RuleOverrides) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements the interface necessary to have greater control over deserializing RuleOverrides

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL