Skip to content

fix: compare tokens, drop stored registry tokens - #104

Merged
uniqueg merged 6 commits into
devfrom
fix/101-102-103-tokens-builds
Nov 9, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/101-102-103-tokens-builds

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Summary

Three small items for 0.2.0, in one PR (tiny issues in the same area):

  • Compare tokens in constant time (fix: compare tokens in constant time #101): every check of a supplied access token (project, user and admin tokens; 12 checks in repositories, builds, subscriptions and users) goes through tokens_match() in the new pubgrade/tokens.py, which uses hmac.compare_digest. Missing, empty or non-string values match nothing (an unquoted numeric admin token in the configuration now gets a 401 instead of a 500; the docs ask for quoted tokens). A unit test fails if an endpoint compares a token with == or != again.
  • Remove the stored registry token after builds (fix: remove the stored registry token after builds #102): a build's record kept the request's dockerhub_token for good. It is now removed ($unset) once the build's completion is recorded (after the signing is triggered and the pod and files are removed) and when the build is canceled (running or finished). It stays while the signing or the pod's deletion can still fail, so that the pod's next report can repeat them; remove_files() now treats files and pods that are gone as removed, so that such a repeat completes the build (before, it failed in rmtree on every report). A report of a build whose completion was recorded already changes nothing (before: signed and notified again). Builds recorded by earlier versions keep their token until canceled, deleted, or (if SUCCEEDED) reported again once.
  • Builds are for trusted repositories only (docs: builds are for trusted repositories only #103): a warning in the Builds section of the deployment guide: with builds on, Pubgrade builds the Dockerfiles of the repositories it is given, as root in its namespace; register only trusted repositories, use a namespace of its own, switch off registration once set up, and prefer prebuilt images from each repository's own CI.

Docs: docs/deployment.md (Configuration, Builds, Registries). No API change (pubgrade/api/pubgrade.yaml untouched).

Closes #101
Closes #102
Closes #103

Verification

  • pytest --cov (mongomock): 694 passed, coverage 100%
  • pytest tests/integration against MongoDB 7.0 (own container on port 27091, removed afterwards): 45 passed, including the new test_completed_build_keeps_no_registry_token and the extended test_cancel_running_build
  • ruff check, ruff format --check, mypy pubgrade tests scripts build-complete-updater: clean
  • mkdocs build --strict (with the sidecar submodule): clean
  • TDD: the new tests failed before the changes (AST check on the endpoints, token removal on completion/cancel, retry after a failed pod deletion, non-string tokens)
  • CI: all checks passed (CI passed, CodeQL, Docs, Read the Docs, codecov); no open code scanning alerts for the PR

Review

Full lane (auth-related). Sourcery: 9 threads; fixed: tokens of builds that earlier versions canceled are removed at start (5a62c07); the others answered (pre-existing behaviour, covered by existing tests, or no README mention of builds) and resolved; #101 wording corrected (non-ASCII tokens are compared, not rejected). Two rounds of adversarial-reviewer and quality-reviewer; fixed: idempotent remove_files() (round 1, medium), non-string tokens (low), legacy-record test and docs (medium), test docstrings (medium), test of remove_files() with missing files (round 2, medium), docs accuracy and wrapping (lows).

Declined review findings

  • Reorder build_completed (remove the token right after the signing, notify, delete the pod last) so that a failure after the pod's deletion can still be retried (round 2, low): a larger change to the completion flow for a rare case (Pubgrade stopping, or the Kubernetes API timing out after deleting the pod, between the deletion and the end of the request), and the reordering needs its own cleanup path for repeated reports. The docs now say what happens in that case (the build keeps its token; cancel it). Can be a follow-up issue.
  • Check GitHub's response to the signing dispatch (round 2, low): unchanged behaviour (already documented: "responses of GitHub are not checked"); the new paragraph now says "if GitHub can't be reached". A separate issue if wanted.
  • Check admin tokens' type at start (round 2, low): documented instead (quote tokens); a start-time check fits a later configuration check pass.
  • Move the AST test to a semgrep/ast-grep rule (round 1, low): the unit test runs everywhere the tests run; the failure message now names file and line.
  • Extract a fixture for the build integration tests' setup (round 1, low): the two tests share the pattern; left for a test-cleanup pass to keep the diff small.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 5 commits November 9, 2026 17:55
Every check of a supplied access token (project, user and admin
tokens) now goes through tokens_match() in pubgrade/tokens.py, which
uses hmac.compare_digest. Missing or empty tokens match nothing. A
test checks that no endpoint compares tokens with == or != any more.

Refs #101

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A build's record kept the request's dockerhub_token for good. It is
now removed ($unset) once the build's completion is recorded and its
pod and files are removed, and when the build is canceled. It stays
while the signing or the cleanup can still fail, so that the pod's
next report can repeat them. A report of a build whose completion
was recorded already changes nothing (before: signed and notified
again).

Refs #102

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Builds section of the deployment guide now says plainly that
Pubgrade builds the Dockerfiles of the repositories it is given, as
root in its namespace, so builds are for trusted repositories only,
and recommends prebuilt images from the repositories' own CI. It also
describes when the registry token leaves a build's record, and that
access tokens are compared in constant time.

Refs #101, #102, #103

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review findings:

- remove_files() now treats a missing directory or pod as removed, so
  the pod's next report completes a build whose pod couldn't be
  deleted the first time. Before, it failed again and again in rmtree,
  and the registry token was never removed.
- tokens_match() rejects values that aren't strings (e.g., an
  unquoted numeric admin token in the configuration) with a 401
  instead of a 500.
- Tests: legacy completed builds, retry after a failed cleanup, test
  docstrings; docs describe the retry and earlier records accurately.

Refs #101, #102

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Round-2 review findings: test that remove_files() treats a missing
directory and pod as removed; say which failures a repeated report
recovers from (GitHub unreachable, pod not deleted) and which it
doesn't (completion failing after the pod is gone); ask for quoted
admin tokens; rewrap the warning about builds.

Refs #102, #103

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Centralize access-token checks in a matcher that rejects missing, empty, and non-string values and uses constant-time comparison, then route every endpoint token check through it.

  • pubgrade/modules/endpoints/builds.py L45-865 (4 small edits)
  • pubgrade/modules/endpoints/repositories.py L22, L214, L310
  • pubgrade/modules/endpoints/subscriptions.py L34-260 (5 small edits)
  • pubgrade/modules/endpoints/users.py L18-176 (4 small edits)
  • pubgrade/tokens.py L1-30

Remove registry tokens from canceled builds at startup and during cancellation, and remove them after successful completion while keeping retry behavior for failures before cleanup is recorded.

  • pubgrade/app.py L58-61, L72-75
  • pubgrade/modules/endpoints/builds.py L875-878, L917-921, L940-944 (+5 small edits)

Documentation

Document token configuration and comparison behavior, warn that builds execute trusted repository Dockerfiles as root, and explain registry-token cleanup and completion retries.

  • docs/deployment.md L111-122, L196-213 (+2 small edits)

Tests

Test that all endpoint token checks use the shared matcher and that missing, empty, non-string, differing, and non-ASCII tokens behave as intended.

  • tests/test_tokens.py L1-89

Verify canceled-build tokens are removed at startup and cover token cleanup, retry, idempotency, and legacy build completion behavior.

  • tests/integration/test_api.py L674-754
  • tests/pubgrade/endpoints/test_builds.py L1320-1325, L2037-2194 (+2 small edits)
  • tests/test_app.py L88-112

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 Nov 9, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #104   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           17        18    +1     
  Lines         1517      1533   +16     
=========================================
+ Hits          1517      1533   +16     

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

@read-the-docs-community

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

Copy link
Copy Markdown

Documentation build overview

📚 Pubgrade | 🛠️ Build #35762497 | 📁 Comparing 5a62c07 against latest (5ae9d84)

  🔍 Preview build  

1 file changed
± deployment/index.html

@uniqueg
uniqueg marked this pull request as ready for review November 9, 2026 17:47
@uniqueg
uniqueg requested a review from akash2237778 as a code owner November 9, 2026 17:47

@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 9 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="919-920" />
<code_context>
     )
+    # Not needed any more; kept until here, for a repeated report if the
+    # signing or the cleanup fails
+    db_collection_builds.update_one(
+        {"id": build_id}, {"$unset": {"dockerhub_token": ""}}
+    )
     # A build canceled meanwhile notifies no one
</code_context>
<issue_to_address>
**Subscribers miss completion notifications**

When pubgrade stops or notification-result persistence fails after the token is unset but before notification work completes, `build_completed()` has already removed `dockerhub_token`, so the next report returns at the finished-build guard instead of retrying `notify_all_subscriptions()`; subscribers remain unnotified or their results remain unrecorded.

Keep the token or another retry marker until notification delivery and result persistence complete, and only then take the completed-build shortcut.

Also at `pubgrade/modules/endpoints/builds.py:875-878`.
</issue_to_address>

### Comment 2
<location path="pubgrade/modules/endpoints/builds.py" line_range="875" />
<code_context>
         )
     except StopIteration:
         raise BuildNotFound from None
+    if data.get("status") in FINISHED and "dockerhub_token" not in data:
+        # Its completion was recorded already: signed, cleaned up, notified
+        logger.info("Build %s was reported again; it is complete.", build_id)
</code_context>
<issue_to_address>
**Completion side effects run twice**

When two completion reports for the same build overlap before either removes `dockerhub_token`, `build_completed()` lets both reports pass the token guard, and the later update matches any non-canceled status; both reports sign the image and notify subscribers, duplicating completion side effects.

Atomically claim completion with an update that only one report can match before either report performs signing, cleanup, or notification.
</issue_to_address>

### Comment 3
<location path="pubgrade/modules/endpoints/builds.py" line_range="985" />
<code_context>
-        {"$set": {"status": CANCELED, "finished_at": now(), STOPPING: True}},
+        {
+            "$set": {"status": CANCELED, "finished_at": now(), STOPPING: True},
+            "$unset": {"dockerhub_token": ""},
+        },
     )
</code_context>
<issue_to_address>
**Canceled builds retain registry tokens**

When a build was already marked `CANCELED` by an earlier version and still has `dockerhub_token` stored, `cancel_build()` skips the updates that unset the token and raises `BuildCanceled`, leaving the registry credential in the database indefinitely despite the documented cleanup.

Unset `dockerhub_token` when handling an already-canceled build, including the retry path.

Also at `pubgrade/modules/endpoints/builds.py:991`, `docs/deployment.md:208-212`.
</issue_to_address>

### Comment 4
<location path="pubgrade/modules/endpoints/builds.py" line_range="920-921" />
<code_context>
+    # Not needed any more; kept until here, for a repeated report if the
+    # signing or the cleanup fails
+    db_collection_builds.update_one(
+        {"id": build_id}, {"$unset": {"dockerhub_token": ""}}
+    )
     # A build canceled meanwhile notifies no one
     if is_canceled(build_id):
</code_context>
<issue_to_address>
**Signing failures become permanent**

When gitHub responds with an HTTP error status without a request exception, `trigger_signing_image()` treats a non-2xx GitHub response as success, so `build_completed()` removes the pod and token; the next report takes the completed-build shortcut and never retries signing. The image is left unsigned without an error being logged.

Check the dispatch response status and treat non-success responses as signing failures before removing the pod or token.

Also at `pubgrade/modules/endpoints/builds.py:875-878`.
</issue_to_address>

### Comment 5
<location path="pubgrade/modules/endpoints/builds.py" line_range="991" />
<code_context>
         finished = db_collection_builds.update_one(
             {"id": build_id, "status": {"$in": FINISHED}},
-            {"$set": {"status": CANCELED}},
+            {"$set": {"status": CANCELED}, "$unset": {"dockerhub_token": ""}},
         )
         if finished.matched_count:
</code_context>
<issue_to_address>
**Canceled builds leave pods running**

When completion cleanup fails while the pod still exists, and the caller cancels the now-finished build, `cancel_build()` marks the finished build canceled, removes its token, and returns without calling `stop_builds()`, leaving the pod or its files behind indefinitely if it never reports again.

Stop the build as part of the finished-build cancellation path before returning.
</issue_to_address>

### Comment 6
<location path="pubgrade/modules/endpoints/builds.py" line_range="920" />
<code_context>
+    # Not needed any more; kept until here, for a repeated report if the
+    # signing or the cleanup fails
+    db_collection_builds.update_one(
+        {"id": build_id}, {"$unset": {"dockerhub_token": ""}}
+    )
     # A build canceled meanwhile notifies no one
</code_context>
<issue_to_address>
**Rolling upgrades reject completion retries**

When an old application instance handles a callback after a new instance has removed the build's token, the old completion handler indexes `data["dockerhub_token"]` without a missing-token guard, raises `KeyError`, and returns an error for the callback.

Make the old handler tolerate a missing token or prevent old instances from receiving callbacks after new instances remove tokens.
</issue_to_address>

### Comment 7
<location path="pubgrade/tokens.py" line_range="30" />
<code_context>
+        return False
+    if not supplied or not stored:
+        return False
+    return hmac.compare_digest(supplied.encode("utf-8"), stored.encode("utf-8"))
</code_context>
<issue_to_address>
**Reject non-ASCII tokens**

The issue requires non-ASCII token values to match nothing, but `tokens_match()` UTF-8 encodes them and can accept equal non-ASCII strings; the added test explicitly expects that behavior.
</issue_to_address>

### Comment 8
<location path="tests/pubgrade/endpoints/test_builds.py" line_range="1322-1324" />
<code_context>

+    def test_remove_files_gone_already(self) -> None:
+        """Files and a pod that are gone already count as removed."""
+        with patch("pubgrade.modules.endpoints.builds.delete_pod") as delete_pod:
+            remove_files("build-gone", "pod_name", "namespace")
+        delete_pod.assert_called_once_with("pod_name", "namespace", missing_ok=True)
+
     @patch("kubernetes.config.load_kube_config", mocked_load_cluster_config)
</code_context>
<issue_to_address>
**Missing pods remain untested**

When `CoreV1Api.delete_namespaced_pod` raises a 404 on retry, `test_remove_files_gone_already` replaces `delete_pod` with a mock and checks only that `missing_ok=True` is passed; it still passes if `delete_pod` raises on a 404, so retrying completion fails.

Test `delete_pod` with a 404 response and `missing_ok=True`, asserting that it returns successfully.
</issue_to_address>

### Comment 9
<location path="docs/deployment.md" line_range="111" />
<code_context>
 requests that need them get a 403, as does
 `PUT /repositories/{id}/builds/{build_id}`.

+!!! warning "Builds are for trusted repositories only"
+
+    With builds on, Pubgrade clones the repositories it is given and builds
</code_context>
<issue_to_address>
**Link warning from README**

The deployment guide now has the requested warning, but the README does not point readers to it. Add a link from the README's relevant build mention.
</issue_to_address>

Linked issues

#101 fix: compare tokens in constant time · 2 of 3 met

# Requirement Status Notes
1 Use one hmac.compare_digest helper for every supplied access-token check. ✅ Met The project, user, and admin token checks in the endpoints use tokens_match().
2 Missing or non-ASCII token values count as not matching. 🟡 Partly met Missing and empty values are rejected, but equal non-ASCII strings match.
3 Add unit tests for matching, non-matching, and missing tokens. ✅ Met The tests cover those cases.

#102 fix: remove the stored registry token after builds · 3 of 3 met

# Requirement Status Notes
1 Remove dockerhub_token after completion and cancellation. ✅ Met Completion unsets it after signing and cleanup; cancellation unsets it for running and finished builds.
2 A repeated report of a completed build changes nothing. ✅ Met Completed records without a registry token return early.
3 Add unit tests and document token removal. ✅ Met Tests cover completion, cancellation, repeated reports, and cleanup retry; the deployment guide describes token retention and removal.

#103 docs: builds are for trusted repositories only · 1 of 2 met

# Requirement Status Notes
1 Warn that builds are for trusted repositories; recommend an isolated namespace and prebuilt images from repository CI. ✅ Met The deployment guide's Builds warning includes these recommendations and says to disable repository registration once set up.
2 Point to the warning from the README where builds are mentioned. ❌ Not addressed The README is unchanged and does not link to the new warning.

Sourcery assessment

Needs a human reviewer. 8 findings to address first, and the shared token check now guards repository, user, subscription, and build operations; if it accepts a token that should be rejected, callers could gain unauthorized access or perform those operations. Reverting restores the old comparisons, but it does not put registry tokens back into build records already completed or canceled.

Blocking findings: pubgrade/modules/endpoints/builds.py:920, pubgrade/modules/endpoints/builds.py:875, pubgrade/modules/endpoints/builds.py:985, pubgrade/modules/endpoints/builds.py:921, pubgrade/modules/endpoints/builds.py:991, 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/tokens.py Resolved
Comment thread tests/pubgrade/endpoints/test_builds.py Resolved
Comment thread docs/deployment.md Resolved
Sourcery review: builds that an earlier version canceled kept their
dockerhub_token, as canceling them again gets a 409 without touching
them. The app factory now removes the token of every canceled build
at start, next to the repair of timestamps; other builds keep theirs.

Refs #102

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 663f546 into dev Nov 9, 2026
45 checks passed
@uniqueg
uniqueg deleted the fix/101-102-103-tokens-builds branch November 9, 2026 18:25
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.

docs: builds are for trusted repositories only fix: remove the stored registry token after builds fix: compare tokens in constant time

1 participant