Skip to content

feat(http): let guarded clients trust other CAs - #792

Merged
uniqueg merged 3 commits into
devfrom
feat/790-ca-bundle
Nov 18, 2026
Merged

uniqueg merged 3 commits into
devfrom
feat/790-ca-bundle

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Summary

GuardedClient gets a ca_bundle option: a file (PEM) or directory (hashed names, as by openssl 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_bundle accepts only None, str or os.PathLike[str]; False, True, 0, bytes and empty paths are refused (TypeError / ValueError), because requests would take an empty path as "don't verify".
  • It is read-only (property) and stored as an absolute path; request() passes verify=self._ca_bundle or True, so even a falsy value set behind the property keeps verification on (tested).
  • A bundle that doesn't exist fails before sending with RequestNotSent (tls_error): the guarded adapter's cert_verify() maps the plain OSError of 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).
  • Only the bundle's CAs are trusted (urllib3 loads default certs only without 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. Adding ca_bundle to fetch_json() breaks mypy in foca/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 that fetch_json(), registry reads and ctx.http use the public CAs only, for now.

proWES can then drop its _GuardedHttp wrapper (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%.
  • New TLS tests (real local TLS server, own CAs): CA file, CA directory (hashed with 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.
  • Full test suite: not completed locally (it needs MongoDB on port 12345, which the shared machine reserves for other work); CI ran it: all checks passed on cc2ba22 and again after the Sourcery fixes (77930fb) (tests on Python 3.11 to 3.15, MongoDB 7.0/8.0, lowest dependencies, integration, lint, chart install, image scans, codecov patch and project, Read the Docs).

Declined review findings

  • Directory test shells out to the openssl CLI (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.
  • Error message names the CA bundle path: kept; it's operator configuration, not a secret, and helps diagnosis.
  • "CA bundle not found" is used for any OSError of requests' cert_verify(): kept; in requests 2.33+ that method raises OSError only for a missing bundle (round-2 adversarial review confirmed no other plain OSError path).
  • test_default_bundle_missing patches requests.adapters.DEFAULT_CA_BUNDLE_PATH: kept; the existing trusted fixture already relies on it, and an http request skipping the bundle check was verified by the adversarial reviewer (requests calls cert_verify() for every URL but checks only https).
  • Two rounds of adversarial-reviewer + quality-reviewer; round 2: no high/medium findings.

Open questions

None.

Closes #790

🤖 Generated with Claude Code

uniqueg and others added 2 commits November 18, 2026 22:02
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]>
@uniqueg uniqueg self-assigned this Nov 18, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Add the public ca_bundle option and read-only property to GuardedClient, validating and normalizing paths while ensuring requests always keep TLS verification enabled.

  • foca/utils/http.py L932-941, L953-962, L1092-1095 (+5 small edits)

Implementation

Make the guarded adapter translate CA-bundle loading errors into RequestNotSent and preserve the configured bundle when cloning fake clients.

  • foca/plugins/testing.py L420, L425
  • foca/utils/http.py L173-203, L660-683 (+2 small edits)

Documentation

Explain private CA bundle configuration, its trust behavior and limitations, and which other HTTP paths still use public CAs only.

  • docs/utilities.md L354-355, L380-398, L403-405

Tests

Add local TLS tests for CA files and hashed directories, trust isolation, bundle failures, validation, immutability, and absolute-path handling.

  • tests/utils/test_http_tls.py L11-18, L44-56, L260-454 (+3 small edits)

Check that fake HTTP clients retain their CA bundle without exposing it as a plugin default.

  • tests/plugins/test_plugin_testing.py L480-486

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 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (ff1f2ab) to head (77930fb).

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     
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 18, 2026 21:26
@sourcery-ai

sourcery-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 77930fb

#790 feat: let the guarded HTTP client trust other CAs · 3 of 3 met

# Requirement Status Notes
1 Let GuardedClient verify with a specified CA bundle only, keep verification enabled, and fail before sending when the bundle is missing. ✅ Met GuardedClient accepts and stores the bundle path, passes it as the verification setting, and the TLS tests cover bundle-only trust and missing bundles.
2 Add local-TLS tests using a private CA and document the feature. ✅ Met The tests cover CA files and hashed directories; docs/utilities.md describes configuration and behavior.
3 Enable proWES to drop its guarded-adapter wrapper. ✅ Met The new GuardedClient option provides the private-CA support needed; removing the wrapper is a follow-up in proWES.

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


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

Comment thread foca/utils/http.py Resolved
Comment thread tests/utils/test_http_tls.py Resolved
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]>
@uniqueg
uniqueg merged commit b8b33fb into dev Nov 18, 2026
83 checks passed
@uniqueg
uniqueg deleted the feat/790-ca-bundle branch November 18, 2026 22:15
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: let the guarded HTTP client trust other CAs

1 participant