Skip to content

🐛 Fix validateCertificate to fire pre-emission for TLS pinning - #2512

Open
realmeylisdev wants to merge 19 commits into
cfug:mainfrom
realmeylisdev:fix/2418-pre-emission-tls-pinning
Open

realmeylisdev wants to merge 19 commits into
cfug:mainfrom
realmeylisdev:fix/2418-pre-emission-tls-pinning

Conversation

@realmeylisdev

@realmeylisdev realmeylisdev commented May 10, 2026 •

Copy link
Copy Markdown

Closes #2418.

IOHttpClientAdapter.validateCertificate only runs once the response headers have arrived, so a server whose certificate the callback rejects has already received the request line, headers and body. That defeats certificate and public key pinning.

This PR installs an HttpClient.connectionFactory that calls validateCertificate after the TLS handshake and before HttpClient writes anything, whenever the adapter uses the default HttpClient as is. A rejected certificate closes the connection, and the request fails with DioException.badCertificate without being sent.

@AlexV525, flagging this per AGENTS.md: it changes certificate pinning behavior and touches connection timeout and cancellation handling.

Behavior

  • Trust is unchanged. The factory performs the same handshake HttpClient performs itself when it has no custom SecurityContext or badCertificateCallback. The default trust store still has to accept the chain before validateCertificate sees the leaf certificate, as the doc comment has always said.
  • Only when the adapter owns the TLS setup. The factory replaces HttpClient's handshake and cannot read a SecurityContext or badCertificateCallback configured elsewhere. So it is installed only when createHttpClient and onHttpClientCreate are both unset and no HttpOverrides are active when the client is created. Every other setup behaves as it does today.
  • The response check stays. validateCertificate still runs for every response, with the original request's host and port. That check is the only one in the setups above, for HTTPS through a proxy (where HttpClient performs the CONNECT and the handshake itself), and when the field is set after the first request. As a result, the callback runs twice for the first request on a new connection. The network test 2 requests == 2 approvals is replaced by a local test that expects 3 calls for 2 pooled requests.
  • Redirects. When HttpClient follows a redirect, the pre-send check runs on the connection to the redirect target and receives the target's host and port. A rejected redirect target fails with badCertificate and receives nothing. A callback that compares host can therefore reject a redirect that it used to accept. This is documented on validateCertificate and in the CHANGELOG.
  • Things a connection factory takes over from HttpClient:
    • Unsupported schemes. HttpClient only rejects schemes other than http and https when no factory is set, so the factory throws the same ArgumentError itself.
    • Connection timeout and close(). While the factory waits for the handshake, it applies HttpClient.connectionTimeout and cancels the attempt on close(), as HttpClient does for its own pending connections.
    • A throwing callback. If the callback throws, the connection is closed.
  • Docs. The README pinning example (EN and ZH) built its own HttpClient with withTrustedRoots: false and a badCertificateCallback that accepts everything. With a custom client, validateCertificate only runs on the response, so that setup sent every request to whichever server answered, whatever certificate it presented. The example now uses the default adapter, and so does example_dart/lib/certificate_pinning.dart. Self-signed servers are pointed to the Certificate Authority Verification methods, which reject during the handshake.

There are no public API changes and no SDK constraint changes. SecureSocket.startConnect (Dart 2.0) and HttpClient.connectionFactory (Dart 2.17) predate the 2.18 lower bound.

Verification

dio/test/pinning_test.dart starts local TLS servers using throwaway localhost certificates that openssl generates at test time, so no keys are committed. One certificate is trusted through the default context and the other is not. The tests check that:

  • a rejected certificate never receives the request (fails on main, where the server receives the body);
  • an approving callback is first called before the server sees the request;
  • an untrusted certificate fails the handshake without reaching an approving callback;
  • createHttpClient, onHttpClientCreate and HttpOverrides keep their own badCertificateCallback;
  • proxied requests and late-set validators are still checked on the response;
  • a rejected redirect target fails with badCertificate;
  • a wss:// URL fails with ArgumentError without sending anything;
  • close() during the handshake sends nothing;
  • a handshake that completes after connectTimeout is not validated;
  • a throwing callback closes the connection.

The new tests fail without their fixes. The relay-based ones passed 10 out of 10 runs on Dart 3.13.7 and on 2.18.7. stacktrace_test.dart is unchanged from main.

Locally, dart format and dart analyze --fatal-infos are clean. The full dio VM suite passes on Dart 2.18.7 (--preset=default,min) and on Dart 3.13.7. On 3.13.7 the only failures in some runs were badssl.com connection resets from my network, which exception_test.dart's allow badssl hits on main as well. The tls-tagged pinning tests pass with -P all.

Known limitations

  • HTTPS through a proxy is still only checked on the response.
  • If HttpOverrides added after the client was created make findProxy return a proxy after DIRECT, HttpClient retries through that proxy when the pre-send check rejects the direct connection. That retry is only checked on the response. The default environment-based proxy lookup returns a single entry, so it never does this.

New Pull Request Checklist

  • I have read the Documentation
  • I have read the Agent Contribution Guidelines (required if any part of the change was produced with AI assistance)
  • I have searched for a similar pull request in the project and found none
  • I have updated this branch with the latest main branch to avoid conflicts (via merge from master or rebase)
  • I have added the required tests to prove the fix/feature I'm adding
  • I have updated the documentation (if necessary)
  • I have run the tests without failures
  • I have updated the CHANGELOG.md in the corresponding package

AI disclosure: Claude (Claude Code) did this revision: the merge with main, the fixes, tests and docs, plus an independent review pass by a separate Claude agent.

`IOHttpClientAdapter.validateCertificate` previously ran after
`HttpClientRequest.close()` had already flushed the request method,
headers, and body to the wire. The callback could prevent the response
from being delivered to the caller, but it could not prevent leakage of
outbound request data — defeating the canonical purpose of certificate
or public-key pinning.

Install an `HttpClient.connectionFactory` (when `validateCertificate`
is set and `createHttpClient` is not) that performs the TLS handshake,
runs `validateCertificate`, and only then yields the socket to
`HttpClient`. Rejection throws a private `_BadCertificateException` (a
`HandshakeException` subtype) that `_fetch` translates into
`DioException.badCertificate` — without a single byte of the request
ever leaving the client.

The legacy post-response validation block is preserved as a fallback
for the `createHttpClient` escape hatch, so users who supply a custom
`HttpClient` keep today's degraded-but-not-broken semantics. Proxy
support is included via an HTTP/1.1 CONNECT-tunnel branch, mirroring
the pattern in `dio_http2_adapter`.

Behavior change: validation now runs once per TCP connection rather
than once per HTTP request, matching `dio_http2_adapter`'s existing
semantics. The existing `'2 requests == 2 approvals'` test is updated
accordingly. A new load-bearing regression test asserts that the
server receives zero bytes when `validateCertificate` returns false.

Min Dart SDK is raised to 3.5.0 for `ConnectionTask.fromSocket`. The
existing TODO migrating `DioMixin` to `mixin class` syntax is resolved.

Fixes cfug#2418
…README

Three issues surfaced during self-review of cfug#2512:

H2: late mutation of `validateCertificate` silently no-oped. The gate
on the legacy post-response block was `createHttpClient != null`, so
a user who set `validateCertificate` *after* the `HttpClient` was first
cached saw the callback never fire. Drop the gate so the post-response
block runs whenever `validateCertificate` is non-null — redundant on
the direct-HTTPS pre-emission path (the same cert was already approved
by the connectionFactory hook, idempotent for pinning), but the only
defense for late-mutation, proxy, and `createHttpClient` paths.

H1+M1: the manual `CONNECT`-tunnel inside `_connectHttpsViaProxy` was
broken — `HttpClient` writes its own `CONNECT` over whatever socket the
factory returns, so we ended up issuing two `CONNECT` requests and the
TLS handshake corrupted. (Discovered by the new proxy test failing.)
Drop the manual tunnel entirely; the factory's proxy branch now returns
a plain `Socket.startConnect(proxyHost, proxyPort)` and `HttpClient`
handles `CONNECT` + TLS itself. Proxy + pinning therefore falls back to
post-response validation only — documented as a known limitation; for
pre-emission behind a proxy, users must supply `createHttpClient` and
configure `HttpClient.connectionFactory` themselves. Add two tests that
exercise the proxy code path through a local stub `CONNECT` proxy
fixture.

Add `dio/test/_pinning/README.md` documenting the self-signed cert
regeneration command, since the committed pair has a 10-year validity
and a future maintainer will need to rotate it.

Also drop the redundant `as Socket` cast on the direct HTTPS branch
and consolidate the dangling `## Unreleased *None.*` CHANGELOG header
with the 5.10.0 entry — entries now live under `Unreleased` until the
release script cuts them.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please revert since we don't match the requirement here.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reverted in 8a66e1e — back to abstract class DioMixin implements Dio with the original TODO(EVERYONE): Use \mixin class` when the lower bound of SDK is raised to 3.0.0.` comment.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about other adapters?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fix is intentionally scoped to IOHttpClientAdapter since that's the adapter with the bug. Quick rundown of the others:

  • plugins/http2_adapter — already does pre-emission validation correctly at connection_manager_imp.dart:133-150. This PR brings IOHttpClientAdapter to parity.
  • plugins/web_adapter — no validateCertificate field exists on the web adapter; TLS is browser-controlled and not introspectable from Dart. Not applicable.
  • plugins/native_dio_adapter — delegates to cronet_http / cupertino_http; TLS pinning is platform-native (Android NSC, iOS ATS/TrustKit), not a dio-level callback. Not applicable.

Happy to add this as a one-line cross-reference comment in io_adapter.dart if you'd like that captured in source.

Comment thread dio/pubspec.yaml

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please revert.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reverted in 8a66e1e — back to sdk: '>=2.18.0 <4.0.0'. Same for dio_test/pubspec.yaml. The pre-emission factory no longer needs Dart 3.5+.

Comment thread dio/lib/src/adapters/io_adapter.dart Outdated
}
return ss;
}();
return ConnectionTask.fromSocket(socketFuture, () {});

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation of ConnectionTask is simple, try to copy it into the code base to avoid bumping the SDK version too high.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed differently in 8a66e1e — literal vendoring is blocked because Dart 3.0 made ConnectionTask a final class (any vendored class _ConnectionTask implements ConnectionTask fails to compile from 3.0 onward), and ConnectionTask.fromSocket is Dart 3.5+ only.

Switched to SecureSocket.startConnect(...) (stable pre-2.18 API) which returns a real SDK ConnectionTask<SecureSocket>. We await task.socket once to validate the leaf cert, then return task; HttpClient re-awaits the same Future and gets the resolved socket immediately. Covariance handles the upcast to ConnectionTask<Socket>. No vendoring, no SDK floor change — same observable behavior.

@realmeylisdev

Copy link
Copy Markdown
Author

Pushed review fixes (23aa0c0):

  • H2 (late mutation): the legacy post-response validation block now runs unconditionally when validateCertificate is non-null. Setting the field after the first request now fires the callback (was silently no-oping). For direct HTTPS the callback fires twice (pre-emission + post-response, idempotent for fingerprint pinning) — documented.
  • H1 + M1 (proxy): the manual CONNECT tunnel in the factory was broken — HttpClient writes its own CONNECT over the socket we return, so we ended up issuing two CONNECT requests and the TLS handshake corrupted. Discovered by the new proxy test failing. Dropped the manual tunnel; HTTPS through a proxy now uses post-response validation only (HttpClient handles CONNECT + TLS). Added two proxy tests via a local stub CONNECT fixture.
  • Fixture README: added dio/test/_pinning/README.md with the openssl command to regenerate the 10-year self-signed cert.
  • Cleanups: dropped redundant as Socket cast; consolidated dangling ## Unreleased *None.* with the new entry; removed dart:convert import that's no longer used.

PR description updated to reflect the corrected scope (proxy = known limitation, post-response only).

Per @AlexV525:

1. Revert dio/pubspec.yaml + dio_test/pubspec.yaml min SDK back to
   `>=2.18.0 <4.0.0` (the bump to 3.5.0 is no longer needed).
2. Revert dio/lib/src/dio_mixin.dart to `abstract class DioMixin` with
   the original TODO comment.
3. Replace the Dart-3.5+ `ConnectionTask.fromSocket(...)` call in
   `_pinnedConnectionFactory` with `SecureSocket.startConnect(...)` and
   return the stock SDK [ConnectionTask] it produces. We await
   `task.socket` once to do the leaf-cert validation; HttpClient
   re-awaits the same `Future<SecureSocket>` and gets the resolved
   value immediately (Future await is idempotent).

   This works on every Dart >=2.18.0 because `SecureSocket.startConnect`
   has been in `dart:io` well before the minimum SDK, and the
   `ConnectionTask` generic is covariant in its type parameter so
   `ConnectionTask<SecureSocket>` is implicitly assignable to
   `ConnectionTask<Socket>` at the factory's return position. No
   vendoring or `implements ConnectionTask` is required — and
   `ConnectionTask` being `final class` from Dart 3.0 onward is no
   longer a problem since we never inherit from it.

   The maintainer's suggestion to literally "copy ConnectionTask into
   the code base" cannot be done across the Dart 3.0–3.4 window (final
   class blocks implements; fromSocket didn't exist yet), but
   `SecureSocket.startConnect` achieves the same end with zero new
   types and zero SDK floor change.

4. Drop the two CHANGELOG bullets that referenced the SDK bump and
   the mixin migration. The rest of the entry (the actual cfug#2418 fix)
   stays.

No test changes — the factory's observable behavior is unchanged
(approval yields a validated SecureSocket; rejection still throws
`_BadCertificateException` from the same point in `_fetch`'s try
block). All 222 tests pass; `dart analyze lib/` is clean.
@AlexV525

Copy link
Copy Markdown
Member

Still not covering previous comments

@realmeylisdev

Copy link
Copy Markdown
Author

@AlexV525 thanks for the review. Pushed 8a66e1e addressing all four points:

1. dio/pubspec.yaml (revert) ✅ Restored sdk: '>=2.18.0 <4.0.0'. Same for dio_test/pubspec.yaml.

2. dio/lib/src/dio_mixin.dart (revert) ✅ Back to abstract class DioMixin implements Dio with the // TODO(EVERYONE): Use 'mixin class' when the lower bound of SDK is raised to 3.0.0. comment intact.

3. dio/lib/src/adapters/io_adapter.dart line 384 (vendor ConnectionTask) ✅ Achieved the underlying goal (keep min SDK at 2.18) without literal vendoring. Quick note on the constraint and the workaround:

Literally copying ConnectionTask into the codebase isn't viable across the Dart 3.0–3.4 window — Dart 3.0 made ConnectionTask a final class, so any vendored class _ConnectionTask implements ConnectionTask would fail to compile on Dart 3.0+. The public factory ConnectionTask.fromSocket that I'd been using is itself Dart 3.5+ only.

The fix is to use SecureSocket.startConnect(...) — a stable dart:io API that predates dio's 2.18 floor — which returns a real SDK-built ConnectionTask<SecureSocket>. We await task.socket once to validate the leaf certificate, then return the same task; HttpClient re-awaits task.socket and gets the already-resolved socket immediately (Future awaits are idempotent). Covariance does the upcast from ConnectionTask<SecureSocket> to ConnectionTask<Socket> at the return position.

Diff for the affected branch is small:

  • before: await SecureSocket.connect(...) + ConnectionTask.fromSocket(socketFuture, () {})
  • after: await SecureSocket.startConnect(...) + await task.socket (for validation) + return task

4. "What about other adapters?" ✅ The fix is intentionally scoped to IOHttpClientAdapter because that's where the bug exists. For completeness:

  • plugins/http2_adapter — already does pre-emission validation correctly at connection_manager_imp.dart:133-150. No change needed; this PR brings IOHttpClientAdapter to parity.
  • plugins/web_adapter — no validateCertificate field on the web adapter (it's only on IOHttpClientAdapter). TLS is handled by the browser and is not introspectable from Dart. Not applicable.
  • plugins/native_dio_adapter — delegates to cronet_http / cupertino_http, where TLS pinning is platform-native (Android NSC, iOS ATS/TrustKit). Not exposed via a dio-level callback. Not applicable.

Happy to add a one-line cross-reference comment in io_adapter.dart pointing to this clarification if you'd like that captured in source.

All 222 tests pass; dart analyze lib/ is clean.

@AlexV525

Copy link
Copy Markdown
Member

Tests didn't seem passing.
Additionally, I'm considering ignoring these pinning test certs for Git for security concerns.

@AlexV525

Copy link
Copy Markdown
Member

@realmeylisdev Would you like to bring this up again?

- Format io_adapter.dart, pinning_test.dart, stacktrace_test.dart
  (dart format --set-exit-if-changed was failing on the stable job).
- Fix the failing '2 requests' test: the post-response block still
  fires per-request, so a pooled 2-request flow invokes the validator
  3 times (1 pre-emission + 2 post-response), not 1. Replace the flaky
  network test with a deterministic local-server test asserting 3.
- Generate the localhost test keypair at runtime via openssl in
  setUpAll (temp dir, cleaned up in tearDownAll) instead of committing
  server_cert.pem / server_key.pem. No private key in the repo.
@realmeylisdev

Copy link
Copy Markdown
Author

@AlexV525 thanks — picked this back up. Both points are addressed in a7372d3.

1. CI / failing tests. Two distinct causes against the previous HEAD:

  • dart format wasn't clean on io_adapter.dart, pinning_test.dart, and stacktrace_test.dart, so the stable job failed at the format step before it ever reached the tests. Reformatted.
  • The '2 requests share connection (1 approval)' test asserted approvalCount == 1, but the post-response validation block still fires once per request — so a 2-request pooled flow invokes the validator 3 times (1 pre-emission + 2 post-response), not 1. I replaced that network-dependent test with a deterministic local-server test, 'two pooled requests: 1 pre-emission + 2 post-response validations', asserting 3.

2. Test certs. Agreed — no private key should live in git. The committed test/_pinning/ keypair and README are removed; the local HttpServer.bindSecure tests now mint a throwaway self-signed localhost keypair at runtime via openssl in setUpAll (temp dir, cleaned up in tearDownAll). openssl is already required by scripts/prepare_pinning_certs.sh, so there's no new dependency and dart test works with no extra steps.

Verified locally: dart test test/pinning_test.dart and test/stacktrace_test.dart pass, dart format --set-exit-if-changed is clean, and dart analyze reports no issues. I also refreshed the PR description, which had gone stale after the earlier min-SDK and DioMixin reverts.

…emission-tls-pinning

# Conflicts:
#	dio/CHANGELOG.md
@github-actions

Copy link
Copy Markdown
Contributor

Code Coverage Report: Only Changed Files listed

Package Base Coverage New Coverage Difference
dio/lib/src/adapters/io_adapter.dart 🟢 89.41% 🟢 87.27% 🔴 -2.14%
Overall Coverage 🟢 85.54% 🟢 85.48% 🔴 -0.06%

Minimum allowed coverage is 0%, this run produced 85.48%

realmeylisdev and others added 12 commits November 20, 2026 14:16
…on-tls-pinning

# Conflicts:
#	dio/CHANGELOG.md
The connection factory added for cfug#2418 accepted every certificate during
the handshake (`onBadCertificate: (_) => true`) and left the decision to
`validateCertificate` alone. Any callback that is not a strict pin, such
as one that only logs and returns true or one that only checks
`cert != null`, turned the adapter into a client that trusts every
certificate: a man-in-the-middle presenting a self-signed certificate
received the full request, while on main the handshake fails.

Perform the handshake HttpClient performs itself for a client without a
custom SecurityContext or badCertificateCallback, so the default trust
store still has to accept the chain and the callback keeps its
documented contract of only seeing certificates that passed it. Drop the
`http/1.1` ALPN offer for the same reason; HttpClient does not send one.

The local tests now trust a generated localhost certificate through the
default context, assert that the first call happens before the server
receives the request, and add a regression test with an untrusted
certificate and an approving callback. The example no longer relies on
the bypass to reach wrong.host.badssl.com.

Co-Authored-By: Claude <noreply@anthropic.com>
The connection factory replaces HttpClient's own TLS handshake, but it
can neither read nor reproduce a SecurityContext or badCertificateCallback
set through `onHttpClientCreate` or `HttpOverrides`. Installing it on
those clients silently dropped that configuration: an mTLS context or a
callback accepting a development certificate stopped applying, and a
mock HttpClient injected through HttpOverrides failed with
`MissingStubError: 'connectionFactory='` as soon as `validateCertificate`
was set.

Install the factory only when the default HttpClient is used as is, and
keep validating on the response everywhere else, as before. This also
restores the original HttpOverrides-based badCertificate stack trace
test, which the factory had forced onto `createHttpClient`.

Tests cover all three customization points with a certificate only the
user's badCertificateCallback accepts, and the proxy tests now reach the
factory's proxy branch through `findProxyFromEnvironment` instead of a
client customized by `onHttpClientCreate`, which no longer gets the
factory.

Co-Authored-By: Claude <noreply@anthropic.com>
When HttpClient follows a redirect itself, it opens the connection to the
target through the connection factory while `request.close()` is pending.
A rejection there escaped `_fetch` as the private
`_BadCertificateException`, so callers got `DioExceptionType.unknown`
with an internal error type instead of `badCertificate`.

Translate it on the response future the same way as on `openUrl`.

Co-Authored-By: Claude <noreply@anthropic.com>
The README pinning example builds its own HttpClient with
`SecurityContext(withTrustedRoots: false)` and a badCertificateCallback
that accepts everything, then pins the leaf in `validateCertificate`.
With a custom HttpClient the callback only runs once the response has
arrived, so that setup sends every request to whichever server answers,
whatever certificate it presents.

Show the default adapter with `validateCertificate` instead, which is
checked before the request is sent and on top of the chain validation,
and say which setups are still only checked on the response. Servers
with self-signed certificates are pointed to the Certificate Authority
Verification methods that follow, which reject during the handshake.

Co-Authored-By: Claude <noreply@anthropic.com>
The Dart changelog confirms `ConnectionTask.fromSocket` arrived in 3.5.0
and `SecureSocket.startConnect` in 2.0.0, but not that `ConnectionTask`
became `final` in 3.0. State only what the current SDK declares.

Co-Authored-By: Claude <noreply@anthropic.com>
dio 5.10.0, 5.11.0 and 5.11.1 have shipped since the comment cited
5.9.x; the null certificate on plain HTTP is simply the existing
behavior.

Co-Authored-By: Claude <noreply@anthropic.com>
`HttpClient` only throws `Unsupported scheme` for URLs other than http
and https when no connection factory is set. With the factory installed,
a URL such as `wss://host:port/` reached the factory, which treated every
non-https scheme as plain HTTP and sent the request, headers included,
over an unencrypted socket. Redirects to such URLs were followed the same
way. On main both fail with an `ArgumentError` before anything is sent.

Throw the same `ArgumentError` at the top of the factory, before the
proxy branch.

Co-Authored-By: Claude <noreply@anthropic.com>
`HttpClient` only starts tracking a connection once the connection
factory has returned it, and the factory waits for the TLS handshake
before it does. During that wait neither `close()` nor the
`connectionTimeout` that `HttpClient` applies to `task.socket` could
reach the attempt:

- After `dio.close(force: true)`, a request whose handshake was still
  in progress was sent anyway once the handshake completed. On main
  the attempt is cancelled and nothing is sent.
- After `connectTimeout` fired, the attempt kept running. A blackholed
  connect stayed in SYN_SENT, and a handshake that completed later was
  still validated and kept open for a request that had already failed.

Track the attempts the factory is waiting for, cancel them in `close()`
and on timeout the way `HttpClient` cancels its own, and give up on a
handshake that completes after `close()`. The timeout error is the same
`SocketException` `HttpClient` throws, so it still maps to
`DioExceptionType.connectionTimeout`.

Co-Authored-By: Claude <noreply@anthropic.com>
The factory destroyed the socket when the callback returned false, but
not when it threw. The handshake was complete by then, so the
connection stayed open with nothing using it until the server dropped
it.

Destroy the socket before rethrowing.

Co-Authored-By: Claude <noreply@anthropic.com>
`_BadCertificateException` never leaves the adapter: both places that
can see it turn it into `DioException.badCertificate`, and HttpClient
does not treat `HandshakeException` specially. Implementing an SDK
exception only tied dio to every member a future SDK adds to it, and
its `toString` reported a handshake failure that did not happen.

Co-Authored-By: Claude <noreply@anthropic.com>
When HttpClient follows a redirect, the connection factory checks the
redirect target's connection, so `validateCertificate` receives the
target's host and port before sending. The response check keeps passing
the original request's host and port, as on main. A callback that
compares `host` can therefore reject a redirect that main accepted. Say
so in the doc comment and the CHANGELOG, and stop claiming in the
response-check comment that the same certificate was always approved
before, which does not hold for redirect hops.

Co-Authored-By: Claude <noreply@anthropic.com>
realmeylisdev and others added 2 commits November 20, 2026 15:19
The test only checked that the last certificate it saw was null, so it
would still pass if the factory also called the validator before sending
a plain HTTP request. Record every call and expect exactly one.

Co-Authored-By: Claude <noreply@anthropic.com>
On Dart 2.18 the close test failed most runs: the relay's own connection
to the TLS server, made by resolving `localhost`, failed with
`Connection reset by peer`, and the relay also left write errors on its
sockets unhandled. Connect to the address the server is bound to,
ignore write errors on a side the code under test has already torn
down, and stop forwarding once the client is gone.

Both tests now pass 10 out of 10 runs on Dart 2.18.7 and 3.13.7.

Co-Authored-By: Claude <noreply@anthropic.com>
@realmeylisdev

Copy link
Copy Markdown
Author

@AlexV525 I merged main and reworked this after finding problems in the previous revision while picking it back up:

  1. It weakened certificate validation. The connection factory accepted every certificate during the handshake (onBadCertificate: (_) => true) and left trust to validateCertificate alone. Any callback that is not a strict pin, for example one that logs and returns true, let a man-in-the-middle presenting a self-signed certificate receive the whole request, where on main the handshake fails. The factory now performs the same handshake HttpClient does, so the chain must still be trusted before the callback sees the leaf certificate.
  2. It could send requests unencrypted. HttpClient skips its Unsupported scheme check once a connection factory is set, and the factory treated every non-https scheme as plain HTTP. A wss:// URL, or a redirect to one, was sent with its headers over a plain socket. It now throws the same ArgumentError as main.
  3. It dropped TLS configuration it could not see. It was also installed on clients configured through onHttpClientCreate or HttpOverrides, silently bypassing their SecurityContext or badCertificateCallback. It also broke HttpOverrides-injected mocks with MissingStubError: 'connectionFactory=', which is why stacktrace_test.dart had been rewritten. The factory is now only installed when the adapter uses the default client as is, and stacktrace_test.dart is back to main's version.
  4. close() and connectTimeout stopped working during the handshake. HttpClient only tracks a connection once the factory returns it, so a request was still sent after close(force: true), and a timed-out connect stayed in SYN_SENT. The factory now cancels pending attempts the way HttpClient does.

Smaller changes:

  • A rejected redirect target now fails with badCertificate instead of unknown.
  • A throwing callback closes the connection.
  • The ALPN http/1.1 offer is gone, since HttpClient doesn't send one.
  • The internal error no longer implements HandshakeException.
  • The README pinning example (EN and ZH) no longer uses a custom HttpClient: with one, the check only runs after the request has been sent.
  • The CHANGELOG entry is now a single bullet under Unreleased.

One intended behavior change to check: for a followed redirect, the pre-send check receives the redirect target's host and port, while the response check keeps the original ones. It is documented on validateCertificate and in the CHANGELOG.

The description is updated with the resulting behavior and the verification. Could you take another look?

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.

validateCertificate callback fires after request body is sent, so true TLS-pinning is impossible

2 participants