Skip to content

[8.0.0 Cherry-pick] Connection encryption info - Slices A, B and C - #5103

Closed
priyankatiwari08 wants to merge 2 commits into
release/8.0from
dev/automation/pr-4830-to-8.0.0-v2
Closed

priyankatiwari08 wants to merge 2 commits into
release/8.0from
dev/automation/pr-4830-to-8.0.0-v2

Conversation

@priyankatiwari08

@priyankatiwari08 priyankatiwari08 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Description

8.0.0 port of the connection-encryption info feature (#2353): Slices A, B and C, all merged to main.

Slice main PR main commit
A: public API surface #4830 d8a60de2f
A: review follow-up #5043 8d330f187
B: negotiated mode and TLS protocol #4831 0a46e011d
C: managed SNI certificate capture #4835 ce73774d1

Branch contents on top of release/8.0:

Verification: all 41 files touched by the four main commits are byte-identical between main and this branch, except one line in TdsParser.cs. That line is an unrelated Always Encrypted change that exists only on main, so it is not part of this feature.

Slice D (#4836, native SNI interop) is intentionally excluded. It depends on a native SNI package that will not ship in 8.0.0. Until then, native SNI connections report a null server certificate and validation info, as documented.

Earlier attempt: #5037, merged and then reverted by #5090 so that the feature lands as a whole.

Issues

Ports #4830, #5043, #4831 and #4835 to release/8.0. Feature: #2353.

Testing

Guidelines

Please review the contribution guidelines before submitting a pull request:

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.

🔵 Needs a closer look

This API-only slice has an explicit merge hold pending maintainer confirmation of complete-feature integration, coordinated release readiness, and managed/native SNI validation.

No open issues 🎉

What changed in this PR

Reapplies the Slice A public API and review follow-up for connection-encryption diagnostics to release/8.0, supporting #2353. This slice exposes empty snapshots; later slices populate negotiated encryption and certificate details. The PR remains marked DO NOT MERGE until the complete feature is ready.

Changes:

  • Adds immutable encryption snapshots, encryption-mode and validation-error enums, and connection/exception accessors.
  • Updates reference APIs and unsupported-platform generation for the new surface.
  • Adds API documentation and tests for snapshot semantics, certificate ownership, cloning, and serialization.
File Description
src/​Microsoft.Data.SqlClient/​tests/​UnitTests/​Utilities/​EncryptionInfoTestData.cs Provides shared certificate data and snapshot assertions.
src/​Microsoft.Data.SqlClient/​tests/​UnitTests/​Microsoft/​Data/​SqlClient/​SqlExceptionTests.cs Tests snapshot access, cloning, serialization, and unchanged messages.
src/​Microsoft.Data.SqlClient/​tests/​UnitTests/​Microsoft/​Data/​SqlClient/​SqlConnectionTests.cs Tests empty snapshots before opening and after close/disposal.
src/​Microsoft.Data.SqlClient/​tests/​UnitTests/​Microsoft/​Data/​SqlClient/​SqlConnectionEncryptionInfoTests.cs Tests snapshot contracts, cipher values, and certificate isolation.
src/​Microsoft.Data.SqlClient/​src/​Microsoft/​Data/​SqlClient/​SqlServerCertificateValidationErrors.cs Defines certificate-validation error flags.
src/​Microsoft.Data.SqlClient/​src/​Microsoft/​Data/​SqlClient/​SqlException.cs Adds a non-serialized snapshot preserved by internal cloning.
src/​Microsoft.Data.SqlClient/​src/​Microsoft/​Data/​SqlClient/​SqlConnectionEncryptionMode.cs Defines negotiated encryption modes.
src/​Microsoft.Data.SqlClient/​src/​Microsoft/​Data/​SqlClient/​SqlConnectionEncryptionInfo.cs Implements immutable snapshots and caller-owned certificate retrieval.
src/​Microsoft.Data.SqlClient/​src/​Microsoft/​Data/​SqlClient/​SqlConnection.cs Exposes the empty encryption snapshot accessor.
src/​Microsoft.Data.SqlClient/​ref/​Microsoft.Data.SqlClient.cs Declares the new public API across target frameworks.
src/​Microsoft.Data.SqlClient/​notsupported/​Microsoft.Data.SqlClient.csproj Configures GenAPI header and attribute exclusions.
src/​Microsoft.Data.SqlClient/​notsupported/​GenApiHeader.txt Enables nullable annotations in generated stubs.
src/​Microsoft.Data.SqlClient/​notsupported/​GenApiExcludeAttributes.txt Excludes compiler-owned nullable metadata attributes.
doc/​snippets/​Microsoft.Data.SqlClient/​SqlServerCertificateValidationErrors.xml Documents validation-error flag meanings.
doc/​snippets/​Microsoft.Data.SqlClient/​SqlException.xml Documents exception snapshot availability and serialization behavior.
doc/​snippets/​Microsoft.Data.SqlClient/​SqlConnectionEncryptionMode.xml Documents negotiated encryption modes.
doc/​snippets/​Microsoft.Data.SqlClient/​SqlConnectionEncryptionInfo.xml Documents snapshot values, null semantics, and certificate ownership.
doc/​snippets/​Microsoft.Data.SqlClient/​SqlConnection.xml Documents the intended connection snapshot lifecycle.
doc/​design-notes/​2353-connection-encryption-info.md Records the API design, diagnostic guarantees, and implementation slices.

Review effort: Balanced

@codecov

codecov Bot commented Nov 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 72.43%. Comparing base (463a45c) to head (3d57949).
⚠️ Report is 13 commits behind head on release/8.0.

Additional details and impacted files
@@               Coverage Diff               @@
##           release/8.0    #5103      +/-   ##
===============================================
+ Coverage        68.97%   72.43%   +3.46%     
===============================================
  Files              314      314              
  Lines            45857    71062   +25205     
===============================================
+ Hits             31629    51474   +19845     
- Misses           14228    19588    +5360     
Flag Coverage Δ
CI-SqlClient ?
sqlclient-pr 72.43% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

#4831) (#5102)

* 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.



* 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.



* 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.



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



* 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.



* 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.



* 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.



* 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.



* 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().



* 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.



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



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



* 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.



* 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.



* 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.



* 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.



* 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.



* 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.



* 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.



* 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.



---------


(cherry picked from commit 0a46e01)

Co-authored-by: priyankatiwari08 <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 23, 2026 14:28

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.

🟡 Changes recommended

Runtime changes exceed the documented API-only scope, requiring aligned description, stack order, and validation results, and the new exception message needs localization.

2 open issues

Review effort: Balanced

@priyankatiwari08 priyankatiwari08 changed the title [DO NOT MERGE] [8.0.0 Cherry-pick] Connection encryption info – Slice A: public API surface [8.0.0 Cherry-pick] Connection encryption info - Slices A, B and C Nov 23, 2026
@priyankatiwari08
priyankatiwari08 marked this pull request as ready for review November 23, 2026 14:37
@github-project-automation github-project-automation Bot moved this from To triage to Done in SqlClient Board Nov 24, 2026
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.

4 participants