Skip to content

feat(plugins): key store hashes with a secret - #589

Merged
uniqueg merged 10 commits into
devfrom
feat/565-store-key-secret
Nov 2, 2026
Merged

uniqueg merged 10 commits into
devfrom
feat/565-store-key-secret

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

Summary

Implements the maintainer's decision in #565 (optional HMAC secret):

  • New setting plugins.defaults.store.key_secret (SecretStr; applies to all plugins); if unset or empty, the environment variable FOCA_PLUGINS_STORE_KEY_SECRET is used, so it can come from an env var or a mounted secret and is never committed.
  • With a secret, key_for() returns HMAC-SHA256 keys prefixed hk:; without, plain SHA-256 h: as before.
  • Without a secret, a warning is logged once at startup if plugins keep store entries in the database.
  • The secret is not in repr() of config or store settings, logs, dumps, the plugin listing or validation error messages: the top-level Config and the plugin config models now set hide_input_in_errors, so config validation errors no longer show input_value (noted in the migration guide).
  • Helm library chart foca-common 0.4.0: new value plugins.existingSecret, the name of an existing Secret whose key store-key-secret the app and the worker get as FOCA_PLUGINS_STORE_KEY_SECRET (same pattern as broker.existingSecret: fixed kebab-case key, no value inlined). Rendering fails if the config overlay (a ConfigMap) sets a non-empty config.plugins.defaults.store.key_secret; the error never shows the value. Schema (library and petstore copy), petstore values, dependency and Chart.lock updated. The chart version is bumped in this PR because CI requires it for every chart change since chart-v0.3.0 (as feat(chart): add app replicas and a PDB #585 did for 0.3.0); no tag.
  • Docs: configuration reference (secret handling, rotation, replicas, the new environment variable in the variables table), plugin author guide, Helm chart guide (values table, deployment note), deployment guide, 0.20.0 migration guide.

Closes #565

Verification

  • coverage run -m pytest (full suite, local MongoDB 7.0 on port 12345): 3293 passed, 1 skipped; coverage 100% (rerun after every fix)
  • pytest charts/foca-common/tests with Helm 3.22.1 (CI's version): 248 passed; snapshots unchanged
  • helm lint --strict of the library chart and the petstore chart with all ci/*-values.yaml: clean
  • ruff check, ruff format --check, mypy, ast-grep scan / ast-grep test, semgrep scan --config .semgrep / semgrep --test, mkdocs build --strict: clean
  • Not run locally: integration tests and the kind chart install (CI)
  • CI on 683b9e6: all checks passed (also the Sourcery review check) ; CI passed, CodeQL, PR title, Chart, Chart install, tests, integration tests, image scans, Codecov, Read the Docs

Review

Regular lane, two rounds.

  • Round 1, adversarial: medium, secret could leak via pydantic's input_value in config validation errors (model-level check failing elsewhere in plugins): fixed with hide_input_in_errors plus regression test. Low, blank plugins.existingSecret: declined (below).
  • Round 1, quality: lows only; fixed: test helper docstring, more refused overlay values (bool, 0, map, list), comment why the helper doesn't use dig, rewrapped docs.
  • Round 2, adversarial: no high/medium; low (setting applies only to the outermost model; errors()/json() still carry input): documented in the _Model docstring.
  • CI round 1: CodeQL flagged the startup warning (it interpolated the constant naming the environment variable) as clear-text logging of a secret, a false positive; the name is now literal text, and the test pins it to the constant. PR title shortened to 50 characters or less.
  • Sourcery (low): the key secret warning also fired for plugins that declare no stored data; fixed (only data_stored plugins count, as for the memory warning), with test and docs. Small logic fix after the two reviewer rounds (the maximum), covered by the tests.
  • Earlier (before the chart work): adversarial 2 lows (empty secret: fixed; numeric secrets: documented).

Declined review findings

  • Numeric secrets are still converted to strings rather than rejected, so that an unquoted number does not leak into a validation error; documented.
  • A whitespace-only plugins.existingSecret renders and is rejected by the API server at apply time: same behaviour as broker.existingSecret and mongodb.auth.existingSecret; kept consistent rather than special-casing one value.
  • ValidationError.errors()/.json() still contain the raw input (pydantic keeps it there regardless of hide_input_in_errors); FOCA never logs or serialises them for config errors. Documented in the _Model docstring.
  • Refactoring the secret resolution in engine.py into a helper: readability only, behaviour covered by tests.
  • Setting plugins.existingSecret in ci/gateway-values.yaml: the kind install would need an extra Secret; template tests cover the rendering.

Open questions

None.

🤖 Generated with Claude Code

https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG

uniqueg and others added 2 commits November 1, 2026 18:24
Add the optional setting plugins.defaults.store.key_secret, with the
environment variable FOCA_PLUGINS_STORE_KEY_SECRET as fallback. With a
secret, Store.key_for() returns HMAC-SHA256 keys prefixed hk:, which
never collide with the plain SHA-256 keys (h:). Without one, keys stay
plain and the plugin host logs a warning at startup if plugins keep
their entries in the database.

The secret is a SecretStr and not part of the repr of the store
settings. Changing it makes earlier entries unreachable until they
expire; documented in the configuration reference, the plugin author
guide and the 0.20.0 migration guide.

The Helm library chart value is left to a separate change.

Refs #565

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.20.0 milestone Nov 1, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces optional HMAC-SHA256 keying for database-backed plugin store entries, securely resolves and hides the secret, warns when unkeyed persistence remains, and provisions the secret through Helm while documenting migration and rotation behavior.

Sequence diagram for resolving the plugin store key secret

sequenceDiagram
    participant Config
    participant Engine
    participant Env as Environment
    participant StoreSettings
    Config->>Engine: _store_settings()
    Engine->>Config: read key_secret
    alt configured key_secret is non-empty
        Engine->>StoreSettings: set key_secret bytes
    else key_secret unset or empty
        Engine->>Env: read FOCA_PLUGINS_STORE_KEY_SECRET
        Env-->>Engine: secret or empty
        Engine->>StoreSettings: set key_secret bytes
    end
Loading

Sequence diagram for deriving keyed plugin store keys

sequenceDiagram
    participant Plugin
    participant Store
    participant StoreSettings
    Plugin->>Store: key_for(parts)
    Store->>StoreSettings: read key_secret
    alt secret configured
        Store-->>Plugin: hk: HMAC-SHA256(message)
    else no secret
        Store-->>Plugin: h: SHA-256(message)
    end
Loading

Flow diagram for protecting the plugin store secret in Helm

flowchart TD
    Overlay[Config overlay ConfigMap]
    Check{key_secret is empty or unset?}
    Render[Render deployment and ConfigMap]
    Fail[Fail rendering without showing the secret]
    Overlay --> Check
    Check -->|yes| Render
    Check -->|no| Fail
Loading

File-Level Changes

Change Details Files
Add optional secret-backed key derivation for plugin store entries, with environment fallback and startup safeguards.
  • Add SecretStr configuration with numeric normalization and environment-variable precedence.
  • Generate hk: HMAC-SHA256 keys when configured while preserving h: SHA-256 behavior otherwise.
  • Propagate secrets into store settings without exposing them in representations, dumps, or validation messages.
  • Warn once for database-backed stores operating without a secret.
foca/plugins/config.py
foca/plugins/engine.py
foca/plugins/store.py
foca/models/config.py
tests/plugins/test_plugin_store.py
Integrate plugin store secrets into the Helm library chart without placing secret values in ConfigMaps.
  • Add plugins.existingSecret schema and inject the referenced store-key-secret into app and worker pods.
  • Reject non-empty overlay values for config.plugins.defaults.store.key_secret without echoing the value.
  • Update chart version, dependency lockfiles, petstore defaults, and comprehensive rendering tests.
charts/foca-common/Chart.yaml
charts/foca-common/app-values.schema.json
charts/foca-common/templates/_deployment.tpl
charts/foca-common/templates/_helpers.tpl
charts/foca-common/templates/_worker.tpl
charts/foca-common/tests/test_templates.py
examples/petstore/chart/Chart.yaml
examples/petstore/chart/Chart.lock
examples/petstore/chart/values.schema.json
examples/petstore/chart/values.yaml
Document secret configuration, operational impact, rotation behavior, and deployment integration.
  • Document the environment variable and secret-handling guarantees.
  • Explain key changes, replica consistency, rotation, and migration effects.
  • Update plugin author, deployment, Helm, and 0.20.0 migration guidance.
docs/configuration/index.md
docs/configuration/plugins.md
docs/deployment.md
docs/helm-chart.md
docs/migration-0.20.md
docs/plugins.md

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Comment thread foca/plugins/engine.py Fixed
@codecov

codecov Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (5a9abdb) to head (683b9e6).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #589   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           56        56           
  Lines         7068      7090   +22     
=========================================
+ Hits          7068      7090   +22     
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 and others added 7 commits November 2, 2026 07:13
Add the value plugins.existingSecret to foca-common: the name of an
existing Secret whose key store-key-secret the app and the worker get
as FOCA_PLUGINS_STORE_KEY_SECRET. Rendering fails if the config
overlay, a ConfigMap, sets plugins.defaults.store.key_secret. Bump the
chart to 0.4.0 and the petstore example's dependency.

Closes #565

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Describe plugins.existingSecret in the chart's deployment notes and
values, the configuration reference (also the environment variable),
the deployment guide and the migration guide to 0.20.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Pydantic showed the raw input of a failed check (input_value), which
could contain plugins.defaults.store.key_secret before it is masked,
e.g., when another plugin setting is invalid. Hide the input in
validation errors of the configuration (Config, whose setting applies
to nested models, and the plugin models validated on their own).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Also refuse booleans, zero, maps and lists in the overlay's key
secret in the tests, and explain the helper's walk of the overlay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
CodeQL flagged the startup warning as clear-text logging of a secret,
as it interpolated the constant with the variable's name. Write the
name into the message instead; the test checks it matches the
constant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
@uniqueg uniqueg changed the title feat(plugins): key plugin store hashes with a secret feat(plugins): key store hashes with a secret Nov 2, 2026
@uniqueg
uniqueg marked this pull request as ready for review November 2, 2026 07:18

@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 1 issue

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

## Individual Comments

### Comment 1
<location path="foca/plugins/engine.py" line_range="676-680" />
<code_context>
+            `False` only if some plugin keeps its entries in the database
+            (mode `shared`) and the operator set no key secret.
+        """
+        return all(
+            settings.key_secret
+            for settings in self._stores.values()
+            if settings.mode == "shared"
+        )
+
     def setup_store(self) -> None:
</code_context>
<issue_to_address>
**Unused stores trigger warning**

When a gateway loads a plugin with no declared `data_stored` whose store is enabled and the database backend is shared, `_key_secret_set()` checks only whether a plugin's store is in shared mode, so a loaded plugin that declares no stored data still triggers the startup warning even though it does not keep entries in the database; operators see a misleading warning to configure a secret.

Apply the warning check only to shared stores of plugins that declare stored data.
</issue_to_address>

Linked issues

#565 feat(plugins): key plugin store hashes with a secret · 5 of 5 met

# Requirement Status Notes
1 Add the optional store key secret, HMAC keys with an hk: prefix, plain SHA-256 fallback, and a startup warning when database-backed entries have no secret. ✅ Met The secret resolves from configuration or the environment; the warning is emitted for shared stores without a secret.
2 Keep the secret out of logs, the plugin listing, and error messages. ✅ Met The secret uses SecretStr; configuration validation hides inputs, and the plugin listing exposes plugin metadata rather than admin settings.
3 Test both key modes, prefixes, the warning, and secret rotation. ✅ Met Tests cover key generation, warning conditions, and entries becoming unreachable across secret changes.
4 Document configuration, plugin-author use of key_for(), operator secret handling, rotation and replicas, and upgrade notes. ✅ Met The configuration reference, plugin author guide, deployment guide, and 0.20.0 migration guide cover these topics.
5 Add the Helm library chart secret reference and documentation. ✅ Met plugins.existingSecret passes the existing Secret to the app and worker; overlay secrets are rejected and the chart docs describe setup.

Sourcery assessment

Needs a human reviewer. With a configured secret, key_for() writes entries under HMAC-derived keys instead of the previous SHA-256 keys; inconsistent secrets or a faulty derivation can make stored entries unreachable and reset plugin state such as per-user budgets. The entries remain in the store and are bounded by max_ttl, so reverting or restoring the matching secret can recover access.


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

Comment thread foca/plugins/engine.py Resolved
Warn about a missing key secret only if plugins that declare stored
data (data_stored) keep it in the database, like the warning about
stores in memory (Sourcery review).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
@uniqueg
uniqueg merged commit 6022851 into dev Nov 2, 2026
80 checks passed
@uniqueg
uniqueg deleted the feat/565-store-key-secret branch November 2, 2026 07:45
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): key plugin store hashes with a secret

2 participants