diff --git a/README.md b/README.md index 2d0ee61..af45bb4 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ rule offers an editor suggestion instead. | [`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 | +| [`require-absolute-workdir`](./docs/rules/require-absolute-workdir.md) | DL3000 | `WORKDIR` paths must be absolute | | error | Fixable rules only autofix when the rewrite is unambiguous — for example, `prefer-exec-form` leaves commands that rely on shell features alone. diff --git a/docs/rules/require-absolute-workdir.md b/docs/rules/require-absolute-workdir.md new file mode 100644 index 0000000..9b50c43 --- /dev/null +++ b/docs/rules/require-absolute-workdir.md @@ -0,0 +1,70 @@ +# require-absolute-workdir + +Require `WORKDIR` paths to be absolute. + +## Background + +A relative `WORKDIR` is resolved against the previous `WORKDIR`, so its +meaning depends on everything that came before it — including `WORKDIR` +instructions inherited from the base image: + +```dockerfile +# a base image whose WORKDIR might be anything +FROM some-base +# …/app, wherever that is +WORKDIR app +``` + +If the base image changes its working directory, the build breaks or, +worse, silently writes files to the wrong place. An absolute path always +means the same thing. + +## Rule Details + +This rule warns when a `WORKDIR` path is not absolute. Unix paths starting +with `/`, Windows paths starting with a drive letter (`C:/`), and paths +starting with a variable reference (`$NAME` or `${...}`) are accepted; +variable values cannot be checked statically. Quotes and Dockerfile escapes +are removed before the check. Docker does not expand `%NAME%` in `WORKDIR`, +so such paths are reported, as is an empty path (`WORKDIR ""`), which +keeps the previous working directory. A drive letter is not accepted in a +stage that explicitly targets Linux (`FROM --platform=linux/...`), where it +is an ordinary relative path component. + +Examples of **incorrect** code for this rule: + +```dockerfile +# eslint docker/require-absolute-workdir: "error" + +FROM node:20 +WORKDIR app +WORKDIR ./app +WORKDIR usr/src/app +``` + +Examples of **correct** code for this rule: + +```dockerfile +# eslint docker/require-absolute-workdir: "error" + +FROM node:20 +WORKDIR /usr/src/app +WORKDIR $APP_HOME +WORKDIR C:/app +``` + +## Options + +This rule has no options. + +## When Not to Use It + +If you deliberately use relative `WORKDIR` instructions to build paths in +steps (`WORKDIR /app` followed by `WORKDIR src`), you can disable this +rule, though writing the full path in each `WORKDIR` is clearer. + +## Prior Art + +- [hadolint DL3000](https://github.com/hadolint/hadolint/wiki/DL3000) +- [`WorkdirRelativePath`](https://docs.docker.com/reference/build-checks/workdir-relative-path/) + build check diff --git a/src/index.spec.ts b/src/index.spec.ts index 5ab43f2..ac80fc8 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -38,6 +38,7 @@ describe("plugin", () => { "no-sudo", "prefer-copy-over-add", "prefer-exec-form", + "require-absolute-workdir", ]); }); diff --git a/src/index.ts b/src/index.ts index 43ba2e5..9b725db 100644 --- a/src/index.ts +++ b/src/index.ts @@ -17,6 +17,7 @@ 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"; +import requireAbsoluteWorkdir from "./rules/require-absolute-workdir.js"; const rules = { "consistent-instruction-casing": consistentInstructionCasing, @@ -27,6 +28,7 @@ const rules = { "no-sudo": noSudo, "prefer-copy-over-add": preferCopyOverAdd, "prefer-exec-form": preferExecForm, + "require-absolute-workdir": requireAbsoluteWorkdir, }; const plugin = { @@ -59,6 +61,7 @@ const plugin = { "docker/no-sudo": "error", "docker/prefer-copy-over-add": "error", "docker/prefer-exec-form": "warn", + "docker/require-absolute-workdir": "error", } as const, }, }, diff --git a/src/rules/require-absolute-workdir.spec.ts b/src/rules/require-absolute-workdir.spec.ts new file mode 100644 index 0000000..ef81052 --- /dev/null +++ b/src/rules/require-absolute-workdir.spec.ts @@ -0,0 +1,148 @@ +/** + * @fileoverview Tests for the require-absolute-workdir rule. + */ + +import { RuleTester } from "eslint"; +import { DockerFileLanguage } from "../languages/docker-language.js"; +import rule from "./require-absolute-workdir.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("require-absolute-workdir", rule as never, { + valid: [ + "WORKDIR /app", + "WORKDIR /usr/src/app", + 'WORKDIR "/quoted path"', + // Quoted prefixes combine with the rest of the operand. + 'WORKDIR "/opt/my app"/src', + "WORKDIR '/opt'/src", + 'WORKDIR ""/app', + // Windows-style absolute paths. + "WORKDIR C:/app", + // Variables cannot be checked. + "WORKDIR $HOME", + 'WORKDIR "$HOME/app"', + "WORKDIR ${APP_DIR}", + "WORKDIR", + // Dockerfile escapes are removed before the check. + "WORKDIR \\/app", + 'WORKDIR "C:\\app"', + "# escape=`\nFROM scratch\nWORKDIR `/app", + // Comment lines inside a continuation are not part of the path. + 'WORKDIR ""\\\n# comment\n/app', + // Drive letters are absolute when the stage may target Windows. + "FROM --platform=windows/amd64 example/app\nWORKDIR C:/app", + "WORKDIR C:\\app", + ], + invalid: [ + { + // BuildKit does not expand %NAME% in WORKDIR. + code: "WORKDIR %APP_HOME%", + errors: [{ messageId: "expectedAbsolute" }], + }, + { + // An empty operand keeps the previous working directory. + code: 'WORKDIR ""', + errors: [{ messageId: "expectedAbsolute", data: { path: "" } }], + }, + { + // A drive letter is a relative path component on Linux. + code: "FROM --platform=linux/amd64 alpine\nWORKDIR C:/app", + errors: [{ messageId: "expectedAbsolute" }], + }, + { + // A $ without a variable name is kept literally. + code: "WORKDIR $/cache", + errors: [{ messageId: "expectedAbsolute" }], + }, + { + // $'...' is not expanded by Docker. + code: "WORKDIR $'HOME'/cache", + errors: [{ messageId: "expectedAbsolute" }], + }, + { + // Inside double quotes, the backslash before `/` is kept. + code: 'WORKDIR "\\/app"', + errors: [ + { messageId: "expectedAbsolute", data: { path: "\\/app" } }, + ], + }, + { + // Inside double quotes, an escaped $ is still literal. + code: 'WORKDIR "\\$HOME/app"', + errors: [ + { messageId: "expectedAbsolute", data: { path: "$HOME/app" } }, + ], + }, + { + // An escaped $ is literal. + code: "WORKDIR \\$HOME/app", + errors: [{ messageId: "expectedAbsolute" }], + }, + { + // Single-quoted variable references are literal. + code: "WORKDIR '$HOME'/app", + errors: [ + { messageId: "expectedAbsolute", data: { path: "$HOME/app" } }, + ], + }, + { + code: 'WORKDIR "my app"/src', + errors: [ + { messageId: "expectedAbsolute", data: { path: "my app/src" } }, + ], + }, + { + code: "WORKDIR app", + errors: [ + { + messageId: "expectedAbsolute", + data: { path: "app" }, + line: 1, + column: 9, + endColumn: 12, + }, + ], + }, + { + code: "WORKDIR ./app", + errors: [{ messageId: "expectedAbsolute" }], + }, + { + code: "WORKDIR usr/src/app", + errors: [{ messageId: "expectedAbsolute" }], + }, + { + code: 'WORKDIR "relative dir"', + errors: [{ messageId: "expectedAbsolute" }], + }, + { + // Leading whitespace inside quotes is part of the path. + code: 'WORKDIR " relative dir"', + errors: [ + { + messageId: "expectedAbsolute", + data: { path: " relative dir" }, + }, + ], + }, + { + // Single quotes suppress variable substitution. + code: "WORKDIR '$APP_HOME'", + errors: [{ messageId: "expectedAbsolute" }], + }, + { + // A lone percent sign is not a variable reference. + code: "WORKDIR %cache", + errors: [{ messageId: "expectedAbsolute" }], + }, + ], +}); diff --git a/src/rules/require-absolute-workdir.ts b/src/rules/require-absolute-workdir.ts new file mode 100644 index 0000000..f58d54d --- /dev/null +++ b/src/rules/require-absolute-workdir.ts @@ -0,0 +1,153 @@ +/** + * @fileoverview Rule to require WORKDIR paths to be absolute. Relative + * paths depend on the previous WORKDIR and break silently when earlier + * instructions change. + */ + +//------------------------------------------------------------------------------ +// Imports +//------------------------------------------------------------------------------ + +import type { DockerRuleDefinition } from "../types.js"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const WINDOWS_ABSOLUTE = /^[A-Za-z]:[\\/]/u; + +/** A character that can start a variable name after `$`. */ +const VARIABLE_START = /^[A-Za-z_{]/u; + +/** + * Removes quotes and Dockerfile escapes anywhere in a WORKDIR operand, the + * way Docker combines `"/opt/my app"/src` into `/opt/my app/src` and + * `\/app` into `/app`. Returns the resulting path and whether it starts + * with a variable reference that Docker expands: an unescaped `$` outside + * single quotes, directly followed by a variable name or `{`. + */ +function unquote( + raw: string, + escapeCharacter: string, +): { path: string; startsWithVariable: boolean } { + let path = ""; + let quote: string | null = null; + let startsWithVariable = false; + + for (let i = 0; i < raw.length; i++) { + const character = raw[i] as string; + + const next = raw[i + 1]; + + if ( + character === escapeCharacter && + next !== undefined && + (quote === null || + // Inside double quotes, the escape character is kept + // unless it escapes `"`, `$`, or itself. + (quote === '"' && + (next === '"' || next === "$" || next === escapeCharacter))) + ) { + // The escaped character is literal, including `$`. + i++; + path += raw[i]; + } else if (quote === null && (character === '"' || character === "'")) { + quote = character; + } else if (character === quote) { + quote = null; + } else { + if ( + path === "" && + character === "$" && + quote !== "'" && + VARIABLE_START.test(raw.slice(i + 1)) + ) { + startsWithVariable = true; + } + + path += character; + } + } + + return { path, startsWithVariable }; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const rule: DockerRuleDefinition<{ MessageIds: "expectedAbsolute" }> = { + meta: { + type: "problem", + docs: { + description: "Require `WORKDIR` paths to be absolute", + recommended: true, + url: "https://github.com/eslint/docker/blob/main/docs/rules/require-absolute-workdir.md", + }, + schema: [], + messages: { + expectedAbsolute: + "Use an absolute path for WORKDIR instead of '{{path}}'.", + }, + }, + + create(context) { + const { sourceCode } = context; + const escapeCharacter = + sourceCode.ast.directives.find( + directive => directive.name.toLowerCase() === "escape", + )?.value ?? "\\"; + + // Whether the current stage explicitly targets Linux, where a + // drive letter is an ordinary relative path component. + let linuxStage = false; + + return { + FromInstruction(node) { + const platform = node.flags.find( + flag => flag.name === "platform", + ); + + linuxStage = /^linux(?:\/|$)/iu.test(platform?.value ?? ""); + }, + + WorkdirInstruction(node) { + if (!node.path) { + return; + } + + // Remove quotes and escapes. Single quotes suppress + // variable substitution, so their contents are literal. + const { path, startsWithVariable } = unquote( + node.path.value, + escapeCharacter, + ); + + // An empty operand (`WORKDIR ""`) keeps the previous working + // directory, which is as fragile as a relative path. + const isAbsolute = + path.startsWith("/") || + // Windows paths such as `C:\app` are often written with + // the default escape character, so also check the + // operand without escape processing. + (!linuxStage && + (WINDOWS_ABSOLUTE.test(path) || + WINDOWS_ABSOLUTE.test( + unquote(node.path.value, "").path, + ))) || + // Variable references cannot be checked. + startsWithVariable; + + if (!isAbsolute) { + context.report({ + node: node.path, + messageId: "expectedAbsolute", + data: { path }, + }); + } + }, + }; + }, +}; + +export default rule;