Skip to content

fix: reject unknown Git refs of builds with 400 - #79

Merged
uniqueg merged 5 commits into
devfrom
fix/28-unknown-git-ref
Nov 7, 2026
Merged

uniqueg merged 5 commits into
devfrom
fix/28-unknown-git-ref

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Summary

With builds switched on, POST /repositories/{id}/builds (the issue says PUT; the endpoint is POST) answered a branch, tag or commit in head_commit that isn't in the repository with a 500, and left a QUEUED build behind. Now:

  • Pubgrade clones the repository and looks up the branch (show-ref on 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 existing 400 response). Revision expressions such as HEAD~1 and the branch HEAD are rejected too. Checkouts use the resolved commit only.
  • With a branch, commit_sha must be a commit hash; an explicitly empty commit_sha gets a 400. Only Git lookups that exit with status 1 (unknown or ambiguous name) become a 400; other Git errors stay 500s.
  • A build that can't start is removed from the repository's build_list and 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.
  • The API specification (postBuild, head_commit) and the deployment guide (section Builds) describe the behaviour.

Closes #28

Verification

  • Test-first: the new integration test test_build_of_unknown_ref (local Git remote from the fixtures in tests/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/integration against MongoDB 7.0 in Docker: 16 passed.
  • ruff check, ruff format --check, mypy: clean.
  • mkdocs build --strict: OK.
  • pre-commit hooks that fetch repositories (gitleaks, actionlint) were not run locally; CI runs them.
  • CI: all checks passed (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-reviewer and quality-reviewer, two rounds. All high and medium findings were fixed (none were high), as were the cheap lows.

Declined review findings

  • Validate the refs before inserting the build, to avoid a short window in which a build that is later removed is listed as QUEUED. This would need a clone before a build ID exists. Instead, the window is documented in the register_builds docstring and in the deployment guide.
  • minLength: 1 on branch, tag and commit_sha in the spec. This would also change the default path with builds switched off. Instead, empty names are rejected in code, for builds only.
  • Sourcery: tags unreachable from branches would be missing after the clone. git clone fetches all tags (checked with Git 2.53).
  • Sourcery: branch names starting with - 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

uniqueg and others added 4 commits November 7, 2026 10:49
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]>
@sourcery-ai

sourcery-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Define the 400 response and document which invalid build references produce it, along with failed-build retention behavior.

  • pubgrade/api/pubgrade.yaml L246-248, L1014-1017
  • pubgrade/errors/exceptions.py L95-100, L213-220

Implementation

Validate 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.

  • pubgrade/modules/endpoints/builds.py L194-270, L380-438, L465-528 (+8 small edits)

Documentation

Explain exact Git reference requirements, 400 responses, and which failed builds are removed or retained.

  • docs/deployment.md L106-118

Tests

Cover API behavior, ref validation and checkout, cleanup on startup failures, pod-error retention, and response details.

  • tests/integration/test_api.py L3-5, L11-13, L276-347
  • tests/pubgrade/endpoints/test_builds.py L481-618, L711-847, L1046-1142 (+4 small edits)

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

@read-the-docs-community

read-the-docs-community Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 Pubgrade | 🛠️ Build #35717159 | 📁 Comparing 9203770 against latest (6be434c)

  🔍 Preview build  

1 file changed
± deployment/index.html

@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

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

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.
📢 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 November 7, 2026 10:06
@uniqueg
uniqueg requested a review from akash2237778 as a code owner November 7, 2026 10:06

@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 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 is free for open source - if you like our reviews please consider sharing them ✨

Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
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]>
@uniqueg
uniqueg merged commit 7cfe152 into dev Nov 7, 2026
41 of 46 checks passed
@uniqueg
uniqueg deleted the fix/28-unknown-git-ref branch November 7, 2026 10:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PUT /repositories/{repo_id}/builds failing with 500 if wrong branch name given in request body

1 participant