Skip to content

fix: small pre-release findings of 0.20.0 - #652

Merged
uniqueg merged 7 commits into
devfrom
fix/small-prerelease-findings
Nov 3, 2026
Merged

uniqueg merged 7 commits into
devfrom
fix/small-prerelease-findings

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Summary

Small findings of the pre-release review of 0.20.0:

  • GuardedClient and the fake client report names, values and credentials that can't be encoded as invalid_header rather than invalid_url.
  • A warning at the first token validation names issuers reached without TLS, except on the loopback interface. Token validation itself doesn't change. Token exchange isn't touched.
  • Real TLS tests of sent and not sent, with a local certificate (tests/utils/test_http_tls.py).
  • An origin note on the Casbin adapter. Whether a NOTICE file is needed too is the maintainer's call.

Closes #647

How it was verified

  • coverage run -m pytest with MongoDB 7.0.34, Python 3.13: 3346 passed, 1 skipped, 100% coverage.
  • ruff, mypy, ast-grep, semgrep, mkdocs build --strict: passed.
  • Full review (touches auth logging), two rounds.

Declined review findings

  • Warn about http values of jwks_uri and userinfo_endpoint (adversarial, low): needs a change in the token path, for a release in which it is otherwise unchanged; for a later release.
  • Spellings such as foo.localhost or 127.1 count as remote and warn (adversarial, low): log noise in local setups only.
  • A lone surrogate in params or data is reported as invalid_header (adversarial, low): unusual input, and it is not sent either way.
  • The TLS fixture patches requests.adapters.DEFAULT_CA_BUNDLE_PATH (quality, medium): the session doesn't trust the environment, so the named variables can't affect it, and a change in requests makes the tests fail, not pass.

🤖 Generated with Claude Code

https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG

Summary by Sourcery

Improve pre-release HTTP error classification and authentication security warnings, with expanded TLS and validation coverage.

Bug Fixes:

  • Classify unencodable header names, values, and credentials as invalid headers instead of invalid URLs.
  • Warn when configured token issuers use unencrypted HTTP outside loopback interfaces.

Enhancements:

  • Add realistic local TLS coverage for distinguishing requests that were not sent from those that may have been sent.
  • Document insecure issuer warnings and expanded invalid-header handling.
  • Add licensing provenance information for the Casbin adapter.

Tests:

  • Expand request validation tests for non-encodable headers and credentials, issuer security warnings, and real TLS request outcomes.

uniqueg and others added 4 commits November 3, 2026 10:57
- GuardedClient reports a header that can't be encoded as Latin-1 as
  invalid_header rather than invalid_url, and so does the fake client.
- Warn at the first token validation about issuers reached without TLS,
  except on the loopback interface.
- Test sent and not sent over real TLS, with a local certificate.
- Add an origin note to the Casbin adapter.

Closes #647

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Header names are encoded as ASCII, so matching Latin-1 missed them, and
credentials reach the Authorization header. Do the same in the fake
client, also for auth, and accept a reset in the handshake test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
@sourcery-ai

sourcery-ai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR tightens HTTP error classification for unencodable request data, adds diagnostics for insecure non-loopback token issuers, and validates request delivery semantics with real TLS integration tests, alongside related documentation and provenance updates.

Sequence diagram for HTTP request validation and error classification

sequenceDiagram
    participant Client
    participant GuardedClient
    participant Requests
    participant HTTP

    Client->>GuardedClient: request(method, url, params, headers, auth)
    GuardedClient->>Requests: prepare request
    Requests-->>GuardedClient: prepared request or encoding error
    alt unencodable header or credential
        GuardedClient-->>Client: InvalidRequest(reason=invalid_header)
    else valid request
        GuardedClient->>HTTP: send prepared request
        HTTP-->>GuardedClient: response or transport error
        GuardedClient-->>Client: response or classified HttpError
    end
Loading

Sequence diagram for insecure token issuer warning

sequenceDiagram
    participant AuthConfig
    participant AuthWarnings
    participant Logger

    AuthConfig->>AuthWarnings: log_auth_config_warnings(conf)
    loop each issuer in conf.issuer_urls
        AuthWarnings->>AuthWarnings: _reached_without_tls(issuer)
        alt HTTP issuer outside loopback
            AuthWarnings->>Logger: warning(issuer reached without TLS)
        end
    end
Loading

File-Level Changes

Change Details Files
Classify request fields that fail wire encoding as invalid headers consistently in real and fake HTTP clients.
  • Pre-validate prepared header names as ASCII and values as Latin-1.
  • Include authentication preparation in the invalid-header error path.
  • Map Unicode encoding failures to the invalid_header reason code.
  • Document and test unencodable headers and credentials.
foca/plugins/testing.py
foca/utils/http.py
docs/utilities.md
tests/plugins/test_plugin_testing.py
tests/utils/test_http.py
Add first-validation warnings for non-TLS token issuers outside loopback while leaving token validation and exchange behavior unchanged.
  • Parse issuer URLs and warn for HTTP issuers on non-loopback hosts, including malformed URLs.
  • Exclude HTTPS and loopback HTTP issuers from the warning.
  • Document the warning timing and scope and add parameterized coverage.
foca/security/auth.py
docs/deployment.md
tests/security/test_auth.py
Add integration coverage proving request-sent classification across real TLS handshakes and connections.
  • Generate a local self-signed certificate and run loopback TLS servers.
  • Verify handshake failures are RequestNotSent and post-send failures are RequestMaybeSent.
  • Verify successful responses and deadline behavior with server-controlled connection states.
tests/utils/test_http_tls.py
Attribute the Casbin adapter's upstream origin and license.
  • Add module documentation identifying casbin-pymongo-adapter as the original source and noting subsequent rewrites.
foca/security/access_control/foca_casbin_adapter/adapter.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

Comment thread tests/utils/test_http_tls.py Fixed
@codecov

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (397fff1) to head (d7d3176).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #652   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           56        56           
  Lines         7142      7164   +22     
=========================================
+ Hits          7142      7164   +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
uniqueg marked this pull request as ready for review November 3, 2026 10:43

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

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

## Individual Comments

### Comment 1
<location path="foca/security/auth.py" line_range="314" />
<code_context>
+            logger.warning(
+                "Trusted issuer %s is reached without TLS: anyone on the network "
+                "can change its signing keys, and so forge what it signs.",
+                escape_log_value(issuer),
+            )
     if not conf.verify_audience and conf.clients is None:
</code_context>
<issue_to_address>
**Issuer secrets reach logs**

When a configured HTTP issuer URL contains credentials or secret query parameters, `escape_log_value(issuer)` preserves printable URL secrets, so `log_auth_config_warnings` writes credentials or tokens to warning logs and exposes them to log readers.

Redact URL userinfo and sensitive query parameters before logging the issuer.
</issue_to_address>

### Comment 2
<location path="foca/plugins/testing.py" line_range="553-556" />
<code_context>
     prepared = requests.Request(
         method.upper(), url, params=params, headers=dict(headers or {})
     ).prepare()
+    for name, value in prepared.headers.items():
+        name.encode("ascii")
+        if isinstance(value, str):
+            value.encode("latin-1")
     return str(prepared.url)

</code_context>
<issue_to_address>
**Fake accepts invalid URL credentials**

When URL-embedded credentials cannot be encoded for Basic Authorization, `_prepared_url` does not validate the Authorization header generated from URL userinfo, so `FakeHttp.request` records the request and can return a canned response while `GuardedClient` raises `invalid_header`.

Validate URL-embedded credentials using the same encoding checks as the prepared Authorization header.

Also at `foca/plugins/testing.py:484-486`.
</issue_to_address>

### Comment 3
<location path="foca/plugins/testing.py" line_range="485-486" />
<code_context>
             url = _prepared_url(method, url, params, headers)
-        except requests.exceptions.InvalidHeader as exc:
+            if auth is not None:
+                prepared = requests.Request(method, url, auth=auth).prepare()
+                _check_response_hooks(prepared.hooks)
+        except (requests.exceptions.InvalidHeader, UnicodeEncodeError) as exc:
             raise InvalidRequest(
</code_context>
<issue_to_address>
**Fake accepts unencodable auth headers**

When a custom auth handler adds a header name or value that cannot be encoded for sending, `FakeHttp` checks only response hooks on the prepared auth request, so it records the request and can return a canned response instead of raising `InvalidRequest` as `GuardedClient` does.

Check the prepared auth request's header names and values for send-time encoding errors.
</issue_to_address>

### Comment 4
<location path="tests/utils/test_http_tls.py" line_range="242" />
<code_context>
+            stop.wait(10)
+
+    with pytest.raises(RequestMaybeSent):
+        client(timeout=0.5).post(serve(behaviour), json={})
</code_context>
<issue_to_address>
**TLS test times out before sending**

When local scheduling or TLS setup takes more than 0.5 seconds before the request is sent, `test_hang_after_sending` expects `RequestMaybeSent` at the `client(timeout=0.5)` call. If local TCP/TLS setup takes longer than 0.5 seconds, the correct client raises `DeadlineExceeded` before sending, so the test fails.

Use a longer timeout or synchronize the timeout phase so the test starts its wait only after the server has received the request.
</issue_to_address>

### Comment 5
<location path="foca/security/auth.py" line_range="312-314" />
<code_context>
+    for issuer in conf.issuer_urls:
+        if _reached_without_tls(issuer):
+            logger.warning(
+                "Trusted issuer %s is reached without TLS: anyone on the network "
+                "can change its signing keys, and so forge what it signs.",
+                escape_log_value(issuer),
+            )
     if not conf.verify_audience and conf.clients is None:
</code_context>
<issue_to_address>
**Issuer warning appears twice**

When concurrent requests perform their first token validation using the same config, `validate_token` can have multiple calls observe `_warnings_logged` as false before either sets it, so each calls `log_auth_config_warnings` and emits the issuer warning.

Synchronize the `_warnings_logged` check, warning call, and flag update.
</issue_to_address>

Linked issues

#647 fix: small pre-release findings of 0.20.0 · 4 of 4 met

# Requirement Status Notes
1 Report unencodable headers as InvalidRequest with reason invalid_header in GuardedClient and the fake client. ✅ Met GuardedClient maps InvalidHeader and UnicodeEncodeError to invalid_header; the fake client checks header-name/value encodings and maps encoding errors, including auth credentials, the same way.
2 Warn at the first token validation about http:// issuers, except for loopback hosts. ✅ Met The warning is logged from log_auth_config_warnings, called once at the start of validate_token; the check excludes localhost and loopback IP addresses.
3 Add a local TLS fixture covering sent-versus-not-sent behavior during the handshake and after sending. ✅ Met The local TLS tests cover handshake close, timeout and certificate failure as not sent, and connection close and timeout after reading the request as maybe sent.
4 Add an origin note to the Casbin adapter. ✅ Met The adapter docstring attributes its origin to casbin-pymongo-adapter and names its Apache License 2.0.

Sourcery assessment

Approval pending. 5 findings to address first.

Blocking findings: foca/security/auth.py:314, foca/plugins/testing.py:556, foca/plugins/testing.py:486, tests/utils/test_http_tls.py:242, foca/security/auth.py:314


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

Comment thread foca/security/auth.py Resolved
Comment thread foca/plugins/testing.py Resolved
Comment thread foca/plugins/testing.py Resolved
Comment thread tests/utils/test_http_tls.py Resolved
Comment thread foca/security/auth.py Resolved
uniqueg and others added 2 commits November 3, 2026 12:18
Show the issuer without credentials and query, and check the encoding
of headers added by auth handlers in the fake client. Give the test of
a server that hangs after the request more time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
@uniqueg
uniqueg merged commit 631da3a into dev Nov 3, 2026
56 checks passed
@uniqueg
uniqueg deleted the fix/small-prerelease-findings branch November 3, 2026 11:29
uniqueg added a commit that referenced this pull request Nov 4, 2026
The adapter derives from casbin-pymongo-adapter (Apache-2.0). Its
module docstring already says so (#652); add a NOTICE file with the
entry, and ship it in the distributions and the image build.

Closes #655

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

fix: small pre-release findings of 0.20.0

2 participants