diff --git a/README.md b/README.md index abc4ff5..2d0ee61 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,10 @@ rule offers an editor suggestion instead. | [`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 | +| [`prefer-exec-form`](./docs/rules/prefer-exec-form.md) | DL3025 | Use the exec (JSON array) form for `CMD` and `ENTRYPOINT` | ✅ | warn | + +Fixable rules only autofix when the rewrite is unambiguous — for example, +`prefer-exec-form` leaves commands that rely on shell features alone. ## Configuration comments diff --git a/docs/rules/prefer-exec-form.md b/docs/rules/prefer-exec-form.md new file mode 100644 index 0000000..ab56c0f --- /dev/null +++ b/docs/rules/prefer-exec-form.md @@ -0,0 +1,96 @@ +# prefer-exec-form + +Require the exec (JSON array) form for `CMD` and `ENTRYPOINT`. + +## Background + +`CMD` and `ENTRYPOINT` accept two forms: + +```dockerfile +# shell form +CMD npm start + +# exec form +CMD ["npm", "start"] +``` + +The shell form wraps the command in `/bin/sh -c`, so the shell — not your +program — becomes PID 1. Signals such as the SIGTERM sent by +`docker stop` go to the shell and are typically not forwarded, which +means containers take the full stop timeout and are then killed. The +exec form runs the program directly, so it receives signals and shuts +down cleanly. The two forms also compose differently: with an exec-form +`ENTRYPOINT`, a shell-form `CMD` is appended as the shell invocation +followed by the command (`/bin/sh -c "npm start"`) rather than as the +command's own words, and a shell-form `ENTRYPOINT` ignores `CMD` +entirely. + +## Rule Details + +This rule warns when a `CMD` or `ENTRYPOINT` instruction uses the shell +form. When the command is a simple sequence of words with no shell +features (variables, quoting, pipes, redirection, leading environment +assignments, escaped whitespace, or shell builtins such as `exec`), the +rule fixes it by rewriting the command as a JSON array. Commands that rely +on shell features are reported without a fix, since converting them +requires deciding how to handle the shell. Commands that start with a +builtin whose external program behaves differently, such as `echo` or +`printf`, are also reported without a fix; use a full path such as +`/usr/bin/echo` to choose the program explicitly. + +The rule also reports without a fix when: + +- a `SHELL` instruction appears earlier in the file, because the command + may be written for that shell (for example, PowerShell cmdlets) rather + than being an executable, +- the stage targets Windows (a `--platform=windows/...` flag or a Windows + base image), because the default shell there is `cmd.exe`, +- the instruction is an `ENTRYPOINT` in a stage that sets `CMD`, or that + a later stage builds on and sets `CMD` without replacing the + `ENTRYPOINT`, because an exec-form `ENTRYPOINT` receives `CMD` as + arguments while the shell form ignores it, or +- the instruction is an `ONBUILD` trigger, because the downstream build + determines whether the conversion is safe. + +The rule cannot see `SHELL` instructions in external base images. If a +base image changes the default shell, disable the fix for that file. + +`RUN` instructions are not checked; the shell form is the normal way to +write them. + +Examples of **incorrect** code for this rule: + +```dockerfile +# eslint docker/prefer-exec-form: "error" + +FROM node:20 +ENTRYPOINT /docker-entrypoint.sh +CMD npm start +``` + +Examples of **correct** code for this rule: + +```dockerfile +# eslint docker/prefer-exec-form: "error" + +FROM node:20 +ENTRYPOINT ["/docker-entrypoint.sh"] +CMD ["npm", "start"] +``` + +## Options + +This rule has no options. + +## When Not to Use It + +If a `CMD` or `ENTRYPOINT` genuinely needs shell processing — environment +variable expansion, for example — the shell form is legitimate. Consider +making the shell explicit (`CMD ["sh", "-c", "..."]`), or disable this +rule for that line with a configuration comment. + +## Prior Art + +- [hadolint DL3025](https://github.com/hadolint/hadolint/wiki/DL3025) +- [`JSONArgsRecommended`](https://docs.docker.com/reference/build-checks/json-args-recommended/) + build check diff --git a/src/index.spec.ts b/src/index.spec.ts index ea2e844..5ab43f2 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -37,6 +37,7 @@ describe("plugin", () => { "no-maintainer", "no-sudo", "prefer-copy-over-add", + "prefer-exec-form", ]); }); diff --git a/src/index.ts b/src/index.ts index 92677fa..43ba2e5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,6 +16,7 @@ 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"; +import preferExecForm from "./rules/prefer-exec-form.js"; const rules = { "consistent-instruction-casing": consistentInstructionCasing, @@ -25,6 +26,7 @@ const rules = { "no-maintainer": noMaintainer, "no-sudo": noSudo, "prefer-copy-over-add": preferCopyOverAdd, + "prefer-exec-form": preferExecForm, }; const plugin = { @@ -56,6 +58,7 @@ const plugin = { "docker/no-maintainer": "error", "docker/no-sudo": "error", "docker/prefer-copy-over-add": "error", + "docker/prefer-exec-form": "warn", } as const, }, }, diff --git a/src/rules/prefer-exec-form.spec.ts b/src/rules/prefer-exec-form.spec.ts new file mode 100644 index 0000000..51be8a2 --- /dev/null +++ b/src/rules/prefer-exec-form.spec.ts @@ -0,0 +1,183 @@ +/** + * @fileoverview Tests for the prefer-exec-form rule. + */ + +import { RuleTester } from "eslint"; +import { DockerFileLanguage } from "../languages/docker-language.js"; +import rule from "./prefer-exec-form.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-exec-form", rule as never, { + valid: [ + 'CMD ["node", "app.js"]', + 'ENTRYPOINT ["/docker-entrypoint.sh"]', + // RUN legitimately uses the shell form. + "RUN apt-get update", + "CMD", + ], + invalid: [ + { + code: "CMD npm start", + output: 'CMD ["npm", "start"]', + errors: [ + { + messageId: "useExecForm", + data: { keyword: "CMD" }, + line: 1, + column: 5, + endColumn: 14, + }, + ], + }, + { + code: "ENTRYPOINT /docker-entrypoint.sh", + output: 'ENTRYPOINT ["/docker-entrypoint.sh"]', + errors: [ + { + messageId: "useExecForm", + data: { keyword: "ENTRYPOINT" }, + }, + ], + }, + { + // Shell features prevent a safe autofix. + code: "CMD node app.js > /var/log/app.log", + output: null, + errors: [{ messageId: "useExecForm" }], + }, + { + code: "CMD echo $HOME", + output: null, + errors: [{ messageId: "useExecForm" }], + }, + { + code: 'CMD echo "hello world"', + output: null, + errors: [{ messageId: "useExecForm" }], + }, + // cmd.exe expands %VAR% in the shell form only. + { + code: "CMD ping %COMPUTERNAME%", + output: null, + errors: [{ messageId: "useExecForm" }], + }, + // A leading assignment is an environment variable, not a command. + { + code: "CMD NODE_ENV=production node app.js", + output: null, + errors: [{ messageId: "useExecForm" }], + }, + // Shell builtins cannot be executed from the exec form. + { + code: "ENTRYPOINT exec /app/server", + output: null, + errors: [{ messageId: "useExecForm" }], + }, + { + code: "CMD . /env.sh", + output: null, + errors: [{ messageId: "useExecForm" }], + }, + // After SHELL, the command may need that shell. + { + code: 'SHELL ["powershell", "-command"]\nCMD Write-Host hello', + output: null, + errors: [{ messageId: "useExecForm" }], + }, + { + code: 'FROM base AS a\nSHELL ["pwsh", "-c"]\nFROM a\nCMD Write-Host hello', + output: null, + errors: [{ messageId: "useExecForm" }], + }, + // SHELL after the instruction does not apply to it. + { + code: 'CMD npm start\nSHELL ["/bin/bash", "-c"]', + output: 'CMD ["npm", "start"]\nSHELL ["/bin/bash", "-c"]', + errors: [{ messageId: "useExecForm" }], + }, + // An exec-form ENTRYPOINT would start receiving CMD as arguments. + { + code: 'ENTRYPOINT /bin/sleep 60\nCMD ["--invalid"]', + output: null, + errors: [{ messageId: "useExecForm" }], + }, + { + code: 'CMD ["--invalid"]\nENTRYPOINT /bin/sleep 60', + output: null, + errors: [{ messageId: "useExecForm" }], + }, + // CMD in another stage does not apply. + { + code: 'FROM a\nCMD ["--invalid"]\nFROM b\nENTRYPOINT /bin/sleep 60', + output: 'FROM a\nCMD ["--invalid"]\nFROM b\nENTRYPOINT ["/bin/sleep", "60"]', + errors: [{ messageId: "useExecForm" }], + }, + // A later stage built on this one inherits the ENTRYPOINT. + { + code: 'FROM alpine AS base\nENTRYPOINT /bin/sleep 60\nFROM base\nCMD ["--invalid"]', + output: null, + errors: [{ messageId: "useExecForm" }], + }, + // A child stage that replaces the ENTRYPOINT does not block the fix. + { + code: 'FROM alpine AS base\nENTRYPOINT /bin/sleep 60\nFROM base\nENTRYPOINT ["/bin/true"]\nCMD ["x"]', + output: 'FROM alpine AS base\nENTRYPOINT ["/bin/sleep", "60"]\nFROM base\nENTRYPOINT ["/bin/true"]\nCMD ["x"]', + errors: [{ messageId: "useExecForm" }], + }, + // A bracket that does not start a JSON array is shell form. + { + code: "CMD [ -f /ready ]", + output: null, + errors: [{ messageId: "useExecForm" }], + }, + // The external echo may behave differently from the builtin. + { + code: "CMD echo -e ready", + output: null, + errors: [{ messageId: "useExecForm" }], + }, + { + code: "CMD /usr/bin/echo ready", + output: 'CMD ["/usr/bin/echo", "ready"]', + errors: [{ messageId: "useExecForm" }], + }, + // An escaped blank keeps two words together. + { + code: "CMD /bin/cat report\\ final.txt", + output: null, + errors: [{ messageId: "useExecForm" }], + }, + // Windows images use cmd.exe as the default shell. + { + code: "FROM mcr.microsoft.com/windows/servercore:ltsc2022\nCMD dir", + output: null, + errors: [{ messageId: "useExecForm" }], + }, + { + code: "FROM --platform=windows/amd64 example/app\nCMD dir", + output: null, + errors: [{ messageId: "useExecForm" }], + }, + // ONBUILD triggers are reported without a fix. + { + code: "ONBUILD CMD /app/start", + output: null, + errors: [{ messageId: "useExecForm", column: 13 }], + }, + // Arguments that are not assignments still convert. + { + code: "CMD node app.js --port=8080", + output: 'CMD ["node", "app.js", "--port=8080"]', + errors: [{ messageId: "useExecForm" }], + }, + ], +}); diff --git a/src/rules/prefer-exec-form.ts b/src/rules/prefer-exec-form.ts new file mode 100644 index 0000000..e44e327 --- /dev/null +++ b/src/rules/prefer-exec-form.ts @@ -0,0 +1,312 @@ +/** + * @fileoverview Rule to prefer the exec (JSON array) form for CMD and + * ENTRYPOINT. The shell form wraps the command in `/bin/sh -c`, which + * swallows signals such as SIGTERM. + */ + +//------------------------------------------------------------------------------ +// Imports +//------------------------------------------------------------------------------ + +import type { + CmdInstructionNode, + DockerRuleDefinition, + EntrypointInstructionNode, + InstructionNode, +} from "../types.js"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Tokens that can safely be converted into a JSON array element: no shell + * metacharacters, quotes, or variable expansions (including Windows + * `%VAR%` expansion in cmd.exe). + */ +const SAFE_TOKEN = /^[\w./:=@+,-]+$/u; + +/** + * A leading `NAME=value` word, which the shell treats as an environment + * assignment for the command rather than as the command itself. + */ +const ASSIGNMENT = /^[A-Za-z_]\w*=/u; + +/** + * Shell builtins that have no executable equivalent, so they cannot be + * run from the exec form. + */ +const SHELL_BUILTINS = new Set([ + ".", + ":", + "alias", + "bg", + "break", + "builtin", + "cd", + "command", + "continue", + "declare", + "eval", + "exec", + "exit", + "export", + "fg", + "getopts", + "hash", + "jobs", + "let", + "local", + "read", + "readonly", + "return", + "set", + "shift", + "source", + "times", + "trap", + "type", + "typeset", + "ulimit", + "umask", + "unalias", + "unset", + "wait", +]); + +/** + * Shell builtins whose external executable behaves differently, such as + * `echo -e`, which dash's builtin prints literally but GNU `echo` + * interprets. Converting these changes the program that runs. + */ +const AMBIGUOUS_BUILTINS = new Set([ + "[", + "echo", + "false", + "kill", + "printf", + "pwd", + "test", + "true", +]); + +/** + * Image references and platforms that indicate a Windows image, where the + * default shell is `cmd.exe` rather than a POSIX shell. + */ +const WINDOWS_IMAGE = /(?:^|\/)(?:windows|servercore|nanoserver)(?:[/:@]|$)/iu; +const WINDOWS_PLATFORM = /^windows(?:\/|$)/iu; + +/** + * Information about a build stage needed to decide whether a fix is safe. + */ +interface StageInfo { + instructions: InstructionNode[]; + name: string | null; + base: string | null; + windows: boolean; + hasCmd: boolean; + hasEntrypoint: boolean; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const rule: DockerRuleDefinition<{ MessageIds: "useExecForm" }> = { + meta: { + type: "suggestion", + docs: { + description: + "Require the exec (JSON array) form for `CMD` and `ENTRYPOINT`", + recommended: true, + url: "https://github.com/eslint/docker/blob/main/docs/rules/prefer-exec-form.md", + }, + fixable: "code", + schema: [], + messages: { + useExecForm: "Use the exec (JSON array) form for {{keyword}}.", + }, + }, + + /** + * Creates the rule's visitor. + * @param context The rule context. + * @returns A visitor that checks the CMD and ENTRYPOINT instructions of + * the whole Dockerfile. + */ + create(context) { + const { sourceCode } = context; + + /** + * Reports a shell-form CMD or ENTRYPOINT. + * @param node The instruction to check. + * @param fixAllowed Whether the instruction's context permits a + * fix at all. It does not when a SHELL instruction may apply, the + * stage targets Windows, the instruction is an ONBUILD trigger, + * or an exec-form ENTRYPOINT would start receiving a CMD. + */ + function check( + node: CmdInstructionNode | EntrypointInstructionNode, + fixAllowed: boolean, + ): void { + const { command } = node; + + if (command?.type !== "ShellForm") { + return; + } + + // Commands relying on shell features (variables, pipes, + // redirection, quoting, escaped whitespace, environment + // assignments, builtins) cannot be converted automatically. + const first = command.arguments[0]?.value ?? ""; + const canFix = + fixAllowed && + !ASSIGNMENT.test(first) && + !SHELL_BUILTINS.has(first) && + !AMBIGUOUS_BUILTINS.has(first) && + command.arguments.every( + (argument, index) => + SAFE_TOKEN.test(argument.value) && + SAFE_TOKEN.test( + sourceCode.text.slice(argument.start, argument.end), + ) && + // Only plain blanks may separate words; an escaped + // blank (`report\ final.txt`) joins them. + (index === 0 || + /^[ \t]+$/u.test( + sourceCode.text.slice( + command.arguments[index - 1]?.end, + argument.start, + ), + )), + ); + + context.report({ + node: command, + messageId: "useExecForm", + data: { keyword: node.keyword }, + fix: canFix + ? fixer => + fixer.replaceTextRange( + [command.start, command.end], + `[${command.arguments + .map(argument => + JSON.stringify(argument.value), + ) + .join(", ")}]`, + ) + : undefined, + }); + } + + return { + /** + * Reports each shell-form CMD and ENTRYPOINT, deciding per build + * stage whether a fix is safe. + * @param node The root node of the Dockerfile. + */ + Dockerfile(node) { + // Group instructions into build stages, each starting at + // a FROM instruction. + const stages: StageInfo[] = [ + { + instructions: [], + name: null, + base: null, + windows: false, + hasCmd: false, + hasEntrypoint: false, + }, + ]; + + for (const instruction of node.body) { + if (instruction.type === "FromInstruction") { + const platform = instruction.flags.find( + flag => flag.name === "platform", + ); + const base = instruction.image?.name ?? null; + + stages.push({ + instructions: [], + name: instruction.alias?.name.toLowerCase() ?? null, + base: base?.toLowerCase() ?? null, + windows: + (base !== null && WINDOWS_IMAGE.test(base)) || + WINDOWS_PLATFORM.test(platform?.value ?? ""), + hasCmd: false, + hasEntrypoint: false, + }); + } + + const stage = stages.at(-1) as StageInfo; + + stage.instructions.push(instruction); + stage.hasCmd ||= instruction.type === "CmdInstruction"; + stage.hasEntrypoint ||= + instruction.type === "EntrypointInstruction"; + } + + /** + * Returns whether a stage's ENTRYPOINT would receive a CMD, + * either from the stage itself or from a later stage that + * builds on it without replacing the ENTRYPOINT. + * @param index The index of the stage in `stages`. + * @returns `true` if the stage's ENTRYPOINT would receive a + * CMD. + */ + function receivesCmd(index: number): boolean { + const stage = stages[index] as StageInfo; + + if (stage.hasCmd) { + return true; + } + + return stages.some( + (child, childIndex) => + childIndex > index && + stage.name !== null && + child.base === stage.name && + !child.hasEntrypoint && + receivesCmd(childIndex), + ); + } + + // A stage can inherit SHELL from an earlier stage, so any + // preceding SHELL instruction counts. Windows images use + // cmd.exe, so the POSIX fix checks do not apply to them. + let customShell = false; + + stages.forEach((stage, index) => { + for (const instruction of stage.instructions) { + if (instruction.type === "ShellInstruction") { + customShell = true; + } else if (instruction.type === "CmdInstruction") { + check(instruction, !customShell && !stage.windows); + } else if ( + instruction.type === "EntrypointInstruction" + ) { + check( + instruction, + !customShell && + !stage.windows && + !receivesCmd(index), + ); + } else if ( + instruction.type === "OnbuildInstruction" && + (instruction.trigger?.type === "CmdInstruction" || + instruction.trigger?.type === + "EntrypointInstruction") + ) { + // The downstream build decides whether the + // conversion is safe, so report without a fix. + check(instruction.trigger, false); + } + } + }); + }, + }; + }, +}; + +export default rule;