Repository navigation
fix: reject unknown Git refs of builds with 400 - #79
Conversation
With builds switched on, a branch, tag or commit in `head_commit` that
isn't in the repository made `POST /repositories/{id}/builds` fail with
a 500, and left a queued build behind.
Pubgrade now clones the default branch, looks the branch up among the
remote branches and the tag or commit with `rev-parse`, and answers
unknown ones with a 400 (`GitRefNotFound`). Checkouts use the resolved
references only, so names can't act as options. A build that can't
start is removed from the database and the repository's build list,
and its files are removed.
Closes #28
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe in the API specification and the deployment guide that, with builds switched on, a branch, tag or commit that isn't in the repository gets a 400 and that builds that can't start aren't kept. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-ups for #28: - Accept tags by exact name and commits only as hashes of 4 to 40 hexadecimal digits; reject revision expressions (e.g. `HEAD~1`), the branch `HEAD` and empty names with a 400. - Keep the original error if removing a build that can't start fails, and log the failure. - Test branch-only and full-hash checkouts, other errors of starting a build, and the full problem details of the 400. - Describe the accepted names in the specification and the deployment guide, and that builds failing with a 500 aren't kept either. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Second review round for #28: - Reject an empty branch also when a `commit_sha` is given. - Accept commit hashes of up to 64 digits (SHA-256 repositories). - Say in the error that a short hash may not be unique. - Unit-test `start_build` directly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideAPIDefine the 400 response and document which invalid build references produce it, along with failed-build retention behavior.
ImplementationValidate build references before checkout, return client errors for unknown refs, and clean up builds that cannot start while retaining builds whose pod may have started.
DocumentationExplain exact Git reference requirements, 400 responses, and which failed builds are removed or retained.
TestsCover API behavior, ref validation and checkout, cleanup on startup failures, pod-error retention, and response details.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #79 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 17 17
Lines 1257 1322 +65
=========================================
+ Hits 1257 1322 +65 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 8 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="pubgrade/modules/endpoints/builds.py" line_range="400" />
<code_context>
+ build_push_image_using_kaniko(deployment_file_location=deployment_file_location)
+ except Exception:
+ # No pod uses the files of a build that didn't start
+ shutil.rmtree(build_dir, ignore_errors=True)
+ raise
</code_context>
<issue_to_address>
**Accepted pods lose their build inputs**
When kubernetes accepts pod creation but its response is lost or times out, `create_build` treats the transport error as a failed start, removes `build_dir`, and `register_builds` deletes the build record, leaving the running pod without its files and its callback without a tracked build.
Reconcile uncertain pod creation before removing the build files or database record.
</issue_to_address>
### Comment 2
<location path="pubgrade/modules/endpoints/builds.py" line_range="201-203" />
<code_context>
- break
- branch = ""
- commit_sha = ""
- try:
- branch = build_data["head_commit"]["branch"]
- try:
</code_context>
<issue_to_address>
**Failed cleanup breaks build listings**
When the build document is deleted but the repository update fails, `register_builds` deletes the build document before pulling its ID from `build_list`; the stale ID makes `get_builds` raise `BuildNotFound` and fail the listing.
Make the build deletion and repository-list update atomic, or recover the stale reference if either operation fails.
</issue_to_address>
### Comment 3
<location path="pubgrade/modules/endpoints/builds.py" line_range="473-475" />
<code_context>
+ repository.
+ GitCommandError: If Git can't resolve the tag or hash to a commit.
+ """
+ tag = f"refs/tags/{name}"
+ try:
+ repo.git.show_ref("--verify", "--quiet", tag)
+ except GitCommandError:
+ if not COMMIT_HASH.fullmatch(name):
</code_context>
<issue_to_address>
**Commit hashes accept tag names**
When a branch build supplies a non-hex `commit_sha` that matches an existing tag, `resolve_tag_or_commit` checks for a tag before validating `COMMIT_HASH`, and `start_build` uses it for `commit_sha`, so the request checks out the tag instead of rejecting the invalid hash.
Validate branch-build `commit_sha` values as hashes before resolving them.
Also at `pubgrade/modules/endpoints/builds.py:444`.
</issue_to_address>
### Comment 4
<location path="pubgrade/modules/endpoints/builds.py" line_range="235-242" />
<code_context>
+ head_commit = build_data["head_commit"]
+ if "branch" in head_commit:
+ branch = head_commit["branch"]
+ commit_sha = head_commit.get("commit_sha", "")
+ name = branch
+ else:
+ branch = ""
+ commit_sha = head_commit["tag"]
+ name = commit_sha
+ # An empty branch or tag would build the repository's default branch
+ if name == "":
+ raise GitRefNotFound
+ intermediate_registry_format = endpoints()["builds"][
</code_context>
<issue_to_address>
**Empty commit selector builds branch head**
When `head_commit` supplies an explicitly empty `commit_sha` alongside a valid branch, `start_build` checks only the branch name for emptiness, then `git_clone_and_checkout` treats the empty commit as no selector and checks out the branch head, so the request builds a different revision instead of returning 400.
Reject an explicitly empty `commit_sha` before checkout.
</issue_to_address>
### Comment 5
<location path="pubgrade/modules/endpoints/builds.py" line_range="475" />
<code_context>
+ """
+ tag = f"refs/tags/{name}"
+ try:
+ repo.git.show_ref("--verify", "--quiet", tag)
+ except GitCommandError:
+ if not COMMIT_HASH.fullmatch(name):
</code_context>
<issue_to_address>
**Valid remote tags get rejected**
When a requested tag points to a commit that is not reachable from any branch fetched by the clone, `Repo.clone_from` does not fetch tags whose target commits are unreachable from the fetched branch histories, so `show_ref` cannot find such a remote tag and raises `GitRefNotFound`; callers receive a 400 for a tag that exists in the repository.
Fetch remote tags before checking them, or otherwise look up the tag against the remote without relying on clone's automatic tag following.
</issue_to_address>
### Comment 6
<location path="pubgrade/modules/endpoints/builds.py" line_range="446-447" />
<code_context>
- return clone_path
+ target = resolve_tag_or_commit(repo, commit)
+ except GitCommandError:
+ raise GitRefNotFound from None
+ try:
+ if branch != "":
+ repo.git.checkout("-B", branch, remote_branch)
</code_context>
<issue_to_address>
**Git failures look like bad requests**
When a Git lookup command fails for a reason other than an absent ref, such as a repository/object error, `git_clone_and_checkout` catches every `GitCommandError` from branch and tag/hash lookup, including failures unrelated to a missing or ambiguous ref, and raises `GitRefNotFound`; callers therefore receive a 400 instead of a server error for Git-side failures.
Translate only the Git command failures that signify a missing or ambiguous ref, and let other failures remain server errors.
</issue_to_address>
### Comment 7
<location path="pubgrade/modules/endpoints/builds.py" line_range="439" />
<code_context>
- # Checkout only if tag or commit sha is specified, otherwise stay at
- # HEAD of branch.
+ # `origin/HEAD` is a remote ref, but not a branch
+ if branch == "HEAD" or branch.startswith("-"):
+ raise GitRefNotFound
+ repo.git.show_ref("--verify", "--quiet", remote_branch)
</code_context>
<issue_to_address>
**Valid dash-prefixed branches are rejected**
When the repository contains a valid branch whose exact name starts with `-`, `git_clone_and_checkout` rejects the branch name before checking out its exact remote ref, so the build receives a 400 instead of checking out the existing branch.
Handle dash-prefixed branch names safely rather than rejecting them.
</issue_to_address>
### Comment 8
<location path="pubgrade/modules/endpoints/builds.py" line_range="400" />
<code_context>
+ build_push_image_using_kaniko(deployment_file_location=deployment_file_location)
+ except Exception:
+ # No pod uses the files of a build that didn't start
+ shutil.rmtree(build_dir, ignore_errors=True)
+ raise
</code_context>
<issue_to_address>
**Failed cleanup leaves build files**
When the build directory cannot be removed because of a permission or filesystem error, `shutil.rmtree(..., ignore_errors=True)` suppresses the removal failure, so `create_build` re-raises the startup error while build files, including the intermediate registry token, remain on disk.
Handle and log removal errors instead of suppressing them.
</issue_to_address>Linked issues
#28 PUT /repositories/{repo_id}/builds failing with 500 if wrong branch name given in request body · 1 of 1 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | A build request with a wrong branch name should not fail with 500. | ✅ Met | Unknown branch refs raise GitRefNotFound, mapped to 400; the integration test checks that the build endpoint returns 400 and leaves no build behind. |
Sourcery assessment
Needs a human reviewer. 8 findings to address first, and if the new ref resolution selects the wrong commit, the build can publish an image built from unintended source to the requested registry. Reverting the change would not retract an image already published.
Blocking findings: pubgrade/modules/endpoints/builds.py:400, pubgrade/modules/endpoints/builds.py:203, pubgrade/modules/endpoints/builds.py:475, pubgrade/modules/endpoints/builds.py:242, pubgrade/modules/endpoints/builds.py:475, and 3 more
Sourcery review follow-ups for #28: - If only creating the build pod fails, keep the build and its files: the pod may have been created nonetheless. Other errors of creating the pod are reported as `CreatePodError`. - Remove a failed build from the repository's list before deleting it, so that a failed removal can't break the listing. - Log files of a failed build that can't be removed. - Reject an empty `commit_sha`, and accept only commit hashes (no tags) as `commit_sha` of a branch. - Answer only Git lookups that exit with status 1 (unknown or ambiguous name) with a 400; other Git errors stay 500s. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
With builds switched on,
POST /repositories/{id}/builds(the issue saysPUT; the endpoint isPOST) answered a branch, tag or commit inhead_committhat isn't in the repository with a 500, and left aQUEUEDbuild behind. Now:show-refon the exact remote branch), the tag (exact name) or the commit (a hash of 4 to 64 hexadecimal digits) before checking anything out. If the branch or tag is empty, or a name isn't in the repository or a short hash isn't unique, the request gets a 400 with problem details (GitRefNotFound, the spec's existing400response). Revision expressions such asHEAD~1and the branchHEADare rejected too. Checkouts use the resolved commit only.commit_shamust be a commit hash; an explicitly emptycommit_shagets a 400. Only Git lookups that exit with status 1 (unknown or ambiguous name) become a 400; other Git errors stay 500s.build_listand from the database, and its files are removed. The client gets no build ID in that case, so the build isn't kept. If the removal itself fails, the original error is still returned and the failure is logged. Exception: if only creating the build pod fails (500), the build and its files are kept, since the pod may have been created anyway.postBuild,head_commit) and the deployment guide (section Builds) describe the behaviour.Closes #28
Verification
test_build_of_unknown_ref(local Git remote from the fixtures intests/conftest.py, no network) failed with a 500 before the fix.uv run --locked pytest -q --cov: 542 passed, 100% coverage.MONGODB_TEST_URI=mongodb://127.0.0.1:27028 uv run --locked pytest tests/integrationagainst MongoDB 7.0 in Docker: 16 passed.ruff check,ruff format --check,mypy: clean.mkdocs build --strict: OK.CI passed, Lint, Test with mongomock and MongoDB 7.0, Docs, Chart, Smoke test, Upgrade test, image scans, CodeQL, Codecov, Read the Docs), also after the Sourcery fixes.Review
Full review:
adversarial-reviewerandquality-reviewer, two rounds. All high and medium findings were fixed (none were high), as were the cheap lows.Declined review findings
QUEUED. This would need a clone before a build ID exists. Instead, the window is documented in theregister_buildsdocstring and in the deployment guide.minLength: 1onbranch,tagandcommit_shain the spec. This would also change the default path with builds switched off. Instead, empty names are rejected in code, for builds only.git clonefetches all tags (checked with Git 2.53).-are rejected. Git doesn't create such branch names, and rejecting them keeps them from being read as options.Open questions
None.
🤖 Generated with Claude Code