Skip to content

fix(plugins): fail closed on client pipelines - #526

Merged
uniqueg merged 6 commits into
devfrom
fix/client-pipelines-closed
Oct 26, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/client-pipelines-closed

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Summary

Client pipelines now fail closed (pre-release review of v0.18.0, finding 3 and the low finding on anonymous callers).

  • Default off: plugins.client_pipelines.enabled now defaults to false.

  • Authentication: only authenticated callers (a Principal with a subject) may choose pipelines (gateway.pipeline) or backends (gateway.backends). The plugin listing shows nothing to choose for anonymous callers.

  • Startup warning: when client pipelines are enabled, the app warns about steps of plugins.pipeline that clients can skip. A step counts as covered only if one of these holds:

    • a step in client_pipelines.prepend, or in append without if_missing_phase, has the same alternatives (plugins and params) and the same on_failure;
    • clients may choose presets only, and every preset has the step.

    The default route step without params is exempt.

  • Docs: I fixed the ClientPipelinesConfig docstring and both warning boxes. They said the frame runs for every request, but requests without the pipeline tag get plugins.pipeline without the frame. The full rule is now on the configuration page, and docs/plugins.md links to it.

Why I chose "default off"

The review offered three options:

  1. Default enabled: false (chosen). This fails closed for every configuration, including ones whose admins never thought about the frame. Admins who enable client pipelines opt in on purpose, and the new startup warning tells them which steps clients could skip.
  2. Also apply prepend to the default pipeline. I rejected this. While client pipelines stay enabled by default, a policy that sits only in plugins.pipeline could still be skipped, so this alone does not fail closed. It would also change what the frame means, and configurations that list a policy in both places (the pattern the guide shows) would run it twice.
  3. A required or policy flag on steps. I rejected this as well. It adds a new configuration concept and new semantics shortly before the release. If it is wanted later, it can come as an addition.

Backend choices stay enabled by default: they can only narrow or reorder the configured candidates, never add backends, so they cannot bypass policies. They now need an authenticated caller too.

Plugins are new in 0.18 (they are in no released tag), so the changed default needs no migration note. proTES, which is planned to use these settings, must set client_pipelines.enabled: true explicitly if it wants client pipelines, and should list its policies in both pipeline and prepend.

Closes #518

Verification

  • pytest tests/plugins: 394 passed. Coverage of foca/plugins is 100%.
  • Full pytest before the review fixes: 2794 passed, 1 skipped. The 131 errors are all mongodb-marked tests, because no MongoDB server was running locally; CI runs them.
  • ruff check, ruff format --check, mypy, ast-grep scan, ast-grep test, semgrep (.semgrep) and mkdocs build --strict are all clean.
  • The new regression tests failed before the fix: default off, anonymous pipeline and backend choices, the listing for anonymous callers, and the warning cases.
  • CI: all checks passed (skips are image pushes on PRs).

Declined review findings

  • The listing reports client_backends.enabled for callers without a subject (low). The listing endpoints require authentication. A validated token without an identity claim is also rejected by access control, so I did not add a per-caller flag to the listing schema.
  • One shared engine helper for the may choose rule of the listing and of resolve (optional, low). The listing helper already composes the same two predicates (_is_authenticated, _has_role), and the listing tests compare it with selection.

🤖 Generated with Claude Code

Summary by Sourcery

Fail closed for client-selected pipelines by disabling them by default and restricting pipeline and backend choices to authenticated callers.

Bug Fixes:

  • Require authenticated callers to select per-request pipelines or backends, preventing anonymous callers from bypassing configured policies.

Enhancements:

  • Disable client-selected pipelines by default and warn at startup when enabled configurations allow clients to skip default pipeline steps.
  • Update plugin listings and configuration guidance to reflect authentication requirements, default-off pipeline selection, and the distinction between framed client pipelines and the default pipeline.

Documentation:

  • Clarify client pipeline behavior, policy placement, authentication requirements, and startup warnings in the plugin configuration and usage documentation.

Tests:

  • Add regression coverage for default-disabled pipelines, anonymous selection and listings, and warnings for skippable pipeline and preset steps.

uniqueg and others added 4 commits October 26, 2026 19:32
A client pipeline replaces plugins.pipeline, so with client pipelines
enabled by default any caller could drop policy steps that sit only in
the default pipeline, even plugins that are not client_selectable.

- Disable client_pipelines by default; admins enable them explicitly.
- Refuse pipeline and backend choices of unauthenticated callers (no
  subject), also in the plugin listing.
- Warn on startup about steps of plugins.pipeline whose plugins are in
  neither client_pipelines.prepend nor append.
- Correct the docstring and both warning boxes: the frame runs only
  around client pipelines and presets, so policies belong in both
  pipeline and prepend.

Closes #518

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Count only prepend and unconditional append steps as framed, and
  compare alternatives (plugins and params) and on_failure, so policy
  routers in append with if_missing_phase or weaker copies in the frame
  are reported.
- Check authentication for both choices right after reading the tags.
- Rewrap and deduplicate the docs; split the tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Skip the warning for steps that every preset has when clients may
  choose presets only.
- Check pipeline authentication in resolve only; document the refusal
  in the docstrings.
- Keep the full rule on the configuration page only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.18.0 milestone Oct 26, 2026
@uniqueg uniqueg added the type: security Related to security label Oct 26, 2026
@sourcery-ai

sourcery-ai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Client-controlled pipeline and backend choices now fail closed by default and require authenticated callers, while enabled configurations receive startup warnings for default-pipeline steps that clients can bypass; documentation and regression coverage were updated to reflect the new semantics.

Sequence diagram for authenticated client pipeline and backend selection

sequenceDiagram
    participant Caller
    participant Host as PluginHost
    participant Selection as Selection
    participant Pipeline as PipelineResolver

    Caller->>Host: start(tags, principal)
    Host->>Selection: parse choices
    alt backend choice and caller has no subject
        Host-->>Caller: InvalidSelection
    else pipeline choice and caller has no subject
        Host->>Pipeline: resolve(value, principal)
        Pipeline-->>Caller: InvalidSelection
    else authenticated caller
        Host->>Pipeline: resolve(value, principal)
        Pipeline-->>Host: ResolvedPipeline
        Host-->>Caller: PipelineRun
    end
Loading

Flow diagram for fail-closed client choice eligibility

flowchart LR
    Config["client_pipelines.enabled"] --> PipelineChoice{"Pipeline choice allowed?"}
    Subject["Principal.subject"] --> PipelineChoice
    Roles["_has_role"] --> PipelineChoice
    PipelineChoice -->|yes| Choose["Select pipeline or preset"]
    PipelineChoice -->|no| Reject["Reject client pipeline choice"]

    BackendConfig["client_backends.enabled"] --> BackendChoice{"Backend choice allowed?"}
    Subject --> BackendChoice
    BackendChoice -->|yes| Backends["Select configured backend candidates"]
    BackendChoice -->|no| RejectBackends["Reject backend choice"]
Loading

Flow diagram for startup warnings on skippable pipeline steps

flowchart TD
    Start["PluginHost startup"] --> Enabled{"client_pipelines.enabled?"}
    Enabled -->|no| Done["No warning"]
    Enabled -->|yes| Steps["Inspect plugins.pipeline steps"]
    Steps --> Frame["Compare client_pipelines.prepend and append"]
    Frame --> Presets["Check presets when inline choices are unavailable"]
    Presets --> Exempt["Ignore default route step without params"]
    Exempt --> Warning{"Any step clients can skip?"}
    Warning -->|yes| Log["logger.warning"]
    Warning -->|no| Done
Loading

File-Level Changes

Change Details Files
Client pipeline and backend selection now requires authentication, with client pipelines disabled by default.
  • Defaulted client_pipelines.enabled to false.
  • Rejected pipeline and backend choices from principals without a subject.
  • Updated plugin listings to hide selectable plugins, presets, and steps from anonymous callers.
  • Added regression coverage for defaults, selection, direct resolution, and listing behavior.
foca/plugins/config.py
foca/plugins/engine.py
foca/plugins/api.py
tests/plugins/test_plugin_api.py
tests/plugins/test_plugin_selection.py
tests/plugins/test_plugin_provenance.py
tests/plugins/test_plugin_routing.py
tests/plugins/test_plugin_tags.py
Startup validation warns when enabled client pipelines can bypass steps in the default pipeline.
  • Compared default steps against prepend and unconditional append frame steps, including alternatives, parameters, and failure handling.
  • Handled presets-only configurations and exempted the default route step without parameters.
  • Added tests covering missing frame steps, mismatched parameters or failure behavior, conditional append steps, and preset coverage.
foca/plugins/engine.py
tests/plugins/test_plugin_selection.py
Documentation now describes fail-closed selection and the corrected pipeline framing semantics.
  • Documented that requests without a pipeline choice receive the default pipeline without the client frame.
  • Directed administrators to place mandatory policies in both plugins.pipeline and client_pipelines.prepend.
  • Documented authentication requirements, the disabled-by-default setting, startup warnings, and backend-selection behavior.
  • Corrected the client pipeline configuration docstring.
docs/configuration/plugins.md
docs/plugins.md
foca/plugins/config.py

Assessment against linked issues

Issue Objective Addressed Explanation
#518 Fail closed for client-controlled pipeline and backend choices by default, and require an authenticated caller before honoring those tags. ✅
#518 Correct the configuration docstring and warning documentation to explain that the client frame does not run for requests using the default pipeline, and where policies must be placed. ✅
#518 Warn at startup when enabled client pipelines can skip steps in the default pipeline, and keep the configuration and migration guidance consistent with the changed semantics. ✅

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 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (23822c5) to head (bc58d31).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #526   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           55        55           
  Lines         6616      6636   +20     
=========================================
+ Hits          6616      6636   +20     
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 26, 2026 20:17

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

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

## Individual Comments

### Comment 1
<location path="foca/plugins/engine.py" line_range="235" />
<code_context>
+    """
+    return any(
+        kept.alternatives == step.alternatives and kept.on_failure == step.on_failure
+        for kept in steps
+    )
+
</code_context>
<issue_to_address>
**Timed-out policies go unnoticed**

When the plugin exceeds the shorter timeout of a frame step matching a default policy step with the same alternatives and `on_failure: skip`, `_has_step` compares alternatives and `on_failure` but not timeout, so it treats the frame as covering the default step; the frame copy times out and skips the policy without a startup warning, letting clients bypass it.

Include timeout when comparing steps in `_has_step`.
</issue_to_address>

### Comment 2
<location path="foca/plugins/engine.py" line_range="390" />
<code_context>
+        skippable = [
+            step.id
+            for step in self.default_pipeline.steps
+            if not _is_default_route_step(step)
+            and any(not _has_step([*frame, *steps], step) for steps in choices)
+        ]
</code_context>
<issue_to_address>
**Default routing bypass goes unwarned**

When client pipelines are enabled, `client_pipelines.append` is empty, and a client selects an inline pipeline without a route step, `_warn_skippable_steps` exempts the default router without checking whether the frame still appends one. With no append route, an inline client pipeline without a route step skips the default router’s ordering behavior, but startup reports no skippable step.

Exempt the default route only when the frame guarantees a fallback route step, or when every selectable choice supplies an equivalent route step.
</issue_to_address>

### Comment 3
<location path="foca/plugins/engine.py" line_range="234-235" />
<code_context>
+        `on_failure` (identifiers and timeouts may differ).
+    """
+    return any(
+        kept.alternatives == step.alternatives and kept.on_failure == step.on_failure
+        for kept in steps
+    )
+
</code_context>
<issue_to_address>
**Repeated steps evade warning**

When the default pipeline contains multiple equivalent steps with distinct IDs, while a frame or a selectable preset contains fewer equivalent copies, `_has_step` reuses the same matching frame or preset step for every identical default step, so a single copy can suppress warnings for multiple default steps and admins are not alerted that client choices run fewer copies.

Match equivalent steps as a multiset, consuming each match once, and warn when a choice has fewer copies than the default pipeline.
</issue_to_address>

### Comment 4
<location path="foca/plugins/engine.py" line_range="206-219" />
<code_context>
     return not roles or bool(set(roles) & set(principal.groups))


+def _is_default_route_step(step: ResolvedStep) -> bool:
+    """Check whether a step is the default route step without params.
+
+    Args:
+        step: Resolved step.
+
+    Returns:
+        Whether all alternatives are the default router with default params.
+    """
+    return all(
+        alternative.plugin == DEFAULT_ROUTER
+        and not alternative.params.model_dump(exclude_defaults=True)
+        for alternative in step.alternatives
+    )
+
+
</code_context>
<issue_to_address>
**Changed routing behavior goes unnoticed**

When the default pipeline has a route step with default router params but a customized timeout or `on_failure`, and client pipelines are enabled, `_is_default_route_step` exempts that step based only on plugin and params, so startup emits no warning when a client route phase replaces its configured timeout or failure behavior.

Include timeout and `on_failure` when deciding whether the default route step is exempt.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and if the authentication check or the default is wrong, a caller could select a replacement pipeline or backend and bypass steps the default pipeline was meant to enforce. Reverting would restore the old behavior, but requests already processed under the wrong selection could have effects that cannot be undone.

Blocking findings: foca/plugins/engine.py:235, foca/plugins/engine.py:390, foca/plugins/engine.py:235, foca/plugins/engine.py:219


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

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/engine.py Resolved
uniqueg and others added 2 commits October 26, 2026 21:39
A frame copy of a policy step with a shorter timeout (and on_failure:
skip) can let clients skip the policy, so the startup warning now
compares timeouts too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit fc356e7 into dev Oct 26, 2026
30 checks passed
@uniqueg
uniqueg deleted the fix/client-pipelines-closed branch October 26, 2026 20:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: security Related to security

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Client pipelines can drop policy steps by default

1 participant