Repository navigation
🐛 Fix validateCertificate to fire pre-emission for TLS pinning - #2512
realmeylisdev wants to merge 19 commits into
Conversation
`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.
There was a problem hiding this comment.
Please revert since we don't match the requirement here.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 atconnection_manager_imp.dart:133-150. This PR bringsIOHttpClientAdapterto parity.plugins/web_adapter— novalidateCertificatefield exists on the web adapter; TLS is browser-controlled and not introspectable from Dart. Not applicable.plugins/native_dio_adapter— delegates tocronet_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.
There was a problem hiding this comment.
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+.
| } | ||
| return ss; | ||
| }(); | ||
| return ConnectionTask.fromSocket(socketFuture, () {}); |
There was a problem hiding this comment.
The implementation of ConnectionTask is simple, try to copy it into the code base to avoid bumping the SDK version too high.
There was a problem hiding this comment.
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.
|
Pushed review fixes (23aa0c0):
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.
|
Still not covering previous comments |
|
@AlexV525 thanks for the review. Pushed 8a66e1e addressing all four points: 1. 2. 3.
The fix is to use Diff for the affected branch is small:
4. "What about other adapters?" ✅ The fix is intentionally scoped to
Happy to add a one-line cross-reference comment in All 222 tests pass; |
|
Tests didn't seem passing. |
|
@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.
|
@AlexV525 thanks — picked this back up. Both points are addressed in a7372d3. 1. CI / failing tests. Two distinct causes against the previous HEAD:
2. Test certs. Agreed — no private key should live in git. The committed Verified locally: |
…emission-tls-pinning # Conflicts: # dio/CHANGELOG.md
Code Coverage Report: Only Changed Files listed
Minimum allowed coverage is |
…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>
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>
|
@AlexV525 I merged
Smaller changes:
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 The description is updated with the resulting behavior and the verification. Could you take another look? |
Closes #2418.
IOHttpClientAdapter.validateCertificateonly 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.connectionFactorythat callsvalidateCertificateafter the TLS handshake and beforeHttpClientwrites anything, whenever the adapter uses the defaultHttpClientas is. A rejected certificate closes the connection, and the request fails withDioException.badCertificatewithout being sent.@AlexV525, flagging this per AGENTS.md: it changes certificate pinning behavior and touches connection timeout and cancellation handling.
Behavior
HttpClientperforms itself when it has no customSecurityContextorbadCertificateCallback. The default trust store still has to accept the chain beforevalidateCertificatesees the leaf certificate, as the doc comment has always said.HttpClient's handshake and cannot read aSecurityContextorbadCertificateCallbackconfigured elsewhere. So it is installed only whencreateHttpClientandonHttpClientCreateare both unset and noHttpOverridesare active when the client is created. Every other setup behaves as it does today.validateCertificatestill 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 (whereHttpClientperforms theCONNECTand 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 test2 requests == 2 approvalsis replaced by a local test that expects 3 calls for 2 pooled requests.HttpClientfollows 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 withbadCertificateand receives nothing. A callback that compareshostcan therefore reject a redirect that it used to accept. This is documented onvalidateCertificateand in the CHANGELOG.HttpClient:HttpClientonly rejects schemes other thanhttpandhttpswhen no factory is set, so the factory throws the sameArgumentErroritself.close(). While the factory waits for the handshake, it appliesHttpClient.connectionTimeoutand cancels the attempt onclose(), asHttpClientdoes for its own pending connections.HttpClientwithwithTrustedRoots: falseand abadCertificateCallbackthat accepts everything. With a custom client,validateCertificateonly 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 doesexample_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) andHttpClient.connectionFactory(Dart 2.17) predate the 2.18 lower bound.Verification
dio/test/pinning_test.dartstarts local TLS servers using throwawaylocalhostcertificates thatopensslgenerates 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:main, where the server receives the body);createHttpClient,onHttpClientCreateandHttpOverrideskeep their ownbadCertificateCallback;badCertificate;wss://URL fails withArgumentErrorwithout sending anything;close()during the handshake sends nothing;connectTimeoutis not validated;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.dartis unchanged frommain.Locally,
dart formatanddart analyze --fatal-infosare 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, whichexception_test.dart'sallow badsslhits onmainas well. Thetls-tagged pinning tests pass with-P all.Known limitations
HttpOverridesadded after the client was created makefindProxyreturn a proxy afterDIRECT,HttpClientretries 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
mainbranch to avoid conflicts (via merge from master or rebase)CHANGELOG.mdin the corresponding packageAI 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.