Skip to content

Stabilize simulated server tests while retaining quarantine - #4891

Merged
mdaigle merged 8 commits into
mainfrom
dev/mdaigle/simulatedserver-flakiness
Oct 23, 2026
Merged

mdaigle merged 8 commits into
mainfrom
dev/mdaigle/simulatedserver-flakiness

Conversation

@mdaigle

@mdaigle mdaigle commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Description

Remove several sources of nondeterminism from the TDS simulator and its connection/retry/failover tests, without changing production driver behavior.

  • Run blocking connection workers on dedicated threads, register them before starting, drain them during shutdown, and propagate unexpected processing/cleanup failures instead of only logging them.
  • Reserve transient SQL-error and delay quotas atomically before generating responses or blocking. Canceled delays must not produce late responses.
  • Replace timing-dependent network-failure scenarios with explicit pre-login gates. Keep the listener and existing sessions alive so failures cannot drift into Login7 or depend on ephemeral-port reuse.
  • Isolate scenario pools, clear only the owned pool, and assert physical connection reuse/invalidation through ClientConnectionId. Expand the affected scenarios' sync/async coverage from 20 to 29 data cases.
  • Correct simulator encryption resolution when encryption metadata is omitted, add deterministic lifecycle/fault-injection regressions, and document simulator testing practices in TESTGUIDE.md.

Retain quarantine: all nine originally flaky methods remain marked [Trait("category", "flaky")], including their expanded 29 data cases. Let the existing flaky-test jobs accumulate longer-term stability evidence; removing these tags will be a separate follow-up. The new deterministic lifecycle regressions remain in the ordinary suite. Success in ordinary jobs alone is not evidence that the quarantined cases are clean.

No production APIs, package dependencies, or localization resources change. The temporary focused CI runner, pipeline stage, and mode-proof test were removed after validation; the final diff contains no pipeline changes.

Issues

Related history: #4467 and #4873. No issue is being closed by this PR.

Testing

Added controlled regressions for dedicated worker scheduling, concurrent ownership/rearming of one-shot SQL faults, delay ownership/cancellation, repeated server lifetimes, processing/cleanup failure propagation, and missing encryption metadata. The worker-scheduling and one-shot-fault regressions failed against the original harness and passed after repair. Existing endpoint, SQL-error, and pool assertions remain strict; there are no automatic test retries or retry-based masking.

Repeated sqlclient-pr validation

Five consecutive focused runs passed: 184487, 184488, 184489, 184490, and 184491, on candidate bebe79d5b.

Each run executed 73 selected cases 20 times on Windows net462/native SNI, Windows net10.0/native SNI, Windows net10.0/managed SNI, and Linux net10.0/managed SNI. All 400 TRX files were checked: 29,200 passes, zero failures/skips, every job on attempt 1. Each selected case executed 100 times per framework/SNI leg across the five runs.

After restoring the normal pipeline, all 24 unit-test jobs across eight normal runs of 53aa9c5df passed, with 6,040 simulator executions and zero simulator failures/skips, verified from TRX files. Overall pipeline results were mixed:

Runs Overall result
184501, 184516, 184517, 184526 Entire pipeline passed.
184502 Failed outside the simulator suite: distributed-transaction promotion unsupported on Linux.
184503 Failed outside the simulator suite: Windows certificate generation / SQLSERVERAGENT service-control failures.
184518 Failed outside the simulator suite: real-server Linux reader/streaming timeouts and a closed connection.
184540 Failed outside the simulator suite: Azure SQL schema-test deadlocks.

The extra goal of three consecutive entirely green normal pipelines was not achieved and is not claimed. These unrelated integration failures were not hidden, excluded, retried, or changed.

The historical CI runs preceded restoration of the flaky traits. Commit 9c210ae4f restores only nine annotations; it does not change the validated harness or test bodies. Future ordinary runs intentionally exclude these cases; observe their quarantine jobs before unquarantining them.

Final quarantine-selection checks

Both discovery commands succeeded and selected exactly 29 cases across the original nine methods:

dotnet test src\Microsoft.Data.SqlClient\tests\UnitTests\Microsoft.Data.SqlClient.UnitTests.csproj --no-restore -f net10.0 --list-tests --filter "FullyQualifiedName~SimulatedServerTests&category=flaky" -v:q
dotnet test src\Microsoft.Data.SqlClient\tests\UnitTests\Microsoft.Data.SqlClient.UnitTests.csproj --no-restore -f net462 --list-tests --filter "FullyQualifiedName~SimulatedServerTests&category=flaky" -v:q

The selected tests passed twice consecutively on each framework after restoring the traits: 29 passed, zero failed/skipped per execution. The final executions used:

dotnet test src\Microsoft.Data.SqlClient\tests\UnitTests\Microsoft.Data.SqlClient.UnitTests.csproj --no-build --no-restore -f net10.0 --filter "FullyQualifiedName~SimulatedServerTests&category=flaky" -v:q
dotnet test src\Microsoft.Data.SqlClient\tests\UnitTests\Microsoft.Data.SqlClient.UnitTests.csproj --no-build --no-restore -f net462 --filter "FullyQualifiedName~SimulatedServerTests&category=flaky" -v:q

Ordinary selection succeeded with 223 simulator cases, including all 10 lifecycle cases, with no overlap with the 29 quarantined cases:

dotnet test src\Microsoft.Data.SqlClient\tests\UnitTests\Microsoft.Data.SqlClient.UnitTests.csproj --no-build --no-restore -f net10.0 --list-tests --filter "FullyQualifiedName~SimulatedServerTests&category!=flaky" -v:q

git diff --check 29c804ee9 passed. A comparison against the base verified that exactly the original three ConnectionTests methods and six ConnectionFailoverTests methods remain quarantined. No additional methods were quarantined. No new real-SQL-Server integration scenario is required for these simulator-only changes; broader integration runs and their failures are disclosed above.

Guidelines

Please review the contribution guidelines before submitting a pull request:

  • Contributing

  • Code of Conduct

  • Best Practices

  • Coding Style

  • Review Process

  • Tests added or updated.

  • Public API changes documented (not applicable: no public API changes).

  • Verified against customer repro (not applicable: simulator-only defects reproduced by controlled regressions; no customer repro supplied).

  • Ensure no breaking changes introduced (no production driver changes).

mdaigle and others added 4 commits October 20, 2026 12:14
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 67997771-8f8e-4c62-b790-0111accb47f4
Isolate blocking protocol workers, reserve one-shot faults before responses, gate pre-login failures, and isolate scenario pools with physical-connection assertions. Add lifecycle and encryption regressions and restore quarantined sync/async coverage.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 67997771-8f8e-4c62-b790-0111accb47f4
Remove temporary focused pipeline and mode-proof test after five clean runs, each exercising 73 cases twenty times on all four framework/SNI legs. Restore the original pipeline without retained configuration changes.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 67997771-8f8e-4c62-b790-0111accb47f4
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 67997771-8f8e-4c62-b790-0111accb47f4
@mdaigle
mdaigle requested a review from a team as a code owner October 21, 2026 16:19
Copilot AI balanced review requested due to automatic review settings October 21, 2026 16:19
@github-project-automation github-project-automation Bot moved this to To triage in SqlClient Board Oct 21, 2026
@mdaigle mdaigle added this to the 8.1.0-preview1 milestone Oct 21, 2026

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

Expected TLS rejections can escape during teardown, and one pool-preservation assertion does not verify reuse of the pre-fault connection.

2 open issues
What changed in this PR

Stabilizes the TDS simulator and connection tests without changing production driver behavior, while retaining quarantine for the original nine flaky methods.

Changes:

  • Adds dedicated workers, shutdown error propagation, and atomic fault budgets.
  • Uses pre-login gates and isolated pools with physical-connection assertions.
  • Adds lifecycle regressions and testing guidance.
File Description
TESTGUIDE.md Documents simulator testing practices.
src/​Microsoft.Data.SqlClient/​tests/​UnitTests/​SimulatedServerTests/​ServerLifecycleTests.cs Adds lifecycle and fault-ownership regressions.
src/​Microsoft.Data.SqlClient/​tests/​UnitTests/​SimulatedServerTests/​Fixtures/​SimulatedServerPoolScope.cs Isolates and clears scenario pools.
src/​Microsoft.Data.SqlClient/​tests/​UnitTests/​SimulatedServerTests/​Fixtures/​GatedTdsServer.cs Adds explicit pre-login gates.
src/​Microsoft.Data.SqlClient/​tests/​UnitTests/​SimulatedServerTests/​ConnectionTests.cs Stabilizes connection scenarios while retaining quarantine.
src/​Microsoft.Data.SqlClient/​tests/​UnitTests/​SimulatedServerTests/​ConnectionFailoverTests.cs Expands sync/async coverage and pool assertions.
src/​Microsoft.Data.SqlClient/​tests/​tools/​TDS/​TDS/​TDSUtilities.cs Handles omitted encryption metadata.
src/​Microsoft.Data.SqlClient/​tests/​tools/​TDS/​TDS.Servers/​TransientTdsErrorTdsServer.cs Reserves and rearms errors atomically.
src/​Microsoft.Data.SqlClient/​tests/​tools/​TDS/​TDS.Servers/​TransientDelayTdsServer.cs Reserves delay quotas and suppresses canceled responses.
src/​Microsoft.Data.SqlClient/​tests/​tools/​TDS/​TDS.EndPoint/​TDSServerEndPointConnection.cs Uses dedicated workers and propagates failures.
src/​Microsoft.Data.SqlClient/​tests/​tools/​TDS/​TDS.EndPoint/​TDSServerEndPoint.cs Registers workers before starting and aggregates failures.

Review effort: Balanced

Make TLS handshake failure an explicit opt-in for negative certificate scenarios while retaining missing-certificate, missing-key, and handler failures. Require negative certificate connections to fail and replace a contradictory duplicate data row with a distinct mismatch scenario. Verify reuse of the pre-fault warmup connection, not a connection created by the retry.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 67997771-8f8e-4c62-b790-0111accb47f4
Copilot AI balanced review requested due to automatic review settings October 21, 2026 16:50

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

Shared worker-lifecycle and cross-platform TLS changes warrant human confirmation of the reported framework and networking validation.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 67997771-8f8e-4c62-b790-0111accb47f4
Copilot AI balanced review requested due to automatic review settings October 21, 2026 18:08

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

Shared worker shutdown and cross-platform TLS behavior warrant final human review despite the reported validation.

No open issues 🎉

Review effort: Balanced

@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 — no concerns.

@apoorvdeshmukh apoorvdeshmukh 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.

This test appears to be failing across multiple jobs.

Bring in the current main branch, including the friend-assembly assertion correction, while retaining the simulator test quarantine.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 67997771-8f8e-4c62-b790-0111accb47f4
Copilot AI balanced review requested due to automatic review settings October 22, 2026 18:59
priyankatiwari08 added a commit that referenced this pull request Nov 10, 2026
…eporting

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 <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 10, 2026
… 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.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 10, 2026
…eporting

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 <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 10, 2026
… 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.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 10, 2026
…eporting

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 <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 10, 2026
… 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.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 10, 2026
…eporting

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 <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 10, 2026
… 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.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 11, 2026
…eporting

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 <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 11, 2026
… 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.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 12, 2026
…eporting

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 <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 12, 2026
… 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.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 13, 2026
…eporting

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 <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 13, 2026
… 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.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 17, 2026
… 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.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 17, 2026
… 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.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 17, 2026
…eporting

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 <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 17, 2026
… 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.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 18, 2026
#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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
priyankatiwari08 added a commit that referenced this pull request Nov 18, 2026
#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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

* 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 <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
(cherry picked from commit 0a46e01)
priyankatiwari08 added a commit that referenced this pull request Nov 20, 2026
…#4835)

* 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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Align native SNI failure note with Managed SNI capture

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Address Slice C TLS diagnostics review feedback

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

* Scope Managed SNI switch to each certificate capture test

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e
priyankatiwari08 added a commit that referenced this pull request Nov 23, 2026
…#4835)

* 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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Align native SNI failure note with Managed SNI capture

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Address Slice C TLS diagnostics review feedback

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

* Scope Managed SNI switch to each certificate capture test

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e
(cherry picked from commit ce73774)
priyankatiwari08 added a commit that referenced this pull request 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 <prtiwar@microsoft.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e
priyankatiwari08 added a commit that referenced this pull request Nov 23, 2026
#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 <prtiwar@microsoft.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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.

6 participants