Skip to content

fix: check connections to discovered backends - #347

Merged
uniqueg merged 3 commits into
devfrom
fix/guarded-backends
Oct 31, 2026
Merged

uniqueg merged 3 commits into
devfrom
fix/guarded-backends

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Summary

Requests to TES instances discovered in service registries now go through FOCA 0.18's guarded HTTP client (foca.utils.http.GuardedClient), which checks the address of each connection itself. A host whose addresses change after discovery (DNS rebinding, TTL 0) can no longer lead requests, with proTES's token, to private addresses (unless allow_private_addresses is set on the registry entry).

  • TesClient creates a GuardedClient for discovered backends (allow_private_addresses of the registry entry, https only, as FOCA discovers https services only, responses up to 64 MiB). TesClient._request() sends creates, gets and cancels through it. Configured backends still use plain requests, since they are trusted and may be internal.
  • The per-request check_public_host() is dropped, because the guard covers it. Discovery still checks hosts.
  • Errors of the guarded client map onto those of requests:
    • not sent → BackendRequestNotSent, or BackendAddressNotAllowed for private or unresolved hosts; these fail over;
    • maybe sent → ReadTimeout or ConnectionError; these give an unknown outcome (502) and no failover.
  • TLS errors count as not sent only for refused certificates, as for configured backends. FOCA classifies all TLS errors as not sent, including those after the request was written, which would risk creating a task twice.
  • Guarded connect timeouts are reported as connect_timeout. Invalid headers and URLs that the guarded client reports count as an unknown outcome, since FOCA also reports them for responses, e.g. of redirects, after the request was sent.
  • Docs: the DNS rebinding caveat is removed from docs/configuration.md. The docs now describe the per-connection check, the response limit and the timeouts of discovered backends. docs/plugins.md notes the forward-budget limitation below.

Closes #339

Verification

  • coverage run -m pytest: 999 passed, 142 skipped (Helm not installed locally); 100% coverage.
  • New tests:
    • A discovered host that resolves to 127.0.0.1 at connection time is refused before connecting, and no connection reaches the local listener.
    • With allow_private_addresses, the connection is made.
    • Error mapping, TLS classification, response conversion, unsupported arguments, and the guarded client's settings.
  • ruff check ., ruff format --check ., mypy pro_tes tests, ast-grep scan, semgrep --config=.semgrep --error and mkdocs build --strict all pass.
  • CI: all checks passed (image push/publish skipped on PRs).

Declined review findings

  • Quality (low): drop allow_redirects=False from _request_params for registry entries, which the guarded path ignores. Kept as a defence in depth for the plain path.

  • Adversarial (medium, partly): the forward budget (plugins.defaults.forward_timeout) doesn't shorten connects to discovered backends. FOCA's GuardedClient.request() has no per-request connect timeout; its connect limit is min(custom.tes.timeout, 10) s. This is documented. Fixing it needs a FOCA change (a connect_timeout argument), which this PR doesn't make (tracked under feat: add gateway plugin engine foca#485).

  • Adversarial (medium, FOCA): FOCA 0.18's GuardedClient reads the bodies of 3xx responses whole before its size check, because requests resolves redirect targets even with allow_redirects=False. The 64 MiB limit therefore doesn't hold for redirects. This is documented as a limitation and needs a FOCA fix (e.g. sending through the adapter directly), tracked under feat: add gateway plugin engine foca#485.

  • Adversarial (medium, FOCA): FOCA classifies invalid response headers and redirect URLs as RequestNotSent. proTES works around this by treating them as an unknown outcome; the classification itself should be fixed in FOCA.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Protect requests to discovered TES backends with per-connection address validation and consistent guarded-client error handling.

New Features:

  • Route requests to discovered TES backends through FOCA’s guarded HTTP client, including per-connection address validation and response-size limits.
  • Allow registry entries to explicitly permit private backend addresses while retaining secure defaults.

Bug Fixes:

  • Prevent DNS rebinding from redirecting proTES credentials or requests to private addresses.
  • Classify guarded-client failures according to whether a backend request was sent, enabling safe failover and unknown-outcome handling.

Enhancements:

  • Preserve plain requests behavior for configured backends while adapting guarded-client responses and errors to proTES interfaces.
  • Document discovered-backend connection, timeout, response-size, and forwarding-budget behavior.

Documentation:

  • Update backend security and timeout documentation to describe per-connection checks and guarded-client limitations.

Tests:

  • Add coverage for DNS rebinding protection, private-address opt-in, guarded request error mapping, TLS classification, response conversion, and supported arguments.

uniqueg and others added 3 commits October 31, 2026 01:28
Send requests to TES backends discovered in service registries through
FOCA's GuardedClient, which checks the address of each connection, so
that hosts whose addresses change after discovery (DNS rebinding) can't
lead requests and proTES's credentials to private addresses. The
per-request host check is dropped. Responses of discovered backends are
limited to 64 MiB; errors of the guarded client map onto those of
requests (not sent, or maybe sent).

Remove the DNS rebinding caveat from the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Treat TLS errors of the guarded client as not sent only for refused
certificates, as for configured backends; other TLS errors may come
after the request was sent, so the outcome is unknown and the task
isn't sent elsewhere. Convert guarded responses with their reason and
encoding, refuse arguments the guarded client doesn't support, and
document that the forward budget doesn't shorten connecting to
discovered backends yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Report connect timeouts of discovered backends as connect_timeout, and
treat invalid headers and URLs reported by the guarded client as an
unknown outcome, as FOCA also reports them for responses (e.g., of
redirects) after the request was sent. Note in the docs that FOCA 0.18
reads bodies of redirects whole, beyond the response limit, and why
the forward budget doesn't shorten connecting to discovered backends.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Discovered TES backends now use FOCA 0.18's per-connection guarded client to prevent DNS-rebinding requests to private addresses, with registry-specific policy, bounded responses, requests-compatible response conversion, and careful error mapping that preserves failover and unknown-outcome semantics.

Sequence diagram for guarded requests to discovered TES backends

sequenceDiagram
    participant TesClient
    participant GuardedClient
    participant DNS
    participant TES

    TesClient->>GuardedClient: request(method, url, params, headers, data, auth)
    GuardedClient->>DNS: Resolve host for connection
    DNS-->>GuardedClient: Address
    alt Private or unresolved address
        GuardedClient-->>TesClient: AddressNotAllowed or HostNotResolved
        TesClient-->>TesClient: BackendAddressNotAllowed
    else Allowed address
        GuardedClient->>TES: HTTPS request
        TES-->>GuardedClient: Response up to 64 MiB
        GuardedClient-->>TesClient: HttpResponse
        TesClient-->>TesClient: as_response()
    end
Loading

Flow diagram for discovered backend error mapping

flowchart TD
    A["GuardedClient.request()"] --> B{Request outcome}
    B -->|AddressNotAllowed or HostNotResolved| C[BackendAddressNotAllowed]
    B -->|RequestNotSent| D[BackendRequestNotSent]
    B -->|RequestMaybeSent read_timeout| E[requests.ReadTimeout]
    B -->|RequestMaybeSent other error| F[requests.ConnectionError]
    B -->|Valid response| G["as_response()"]
    C --> H[Fail over]
    D --> H
    E --> I[Unknown outcome 502]
    F --> I
Loading

File-Level Changes

Change Details Files
Route discovered-backend requests through FOCA's per-connection guarded HTTP client while preserving the existing plain requests path for configured backends.
  • Instantiate the guard with registry-specific private-address policy, HTTPS-only access, timeout, and 64 MiB response limit.
  • Use the guarded path for task creation, retrieval, and cancellation; retain redirect blocking and supported-argument validation.
  • Convert guarded responses into requests-compatible responses for existing TES handling.
pro_tes/ga4gh/tes/backends.py
docs/configuration.md
docs/plugins.md
Map FOCA request outcomes to proTES and requests error semantics so failover only occurs when a request was definitely not sent.
  • Add distinct not-sent and address-not-allowed backend exceptions.
  • Classify unresolved/private hosts, connect timeouts, TLS failures, invalid requests, and maybe-sent read/connection failures according to delivery certainty.
  • Preserve unknown outcomes for errors that may follow request transmission and expose appropriate forwarding reasons.
pro_tes/exceptions.py
pro_tes/ga4gh/tes/backends.py
Expand backend tests around DNS rebinding protection, guarded-client configuration, response conversion, and error classification.
  • Verify private rebinding is blocked before a socket connection and is allowed only when configured.
  • Test guarded and unguarded client paths, supported arguments, response metadata, TLS/connect classifications, and forwarded request behavior.
  • Update request mocks and move loopback support to the discovered-backend test fixture.
tests/ga4gh/tes/conftest.py
tests/ga4gh/tes/test_backend_list.py
tests/ga4gh/tes/test_backends.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

@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 proTES | 🛠️ Build #35537872 | 📁 Comparing 2a3f498 against latest (d9f3efa)

  🔍 Preview build  

3 files changed
± configuration/index.html
± plugins/index.html
± reference/index.html

@codecov

codecov Bot commented Oct 31, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (d9f3efa) to head (2a3f498).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #347   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           23        23           
  Lines         2099      2136   +37     
=========================================
+ Hits          2099      2136   +37     

☔ 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 October 31, 2026 01:20

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

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

## Individual Comments

### Comment 1
<location path="pro_tes/ga4gh/tes/backends.py" line_range="790" />
<code_context>
+        if unsupported:
+            raise TypeError(f"Unsupported arguments of guarded requests: {unsupported}")
+        try:
+            guarded = self.guarded.request(
+                method,
+                url,
</code_context>
<issue_to_address>
**Discovered requests outlive forwarding budget**

When a discovered-backend request takes longer than the forwarding attempt's remaining budget, especially while connecting or when the configured TES timeout exceeds that budget, `TesClient._request` lets `GuardedClient.request` use its configured timeout instead of the remaining forwarding budget, so the request continues past the deadline, tying up worker capacity and delaying task processing; a late task submission can then be followed by a retry that creates a second remote task.

Pass the forwarding attempt's remaining budget as the timeout to `GuardedClient.request`.
</issue_to_address>

Linked issues

#339 fix: check connections to discovered backends · 2 of 2 met

# Requirement Status Notes
1 Check each connection to discovered TES instances, refusing private addresses unless allowed, with tests. ✅ Met Discovered backends use FOCA's GuardedClient with the registry entry's allow_private_addresses setting; tests cover refusal before connecting and the allowed-private case.
2 Remove the DNS rebinding caveat from the docs. ✅ Met The configuration docs replace the caveat with a description of the per-connection check and its DNS-rebinding protection.

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and if the guarded client checks one address but connects to another, a discovered backend that changes DNS could still receive proTES credentials at a private address. Any credentials exposed before the mistake is found cannot be recovered by reverting this change.

Blocking findings: pro_tes/ga4gh/tes/backends.py:790


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

Comment thread pro_tes/ga4gh/tes/backends.py Resolved
@uniqueg
uniqueg merged commit d28342f into dev Oct 31, 2026
19 checks passed
@uniqueg
uniqueg deleted the fix/guarded-backends branch October 31, 2026 01:34
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: check connections to discovered backends

1 participant