Repository navigation
feat(plugins): add plugin engine - #496
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]>
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]>
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]>
Reviewer's GuideAdds the first framework-neutral gateway plugin stack: strict configuration and allowlisted entry-point loading feed an isolated, timeout-bounded multi-phase engine, integrated through a per-process runtime and Flask adapter, with Via loop protection, security-claims access, documentation, and extensive tests. Sequence diagram for gateway request plugin processing and forwardingsequenceDiagram
participant Client
participant Adapter
participant Host as PluginHost
participant Run as PipelineRun
participant Plugin
participant Backend
Client->>Adapter: HTTP request
Adapter->>Host: get_host()
Adapter->>Host: start(inbound, principal, request_id)
Host->>Run: create PipelineRun
Adapter->>Run: request()
Run->>Plugin: on_request(request, ctx)
Plugin-->>Run: success or fallback outcome
Adapter->>Run: route(candidates)
Run->>Plugin: on_route(candidates, ctx)
Plugin-->>Run: routed backends
loop backend attempts
Adapter->>Run: attempts(candidates)
Run->>Plugin: on_forward(outbound, ctx)
Plugin-->>Run: outbound request
Adapter->>Backend: send(outbound)
alt backend accepted
Backend-->>Adapter: response
Adapter->>Run: attempt.succeeded(response)
Run->>Plugin: on_response(response, ctx)
Plugin-->>Run: client response
else backend not accepted
Backend-->>Adapter: NotAccepted
Adapter->>Run: attempt.report(outcome)
end
end
Sequence diagram for Via loop protection and outbound forwardingsequenceDiagram
participant Client
participant Run as PipelineRun
participant Backend
Client->>Run: start(inbound)
alt Via header exceeds 1024 characters
Run-->>Client: InvalidVia 400
else Via already contains gateway_id
Run-->>Client: LoopDetected 508
else valid Via
Run->>Run: default_outbound(backend, inbound)
Run->>Run: _set_via(outbound)
Note over Run: Outbound Via = inbound Via plus gateway entry
Run->>Backend: send(outbound)
Backend-->>Run: accepted or forwarding outcome
end
Flow diagram for isolated plugin alternatives and failure handlingflowchart TD
Start["Run pipeline step"] --> Copy["Copy input, context, claims and state"]
Copy --> Hook["Call plugin hook with timeout"]
Hook --> Check["Validate hook output"]
Check -->|success| Commit["Commit copied result and state"]
Check -->|failure, timeout or invalid output| Next["Try next alternative"]
Hook -->|Rejected| Stop["Stop request with rejection"]
Next --> More{More alternatives?}
More -->|yes| Copy
More -->|no, skip| Skip["Skip step"]
More -->|no, fail| Failed["Fail pipeline or forwarding attempt"]
Commit --> Done["Continue to next step"]
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 #496 +/- ##
===========================================
Coverage 100.00% 100.00%
===========================================
Files 29 43 +14
Lines 3444 4458 +1014
===========================================
+ Hits 3444 4458 +1014
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:
|
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]>
There was a problem hiding this comment.
Hey - I've found 12 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/plugins/adapter.py" line_range="57" />
<code_context>
+ if not has_request_context():
+ return Principal()
+ claims = get_current_claims()
+ scheme, _, token = request.headers.get("Authorization", "").partition(" ")
+ issuer = claims.get("iss")
+ return Principal(
</code_context>
<issue_to_address>
**Unverified bearer token reaches plugins**
When a request reaches a gateway route without token validation while carrying an `Authorization: Bearer ...` header, `current_principal()` fills `Principal.token` directly from the request’s `Authorization` header, independently of `get_current_claims()`. On routes where authentication is optional or that do not validate the supplied token, plugins receive an attacker-supplied token as the caller’s bearer token, where it can be treated as trusted or forwarded onward.
Only populate `Principal.token` from a token that the authentication layer has confirmed was validated for the current request.
</issue_to_address>
### Comment 2
<location path="foca/foca.py" line_range="99" />
<code_context>
self.config_files: list[Path] = parser.config_files
self.config_dir: Path = parser.config_dir
+ self.gateway = gateway
+ runtime.configure(gateway)
logger.info("Log formatting configured.")
if not self.config_files:
</code_context>
<issue_to_address>
**Gateway apps use each other’s settings**
When multiple `Foca` instances coexist and one later requests a host, `runtime.configure()` replaces the process-global gateway settings and host, while `get_host()` combines that global gateway with the current app’s configuration. One app can therefore clear another’s runtime or load its plugins with mismatched API and callbacks, so requests fail or run the wrong pipeline.
Keep gateway settings and hosts scoped to the `Foca` app that uses them instead of replacing a shared process-global slot.
Also at `foca/plugins/runtime.py:80-81`, `foca/plugins/runtime.py:98-101`, `foca/plugins/runtime.py:121-126`.
</issue_to_address>
### Comment 3
<location path="foca/plugins/loader.py" line_range="227" />
<code_context>
+ loaded[plugin_id] = LoadedPlugin(
+ id=plugin_id,
+ cls=cls,
+ instance=cls(plugin_id, config),
+ distribution=distribution,
+ version=version,
</code_context>
<issue_to_address>
**Failed startup leaves plugins open**
When a later plugin load or pipeline resolution fails after earlier plugins have run `setup()`, `load_plugins()` and `PluginHost.__init__()` propagate the error without closing already-created instances, leaving setup-acquired resources open after startup fails or is retried.
Close all previously instantiated plugins when plugin loading or pipeline resolution fails.
Also at `foca/plugins/engine.py:203-207`.
</issue_to_address>
### Comment 4
<location path="foca/plugins/runtime.py" line_range="79-81" />
<code_context>
+ """
+ with _runtime.lock:
+ if _runtime.host is not None:
+ _runtime.host.close()
+ _runtime.app = app
+ _runtime.host = None
+
+
</code_context>
<issue_to_address>
**Reconfiguration closes active plugins**
When a new `Foca` instance calls `runtime.configure()` while requests are still using the existing host, `configure()` closes the old host while requests may still be using it; `PluginHost.close()` closes plugin instances before shutting down the executor, and the executor shutdown does not wait for running hooks. An in-flight hook can therefore use a resource after its plugin closed it, while a concurrent request using the old host can fail when submitting work to the shut-down pool.
Drain or otherwise quiesce active runs before closing the old host, and prevent new runs from acquiring it during reconfiguration.
Also at `foca/plugins/engine.py:390-397`.
</issue_to_address>
### Comment 5
<location path="foca/plugins/engine.py" line_range="626-627" />
<code_context>
+ """
+
+ def check(candidate: InboundRequest, _: InboundRequest) -> InboundRequest:
+ candidate.payload = self.host.check_payload(candidate.payload)
+ return candidate
+
+ self.inbound = self._run_phase(
</code_context>
<issue_to_address>
**Callbacks outlive pipeline deadlines**
When an app-provided sanitizer, validator, build, or `validate_outbound` callback blocks or exceeds its budget, `check_payload()` runs synchronously after the hook, and `build()` and `validate_outbound()` also run outside the bounded executor. The engine cannot enforce the pipeline or forwarding deadline, so the request remains stuck past its configured timeout.
Run these app callbacks under the bounded executor and enforce the applicable deadline.
Also at `foca/plugins/engine.py:369-376`, `foca/plugins/engine.py:703-714`.
</issue_to_address>
### Comment 6
<location path="foca/plugins/engine.py" line_range="963" />
<code_context>
+ except _AppError as exc:
+ execution.outcome = "error"
+ execution.error = sanitize_error(exc.error)
+ self._finish(execution, started, ctx)
+ self.executions.append(execution)
+ raise exc.error from None
</code_context>
<issue_to_address>
**Response rejection is ignored**
When a response hook raises `Rejected`, `PipelineRun._call` does not raise `PipelineRejected` for the response phase, so `_run_step()` skips the rejected response step and returns the backend response instead of the rejection status.
Propagate response-phase rejections as `PipelineRejected` rather than treating them as a skipped step.
</issue_to_address>
### Comment 7
<location path="foca/plugins/adapter.py" line_range="81-87" />
<code_context>
+ headers without credentials (cf.
+ :py:data:`foca.plugins.model.CREDENTIAL_HEADERS`).
+ """
+ headers = Headers(
+ {
+ name: value
+ for name, value in request.headers.items()
+ if name.lower() not in CREDENTIAL_HEADERS
+ }
+ )
+ rule = request.url_rule.rule if request.url_rule is not None else request.path
+ return InboundRequest(
</code_context>
<issue_to_address>
**Repeated Via entries disappear**
When an inbound request carries multiple `Via` field lines, including this gateway in a value that gets overwritten, `inbound_from_request()` first builds a regular dictionary, and `Headers.__setitem__()` then replaces values with the same case-insensitive name instead of joining them. When an inbound request has multiple `Via` field lines and an earlier one names this gateway, the engine sees only one value, fails to detect the loop, and can forward the request again.
Combine repeated field values case-insensitively when constructing inbound `Headers`, preserving the RFC list semantics of `Via`.
Also at `foca/plugins/model.py:80`.
</issue_to_address>
### Comment 8
<location path="foca/plugins/engine.py" line_range="135" />
<code_context>
+ return None
+ if not host:
+ return None
+ name = f"{host}:{port}" if port is not None else host
+ return name if _GATEWAY_ID.fullmatch(name) else None
+
</code_context>
<issue_to_address>
**IPv6 Via entries are invalid**
When the public URL uses an IPv6 literal and no explicit gateway ID is configured, `_default_gateway_id()` removes the IPv6 brackets, and `_set_via()` emits the resulting value as `received-by`, such as `::1:80`. Intermediaries cannot reliably parse this as a valid Via host literal, and `_via_names` cannot match a bracketed entry on a returning request, breaking interoperability and loop detection.
Format IPv6 gateway IDs as bracketed host literals, including their port, and use that same form when matching Via entries.
Also at `foca/plugins/engine.py:136`, `foca/plugins/engine.py:591-593`.
</issue_to_address>
### Comment 9
<location path="foca/plugins/engine.py" line_range="580-594" />
<code_context>
+ self._deadline = time.monotonic() + host.conf.defaults.pipeline_timeout
+
+ def _set_via(self, outbound: OutboundRequest) -> None:
+ """Set the `Via` header of an outbound request (RFC 9110, 7.6.3).
+
+ The header is the inbound request's, passed through verbatim (at most
+ :py:data:`MAX_VIA_LENGTH` characters), with this gateway's entry
+ appended, whatever plugins or the app's builder set, so that loops
+ through several gateways are detected.
+
+ Args:
+ outbound: Outbound request.
+ """
+ entries = [self._inbound_via] if self._inbound_via else []
+ if self.host.gateway_id is not None:
+ entries.append(f"1.1 {self.host.gateway_id}")
+ if entries:
+ outbound.headers["Via"] = ", ".join(entries)
+ else:
+ outbound.headers.pop("Via", None)
</code_context>
<issue_to_address>
**Forwarded Via exceeds size limit**
When a request arrives with a `Via` header near 1024 characters and this gateway has a `gateway_id`, `_set_via()` appends the gateway entry without checking the resulting header length. An inbound `Via` close to the 1024-character limit therefore produces an outbound header over that limit, which a subsequent gateway rejects with `InvalidVia` instead of forwarding the request through the chain.
Account for the appended gateway entry when validating the inbound header, or enforce a safe outbound limit with defined failure behavior.
</issue_to_address>
### Comment 10
<location path="foca/plugins/runtime.py" line_range="126" />
<code_context>
+ return host
+ with _runtime.lock:
+ if _runtime.host is None:
+ _runtime.host = create_host()
+ return _runtime.host
</code_context>
<issue_to_address>
**Plugin cleanup never runs**
When a process has created its plugin host and then shuts down without reconfiguring the runtime, `get_host()` caches the process host, but no shutdown path calls `PluginHost.close()`; plugins' `close()` methods therefore do not release their resources when the process exits gracefully.
Register process shutdown cleanup for the cached host and call `PluginHost.close()` there.
</issue_to_address>
### Comment 11
<location path="foca/plugins/adapter.py" line_range="114-116" />
<code_context>
+ problem type as extension member `problem_type` (FOCA maps `type`
+ per exception class).
+ """
+ http_exc = HTTPException(description=exc.detail)
+ http_exc.code = exc.code
+ return problem_response(http_exc, problem_type=exc.problem_type)
</code_context>
<issue_to_address>
**Rejections lose their custom title**
When a plugin raises `Rejected` with a custom title, `problem()` passes only the detail and status to `problem_response()`, which supplies the status’s standard title instead of the rejection’s title, so callers receive the wrong problem title.
Pass the rejection’s custom title through to `problem_response()`.
</issue_to_address>
### Comment 12
<location path="foca/plugins/context.py" line_range="130" />
<code_context>
+ elif not isinstance(value, _SCALARS):
+ raise ValueError("Annotation values must be JSON scalars or lists")
+ annotations = {**self.annotations, key: value}
+ size = len(json.dumps(annotations, separators=(",", ":")).encode())
+ if size > MAX_ANNOTATIONS_SIZE:
+ raise ValueError(f"Annotations exceed {MAX_ANNOTATIONS_SIZE} bytes")
</code_context>
<issue_to_address>
**Non-finite annotations are accepted**
When a plugin records NaN or positive or negative infinity, `record()` accepts these floats, and `json.dumps()` serializes them as `NaN` or `Infinity` rather than valid JSON numbers. The annotations violate the JSON-data contract and can make strict serialization of execution records fail.
Reject non-finite floats when validating annotation values.
Also at `foca/plugins/context.py:17`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 12 findings to address first, and the engine runs installed plugin hooks on authenticated requests, exposes the caller’s claims and bearer token to them, and lets hooks change payloads and backend routing before forwarding. If a hook or pipeline sends sensitive data to the wrong destination or submits an unintended task, removing the plugin or reverting the change cannot recall that data or undo the backend’s action.
Blocking findings: foca/plugins/adapter.py:57, foca/foca.py:99, foca/plugins/loader.py:227, foca/plugins/runtime.py:81, foca/plugins/engine.py:627, and 7 more
- 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]>
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]>
Summary
Adds
foca.plugins, a framework-free plugin engine for gateway apps (proTES first). This is the first PR of the v0.18.0 plugin stack (#485).Principal,InboundRequest,Backend,OutboundRequest,BackendResponse, case-insensitiveHeaders, read-onlyFrozenMappingfor claims,Pluginwith the hookson_request,on_route,on_forwardandon_response, and the exceptionsNotApplicable,Rejected,PluginError,NotAcceptedandOutcomeUnknown.pluginskey holds the allowlist, defaults, pipeline steps and presets. Unknown or reserved keys are rejected. A legacymiddlewareskey stops the app with a migration hint.foca.plugins) that are allowlisted and match their version pins are loaded.BaseExceptionfrom a hook is recorded as an error;KeyboardInterruptandGeneratorExitare re-raised.Viais the inboundViaplus this gateway's entry. Inbound values longer than 1024 characters are rejected withInvalidVia(400).errors,outcomes,records,executor,checksandengine.Foca(..., gateway=GatewayApp(...))sets up the engine, andget_host()returns the per-process host, also outside Flask (Celery). The only Flask glue isfoca.plugins.adapter, so the engine doesn't block the move to Connexion 3.get_current_claims()is added infoca.security.access_control.Config.pluginsis a strict model. Apps that already use a top-levelpluginskey must rename it. The app logs a warning whenpluginsis configured withoutgateway=.Closes #486
Verification
Run locally on every branch of the stack:
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-marked tests didn't run locally. CI: all 27 checks pass (2 skipped as intended), including the MongoDB tests. CodeQL first flagged reflected XSS in a test view that echoed a path parameter; d150b4f makes it return a constant. After the Sourcery fixes (f056d28, 56aa7fb): 28 checks pass, 2 skipped as intended.
Sourcery: 12 findings; 10 fixed in f056d28 (validated tokens only, one gateway app per process, closing plugins on failure and at exit, joined repeated headers, bracketed IPv6 gateway IDs, outbound
Viacap, rejection titles, finite annotations), 2 answered as intended (trusted app callbacks outside plugin deadlines; response-phase rejections count as failed alternatives).Review: two rounds of adversarial and quality review. Fixed:
Viapass-through, length cap and validation order;SystemExitfrom hooks;Declined review findings
StepConfig.if_missing_phase,Context.http): it stays here, because the stack is merged forward. It is used by feat(plugins): resolve per-request pipelines #487 (client pipelines) and feat(utils): add a guarded HTTP client #490 (guarded HTTP client).FOCABaseConfigfor the plugin config models: not done.foca.models.configimportsfoca.plugins.config, so reusing it would create an import cycle.FOCABaseConfigalso allows arbitrary types.create_appcomment and the docs, andPlugin.setup()must be idempotent.docs/plugins.md: taste only; left as they are.🤖 Generated with Claude Code