Repository navigation
build: move to FOCA 0.21 and Python 3.13 - #63
Conversation
Build the image on elixircloud/foca:0.21.0-py3.13 instead of FOCA 0.7 on Python 3.9, with GitPython 3.2, Gunicorn 26 and kubernetes 37, and drop the unused mock, setuptools and yq. - Adapt to FOCA 0.21: config via get_config(), named API spec, problem details instead of msg/status_code (API 2.0.0), no server.environment/use_reloader, a 1 MiB limit on request bodies. - Add an app factory (pubgrade.app:create_app) that the image serves with Gunicorn and FOCA's settings, instead of the development server. - Write timestamps in UTC with time zone and null for unfinished builds, as FOCA checks responses against date-time, and repair stored ones at start. - Install the requirements with uv, as the FOCA image has no pip; add git for GitPython; run with read-only app files; allowlist the build context. - Bump pytest and coverage, add mongomock to the test dependencies. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Run the unit tests on the runner with Python 3.13, the version of the new base image, as the FOCA image has no pip to install the test dependencies with; make the scan of the app's image fail on critical and high vulnerabilities that have a fix (the updater's image, not built on FOCA, is still reported only); and drop the Dependabot ignores for Python 3.9 (pytest, coverage, gunicorn, kubernetes and setuptools, which is no longer a requirement). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe problem details, timestamps and the 413 of API 2.0.0, the upgrade notes for configurations of deployments, the test setup on Python 3.13 and how FOCA is bumped, and the blocking image scan. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Answer unverified users with the 403 of the mapping: their exception derives from Forbidden now, not Unauthorized (401). - Fix typos and punctuation in the problem details, and check that each entry is complete and matches the status of its exception. - Test the app factory and the entry point (no longer omitted from the coverage), timestamps with time zone, and the image's user. - Say what happens to values the startup repair can't bring into the format. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Return builds and subscriptions with repaired timestamps, as an instance of the previous version can still write the old format during a rolling update, after the repair at start. - Repair at start only documents that need it, and only while their values are still the ones read, so a concurrent write is kept. - Serve with 16 Gunicorn threads instead of FOCA's 4: a publish holds a thread until its subscribers answer, and a slow client while it sends. - Document the threads, a buffering proxy, and subscriptions whose callback URL isn't a URI. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Move the Gunicorn settings into pubgrade/gunicorn_config.py (FOCA's, with 16 threads), so GUNICORN_CMD_ARGS stays free for deployments, and give running publishes 28 s on shutdown, within Kubernetes' default grace period. - Check the effective settings in a test, loaded as the image's command does. - Compute repaired values once, and test that concurrent writes to started_at and notifications are kept. - Document the shutdown limit and the margin of a publish. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideSchema and migrationsAdd the compatibility migration and read-time repair for legacy stored timestamps, including null unfinished-build values and compare-and-set updates that preserve concurrent writes.
APIRevise the OpenAPI contract to version 2.0.0, use RFC 9457 problem details, and allow a null build completion timestamp; align exception mappings and the unverified-user status with that contract.
Uses of the APIAdapt the endpoint handlers to FOCA 0.21 configuration access and the new timestamp representation, while returning legacy build and subscription records in the API format.
ImplementationCreate the FOCA app factory and development entry point, synchronize configured admin users, repair stored timestamps at startup, and set the image's Gunicorn concurrency and shutdown behavior.
ConfigurationMove the application image and dependency installation to FOCA 0.21/Python 3.13, configure its runtime and metadata, and update the test and vulnerability-scan workflows and dependency update policy.
DocumentationDocument the API error and timestamp changes, the FOCA 0.21 deployment upgrade requirements, and the Python 3.13 development and CI setup.
TestsUpdate endpoint tests for FOCA's configuration interface and add checks for legacy timestamp responses, app startup, problem-detail mappings, image runtime settings, and timestamp repair concurrency.
Other changesFiles not grouped.
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 #63 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 7 10 +3
Lines 669 745 +76
=========================================
+ Hits 669 745 +76 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 7 issues
Fixed security issues:
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="Dockerfile" line_range="29-30" />
<code_context>
-COPY --chown=1000:1000 ./ /app
+## Git, which GitPython needs to clone repositories for builds (and to be
+## imported at all); the FOCA image has none
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends git \
+ && rm -rf /var/lib/apt/lists/*
</code_context>
<issue_to_address>
**Builds can reach internal hosts**
When builds are enabled and an external caller registers a repository URL pointing to an internal host, then submits a build with the token returned at registration, `register_repository` stores the caller-supplied URL without validating it, and `git_clone_and_checkout` clones that URL from the Pubgrade pod. Installing Git makes this path available to callers who can register a repository and submit a build, allowing them to make the pod connect to internal hosts or services.
Validate repository URLs against an allowed scheme and host policy, and restrict the build pod's network egress to prevent access to internal services.
</issue_to_address>
### Comment 2
<location path="pubgrade/gunicorn_config.py" line_range="13" />
<code_context>
+
+from foca.gunicorn_config import * # noqa: F401,F403
+
+threads = 16
+graceful_timeout = 28
</code_context>
<issue_to_address>
**Slow subscribers exhaust notifier threads**
When a subscriber slowly trickles response headers without exceeding the per-read inactivity timeout, and publishes continue to that subscriber, `requests` treats the configured timeout as a connect/read inactivity timeout, not a total deadline; a subscriber that keeps its response headers trickling can therefore hold a notifier thread after `notify_all_subscriptions()` has returned and shut down its executor without waiting. Repeated publishes accumulate those threads until Pubgrade can no longer serve requests.
Enforce a true total deadline for subscriber calls and ensure timed-out work is cancelled or otherwise bounded so lingering notifier threads cannot accumulate.
</issue_to_address>
### Comment 3
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="366" />
<code_context>
- subscription_object["updated_at"] = str(
- datetime.datetime.now().isoformat()
- )
+ subscription_object["updated_at"] = now()
db_collection_subscriptions.update_one(
{"id": subscription_id}, {"$set": subscription_object}
</code_context>
<issue_to_address>
**Older build can overwrite newer deployment**
When two builds matching the same subscription complete concurrently and the older build's callback is processed last, the older build's callback can finish after the newer build's callback, so `notify_subscriptions` sends the older image last and stores its `build_id` and state over the newer result. The subscriber ends up running a stale image while Pubgrade records that older build as the latest notification.
Serialize notifications per subscription or reject a notification when its build is older than the one already applied.
</issue_to_address>
### Comment 4
<location path="pubgrade/modules/endpoints/builds.py" line_range="93" />
<code_context>
"$set": {
"status": "FAILED" if failed else "SUCCEEDED",
- "finished_at": datetime.datetime.now().isoformat(),
+ "finished_at": now(),
}
},
</code_context>
<issue_to_address>
**Delivered builds can remain queued**
When the process stops after a subscriber applies the update but before the final build update, `publish_prebuilt_image` sends subscriber updates before it records the build's terminal status and `finished_at`. A process termination after subscribers apply the image but before that database update leaves the build stored as `QUEUED` with no completion marker, despite the external update having taken effect.
Persist a recoverable notification/completion state or reconcile unfinished prebuilt builds after interruption.
</issue_to_address>
### Comment 5
<location path="pubgrade/modules/endpoints/builds.py" line_range="593" />
<code_context>
data['status'] = "SUCCEEDED"
- data['finished_at'] = str(
- datetime.datetime.now().isoformat())
+ data['finished_at'] = now()
- intermediate_registry_format = current_app.config["FOCA"].endpoints["builds"]["intermediate_registery_format"]
</code_context>
<issue_to_address>
**Retried completion repeats notifications**
When the completion callback is retried or delivered concurrently for the same build, both `build_completed` calls pass the repository check, trigger image signing, and call `notify_all_subscriptions` because completion does not check the build's current status or claim the transition atomically. The subscriber receives duplicate updates, and the later call overwrites the build's notification results.
Make completion an atomic, idempotent state transition and only dispatch signing and notifications for the request that claims it.
</issue_to_address>
### Comment 6
<location path="pubgrade/errors/exceptions.py" line_range="114" />
<code_context>
+# in the configuration); exceptions that aren't listed get those of their
+# closest listed base class
exceptions = {
Exception: {
- "msg": "An unexpected error occurred.",
- "status_code": "500",
</code_context>
<issue_to_address>
**Oversized requests return 500**
When a request body exceeds the advertised 1 MiB limit, werkzeug raises `RequestEntityTooLarge`, but the exception mapping has no entry for it or its `HTTPException` base, so it falls back to the generic `Exception` mapping and returns status 500 instead of 413.
Add a mapping for `RequestEntityTooLarge` or its `HTTPException` base that returns status 413.
Also at `pubgrade/config.yaml:14`.
</issue_to_address>
### Comment 7
<location path="pubgrade/modules/endpoints/builds.py" line_range="178" />
<code_context>
try:
- build_data["finished_at"] = "NULL"
- build_data["started_at"] = str(datetime.datetime.now().isoformat())
+ build_data["finished_at"] = None
+ build_data["started_at"] = now()
build_data["status"] = "QUEUED"
</code_context>
<issue_to_address>
**Old replicas reject unfinished builds**
When a new replica creates an unfinished build while an old replica is still serving requests for it, an old FOCA 0.7 replica serving a build created by the new version returns `finished_at: null`; its API schema requires a non-null date-time, so response validation fails and the caller receives an error during the rolling upgrade.
Use a cutover that prevents old replicas from serving new-format records, or otherwise delay writing nullable `finished_at` values until all old replicas are gone.
</issue_to_address>Linked issues
#62 build: move to a current FOCA base image · 3 of 3 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | The image builds on a current FOCA image and passes the tests. | ✅ Met | The Dockerfile uses FOCA 0.21.0 on Python 3.13; the PR reports a successful image build and passing tests. |
| 2 | The image scan fails CI on fixable critical and high findings. | ✅ Met | The CI scan matrix enables failure for the pubgrade image; the updater image remains report-only. |
| 3 | The Dependabot ignores for Python 3.9 are gone, and those packages are bumped. | ✅ Met | The Python-version package ignores are removed; pytest, coverage, Gunicorn, and Kubernetes are upgraded, while the unused setuptools dependency is dropped. |
Sourcery assessment
Needs a human reviewer. 7 findings to address first, and on startup, the app rewrites legacy timestamps in MongoDB, adding UTC offsets and changing unfinished-build values from "NULL" to null; those stored changes remain after a revert, though they are bounded and can be normalized. The image and API runtime also change substantially, but ordinary deployment or response bugs can be fixed by reverting.
Blocking findings: Dockerfile:30, pubgrade/gunicorn_config.py:13, pubgrade/modules/endpoints/subscriptions.py:366, pubgrade/modules/endpoints/builds.py:93, pubgrade/modules/endpoints/builds.py:593, and 2 more
Check that a body over the limit gets 413 and other werkzeug errors keep their status, as FOCA skips the catch-all Exception for exceptions with an HTTP status. Document that a pod of the previous version answers unfinished builds of the new one with 500 during a rolling update. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Moves Pubgrade off the FOCA 0.7 / Python 3.9 base image to FOCA 0.21 on
elixircloud/foca:0.21.0-py3.13(same digest as cloud-registry and Pubgrade-Sidecar), with the dependencies that come with it, makes the scan of the app's image blocking again, and drops the Dependabot ignores that held packages back for Python 3.9.foca==0.21.0,gitpython~=3.2.1,gunicorn~=26.2.0,kubernetes~=37.0.2;setuptoolsdropped; test extraspytest==9.2.0,coverage==7.17.2,mongomock==4.3.0(unchanged);python_requires=">=3.13".get_config()/app.config.focainstead ofconfig["FOCA"]; named API spec with a path relative to the config file;exceptions.mappingwith problem details (RFC 9457,application/problem+json) instead ofmsg/status_code;server.environmentanduse_reloaderremoved;server.max_content_length1 MiB (413).pubgrade.app:create_app(); the image serves it with Gunicorn and FOCA's settings (pubgrade/gunicorn_config.py: FOCA'sfoca.gunicorn_config, port 8080, one worker), but with 16 threads instead of 4, as a publish holds its thread until the subscribers answer, and a graceful timeout of 28 s, so a running publish can finish within Kubernetes' default grace period.GUNICORN_CMD_ARGSstays free for deployments.python -m pubgrade.appruns the development server.date-timevalues need a time zone. New timestamps are UTC with offset; a build'sfinished_atisnulluntil it finishes (was the string"NULL"). At startup,pubgrade/timestamps.pybrings stored builds and subscriptions into that format (naive values get+00:00,"NULL"becomesnull): it reads only documents that need repair, updates them only while they still hold the values it read, and logs how many it changed. Builds and subscriptions are also returned repaired, for objects that a pod of the previous version writes during a rolling update.finished_at). Unverified users get the 403 of the mapping as before; their exception now derives fromForbidden(wasUnauthorized), and a test checks that each exception's status matches its problem details.uv pip check; git installed for GitPython; OCI labels; runs as the FOCA image's user 1000 with read-only app files and/pubgrade_temp_fileswritable for group 0 (any UID works, as on OpenShift)..dockerignoreis now an allowlist.pubgradeimage fails on fixable critical and high findings again (as in cloud-registry). The scan ofpubgrade-updater(based onpython:3, not FOCA) stays report-only: its only finding is a setuptools vendored by pip in the base image, which this PR leaves to a separate decision.docs/api.md); upgrade notes "Upgrading to FOCA 0.21 (API 2.0.0)" (docs/deployment.md: config migration, errors, timestamps, Gunicorn, user 1000, MongoDB 4.4 or newer); tests on Python 3.13 and bumping FOCA (docs/development.md); README badge.Closes #62
Verification
make test(Python 3.13): 192 passed, 100% coverage,pubgrade/app.pyno longer omitted (new:tests/test_timestamps.py,tests/test_app.py,tests/test_exceptions.py,tests/test_image.pychecks the base image's FOCA againstrequirements.txt, the Gunicorn command, threads and user; config tests load the config with FOCA 0.21 and check the body limit; endpoint tests for builds and subscriptions in the old format).helm lint helm --strictandtests/chart.sh: OK.mkdocs build --strict: OK.docker buildandtests/smoke.shon the image as UID 12345, group 0, as in CI: passed; Gunicorn settings in the image: 1 worker, 16 threads, graceful timeout 28 s (also checked bytests/test_image.py).pubgradeimage (--ignore-unfixed --severity CRITICAL,HIGH): 0 findings.tests/e2e/upgrade.sh(k3s, two sites, Pubgrade-Sidecar fromdevon the new base, including the unreachable subscriber): "Upgrade test passed".Review
Full review (
adversarial-reviewerandquality-reviewer, two rounds). Round 1 fixed: unverified users' status, problem-detail texts, tests for the factory and the mapping, read-time repair for rolling updates, a filtered compare-and-set repair, 16 Gunicorn threads with docs on a buffering proxy, and a note on stored callback URLs without scheme. Round 2 fixed: Gunicorn settings in a module of the app (soGUNICORN_CMD_ARGSisn't taken) with a shutdown time for publishes, a test of the effective settings, and a compare-and-set test for notifications.Sourcery: 7 threads answered and resolved. 413 for oversized bodies holds (FOCA 0.21 uses the exception's own status before the catch-all; checked on the image and now pinned in
tests/test_exceptions.py). The window in a rolling update in which the old pod answers new unfinished builds with 500 is now in the upgrade notes. Unchanged behaviour ofdev(Git in the image for builds, notifier deadlines and ordering, completion idempotence, interrupted publishes) is beyond this PR.Declined review findings
dev, whose mapping already answered 403; only the exception's base class changed to match. The spec lists 403 for these operations.make test(low): pip already refuses withpython_requires>=3.13.current_appkept innotify_all_subscriptions(low): its threads need the app object for an app context; unchanged by this PR.Open questions
None.
🤖 Generated with Claude Code