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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ export default defineConfig([

## Rules

Each rule mirrors a well-known hadolint check or Docker best practice.
Each rule mirrors a well-known hadolint check or Docker best practice. In the
Fixable column, ✅ means `eslint --fix` fixes the problem and 💡 means the
rule offers an editor suggestion instead.

| Rule | hadolint | Description | Fixable | Recommended |
| -------------------------------------------------------------------------------- | ------------- | --------------------------------------------------------------------- | ------- | ----------- |
Expand All @@ -74,6 +76,7 @@ Each rule mirrors a well-known hadolint check or Docker best practice.
| [`no-duplicate-instructions`](./docs/rules/no-duplicate-instructions.md) | DL4003/DL4004 | Only one `CMD`, `ENTRYPOINT`, or `HEALTHCHECK` per stage takes effect | | error |
| [`no-maintainer`](./docs/rules/no-maintainer.md) | DL4000 | `MAINTAINER` is deprecated; use a `maintainer` `LABEL` | ✅ | error |
| [`no-sudo`](./docs/rules/no-sudo.md) | DL3004 | Don't use `sudo` in `RUN`; switch users with `USER` | | error |
| [`prefer-copy-over-add`](./docs/rules/prefer-copy-over-add.md) | DL3020 | Use `COPY` unless you need `ADD`'s URL or archive handling | 💡 | error |

## Configuration comments

Expand Down
70 changes: 70 additions & 0 deletions docs/rules/prefer-copy-over-add.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# prefer-copy-over-add

Require `COPY` instead of `ADD` for local files and directories.

## Background

`COPY` and `ADD` both copy files into the image, but `ADD` has two extra
behaviors: it can download remote URLs, and it automatically extracts
recognized archive formats. Those behaviors are implicit — a reader
cannot tell from `ADD app.tar.gz /opt/` whether the archive ends up
extracted or copied without knowing `ADD`'s rules — and they have been the
source of security issues with attacker-controlled archives.

The Docker documentation recommends `COPY` for the common case of copying
local files, reserving `ADD` for the cases that actually need it.

## Rule Details

This rule warns when an `ADD` instruction copies local, non-archive
sources, and suggests replacing `ADD` with `COPY`. The replacement is a
suggestion rather than an automatic fix because Docker recognizes archives
by their contents, not their file names: a local archive without an
archive extension is still extracted by `ADD`, so check the sources before
applying it. The rule does not warn when `ADD`'s extra behavior may be
intended:

- a source is a remote URL (`https://...`) or a Git reference (`git@...`),
- a source looks like an archive (`.tar`, `.tar.gz`, `.tgz`, `.tar.bz2`,
`.tar.xz`, `.tar.zst`, and similar),
- the instruction uses an ADD-only flag (`--checksum`, `--keep-git-dir`,
or `--unpack`), or
- a source contains a variable reference, a wildcard, quotes, or escapes,
which cannot be checked.

Examples of **incorrect** code for this rule:

```dockerfile
# eslint docker/prefer-copy-over-add: "error"

FROM node:20
ADD src/ /app/src/
ADD --chown=node:node package.json /app/
```

Examples of **correct** code for this rule:

```dockerfile
# eslint docker/prefer-copy-over-add: "error"

FROM node:20
COPY src/ /app/src/
ADD https://example.com/release.tar.gz /tmp/
ADD rootfs.tar.gz /
ADD --checksum=sha256:24454f830cdb571e2c4ad15481119c43b3cafd48dd869a9b2945d1036d1dc68d https://example.com/tool.tar.gz /opt/
```

## Options

This rule has no options.

## When Not to Use It

If you rely on `ADD` behavior this rule cannot detect — for example,
extracting an archive whose name has no recognizable extension — disable
the rule for that line with a configuration comment.

## Prior Art

- [hadolint DL3020](https://github.com/hadolint/hadolint/wiki/DL3020)
- [Dockerfile best practices: `ADD` or `COPY`](https://docs.docker.com/build/building/best-practices/#add-or-copy)
1 change: 1 addition & 0 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ describe("plugin", () => {
"no-duplicate-instructions",
"no-maintainer",
"no-sudo",
"prefer-copy-over-add",
]);
});

Expand Down
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import noCdInRun from "./rules/no-cd-in-run.js";
import noDuplicateInstructions from "./rules/no-duplicate-instructions.js";
import noMaintainer from "./rules/no-maintainer.js";
import noSudo from "./rules/no-sudo.js";
import preferCopyOverAdd from "./rules/prefer-copy-over-add.js";

const rules = {
"consistent-instruction-casing": consistentInstructionCasing,
Expand All @@ -23,6 +24,7 @@ const rules = {
"no-duplicate-instructions": noDuplicateInstructions,
"no-maintainer": noMaintainer,
"no-sudo": noSudo,
"prefer-copy-over-add": preferCopyOverAdd,
};

const plugin = {
Expand Down Expand Up @@ -53,6 +55,7 @@ const plugin = {
"docker/no-duplicate-instructions": "error",
"docker/no-maintainer": "error",
"docker/no-sudo": "error",
"docker/prefer-copy-over-add": "error",
} as const,
},
},
Expand Down
123 changes: 123 additions & 0 deletions src/rules/prefer-copy-over-add.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/**
* @fileoverview Tests for the prefer-copy-over-add rule.
*/

import { RuleTester } from "eslint";
import { DockerFileLanguage } from "../languages/docker-language.js";
import rule from "./prefer-copy-over-add.js";

const ruleTester = new RuleTester({
plugins: {
docker: {
languages: { dockerfile: new DockerFileLanguage() },
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- plugin shape is validated by ESLint at runtime.
} as any,
language: "docker/dockerfile",
});

ruleTester.run("prefer-copy-over-add", rule as never, {
valid: [
"COPY src/ /app/",
// URLs require ADD.
"ADD https://example.com/file.tar.gz /tmp/",
"ADD git@github.com:user/repo.git /src/",
"ADD deploy@code.example.org:team/repo.git /src/",
// Archives are auto-extracted by ADD.
"ADD rootfs.tar.gz /",
"ADD layer.tar /",
"ADD app.tgz /opt/",
// ADD-only flags.
"ADD --checksum=sha256:abc123 files/ /app/",
"ADD --keep-git-dir=true repo /src/",
"ADD --unpack=false file.txt /app/",
// Trailing slashes are ignored when resolving sources.
"ADD rootfs.tar.gz/ /",
"ADD rootfs.tar.gz/. /",
"ADD rootfs.tar.gz//./ /",
// Variable sources cannot be checked.
"ADD $ARTIFACT /app/",
// Wildcards may match archives.
"ADD *.tar.* /out/",
"ADD layer?.bin /out/",
// Quoted and escaped sources are not resolved.
'ADD "rootfs.tar.gz" /',
"ADD 'https://example.com/file' /tmp/",
"ADD rootfs\\.tar.gz /",
'ADD ["rootfs\\u002etar.gz", "/"]',
"ADD",
],
invalid: [
{
// A long run of slashes inside a source is checked in linear
// time.
code: `ADD src${"/".repeat(64)}file /app/`,
output: null,
errors: [
{
messageId: "useCopy",
suggestions: [
{
messageId: "replaceWithCopy",
output: `COPY src${"/".repeat(64)}file /app/`,
},
],
},
],
},
{
// A keyword split by a line continuation gets no suggestion.
code: "AD\\\nD src/ /app/",
output: null,
errors: [{ messageId: "useCopy", suggestions: [] }],
},
{
code: "ADD src/ /app/",
output: null,
errors: [
{
messageId: "useCopy",
line: 1,
column: 1,
endColumn: 15,
suggestions: [
{
messageId: "replaceWithCopy",
output: "COPY src/ /app/",
},
],
},
],
},
{
code: "ADD --chown=node:node src/ lib/ /app/",
output: null,
errors: [
{
messageId: "useCopy",
suggestions: [
{
messageId: "replaceWithCopy",
output: "COPY --chown=node:node src/ lib/ /app/",
},
],
},
],
},
{
code: "add config.json /etc/app/config.json",
output: null,
errors: [
{
messageId: "useCopy",
suggestions: [
{
messageId: "replaceWithCopy",
output: "COPY config.json /etc/app/config.json",
},
],
},
],
},
],
});
144 changes: 144 additions & 0 deletions src/rules/prefer-copy-over-add.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/**
* @fileoverview Rule to prefer COPY over ADD for local files and
* directories. ADD is only needed for remote URLs and automatic archive
* extraction.
*/

//------------------------------------------------------------------------------
// Imports
//------------------------------------------------------------------------------

import type { DockerRuleDefinition } from "../types.js";

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const URL_SOURCE = /^[a-z][a-z0-9+.-]*:\/\//iu;
/** An SCP-style Git reference such as `deploy@example.org:team/repo.git`. */
const GIT_SOURCE = /^[\w.-]+@[\w.-]+:/u;
const ARCHIVE_SOURCE = /\.(?:tar|tgz|txz|tbz2?|tar\.(?:gz|bz2|xz|zst))$/iu;

/**
* Sources whose meaning depends on expansion or quoting: variables,
* wildcards, and quotes.
*/
const UNRESOLVED_SOURCE = /[$*?[\]"']/u;

/**
* Removes trailing `/` and `/.` segments from a path, so `dir/` becomes
* `dir` and `archive.tar.gz/.` becomes `archive.tar.gz`. A loop keeps
* this linear in the length of the path.
*/
function removeTrailingSeparators(path: string): string {
let end = path.length;

for (;;) {
if (path[end - 1] === "/") {
end--;
} else if (path[end - 1] === "." && path[end - 2] === "/") {
end -= 2;
} else {
return path.slice(0, end);
}
}
}

/** Flags that COPY does not support. */
const ADD_ONLY_FLAGS = new Set(["checksum", "keep-git-dir", "unpack"]);

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

const rule: DockerRuleDefinition<{
MessageIds: "useCopy" | "replaceWithCopy";
}> = {
meta: {
type: "suggestion",
docs: {
description:
"Require `COPY` instead of `ADD` for local files and directories",
recommended: true,
url: "https://github.com/eslint/docker/blob/main/docs/rules/prefer-copy-over-add.md",
},
hasSuggestions: true,
schema: [],
messages: {
useCopy: "Use COPY instead of ADD for local files and directories.",
replaceWithCopy: "Replace ADD with COPY.",
},
},

create(context) {
const { sourceCode } = context;

return {
AddInstruction(node) {
if (node.sources.length === 0) {
return;
}

// These flags only exist on ADD.
if (node.flags.some(flag => ADD_ONLY_FLAGS.has(flag.name))) {
return;
}

// ADD is legitimately needed for URLs and archives. Sources
// that cannot be classified from their literal text
// (variables, wildcards, quoting, and escapes) are skipped.
if (
node.sources.some(source => {
const { value } = source;
// `archive.tar.gz/.` and `archive.tar.gz/` name the
// same file as `archive.tar.gz`.
const path = removeTrailingSeparators(value);

return (
URL_SOURCE.test(value) ||
GIT_SOURCE.test(value) ||
ARCHIVE_SOURCE.test(path) ||
UNRESOLVED_SOURCE.test(value) ||
sourceCode.text
.slice(source.start, source.end)
.includes("\\")
);
})
) {
return;
}

// Docker detects archives by their contents, not their
// names, so a local source without an archive extension
// may still be extracted by ADD. The replacement is
// therefore offered as a suggestion rather than a fix. A
// keyword split by a line continuation is not contiguous,
// so it gets no suggestion.
const keywordEnd = node.start + node.keyword.length;
const keywordIsContiguous =
sourceCode.text
.slice(node.start, keywordEnd)
.toUpperCase() === node.keyword;

context.report({
node,
messageId: "useCopy",
suggest: keywordIsContiguous
? [
{
messageId: "replaceWithCopy",
fix: fixer =>
fixer.replaceTextRange(
[node.start, keywordEnd],
"COPY",
),
},
]
: [],
});
},
};
},
};

export default rule;
Loading