Skip to content

[8.0.0 Cherry-pick] Connection encryption info – Slice B: negotiated mode and TLS protocol - #5102

Merged
priyankatiwari08 merged 2 commits into
dev/automation/pr-4830-to-8.0.0-v2from
dev/automation/pr-4831-to-8.0.0
Nov 23, 2026
Merged

priyankatiwari08 merged 2 commits into
dev/automation/pr-4830-to-8.0.0-v2from
dev/automation/pr-4831-to-8.0.0

Conversation

@github-actions

@github-actions github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Description

Important

DO NOT MERGE. The connection-encryption info feature (#2353) will land in release/8.0 as a whole, only after all slices have merged to main (remaining: Slice C #4835 and Slice D #4836). An earlier Slice A cherry-pick (#5037) was merged and then reverted by #5090 for this reason. This PR is up for review now so the 8.0 port is ready when the feature is complete.

8.0.0 cherry-pick of Slice B of the connection-encryption info feature: #4831 (main 0a46e011d), via git cherry-pick -x 0a46e011d on top of the Slice A port.

Populates the negotiated encryption mode and TLS protocol: adds EncryptionInfoAccumulator, wires it through SqlConnectionInternal/TdsParser, and adds unit and simulated-server tests.

Stack order (each PR is based on the previous one; merge bottom-up):

  1. [8.0.0 Cherry-pick] Connection encryption info - Slices A, B and C #5103 — Slice A: public API surface (Connection encryption info – Slice A: public API surface #4830) + Slice A review follow-up (Connection encryption info – Slice A review follow-up #5043), base release/8.0
  2. [8.0.0 Cherry-pick] Connection encryption info – Slice B: negotiated mode and TLS protocol #5102 — Slice B: negotiated mode and TLS protocol (Connection encryption info – Slice B: negotiated mode and TLS protocol #4831), base dev/automation/pr-4830-to-8.0.0-v2

A separate PR for the Slice A review follow-up (#5043) is not needed: #5037 already contained every #5043 change. git cherry-pick -x 8d330f187 on top of PR1 produced an empty commit, and all 15 files touched by #5043 are byte-identical between main@8d330f187 and this branch. (The earlier auto cherry-pick #5055 was closed unmerged.)

Conflicts

None. The original auto cherry-pick onto bare release/8.0 conflicted because Slice A was not present (it had been reverted). Rebased onto the Slice A port, the cherry-pick applies cleanly with no adaptation. The simulated-server Strict tests use TdsServerArguments.TlsFirst/ExpectTlsHandshakeFailure, which release/8.0 already has, so #5051 is not needed.

The branch was force-pushed (with lease against 011dd0813, the previous empty conflict-marker commit) and retargeted to the Slice A port branch.

Issues

Ports #4831 to release/8.0. Feature: #2353.

Testing

Build (0 warnings, 0 errors each):

  • dotnet build build.proj -t:BuildSqlClient (driver, ref, NotSupported) — succeeded, 0 warnings, 0 errors
  • dotnet build src\Microsoft.Data.SqlClient\tests\UnitTests\Microsoft.Data.SqlClient.UnitTests.csproj — succeeded, 0 warnings, 0 errors
  • dotnet build src\Microsoft.Data.SqlClient\tests\ManualTests\Microsoft.Data.SqlClient.ManualTests.csproj — succeeded, 0 warnings, 0 errors

Focused unit tests ($f = 'FullyQualifiedName~EncryptionInfo|FullyQualifiedName~EncryptionInfoAccumulator|FullyQualifiedName~ConnectionEncryptionInfo|FullyQualifiedName~SqlConnectionTests|FullyQualifiedName~SqlExceptionTest'):

  • dotnet test src\Microsoft.Data.SqlClient\tests\UnitTests\Microsoft.Data.SqlClient.UnitTests.csproj --no-build -f passed: 127/127, 0 failed, 0 skipped.0 --filter $f — passed: 127/127, 0 failed, 0 skipped
  • dotnet test src\Microsoft.Data.SqlClient\tests\UnitTests\Microsoft.Data.SqlClient.UnitTests.csproj --no-build -f passed: 132/132, 0 failed, 0 skipped --filter $f --blame-hang-timeout 5m (with a clean Windows PowerShell PSModulePath) — passed: 132/132, 0 failed, 0 skipped

Guidelines

Please review the contribution guidelines before submitting a pull request:

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@priyankatiwari08
priyankatiwari08 marked this pull request as ready for review November 18, 2026 07:32
Copilot AI balanced review requested due to automatic review settings November 18, 2026 07:32

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot wasn't able to review any files in this pull request. Check if the Files changed in this pull request are included in default exclusions.

#4831)

* Capture negotiated encryption mode and TLS protocol for EncryptionInfo (Slice B)

Records the final negotiated encryption mode and TLS protocol per physical
login attempt, publishes an immutable snapshot to SqlConnection.EncryptionInfo
on successful open, and attaches the terminal attempt's values to
SqlException.EncryptionInfo when open fails.

Part of #2353.

Co-authored-by: Copilot App <[email protected]>

* Discard negotiated encryption details on deferred TLS validation failure

Native SNI (Schannel) defers server certificate verification, so EnableSsl
succeeds and an untrusted certificate only surfaces as an SSL provider error
on the LOGIN7 write. Discard the mode/protocol recorded for the in-progress
login attempt when ProcessSNIError sees an SSL provider error, so
SqlException.EncryptionInfo no longer reports a negotiated mode for a TLS
session that was never established. Managed SNI is unaffected.

Part of #2353.

Co-authored-by: Copilot App <[email protected]>

* Clear only negotiated mode/protocol on SSL provider login errors

Preserve other capture state (certificate details from Slices C/D) when Native
SNI's deferred certificate validation fails on the LOGIN7 write.

Co-authored-by: Copilot App <[email protected]>

* Clarify that the SSL-error reset covers only mode and protocol

Co-authored-by: Copilot App <[email protected]>

* Keep observed mode/protocol on TLS validation failure (G2/D15)

Replace ClearNegotiated with DiscardUnobservedNegotiation: on SSL-provider login errors the mode is dropped only when no protocol was observed. Failed EnableSsl attempts record the mode only when a protocol was observed. Certificate fields are untouched.

Co-authored-by: Copilot App <[email protected]>

* Add negotiated cipher suite capture plumbing (Slice B)

EncryptionInfoCapture.RecordCipherSuite(int) is the single recording point
for NegotiatedCipherSuite, used by Slice C (managed SslStream) and Slice D
(native SNI). The value resets with the other fields per attempt, flows
into SqlConnection and SqlException snapshots, and is kept on failure like
the protocol; DiscardUnobservedNegotiation never clears or invents it.

Co-authored-by: Copilot App <[email protected]>

* Align EncryptionInfo simulator tests with stricter TDS server fault reporting

Main's #4891 makes the simulated server rethrow connection faults on Stop. Use
Encryption=None for the pre-login rejection case (as ConnectionTests does) and
mark the untrusted-certificate case as an expected TLS handshake failure.

Co-authored-by: Copilot App <[email protected]>

* Adapt Slice B tests and design note to NegotiatedCipherSuiteId

Assert the numeric cipher-suite ID through the public NegotiatedCipherSuiteId property and cover the .NET-only TlsCipherSuite surface under #if NET.

Co-authored-by: Copilot App <[email protected]>

* Replace removed certificate hash references with full certificate API (Slice B)

Pass presentedServerCertificate: null from EncryptionInfoCapture and assert the certificate is unavailable through PresentedServerCertificateRawData and GetServerCertificate().

Co-authored-by: Copilot App <[email protected]>

* Address #4831 review feedback

- Sort EncryptionInfoCapture members; use auto-properties for capture/snapshot.
- Replace SSL provider magic number with TdsEnums.SNI_SSL_PROVIDER.
- Reset capture on instance-failure reconnect.
- Restructure tests per testing instructions; split sync/async scenarios.
- Untrusted-certificate failure asserts no inferred mode/protocol.
- Clarify Strict/PRELOGIN failure semantics in design note.

Co-authored-by: Copilot App <[email protected]>

* Document EncryptionInfo failure scope: post-login enlistment keeps Empty

Co-authored-by: Copilot App <[email protected]>

* Release encryption capture on non-pooled auto-enlist failure; clarify design note failure rules

Co-authored-by: Copilot App <[email protected]>

* Add reconnect, enlistment and ManualTests coverage for encryption info

- Simulated-server tests (sync and async): reconnect after a server drop
  publishes a new snapshot; non-pooled and pooled DTC enlistment failures
  leave SqlException.EncryptionInfo empty.
- ManualTests against SQL Server: Optional, Mandatory, Strict and a login
  failure (sync and async), close keeps a held snapshot, pooled reuse.
- Restore the UTF-8 BOM in SqlException.xml.

Co-authored-by: Copilot App <[email protected]>

* Run encryption info ManualTests in CI and harden enlistment teardown assert

Add the Set=1 trait so the PR pipeline selects the ConnectionEncryptionInfo ManualTests, and assert on the base exception during simulated server teardown so both teardown orderings pass.

Co-authored-by: Copilot App <[email protected]>

* Adapt Slice B to the Slice A review follow-up (#5043)

Convert the captured cipher suite to TlsCipherSuite? at the snapshot boundary
on .NET, and use the shared EncryptionInfoTestData helpers in B's tests.
The SqlException attach test is covered by SqlExceptionTests.

Co-authored-by: Copilot App <[email protected]>

* Address Slice B review: accumulator, TdsParser rules, SqlException contract

- Rename EncryptionInfoCapture to EncryptionInfoAccumulator (file, field,
  property, tests and docs).
- Make the accumulator a plain holder (Mode, Protocol, CipherSuite,
  HasValues, Reset, ToSnapshot). Move the recording rules into TdsParser:
  RecordEncryption (SslProtocols.None maps to null),
  RecordModeIfProtocolObserved, DiscardUnobservedNegotiation and
  RecordCipherSuite. Rule tests move to Parser/TdsParserTests.
- On .NET, store the cipher suite as TlsCipherSuite and record it with
  RecordCipherSuite(TlsCipherSuite); .NET Framework keeps the
  range-checked int.
- Use target-typed new() where the type is obvious.
- Add a dedicated SqlException catch in the login path that attaches the
  encryption info; AttachEncryptionInfo now takes SqlException.
- A SqlException thrown while opening carries the encryption info whenever
  any is available, including transaction enlistment. Pooled checkout
  enlistment failures attach the physical connection's published snapshot.
- Update the SqlException.EncryptionInfo docs and design note.

Co-authored-by: Copilot App <[email protected]>

* Clarify SqlException.EncryptionInfo scope in docs

State that only exceptions thrown while opening a connection carry
encryption information, that other operations return an empty snapshot,
and that pooled-connection enlistment failures carry the values recorded
at the physical connection's earlier login. Remove a duplicated sentence
about deserialized exceptions.

Co-authored-by: Copilot App <[email protected]>

* Address review: record mode when selected, normalize in accumulator setters

- Protocol setter maps SslProtocols.None to null; netfx CipherSuite setter
  discards values outside the TLS cipher-suite range.
- Remove RecordEncryption, RecordCipherSuite, RecordModeIfProtocolObserved,
  DiscardUnobservedNegotiation and the ProcessSNIError mode erasure; TdsParser
  assigns accumulator properties directly.
- Record the encryption mode as soon as PRELOGIN selects it (or before the
  Strict TLS-first handshake), independent of the TLS outcome.
- Keep the single-attach assert in AttachPublishedEncryptionInfo, drop the guard.
- Move rule tests to accumulator setter tests; update docs and design note.

Co-authored-by: Copilot App <[email protected]>

* Address Paul's review: PRELOGIN encryption negotiation, Strict tests

- Move the PRELOGIN ENCRYPT negotiation into NegotiateEncryptionOption, which
  returns the negotiated option; GetEncryptionMode maps it to the reported mode.
- Add TLS-first (TDS 8) support to the simulated TDS server and Strict
  success/failure tests (sync and async).
- Rewrite accumulator setter tests: all modes, all reported protocols via
  Enum.GetValues, other-properties-unaffected asserts, all property subsets.
- Remove manual ConnectionEncryptionInfo tests now covered by simulated tests.
- Run ResetSessionIsolationLevel inside the Activate attach try, with tests.

Co-authored-by: Copilot App <[email protected]>

* Correct Optional + ENCRYPT_ON row in the mode mapping table

With Encrypt=Optional the client sends ENCRYPT_OFF, and a server reply of
ENCRYPT_ON leaves the option OFF, so no TLS runs and the mode is None. Only
ENCRYPT_REQ upgrades the session to Full.

Co-authored-by: Copilot App <[email protected]>

---------

Co-authored-by: Copilot App <[email protected]>
(cherry picked from commit 0a46e01)
@priyankatiwari08
priyankatiwari08 force-pushed the dev/automation/pr-4831-to-8.0.0 branch from 011dd08 to 8fcb746 Compare November 18, 2026 07:46
@priyankatiwari08
priyankatiwari08 requested a review from a team as a code owner November 18, 2026 07:46
@priyankatiwari08 priyankatiwari08 changed the title [8.0.0 Cherry-pick - CONFLICTS] Connection encryption info – Slice B: negotiated mode and TLS protocol [DO NOT MERGE] [8.0.0 Cherry-pick] Connection encryption info – Slice B: negotiated mode and TLS protocol Nov 18, 2026
@priyankatiwari08
priyankatiwari08 changed the base branch from release/8.0 to dev/automation/pr-4830-to-8.0.0-v2 November 18, 2026 07:47

@priyankatiwari08 priyankatiwari08 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks good — patch-identical to #4831 (git patch-id match).

@priyankatiwari08 priyankatiwari08 changed the title [DO NOT MERGE] [8.0.0 Cherry-pick] Connection encryption info – Slice B: negotiated mode and TLS protocol [8.0.0 Cherry-pick] Connection encryption info – Slice B: negotiated mode and TLS protocol Nov 23, 2026
…#4835) (#5126)

* Connection encryption info: capture Managed SNI server certificate details (Slice C)

Capture SHA-256 of the presented leaf certificate, the effective SqlClient
validation verdict, and the original callback chain status flags in Managed
SNI, and flow them into the per-attempt encryption info capture so both
SqlConnection.EncryptionInfo and SqlException.EncryptionInfo report them.
No trust decisions, messages, or tracing are changed.

Part of #2353



* Keep Managed SNI certificate verdict when the host name check throws

Named pipes validate against the target '.', which X509Certificate2.MatchesHostname
rejects with ArgumentException before the final verdict is recorded. Record the
errors already established (e.g. ChainError and callback chain status) before the
host name check so the capture survives. The exception is not caught or changed.



* Managed SNI: capture negotiated cipher suite

Record (int)SslStream.NegotiatedCipherSuite after the handshake (authoritative)
and inside the certificate validation callback (adopt-if-none), so failed
certificate validation keeps the observed suite. TCP and named-pipe handles;
MARS passes through. Reads are exception-safe; 0 is treated as unavailable.



* Mark Managed SNI capture simulator failures as expected TLS handshake failures

Main's #4891 makes the TDS simulator rethrow connection faults on Stop. The
untrusted, host-name-mismatch and pin-mismatch capture tests now set
ExpectTlsHandshakeFailure so the server treats the client's rejection as
expected. Test-only change.



* Adapt Slice C tests and design note to NegotiatedCipherSuiteId

Assert the public CLS-compliant NegotiatedCipherSuiteId property in the Managed SNI simulator tests and describe the two-property shape in the Managed capture section.



* Capture the presented server certificate instead of its hash (Managed SNI)

Managed SNI now captures a copy of the presented leaf certificate's DER
encoding (GetRawCertData) instead of its SHA-256 hash, and passes it to the
snapshot so SqlConnectionEncryptionInfo.GetServerCertificate() can return it.
Certificates over 64 KiB are not captured, and the first certificate
presented in an attempt is kept. Capture still happens in the validation
callback's finally block, so it is present on TrustServerCertificate bypass
and on validation failure.



* Address review feedback on Managed SNI certificate capture

- Reset the attempt's encryption info capture when Connect retries after an
  instance-resolution failure, so only the retried attempt's values publish.
- Document that an observed protocol is kept after a failure.
- Compare capture outcomes against an independent restatement of the
  validation rules instead of the legacy overload.
- Add routed single-login tests proving only the terminal attempt's certificate
  is published, including a terminal attempt that fails before TLS.
- Add XML summaries and Arrange/Act/Assert structure to the capture tests.



* Split Managed SNI capture simulator tests into Open and OpenAsync tests

Replace the bool-async theories with separate Open_ and OpenAsync_ tests that call each API directly, sharing setup and scenario assertion helpers.



* Align native SNI failure note with Managed SNI capture



* Adapt reconnect tests to Managed SNI certificate capture

Slice B's reconnect tests asserted that certificate fields are null. Managed SNI now records the presented certificate under TrustServerCertificate, so use the bypass assertion.



* Adapt Slice C tests to the Slice A review follow-up helpers

Use the shared EncryptionInfoTestData.AssertEmpty helper and value-returning Assert.NotNull instead of ad-hoc IsEmpty checks and null-forgiving operators. Test-only; no product change.



* Adapt Slice C to the Slice B accumulator design

Move C's certificate-field tests into EncryptionInfoAccumulatorTests using the
accumulator's settable properties, drop the RecordServerCertificate-based tests,
remove the inherited AssertCertificateFieldsNull use from the enlistment test
(Managed SNI now records the presented certificate), and update the remaining
EncryptionInfoCapture references in docs and comments.



* Address Slice C review feedback

- Rename ServerCertificateCapture to ServerCertificate, with matching handle,
  state-object, factory, file and test names.
- Document MaxRawCertificateSize as 64 KiB (65,536 bytes) and sort properties.
- Document SNI handle overrides with inheritdoc; make SniMarsConnection
  pass-throughs internal and document them.
- Use a volatile field for the captured certificate on TCP and NP handles.
- Use a using declaration in SniNpHandle.ValidateServerCertificate.
- Replace the accumulator property-subset theory with the existing
  per-property tests.



* Address Paul's review: TlsHandshakeInfo record as single source of truth

- Rename ServerCertificate to TlsHandshakeInfo (DerBytes, MaxDerBytesSize,
  TlsCipherSuite? CipherSuite on .NET); GetTlsHandshakeInfo() on state objects.
- Remove NegotiatedCipherSuite from SNI handles and GetNegotiatedCipherSuite;
  EnableSsl assigns all record values directly, without precedence logic.
- Fold helpers into CreateTlsHandshakeInfo(SslStream, ...) and GetChainStatus;
  only CryptographicException is caught; latest callback record wins.
- Rename accumulator ServerCertificateRawData to ServerCertificateDerBytes.
- Enable nullable for new code, simplify conditionals, update design note.
- Replace synthetic tests with in-callback loopback handshake tests.



* Explain the 64 KiB certificate capture limit in the design note



* Address Slice C TLS diagnostics review feedback




* Scope Managed SNI switch to each certificate capture test




* Record Managed SNI handshake directly into the attempt accumulator

Pass the per-attempt EncryptionInfoAccumulator into EnableSsl and
register a per-handshake certificate validation callback through
SslClientAuthenticationOptions. The callback captures a local reference
that is cleared in finally, so the handle keeps no handshake state and a
late callback cannot write to the attempt.

SniCommon.RecordTlsHandshake writes the certificate, chain status,
cipher suite, protocol and validation errors straight to the
accumulator, which owns normalization and the 64 KiB cap. This removes
TlsHandshakeInfo and the copy step in TdsParser.EnableSsl.




* Avoid copying an oversized Managed SNI server certificate

Read the presented certificate through X509Certificate2.RawDataMemory
and add EncryptionInfoAccumulator.SetServerCertificateDerBytes, which
copies the span only when it is within the 64 KiB cap. An oversized
certificate is now never copied, rather than copied and then dropped.




* Share the accumulator's server certificate copy with the snapshot

ServerCertificateDerBytes is now ReadOnlyMemory<byte>? and its setter
applies the size cap and stores the accumulator's own copy, replacing
SetServerCertificateDerBytes. SqlConnectionEncryptionInfo retains that
never-mutated copy instead of cloning it, so ToSnapshot copies nothing.




---------



(cherry picked from commit ce73774)

Co-authored-by: priyankatiwari08 <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e
@priyankatiwari08
priyankatiwari08 merged commit d118e2f into dev/automation/pr-4830-to-8.0.0-v2 Nov 23, 2026
4 checks passed
@priyankatiwari08
priyankatiwari08 deleted the dev/automation/pr-4831-to-8.0.0 branch November 23, 2026 14:28
@github-project-automation github-project-automation Bot moved this from To triage to Done in SqlClient Board Nov 23, 2026
@mdaigle mdaigle mentioned this pull request Nov 24, 2026
3 of 4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants