Repository navigation
feat(plugins): add default failover router - #504
Conversation
Add `foca.plugins`, a framework-neutral engine for gateway plugins: - plain request model (`InboundRequest`, `Backend`, `OutboundRequest`, `BackendResponse`, `Principal`, case-insensitive `Headers`) and an explicit `Context` per hook call; no Flask, Werkzeug or Connexion types, so plugins run unchanged after the move to Connexion 3 - `Plugin` base with `on_request`, `on_route`, `on_forward` and `on_response` hooks, `NotApplicable`, `Rejected` and `PluginError` - allowlisted loading of entry points (group `foca.plugins`) with distribution and version pins, `RECORD` digests, `enabled: false` kill switch and a startup error with a migration hint for legacy `middlewares` keys - steps with ordered alternatives, copy-and-commit per alternative, failure semantics, timeouts via a bounded thread pool, forwarding attempts with "not accepted" / "outcome unknown" outcomes, a total `forward_timeout`, `Via` headers, loop detection (508) and no routing to the gateway's own public URL - `foca.plugins.adapter`, the only module using Connexion 2 / Flask - config section `plugins`, docs pages, and an ast-grep rule that keeps framework imports out of `foca/plugins` except the adapter Co-Authored-By: Claude Opus 5.5 <[email protected]>
What proTES needs to adopt the engine: - `Foca(gateway=GatewayApp(api, validate, sanitize, validate_outbound))` declares a gateway app; `create_app()` loads its plugins once to fail fast, and `foca.plugins.runtime.get_host()` gives controllers and Celery tasks the host of their process, created on first use after forks (no Flask app context needed) - legacy `middlewares` keys are refused before the app's strict `custom` model is validated - errors of the app's `sanitize` (e.g. 413) stop the request unchanged; `validate` failures stay invalid output - `validate_outbound` per attempt (reason `invalid_outbound`) - `NotAccepted`/`OutcomeUnknown` exceptions with reason codes for the app's client, and `Attempt.report()` - adapter: `request_id()` from a safe `X-Request-ID` or a new one; `Principal.groups` are the mapped roles of access control - string short form of steps (`- <plugin id>`) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Let clients choose the pipeline and the backends of a request in two
reserved tags, under the configurable prefix `plugins.tags.prefix`
(default `gateway.`):
- `gateway.pipeline`: a preset name (`plugins.presets`) or a pipeline
as JSON, validated and authorized before any plugin runs (limits,
roles, `client_selectable`, uniform "plugin not available" errors)
and framed by `client_pipelines.prepend`/`append` (`if_missing_phase`
for a default route step)
- `gateway.backends`: `{"type": "order" | "allow" | "forbid",
"backends": [...]}`, applied to the routed candidates; items that are
no candidates are discarded and recorded
- any other client tag under the prefix is refused with 400
Presets and frames are resolved on startup; presets that need a
disabled plugin are unavailable. Gateway errors move to
`foca.plugins.errors`. `foca.utils.urls` imports Flask only in
`get_public_url()`.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`run.provenance()` describes a pipeline run as plain JSON data for the app to store with its resource: - prospective: pipeline source, preset, the client's tag by reference, the resolved pipeline and its `sha256:` hash of the RFC 8785 canonical JSON (own implementation, tested with the RFC's vectors) - retrospective: hook calls with build keys, outcomes, timings, sanitized errors, annotations and changes as hashes and JSON Pointers without values (`plugins.provenance.detail: paths`); route candidates, the client's backend selection, attempts and the final reason - engine: FOCA, plugin API and app versions (`GatewayApp(name, version)`) `ProvenanceStore` takes collections of the app: plugin builds (with an optional image digest from `FOCA_IMAGE_DIGEST`) and default or preset pipelines are stored once by hash; client pipelines stay inline. Failed runs are stored only with `plugins.provenance.record_failed` (default off), with documented TTL index specs. Hook records keep changes instead of the data before and after. The engine's usage example now catches `OutcomeUnknown` before its base class. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.utils.http` sends requests to URLs from users and registries without becoming an SSRF vector, on requests/urllib3 only: - `GuardedClient` checks the peer address of each new connection after connecting and before sending (so DNS rebinding cannot reach internal hosts), never follows redirects, ignores proxies and `.netrc` of the environment, allows `https` only and always verifies TLS, bounds requests by a deadline (connect timeout capped at 10 s) and response bodies by size, and returns a plain `HttpResponse` - errors carry reason codes and tell requests that certainly did not reach the server (`RequestNotSent`) from those that may have (`RequestMaybeSent`), for gateway outcomes - `is_public_address()`, `check_public_host()` and `fetch_json()`, moved from proTES Plugins get a client bound to their deadline as `ctx.http`, configured by `plugins.defaults.http`. The framework-import rule covers the client. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.plugins.backends` gives gateway apps one ordered list of typed backend entries, under a key of their own (proTES: `custom.tes.backends`), replacing configured lists plus one registry: - `ga4gh-tes` entries (`url`, `url_schemes` default `["https"]`, `id`, `auth`, `basic` env var names, `labels`, `location`) and `ga4gh-service-registry` entries (`https` only, refresh interval, timeout, version prefixes, environments, `auth` and labels for the discovered backends, `allow_private_addresses`); unique ids, normalized URLs without user info - registry discovery moved from proTES and made generic by API type: verified services only, type/version/environment filters, `https`, public hosts, no redirects, no token; cache per entry and process with last-good fallback, retries after 30 s at most, fork-safe locks - `BackendList.expand()`: candidates in entry order, de-duplicated by URL at the first position with configured settings winning, the gateway's own public URL and everything below it left out - `entry_for()`, `find(url, refresh=True)` (rate-limited registry re-read, for other processes), `snapshots()` and `describe()` Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.routing.ordered` (`foca.plugins.routing.OrderedRouter`) is the least surprising route step: it keeps the order of the backend list and shuffles the backends of each service registry among themselves (`random.SystemRandom`), with no round-robin state. Optional params: `labels` (keep only candidates with them) and `seed` (tests only, refused unless the admin setting `allow_seed` is on). - FOCA registers it as an entry point; built-ins (`foca.*`, a reserved prefix) are available without a `plugins.available` entry, which may only set `enabled`, `roles`, `client_selectable` and `config`; other distributions must not provide them, and they load from their object reference if FOCA's metadata lacks the entry point - it is the default pipeline, and the default `client_pipelines.append` step for pipelines without a route step (`on_failure: skip`) - `Plugin.check_params()` lets plugins refuse params when pipelines are resolved - `run.route(candidates, snapshots=...)` records the registry read times in the provenance Refs #491 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes: - outbound `Via` headers are the inbound request's with this gateway's entry appended (RFC 9110, section 7.6.3), whatever plugins or the app's builder set, so that loops through several gateways are detected (A -> B -> A) - each call gets its own deep copy of the step's parameters, and the caller's claims as a read-only deep copy, so that a hook cannot change them for later calls, requests or provenance - hooks raising `SystemExit` and other `BaseException`s fail like others; `KeyboardInterrupt` and `GeneratorExit` propagate Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.security.access_control.get_current_claims()` returns a copy of the claims of the current request's token, next to `get_current_subject()` and `get_current_groups()`; the plugin adapter uses it instead of a private helper. Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Apps that configure `plugins` without `Foca(gateway=...)` get a startup warning, as the section is validated but not used. The docs say that there is no runtime API for operators, summarize the steps for gateway app authors, and note that plugins are instantiated once more per process after the startup check. Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.plugins.engine` keeps the host, runs and attempts; the rest moves along its seams, with the public imports from `foca.plugins` and `foca.plugins.engine` unchanged: - `errors`: gateway errors with problem details - `outcomes`: `NotAccepted`, `OutcomeUnknown`, `sanitize_error()` and the engine's internal errors - `records`: resolved pipelines, hook call and attempt records - `executor`: the bounded thread pool of hook calls - `checks`: outbound requests, `Via` names and hook output checks Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes of #486; the engine split is redone on this branch's engine module. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes of #486; the engine split is redone on this branch's engine module. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes and engine split of #486. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes and engine split of #486. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes and engine split of #486. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the second review round of the plugin engine: - Claims of the caller are a FrozenMapping, which plugins can keep in their state: unlike MappingProxyType, it can be deep-copied and pickled. The engine copies state and candidates inside the guarded block, so a failing copy fails that alternative only, not the request. - The engine sets Via before the app's outbound check; inbound Via headers longer than 1024 characters are refused (400, InvalidVia). Docs say that the inbound Via is passed through verbatim. - The default gateway_id is the host and port of the public URL, without user information, and only if it matches the gateway_id pattern. - setup() of plugins may run more than once per process (docstring and author docs); tests import internals from their new modules. Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # foca/plugins/__init__.py # foca/plugins/engine.py
# Conflicts: # foca/plugins/engine.py
# Conflicts: # foca/plugins/engine.py # tests/plugins/test_plugin_engine.py
CodeQL flagged reflected XSS in a view that only exists for its URL rule. Return a constant instead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Principal.token is set only if a token was validated (claims). - Repeated header fields of inbound requests are combined (e.g., Via). - Problem responses keep the custom title of a plugin's rejection; problem_response() takes a request-specific title. - Annotations reject NaN and infinite numbers. - Plugins loaded before a load or pipeline error are closed. - Gateway names bracket IPv6 addresses (pattern GATEWAY_ID_PATTERN), and the outbound Via header, with this gateway's entry, stays within 1024 characters. - One gateway app per process: configure() refuses other settings while a host is in use; reset() closes it; the host is closed at exit. - Docs: app callbacks run outside plugin deadlines and must be fast; rejections in the response phase count as errors. Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # foca/plugins/config.py # foca/plugins/engine.py
Dev has the squash of #499 (provenance), whose tree equals feat/plugin-provenance, already merged here; conflicts in foca/plugins/context.py and tests/plugins/test_plugin_engine.py are resolved to this branch's tree.
One GuardedClient shared its end, timer and sockets across requests, so concurrent requests (e.g., of a plugin that fans out) overwrote each other's deadlines: one request finishing cancelled another's timer, and its own timer then shut the other's sockets down. Each request now gets its own guard, found by its connections per thread (urllib3 connects, sends and reads in the request's thread); pooled connections that a request reuses are tracked in its guard, and the guard finishes before the connection goes back to the pool, so a late timer cannot stop a socket that another request uses. No lock serializes requests. Tests: two concurrent requests with overlapping deadlines, a deadline on a reused connection. Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
A json body that is no JSON (NaN, a set, other objects) gave an InvalidJSONError classified as connection_lost, or a raw TypeError, although nothing was sent; a header with a line break gave invalid_url. Both now raise InvalidRequest (a RequestNotSent, reason invalid_request or invalid_header) before sending, so all errors stay HttpErrors. The dead InvalidHeader branch of _classify is gone. Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Connections checked all resolved addresses but connected only to the first, losing urllib3's fallback across A/AAAA records. They now try the checked addresses in order within one connect budget; the peer of the one that connects is checked as before. Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
While one thread read a registry, the others got the cached backends, which are none before the first read and after an idle gap longer than max_stale, so requests found no discovered backends although a read was about to deliver them. Threads now wait for the read unless a good read within max_stale is cached; with one, they keep getting it while the refresh runs. Tests use two real threads. Refs #493 Co-Authored-By: Claude Opus 5.5 <[email protected]>
A discovered backend's id is its URL, which can equal a configured entry's custom id for another URL; candidates then had two backends with one id, and the client's backend selection could pick the wrong one. expand() now skips such discovered backends (logged at debug level). Refs #493 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The appended router's if_missing_phase also counted the admin's prepend steps, so a route plugin in prepend dropped foca.routing.ordered from every client and preset pipeline. Only the client's or preset's own steps count now. Refs #491 Co-Authored-By: Claude Opus 5.5 <[email protected]>
client_pipelines.prepend frames client and preset pipelines only, not plugins.pipeline, so pinning that must always hold belongs in both. The router's module docstring now says that BUILTIN_PLUGINS is its only source, not an entry point. Refs #491 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Python 3.14 parses unbalanced deep arrays without RecursionError, so the ValueError branch of HttpResponse.json was not covered in CI. The test now also forces the RecursionError. Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Error messages name URLs without user info, query and fragment, with control characters escaped (_redact). - Guards track connections, not sockets: a connection belongs to the request that uses it, so a late timer of an earlier request no longer stops it, and one that such a timer stopped is closed before reuse. Timers shut down the current socket of a connection, so TLS sockets that wrap the new one are stopped too. - Sessions keep no cookies, and are created once under a lock. - Docs: cookies, redacted messages, and why network-specific NAT64 prefixes are not checked. Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
CodeQL flags host substring checks in tests; compare the whole message instead (with an escape character, since urlsplit drops line breaks itself). Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The retry interval is the difference of two monotonic floats, which is not exact (29.999... in CI). Refs #493 Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Services whose verified API version differs from the offered one are not used. - Next reads and staleness count from the end of a registry read. - Threads wait for a running read if the cache expires meanwhile. - The own-URL check compares effective ports; default ports of http and https still count as the same. - expand(snapshots=...) records the read that the candidates of each registry come from; URLs and read time are published together. - Registry timeouts are finite; backend entries must be ordered. Refs #493 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refs #491 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideImplements Sequence diagram for ordered backend failoversequenceDiagram
participant PipelineRun
participant OrderedRouter
participant Backend
PipelineRun->>OrderedRouter: on_route(candidates, ctx)
OrderedRouter->>OrderedRouter: filter candidates by labels
OrderedRouter->>OrderedRouter: shuffle discovered backends per registry group
OrderedRouter-->>PipelineRun: ordered candidates
PipelineRun->>Backend: forward request to next candidate
alt backend certainly did not accept request
PipelineRun->>Backend: forward request to next candidate
else unknown outcome
PipelineRun-->>PipelineRun: stop failover
end
Flow diagram for default and client routing pipelinesflowchart LR
Config[PluginsConfig] --> Default[Default pipeline]
Config --> Client[Client or preset pipeline]
Default --> Router[foca.routing.ordered]
Client --> Frame[client_pipelines framing]
Frame --> Missing{Route phase missing?}
Missing -->|Yes| Router
Missing -->|No| Existing[Existing route step]
Router --> Resolve[Resolve plugin parameters]
Existing --> Resolve
File-Level Changes
Assessment against linked issues
Possibly linked issues
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/plugins/engine.py" line_range="390" />
<code_context>
f"Invalid params of plugin {alternative.plugin!r} in step"
f" {step.id!r}: {exc}"
) from exc
+ except Exception as exc:
+ logger.exception(
+ "Plugin %s failed to check params", alternative.plugin
</code_context>
<issue_to_address>
**SystemExit bypasses plugin error handling**
When a plugin’s `check_params()` raises `SystemExit` while a pipeline is resolved, `resolve_steps()` catches only `Exception` from `check_params()`, so `SystemExit` bypasses the `PluginError` handling and can terminate the request worker or process while resolving a pipeline.
Handle `SystemExit` from `check_params()` in the same plugin-error path as other plugin failures.
Also at `foca/plugins/engine.py:392`.
</issue_to_address>
### Comment 2
<location path="foca/plugins/loader.py" line_range="304-305" />
<code_context>
continue
- entry_point = _find(plugin_id, candidates)
+ entry_point = (
+ _find_builtin(plugin_id, candidates)
+ if plugin_id in BUILTIN_PLUGINS
+ else _find(plugin_id, candidates)
+ )
</code_context>
<issue_to_address>
**Disabled built-in conflicts go unchecked**
When the built-in is disabled in `plugins.available` and another distribution registers the same identifier, `find_entry_points()` skips disabled plugins before it reaches `_find_builtin()`, so a foreign distribution that claims a reserved built-in ID is not refused when that built-in is disabled. The installation can therefore pass startup despite violating the stated built-in ID ownership rule.
Check for conflicting built-in entry points independently of whether the built-in plugin is enabled.
</issue_to_address>
### Comment 3
<location path="foca/plugins/engine.py" line_range="384" />
<code_context>
try:
params = loaded.cls.Params.model_validate(alternative.params)
- except ValidationError as exc:
+ loaded.instance.check_params(params)
+ except (ValidationError, InvalidParams) as exc:
raise ValueError(
</code_context>
<issue_to_address>
**Plugin bug becomes client 400**
When a plugin's `check_params()` raises Pydantic's `ValidationError`, `resolve_steps()` catches `ValidationError` from either parameter validation or `check_params()` and wraps it as `ValueError`; `resolve()` then reports it as an invalid client selection instead of a plugin failure, so the caller receives a misleading 400.
Handle parameter-model validation separately from `check_params()`, and classify only `InvalidParams` from the latter as invalid parameters.
</issue_to_address>
### Comment 4
<location path="tests/plugins/test_plugin_routing.py" line_range="90-91" />
<code_context>
+
+def test_no_groups() -> None:
+ """Configured backends only are not shuffled."""
+ ids, run = route({"labels": {"region": "us"}, "seed": None})
+ assert sorted(ids) == ["r0", "r2"]
+ ids, run = route({"labels": {"nothing": "x"}})
+ assert ids == []
</code_context>
<issue_to_address>
**No-group case is not exercised**
When the router shuffles candidates when the input has no discovered registry groups, `test_no_groups` (`tests/plugins/test_plugin_routing.py:90-94`) filters to `r0` and `r2`, which are discovered candidates in group `reg`, then sorts their IDs; its other case routes no candidates. A router that shuffles candidates when there are no registry groups therefore passes without exercising that behavior.
Route at least two configured candidates with no registry group and assert their exact order.
</issue_to_address>
Sourcery assessment
Approval pending. 3 findings to address first.
Blocking findings: foca/plugins/engine.py:390, foca/plugins/engine.py:384, tests/plugins/test_plugin_routing.py:91
- Only InvalidParams from check_params means invalid params (400); validation errors, SystemExit and other errors of the hook are plugin errors. - Other distributions must not claim built-ins, even disabled ones. - test_no_groups routes configured backends only, in exact order. Refs #491 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Adds
foca.routing.ordered(foca.plugins.routing.OrderedRouter), the default route step of gateways and the least surprising one. It keeps the order of the backend list, and shuffles the backends of each service registry among themselves (random.SystemRandom), with no round-robin state. This is the sixth PR of the v0.18.0 plugin stack (#485).labels: keep only candidates that have them.seed: for tests only, refused unless the admin settingallow_seedis on.BUILTIN_PLUGINSis the only source of built-in plugins; there is no entry point in FOCA's metadata.foca.*prefix) are available without aplugins.availableentry. Such an entry may set onlyenabled,roles,client_selectableandconfig.client_pipelines.appendstep for pipelines without a route step.if_missing_phaselooks only at the client's or preset's own steps.Plugin.check_params()lets plugins refuse params when pipelines are resolved, by raising the newInvalidParams(400). Other exceptions count as plugin errors.Closes #491
Verification
Run locally on 85f85d0 (with dev merged):
ruff checkandruff format --check: pass.mypy: pass.pytestwithout MongoDB: pass, with 100% coverage offoca/pluginsandfoca/utils/http.py.mkdocs build --strict: pass.pre-commit: pass.The MongoDB tests and semgrep did not run locally (CI runs them). CI on 85f85d0: 27 checks pass, and 2 are skipped as intended.
Review: two rounds of adversarial and quality review.
check_paramswas reported as invalid params;client_pipelines.prependdropped the appended router (85f724d);All are fixed.
Sourcery: 4 findings, all fixed in a9c8dac:
InvalidParamsfromcheck_paramsgives 400; validation errors,SystemExitand other errors are plugin errors;test_no_groupsnow checks configured backends in exact order.CI on a9c8dac: 28 checks pass, and 2 are skipped as intended.
Declined review findings
🤖 Generated with Claude Code