Skip to content

feat(plugins): record provenance - #499

Merged
uniqueg merged 40 commits into
devfrom
feat/plugin-provenance
Oct 25, 2026
Merged

uniqueg merged 40 commits into
devfrom
feat/plugin-provenance

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Records the provenance of every request a gateway handles: which plugins ran, in which versions, with which pipeline, which alternatives were tried, and their outcomes. This is the third PR of the v0.18.0 plugin stack (#485).

  • Records:
    • Plugin distributions with version and RECORD digest, the app's name and version, and the image digest. Together these form a deduplicated build document.
    • The resolved pipeline: stored inline for client pipelines, and by hash for default and preset pipelines. Hashes use RFC 8785 canonical JSON.
    • Executions per step and alternative, with outcome, annotations, timings and changed paths.
    • Forward attempts, with reasons and final_reason (including outcome_unknown).
  • Store: ProvenanceStore.save() and save_failure() write to MongoDB. Failure records expire after 30 days (TTL index). The stores never raise: errors are logged, the record gets stored: false, and the task stays inline.
  • Bounds:
    • Hashed data must be I-JSON; records whose data isn't get resolved_hash: null and error: not_json.
    • Changed paths are capped at 256 per execution and 64 KiB per run (truncated: true). Pointers longer than 512 characters fall back to their parent, and arrays whose length changed are recorded whole.
    • Annotations must be I-JSON.
  • Privacy:
    • Credential headers, client-address headers (x-forwarded-for, forwarded, x-real-ip), headers listed in plugins.provenance.secret_headers, and backend auth are excluded from hashing.
    • SecretStr params are redacted.
    • The docs say that hashes of low-entropy values can be guessed.
  • Robustness: response hooks can no longer break provenance after the backend accepted. client_headers must be Headers, and describing changes never raises.

Closes #488

Verification

Run locally:

  • ruff check and ruff format --check: pass.
  • mypy: pass.
  • pytest without MongoDB: pass, with 100% coverage of foca/plugins. The TTL index is checked on mongomock.
  • mkdocs build --strict: pass.
  • pre-commit run --all-files: pass.
  • Push hook (semgrep, ast-grep): pass.

The MongoDB tests did not run locally. CI: 27 checks pass, including the MongoDB tests; 2 are skipped as intended.

Review: two rounds of adversarial and quality review on frozen snapshots of the branch.

  • Round 1 found:
    • overflowing integers escaping as 500s after the backend accepted;
    • hashing errors on non-I-JSON params;
    • a stale image_digest;
    • unbounded changed paths;
    • hashes of credential headers;
    • a missing final_reason;
    • loose types;
    • a scattered record format;
    • duplicated build fields.
  • Round 2 found:
    • non-Headers client_headers raising after the backend accepted (a regression);
    • path sizes still unbounded, despite the count cap;
    • non-I-JSON annotations;
    • weak index and app_info tests;
    • save() not guarding record construction.

All are fixed.

Sourcery: 12 findings. 10 are fixed in 77a671e:

  • plugin exception messages are no longer stored;
  • Set-Cookie is excluded;
  • change hashes are keyed per process (HMAC);
  • user info and query are stripped from URLs;
  • deadline expiry is reported correctly;
  • non-I-JSON resolved pipelines no longer break writes;
  • records are capped at 1 MiB;
  • build documents are kept inline when a write fails;
  • failure records are idempotent;
  • array pointers are bounded.

The other 2 are documented instead of changed: map keys in paths, and MongoDB client timeouts. CodeQL flagged a URL substring check in a test as a false positive; b6c276a compares the fields exactly. CI on b6c276a: 27 checks pass, 3 skipped as intended.

Declined review findings

  • Commit hygiene (merge commits from the stack): declined, because the PR is squash-merged.

🤖 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]>
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]>
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
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]>
- Principal.token is set only if a token was validated (claims).
- Repeated header fields of inbound requests are combined (e.g., Via).
- Problem responses keep the custom title of a plugin's rejection;
  problem_response() takes a request-specific title.
- Annotations reject NaN and infinite numbers.
- Plugins loaded before a load or pipeline error are closed.
- Gateway names bracket IPv6 addresses (pattern GATEWAY_ID_PATTERN),
  and the outbound Via header, with this gateway's entry, stays within
  1024 characters.
- One gateway app per process: configure() refuses other settings
  while a host is in use; reset() closes it; the host is closed at
  exit.
- Docs: app callbacks run outside plugin deadlines and must be fast;
  rejections in the response phase count as errors.

Refs #486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	foca/plugins/config.py
#	foca/plugins/engine.py
Guard against names in foca.plugins.__all__ that do not resolve (e.g.,
a missing import), as noticed by proTES.

Refs #486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
After an attempt whose outcome is unknown, attempts() ends without
raising; final_reason is now outcome_unknown, so that provenance and
apps can tell this from a success. Docs and the module example check
it after the loop.

Refs #488

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A merge dropped InvalidVia from the imports of foca.plugins, though it
is still in __all__; the test of the exported names catches this now.

Refs #487

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the pre-review of per-request pipelines and backends:

- Tags that are not a map give 400 (reserved-tag) instead of being
  ignored, which skipped the check of reserved tags. Apps of APIs other
  than TES must pass tags= to start() (TypeError otherwise); the default
  is a typed sentinel. (start() takes no pipeline= argument any more
  since the per-request pipelines landed; callers pass tags.)
- Whether choices are enabled is checked in one place, when the tags
  are read, and before their values are parsed.
- The backends tag is at most 8 KiB before it is parsed, and lists at
  least one backend.
- Presets need the roles of their plugins (not client_selectable, as
  admins write them); unknown presets get the same message.
- Preset steps with the identifier of a frame step and
  client_pipelines.allowed: [] are refused at startup; the message for
  preset names without presets allowed says so.
- PRESET_PATTERN is defined once (config), the item length limit is
  not repeated in its message, the unused ClientSelection.backends_raw
  and the PROBLEM_TYPE_BASE re-export of the engine are removed.
- Tests: random client pipelines from allowed and forbidden plugins
  never let a forbidden one through; unknown plugins in prepend fail
  at startup; WES tags; limits of the backends tag.

foca/utils/urls.py keeps its lazy Flask import: get_public_url() needs
the request context, while the other URL helpers serve the
framework-free foca.plugins, which must import without Flask.

Refs #487

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A preset or client pipeline (even an empty one) runs instead of
plugins.pipeline; only the frame runs for every request, so policies
belong in client_pipelines.prepend. Also name the available keys
client_selectable and roles, the preset role rule, the limits of the
backends tag, and the problem types invalid-via and gateway-error.

Refs #487

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Client pipelines with NaN, Infinity, non-finite numbers (1e999) or
integers beyond 2^53 - 1 are refused (400): RFC 8785 hashes of the
resolved pipeline cannot represent them, so provenance would fail
after the backend accepted, or pipelines would collide.

Refs #487

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	docs/configuration/plugins.md
Address the pre-review of provenance:

- Hashes refuse integers beyond 2^53 - 1 (I-JSON), which RFC 8785
  cannot represent exactly and which overflowed for huge integers;
  changes of such data are recorded as error: not_json, also for
  arithmetic errors, so hook calls never fail on them.
- provenance() records resolved_hash: null with error: not_json for
  pipelines that are no I-JSON; save() and save_failure() never raise
  (errors of the collections are logged; stored: false), as the
  backend may have accepted already.
- Build keys include the image digest, so that a new image gives new
  build documents ($setOnInsert kept the first digest).
- Changed paths are capped at 256 per call (truncated: true), and
  arrays whose length changed are recorded as a whole.
- Hashes of changes leave out credential headers, the new
  plugins.provenance.secret_headers and the credential type (auth).
- The record format lives in provenance.py (describe_changes, public);
  build keys and documents share one field dict; the store is typed
  with PipelineRun and a Collection protocol.
- Execution.describe drops only fields that are None.
- plugins.provenance.detail is removed: no other level is planned in
  this release, and nothing used it.

Refs #488

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add GatewayApp(name=, version=) to the apps example, describe the
app_info of records, a shortened sample record, the I-JSON rule, the
left-out credentials and secret_headers, and the 30-day default
retention of failure records on the configuration page.

Refs #488

Co-Authored-By: Claude Opus 5.5 <[email protected]>
uniqueg and others added 8 commits October 25, 2026 03:17
Address the second review round of client pipelines:

- Tag values with unpaired surrogates are refused with 400 instead of
  failing with a UnicodeEncodeError; client pipelines must be valid
  Unicode (strings and keys) and are nested 32 levels deep at most.
- Identifiers of client pipelines and presets clash only with the
  frame steps that are kept: appended defaults (if_missing_phase) that
  are left out no longer block the same identifiers; presets are
  checked against them at startup. Errors say to set an explicit id,
  and the client's error no longer names the gateway's steps.
- A _has_role() helper replaces three role checks; InvalidSelection
  sits next to InvalidVia; STEP_ID_PATTERN has its docstring back.
- Docs no longer say that discarded backends are recorded (#488 adds
  that).

Refs #487

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Backend selections match items with :// against candidate URLs and
  other items against identifiers only, so that an identifier that
  equals another candidate's URL cannot select the wrong backend.
- Choice tags that are present count whatever their value: null and
  other non-strings get 400, also when the choice is disabled.
- Objects of client pipelines must not have duplicate keys (I-JSON).
- Clashes of preset steps with the frame are checked by the engine
  only, against the frame steps that are kept (no steps dropped for
  lack of enabled plugins, no left-out appended defaults).

Refs #487

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the second review round of provenance:

- Response hooks must keep the client's Headers (as forward hooks do),
  and describing changes never raises (error: internal), so that a
  hook cannot fail a request that a backend accepted.
- Changed paths are collected up to the cap only, pointers longer
  than 512 characters are recorded as their parent, and the paths of
  a run take at most 64 KiB (then truncated: true), so that records
  stay far below the BSON limit.
- Annotations must be I-JSON (exact integers, valid Unicode).
- save() also catches errors while building the record, with a
  minimal fallback record.
- Client address headers (Forwarded, X-Forwarded-For, X-Real-IP) are
  left out of hashes; docs say to put low-entropy headers in
  secret_headers and to declare secret params as SecretStr, which is
  redacted (tested).
- Tests: TTL index on mongomock from FAILURE_INDEXES, app_info of
  create_host().

Refs #488

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

This PR adds end-to-end plugin provenance: the runtime captures privacy-conscious, bounded execution and forwarding details using RFC 8785 hashes, while ProvenanceStore deduplicates build and pipeline data and optionally persists failed runs with TTL retention; configuration, documentation, and comprehensive tests expose and validate the feature.

Sequence diagram for recording gateway provenance

sequenceDiagram
    participant Client
    participant PipelineRun
    participant PluginHost
    participant Backend
    participant ProvenanceStore
    participant MongoDB

    Client->>PipelineRun: attempts(candidates)
    PipelineRun->>PluginHost: execute plugin hooks
    PluginHost-->>PipelineRun: Execution with annotations and changes
    PipelineRun->>PipelineRun: describe_changes()
    PipelineRun->>Backend: forward request
    Backend-->>PipelineRun: attempt outcome
    PipelineRun->>PipelineRun: provenance()
    PipelineRun->>ProvenanceStore: save(run)
    ProvenanceStore->>MongoDB: upsert plugin build and pipeline
    ProvenanceStore-->>Client: task provenance record
Loading

Flow diagram for bounded privacy-conscious provenance

flowchart TD
    Input[Plugin hook input and output] --> Snapshot[Sanitize snapshot]
    Snapshot --> Exclude[Exclude credentials client addresses secret headers and auth]
    Exclude --> Hash[RFC 8785 canonical JSON SHA-256]
    Exclude --> Paths[Changed JSON Pointers]
    Paths --> Bounds[Cap 256 paths 512-character pointers and 64 KiB per run]
    Hash --> Result[Execution changes]
    Bounds --> Result
    Result --> Record[Provenance record]
    Record --> Invalid{I-JSON valid?}
    Invalid -->|No| Error[error: not_json]
    Invalid -->|Yes| Store[Store or keep inline]
Loading

File-Level Changes

Change Details Files
Add provenance capture across plugin pipeline execution, routing, forwarding, and application metadata.
  • Expose run provenance as JSON with engine, pipeline, plugin builds, executions, route, selection, attempts, and final outcome.
  • Track per-hook changes using RFC 8785 hashes and bounded JSON Pointer paths, including I-JSON handling, secret exclusion, redacted parameters, annotations, and robust error fallbacks.
  • Record app name/version and image digest alongside FOCA and plugin API metadata.
  • Handle unknown forwarding outcomes without raising after a backend may have accepted the request.
foca/plugins/engine.py
foca/plugins/records.py
foca/plugins/runtime.py
foca/plugins/checks.py
foca/plugins/context.py
Implement canonical provenance hashing, change descriptions, build identity, and MongoDB persistence.
  • Add RFC 8785 canonical JSON serialization and SHA-256 content hashes with I-JSON validation.
  • Generate deduplicated plugin build documents from distribution metadata, RECORD digest, API version, and image digest.
  • Persist default/preset pipelines and build documents by hash while keeping client pipelines inline.
  • Add failure-record persistence with optional configuration, error metadata, and a 30-day TTL index; ensure storage failures never escape.
foca/plugins/provenance.py
foca/plugins/__init__.py
foca/plugins/config.py
Document and test the provenance contract, privacy guarantees, bounds, configuration, and storage behavior.
  • Document provenance fields, pipeline references, privacy exclusions, low-entropy hash caveats, failure retention, and integration examples.
  • Add configuration for failed-run recording and secret headers, plus public API/reference documentation.
  • Cover canonicalization vectors, hashing/privacy behavior, path and run-size limits, annotations, secret redaction, final reasons, MongoDB persistence, TTL indexes, and robustness regressions.
docs/configuration/plugins.md
docs/plugins.md
docs/reference.md
tests/plugins/test_plugin_provenance.py
tests/plugins/test_plugin_engine.py
tests/plugins/test_plugin_runtime.py
tests/plugins/fakes.py

Assessment against linked issues

Issue Objective Addressed Explanation
#488 Record prospective pipeline provenance, including its source, requested tag reference, resolved pipeline, and RFC 8785 SHA-256 hash, with build and pipeline normalization helpers. ✅
#488 Capture retrospective execution, routing, selection, and forwarding provenance with bounded changed-path descriptions, annotations, sanitized errors, and privacy-aware hashing. ✅
#488 Provide configurable, app-owned storage for provenance and optional failed-run records, and document the record shape, storage, retention, and privacy considerations. ✅

Possibly linked issues

  • feat(plugins): record provenance #488: The PR directly implements the issue’s provenance requirements, including RFC 8785 hashes, execution records, app-owned collections, and optional failed-run storage.

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 (6914279) to head (b6c276a).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #499    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           44        45     +1     
  Lines         4749      5044   +295     
==========================================
+ Hits          4749      5044   +295     
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 04:39

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 12 issues

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

## Individual Comments

### Comment 1
<location path="foca/plugins/provenance.py" line_range="297" />
<code_context>
+    """
+    if phase == "route":
+        return [backend.id for backend in value]
+    excluded = CREDENTIAL_HEADERS | CLIENT_ADDRESS_HEADERS | secret_headers
+    if phase == "response":
+        return {
</code_context>
<issue_to_address>
**Session cookies enter hashes**

When a response contains a Set-Cookie header, `_snapshot()` includes the cookie value, so `describe_changes()` hashes session credentials into the stored response record, where readers can guess low-entropy values.

Exclude `Set-Cookie` from response snapshots before hashing.

Also at `foca/plugins/provenance.py:301`.
</issue_to_address>

### Comment 2
<location path="foca/plugins/provenance.py" line_range="308" />
<code_context>
+        "path": value.path,
+        "query": value.query,
+        "headers": _headers(value.headers, excluded),
+        "payload": value.payload,
+    }
+
</code_context>
<issue_to_address>
**Payload values remain guessable**

When a request payload contains low-entropy personal or sensitive values and someone with access to provenance records can test likely values, `_snapshot` hashes the entire payload, so stored before/after hashes let anyone with the provenance record test guesses for predictable fields such as usernames or claims; `secret_headers` cannot exclude payload fields, exposing data despite the record containing no plaintext values.

Add configurable payload-field redaction or use a keyed hash for payload content so stored records do not enable offline guessing.
</issue_to_address>

### Comment 3
<location path="foca/plugins/records.py" line_range="168" />
<code_context>
+            "started_at": self.started_at,
+            "duration_ms": self.duration_ms,
+            "attempt": self.attempt,
+            "error": self.error,
+            "annotations": self.annotations,
+            "changes": self.changes,
</code_context>
<issue_to_address>
**Exception secrets appear in records**

When a plugin or validation exception contains a token or other secret, `sanitize_error()` strips URL user-info but retains other message content, and `Execution.describe()` stores that message in provenance, where record readers can see the secret.

Redact secrets from exception messages before `Execution.describe()` stores them.
</issue_to_address>

### Comment 4
<location path="foca/plugins/engine.py" line_range="918" />
<code_context>
+            "plugins": {builds[plugin]: plugin for plugin in sorted(ran)},
+            "executions": [execution.describe(builds) for execution in self.executions],
+            "route": {
+                "candidates_in": self.candidates_in,
+                "candidates_out": self.candidates_out,
+            },
</code_context>
<issue_to_address>
**Sensitive URL details are persisted**

When a backend identifier, attempt, or client selection contains an IP address or sensitive URL components, `PipelineRun.provenance()` copies these values into the record, exposing IP addresses, URL user-info, or query tokens despite the privacy claim.

Redact IP-address hosts, URL user-info, and query parameters before copying URL-bearing values into provenance.

Also at `foca/plugins/engine.py:923-925`, `foca/plugins/engine.py:933`.
</issue_to_address>

### Comment 5
<location path="foca/plugins/provenance.py" line_range="257" />
<code_context>
+    """
+    if isinstance(before, Mapping) and isinstance(after, Mapping):
+        for key in sorted({*before, *after}, key=str):
+            child = _pointer(prefix, key)
+            if len(child) > MAX_POINTER_LENGTH:
+                if before != after:
</code_context>
<issue_to_address>
**Sensitive map keys appear in paths**

When a changed object is keyed by a personal or otherwise sensitive identifier, `_changed()` copies the key into a JSON Pointer, and `changed_paths()` stores that path in provenance, exposing the identifier to record readers.

Redact or replace sensitive object keys before emitting changed paths.

Also at `foca/plugins/provenance.py:353-357`, `foca/plugins/engine.py:1368-1369`.
</issue_to_address>

### Comment 6
<location path="foca/plugins/engine.py" line_range="1123" />
<code_context>
+                self.final_reason = "outcome_unknown"
             if attempt.state != "not_accepted":
                 return
+        self.final_reason = "no_backend"
         raise NoBackendAvailable("No backend accepted the request", run=self)

</code_context>
<issue_to_address>
**Expired attempts report no backend**

When the final candidate reports non-acceptance after the forwarding deadline, `attempts()` checks the deadline only before each candidate, then sets `final_reason` to `no_backend` and raises `NoBackendAvailable` instead of reporting `ForwardTimeout` and `forward_timeout`.

Check the forwarding deadline after the final failed attempt before setting `no_backend`.
</issue_to_address>

### Comment 7
<location path="foca/plugins/engine.py" line_range="911-913" />
<code_context>
+                    if self.selection.pipeline is not None
+                    else None
+                ),
+                "resolved": resolved,
+                "resolved_hash": resolved_hash,
+                **({} if resolved_hash else {"error": "not_json"}),
+            },
+            "plugins": {builds[plugin]: plugin for plugin in sorted(ran)},
</code_context>
<issue_to_address>
**Unsupported integers break task writes**

When an admin-configured plugin parameter contains an integer outside BSON's supported range, `content_hash()` rejects the value, but `provenance()` leaves it in `resolved`, so MongoDB rejects the task provenance write after the backend accepts the request.

Replace or omit BSON-unrepresentable values from `resolved` when hashing fails.
</issue_to_address>

### Comment 8
<location path="foca/plugins/engine.py" line_range="911-916" />
<code_context>
+                    if self.selection.pipeline is not None
+                    else None
+                ),
+                "resolved": resolved,
+                "resolved_hash": resolved_hash,
+                **({} if resolved_hash else {"error": "not_json"}),
+            },
+            "plugins": {builds[plugin]: plugin for plugin in sorted(ran)},
+            "executions": [execution.describe(builds) for execution in self.executions],
+            "route": {
+                "candidates_in": self.candidates_in,
</code_context>
<issue_to_address>
**Large provenance records cannot be stored**

When a configured pipeline, execution history, or backend list grows large enough to exceed MongoDB's document-size limit, `provenance()` has no overall record-size cap, so the full resolved pipeline and execution or route data exceed the BSON limit and the task's provenance write fails.

Enforce an overall BSON-safe size limit on provenance records, including resolved pipeline and execution or route data.

Also at `foca/plugins/engine.py:918`, `foca/plugins/engine.py:930`.
</issue_to_address>

### Comment 9
<location path="foca/plugins/provenance.py" line_range="565-567" />
<code_context>
+        collection: Collection.
+        document: Document with `_id`.
+    """
+    collection.update_one(
+        {"_id": document["_id"]}, {"$setOnInsert": document}, upsert=True
+    )
</code_context>
<issue_to_address>
**Slow storage delays responses**

When the app calls `save()` or `save_failure()` while its configured collections are slow or unreachable, `ProvenanceStore.save()` performs collection writes synchronously, and `save_failure()` can perform another write; a slow or unreachable database holds the calling request or task until the collection driver's timeout expires, delaying the caller even though write errors are eventually caught.

Use bounded collection-operation timeouts (or move these writes off the request path) so storage outages cannot consume the request's latency budget.

Also at `foca/plugins/provenance.py:551`.
</issue_to_address>

### Comment 10
<location path="foca/plugins/provenance.py" line_range="521-523" />
<code_context>
+                    },
+                )
+                del pipeline["resolved"]
+        except Exception as exc:
+            logger.warning("Provenance not stored: %s", type(exc).__name__)
+            record["stored"] = False
+        return record
+
</code_context>
<issue_to_address>
**Failed audits lose build details**

When a plugin-build write fails while the failures collection remains writable, `save()` stops writing shared build documents at the first collection error and marks the record `stored: false`, but `save_failure()` still inserts it. The failure audit can therefore contain plugin build keys whose build documents were never stored, leaving those executions without resolvable version and digest details.

Avoid storing a failure record with unresolved build references, or include the missing build metadata inline when shared writes fail.

Also at `foca/plugins/provenance.py:551`.
</issue_to_address>

### Comment 11
<location path="foca/plugins/provenance.py" line_range="551" />
<code_context>
+            "slug": getattr(error, "slug", None),
+        }
+        try:
+            self.failures.insert_one(record)
+        except Exception as exc:
+            logger.warning("Failure record not stored: %s", type(exc).__name__)
</code_context>
<issue_to_address>
**Retries duplicate failure records**

When the caller retries `save_failure()` for the same run, `insert_one()` assigns a fresh document ID on each call, so the retry creates another audit record and counts the same failure more than once.

Use a stable identifier or unique request key so repeated saves of the same failure are idempotent.
</issue_to_address>

### Comment 12
<location path="foca/plugins/provenance.py" line_range="272" />
<code_context>
+            yield prefix
+            return
+        for index, (old, new) in enumerate(zip(before, after, strict=True)):
+            yield from _changed(old, new, _pointer(prefix, index))
+        return
+    if type(before) is not type(after) or before != after:
</code_context>
<issue_to_address>
**Nested arrays exceed pointer limit**

When a changed value is nested deeply enough in arrays for its pointer to exceed 512 characters, `_changed` appends array indexes without checking the resulting pointer length. A changed value nested in sufficiently many arrays is therefore recorded with a path longer than 512 characters, violating the documented bound and consuming the run’s path-size budget with an oversized pointer.

Apply the pointer-length check to array child paths and report the parent when the limit is exceeded.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 12 findings to address first, and an OutcomeUnknown attempt now ends the loop without raising, so callers that relied on the exception may continue or retry even though a backend could already have accepted the task, causing an irreversible duplicate. Reverting restores the prior control flow, but cannot undo a task already accepted twice.

Blocking findings: foca/plugins/provenance.py:297, foca/plugins/provenance.py:308, foca/plugins/records.py:168, foca/plugins/engine.py:918, foca/plugins/provenance.py:257, and 7 more


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

Comment thread foca/plugins/provenance.py Resolved
Comment thread foca/plugins/provenance.py Resolved
Comment thread foca/plugins/records.py Resolved
Comment thread foca/plugins/engine.py Resolved
Comment thread foca/plugins/provenance.py Resolved
Comment thread foca/plugins/engine.py Resolved
Comment thread foca/plugins/provenance.py Resolved
Comment thread foca/plugins/provenance.py Resolved
Comment thread foca/plugins/provenance.py Resolved
Comment thread foca/plugins/provenance.py Resolved
Address the Sourcery review of PR #499:

- Records keep only the type of errors of plugins and other code, as
  their messages may hold secrets; logs get the message
  (describe_error). FOCA's gateway errors, rejections and its own
  timeout and invalid-output texts keep their message.
- Set-Cookie of responses is left out of hashes; hashes of changes
  are keyed (HMAC-SHA256, random key per process), content hashes of
  pipelines and builds stay plain RFC 8785 SHA-256.
- Backend URLs in records lose user info, query and fragment.
- A budget that runs out during the last attempt gives
  forward_timeout, not no_backend.
- Pipelines that are no I-JSON are recorded without resolved.
- Records are cut to 1 MiB of JSON (changed paths, then annotations,
  then the resolved pipeline; truncated: true).
- If storing builds fails, the record keeps their documents inline.
- save_failure() is idempotent: _id is the request ID, else the
  run's random run_id, written with replace_one(upsert=True).
- The pointer length cap applies to array items too.
- Docs: map keys in changed paths, MongoDB client timeouts.

Refs #488

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Compare the URL fields of the record exactly instead of testing for
URL substrings in its JSON text (CodeQL: incomplete URL substring
sanitization).

Refs #488

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 176eb0e into dev Oct 25, 2026
30 checks passed
@uniqueg
uniqueg deleted the feat/plugin-provenance branch October 25, 2026 05:47
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): record provenance

2 participants