Repository navigation
feat(config)!: support secrets in config - #691
Conversation
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]>
# Conflicts: # foca/factories/celery_app.py
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]>
Reviewer's GuideThe PR introduces secure secret injection across configuration, MongoDB, Celery, and Helm by interpolating environment references per config file, supporting Docker-style Sequence diagram for configuration environment interpolationsequenceDiagram
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)
Sequence diagram for file-backed secret environment variablessequenceDiagram
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
File-Level Changes
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 #691 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 65 66 +1
Lines 8523 8588 +65
=========================================
+ Hits 8523 8588 +65
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:
|
# Conflicts: # foca/models/config.py
There was a problem hiding this comment.
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
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]>
Summary
Lets deployments keep secrets out of configuration files.
${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._FILEvariables:MONGO_URI,MONGO_USERNAME,MONGO_PASSWORD,CELERY_BROKER_URLandCELERY_RESULT_BACKENDcan 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_FILEforms of what it sets.SecretStr:jobs.backendand the MongoDB client optionsauthMechanismPropertiesandtlsCertificateKeyFilePassword. Custom config models are documented to do the same.clientofDBConfigandCollectionConfigis out ofrepr()and dumps of the config, as the repr of PyMongo clients has credentials.unknownif the connection string has an@after them, where an unescaped credential can pass for a host, and aMONGO_DBNAMEwith 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, andjobs.backendmust 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
mkdocs build --strict; pytest with own MongoDB 7.0: 100% coverage, one failure oftest_no_personal_email_addresseson 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.connect=False, for credentials and options inMONGO_URI,MONGO_URI_FILE,MONGO_HOST,MONGO_PORT,MONGO_DBNAMEand the configured host.unknown. The changes after round 2 had no further review round, as the limit is two.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.mappingechoes its value in validation errors: secrets don't belong there.from Noneleaves the decoding error on__context__, reachable only by code that ignores suppression.Xnext toX_FILEconflicts: empty counts as not set, as in Docker's official images and for Compose's${X:-}.,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.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.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:
_FILEenvironment variables.Enhancements:
_FILEenvironment variables and expand configuration and migration documentation for secret handling.Documentation:
Tests: