Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Build secrets: keep credentials out of layers and exported caches

Last updated: 5 Oct 20266 min read
tutorial
AdvancedBy AITrove Editorial

A build may need a credential to fetch a private dependency. Passing it as a build argument, environment variable, copied file, or command literal can expose it in image metadata, layers, logs, or an exported cache. A dedicated build secret mount makes the value available only to a selected build step, but the command inside that step can still accidentally write the value into its output.

Operational decision

A settlement worker fetches a private module during image creation. Supply the read-only package token to the builder as a temporary secret mount and never copy the token into the build context. The Dockerfile fragment shows the mount shape without including a real credential; pair it with a CI secret source and a locked dependency set. Run the build with a disposable canary token. Search the final image filesystem, image history, provenance fields, build logs, and exported cache for that token. Revoke it after the test and repeat a clean build without cache to prove dependency resolution does not rely on stale credentials. If the fetch command writes an authenticated package URL or token into a config file, remove that file in the same build step and verify it did not enter an exported layer. Keep the runtime stage free of package-manager credentials and build tools.

dockerfile
FROM python:3.13-slim AS dependency-builder
WORKDIR /build
COPY requirements.lock .
RUN --mount=type=secret,id=package_token \
    PIP_INDEX_URL="$(cat /run/secrets/package_token)" \
    pip wheel --no-deps --wheel-dir /wheels -r requirements.lock
FROM python:3.13-slim
COPY --from=dependency-builder /wheels /wheels

Cost and verification

A clean builder and secret scanning add CI time. Keeping an external cache improves speed but creates another place to inspect and restrict. A secret mount limits automatic persistence; it does not sanitize the outputs of a command that prints or copies the secret. Rotate any token found in an artifact and rebuild from a clean context after removing the leak. Measure cache hit rate separately from security checks so a faster build is not mistaken for a safer one.

Common Mistakes

  • Do not use a build argument to carry a package credential.
  • Do not assume a secret mount prevents the build command from copying the value out.
  • Do not verify only the final filesystem while ignoring history, logs, and cache.

Connected lessons

Practice and check

devops
operations
Storage details