Repository navigation
feat(plugins): resolve per-request pipelines - #498
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]>
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]>
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
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
Guard against names in foca.plugins.__all__ that do not resolve (e.g., a missing import), as noticed by proTES. Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
A merge dropped InvalidVia from the imports of foca.plugins, though it is still in __all__; the test of the exported names catches this now. Refs #487 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the pre-review of per-request pipelines and backends: - Tags that are not a map give 400 (reserved-tag) instead of being ignored, which skipped the check of reserved tags. Apps of APIs other than TES must pass tags= to start() (TypeError otherwise); the default is a typed sentinel. (start() takes no pipeline= argument any more since the per-request pipelines landed; callers pass tags.) - Whether choices are enabled is checked in one place, when the tags are read, and before their values are parsed. - The backends tag is at most 8 KiB before it is parsed, and lists at least one backend. - Presets need the roles of their plugins (not client_selectable, as admins write them); unknown presets get the same message. - Preset steps with the identifier of a frame step and client_pipelines.allowed: [] are refused at startup; the message for preset names without presets allowed says so. - PRESET_PATTERN is defined once (config), the item length limit is not repeated in its message, the unused ClientSelection.backends_raw and the PROBLEM_TYPE_BASE re-export of the engine are removed. - Tests: random client pipelines from allowed and forbidden plugins never let a forbidden one through; unknown plugins in prepend fail at startup; WES tags; limits of the backends tag. foca/utils/urls.py keeps its lazy Flask import: get_public_url() needs the request context, while the other URL helpers serve the framework-free foca.plugins, which must import without Flask. Refs #487 Co-Authored-By: Claude Opus 5.5 <[email protected]>
A preset or client pipeline (even an empty one) runs instead of plugins.pipeline; only the frame runs for every request, so policies belong in client_pipelines.prepend. Also name the available keys client_selectable and roles, the preset role rule, the limits of the backends tag, and the problem types invalid-via and gateway-error. Refs #487 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Client pipelines with NaN, Infinity, non-finite numbers (1e999) or integers beyond 2^53 - 1 are refused (400): RFC 8785 hashes of the resolved pipeline cannot represent them, so provenance would fail after the backend accepted, or pipelines would collide. Refs #487 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the second review round of client pipelines: - Tag values with unpaired surrogates are refused with 400 instead of failing with a UnicodeEncodeError; client pipelines must be valid Unicode (strings and keys) and are nested 32 levels deep at most. - Identifiers of client pipelines and presets clash only with the frame steps that are kept: appended defaults (if_missing_phase) that are left out no longer block the same identifiers; presets are checked against them at startup. Errors say to set an explicit id, and the client's error no longer names the gateway's steps. - A _has_role() helper replaces three role checks; InvalidSelection sits next to InvalidVia; STEP_ID_PATTERN has its docstring back. - Docs no longer say that discarded backends are recorded (#488 adds that). Refs #487 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR enables clients to select bounded, role-authorized presets or inline pipelines and narrow or reorder routed backends per request, while admins retain control through plugin allowlists, frames, presets, limits, reserved-tag validation, uniform errors, and startup checks. Sequence diagram for per-request pipeline and backend selectionsequenceDiagram
actor Client
participant Host as PluginHost
participant Selection as selection
participant Run as PipelineRun
Client->>Host: start(inbound, principal, tags)
Host->>Selection: parse_client_tags(tags, prefix, limits)
Selection-->>Host: ClientSelection
Host->>Host: resolve(pipeline, principal)
alt inline pipeline
Host->>Selection: parse_client_pipeline(value)
Selection-->>Host: validated steps
end
Host->>Run: PipelineRun(pipeline, selection)
Run->>Run: route(candidates)
Run->>Selection: apply_backend_selection(routed, backends)
Selection-->>Run: filtered or reordered candidates
Run-->>Client: execute selected pipeline and backends
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@@ Coverage Diff @@
## dev #498 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 43 44 +1
Lines 4458 4749 +291
==========================================
+ Hits 4458 4749 +291
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 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/plugins/selection.py" line_range="398-399" />
<code_context>
+ """
+ keys: dict[str, Backend] = {}
+ for backend in candidates:
+ keys.setdefault(backend.id, backend)
+ keys.setdefault(_key(backend.url), backend)
+ listed: list[Backend] = []
+ discarded: list[str] = []
</code_context>
<issue_to_address>
**Backend choices target the wrong candidate**
When a candidate's ID equals another candidate's URL or normalized URL, `apply_backend_selection` stores IDs and normalized URLs in one dictionary and checks the raw item in that shared namespace first, so an allow or forbid choice by URL can resolve to the wrong backend and fail to enforce the requested selection.
Resolve backend IDs and normalized URLs in separate namespaces.
Also at `foca/plugins/selection.py:403`.
</issue_to_address>
### Comment 2
<location path="foca/plugins/selection.py" line_range="173-174" />
<code_context>
+ f"Tags under {prefix!r} are reserved for the gateway: {reserved[0]}",
+ slug="reserved-tag",
+ )
+ pipeline = tags.get(f"{prefix}{PIPELINE_TAG}")
+ raw = tags.get(f"{prefix}{BACKENDS_TAG}")
+ if pipeline is not None and not pipelines_enabled:
+ raise InvalidSelection("Choosing pipelines per request is disabled")
</code_context>
<issue_to_address>
**Null choice tags bypass rejection**
When a caller supplies `gateway.pipeline: null` or `gateway.backends: null`, `parse_client_tags` treats the reserved tag as absent, skips parsing and validation (including disabled-choice checks), and uses the default pipeline or unrestricted server candidate set instead of returning a 400 response.
Reject reserved choice tags that are present with a `None` value.
Also at `foca/plugins/selection.py:175-177`.
</issue_to_address>
### Comment 3
<location path="foca/plugins/selection.py" line_range="334" />
<code_context>
+ InvalidSelection: The value is not a valid pipeline.
+ """
+ try:
+ data = json.loads(value, parse_constant=_reject_constant)
+ if not isinstance(data, list):
+ raise TypeError("not a list")
</code_context>
<issue_to_address>
**Duplicate keys bypass I-JSON validation**
When an inline pipeline contains duplicate object member names, `json.loads` collapses duplicate keys before `check_i_json` runs, so `parse_client_pipeline` accepts ambiguous input that violates the I-JSON contract and uses whichever duplicate value the parser retains.
Reject duplicate object member names during JSON decoding before they are collapsed.
</issue_to_address>
### Comment 4
<location path="foca/plugins/config.py" line_range="518-521" />
<code_context>
" 'plugins.available'"
)
+ frame = self.client_pipelines
+ reserved = {
+ step.id
+ for step in (*frame.prepend, *frame.append)
+ if step.if_missing_phase is None
+ }
+ for name, steps in self.presets.items():
</code_context>
<issue_to_address>
**Dropped frame steps block startup**
When a frame step's plugins are all disabled and the step uses `on_failure: skip`, while a preset uses its ID, `_check_references` reserves IDs from the raw frame configuration even when a frame step has no enabled plugin and `on_failure: skip`; the engine drops such steps during resolution, but the config validator still rejects a preset reusing their IDs, so the application fails to start for a non-clashing configuration.
Check preset/frame ID clashes against the resolved steps that are actually retained, rather than reserving IDs from dropped frame steps.
</issue_to_address>
### Comment 5
<location path="foca/plugins/config.py" line_range="320" />
<code_context>
+ )
+ max_steps: PositiveInt = 8
+ max_alternatives: PositiveInt = 3
+ max_size: PositiveInt = 8192
+ roles: list[str] = []
+ prepend: list[StepConfig] = []
</code_context>
<issue_to_address>
**Default pipeline size exceeds stated cap**
When the default configuration is used and a pipeline tag is larger than 2 KiB but no larger than 8 KiB, `max_size` defaults to 8192, so `parse_client_tags` accepts pipeline tag values larger than the stated 2 KiB limit.
Set the default `max_size` to 2048 bytes.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 5 findings to address first, and per-request pipeline choice is enabled by default, and a client-supplied pipeline—including an empty one—replaces the configured default; policies not placed in prepend can therefore be skipped by authenticated callers. Reverting stops future choices, but cannot undo processing or forwarding effects that already occurred.
Blocking findings: foca/plugins/selection.py:399, foca/plugins/selection.py:174, foca/plugins/selection.py:334, foca/plugins/config.py:521, foca/plugins/config.py:320
- Backend selections match items with :// against candidate URLs and other items against identifiers only, so that an identifier that equals another candidate's URL cannot select the wrong backend. - Choice tags that are present count whatever their value: null and other non-strings get 400, also when the choice is disabled. - Objects of client pipelines must not have duplicate keys (I-JSON). - Clashes of preset steps with the frame are checked by the engine only, against the frame steps that are kept (no steps dropped for lack of enabled plugins, no left-out appended defaults). Refs #487 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Lets clients choose a pipeline and backends per request, within limits that admins set. This is the second PR of the v0.18.0 plugin stack (#485), on top of the engine (#486).
gateway.pipelineholds a preset name or an inline JSON pipeline.gateway.backendsholds an allow or deny list of backends, as JSON.gateway.*tag from a client is rejected with 400 (reserved-tag), as are tags that are not a mapping.start()requirestags=to be passed explicitly.plugins.client_pipelinessetsenabled,allowed(presets and/or inline),roles,max_steps,max_alternativesand the frame (prepend/append).plugins.presetsdefines named pipelines.available.<id>.client_selectableandrolesdecide what clients may choose.rolesbut may include plugins that are notclient_selectable, since admins write them.plugins.pipeline. Steps that must always run belong inprepend. The docs and the config docstrings say so with a warning.client_pipelines.max_size).Closes #487
Verification
Run locally:
ruff checkandruff format --check: pass.mypy: pass.pytestwithout MongoDB: pass, with 100% coverage offoca/plugins.mkdocs build --strict: pass.pre-commit run --all-files: pass.The MongoDB tests did not run locally. CI: 27 checks pass, including the MongoDB tests; 2 are skipped as intended.
The tests include a seeded, table-driven test over 300 random client pipelines built from allowed and forbidden plugins. No forbidden plugin gets through.
Review: two rounds of adversarial and quality review on frozen snapshots of the branch. Round 1 found:
InvalidViaexport;Round 2 found surrogate encoding errors returning 500, leaks of frame step IDs, false clashes with dropped frame steps, and unbounded nesting. All of these are fixed.
Declined review findings
prepend/append.🤖 Generated with Claude Code
Summary by Sourcery
Enable safely constrained, per-request selection of plugin pipelines and backends while preserving administrator-defined policy frames.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests:
Chores: