🐳 Fix a Build Secret Leaking Into a Cached Layer
Docker’s build cache stores every layer by the exact filesystem diff it produced, and that’s true whether a file written during that layer was deleted later in the same RUN instruction or not – the cache is keyed on the instruction, not on the final state of the filesystem. A RUN instruction that writes a secret to a file, uses it, and then removes it in the same line is cached once and reused on every subsequent build whose earlier instructions haven’t changed, which means that cached layer’s diff can still be pulled apart with docker history –no-trunc or docker save to recover the secret, even though the final image’s visible filesystem never shows the file at all.
🔎 The Problem
ARG NPM_TOKEN
RUN echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc \
&& npm install \
&& rm .npmrc
# .npmrc is gone from the final image filesystem - but the build cache
# still holds this exact layer's diff from the last time it ran, and a
# `docker build --cache-from registry/myimage:buildcache` on CI reuses
# it layer-for-layer without ever re-running the RUN instruction
✅ Fix: Use BuildKit’s Secret Mounts
- Switch the secret from a build ARG to BuildKit’s dedicated mechanism: RUN –mount=type=secret,id=npmtoken cat /run/secrets/npmtoken > .npmrc && npm install, built with docker build –secret id=npmtoken,src=./token.txt – BuildKit mounts the secret into an ephemeral location that never becomes part of any cached layer’s filesystem diff.
- If a remote build cache was ever populated before the migration, invalidate or rebuild it explicitly (a cache-busting ARG, or simply deleting the old cache image) rather than assuming switching the Dockerfile alone retroactively cleans layers already sitting in a shared registry-backed cache.
- Rotate any token that was ever baked into a build this way – removing the file from the Dockerfile doesn’t remove it from history that’s already been pushed, pulled, or cached anywhere.
🚨 Why This Is Dangerous
A secret that never appears in docker inspect or the final container’s filesystem can still be sitting in plain sight inside a cached layer, and a shared CI build cache is exactly the kind of place other pipelines, other teams, or a compromised cache backend get to read from.
BuildKit’s secret mounts exist because a RUN instruction’s cache doesn’t know the difference between a file you deleted and a file that was never there – only one of those is actually safe.




