Skip to content

feat(config)!: support secrets in config - #691

Merged
uniqueg merged 8 commits into
devfrom
feat/625-config-secrets
Nov 4, 2026
Merged

uniqueg merged 8 commits into
devfrom
feat/625-config-secrets

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Lets deployments keep secrets out of configuration files.

  • References: string values in config files can use ${VAR}, ${VAR:-default}, ${VAR:?message} and $$, as in the Compose specification, per file, after parsing the YAML and before merging. Errors name the key, not values.
  • _FILE variables: MONGO_URI, MONGO_USERNAME, MONGO_PASSWORD, CELERY_BROKER_URL and CELERY_RESULT_BACKEND can come from files, as with Docker's official images. Setting both forms, or a file that can't be read, is an error. The library chart reserves the _FILE forms of what it sets.
  • SecretStr: jobs.backend and the MongoDB client options authMechanismProperties and tlsCertificateKeyFilePassword. Custom config models are documented to do the same.
  • Clients: client of DBConfig and CollectionConfig is out of repr() and dumps of the config, as the repr of PyMongo clients has credentials.
  • Log of new MongoDB clients: only hosts and ports as the client understands them, and the database, instead of a redacted connection string (CodeQL alert 539, as the maintainer decided; not dismissed). Hosts show as unknown if the connection string has an @ after them, where an unescaped credential can pass for a host, and a MONGO_DBNAME with unusual characters isn't shown. _redact_uri() is removed, as nothing else used it.

Breaking, in the migration guide: ${ and $$ in config files now have a meaning, and jobs.backend must be read with .get_secret_value(). The log text change is there too. cloud-registry has no ${ in its config files, only in its Compose file.

Docs: configuration/index.md, custom.md, db.md, jobs.md, helm-chart.md, migration guide.

Closes #625

How it was verified

  • Local checks on the final code: ruff, mypy, ast-grep, semgrep, mkdocs build --strict; pytest with own MongoDB 7.0: 100% coverage, one failure of test_no_personal_email_addresses on a test value, which was fixed and that file rerun with the two test files of this change (189 passed), not the whole suite; chart tests with Helm 3.22.1: 437 passed.
  • The log tests use real PyMongo clients with connect=False, for credentials and options in MONGO_URI, MONGO_URI_FILE, MONGO_HOST, MONGO_PORT, MONGO_DBNAME and the configured host.
  • Both reviewers, two rounds on the log fix. Round 1 found a leak of option values from parsing the connection string, which led to reading hosts from the client; round 2 found fragments of unescaped passwords taken for hosts, which led to unknown. The changes after round 2 had no further review round, as the limit is two.
  • CI: see the checks of this PR.

Not verified locally: the integration tests of the examples, which need containers; CI runs them. CodeQL isn't installed locally; its run on this PR decides on the alert.

Declined review findings

  • exceptions.mapping echoes its value in validation errors: secrets don't belong there.
  • from None leaves the decoding error on __context__, reachable only by code that ignores suppression.
  • Sourcery: an empty X next to X_FILE conflicts: empty counts as not set, as in Docker's official images and for Compose's ${X:-}.
  • Sourcery: release note entry: the repo has no notes file; notes are written at release time.
  • Reviewer: derive the log text from the connection string already built, to avoid a second read: this is what leaked and what CodeQL flagged. The fix no longer reads anything twice.
  • Reviewer: a password with an unescaped , and no @ (e.g., MONGO_HOST=u:12,part) still shows its parts as hosts: it can't be told apart from a list of hosts, and PyMongo connects there. The docstring and the migration guide state this limit.
  • Reviewer: PyMongo's own exceptions and warnings for malformed connection strings can quote parts of them (e.g., InvalidURI: Bad database name), which end up in a traceback at startup: not the log line of this change, and not new. Replacing them would hide what's wrong with options too, so that's a decision of its own.
  • Reviewer: ids= and a split of the parametrized log test: comments group its rows.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Enable secure secret injection and handling across configuration files, environment variables, database and job settings, and deployment charts.

New Features:

  • Support Compose-style environment variable references in YAML configuration values, including defaults, required variables, and escaped dollar signs.
  • Allow supported MongoDB and Celery credentials to be supplied through Docker-compatible _FILE environment variables.
  • Protect configured secrets and credential-bearing clients from representations and serialized configuration output.

Enhancements:

  • Update the Helm chart to reserve secret _FILE environment variables and expand configuration and migration documentation for secret handling.

Documentation:

  • Document environment variable interpolation, file-backed secrets, SecretStr usage, and the associated migration requirements.

Tests:

  • Add comprehensive coverage for interpolation, file-backed environment variables, secret masking, client options, and affected integrations.

uniqueg and others added 3 commits November 4, 2026 11:29
String values of config files can reference environment variables, as
${VAR}, ${VAR:-default} and ${VAR:?message}, with $$ for a literal $,
per file before merging. MONGO_* and CELERY_* variables can come from
files through <NAME>_FILE, as with Docker's official images.

BREAKING CHANGE: `${` and `$$` in config files now have a meaning, and
`jobs.backend` and the MongoDB client options that hold secrets are of
type SecretStr, to be read with `.get_secret_value()`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The gateway example reads the result backend as a SecretStr, and takes
its broker settings as the worker does. Clients are not in reprs and
dumps of the configuration any more, as their repr has credentials.
Secret files are read as bytes, so that line breaks within them stay,
and decoding errors don't chain a byte of the content. The chart
reserves the _FILE forms of what it sets. Docs say where values can come
from in the pages on the database and on jobs.

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

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR introduces secure secret injection across configuration, MongoDB, Celery, and Helm by interpolating environment references per config file, supporting Docker-style _FILE variables, and masking sensitive values and clients through SecretStr and excluded representations/dumps; documentation and migration guidance are updated accordingly.

Sequence diagram for configuration environment interpolation

sequenceDiagram
    participant ConfigParser
    participant YAML
    participant Environment
    ConfigParser->>YAML: parse(config_file)
    YAML-->>ConfigParser: content
    ConfigParser->>Environment: interpolate(content)
    Environment->>Environment: os.environ.get(name)
    Environment-->>ConfigParser: resolved content
    ConfigParser->>ConfigParser: deep_merge(content)
Loading

Sequence diagram for file-backed secret environment variables

sequenceDiagram
    participant Application
    participant get_env
    participant Environment
    participant SecretFile
    Application->>get_env: get_env(name, default)
    get_env->>Environment: os.environ.get(name)
    get_env->>Environment: os.environ.get(name_FILE)
    alt name_FILE is set
        get_env->>SecretFile: read_bytes(path)
        SecretFile-->>get_env: secret value
    else name is set
        Environment-->>get_env: environment value
    else neither is set
        get_env-->>Application: default
    end
    get_env-->>Application: resolved value
Loading

File-Level Changes

Change Details Files
Add Compose-style environment interpolation to configuration parsing.
  • Resolve supported ${...} and $$ forms recursively in string values after YAML parsing and before file merging.
  • Preserve string types, avoid interpolating keys and referenced external files, and report errors with file/key context without echoing values.
  • Cover defaults, required variables, invalid syntax, overlays, and validation behavior with tests.
foca/config/environment.py
foca/config/config_parser.py
tests/config/test_environment.py
docs/configuration/index.md
docs/migration-0.21.md
Support file-backed environment variables for credential-bearing MongoDB and Celery settings.
  • Add shared _FILE loading with final-newline trimming, conflict detection, readable-text validation, and safe errors.
  • Use file-aware lookup for Mongo URI, Mongo credentials, Celery broker URL, and Celery result backend.
  • Reserve the corresponding _FILE names in Helm chart extra environment validation and update chart tests/documentation.
foca/config/environment.py
foca/database/register_mongodb.py
foca/factories/celery_app.py
examples/gateway/controllers.py
charts/foca-common/templates/_helpers.tpl
charts/foca-common/tests/test_templates.py
foca/testing/pytest_plugin.py
docs/configuration/index.md
docs/configuration/db.md
docs/configuration/jobs.md
docs/helm-chart.md
tests/config/test_environment.py
Mask secrets and credential-bearing clients in configuration representations and serialized output.
  • Change jobs.backend to SecretStr and unwrap it only at Celery client construction.
  • Convert sensitive Mongo client options to SecretStr and unwrap them only when creating PyMongo options.
  • Exclude DB and collection clients from reprs and config dumps because their representations can contain credentials.
  • Document the custom-model SecretStr convention and migration impact, with coverage for masking and unwrapping.
foca/models/config.py
foca/database/register_mongodb.py
foca/factories/celery_app.py
docs/configuration/custom.md
docs/configuration/index.md
docs/configuration/jobs.md
docs/configuration/db.md
docs/migration-0.21.md
tests/config/test_environment.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

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

Customizing Your Experience

Access your dashboard to:

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

Getting Help

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (8e23b72) to head (1ce864a).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #691   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           65        66    +1     
  Lines         8523      8588   +65     
=========================================
+ Hits          8523      8588   +65     
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 November 4, 2026 11:33

@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 security issue, and 3 other issues

Security issues:

  • Detected a MongoDB connection string with embedded credentials, potentially exposing direct database access and sensitive application data. (link)
Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/database/register_mongodb.py" line_range="350" />
<code_context>
         # An unset password is passed as 'None', as in previous versions;
         # PyMongo refuses to create clients with a username but no password
-        password = str(os.environ.get("MONGO_PASSWORD"))
+        password = str(get_env("MONGO_PASSWORD"))
         auth = f"{quote_plus(user)}:{quote_plus(password)}@"
     host = os.environ.get("MONGO_HOST", host)
</code_context>
<issue_to_address>
**Conflicting password sources are ignored**

When `MONGO_USERNAME` is unset or empty while `MONGO_PASSWORD` and `MONGO_PASSWORD_FILE` are both set, or the configured password file is unreadable, `get_mongo_uri` calls `get_env("MONGO_PASSWORD")` only inside the non-empty-username branch, so it skips the both-sources check and file read, then builds a URI without credentials; startup can proceed without the intended MongoDB authentication.

Resolve the password source before the username branch so conflicting sources and unreadable files are reported even when the username is absent.
</issue_to_address>

### Comment 2
<location path="foca/config/environment.py" line_range="166" />
<code_context>
+    path = os.environ.get(file_name)
+    if not path:
+        return default if value is None else value
+    if value:
+        raise ValueError(
+            f"Environment variables '{name}' and '{file_name}' must not both be set"
</code_context>
<issue_to_address>
**Empty variable conflict**

The implementation checks whether `value` is truthy, so an empty `X` alongside a set `X_FILE` reads the file instead of raising. The issue requires an error whenever both variables are set.
</issue_to_address>

### Comment 3
<location path="docs/migration-0.21.md" line_range="66" />
<code_context>
 `datetime.isoformat()`. Check what your specifications declare and what your clients
 send. Other formats are checked as before.

+### References to environment variables in configuration files
+
+String values in configuration files now [reference environment
</code_context>
<issue_to_address>
**Missing release notes**

The migration guide documents the breaking changes, but no release-note entry is added. The issue asks for the breaking changes to be documented in both places.
</issue_to_address>

### Comment 4
<location path="tests/config/test_environment.py" line_range="302" />
<code_context>
mongodb://alice:pass+word@db:1/
</code_context>
<issue_to_address>
**security (mongodb-connection-string):** Detected a MongoDB connection string with embedded credentials, potentially exposing direct database access and sensitive application data.

*Source: betterleaks*
</issue_to_address>

Linked issues

#625 feat(config)!: support secrets in config · 5 of 7 met

# Requirement Status Notes
1 Interpolate supported environment references in YAML string values before merging, without changing keys. ✅ Met ConfigParser calls interpolate on each parsed file before merging; the implementation and tests cover the requested forms, keys remaining unchanged, and errors naming the key.
2 Support the specified *_FILE variables, strip the final newline, and error if both forms are set or the file cannot be read. 🟡 Partly met The variables can be read from files, with the final line break removed and unreadable files rejected, but an empty X plus a set X_FILE is treated as unset rather than an error.
3 Use SecretStr for FOCA secret-bearing fields and recommend it for custom config models. ✅ Met jobs.backend and the named MongoDB client options are wrapped in SecretStr, and the custom configuration docs recommend SecretStr.
4 Prevent secret values from appearing in representations and configuration dumps. ✅ Met SecretStr masks the secret fields, and DBConfig and CollectionConfig exclude their credential-bearing clients from reprs and dumps.
5 Add tests for interpolation, overlays, *_FILE behavior, and SecretStr masking, with 100% coverage. ✅ Met The added tests cover the requested cases; the PR description reports 100% coverage.
6 Document the feature on the configuration page and in the migration guide. ✅ Met The configuration page describes environment references and file-based variables, and the migration guide documents the breaking changes.
7 Document the breaking changes in release notes and the migration guide. 🟡 Partly met The migration guide covers the breaking changes, but the diff adds no release-note entry.

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and if environment interpolation or file-based lookup supplies the wrong MongoDB or broker URL or credentials, the app could authenticate to an unintended service or disclose credentials while connecting. Reverting stops future use, but any access or credential exposure during the deployment cannot be undone.

Blocking findings: foca/database/register_mongodb.py:350, foca/config/environment.py:166, tests/config/test_environment.py:302


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

Comment thread foca/database/register_mongodb.py Resolved
Comment thread foca/config/environment.py Resolved
Comment thread docs/migration-0.21.md Resolved
Comment thread tests/config/test_environment.py Resolved
uniqueg and others added 4 commits November 4, 2026 12:51
Read MONGO_PASSWORD also if MONGO_USERNAME is unset, so that a password
set in both ways or an unreadable password file is an error rather than
a connection without credentials.

Log the result backend as read back from the Celery app. The value was
redacted before as well; CodeQL's check of clear-text logging can't see
that, as it follows the value from get_secret_value() to the logger.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reading the backend back from the app did not change the result of
CodeQL's check, so it had no reason to stay. The logged value is
redacted either way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Log hosts and ports as the client understands them and the name of the
configured database, instead of a redacted connection string, so that
no value built with credentials reaches the log (CodeQL alert 539). The
connection string is only checked for an `@` after the hosts, where an
unescaped credential can be taken for a host: hosts then show as
`unknown`, as do those of stand-ins for clients in tests. Names of
databases with unusual characters aren't shown either.

Remove _redact_uri(), which nothing else used. Build connection strings
with credentials from parts in tests, as Sourcery's secret scan blocks
on literal ones even if they are made up and their thread is resolved.
Name the changes that apps must check in the migration guide's list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit d5df440 into dev Nov 4, 2026
61 of 83 checks passed
@uniqueg
uniqueg deleted the feat/625-config-secrets branch November 4, 2026 21:57
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(config)!: support secrets in config

1 participant