Skip to content

feat(plugins): write gateway tags - #505

Merged
uniqueg merged 135 commits into
devfrom
feat/gateway-tags
Oct 25, 2026
Merged

uniqueg merged 135 commits into
devfrom
feat/gateway-tags

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds foca.plugins.tags, a spec-compliant, trustworthy record of where a task went, as string tags under plugins.tags.prefix (default gateway.). It replaces proTES's forwarded_to array, which isn't spec-compliant. This is the seventh PR of the v0.18.0 plugin stack (#485).

  • creation_tags(run): pipeline_hash (left out without a hash), pipeline_source, plugins (id@version) and provenance.
  • routing_tags(run):
    • backend, backend_task_id, forwarded_at and attempts.
    • route: compact JSON of the last max_route_entries attempts (a new setting, default 10).
    • route_truncated.
  • Limits: values are strings of at most 1 KiB, and route is at most 4 KiB, with the earliest attempts dropped first. URLs have no user info, query or fragment, and only reason codes are recorded.
  • strip_for_forwarding(): removes every key under the prefix from relayed requests, so nested gateways write their own.
  • Trust:
    • The engine refuses request hook output that adds, changes or removes tags under the prefix (invalid_output), so plugins can't forge them.
    • without_server_tags() drops all keys under the prefix except the client's pipeline and backends before the gateway's tags are merged in, as a second line of defence.
  • Docs: the tag table for clients and dashboards, and how apps write the tags.

Closes #494

Verification

Run locally on 04091e8 (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.
  • mkdocs build --strict: pass.
  • pre-commit: pass.

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

Review: two rounds of adversarial and quality review.

  • Round 1 (ed759f4):
    • None was written into a string map when a pipeline had no hash;
    • non-string remote IDs failed after the backend accepted;
    • an unused constant;
    • loose types;
    • missing tests for the app flow and for truncation.
  • Round 2:
    • request hooks could forge or drop gateway tags, so dashboards couldn't trust them (28b66d6). The reviewer's spoofing repro now ends in PipelineFailed.

All are fixed.

Sourcery: 8 findings. 6 are fixed or clarified in c046cd8:

  • lone surrogates and invalid ports no longer break tags;
  • references that don't fit are left out instead of cut;
  • the latest attempt stays in the route;
  • gateway.plugins lists the plugins that ran, whatever the outcome;
  • the docs say that it covers the request phase.

2 are declined (see below). CI on c046cd8: 27 checks pass, and 3 are skipped (the image jobs, and the Trivy upload).

Declined review findings

  • Sourcery: backend URLs in tags: declined. Naming the backend is the purpose of gateway.backend. URLs are registry-verified or admin-configured base URLs without user info, query or fragment, and apps choose which tags they write.
  • Sourcery: durability of the accepted backend: declined. Persisting the task is the app's job, and ProvenanceStore.save() persists the attempts.
  • Commit hygiene (merge commits from the stack): declined, because the PR is squash-merged.

Notes

The reserved-tag check covers payloads with a tags map (TES). Apps of other APIs (e.g., WES, whose tags are a form field) apply without_server_tags() themselves; the docs say so.

🤖 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 23 commits October 25, 2026 18:31
A json body that is no JSON (NaN, a set, other objects) gave an
InvalidJSONError classified as connection_lost, or a raw TypeError,
although nothing was sent; a header with a line break gave
invalid_url. Both now raise InvalidRequest (a RequestNotSent, reason
invalid_request or invalid_header) before sending, so all errors stay
HttpErrors. The dead InvalidHeader branch of _classify is gone.

Refs #490

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Connections checked all resolved addresses but connected only to the
first, losing urllib3's fallback across A/AAAA records. They now try
the checked addresses in order within one connect budget; the peer of
the one that connects is checked as before.

Refs #490

Co-Authored-By: Claude Opus 5.5 <[email protected]>
While one thread read a registry, the others got the cached backends,
which are none before the first read and after an idle gap longer
than max_stale, so requests found no discovered backends although a
read was about to deliver them. Threads now wait for the read unless
a good read within max_stale is cached; with one, they keep getting
it while the refresh runs. Tests use two real threads.

Refs #493

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A discovered backend's id is its URL, which can equal a configured
entry's custom id for another URL; candidates then had two backends
with one id, and the client's backend selection could pick the wrong
one. expand() now skips such discovered backends (logged at debug
level).

Refs #493

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The appended router's if_missing_phase also counted the admin's
prepend steps, so a route plugin in prepend dropped
foca.routing.ordered from every client and preset pipeline. Only the
client's or preset's own steps count now.

Refs #491

Co-Authored-By: Claude Opus 5.5 <[email protected]>
client_pipelines.prepend frames client and preset pipelines only,
not plugins.pipeline, so pinning that must always hold belongs in
both. The router's module docstring now says that BUILTIN_PLUGINS is
its only source, not an entry point.

Refs #491

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces spec-compliant, bounded gateway tags for pipeline provenance and backend routing, integrates reserved-tag protections into the request engine, and documents and tests the forwarding, trust, privacy, and truncation behavior.

Sequence diagram for trusted gateway tag lifecycle

sequenceDiagram
    participant Client
    participant Engine
    participant Hook as RequestHook
    participant GatewayTags
    participant Backend

    Client->>Engine: submit request with client tags
    Engine->>Hook: request()
    Hook-->>Engine: payload
    Engine->>GatewayTags: check_reserved_tags(before, after, prefix)
    alt reserved tags changed
        GatewayTags-->>Engine: invalid_output
        Engine-->>Client: PipelineFailed
    else tags unchanged
        Engine->>GatewayTags: without_server_tags(tags, prefix)
        GatewayTags-->>Engine: client tags only
        Engine->>GatewayTags: creation_tags(run)
        GatewayTags-->>Engine: creation tags
        Engine->>GatewayTags: strip_for_forwarding(tags, prefix)
        GatewayTags-->>Backend: tags without gateway prefix
        Engine->>Backend: forward request
        Backend-->>Engine: forwarding result
        Engine->>GatewayTags: routing_tags(run)
        GatewayTags-->>Engine: routing tags
    end
Loading

Flow diagram for bounded gateway routing tags

flowchart LR
    A[Pipeline attempts] --> B["routing_tags(run)"]
    B --> C[Clean URLs and record outcomes]
    C --> D[Keep last max_route_entries]
    D --> E{route exceeds 4 KiB?}
    E -- Yes --> F[Drop earliest attempts]
    F --> G[Set route_truncated=true]
    E -- No --> H[Write compact route JSON]
    G --> I[Write backend and attempt tags]
    H --> I[Write backend and attempt tags]
Loading

File-Level Changes

Change Details Files
Added a pure gateway-tag generation and sanitization module with bounded creation and routing metadata.
  • Generate pipeline, plugin, provenance, backend, attempt, and compact route tags.
  • Normalize URLs and remote IDs, omit unavailable values, and enforce UTF-8 size limits.
  • Strip reserved tags before forwarding and preserve only client pipeline/backend selections when merging.
  • Reject malformed or oversized route configuration through validation.
foca/plugins/tags.py
foca/plugins/config.py
Integrated reserved-tag trust checks into request processing.
  • Detect plugins that add, modify, or remove any reserved-prefix tag and treat the output as invalid.
  • Document and enforce the distinction between client-owned selection tags and gateway-owned tags.
foca/plugins/engine.py
Documented the gateway tag contract and application integration points.
  • Added configuration and API reference coverage for tag helpers.
  • Documented tag names, limits, privacy rules, forwarding behavior, trust guarantees, and TES/WES integration.
docs/configuration/plugins.md
docs/plugins.md
docs/reference.md
Added comprehensive unit and flow coverage for tag generation, trust boundaries, forwarding, and limits.
  • Tested creation and routing tags across accepted, failed, unknown, and unaccepted attempts.
  • Covered URL cleanup, truncation, missing hashes, non-string remote IDs, and configuration validation.
  • Verified plugin spoofing is rejected while non-reserved tags remain mutable.
tests/plugins/test_plugin_tags.py
tests/plugins/fakes.py

Assessment against linked issues

Issue Objective Addressed Explanation
#494 Provide pure tag helpers that write creation and forwarding metadata as string-map values, enforce the specified size and URL sanitization limits, truncate routes, and strip all gateway-prefixed tags before forwarding. ✅
#494 Ensure gateway-reserved tags remain trustworthy by preventing request hooks from changing them and by preserving only permitted client tags when apps merge server-written tags. ✅
#494 Document the gateway tag reference, client restrictions, and re-run behavior, and configure a positive route-entry limit. ✅

Possibly linked issues

  • feat(plugins): write gateway tags #494: The PR implements the issue’s requested creation_tags, routing_tags, stripping, limits, trust protections, and documentation.
  • #N/A: The PR implements the issue’s P11 gateway-tags component, including creation and routing tags, reserved-tag protections, and documentation.

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 (3e6e1b2) to head (c046cd8).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #505   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           51        52    +1     
  Lines         5870      5963   +93     
=========================================
+ Hits          5870      5963   +93     
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 21:36

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

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

## Individual Comments

### Comment 1
<location path="foca/plugins/tags.py" line_range="236" />
<code_context>
+    tags: dict[str, str] = {f"{prefix}attempts": str(len(records))}
+    if records and records[-1].outcome != "not_accepted":
+        last = records[-1]
+        tags[f"{prefix}backend"] = _clip(clean_url(last.url))
+        tags[f"{prefix}forwarded_at"] = last.started_at
+        if last.outcome == "accepted" and last.remote_id is not None:
</code_context>
<issue_to_address>
**Backend URL details reach task readers**

When a configured or discovered backend URL contains a sensitive path or internal hostname, and a task reader is not trusted with that information, `clean_url()` removes user info, query and fragment but preserves the backend host and path; `routing_tags()` writes them into task tags, which the task reader can retrieve. A backend URL with a path-based credential or sensitive internal hostname therefore exposes it to the task reader.

Avoid exposing full backend URLs in client-readable tags, or provide an explicit policy that redacts sensitive paths and hosts before writing them.

Also at `foca/plugins/tags.py:244`.
</issue_to_address>

### Comment 2
<location path="foca/plugins/tags.py" line_range="63" />
<code_context>
+    Returns:
+        The value, without trailing characters beyond the limit.
+    """
+    return value.encode("utf-8")[:limit].decode("utf-8", errors="ignore")
+
+
</code_context>
<issue_to_address>
**Malformed text breaks tag generation**

When an accepted backend returns a task ID containing an unpaired surrogate, or an app passes such a provenance path, `_clip()` raises `UnicodeEncodeError` while encoding the value, so `routing_tags()` or `creation_tags()` fails while producing tags.

Handle unpaired surrogates before UTF-8 clipping so tag generation completes.

Also at `foca/plugins/tags.py:215`, `foca/plugins/tags.py:239`, `foca/plugins/engine.py:827`.
</issue_to_address>

### Comment 3
<location path="foca/plugins/tags.py" line_range="79" />
<code_context>
+    host = parts.hostname or ""
+    if ":" in host:
+        host = f"[{host}]"
+    netloc = f"{host}:{parts.port}" if parts.port else host
+    return urlunsplit((parts.scheme, netloc, parts.path, "", "")).rstrip("/")
+
</code_context>
<issue_to_address>
**Malformed backend URL breaks tag writing**

When a caller supplies a backend URL with a non-numeric port and then calls `routing_tags(run)`, `parts.port` raises `ValueError` for a URL with a non-numeric port, so `routing_tags()` aborts while formatting an attempt record. The app cannot write routing tags after forwarding, even when the attempt was already recorded as not accepted.

Handle malformed URL parsing in `clean_url()` as the provenance helper does, or reuse that helper.
</issue_to_address>

### Comment 4
<location path="foca/plugins/tags.py" line_range="254-255" />
<code_context>
+    ]
+    shown = entries[-conf.max_route_entries :]
+    route = json.dumps(shown, separators=(",", ":"))
+    while shown and _size(route) > MAX_ROUTE_SIZE:
+        shown = shown[1:]
+        route = json.dumps(shown, separators=(",", ":"))
+    tags[f"{prefix}route"] = route
</code_context>
<issue_to_address>
**Latest attempt disappears**

When a backend URL makes its single route entry exceed 4 KiB, `routing_tags()` drops the oversized entry while shrinking `shown`, then stores an empty route, so dashboards lose the latest attempt.

Preserve the oversized latest entry, for example by truncating its fields, instead of dropping it.
</issue_to_address>

### Comment 5
<location path="foca/plugins/tags.py" line_range="215" />
<code_context>
+    if pipeline["resolved_hash"] is not None:
+        tags[f"{prefix}pipeline_hash"] = pipeline["resolved_hash"]
+    if provenance_path is not None:
+        tags[f"{prefix}provenance"] = _clip(provenance_path)
+    return tags
+
</code_context>
<issue_to_address>
**Long references become unusable**

When the provenance path or accepted backend ID exceeds 1 KiB, `_clip` stores only a prefix of `provenance_path` or `last.remote_id`, so the provenance link points to a nonexistent path and the backend task ID no longer identifies the accepted task.

Omit an overlong reference (or provide an explicit truncation indication) instead of storing a misleading partial path or ID.

Also at `foca/plugins/tags.py:239`.
</issue_to_address>

### Comment 6
<location path="foca/plugins/tags.py" line_range="200" />
<code_context>
+        source = f"preset:{pipeline['preset']}"
+    plugins: list[str] = []
+    for execution in run.executions:
+        if execution.outcome != "ok" or execution.plugin is None:
+            continue
+        loaded = run.host.plugins[execution.plugin]
</code_context>
<issue_to_address>
**Ran plugins disappear**

When a plugin hook fails but a fallback, `on_failure: skip`, or later alternative lets the pipeline continue, `creation_tags()` filters out executions whose outcome is not `ok`, so `gateway.plugins` omits plugins that ran and dashboards show an incomplete list.

Include executions with a plugin even when their outcome is not `ok`.

Also at `docs/plugins.md:538`.
</issue_to_address>

### Comment 7
<location path="foca/plugins/tags.py" line_range="200-201" />
<code_context>
+        source = f"preset:{pipeline['preset']}"
+    plugins: list[str] = []
+    for execution in run.executions:
+        if execution.outcome != "ok" or execution.plugin is None:
+            continue
+        loaded = run.host.plugins[execution.plugin]
+        name = f"{execution.plugin}@{loaded.version or 'unknown'}"
</code_context>
<issue_to_address>
**Plugin tag omits later hooks**

When the pipeline has plugins whose hooks run only in route, forward, or response phases, `creation_tags()` reads `run.executions` when apps call it after the request phase, so plugins that run only in route, forward, or response phases are absent from the stored `gateway.plugins` value; dashboards see an incomplete plugin list.

Update the stored plugin tag after those phases, or define and document it explicitly as listing only plugins executed by task creation.
</issue_to_address>

### Comment 8
<location path="docs/plugins.md" line_range="552-553" />
<code_context>
+never messages; `gateway.pipeline_hash` is left out for pipelines without
+hash (no I-JSON), and `gateway.plugins` is empty if its first entry does
+not fit. FOCA provides the tags, and apps write them: they merge
+`foca.plugins.tags.creation_tags(run)` into new tasks after the `request`
+phase and `routing_tags(run)` after forwarding, and relay requests without
+any key under the prefix (`strip_for_forwarding(tags, prefix)`), so nested
+gateways write their own:
</code_context>
<issue_to_address>
**Accepted backend can go unrecorded**

When a backend accepts the request and the process stops before the app persists `routing_tags(run)`, `attempt_records` exists only on the in-memory run, and `routing_tags()` reads it after forwarding. If the process stops before the app persists those tags, the task retains only its creation tags and the accepted backend cannot be recovered from this record.

Persist attempt outcomes durably or make the post-forward tag update recoverable before the task is considered complete.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 8 findings to address first, and if consuming apps store these tags as documented, the backend host/path and accepted backend task ID can be returned in task or run responses; a client that has read them cannot be made to forget them by reverting. URL cleanup removes credentials and query strings, but not internal hostnames or paths.

Blocking findings: foca/plugins/tags.py:236, foca/plugins/tags.py:63, foca/plugins/tags.py:79, foca/plugins/tags.py:255, foca/plugins/tags.py:215, and 3 more


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

Comment thread foca/plugins/tags.py Resolved
Comment thread foca/plugins/tags.py Resolved
Comment thread foca/plugins/tags.py Resolved
Comment thread foca/plugins/tags.py Resolved
Comment thread foca/plugins/tags.py Resolved
Comment thread foca/plugins/tags.py Resolved
Comment thread foca/plugins/tags.py Resolved
Comment thread docs/plugins.md Resolved
- 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]>
@uniqueg
uniqueg merged commit 93fa956 into dev Oct 25, 2026
30 checks passed
@uniqueg
uniqueg deleted the feat/gateway-tags branch October 25, 2026 21:54
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): write gateway tags

1 participant