Repository navigation
fix: compare tokens, drop stored registry tokens - #104
Conversation
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]>
Reviewer's GuideImplementationCentralize 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.
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.
DocumentationDocument token configuration and comparison behavior, warn that builds execute trusted repository Dockerfiles as root, and explain registry-token cleanup and completion retries.
TestsTest that all endpoint token checks use the shared matcher and that missing, empty, non-string, differing, and non-ASCII tokens behave as intended.
Verify canceled-build tokens are removed at startup and cover token cleanup, retry, idempotency, and legacy build completion behavior.
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 #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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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 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]>
Summary
Three small items for 0.2.0, in one PR (tiny issues in the same area):
tokens_match()in the newpubgrade/tokens.py, which useshmac.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.dockerhub_tokenfor 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 inrmtreeon 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 (ifSUCCEEDED) reported again once.Docs:
docs/deployment.md(Configuration, Builds, Registries). No API change (pubgrade/api/pubgrade.yamluntouched).Closes #101
Closes #102
Closes #103
Verification
pytest --cov(mongomock): 694 passed, coverage 100%pytest tests/integrationagainst MongoDB 7.0 (own container on port 27091, removed afterwards): 45 passed, including the newtest_completed_build_keeps_no_registry_tokenand the extendedtest_cancel_running_buildruff check,ruff format --check,mypy pubgrade tests scripts build-complete-updater: cleanmkdocs build --strict(with the sidecar submodule): cleanReview
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-reviewerandquality-reviewer; fixed: idempotentremove_files()(round 1, medium), non-string tokens (low), legacy-record test and docs (medium), test docstrings (medium), test ofremove_files()with missing files (round 2, medium), docs accuracy and wrapping (lows).Declined review findings
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.Open questions
None.
🤖 Generated with Claude Code