Repository navigation
feat(http): let guarded clients trust other CAs - #792
Conversation
Add a ca_bundle option to GuardedClient: a file or directory of certificate authorities that TLS certificates are verified with instead of the public ones (e.g., for backends behind a private CA). Values that would turn verification off or leave it to requests (False, True, empty paths, bytes) are refused, and the option is read-only. A bundle that doesn't exist or holds no certificate fails requests before sending (RequestNotSent, tls_error). Closes #790 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Map the OSError that requests raises for a missing CA bundle in the guarded adapter's cert_verify() (https only) instead of checking the path before each request and labelling any plain OSError a TLS error. Keep CA bundles as absolute paths, and test that a falsy bundle set behind the property still verifies. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideAPIAdd the public
ImplementationMake the guarded adapter translate CA-bundle loading errors into
DocumentationExplain private CA bundle configuration, its trust behavior and limitations, and which other HTTP paths still use public CAs only.
TestsAdd local TLS tests for CA files and hashed directories, trust isolation, bundle failures, validation, immutability, and absolute-path handling.
Check that fake HTTP clients retain their CA bundle without exposing it as a plugin default.
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 #792 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 75 75
Lines 10025 10048 +23
=========================================
+ Hits 10025 10048 +23
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:
|
Linked issuesChecked at commit 77930fb #790 feat: let the guarded HTTP client trust other CAs · 3 of 3 met
|
There was a problem hiding this comment.
Hey - I've found 2 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/utils/http.py" line_range="921" />
<code_context>
allow_private_addresses: bool = False,
allow_http: bool = False,
max_response_size: int = MAX_RESPONSE_SIZE,
+ ca_bundle: str | os.PathLike[str] | None = None,
) -> None:
"""Create the client.
</code_context>
<issue_to_address>
**Clones lose custom CA bundle**
When a FakeHttp configured with ca_bundle is cloned without a ca_bundle override, fakeHttp.client() rebuilds the child from self.options(), which omits ca_bundle, so the child reports None instead of retaining the configured path.
Include ca_bundle in FakeHttp.options() so cloned clients retain the configured bundle.
</issue_to_address>
### Comment 2
<location path="tests/utils/test_http_tls.py" line_range="374" />
<code_context>
+ http = GuardedClient(allow_private_addresses=True, timeout=5, ca_bundle=other)
+ with pytest.raises(RequestNotSent) as info:
+ http.post(serve(_handshake_only(certificate)), json={})
+ assert info.value.reason == "tls_error"
+
+
</code_context>
<issue_to_address>
**Malformed bundles pass unnoticed**
When the client ignores the malformed custom bundle and falls back to default CAs, `test_ca_bundle_invalid` checks only `tls_error`; its server certificate is untrusted by the default CAs, so ignoring the malformed bundle and falling back to default verification still produces that error and lets the test pass.
Use the `trusted` fixture in this test so fallback to default CAs accepts the server certificate and the test distinguishes that from rejecting the malformed bundle.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 1 finding to address first, and a configured CA bundle replaces the public trust roots for that client, so a malicious or mistakenly trusted CA could validate a server certificate and expose request data or credentials. Reverting removes the custom trust option, but any data already exposed cannot be recovered.
Blocking findings: tests/utils/test_http_tls.py:374
FakeHttp.client() now passes the CA bundle on to the clients it makes (not via options(), which feed plugins.defaults.http). The tests of missing and invalid bundles trust the server by default, so that a fallback to the default CAs would fail them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
GuardedClientgets aca_bundleoption: a file (PEM) or directory (hashed names, as byopenssl rehash) of certificate authorities that TLS certificates are verified with instead of the public ones (certifi), e.g., for backends behind a private CA. Verification can never be switched off:ca_bundleaccepts onlyNone,stroros.PathLike[str];False,True,0, bytes and empty paths are refused (TypeError/ValueError), because requests would take an empty path as "don't verify".request()passesverify=self._ca_bundle or True, so even a falsy value set behind the property keeps verification on (tested).RequestNotSent(tls_error): the guarded adapter'scert_verify()maps the plainOSErrorof requests (https only, at the point of use, so no race with a pre-check). A bundle without certificates fails the handshake (RequestNotSent,tls_error).ca_certs/ca_cert_dir; tested with a server whose CA is trusted by default but not in the bundle).foca.plugins.testing.FakeHttp.client()keeps the CA bundle of its parent (Sourcery review).Docs: "Sending requests to untrusted URLs" in
docs/utilities.md.Not in this PR (the issue marks it optional):
fetch_json()and the registry reads of backend lists. Addingca_bundletofetch_json()breaks mypy infoca/plugins/backends/registry.py(it passes**dict[str, bool]), and that package is being changed for #789 in parallel; a follow-up issue is drafted (fetch_json()+ a registry entry option together). The docs say thatfetch_json(), registry reads andctx.httpuse the public CAs only, for now.proWES can then drop its
_GuardedHttpwrapper (follow-up issue drafted for prowes).Verification
pytest tests/utils/test_http.py tests/utils/test_http_tls.py: 112 passed;coverage report --include=foca/utils/http.py: 100%.openssl x509 -hash), bundle-only trust, missing bundle, missing default bundle, bundle without certificates, refused values, read-only property, falsy value behind the property, relative path.ruff check,ruff format --check,mypy(187 files): clean.ast-grep scan --error=flask-import: clean.semgrep scan --config .semgrep --error: 0 findings.mkdocs build --strict: OK.Declined review findings
opensslCLI (skips if missing): kept; computing OpenSSL's subject hash in pure Python would reimplement OpenSSL's canonical-name hashing, and the CLI is on CI runners and dev machines.OSErrorof requests'cert_verify(): kept; in requests 2.33+ that method raisesOSErroronly for a missing bundle (round-2 adversarial review confirmed no other plainOSErrorpath).test_default_bundle_missingpatchesrequests.adapters.DEFAULT_CA_BUNDLE_PATH: kept; the existingtrustedfixture already relies on it, and anhttprequest skipping the bundle check was verified by the adversarial reviewer (requests callscert_verify()for every URL but checks onlyhttps).adversarial-reviewer+quality-reviewer; round 2: no high/medium findings.Open questions
None.
Closes #790
🤖 Generated with Claude Code