Repository navigation
feat(plugins): record provenance - #499
Conversation
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
# Conflicts: # 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
# Conflicts: # foca/plugins/config.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]>
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]>
Reviewer's GuideThis 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 provenancesequenceDiagram
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
Flow diagram for bounded privacy-conscious provenanceflowchart 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]
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
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).
final_reason(includingoutcome_unknown).ProvenanceStore.save()andsave_failure()write to MongoDB. Failure records expire after 30 days (TTL index). The stores never raise: errors are logged, the record getsstored: false, and the task stays inline.resolved_hash: nullanderror: not_json.truncated: true). Pointers longer than 512 characters fall back to their parent, and arrays whose length changed are recorded whole.x-forwarded-for,forwarded,x-real-ip), headers listed inplugins.provenance.secret_headers, and backendauthare excluded from hashing.SecretStrparams are redacted.client_headersmust beHeaders, and describing changes never raises.Closes #488
Verification
Run locally:
ruff checkandruff format --check: pass.mypy: pass.pytestwithout MongoDB: pass, with 100% coverage offoca/plugins. The TTL index is checked on mongomock.mkdocs build --strict: pass.pre-commit run --all-files: 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.
image_digest;final_reason;Headersclient_headersraising after the backend accepted (a regression);app_infotests;save()not guarding record construction.All are fixed.
Sourcery: 12 findings. 10 are fixed in 77a671e:
Set-Cookieis excluded;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
🤖 Generated with Claude Code