Skip to content

test: run a real gateway plugin in live services - #658

Merged
uniqueg merged 5 commits into
devfrom
test/gateway-live-services
Nov 4, 2026
Merged

uniqueg merged 5 commits into
devfrom
test/gateway-live-services

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #656.

The integration tests and the chart install used petstore apps without plugins, so no real plugin ran in a live service, and no pod received pluginStore.existingSecret. This adds examples/gateway, a minimal gateway app:

  • a plugin built as a wheel and installed in the image, found through its foca.plugins entry point;
  • a Celery worker running the same pipeline, with MongoDB and RabbitMQ;
  • a thin chart over foca-common.

Test levels:

  • Integration job: the example in Docker Compose, tests/integration_gateway_tests.py. Checks that the plugin changes requests in the app and in a worker process (by process name), that both share the store in MongoDB, the exact hk: HMAC with the secret from the environment, and provenance.
  • Chart install: ct install in a namespace of its own (gateway-example), as the petstore steps select pods by their labels, with worker, bundled broker and pluginStore.existingSecret. helm test sends messages through app and worker and checks that their keys are equal. CI then fails on errors in their logs. release-chart.yml uses the same action, so it runs this too.
  • Unit: tests/examples/test_gateway.py, in-process with a fake entry point, so the example can't rot unnoticed where containers don't run.

Provenance names the plugin and its build key (a hash that includes the distribution's version and RECORD digest), not the version itself, so that is what the tests check; #656 is updated.

Docs: the example's README, docs/contributing/index.md, docs/helm-chart.md, docs/plugins.md.

How it was verified

Local:

  • ruff check, ruff format --check, mypy: clean.
  • pytest -m "not mongodb": 3195 passed, 1 skipped, before the last review fixes; the example's tests and the repository guards were rerun after them. pytest charts/foca-common/tests: 275 passed.
  • helm lint --strict on the chart with its CI values.
  • Tests first: the new tests failed before the example existed.
  • Live, without containers: real mongod 7.0.34 and Gunicorn with two workers, the plugin installed as a wheel. App path passed, including the HMAC and shared counts.
  • Reviewer: real prefork Celery worker with real mongod, on a Mongo broker.

Not run locally: Docker builds, RabbitMQ and rpc://, kind, helm test, the read-only root file system. No Docker socket in the sandbox. These ran only in CI.

CI on edf2996: all checks passed; since 995502b, helm test also compares the keys with the HMAC of the Secret's value. Details from the run on 995502b: Integration test (Python 3.13) and (Python 3.15): tests/integration_gateway_tests.py, 6 passed on each, with RabbitMQ and the worker in containers. Chart install: helm test pod gateway-example-test-plugin succeeded, with pluginStore.existingSecret, and no errors in the app's and worker's logs.

Declined review findings

  • The test re-implements key_for's derivation (quality): deliberate. It pins the documented form and proves this secret is used, which equal keys alone wouldn't.
  • The values repeat the petstore's blocks, keep them in sync (quality): accepted as is. The chart is for CI; the file says the petstore's explains them, and Dependabot covers both.
  • One-line comment for a Celery client per request (quality): resolved differently, one cached client per process.
  • Require authentication (Sourcery): a test fixture, like the petstore; the README says not to expose it.
  • Indexing entry_points() by name always fails (Sourcery): not a bug, the step passes in CI.

Found on the way, not in this PR

Celery's prefork children use a MongoClient opened in the parent: create_celery_app() registers MongoDB before the fork, and the plugin store in the child reuses it. PyMongo warns MongoClient opened before fork. Seen by the reviewer in a real worker run, as a library matter, not specific to this example. It needs its own issue.

🤖 Generated with Claude Code

uniqueg and others added 3 commits November 4, 2026 01:02
The integration tests and the chart install used petstore apps without
plugins, so no real plugin ran in a real pod, and no pod received
`pluginStore.existingSecret`.

Add `examples/gateway`, with a plugin installed as a distribution, a
Celery worker and a thin chart. The integration job tests it with
Docker Compose, the chart install with `helm test`, in a namespace of
its own, as its other steps select pods by their labels.

Closes #656

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Tell the worker from the app by the process name in the payload, so
that a pipeline run in the app can't pass as one in the worker. Retry
the worker in `helm test`, as it has no probes. Read the same result
backend as the worker, and reuse one Celery client per process. Check
the image, cover the chart in Dependabot, and describe the installation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A 500 is logged as an error, and CI fails on errors in the logs, so the
retry of `helm test` couldn't help. A worker that is still starting isn't
an error.

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

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces a minimal gateway application with a real wheel-installed plugin and Celery worker, then validates plugin execution, shared MongoDB state, secret-derived keys, and provenance through unit tests, Docker Compose integration tests, and a dedicated Helm chart installation in CI.

Sequence diagram for processing a message through the gateway plugin

sequenceDiagram
    actor Client
    participant App as Gateway app
    participant Broker as RabbitMQ
    participant Worker as Celery worker
    participant Plugin as Stamp plugin
    participant Store as MongoDB plugin store

    alt app request
        Client->>App: addMessage
        App->>Plugin: on_request
        Plugin->>Store: increment
        Plugin->>Store: key_for
        Plugin-->>App: stamped payload and provenance
        App-->>Client: processed response
    else worker request
        Client->>App: addWorkerMessage
        App->>Broker: send_task
        Broker->>Worker: process_message
        Worker->>Plugin: on_request
        Plugin->>Store: increment
        Plugin->>Store: key_for
        Plugin-->>Worker: stamped payload and provenance
        Worker-->>App: task result
        App-->>Client: processed response
    end
Loading

File-Level Changes

Change Details Files
Adds a production-shaped gateway example whose plugin is built, installed, discovered, and executed in both web and Celery worker processes.
  • Build the plugin as a wheel with a foca.plugins entry point and install it into a dependency-checked image.
  • Implement app and worker pipelines that exercise plugin mutation, MongoDB-backed shared state, HMAC-derived store keys, and provenance.
  • Add Docker Compose services for the gateway, worker, MongoDB, and RabbitMQ.
examples/gateway/Dockerfile
examples/gateway/plugin/gateway_example_plugin/__init__.py
examples/gateway/plugin/pyproject.toml
examples/gateway/config.yaml
examples/gateway/service.py
examples/gateway/controllers.py
examples/gateway/tasks.py
examples/gateway/worker.py
examples/gateway/wsgi.py
examples/gateway/docker-compose.yaml
examples/gateway/requirements.txt
examples/gateway/README.md
Extends automated coverage to validate the real plugin path at unit, container integration, and Helm installation levels.
  • Add in-process example smoke tests using a fake entry point, including validation, worker timeout handling, and task execution.
  • Add container integration tests for app/worker execution, shared counts, exact HMAC keys, provenance, and invalid requests.
  • Add a Helm test pod that sends requests through both processes and verifies shared store behavior and plugin provenance.
tests/examples/test_gateway.py
tests/integration_gateway_tests.py
examples/gateway/chart/templates/tests/test-plugin.yaml
Integrates the gateway example into chart packaging and CI workflows, including secret-backed plugin-store configuration.
  • Add a thin foca-common-based chart with worker, bundled RabbitMQ, MongoDB, security settings, and pluginStore.existingSecret support.
  • Build and load gateway images, run Compose integration tests, lint the chart, and install/test it in a dedicated kind namespace.
  • Collect gateway resources and logs on failure and fail CI on application or worker errors.
examples/gateway/chart/Chart.yaml
examples/gateway/chart/Chart.lock
examples/gateway/chart/values.yaml
examples/gateway/chart/ci/test-values.yaml
examples/gateway/chart/templates/*.yaml
.github/actions/install-chart/action.yml
.github/actions/test-chart/action.yml
.github/workflows/ci.yml
Updates repository maintenance, documentation, dependency automation, and version-mention guards for the new example and chart.
  • Document local gateway integration testing and explain its role in plugin and Helm coverage.
  • Track gateway Python, Docker, and Helm dependencies with Dependabot.
  • Update pre-commit and chart-version validation rules for gateway chart files.
docs/contributing/index.md
docs/helm-chart.md
docs/plugins.md
.github/dependabot.yml
.pre-commit-config.yaml
tests/test_version_mentions.py
.gitignore

Possibly linked issues


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 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (242633b) to head (edf2996).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #658   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           56        56           
  Lines         7189      7189           
=========================================
  Hits          7189      7189           
Flag Coverage Δ
test_unit 100.00% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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 4, 2026 00:35

@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 5 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="examples/gateway/config.yaml" line_range="1" />
<code_context>
+server:
+    host: '0.0.0.0'
+    port: 8080
</code_context>
<issue_to_address>
**Unbounded request bodies**

When an unauthenticated client can reach the published app port and sends an oversized JSON request, connexion parses the JSON body before `addMessage` or `addWorkerMessage` runs, so Flask buffers attacker-controlled data without a configured limit and a sufficiently large request can exhaust the app's memory, taking its endpoints down.

Set a finite `server.max_content_length` for the example, or enforce an equivalent request-size limit at the ingress or proxy.
</issue_to_address>

### Comment 2
<location path="examples/gateway/gateway.yaml" line_range="12-24" />
<code_context>
+servers:
+  - url: http://localhost/
+paths:
+  /messages:
+    post:
+      description: Runs a message through the plugin pipeline in the app
+      operationId: addMessage
+      requestBody:
+        $ref: '#/components/requestBodies/Message'
+      responses:
+        '200':
+          $ref: '#/components/responses/Processed'
+  /messages/worker:
+    post:
+      description: Runs a message through the plugin pipeline in the worker
+      operationId: addWorkerMessage
+      requestBody:
+        $ref: '#/components/requestBodies/Message'
</code_context>
<issue_to_address>
**Unauthenticated task submission**

When a caller can reach the exposed app port, connexion routes anonymous requests to `addMessage` and `addWorkerMessage`; the latter submits each request to Celery, while both run the plugin that mutates shared store state, so an unauthenticated caller can consume worker, broker, and app capacity.

Require appropriate authentication and authorization for the request-processing operations, or otherwise restrict their exposure and rate-limit submissions.
</issue_to_address>

### Comment 3
<location path="examples/gateway/controllers.py" line_range="68" />
<code_context>
+        problem details and status 503 if the worker didn't answer in time,
+        e.g., as it is still starting.
+    """
+    result = _celery_client().send_task(TASK_NAME, args=[body])
+    try:
+        data: dict[str, Any] = result.get(timeout=WORKER_TIMEOUT)
</code_context>
<issue_to_address>
**Broker failures return server errors**

When rabbitMQ is unavailable or rejects the publish, `send_task` runs outside the `try` and its exceptions are not handled, so a broker connection or publish failure escapes the controller and the caller receives a 500 instead of a service-unavailable response.

Handle Celery publish/connection errors and return a 503 response, logging the dependency failure appropriately.
</issue_to_address>

### Comment 4
<location path=".github/workflows/ci.yml" line_range="377" />
<code_context>
+          image=foca-gateway-example:latest
+          scripts/check-no-pip.sh "${image}"
+          docker run --rm "${image}" python -c \
+              "from importlib.metadata import entry_points as e; assert e(group='foca.plugins')['org.example.gateway.stamp']"
+      - name: Wait for gateway example
+        working-directory: examples/gateway
</code_context>
<issue_to_address>
**Integration image check always fails**

When the integration job runs its gateway image check, `entry_points(group="foca.plugins")` returns an `EntryPoints` sequence, so indexing it with the plugin name raises `TypeError` instead of checking the installed entry point; the integration job stops before its tests run.

Select or search the returned entry points by their `name` instead of indexing the sequence by name.
</issue_to_address>

### Comment 5
<location path="examples/gateway/chart/templates/tests/test-plugin.yaml" line_range="37" />
<code_context>
+    - |
+      import json, os, time, urllib.error, urllib.request
+
+      def send(path):
+          request = urllib.request.Request(
+              os.environ["GATEWAY_URL"] + path,
</code_context>
<issue_to_address>
**Wrong store secret passes chart test**

When the app and worker use the same incorrect secret, or a secret other than the one created for the test, the Helm test checks only the `hk:` prefix and equality between process keys, so the same wrong key passes without verifying that `pluginStore.existingSecret` supplied it.

Assert that the key matches the expected value derived from the test's `pluginStore.existingSecret`.

Also at `examples/gateway/chart/templates/tests/test-plugin.yaml:63`.
</issue_to_address>

Linked issues

#656 test: run a real gateway plugin in live services · 8 of 8 met

# Requirement Status Notes
1 Add a minimal gateway example with a real plugin installed as a distribution with a foca.plugins entry point. ✅ Met The gateway image builds and installs the plugin wheel, and the plugin declares its entry point.
2 Run the example in Docker Compose in the integration job, with its own tests. ✅ Met CI builds and starts the gateway services and runs tests/integration_gateway_tests.py.
3 Install the example's thin foca-common chart with app, worker, broker and pluginStore.existingSecret, and check it with helm test. ✅ Met The chart install creates the plugin Secret, installs the gateway chart in its own namespace, and runs the plugin test hook.
4 The plugin runs in the app process and a Celery worker in real containers, and changes the request. ✅ Met The integration tests check the plugin's stamp and distinguish app and worker processes.
5 ctx.store is shared through MongoDB across requests and processes. ✅ Met The integration test checks shared store mode and an increasing count across app and worker requests.
6 FOCA_PLUGINS_STORE_KEY_SECRET reaches the app and worker, producing the same hk: value. ✅ Met The integration test checks each process's exact HMAC-derived key against the configured secret.
7 Provenance names the installed plugin and its build key. ✅ Met The integration test checks the plugin ID in provenance and the sha256: build-key format.
8 Document the example and describe examples and integration tests. ✅ Met The PR adds the example README and updates the contributing guide's integration-test instructions.

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and if the example’s plugin-store wiring is wrong, requests can leave incorrect counter entries in MongoDB’s persistent store; reverting the code will not remove those records. The state is limited to the example and can be cleared or recreated.

Blocking findings: examples/gateway/config.yaml:1, examples/gateway/gateway.yaml:24, examples/gateway/controllers.py:68, .github/workflows/ci.yml:377, examples/gateway/chart/templates/tests/test-plugin.yaml:37


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread examples/gateway/config.yaml Resolved
Comment thread examples/gateway/gateway.yaml Resolved
Comment thread examples/gateway/controllers.py Resolved
Comment thread .github/workflows/ci.yml Resolved
The test required only equal keys in app and worker, which any secret
passes: derive the expected key from the Secret instead. Answer 503 if
the broker can't be reached, limit request bodies, and say that the
example has no authentication.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 6684cd9 into dev Nov 4, 2026
80 checks passed
@uniqueg
uniqueg deleted the test/gateway-live-services branch November 4, 2026 01:10
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.

test: run a real gateway plugin in live services

1 participant