Skip to content

build: hash-check the build backend in the image - #289

Merged
uniqueg merged 4 commits into
devfrom
build/282-hash-build-backend
Oct 29, 2026
Merged

uniqueg merged 4 commits into
devfrom
build/282-hash-build-backend

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #282.

The image build no longer downloads anything without a hash check:

  • The build requirements of the app (build-system.requires: setuptools, setuptools-scm) are now also a PEP 735 dependency group, build-system, so uv.lock locks them (and their dependencies vcs-versioning, packaging) with hashes. A test keeps the group and build-system.requires identical.
  • A new build stage (from the same pinned base image) exports that group with uv (mounted, as before), installs it with pip install --require-hashes --only-binary :all: --no-deps into a venv (pip from ensurepip, no download), and builds the wheel with pip wheel --no-index --no-build-isolation --check-build-dependencies under RUN --network=none.
  • The final stage installs only that wheel (--no-index --no-deps, --network=none, mounted from the build stage). The runtime dependency step is unchanged; scripts/image_requirements.py is untouched.
  • SETUPTOOLS_SCM_PRETEND_VERSION stays a build argument, now of the build stage; uv is still never in the image.

Why a dependency group (Dependabot): Dependabot's uv entry already maintains uv.lock; with the group in the lock, the build requirements are updated by the same entry and group (python-dependencies), with hashes, and no second ecosystem is needed. A hashed requirements.txt under Dependabot's pip ecosystem would add a second lock format, and a pip entry for / would also pick up pyproject.toml. uv's build-constraint-dependencies aren't hash-locked in uv.lock, so that wouldn't do.

Image contents: compared file by file (md5) with an image built from dev: identical, except cloud_registry-*.dist-info/direct_url.json and RECORD (installed from a wheel file now, not a source dir), and a few stray stdlib .pyc files that the old in-image build left behind (image about 0.6 MB smaller). Config, labels, user, command and health check are the same.

How it was verified

  • pytest with coverage (as in CI, mongomock): 1519 passed, 262 skipped (Helm/MongoDB-dependent), coverage 100%. New tests in tests/test_image_build.py fail on dev and pass here.
  • pre-commit run --all-files: all hooks pass.
  • docker build --build-arg SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0+cr282: builds; build log shows only hash-checked downloads; app reports 0.0.0+cr282; no setuptools, setuptools-scm or uv in the image; /tmp empty.
  • Negative check: with setuptools-scm removed from the group (and relocked), the build fails at the wheel step (Some build dependencies for file:///tmp/src are missing: 'setuptools-scm>=8'), so the build doesn't fall back to downloads.
  • Docker Compose (own project, port 18282): both services healthy, service info reports 0.0.0+compose, Swagger UI 200; removed afterwards.
  • CI: all checks pass (Lint, Test (mongomock), Test (MongoDB 7.0), Chart, Docs, Smoke test, Scan image, Release readiness, CI passed). The first Scan image run failed resolving the pinned uv image on ghcr.io (not found, while Smoke test pulled the same digest); a re-run passed.

Declined review findings

  • Quality reviewer (low): unit tests for the private test helpers (_pinned, _runs, _pip_args); they're exercised by the tests that use them, and the tightened checks were probed with modified Dockerfiles (e.g. pip3 install without --network=none fails the tests).
  • Quality reviewer (low): shorten the Dockerfile comments; kept, as the repo documents the build steps in place.
  • Adversarial reviewer (low, not introduced here): CI's push job installs setuptools-scm unhashed to derive the dev version, in a job with Docker Hub credentials. Out of scope for the image build; follow-up ci: hash-check setuptools-scm in the push job #288.

Unverified

  • Whether Dependabot's uv support picks up packages that only a PEP 735 dependency group requires. They are in uv.lock, which Dependabot updates; the first monthly run will show it.

🤖 Generated with Claude Code

Summary by Sourcery

Build and install the application wheel entirely from hash-locked dependencies without allowing unchecked network downloads.

New Features:

  • Build the application wheel in a dedicated Docker stage using hash-locked build requirements.

Bug Fixes:

  • Prevent Docker image builds from downloading unchecked build dependencies by enforcing offline, hash-validated installation and wheel creation.

Enhancements:

  • Install the application from the built wheel in the final image while retaining the existing hash-checked runtime dependency installation.
  • Add validation that the build dependency group matches build-system.requires and that Dockerfile package operations remain hash-checked and network-isolated.

Documentation:

  • Document hash-locking and offline building of the application's build requirements, including the Dependabot update flow.

Tests:

  • Add image-build checks covering dependency locking, hash validation, offline build/install steps, and uv mounting.

Chores:

  • Extend the dependency lock and Dependabot documentation to include the application's build requirements.

uniqueg and others added 3 commits October 29, 2026 04:13
Lock the build requirements of the app (`build-system.requires`) in
`uv.lock` as the dependency group `build-system`, and build the app's
wheel in a build stage: the requirements are installed from the lock
with `--require-hashes` into a virtual environment, and the wheel is
built with them, without build isolation, index or network. The image
installs only the wheel, without index or network, so the image build
downloads nothing without a hash check. Dependabot's `uv` entry keeps
updating the build requirements with the rest of the lock.

Tests check that the group matches `build-system.requires`, that the
locked build requirements are hashed, and that every pip command of the
`Dockerfile` checks hashes or has no index (and no network).

Closes #282

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Recognize `pip3` and `pip3.X` too, reject heredocs in `RUN` (they would
hide their commands from the checks), and drop exact counts of build
steps. Reword the docs on the `build-system` group.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Find pip the same way in both image build checks (also `pip3` steps
must have no network), reject heredocs after line continuations too,
and rewrap the Dependabot paragraph of the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v1.0.0-rc1 milestone Oct 29, 2026
@uniqueg uniqueg added type: security Related to security docker labels Oct 29, 2026
@sourcery-ai

sourcery-ai Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR makes image builds fully hash-checked and network-isolated by locking the app’s build requirements in uv, building the application wheel in a dedicated offline stage, and installing only that wheel in the final image; accompanying tests enforce dependency parity, hash coverage, uv mounting, and Dockerfile download safeguards.

Sequence diagram for the offline wheel build

sequenceDiagram
    participant U as uv
    participant B as build stage
    participant E as build venv
    participant W as wheel
    participant I as final image
    B->>U: export --frozen --only-group build-system
    U-->>B: hashed build requirements
    B->>E: pip install --require-hashes --only-binary :all: --no-deps
    B->>W: pip wheel --no-index --no-build-isolation --check-build-dependencies
    Note over B,W: RUN --network=none
    W->>I: pip install --no-index --no-deps
    Note over I,W: RUN --network=none
Loading

File-Level Changes

Change Details Files
Lock and verify application build requirements alongside runtime dependencies.
  • Added a build-system dependency group mirroring build-system.requires.
  • Updated the lockfile and Dependabot documentation so build requirements and hashes are maintained with the uv lock.
  • Added tests covering group parity, hashed exports, and separation from runtime requirements.
pyproject.toml
uv.lock
.github/dependabot.yml
docs/development.md
tests/test_image_build.py
Reworked the Docker build into an isolated, offline wheel-building stage.
  • Added a pinned-base build stage that exports the locked build group, installs hashed binary wheels into an ensurepip-created virtual environment, and builds the application wheel without build isolation or network access.
  • Kept uv mounted only for export operations and excluded it from image contents.
  • Passed the SCM version argument to the build stage.
Dockerfile
Install the built application wheel in the final image without downloads.
  • Replaced source-tree installation with installation of the wheel produced by the build stage.
  • Enforced --no-index, --no-deps, and --network=none for the final application install while leaving runtime dependency installation unchanged.
  • Added Dockerfile-parsing tests to ensure pip operations are hash-checked or offline and relevant stages disable networking.
Dockerfile
tests/test_image_build.py

Assessment against linked issues

Issue Objective Addressed Explanation
#282 Ensure every package downloaded during the image build, including the app’s build backend and its transitive requirements, is pinned and hash-checked so an untrusted backend cannot alter the built wheel. ✅
#282 Build the app’s wheel using the locked build requirements, then install only that wheel into the runtime image without changing the image’s runtime contents or behavior materially. ✅
#282 Keep the build-requirement pins maintainable through Dependabot and document and test the image-build safeguards. ✅

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (f758f1d) to head (9240743).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #289   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           22        22           
  Lines         2321      2321           
=========================================
  Hits          2321      2321           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review October 29, 2026 03:36

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="pyproject.toml" line_range="158" />
<code_context>
+# image build installs them hash-checked instead of downloading them into an
+# isolated build environment (`Dockerfile`); Dependabot updates them with the
+# other locked packages
+build-system = ["setuptools>=77", "setuptools-scm>=8"]
+
 [project.readme]
</code_context>
<issue_to_address>
**Build backend updates can be missed**

When dependabot's `uv` resolver does not recognize PEP 735 dependency groups for updates, dependabot's `uv` resolver does not treat PEP 735 dependency groups as updateable dependencies, so its configured updates leave the build-only requirements unchanged and the promised lock updates do not arrive.

Verify that Dependabot updates this group in practice, and add a supported update mechanism if it does not.

Also at `.github/dependabot.yml:8`.
</issue_to_address>

### Comment 2
<location path="tests/test_image_build.py" line_range="93" />
<code_context>
+        assert match, run
+        options, commands = match.groups()
+        runs.append(
+            (options.split(), [command.strip() for command in commands.split("&&")])
+        )
+    return runs
</code_context>
<issue_to_address>
**Unchecked pip download passes test**

When a Dockerfile RUN command chains an unchecked pip invocation after `;` or a pipe, `test_downloads_hash_checked` validates only the first pip invocation in each parsed command: `_runs` splits on `&&`, and `_pip_args` returns the first match. A later unchecked pip invocation after `;` or a pipe therefore goes unchecked, and the test passes.

Parse shell commands so every pip invocation is checked, including those separated by other shell operators.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: pyproject.toml:158, tests/test_image_build.py:93


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread pyproject.toml Resolved
Comment thread tests/test_image_build.py Resolved
Split the commands of `RUN` instructions on `||`, `;` and `|` too, not
only on `&&`, so that a chained pip command can't pass unchecked
(Sourcery review).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 06b2cdc into dev Oct 29, 2026
19 checks passed
@uniqueg
uniqueg deleted the build/282-hash-build-backend branch October 29, 2026 03:49
@uniqueg uniqueg added the type: delivery Related to packaging, deployment etc. label Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: delivery Related to packaging, deployment etc. type: security Related to security

Projects

None yet

Development

Successfully merging this pull request may close these issues.

build: hash-check the build backend in the image

1 participant