Skip to content

feat(plugins): add plugin engine - #496

Merged
uniqueg merged 10 commits into
devfrom
feat/plugin-engine
Oct 25, 2026
Merged

uniqueg merged 10 commits into
devfrom
feat/plugin-engine

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

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).

  • Model and base: Principal, InboundRequest, Backend, OutboundRequest, BackendResponse, case-insensitive Headers, read-only FrozenMapping for claims, Plugin with the hooks on_request, on_route, on_forward and on_response, and the exceptions NotApplicable, Rejected, PluginError, NotAccepted and OutcomeUnknown.
  • Config: a new top-level plugins key holds the allowlist, defaults, pipeline steps and presets. Unknown or reserved keys are rejected. A legacy middlewares key stops the app with a migration hint.
  • Loader: only entry points (group foca.plugins) that are allowlisted and match their version pins are loaded.
  • Engine:
    • Each alternative runs on isolated copies of the context, params, claims and state, so a failed alternative leaves no changes behind.
    • Hooks run with per-hook, per-pipeline and forward timeouts.
    • A BaseException from a hook is recorded as an error; KeyboardInterrupt and GeneratorExit are re-raised.
    • Loop detection follows RFC 9110 §7.6.3: the outbound Via is the inbound Via plus this gateway's entry. Inbound values longer than 1024 characters are rejected with InvalidVia (400).
    • The module is split into errors, outcomes, records, executor, checks and engine.
  • Runtime: Foca(..., gateway=GatewayApp(...)) sets up the engine, and get_host() returns the per-process host, also outside Flask (Celery). The only Flask glue is foca.plugins.adapter, so the engine doesn't block the move to Connexion 3.
  • Security: a new public get_current_claims() is added in foca.security.access_control.
  • Breaking (minor): Config.plugins is a strict model. Apps that already use a top-level plugins key must rename it. The app logs a warning when plugins is configured without gateway=.

Closes #486

Verification

Run locally on every branch of the stack:

  • ruff check and ruff format --check: pass.
  • mypy: pass.
  • pytest without MongoDB: pass, with 100% coverage of foca/plugins.
  • mkdocs build --strict: pass.
  • pre-commit run --all-files: pass.
  • The push hook (semgrep, ast-grep): 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 Via cap, 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:

  • loops across two gateways not detected (high);
  • params and claims shared between requests;
  • claims that couldn't be deep-copied;
  • the engine module's size;
  • use of a private claims helper;
  • Via pass-through, length cap and validation order;
  • userinfo in the default gateway ID;
  • SystemExit from hooks;
  • documentation.

Declined review findings

  • Code that the next PRs use (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).
  • Reuse FOCABaseConfig for the plugin config models: not done. foca.models.config imports foca.plugins.config, so reusing it would create an import cycle. FOCABaseConfig also allows arbitrary types.
  • Plugins are instantiated twice (validated at startup, then again lazily per process): this is documented in the create_app comment and the docs, and Plugin.setup() must be idempotent.
  • Underscore names for internals used across modules, and the duplicated app-author summary in docs/plugins.md: taste only; left as they are.

🤖 Generated with Claude Code

uniqueg and others added 7 commits October 25, 2026 00:24
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds 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 forwarding

sequenceDiagram
    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
Loading

Sequence diagram for Via loop protection and outbound forwarding

sequenceDiagram
    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
Loading

Flow diagram for isolated plugin alternatives and failure handling

flowchart 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"]
Loading

File-Level Changes

Change Details Files
Introduces a framework-neutral plugin domain model and plugin contract for gateway request processing.
  • Adds request, backend, response, principal, header, and immutable claims models.
  • Defines typed plugin configuration and lifecycle hooks across request, route, forward, and response phases.
  • Adds plugin outcomes, gateway errors, sanitized execution records, and provenance annotations.
foca/plugins/__init__.py
foca/plugins/base.py
foca/plugins/model.py
foca/plugins/context.py
foca/plugins/errors.py
foca/plugins/outcomes.py
foca/plugins/records.py
Adds strict plugin configuration and secure entry-point loading.
  • Validates allowlists, defaults, pipelines, alternatives, pins, identifiers, reserved keys, and plugin-specific Pydantic config.
  • Loads only enabled allowlisted foca.plugins entry points and verifies distribution, version, API, metadata, capabilities, and configuration.
  • Rejects legacy middleware keys with migration guidance.
foca/plugins/config.py
foca/plugins/loader.py
foca/config/config_parser.py
foca/models/config.py
Implements isolated, bounded pipeline execution with fallback and forwarding semantics.
  • Runs alternatives on deep-copied request data, parameters, claims, and per-plugin state, committing only successful results.
  • Applies per-call, pipeline, and forwarding deadlines through a bounded thread pool; records failures including BaseException while preserving KeyboardInterrupt and GeneratorExit.
  • Validates hook outputs, supports rejection and skip/fallback behavior, reverses response hooks, and tracks backend attempt outcomes.
  • Implements RFC 9110 Via propagation and loop detection, Via length validation, own-gateway backend exclusion, and sanitized execution records.
foca/plugins/engine.py
foca/plugins/executor.py
foca/plugins/checks.py
Integrates plugin hosts into FOCA gateway runtime while isolating framework-specific code.
  • Adds GatewayApp configuration, lazy per-process host creation, fork handling, startup validation, and host shutdown.
  • Provides Flask/Connexion adapter functions for inbound request conversion, principals, request IDs, and problem responses.
  • Keeps framework imports confined to the adapter and adds an AST-Grep enforcement rule.
foca/plugins/runtime.py
foca/plugins/adapter.py
foca/foca.py
.ast-grep/rules/plugins-framework-import.yml
.ast-grep/rule-tests/plugins-framework-import-test.yml
Exposes validated security claims and documents the plugin stack.
  • Adds public get_current_claims() returning a deep copy of validated token claims.
  • Adds configuration, usage, API reference, migration, lifecycle, failure, forwarding, and plugin-author documentation.
  • Adds packaging support for version pin validation.
foca/security/access_control/enforcement.py
foca/security/access_control/__init__.py
pyproject.toml
docs/access-control.md
docs/configuration/index.md
docs/configuration/plugins.md
docs/plugins.md
docs/reference.md
mkdocs.yml
Adds comprehensive tests covering models, configuration, loading, execution, isolation, runtime integration, adapter behavior, and claims access.
  • Covers fallback, rejection, timeout, validation, forwarding, Via loops, response ordering, process isolation, fork behavior, and error sanitization.
  • Tests allowlisting, pins, disabled plugins, legacy-key migration, framework adapters, and public claims copying.
tests/plugins/__init__.py
tests/plugins/fakes.py
tests/plugins/test_plugin_adapter.py
tests/plugins/test_plugin_basics.py
tests/plugins/test_plugin_engine.py
tests/plugins/test_plugin_isolation.py
tests/plugins/test_plugin_loader.py
tests/plugins/test_plugin_runtime.py
tests/security/access_control/test_enforcement.py

Assessment against linked issues

Issue Objective Addressed Explanation
#486 Provide the framework-independent plugin model and engine, including isolated alternatives, bounded hooks, validation, routing, forwarding outcomes, and Via loop handling. ❌ The engine implements most of these behaviors, but it does not append the required default route step when no configured step implements on_route.
#486 Add plugin configuration, allowlisted entry-point loading, startup validation, and a lazy, fork-safe per-process runtime. ❌ The allowlist, pins, startup checks, and runtime are implemented, but the proposed plugins.presets configuration is absent from PluginsConfig and pipeline resolution.
#486 Integrate the engine with gateway apps and access control, and provide framework-import checks and operator, developer, and API documentation. ✅

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 Oct 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (9232908) to head (56aa7fb).

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     
Flag Coverage Δ
test_unit 100.00% <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.

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]>
@uniqueg
uniqueg marked this pull request as ready for review October 25, 2026 00:33

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


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

Comment thread foca/plugins/adapter.py Resolved
Comment thread foca/foca.py Resolved
Comment thread foca/plugins/loader.py Resolved
Comment thread foca/plugins/runtime.py Resolved
Comment thread foca/plugins/engine.py Resolved
Comment thread foca/plugins/engine.py Resolved
Comment thread foca/plugins/engine.py Resolved
Comment thread foca/plugins/runtime.py Resolved
Comment thread foca/plugins/adapter.py Resolved
Comment thread foca/plugins/context.py Resolved
uniqueg and others added 2 commits October 25, 2026 02:50
- 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]>
@uniqueg
uniqueg merged commit a9bc8fe into dev Oct 25, 2026
30 checks passed
@uniqueg
uniqueg deleted the feat/plugin-engine branch October 25, 2026 02:14
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.

feat(plugins): add plugin engine

2 participants