Skip to content

feat(plugins): list plugins for clients - #506

Merged
uniqueg merged 156 commits into
devfrom
feat/plugin-listing
Oct 25, 2026
Merged

uniqueg merged 156 commits into
devfrom
feat/plugin-listing

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Lets clients (SDK, Krini) find out which plugins and presets they may use in per-request pipelines. Public discovery gets generic descriptors only, so it gives no attack map of installed code. This is the eighth PR of the v0.18.0 plugin stack (#485).

  • Spec: an OpenAPI 3 fragment (foca.plugins.api.SPEC_PATH) that apps add to their API specs, so that the paths get the app's base path, security and access control.
  • GET <base>/plugins (authenticated): returns exactly what selection accepts from the caller.
    • Plugins only if the caller may send its own pipelines. Each has its ID, title, description, group, subgroup, phases, capabilities, maturity, distribution, version, data transfers and the JSON Schema of its params.
    • Presets only if presets are allowed for the caller and it has the roles of their plugins.
    • The default pipeline's steps, with their plugins only for callers that may choose pipelines.
    • The limits of client_pipelines and client_backends, and the tag prefix.
    • Admin settings are never returned.
  • GET <base>/plugins/{id}: one plugin. Plugins the caller may not use give 404, whatever the reason.
  • service_info_fields(): a gateway extension of the service info, with the listing URL, the client limits and the union of the plugins' capability descriptors. It has no plugin IDs, distributions or versions.
  • Load checks: plugins whose params have no JSON Schema are refused when they are loaded, so they can't break the listing.
  • Access control: FOCA ships no policies. The docs give the rules apps add: one per endpoint, for models that match paths with keyMatch2. With default_model.conf, which matches paths exactly, apps list each path explicitly.

The listing is a pure function of the config, the loaded plugins and the caller. Only the principal lookup goes through foca.plugins.adapter.

Closes #489

Verification

Run locally on aa2984a (with dev merged):

  • ruff check and ruff format --check: pass.
  • mypy: pass.
  • pytest without MongoDB: pass, with 100% coverage of foca/plugins and foca/utils/http.py. A test checks the documented policy rules with casbin and FOCA's resource role model.
  • mkdocs build --strict: pass.
  • pre-commit: pass.

The MongoDB tests and semgrep did not run locally (CI runs them). CI on aa2984a: 28 checks pass, and 2 are skipped as intended.

Review: two rounds of adversarial and quality review.

  • Round 1 (f9c2f7c):
    • the listing showed more than selection accepted (plugins and presets the caller can't use);
    • the 403 response wasn't documented;
    • client_pipelines and client_backends weren't typed in the spec;
    • tests were missing for 401 and 404 bodies and for the merged spec.
  • Round 2:
    • the documented policy plugins* doesn't match /plugins/<id> with keyMatch2 (5ba67f6, 057b43b);
    • the default pipeline's plugin IDs were shown to every caller (5ba67f6);
    • params without a JSON Schema made the listing return 500 (3e56aa8).

All are fixed.

Sourcery: 6 findings. 5 are fixed in aa2984a:

  • callers without any choice (no inline pipelines, no usable preset) get no steps, as step identifiers default to plugin identifiers; allowed_for_caller says whether selection accepts any choice;
  • service_info_fields() no longer creates the plugin host before workers fork: it reads the plugin classes without instantiating them;
  • titles, descriptions and data transfers that aren't strings are refused when plugins are loaded;
  • the Plugin schema marks all fields that are always returned as required.

Declined review findings

  • Commit hygiene (merge commits from the stack): declined, because the PR is squash-merged.
  • Sourcery: limits in the public service info: declined. The limits matter only to callers who may choose, and they get them from the authenticated listing; anonymous callers learn which features exist, not how the gateway is configured.

Notes

The capability vocabulary is curated in FOCA's docs until a community vocabulary exists.

🤖 Generated with Claude Code

uniqueg and others added 30 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]>
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]>
`foca.plugins.tags` gives gateways a spec-compliant record of where a
task or run went, as string tags under `plugins.tags.prefix`:

- `creation_tags(run, provenance_path)`: `pipeline_hash`,
  `pipeline_source` (`default`, `preset:<name>`, `client`), `plugins`
  (`id@version` of the plugins that ran) and `provenance`
- `routing_tags(run)`: `backend`, `backend_task_id`, `forwarded_at`,
  `attempts`, `route` (compact JSON of the last `max_route_entries`
  attempts, new setting, default 10) and `route_truncated`
- limits: values at most 1 KiB, `route` at most 4 KiB with the earliest
  attempts dropped first; URLs without user info, query or fragment;
  reason codes only
- `strip_for_forwarding(tags, prefix)` removes every key under the
  prefix, also the client's choices, from relayed requests

Refs #494

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]>
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
#	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]>
uniqueg and others added 22 commits October 25, 2026 19:05
Request hooks could add server-written tags (e.g., gateway.backend)
to the payload, and the documented merge kept them when forwarding
failed, so dashboards could not trust them. The engine now treats
request output that adds, changes or removes a key under the reserved
prefix (also the client's own pipeline and backends keys) as invalid
output (check_reserved_tags). without_server_tags() drops all but the
client's keys under the prefix before the merge, as a second line of
defence, and the documented pattern uses it.

Refs #494

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A plugin whose Params model has no JSON Schema (e.g., a field of an
arbitrary type) turned GET /plugins into a 500. check_plugin_class now
generates the schema, so such plugins fail at load.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The documented policy "/ga4gh/tes/v1/plugins*" does not match
/plugins/<id> with keyMatch2. Document one rule per endpoint, and test
the documented rules with the resource role model.

The plugins of the default pipeline are now listed only for callers
that may choose pipelines; others get the step identifiers only, as
for the prepend and append steps.

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]>
- 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]>
- Lone surrogates no longer break tag values (replaced by ?), and URLs
  with invalid ports no longer break routing tags (provenance helper).
- Provenance paths and backend task ids that do not fit are left out
  rather than cut, so they never point elsewhere.
- The latest attempt stays in the route even if it alone is too large
  (its URL is cut, route_truncated is set).
- gateway.plugins lists the plugins that ran in the request phase,
  whatever their outcome; the docs say so.

Refs #494

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

Introduces authenticated, caller-aware plugin and preset discovery for per-request pipelines, with OpenAPI integration, privacy-preserving service metadata, JSON-Schema load validation, documented access-control setup, and comprehensive API, policy, and packaging tests.

Sequence diagram for caller-aware plugin discovery

sequenceDiagram
    actor Client
    participant API as Plugin API
    participant Adapter as adapter.current_principal()
    participant Host as PluginHost
    participant Listing as list_plugins()

    Client->>API: GET /plugins
    API->>Adapter: current_principal()
    Adapter-->>API: Principal
    API->>Host: runtime.get_host()
    API->>Listing: list_plugins(host, principal)
    Listing->>Host: _may_choose(host, principal)
    Listing->>Host: _may_use(host, plugin_id, principal)
    Listing->>Host: may_use_preset(steps, principal)
    Listing-->>API: Caller-filtered listing
    API-->>Client: 200 PluginListing
Loading

Sequence diagram for protected single-plugin lookup

sequenceDiagram
    actor Client
    participant API as Plugin API
    participant Adapter as adapter.current_principal()
    participant Host as PluginHost
    participant Lookup as get_plugin()

    Client->>API: GET /plugins/{plugin_id}
    API->>Adapter: current_principal()
    Adapter-->>API: Principal
    API->>Host: runtime.get_host()
    API->>Lookup: get_plugin(host, plugin_id, principal)
    alt plugin may be selected
        Lookup->>Host: _may_use(host, plugin_id, principal)
        Lookup-->>API: describe_plugin(host, plugin_id)
        API-->>Client: 200 Plugin
    else unknown or unavailable
        Lookup-->>API: PluginNotFound
        API-->>Client: 404 plugin-not-found
    end
Loading

Flow diagram for plugin load validation

flowchart TD
    Load[Load plugin class]
    Check[check_plugin_class]
    Schema["Params.model_json_schema()"]
    Accept[Plugin available for listing]
    Reject[Reject plugin load]

    Load --> Check
    Check --> Schema
    Schema -->|valid JSON Schema| Accept
    Schema -->|PydanticUserError| Reject
Loading

File-Level Changes

Change Details Files
Adds authenticated plugin and preset discovery endpoints that expose only selections permitted for the requesting principal.
  • Builds filtered plugin, preset, default-pipeline, and client-limit listings from host configuration and caller roles.
  • Adds single-plugin lookup with uniform 404 responses for unknown or inaccessible plugins.
  • Provides Connexion controllers and an OpenAPI fragment defining endpoint security, response schemas, and problem responses.
foca/plugins/api.py
foca/plugins/api.yaml
tests/plugins/test_plugin_api.py
Adds privacy-preserving public service metadata for plugin capabilities and listing availability.
  • Introduces a gateway service-info extension with client limits, capability unions, and an optional listing URL.
  • Omits plugin identifiers, distributions, and versions from public metadata.
foca/plugins/api.py
docs/plugins.md
docs/reference.md
tests/plugins/test_plugin_api.py
Hardens plugin loading so every listed plugin can produce a JSON Schema for its parameters.
  • Rejects plugin parameter models that cannot generate JSON Schema during class validation.
  • Packages the OpenAPI YAML resource with the plugin distribution.
foca/plugins/base.py
pyproject.toml
tests/plugins/test_plugin_basics.py
Documents application integration and access-control requirements for the new discovery API.
  • Documents how apps merge the OpenAPI fragment under their base path and define endpoint policies.
  • Explains keyMatch2 path matching and adds the plugin-not-found problem type.
docs/plugins.md
docs/reference.md
Aligns preset selection with the listing's caller-eligibility checks.
  • Exposes the preset authorization helper for reuse by discovery and selection.
  • Updates pipeline resolution to use the shared authorization method.
foca/plugins/engine.py
foca/plugins/api.py
tests/plugins/test_plugin_api.py

Assessment against linked issues

Issue Objective Addressed Explanation
#489 Provide authenticated plugin-listing and single-plugin endpoints that expose only the plugins and presets the caller may select, along with the default pipeline and client constraints, without returning admin configuration. ✅
#489 Provide public service-info gateway fields with the plugin-listing URL, client capabilities, and a generic union of plugin capability descriptors, without exposing plugin identifiers, distributions, or versions. ✅
#489 Document how apps register the OpenAPI fragment and configure access-control policies for plugin discovery and task provenance, while shipping no default policies. ✅

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 (93fa956) to head (aa2984a).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #506   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           52        53    +1     
  Lines         5963      6057   +94     
=========================================
+ Hits          5963      6057   +94     
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.

@uniqueg
uniqueg marked this pull request as ready for review October 25, 2026 22:03

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

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

## Individual Comments

### Comment 1
<location path="foca/plugins/api.py" line_range="52" />
<code_context>
+        Whether client pipelines are enabled and the caller has their roles.
+    """
+    clients = host.conf.client_pipelines
+    return clients.enabled and _has_role(clients.roles, principal)
+
+
</code_context>
<issue_to_address>
**Hidden plugin identifiers are exposed**

When `client_pipelines.allowed` contains only `presets` and the caller has no usable preset, `_may_choose` checks only whether client pipelines are enabled and the caller has the required roles, so `list_plugins` reports `allowed_for_caller: true` and includes default-pipeline plugin IDs, exposing identifiers the caller cannot use.

Make `_may_choose` account for whether the caller has a usable choice before allowing the listing to expose default-pipeline plugin IDs.

Also at `foca/plugins/api.py:147`, `foca/plugins/api.py:161`.
</issue_to_address>

### Comment 2
<location path="foca/plugins/api.py" line_range="161" />
<code_context>
+        ],
+        "default_pipeline": [
+            # plugins of the default pipeline are not public
+            step if allowed else {"id": step["id"], "plugins": []}
+            for step in _steps(host.default_pipeline.steps)
+        ],
</code_context>
<issue_to_address>
**Hidden plugin IDs leak through step names**

When an authenticated caller cannot choose pipelines and the default pipeline has a step whose ID defaults to a plugin identifier the caller is not allowed to use, `list_plugins` clears the `plugins` array for callers who cannot choose pipelines but preserves each default step’s `id`. Since `StepConfig` defaults that ID to its first plugin’s identifier, the response exposes plugin IDs that `get_plugin` otherwise hides with 404s.

Avoid returning plugin-derived step identifiers to callers who cannot view those plugins, or use step identifiers that do not disclose plugin IDs.
</issue_to_address>

### Comment 3
<location path="foca/plugins/api.py" line_range="225" />
<code_context>
+        versions.
+    """
+    if host is None:
+        host = runtime.get_host()
+    capabilities = sorted(
+        {
</code_context>
<issue_to_address>
**Plugin host starts before worker forks**

When an app follows the documented service-info integration and creates its app in a pre-fork server, `service_info_fields()` calls `runtime.get_host()` during `Foca.create_app()`'s service-info check, before the startup check and worker forks. The host's plugin instances are then inherited and forgotten by `runtime._Runtime.forget()` in each child rather than closed, so plugins initialize in the parent and can carry inherited resources into workers.

Avoid initializing the runtime host while checking service info before forks; compute these fields from configuration or defer host creation until after workers fork.
</issue_to_address>

### Comment 4
<location path="foca/plugins/base.py" line_range="264" />
<code_context>
                 f"Plugin {plugin_id!r} has no pydantic Config/Params model"
             )
+    try:
+        cls.Params.model_json_schema()
+    except PydanticUserError as error:  # e.g., arbitrary types
+        raise ValueError(
</code_context>
<issue_to_address>
**Malformed metadata breaks listing**

When a loaded plugin sets title, description, or data-transfer metadata to a non-JSON-serializable value, `check_plugin_class` validates the parameter schema but not the title, description, or `data_transfers` types. `describe_plugin` returns those values directly, so a loaded plugin with non-JSON-serializable metadata makes the listing response fail for callers.

Validate the types and JSON suitability of every plugin metadata field exposed by the listing during plugin loading.
</issue_to_address>

### Comment 5
<location path="foca/plugins/api.yaml" line_range="84-120" />
<code_context>
+      required: [id, title, description, phases, capabilities, maturity, params_schema]
</code_context>
<issue_to_address>
**Plugin response fields are optional**

When a client generates response types from the OpenAPI schema, generated clients treat `group`, `subgroup`, `distribution`, `version`, and `data_transfers` as optional because they are absent from the schema’s `required` list, even though `describe_plugin()` always returns them; callers must handle an absent state the API never produces.

Add the always-present fields to the `Plugin` schema’s `required` list while keeping nullable fields marked nullable.
</issue_to_address>

### Comment 6
<location path="foca/plugins/api.py" line_range="234-236" />
<code_context>
+        }
+    )
+    gateway: dict[str, Any] = {
+        "client_pipelines": host.conf.client_pipelines.enabled,
+        "client_backends": host.conf.client_backends.enabled,
+        "capabilities": capabilities,
+    }
+    if plugins_url is not None:
</code_context>
<issue_to_address>
**Public service info omits limits**

When a client relies on public service info to discover gateway constraints, `service_info_fields` reports only whether client pipelines and backends are enabled, so clients cannot discover configured limits such as `max_steps`, `max_alternatives`, `max_size`, and `max_items` there and must fetch the authenticated listing.

Include the configured client-pipeline and client-backend limits in the public service-info fields.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and if the caller-role filtering or app access policy is wrong, callers could learn plugin inventory details such as identifiers, distributions, versions, and parameter schemas that are intended to stay restricted. Reverting would stop future listings, but it cannot retract information already disclosed.

Blocking findings: foca/plugins/api.py:52, foca/plugins/api.py:161, foca/plugins/api.py:225, foca/plugins/base.py:264, foca/plugins/api.py:236


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

Comment thread foca/plugins/api.py Resolved
Comment thread foca/plugins/api.py Resolved
Comment thread foca/plugins/api.py Resolved
Comment thread foca/plugins/base.py Resolved
Comment thread foca/plugins/api.yaml Resolved
Comment thread foca/plugins/api.py Resolved
Address Sourcery's review of the plugin listing:

- Callers without any choice (no inline pipelines and no usable
  preset) get no steps of the default pipeline, prepend or append, as
  step identifiers default to plugin identifiers;
  allowed_for_caller now says whether selection accepts any choice.
- service_info_fields() no longer creates the plugin host: before the
  host is in use, it reads the plugin classes without instantiating
  them (runtime.current_host(), runtime.plugin_classes() and
  loader.find_plugin_classes()), so no plugin is set up before
  workers fork.
- check_plugin_class() refuses titles and descriptions that are no
  strings, and data_transfers that are no list of strings.
- The Plugin schema marks all fields that are always returned as
  required.

Refs #489

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 04e2017 into dev Oct 25, 2026
30 checks passed
@uniqueg
uniqueg deleted the feat/plugin-listing branch October 25, 2026 22:22
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): list available plugins

1 participant