diff --git a/doc/design-notes/2353-connection-encryption-info.md b/doc/design-notes/2353-connection-encryption-info.md deleted file mode 100644 index b49ee804a8..0000000000 --- a/doc/design-notes/2353-connection-encryption-info.md +++ /dev/null @@ -1,269 +0,0 @@ -# Design note: #2353 — connection encryption information - -| | | -|---|---| -| **Issue** | [#2353](https://github.com/dotnet/SqlClient/issues/2353) | -| **Status** | Public API approved; implementation in progress in slices (see [Implementation plan](#6-implementation-plan)) | -| **Primary consumer** | SQL Server Management Studio (SSMS); the API is general-purpose | -| **Public surface** | `SqlConnection.EncryptionInfo`, `SqlException.EncryptionInfo`, `SqlConnectionEncryptionInfo`, `SqlConnectionEncryptionMode`, `SqlServerCertificateValidationErrors` | - -This note describes the approved API for exposing the encryption that a connection -actually negotiated and the outcome of server certificate validation. Its public API -shape was reviewed with the SSMS team. The implementation is being delivered in slices, as -listed in the implementation plan. - ---- - -## 1. Motivation - -Today an application can only see the encryption it *requested* (`Encrypt`, -`TrustServerCertificate`, `HostNameInCertificate`, `ServerCertificate`). It cannot see -what was actually negotiated, and when certificate validation fails the only information -available is the localized exception message. - -The API brings the negotiated encryption mode, TLS version, the server-presented -certificate, and structured validation results into one model that is available for both -successful and failed connection attempts. Tools such as SSMS can then show connection -security properties and build actionable failure messages from the driver's own -observations, without a second handshake. - -## 2. Scenarios - -| Scenario | Proposed capability | Value | -| --- | --- | --- | -| Show security information for an open connection | Read the negotiated encryption mode, TLS version, and presented server certificate from `connection.EncryptionInfo`. | Display the actual negotiated values. | -| Explain a failed certificate validation | Read typed validation errors, applicable chain-status flags, and the presented certificate from `exception.EncryptionInfo`, when captured. | Build user-facing messages from structured results rather than localized exception text. | -| Identify the certificate involved in the attempt | Call `GetServerCertificate()` to get the leaf certificate captured from that attempt. | Show subject, issuer, validity, SANs, and thumbprint of the certificate observed on that same connection attempt. | - -## 3. Approved API - -Both `SqlConnection.EncryptionInfo` and `SqlException.EncryptionInfo` expose the same -`SqlConnectionEncryptionInfo` snapshot, which is read-only to the caller. The object is -always present; each field is `null` when the information is unavailable or not -applicable. - -| Property on `SqlConnectionEncryptionInfo` | Type | Meaning | -| --- | --- | --- | -| `ChainStatus` | `X509ChainStatusFlags?` | Applicable chain-validation flags, such as `UntrustedRoot`, `NotTimeValid`, or `Revoked`. | -| `NegotiatedCipherSuite` | `TlsCipherSuite?`; .NET only; not CLS-compliant | The same value as `NegotiatedCipherSuiteId`, typed as `System.Net.Security.TlsCipherSuite`. | -| `NegotiatedCipherSuiteId` | `int?` on every target framework; CLS-compliant | IANA TLS cipher suite identifier selected by the server, such as `0x1302` (`TLS_AES_256_GCM_SHA384`). | -| `NegotiatedEncryptionMode` | `SqlConnectionEncryptionMode?` | Actual encryption outcome, not the requested `Encrypt` setting. | -| `NegotiatedEncryptionProtocol` | `SslProtocols?` | Negotiated TLS version, such as TLS 1.2 or TLS 1.3. | -| `ValidationErrors` | `SqlServerCertificateValidationErrors?` | Effective certificate-validation result under the connection's configured rules. | - -| Method on `SqlConnectionEncryptionInfo` | Return type | Meaning | -| --- | --- | --- | -| `GetServerCertificate()` | `X509Certificate2?` | The leaf certificate the server presented, as a new instance on every call, or `null` when none was captured. Not the caller's configured certificate. | - -```csharp -using System; -using System.Security.Authentication; -using System.Security.Cryptography.X509Certificates; - -namespace Microsoft.Data.SqlClient -{ - public sealed partial class SqlConnection - { - // Snapshot captured for the current open connection. Always non-null; empty - // before opening, while opening, and after closing or disposing. - public SqlConnectionEncryptionInfo EncryptionInfo { get; } - } - - public sealed partial class SqlException - { - // Snapshot captured for the connection attempt that produced this exception. - // Always non-null. Its presence alone does not indicate a certificate failure. - public SqlConnectionEncryptionInfo EncryptionInfo { get; } - } - - public sealed class SqlConnectionEncryptionInfo - { - public X509ChainStatusFlags? ChainStatus { get; } -#if NET - [CLSCompliant(false)] - public System.Net.Security.TlsCipherSuite? NegotiatedCipherSuite { get; } -#endif - public int? NegotiatedCipherSuiteId { get; } - public SqlConnectionEncryptionMode? NegotiatedEncryptionMode { get; } - public SslProtocols? NegotiatedEncryptionProtocol { get; } - public SqlServerCertificateValidationErrors? ValidationErrors { get; } - - // New instance on every call; the caller owns and disposes it. - public X509Certificate2? GetServerCertificate(); - } - - public enum SqlConnectionEncryptionMode : byte - { - None = 0, // Unencrypted connection. - LoginOnly = 1, // Login is protected; subsequent session traffic is unencrypted. - Full = 2, // Full-session encryption. - Strict = 3 // TDS 8.0 strict encryption. - } - - [Flags] - public enum SqlServerCertificateValidationErrors - { - None = 0, - ServerCertificateMissing = 1, - HostNameMismatch = 2, - ChainError = 4, - PinnedCertificateMismatch = 8 - } -} -``` - -Applications cannot construct `SqlConnectionEncryptionInfo`; the driver creates the -snapshots. - -### How the encryption mode is negotiated - -`NegotiatedEncryptionMode` reports both how encryption was negotiated and how much of the -connection it covers, so callers do not need to infer it from the TDS version: - -| Value | How it is negotiated | Traffic covered by TLS | -| --- | --- | --- | -| `None` | TDS 7.x PRELOGIN; neither side requested encryption and no login TLS was set up. | None. | -| `LoginOnly` | TDS 7.x PRELOGIN `ENCRYPT_OFF` from both sides; TLS protects only the login. | The LOGIN7 packet only; later session traffic is plaintext. | -| `Full` | TDS 7.x PRELOGIN `ENCRYPT_ON`/`ENCRYPT_REQ`; TLS is set up after PRELOGIN. | Everything after PRELOGIN, including login and session traffic. PRELOGIN itself is plaintext. | -| `Strict` | TDS 8.0 (`Encrypt=Strict`); TLS is set up before any TDS packet. | All TDS traffic, including PRELOGIN. | - -The requested `Encrypt` setting is not echoed back; the value reflects the outcome the -driver observed. - -### Negotiated cipher suite - -`NegotiatedCipherSuiteId` is the 16-bit identifier from the IANA TLS Cipher Suites -registry for the suite the server selected in its ServerHello, for example `0x1302` for -`TLS_AES_256_GCM_SHA384`. It is not a Windows `ALG_ID`. - -- **One shared member, plus a strong type on .NET:** `NegotiatedCipherSuiteId` is `int?` - on every target framework. On .NET only, `NegotiatedCipherSuite` exposes the same value - as `System.Net.Security.TlsCipherSuite?`, the type `SslStream.NegotiatedCipherSuite` - uses. .NET Framework and .NET Standard 2.0 have no `NegotiatedCipherSuite` member, - because `TlsCipherSuite` does not exist there. -- **Why not a per-target type for one property name:** the package ships a - `netstandard2.0` reference assembly. If `NegotiatedCipherSuite` were `ushort?` there and - `TlsCipherSuite?` on .NET, a library compiled against .NET Standard would bind to - `Nullable get_NegotiatedCipherSuite()`, which does not exist in the .NET - implementation, and would fail at run time with `MissingMethodException`. With this - shape, the only member present on every target has an identical signature everywhere. -- **CLS compliance:** `NegotiatedCipherSuiteId` is CLS-compliant and carries no - attribute. `TlsCipherSuite` is backed by `ushort`, so `NegotiatedCipherSuite` is marked - `[CLSCompliant(false)]`, as `SslStream.NegotiatedCipherSuite` is. The assembly stays - `[CLSCompliant(true)]`. -- **Unknown identifiers are preserved:** both properties return the captured identifier - unchanged, without `Enum.IsDefined` filtering, so newly registered or GREASE values are - not dropped. -- **Internal contract:** on .NET, the internal constructor takes `TlsCipherSuite?`, so the - value stays strongly typed from `SslStream` to the public API; both properties are - assigned from it. On .NET Framework, it takes an `int?` that must be in the range 0 to - 0xFFFF. -- **`null` means unavailable:** no TLS, the value was not captured on the current code - path, the network layer (for example, an older native SNI) does not report it, or the - attempt failed before the value was known. It does not mean the server selected no - suite. -- **Failures keep observed values:** a ServerHello can select a suite and the handshake - can still fail afterward, for example during certificate validation. As with - `NegotiatedEncryptionProtocol`, a value that was observed is kept in the snapshot - attached to `SqlException`. -- **Out of scope:** the client's offered suite list, CAPI2-level chain detail, and - key-exchange group or post-quantum information. - -### Server certificate - -Following the threat model review, the snapshot exposes the full certificate the server -presented instead of a hash of it. A hash only lets a caller correlate against a -certificate it already has; the certificate itself lets tools show subject, issuer, -validity, subject alternative names, and any thumbprint the caller wants to compute. - -- **Leaf only, public data only:** the certificate is what the server sent in the TLS - handshake. The chain is not included, and the certificate never has a private key. -- **Captured on success and on failure:** the certificate is captured whenever the server - presents one, including with `TrustServerCertificate=true` and when validation fails - (read it from `SqlException.EncryptionInfo`). -- **Diagnostics only:** returning a certificate is not a trust decision. Validation results - are reported separately through `ValidationErrors` and `ChainStatus`, and callers must - not use the certificate to override or bypass the driver's validation. -- **Storage:** the snapshot keeps a private copy of the DER bytes. Each call parses them - with `X509CertificateLoader.LoadCertificate` (from `Microsoft.Bcl.Cryptography` on .NET - Framework). Bytes that cannot be decoded are reported as `null`. The bytes are never - written to `ToString()`, exception messages, traces, or - serialization. -- **Capture limit:** certificates larger than 64 KiB (DER) are not captured; the method - returns `null` and the connection is unaffected. - -#### Why a method rather than a property - -- **Ownership:** `X509Certificate2` is disposable. Returning a new instance on each call - makes the caller the clear owner. A shared instance would leave it unclear who disposes - it, and disposing it would break other readers of the same snapshot. -- **Immutability:** on .NET Framework, `X509Certificate2` is mutable (`Import`, `Reset`). - A shared instance would let one caller change what others see; a fresh instance per - call keeps the snapshot immutable. -- **Cost:** each call parses the certificate. .NET design guidelines advise against - hiding that kind of work, or returning a new object each time, behind a property getter. - -### Certificate-validation outcomes - -`SqlServerCertificateValidationErrors` is a flags enum; applicable errors can coexist. - -| Value | Meaning | -| --- | --- | -| `None = 0` | Applicable validation ran and reported no error. | -| `ServerCertificateMissing = 1` | An authoritative validation result indicates that the server did not present its certificate. Not a missing local certificate file. | -| `HostNameMismatch = 2` | The certificate did not match the expected hostname after applying configured hostname rules. | -| `ChainError = 4` | Chain validation reported an error; `ChainStatus` supplies the captured detail. | -| `PinnedCertificateMismatch = 8` | The presented certificate did not match the certificate configured through `ServerCertificate`. | - -A pin mismatch is distinct from a chain error: the existing pin check compares -certificate bytes, and this API does not change that comparison. A missing or unreadable -configured file is not a completed pin comparison and is not reported as a mismatch. - -## 4. Behavior - -- **Success and failure:** after `Open()` or `OpenAsync()` succeeds, read - `connection.EncryptionInfo`. If opening throws `SqlException`, read - `exception.EncryptionInfo`. Its presence alone does not identify a certificate - failure. -- **Unknown is not success:** `null` means unavailable, not applicable, or skipped. - Zero-valued `None` / `NoError` means the applicable validation ran without reporting - errors. If `TrustServerCertificate` bypasses validation, the skipped validation fields - remain `null`; a successful connection does not prove that certificate validation - occurred. -- **Only applicable results:** the driver reports its effective verdict, not raw errors - that configured hostname or pin rules resolved. For a pin-only validation path, - `ChainStatus` remains `null` rather than reporting an invented chain failure. Absence - of `Revoked` does not establish that revocation was checked. -- **Lifetime:** the connection snapshot is empty before opening, while opening, and after - close or dispose. Previously retained snapshots and exception snapshots don't change. - Pooled connections report the underlying physical connection's saved information; - retry and redirect results refer only to the terminal attempt. -- **No additional validation:** reading these properties performs no handshake or - certificate check and doesn't change trust decisions. -- **No message changes:** snapshot values are not added to exception messages, - `ToString()`, or default telemetry. Applications control their own display and - logging. -- **Serialization:** the snapshot is not serialized with `SqlException`; a deserialized - exception returns an empty snapshot. -- **Diagnostics only:** the snapshot must not be used to make security decisions; the - driver's own validation is authoritative. - -## 5. Scope - -The API reports negotiated encryption, TLS protocol, the server-selected cipher suite, the -server-presented leaf certificate, and certificate-validation results for successful and failed connection -attempts. - -Intended coverage includes the supported .NET Framework and .NET targets, Managed and -Native SNI, and TCP and Named Pipes where SqlClient uses TLS. - -## 6. Implementation plan - -The feature is delivered as a stack of pull requests: - -| Slice | Content | -| --- | --- | -| **A** | Public API surface only. Both getters return an empty snapshot. | -| **B** | Capture the negotiated mode, TLS protocol and cipher suite, and attach the snapshot to `SqlException` when opening fails. | -| **C** | Capture certificate details (presented certificate, validation errors, and chain status) in Managed SNI, on both successful and failed attempts. | -| **D** | Native SNI interop for the certificate details and cipher suite. | diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml index 868b90dc91..89dd95abe1 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml @@ -1377,22 +1377,6 @@ The following example creates a an You can use the method to enlist in a distributed transaction. Because it enlists a connection in a instance, takes advantage of functionality available in the namespace for managing distributed transactions, making it preferable to , which uses a object (from namespace). It also has slightly different semantics: once a connection is explicitly enlisted on a transaction, it cannot be unenlisted or enlisted in another transaction until the first transaction finishes. For more information about distributed transactions, see Distributed Transactions. - - - Gets a diagnostic snapshot describing the encryption that was negotiated for this connection and the outcome of server certificate validation. - - - A non-null . Individual properties of the snapshot are when the corresponding information is not available. - - - - This property never returns and never throws, regardless of whether the connection has been opened, closed, or disposed. A property value on the returned snapshot means the information was not available at the time the snapshot was obtained. Any snapshot may have any combination of and non-null property values depending on the state of the underlying connection. The presence or absence of property values does not indicate that encryption or certificate validation succeeded or failed. - - - Before the connection opens successfully, the snapshot is empty (all properties) because it has no physical connection associated. Once opened, the snapshot describes the physical connection in use, including an existing physical connection obtained from a pool. Closing or disposing a connection resets this property to its initial empty snapshot. Snapshots are immutable, so a snapshot that was already obtained does not change. - - - Gets or sets the property. diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptionInfo.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptionInfo.xml deleted file mode 100644 index e0696da25d..0000000000 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptionInfo.xml +++ /dev/null @@ -1,137 +0,0 @@ - - - - - Represents an immutable, point-in-time diagnostic snapshot of the encryption negotiated for a connection and the outcome of server certificate validation. - - - - Instances are obtained from or . Applications cannot create instances directly. - - - Every property is nullable, and can return . A value means the information was not available when the snapshot was created (for example, the connection had not reached the relevant phase, or the network implementation in use does not report it). The presence or absence of values does not indicate that encryption or certificate validation succeeded or failed. - - - This type is intended for diagnostics only. It must not be used to make security decisions; the driver's own validation is authoritative. - - - Which values are populated depends on the operation that produced the snapshot and on the network implementation in use. See and for when each snapshot is captured. - - - - - - Gets the aggregated X.509 chain status flags reported while building the server certificate chain. - - - A combination of values, or if chain status is not available. - - - A value of means the chain was built and no status flags were reported, which is distinct from . - - - - - Gets the TLS cipher suite that the server selected for the encrypted channel, as a System.Net.Security.TlsCipherSuite. This property is available only on .NET. - - - A System.Net.Security.TlsCipherSuite value, or if the cipher suite is not available. - - - - This property represents the same cipher suite as , using the type of System.Net.Security.SslStream.NegotiatedCipherSuite. An identifier that has no named member in the enumeration is preserved numerically. When one property is , so is the other. - - - TlsCipherSuite is an unsigned 16-bit enumeration, so this property is not CLS-compliant. Use from CLS-compliant code or from libraries that target .NET Standard or .NET Framework. - - - - - - Gets the identifier of the TLS cipher suite that the server selected for the encrypted channel. - - - The IANA TLS cipher suite identifier selected by the server (for example, 0x1302 for TLS_AES_256_GCM_SHA384), or if the cipher suite is not available. - - - - The value is the 16-bit identifier from the IANA TLS Cipher Suites registry, in the range 0 to 0xFFFF. It is not a Windows ALG_ID. This property has the same type and value on every target framework and is CLS-compliant. Identifiers that have no named member in System.Net.Security.TlsCipherSuite (for example, newly registered or GREASE values) are returned unchanged. - - - On .NET, the same value is also available as a System.Net.Security.TlsCipherSuite through the NegotiatedCipherSuite property. - - - A value means the driver could not obtain the cipher suite: no TLS handshake took place, the value was not captured on the current code path, the network layer in use does not report it, or the connection attempt failed before the value was known. It does not mean that the server selected no cipher suite. - - - When a connection attempt fails after the server has selected a cipher suite (for example, during certificate validation), the observed value is kept, in the same way as . - - - This value describes only the cipher suite selected by the server. It does not list the cipher suites offered by the client. - - - - - - Gets the encryption mode that was negotiated with the server. - - - A value, or if the negotiated mode is not available. - - - This value reflects what was negotiated, which can differ from the setting that was requested. A value of means that no encryption was negotiated, which is distinct from . - - - - - Gets the TLS protocol version that was negotiated for the encrypted channel. - - - A value, or if the protocol is not available. - - - A protocol value observed before a later handshake or connection failure, such as a - certificate-validation failure, is retained in the snapshot. A - value means the driver could not obtain the protocol; it does not indicate whether a - handshake was attempted. - On runtimes where does not define a named member for the negotiated version (for example, TLS 1.3 on .NET Framework), the numeric protocol value is preserved. - - - - - Gets the server certificate validation errors observed by the driver. - - - A combination of values, or if certificate validation did not run or its outcome is not available. - - - A value of means validation ran and no errors were observed, which is distinct from . When the driver does not validate the server certificate (for example, when is ), this value is , even if the server presented a certificate. - - - - - Returns the leaf certificate that the server presented during the TLS handshake. - - - A new instance that contains the server-presented leaf certificate, or if no certificate was captured for the connection attempt or the captured certificate cannot be parsed. - - - - Each call returns a new instance. The caller owns the returned certificate and should dispose it when it is no longer needed. Disposing it does not affect this snapshot or later calls. - - - The returned certificate is the leaf certificate only; the chain is not included. It never contains a private key. It is the certificate the server presented, not a certificate configured by the caller (for example, through ). - - - The certificate is captured whenever the server presents one, including when is and when certificate validation fails. On failure, read it from . Validation results are reported separately through and . - - - This method is intended for diagnostics only. Its result is not a trust decision: a returned certificate does not mean that it passed validation, and it must not be used to override or bypass the driver's certificate validation. - - - If the captured certificate cannot be decoded, this method returns . It does not perform a handshake or certificate validation. - - - - - diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptionMode.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptionMode.xml deleted file mode 100644 index a3fe0ea820..0000000000 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionEncryptionMode.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - Specifies the encryption mode that was negotiated between the client and SQL Server for a connection. - - - This type describes the negotiated outcome reported by . It is distinct from , which describes the requested setting. - - - - - No encryption was negotiated for the connection. - - - - - Only the login packet was encrypted; subsequent traffic was not encrypted. - - - - - The TDS session was encrypted after the pre-login exchange (TDS 7.x encryption). - - - - - TDS 8.0 strict encryption was used: the TLS handshake occurred before any TDS traffic was exchanged. - - - - diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlException.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlException.xml index d7b1585fce..780fbd95f8 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlException.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlException.xml @@ -738,25 +738,6 @@ - - - Gets a diagnostic snapshot describing the connection encryption and server certificate validation state associated with this exception. - - - A non-null . Individual properties of the snapshot are when the corresponding information is not available. - - - - This property never returns . A property value on the returned snapshot means the information was not available when the snapshot was created. Any snapshot may have any combination of and non-null property values depending on how far the connection attempt progressed. The presence or absence of property values does not indicate that encryption or certificate validation succeeded or failed. - - - The snapshot is not serialized with the exception; a deserialized returns a snapshot with all properties set to . The snapshot is not included in or in the output of . - - - When opening a connection fails, the snapshot describes values observed during the final connection attempt. Exceptions unrelated to opening a connection return a snapshot with all properties set to . A deserialized exception also returns an empty snapshot. - - - If this was thrown when executing a , references the specific which triggered the exception. diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlServerCertificateValidationErrors.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlServerCertificateValidationErrors.xml deleted file mode 100644 index c38a175b01..0000000000 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlServerCertificateValidationErrors.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - Specifies server certificate validation errors observed by the driver. This enumeration supports a bitwise combination of its member values. - - - - - Certificate validation ran and no errors were observed. - - - - - The server did not present a certificate. - - - - - The certificate presented by the server does not match the expected host name. - - - - - The certificate chain could not be built or validated. See for details. - - - - - The certificate presented by the server does not match the certificate configured with the ServerCertificate connection string keyword. - - - - diff --git a/src/Microsoft.Data.SqlClient/notsupported/GenApiExcludeAttributes.txt b/src/Microsoft.Data.SqlClient/notsupported/GenApiExcludeAttributes.txt deleted file mode 100644 index 98d220af7f..0000000000 --- a/src/Microsoft.Data.SqlClient/notsupported/GenApiExcludeAttributes.txt +++ /dev/null @@ -1,5 +0,0 @@ -# Attributes that GenAPI must not copy from the ref assembly into the generated source. -# Nullable metadata attributes are reserved for the compiler (CS8335); GenAPI already reflects -# them as '?' annotations in the generated declarations. -T:System.Runtime.CompilerServices.NullableAttribute -T:System.Runtime.CompilerServices.NullableContextAttribute \ No newline at end of file diff --git a/src/Microsoft.Data.SqlClient/notsupported/GenApiHeader.txt b/src/Microsoft.Data.SqlClient/notsupported/GenApiHeader.txt deleted file mode 100644 index bf1cd4205d..0000000000 --- a/src/Microsoft.Data.SqlClient/notsupported/GenApiHeader.txt +++ /dev/null @@ -1,12 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by GenAPI from the Microsoft.Data.SqlClient -// reference assembly. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -// Match the reference assembly: nullable annotations are reproduced, without warnings. -#nullable enable annotations diff --git a/src/Microsoft.Data.SqlClient/notsupported/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/notsupported/Microsoft.Data.SqlClient.csproj index 6002da40fd..8edf47037c 100644 --- a/src/Microsoft.Data.SqlClient/notsupported/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/notsupported/Microsoft.Data.SqlClient.csproj @@ -225,8 +225,6 @@ -l:"@(_referencePathDirectories)" -o:"$(NotSupportedSourceFile)" -t:"Microsoft.Data.SqlClient is not supported on this platform." - --header-file:"$(MSBuildThisFileDirectory)GenApiHeader.txt" - --exclude-attributes-list:"$(MSBuildThisFileDirectory)GenApiExcludeAttributes.txt" $([System.Text.RegularExpressions.Regex]::Replace($(GenApiCommand), "\s*[\r\n]+\s*", " ")) diff --git a/src/Microsoft.Data.SqlClient/ref/Microsoft.Data.SqlClient.cs b/src/Microsoft.Data.SqlClient/ref/Microsoft.Data.SqlClient.cs index 3f72e47e78..262795f399 100644 --- a/src/Microsoft.Data.SqlClient/ref/Microsoft.Data.SqlClient.cs +++ b/src/Microsoft.Data.SqlClient/ref/Microsoft.Data.SqlClient.cs @@ -1103,10 +1103,6 @@ public SqlConnection(string connectionString, Microsoft.Data.SqlClient.SqlCreden [System.ComponentModel.BrowsableAttribute(true)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(0)] public override string DataSource { get { throw null; } } - /// - [System.ComponentModel.BrowsableAttribute(false)] - [System.ComponentModel.DesignerSerializationVisibilityAttribute(0)] - public Microsoft.Data.SqlClient.SqlConnectionEncryptionInfo EncryptionInfo { get { throw null; } } /// public bool FireInfoMessageEventOnUserErrors { get { throw null; } set { } } /// @@ -1305,60 +1301,6 @@ private SqlConnectionEncryptOption(string value) { } public override int GetHashCode() { throw null; } } -/// -public sealed class SqlConnectionEncryptionInfo -{ - internal SqlConnectionEncryptionInfo() { } - /// - public System.Security.Cryptography.X509Certificates.X509ChainStatusFlags? ChainStatus { get { throw null; } } -#if NET - /// - [System.CLSCompliantAttribute(false)] - public System.Net.Security.TlsCipherSuite? NegotiatedCipherSuite { get { throw null; } } -#endif - /// - public int? NegotiatedCipherSuiteId { get { throw null; } } - /// - public Microsoft.Data.SqlClient.SqlConnectionEncryptionMode? NegotiatedEncryptionMode { get { throw null; } } - /// - public System.Security.Authentication.SslProtocols? NegotiatedEncryptionProtocol { get { throw null; } } - /// - public Microsoft.Data.SqlClient.SqlServerCertificateValidationErrors? ValidationErrors { get { throw null; } } - /// -#nullable enable annotations - public System.Security.Cryptography.X509Certificates.X509Certificate2? GetServerCertificate() { throw null; } -#nullable restore -} - -/// -public enum SqlConnectionEncryptionMode : byte -{ - /// - None = 0, - /// - LoginOnly = 1, - /// - Full = 2, - /// - Strict = 3, -} - -/// -[System.FlagsAttribute] -public enum SqlServerCertificateValidationErrors -{ - /// - None = 0, - /// - ServerCertificateMissing = 1, - /// - HostNameMismatch = 2, - /// - ChainError = 4, - /// - PinnedCertificateMismatch = 8, -} - internal class SqlConnectionEncryptOptionConverter : System.ComponentModel.TypeConverter { } @@ -1980,8 +1922,6 @@ private SqlException(System.Runtime.Serialization.SerializationInfo info, System public byte Class { get { throw null; } } /// public System.Guid ClientConnectionId { get { throw null; } } - /// - public Microsoft.Data.SqlClient.SqlConnectionEncryptionInfo EncryptionInfo { get { throw null; } } #if NET /// diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnection.cs index 43f6b05a77..23a5f57659 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -1023,11 +1023,6 @@ public Guid ClientConnectionId } } - /// - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public SqlConnectionEncryptionInfo EncryptionInfo => SqlConnectionEncryptionInfo.Empty; - /// [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionEncryptionInfo.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionEncryptionInfo.cs deleted file mode 100644 index 79ea5ba5d0..0000000000 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionEncryptionInfo.cs +++ /dev/null @@ -1,149 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -#if NET -using System.Net.Security; -#endif -using System.Security.Authentication; -using System.Security.Cryptography; -using System.Security.Cryptography.X509Certificates; - -#nullable enable - -namespace Microsoft.Data.SqlClient -{ - /// - public sealed class SqlConnectionEncryptionInfo - { - /// - /// Shared snapshot with every field unavailable (). Safe to share - /// because instances are immutable. - /// - internal static SqlConnectionEncryptionInfo Empty { get; } = new(); - - private readonly byte[]? _presentedServerCertificate; - - private SqlConnectionEncryptionInfo() - { - } - - /// - /// Creates a populated snapshot. Each argument is when the - /// corresponding value was not captured for the connection attempt. - /// - /// The negotiated encryption mode. - /// The negotiated TLS protocol version. - /// - /// The DER encoding of the leaf certificate presented by the server. The array is copied; - /// an empty array is treated as . - /// - /// The certificate validation errors observed by the driver. - /// The aggregated X.509 chain status flags. - /// - /// The TLS cipher suite selected by the server. On .NET Framework this is the IANA cipher - /// suite identifier (for example, 0x1302), not a Windows ALG_ID, and must be in the range - /// 0 to 0xFFFF when not . - /// - internal SqlConnectionEncryptionInfo( - SqlConnectionEncryptionMode? negotiatedEncryptionMode, - SslProtocols? negotiatedEncryptionProtocol, - byte[]? presentedServerCertificate, - SqlServerCertificateValidationErrors? validationErrors, - X509ChainStatusFlags? chainStatus, -#if NET - TlsCipherSuite? negotiatedCipherSuite = null) -#else - int? negotiatedCipherSuite = null) -#endif - { -#if NET - NegotiatedCipherSuite = negotiatedCipherSuite; - NegotiatedCipherSuiteId = (int?)negotiatedCipherSuite; -#else - if (negotiatedCipherSuite is < 0 or > ushort.MaxValue) - { - throw new ArgumentOutOfRangeException( - nameof(negotiatedCipherSuite), - negotiatedCipherSuite, - "A TLS cipher suite identifier must be in the range 0 to 0xFFFF."); - } - - NegotiatedCipherSuiteId = negotiatedCipherSuite; -#endif - NegotiatedEncryptionMode = negotiatedEncryptionMode; - NegotiatedEncryptionProtocol = negotiatedEncryptionProtocol; - if (presentedServerCertificate is { Length: > 0 }) - { - _presentedServerCertificate = (byte[])presentedServerCertificate.Clone(); - } - ValidationErrors = validationErrors; - ChainStatus = chainStatus; - } - - /// - public X509ChainStatusFlags? ChainStatus { get; } - -#if NET - // TlsCipherSuite is ushort-backed, matching SslStream.NegotiatedCipherSuite, so this member - // is not CLS-compliant. - /// - [CLSCompliant(false)] - public TlsCipherSuite? NegotiatedCipherSuite { get; } -#endif - - /// - public int? NegotiatedCipherSuiteId { get; } - - /// - public SqlConnectionEncryptionMode? NegotiatedEncryptionMode { get; } - - /// - public SslProtocols? NegotiatedEncryptionProtocol { get; } - - /// - public SqlServerCertificateValidationErrors? ValidationErrors { get; } - - /// - public X509Certificate2? GetServerCertificate() - { - if (_presentedServerCertificate is null) - { - return null; - } - - try - { - return X509CertificateLoader.LoadCertificate(_presentedServerCertificate); - } - catch (CryptographicException) - { - // Diagnostics only: bytes that cannot be parsed are reported as unavailable. - return null; - } - } - - /// - /// Gets the captured DER encoding of the server-presented leaf certificate, or - /// if none was captured. The memory wraps the snapshot's private - /// copy without allocating; internal callers must not mutate it. Public callers only - /// receive a newly parsed certificate from . - /// - internal ReadOnlyMemory? PresentedServerCertificateRawData => - _presentedServerCertificate is null - ? (ReadOnlyMemory?)null - : new ReadOnlyMemory(_presentedServerCertificate); - - /// - /// Gets a value indicating whether every field is unavailable. - /// - internal bool IsEmpty => - NegotiatedEncryptionMode is null && - NegotiatedEncryptionProtocol is null && - NegotiatedCipherSuiteId is null && - _presentedServerCertificate is null && - ValidationErrors is null && - ChainStatus is null; - } -} diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionEncryptionMode.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionEncryptionMode.cs deleted file mode 100644 index 1766b1cb08..0000000000 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionEncryptionMode.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.Data.SqlClient -{ - /// - public enum SqlConnectionEncryptionMode : byte - { - /// - None = 0, - - /// - LoginOnly = 1, - - /// - Full = 2, - - /// - Strict = 3, - } -} diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlException.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlException.cs index 3e8234f94e..9a376995ef 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlException.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlException.cs @@ -37,13 +37,6 @@ public sealed partial class SqlException : System.Data.Common.DbException #endif // Do not serialize this field! It is used to indicate that no reconnection attempts are required internal bool _doNotReconnect = false; - // Diagnostic snapshot only; not serialized so the existing serialization graph is unchanged. - // A null value (including after deserialization) is surfaced as an empty snapshot. -#if NETFRAMEWORK - [IgnoreDataMember] -#endif - [NonSerialized] - private SqlConnectionEncryptionInfo _encryptionInfo; private SqlException(string message, SqlErrorCollection errorCollection, Exception innerException, Guid conId) : base(message, innerException) { @@ -139,13 +132,6 @@ public SqlBatchCommand BatchCommand } #endif - /// - public SqlConnectionEncryptionInfo EncryptionInfo - { - get => _encryptionInfo ?? SqlConnectionEncryptionInfo.Empty; - internal set => _encryptionInfo = value; - } - /// public override string ToString() { @@ -315,7 +301,6 @@ internal SqlException InternalClone() } exception._batchCommand = _batchCommand; exception._doNotReconnect = _doNotReconnect; - exception._encryptionInfo = _encryptionInfo; return exception; } } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlServerCertificateValidationErrors.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlServerCertificateValidationErrors.cs deleted file mode 100644 index b04742f783..0000000000 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlServerCertificateValidationErrors.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; - -namespace Microsoft.Data.SqlClient -{ - /// - [Flags] - public enum SqlServerCertificateValidationErrors - { - /// - None = 0, - - /// - ServerCertificateMissing = 1, - - /// - HostNameMismatch = 2, - - /// - ChainError = 4, - - /// - PinnedCertificateMismatch = 8, - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlConnectionEncryptionInfoTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlConnectionEncryptionInfoTests.cs deleted file mode 100644 index 1c66f2a674..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlConnectionEncryptionInfoTests.cs +++ /dev/null @@ -1,621 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Reflection; -using System.Security.Authentication; -using System.Security.Cryptography.X509Certificates; -using Xunit; -using static Microsoft.Data.SqlClient.UnitTests.Utilities.EncryptionInfoTestData; - -namespace Microsoft.Data.SqlClient -{ - /// - /// Unit tests for the public API surface. - /// - public class SqlConnectionEncryptionInfoTests - { - #region Empty snapshot - - /// - /// Verifies that the shared empty snapshot reports every field as unavailable. - /// - [Fact] - public void Empty_AllPropertiesAreNull() - { - // Act - SqlConnectionEncryptionInfo info = SqlConnectionEncryptionInfo.Empty; - - // Assert - AssertEmpty(info); - } - - /// - /// Verifies that the empty snapshot is a single shared instance. - /// - [Fact] - public void Empty_IsSharedInstance() - { - // Act & Assert - Assert.Same(SqlConnectionEncryptionInfo.Empty, SqlConnectionEncryptionInfo.Empty); - } - - /// - /// Verifies that constructing a snapshot with every argument null is equivalent to empty. - /// - [Fact] - public void Constructor_AllNull_IsEmpty() - { - // Act - SqlConnectionEncryptionInfo info = new(null, null, null, null, null); - - // Assert - AssertEmpty(info); - } - - /// - /// Verifies the type is sealed and exposes no public constructors. - /// - [Fact] - public void Type_IsSealedWithNoPublicConstructors() - { - // Act - Type type = typeof(SqlConnectionEncryptionInfo); - - // Assert - Assert.True(type.IsSealed); - Assert.Empty(type.GetConstructors()); - } - - /// - /// Verifies every public property is get-only so the snapshot is immutable. - /// - [Fact] - public void Type_PublicPropertiesAreReadOnly() - { - // Act - PropertyInfo[] properties = typeof(SqlConnectionEncryptionInfo).GetProperties(); - - // Assert - foreach (PropertyInfo property in properties) - { - Assert.True(property.CanRead, property.Name); - Assert.Null(property.GetSetMethod(nonPublic: true)); - } - } - - #endregion - - #region Populated snapshots - - /// - /// Verifies that values supplied to the internal constructor round-trip unchanged. - /// - [Fact] - public void Constructor_Populated_RoundTripsValues() - { - // Act - SqlConnectionEncryptionInfo info = CreatePopulated(); - using X509Certificate2? certificate = info.GetServerCertificate(); - - // Assert - Assert.Equal(SqlConnectionEncryptionMode.Strict, info.NegotiatedEncryptionMode); - Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); - Assert.Equal(SampleCipherSuite, info.NegotiatedCipherSuiteId); -#if NET - Assert.Equal(System.Net.Security.TlsCipherSuite.TLS_AES_256_GCM_SHA384, info.NegotiatedCipherSuite); -#endif - ReadOnlyMemory rawData = Assert.NotNull(info.PresentedServerCertificateRawData); - Assert.Equal(CreateSampleCertificate(), rawData.ToArray()); - Assert.NotNull(certificate); - Assert.Equal(SampleCertificateThumbprint, certificate.Thumbprint); - Assert.Equal(SqlServerCertificateValidationErrors.HostNameMismatch, info.ValidationErrors); - Assert.Equal(X509ChainStatusFlags.UntrustedRoot, info.ChainStatus); - Assert.False(info.IsEmpty); - } - - /// - /// Verifies that each field independently controls , - /// and that the field that was supplied is the one reported. - /// - [Theory] - [InlineData(0)] - [InlineData(1)] - [InlineData(2)] - [InlineData(3)] - [InlineData(4)] - [InlineData(5)] - public void Constructor_SingleFieldSet_IsNotEmpty(int fieldIndex) - { - // Act - SqlConnectionEncryptionInfo info = new( - fieldIndex == 0 ? SqlConnectionEncryptionMode.None : null, - fieldIndex == 1 ? SslProtocols.None : null, - fieldIndex == 2 ? CreateSampleCertificate() : null, - fieldIndex == 3 ? SqlServerCertificateValidationErrors.None : null, - fieldIndex == 4 ? X509ChainStatusFlags.NoError : null, - fieldIndex == 5 ? ToConstructorCipherSuite(0) : null); - - // Assert - object? supplied = fieldIndex switch - { - 0 => info.NegotiatedEncryptionMode, - 1 => info.NegotiatedEncryptionProtocol, - 2 => info.PresentedServerCertificateRawData, - 3 => info.ValidationErrors, - 4 => info.ChainStatus, - _ => info.NegotiatedCipherSuiteId, - }; - Assert.NotNull(supplied); - Assert.False(info.IsEmpty); - } - - /// - /// Verifies that zero-valued enum members are distinct from null (not available). - /// - [Fact] - public void Constructor_ZeroValues_DistinctFromNull() - { - // Act - SqlConnectionEncryptionInfo info = new( - SqlConnectionEncryptionMode.None, - SslProtocols.None, - presentedServerCertificate: null, - SqlServerCertificateValidationErrors.None, - X509ChainStatusFlags.NoError); - - // Assert - Assert.Equal(SqlConnectionEncryptionMode.None, Assert.NotNull(info.NegotiatedEncryptionMode)); - Assert.Equal(SslProtocols.None, Assert.NotNull(info.NegotiatedEncryptionProtocol)); - Assert.Equal(SqlServerCertificateValidationErrors.None, Assert.NotNull(info.ValidationErrors)); - Assert.Equal(X509ChainStatusFlags.NoError, Assert.NotNull(info.ChainStatus)); - Assert.Null(info.PresentedServerCertificateRawData); - Assert.Null(info.GetServerCertificate()); - } - - /// - /// Verifies that combined validation-error and chain-status flags round-trip unchanged. - /// - [Fact] - public void Constructor_FlagCombinations_RoundTrip() - { - // Arrange - const SqlServerCertificateValidationErrors errors = - SqlServerCertificateValidationErrors.HostNameMismatch | - SqlServerCertificateValidationErrors.ChainError | - SqlServerCertificateValidationErrors.PinnedCertificateMismatch; - const X509ChainStatusFlags chain = - X509ChainStatusFlags.UntrustedRoot | - X509ChainStatusFlags.NotTimeValid | - X509ChainStatusFlags.PartialChain; - - // Act - SqlConnectionEncryptionInfo info = new(null, null, null, errors, chain); - - // Assert - SqlServerCertificateValidationErrors actualErrors = Assert.NotNull(info.ValidationErrors); - Assert.Equal(errors, actualErrors); - Assert.True(actualErrors.HasFlag(SqlServerCertificateValidationErrors.ChainError)); - Assert.False(actualErrors.HasFlag(SqlServerCertificateValidationErrors.ServerCertificateMissing)); - X509ChainStatusFlags actualChain = Assert.NotNull(info.ChainStatus); - Assert.Equal(chain, actualChain); - Assert.True(actualChain.HasFlag(X509ChainStatusFlags.PartialChain)); - } - - /// - /// Verifies that a protocol value without a named member on the current runtime (for - /// example TLS 1.3 on .NET Framework) is preserved numerically. - /// - [Fact] - public void Constructor_NumericProtocolValue_IsPreserved() - { - // Arrange - const SslProtocols tls13 = (SslProtocols)0x3000; - - // Act - SqlConnectionEncryptionInfo info = new(SqlConnectionEncryptionMode.Strict, tls13, null, null, null); - - // Assert - Assert.Equal(0x3000, (int)Assert.NotNull(info.NegotiatedEncryptionProtocol)); - } - - #endregion - - #region Negotiated cipher suite - - /// - /// Verifies that the negotiated cipher suite defaults to null (not available) when it is not - /// supplied, even if other fields are populated. - /// - [Fact] - public void NegotiatedCipherSuite_NotSupplied_IsNull() - { - // Act - SqlConnectionEncryptionInfo info = new(SqlConnectionEncryptionMode.Full, SslProtocols.Tls12, null, null, null); - - // Assert - Assert.Null(info.NegotiatedCipherSuiteId); -#if NET - Assert.Null(info.NegotiatedCipherSuite); -#endif - Assert.False(info.IsEmpty); - } - - /// - /// Verifies that IANA cipher suite identifiers, including the boundary values, round-trip unchanged. - /// A value of zero (TLS_NULL_WITH_NULL_NULL) is distinct from null. - /// - [Theory] - [InlineData((ushort)0x0000)] - [InlineData((ushort)0x1301)] - [InlineData((ushort)0x1302)] - [InlineData((ushort)0xC030)] - [InlineData((ushort)0xFFFF)] - public void NegotiatedCipherSuite_Value_RoundTrips(ushort cipherSuite) - { - // Act - SqlConnectionEncryptionInfo info = CreateWithCipherSuite(cipherSuite); - - // Assert - Assert.Equal((int)cipherSuite, info.NegotiatedCipherSuiteId); -#if NET - Assert.Equal((System.Net.Security.TlsCipherSuite)cipherSuite, info.NegotiatedCipherSuite); -#endif - Assert.False(info.IsEmpty); - } - -#if NETFRAMEWORK - /// - /// Verifies that a value outside the 16-bit IANA identifier range is rejected. On .NET the - /// constructor takes a TlsCipherSuite, so such a value cannot be supplied. - /// - [Theory] - [InlineData(-1)] - [InlineData(0x10000)] - [InlineData(int.MaxValue)] - public void Constructor_InvalidCipherSuite_Throws(int cipherSuite) - { - // Act - ArgumentOutOfRangeException ex = Assert.Throws( - () => new SqlConnectionEncryptionInfo(null, null, null, null, null, cipherSuite)); - - // Assert - Assert.Equal("negotiatedCipherSuite", ex.ParamName); - } -#endif - - /// - /// Verifies that a valid 16-bit identifier that is not a registered cipher suite or has no - /// named TlsCipherSuite member (for example, a GREASE value) is preserved numerically - /// and not filtered out. - /// - [Theory] - [InlineData((ushort)0x0A0A)] - [InlineData((ushort)0xF00F)] - [InlineData((ushort)0xFAFA)] - public void NegotiatedCipherSuite_UnknownIdentifier_IsPreserved(ushort cipherSuite) - { - // Act - SqlConnectionEncryptionInfo info = CreateWithCipherSuite(cipherSuite); - - // Assert - Assert.Equal((int)cipherSuite, info.NegotiatedCipherSuiteId); -#if NET - Assert.False(Enum.IsDefined(typeof(System.Net.Security.TlsCipherSuite), cipherSuite)); - Assert.Equal((System.Net.Security.TlsCipherSuite)cipherSuite, info.NegotiatedCipherSuite); -#endif - } - -#if NET - /// - /// Verifies that a known IANA identifier maps to the matching named TlsCipherSuite member. - /// - [Fact] - public void NegotiatedCipherSuite_KnownIdentifier_MapsToNamedMember() - { - // Act - SqlConnectionEncryptionInfo info = new( - null, null, null, null, null, System.Net.Security.TlsCipherSuite.TLS_AES_256_GCM_SHA384); - - // Assert - Assert.Equal(System.Net.Security.TlsCipherSuite.TLS_AES_256_GCM_SHA384, info.NegotiatedCipherSuite); - Assert.Equal(0x1302, info.NegotiatedCipherSuiteId); - } -#endif - - /// - /// Verifies that NegotiatedCipherSuiteId is a read-only int? on every target - /// framework and carries no , so it inherits the assembly's - /// CLS compliance and has an identical signature everywhere. - /// - [Fact] - public void NegotiatedCipherSuiteId_PropertyShape_IsSameOnEveryTargetFramework() - { - // Act - PropertyInfo? property = - typeof(SqlConnectionEncryptionInfo).GetProperty(nameof(SqlConnectionEncryptionInfo.NegotiatedCipherSuiteId)); - - // Assert - Assert.NotNull(property); - Assert.Equal(typeof(int?), property.PropertyType); - Assert.True(property.CanRead); - Assert.False(property.CanWrite); - MethodInfo? getter = property.GetMethod; - Assert.NotNull(getter); - Assert.True(getter.IsPublic); - Assert.Null(Attribute.GetCustomAttribute(property, typeof(CLSCompliantAttribute))); - Assert.Null(Attribute.GetCustomAttribute(getter, typeof(CLSCompliantAttribute))); - } - - /// - /// Verifies that the strongly typed NegotiatedCipherSuite property exists only on .NET, - /// as a read-only TlsCipherSuite? marked not CLS-compliant. - /// - [Fact] - public void NegotiatedCipherSuite_PropertyShape_MatchesTargetFramework() - { - // Act - PropertyInfo? property = - typeof(SqlConnectionEncryptionInfo).GetProperty("NegotiatedCipherSuite"); - - // Assert -#if NET - Assert.NotNull(property); - Assert.Equal(typeof(System.Net.Security.TlsCipherSuite?), property.PropertyType); - Assert.True(property.CanRead); - Assert.False(property.CanWrite); - CLSCompliantAttribute? cls = - (CLSCompliantAttribute?)Attribute.GetCustomAttribute(property, typeof(CLSCompliantAttribute)); - Assert.NotNull(cls); - Assert.False(cls.IsCompliant); -#else - Assert.Null(property); -#endif - } - - /// - /// Verifies that the assembly remains CLS-compliant overall. - /// - [Fact] - public void Assembly_RemainsClsCompliant() - { - // Act - CLSCompliantAttribute? cls = (CLSCompliantAttribute?)Attribute.GetCustomAttribute( - typeof(SqlConnectionEncryptionInfo).Assembly, typeof(CLSCompliantAttribute)); - - // Assert - Assert.NotNull(cls); - Assert.True(cls.IsCompliant); - } - - #endregion - - #region Server certificate - - /// - /// Verifies that the certificate is exposed as a public method returning - /// and that no hash property remains. - /// - [Fact] - public void GetServerCertificate_PublicShape() - { - // Arrange - Type type = typeof(SqlConnectionEncryptionInfo); - - // Act - MethodInfo? method = type.GetMethod( - nameof(SqlConnectionEncryptionInfo.GetServerCertificate), - Type.EmptyTypes); - - // Assert - Assert.NotNull(method); - Assert.True(method.IsPublic); - Assert.Equal(typeof(X509Certificate2), method.ReturnType); - Assert.Null(type.GetProperty("PresentedServerCertificateHash256")); - Assert.Null(type.GetProperty("ServerCertificate")); - Assert.Null(type.GetProperty("PresentedServerCertificateRawData")); - } - - /// - /// Verifies that the returned certificate matches the captured DER bytes. - /// - [Fact] - public void GetServerCertificate_RoundTripsCertificate() - { - // Arrange - byte[] der = CreateSampleCertificate(); - SqlConnectionEncryptionInfo info = new(null, null, der, null, null); - - // Act - using X509Certificate2? certificate = info.GetServerCertificate(); - - // Assert - Assert.NotNull(certificate); - Assert.Equal(SampleCertificateThumbprint, certificate.Thumbprint); - Assert.Equal(SampleCertificateSubject, certificate.Subject); - Assert.Equal(der, certificate.RawData); - Assert.False(certificate.HasPrivateKey); - } - - /// - /// Verifies that every call returns a new, independently owned instance, and that - /// disposing one does not affect later calls. - /// - [Fact] - public void GetServerCertificate_ReturnsNewInstancePerCall() - { - // Arrange - SqlConnectionEncryptionInfo info = CreatePopulated(); - - // Act - X509Certificate2? first = info.GetServerCertificate(); - using X509Certificate2? second = info.GetServerCertificate(); - Assert.NotNull(first); - first.Dispose(); - using X509Certificate2? third = info.GetServerCertificate(); - - // Assert - Assert.NotNull(second); - Assert.NotNull(third); - Assert.NotSame(first, second); - Assert.NotSame(second, third); - Assert.Equal(SampleCertificateThumbprint, second.Thumbprint); - Assert.Equal(SampleCertificateThumbprint, third.Thumbprint); - } - - /// - /// Verifies that mutating the caller's array after construction does not change the - /// snapshot. - /// - [Fact] - public void GetServerCertificate_SourceMutation_DoesNotAffectSnapshot() - { - // Arrange - byte[] source = CreateSampleCertificate(); - SqlConnectionEncryptionInfo info = new(null, null, source, null, null); - - // Act - Array.Clear(source, 0, source.Length); - using X509Certificate2? certificate = info.GetServerCertificate(); - - // Assert - ReadOnlyMemory rawData = Assert.NotNull(info.PresentedServerCertificateRawData); - Assert.Equal(CreateSampleCertificate(), rawData.ToArray()); - Assert.NotNull(certificate); - Assert.Equal(SampleCertificateThumbprint, certificate.Thumbprint); - } - - /// - /// Verifies that mutating the raw data of a returned certificate does not change the - /// snapshot. - /// - [Fact] - public void GetServerCertificate_ReturnedRawDataMutation_DoesNotAffectSnapshot() - { - // Arrange - SqlConnectionEncryptionInfo info = CreatePopulated(); - - // Act - using (X509Certificate2? certificate = info.GetServerCertificate()) - { - Assert.NotNull(certificate); - byte[] raw = certificate.RawData; - Array.Clear(raw, 0, raw.Length); - } - using X509Certificate2? again = info.GetServerCertificate(); - - // Assert - Assert.NotNull(again); - Assert.Equal(SampleCertificateThumbprint, again.Thumbprint); - } - - /// - /// Verifies that null and empty certificate bytes are both reported as unavailable and - /// produce an empty snapshot. - /// - [Fact] - public void GetServerCertificate_NullOrEmpty_ReturnsNull() - { - // Act - SqlConnectionEncryptionInfo fromNull = new(null, null, null, null, null); - SqlConnectionEncryptionInfo fromEmpty = new(null, null, Array.Empty(), null, null); - - // Assert - AssertEmpty(fromNull); - AssertEmpty(fromEmpty); - } - - /// - /// Verifies that bytes that cannot be decoded as a certificate are reported as unavailable - /// instead of throwing. - /// - /// - /// The snapshot is still not empty: - /// reports whether the driver captured anything, and decoding is deferred to - /// . The driver's capture paths - /// only supply certificates from a completed TLS handshake, so this state is not expected - /// outside of tests. - /// - [Theory] - [InlineData(new byte[] { 0x01 })] - [InlineData(new byte[] { 0x30, 0x82, 0x01, 0x00, 0x00 })] - [InlineData(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF })] - public void GetServerCertificate_UndecodableBytes_ReturnsNull(byte[] bytes) - { - // Arrange - SqlConnectionEncryptionInfo info = new(null, null, bytes, null, null); - - // Act - using X509Certificate2? certificate = info.GetServerCertificate(); - - // Assert - Assert.Null(certificate); - Assert.False(info.IsEmpty); - } - - /// - /// Verifies that a captured certificate alone makes the snapshot non-empty. - /// - [Fact] - public void GetServerCertificate_CertificateOnly_IsNotEmpty() - { - // Arrange - SqlConnectionEncryptionInfo info = new(null, null, CreateSampleCertificate(), null, null); - - // Act - using X509Certificate2? certificate = info.GetServerCertificate(); - - // Assert - Assert.NotNull(certificate); - Assert.False(info.IsEmpty); - Assert.Null(info.NegotiatedEncryptionMode); - Assert.Null(info.ValidationErrors); - } - - #endregion - - #region Enum contracts - - /// - /// Verifies the underlying type and numeric values of . - /// - [Fact] - public void SqlConnectionEncryptionMode_HasExpectedValues() - { - // Act - Type underlyingType = Enum.GetUnderlyingType(typeof(SqlConnectionEncryptionMode)); - - // Assert - Assert.Equal(typeof(byte), underlyingType); - Assert.Equal(0, (int)SqlConnectionEncryptionMode.None); - Assert.Equal(1, (int)SqlConnectionEncryptionMode.LoginOnly); - Assert.Equal(2, (int)SqlConnectionEncryptionMode.Full); - Assert.Equal(3, (int)SqlConnectionEncryptionMode.Strict); - Assert.Equal(4, Enum.GetValues(typeof(SqlConnectionEncryptionMode)).Length); - } - - /// - /// Verifies the numeric values and flags attribute of - /// . - /// - [Fact] - public void SqlServerCertificateValidationErrors_HasExpectedValues() - { - // Act - Type type = typeof(SqlServerCertificateValidationErrors); - - // Assert - Assert.True(type.IsDefined(typeof(FlagsAttribute), inherit: false)); - Assert.Equal(typeof(int), Enum.GetUnderlyingType(type)); - Assert.Equal(0, (int)SqlServerCertificateValidationErrors.None); - Assert.Equal(1, (int)SqlServerCertificateValidationErrors.ServerCertificateMissing); - Assert.Equal(2, (int)SqlServerCertificateValidationErrors.HostNameMismatch); - Assert.Equal(4, (int)SqlServerCertificateValidationErrors.ChainError); - Assert.Equal(8, (int)SqlServerCertificateValidationErrors.PinnedCertificateMismatch); - Assert.Equal(5, Enum.GetValues(type).Length); - } - - #endregion - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlConnectionTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlConnectionTests.cs deleted file mode 100644 index 0b7e1cd717..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlConnectionTests.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Xunit; -using static Microsoft.Data.SqlClient.UnitTests.Utilities.EncryptionInfoTestData; - -namespace Microsoft.Data.SqlClient.UnitTests; - -/// -/// Unit tests for members that do not need a server. -/// -public class SqlConnectionTests -{ - /// - /// Verifies the getter returns a non-null empty snapshot on a new connection. - /// - [Fact] - public void EncryptionInfo_NewConnection_ReturnsEmptySnapshot() - { - // Arrange - using SqlConnection connection = new(); - - // Act - SqlConnectionEncryptionInfo info = connection.EncryptionInfo; - - // Assert - AssertEmpty(info); - } - - /// - /// Verifies the getter returns a non-null empty snapshot on a connection with a connection - /// string that has not been opened. - /// - [Fact] - public void EncryptionInfo_UnopenedWithConnectionString_ReturnsEmptySnapshot() - { - // Arrange - using SqlConnection connection = new("Data Source=localhost;Encrypt=Strict"); - - // Act - SqlConnectionEncryptionInfo info = connection.EncryptionInfo; - - // Assert - AssertEmpty(info); - } - - /// - /// Verifies the getter returns a non-null empty snapshot after the connection is closed. - /// - [Fact] - public void EncryptionInfo_ClosedConnection_ReturnsEmptySnapshot() - { - // Arrange - using SqlConnection connection = new("Data Source=localhost"); - connection.Close(); - - // Act - SqlConnectionEncryptionInfo info = connection.EncryptionInfo; - - // Assert - AssertEmpty(info); - } - - /// - /// Verifies the getter does not throw and returns a non-null empty snapshot after the - /// connection is disposed. - /// - [Fact] - public void EncryptionInfo_DisposedConnection_ReturnsEmptySnapshot() - { - // Arrange - SqlConnection connection = new("Data Source=localhost"); - connection.Dispose(); - - // Act - SqlConnectionEncryptionInfo info = connection.EncryptionInfo; - - // Assert - AssertEmpty(info); - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlExceptionTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlExceptionTests.cs index 0c3aae1130..b6a2b078df 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlExceptionTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlExceptionTests.cs @@ -2,27 +2,23 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NETFRAMEWORK + using System; using System.Collections.Generic; +using System.ComponentModel; using System.IO; -using System.Runtime.Serialization; -using System.Security.Cryptography.X509Certificates; -#if NETFRAMEWORK using System.Runtime.Serialization.Formatters.Binary; using Microsoft.Data.Common.ConnectionString; -#endif using Xunit; -using static Microsoft.Data.SqlClient.UnitTests.Utilities.EncryptionInfoTestData; namespace Microsoft.Data.SqlClient.UnitTests; /// -/// Unit tests for . +/// Tests that instances correctly roundtrip when serialized. /// public class SqlExceptionTests { - // These tests use BinaryFormatter, which only exists on .NET Framework; it was removed from .NET. -#if NETFRAMEWORK private static SqlError ExampleSqlError => new(infoNumber: 123, errorState: 2, @@ -95,237 +91,6 @@ public void Serialization_RoundTrips() Assert.Null(actualException.BatchCommand); Assert.False(actualException._doNotReconnect); } -#endif - - #region EncryptionInfo - - /// - /// Verifies exceptions created via the error-collection factory return an empty snapshot. - /// - [Fact] - public void EncryptionInfo_CreateFromCollection_ReturnsEmptySnapshot() - { - // Act - SqlException exception = SqlException.CreateException(CreateErrorCollection(), ServerVersion); - - // Assert - AssertEmpty(exception.EncryptionInfo); - } - - /// - /// Verifies exceptions created via the single-error factory return an empty snapshot. - /// - [Fact] - public void EncryptionInfo_CreateFromError_ReturnsEmptySnapshot() - { - // Act - SqlException exception = SqlException.CreateException( - CreateError(), - ServerVersion, - internalConnection: null, - innerException: new InvalidOperationException("inner")); - - // Assert - AssertEmpty(exception.EncryptionInfo); - } - - /// - /// Verifies exceptions created via the connection-id factory return an empty snapshot. - /// - [Fact] - public void EncryptionInfo_CreateWithConnectionId_ReturnsEmptySnapshot() - { - // Act - SqlException exception = SqlException.CreateException( - CreateErrorCollection(), - ServerVersion, - Guid.NewGuid(), - innerException: null); - - // Assert - AssertEmpty(exception.EncryptionInfo); - } - - /// - /// Verifies exceptions created via the batch-command factory return an empty snapshot. - /// - [Fact] - public void EncryptionInfo_CreateWithBatchCommand_ReturnsEmptySnapshot() - { - // Act - SqlException exception = SqlException.CreateException( - CreateErrorCollection(), - ServerVersion, - new SqlBatchCommand("SELECT 1")); - - // Assert - AssertEmpty(exception.EncryptionInfo); - } - - /// - /// Verifies that a populated snapshot set internally is returned by the getter and is - /// preserved by . - /// - [Fact] - public void EncryptionInfo_PopulatedSnapshot_PreservedByInternalClone() - { - // Arrange - SqlConnectionEncryptionInfo info = CreatePopulated(); - SqlException exception = SqlException.CreateException(CreateErrorCollection(), ServerVersion); - exception.EncryptionInfo = info; - - // Act - SqlException clone = exception.InternalClone(); - - // Assert - Assert.Same(info, exception.EncryptionInfo); - Assert.Same(info, clone.EncryptionInfo); - Assert.Equal(SampleCipherSuite, clone.EncryptionInfo.NegotiatedCipherSuiteId); - } - - /// - /// Verifies that clearing the snapshot internally falls back to the empty snapshot. - /// - [Fact] - public void EncryptionInfo_SetNull_ReturnsEmptySnapshot() - { - // Arrange - SqlException exception = SqlException.CreateException(CreateErrorCollection(), ServerVersion); - exception.EncryptionInfo = CreatePopulated(); - - // Act - // The internal setter accepts null to clear the snapshot. - exception.EncryptionInfo = null!; - - // Assert - AssertEmpty(exception.EncryptionInfo); - } - - /// - /// Verifies that a deserialized exception returns a non-null empty snapshot and that the - /// snapshot is not written to the serialized payload. - /// - [Fact] - public void EncryptionInfo_DataContractRoundTrip_ReturnsEmptySnapshot() - { - // Arrange - SqlException original = SqlException.CreateException(CreateErrorCollection(), ServerVersion); - original.EncryptionInfo = CreatePopulated(); - - // Exception.Data is backed by an internal dictionary type, and GetObjectData writes the - // error collection, so these types must be known to the serializer. - DataContractSerializer serializer = new( - typeof(SqlException), - new[] - { - original.Data.GetType(), - typeof(SqlErrorCollection), - typeof(SqlError), - typeof(List), - }); - using MemoryStream stream = new(); - - // Act - serializer.WriteObject(stream, original); - stream.Position = 0; - string payload = new StreamReader(stream).ReadToEnd(); - stream.Position = 0; - SqlException? roundTripped = serializer.ReadObject(stream) as SqlException; - - // Assert - // The snapshot, including the certificate, is not written to the payload. - Assert.DoesNotContain(nameof(SqlException.EncryptionInfo), payload); - Assert.DoesNotContain(SampleCertificateThumbprint, payload, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain(SampleCertificateBase64.Substring(0, 24), payload); - Assert.DoesNotContain("encryption-info.test", payload); - - // The deserialized exception reports an empty snapshot. - Assert.NotNull(roundTripped); - Assert.Equal(original.Message, roundTripped.Message); - AssertEmpty(roundTripped.EncryptionInfo); - } - - // BinaryFormatter only exists on .NET Framework. -#if NETFRAMEWORK - /// - /// Verifies BinaryFormatter serialization is unaffected by the non-serialized snapshot field - /// and that the deserialized exception returns a non-null empty snapshot. - /// - [Fact] - public void EncryptionInfo_BinaryFormatterRoundTrip_ReturnsEmptySnapshot() - { - // Arrange - SqlException original = SqlException.CreateException(CreateErrorCollection(), ServerVersion); - original.EncryptionInfo = CreatePopulated(); - BinaryFormatter formatter = new(); - using MemoryStream stream = new(); - - // Act - formatter.Serialize(stream, original); - stream.Position = 0; - SqlException roundTripped = (SqlException)formatter.Deserialize(stream); +} - // Assert - Assert.Equal(original.Message, roundTripped.Message); - AssertEmpty(roundTripped.EncryptionInfo); - } #endif - - /// - /// Verifies that and do - /// not change when a populated snapshot is attached, and that no snapshot value leaks into - /// them. - /// - [Fact] - public void EncryptionInfo_PopulatedSnapshot_MessageAndToStringUnchanged() - { - // Arrange - Guid connectionId = Guid.NewGuid(); - SqlException withoutInfo = SqlException.CreateException(CreateErrorCollection(), ServerVersion, connectionId, null); - SqlException withInfo = SqlException.CreateException(CreateErrorCollection(), ServerVersion, connectionId, null); - - // Act - withInfo.EncryptionInfo = CreatePopulated(); - - // Assert - Assert.Equal(withoutInfo.Message, withInfo.Message); - Assert.Equal(withoutInfo.ToString(), withInfo.ToString()); - Assert.DoesNotContain(SampleCertificateThumbprint, withInfo.ToString(), StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain(SampleCertificateThumbprint, withInfo.Message, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain(SampleCertificateBase64.Substring(0, 24), withInfo.ToString()); - Assert.DoesNotContain("encryption-info.test", withInfo.ToString()); - Assert.DoesNotContain(nameof(SqlConnectionEncryptionInfo.GetServerCertificate), withInfo.ToString()); - Assert.DoesNotContain(nameof(SqlConnectionEncryptionMode.Strict), withInfo.Message); - Assert.DoesNotContain("NegotiatedCipherSuite", withInfo.ToString()); - Assert.DoesNotContain("TLS_AES_256_GCM_SHA384", withInfo.ToString()); - } - - /// - /// Verifies that a cloned exception exposes an equivalent certificate, and that disposing a - /// certificate returned from one exception does not affect the other. - /// - [Fact] - public void EncryptionInfo_InternalClone_ServerCertificateIsIsolated() - { - // Arrange - SqlException exception = SqlException.CreateException(CreateErrorCollection(), ServerVersion); - exception.EncryptionInfo = CreatePopulated(); - SqlException clone = exception.InternalClone(); - - // Act - X509Certificate2? fromOriginal = exception.EncryptionInfo.GetServerCertificate(); - using X509Certificate2? fromClone = clone.EncryptionInfo.GetServerCertificate(); - Assert.NotNull(fromOriginal); - fromOriginal.Dispose(); - using X509Certificate2? again = exception.EncryptionInfo.GetServerCertificate(); - - // Assert - Assert.NotNull(fromClone); - Assert.NotNull(again); - Assert.NotSame(fromOriginal, fromClone); - Assert.Equal(SampleCertificateThumbprint, fromClone.Thumbprint); - Assert.Equal(SampleCertificateThumbprint, again.Thumbprint); - } - - #endregion -} diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Utilities/EncryptionInfoTestData.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Utilities/EncryptionInfoTestData.cs deleted file mode 100644 index b5241f20c8..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/Utilities/EncryptionInfoTestData.cs +++ /dev/null @@ -1,140 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics.CodeAnalysis; -using System.Security.Authentication; -using System.Security.Cryptography.X509Certificates; -using Xunit; - -namespace Microsoft.Data.SqlClient.UnitTests.Utilities; - -/// -/// Shared data and assertions for tests of and the -/// getters that expose it. -/// -internal static class EncryptionInfoTestData -{ - /// - /// Server version reported by exceptions created through the internal factories. - /// - internal const string ServerVersion = "16.00.1000"; - - /// - /// Base64 DER encoding of a public-only, self-signed ECDSA P-256 test certificate - /// (CN=encryption-info.test). It has no private key and is used only to verify DER - /// round-tripping. - /// - internal const string SampleCertificateBase64 = - "MIIBNDCB2qADAgECAggohG/gEdxs1TAKBggqhkjOPQQDAjAfMR0wGwYDVQQDExRlbmNyeXB0aW9uLWluZm8u" + - "dGVzdDAgFw0yNjAxMDEwMDAwMDBaGA8yMTI2MDEwMTAwMDAwMFowHzEdMBsGA1UEAxMUZW5jcnlwdGlvbi1p" + - "bmZvLnRlc3QwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATKtC9pE1F5JC1ciq1W/ANr5OBPgXrlvMpmPXMr" + - "ectPyl630QJbCUT640lSLXUfdF3/8iTglUTiCyxg7SNUztJKMAoGCCqGSM49BAMCA0kAMEYCIQDoHA2MzlvfTWHm" + - "n8Iioi8sMoKAnV/DcSrw50GwJf+fGAIhAPCezMdXBEwwpf4MU2fkmifrj36YES+JJM49BDRItkIl"; - - /// - /// SHA-1 thumbprint of the sample certificate, used to confirm the round-tripped identity. - /// - internal const string SampleCertificateThumbprint = "60820F552FF4F3CAAEC10B18EB468A16F01D7313"; - - /// - /// Subject distinguished name of the sample certificate. - /// - internal const string SampleCertificateSubject = "CN=encryption-info.test"; - - /// - /// IANA identifier for TLS_AES_256_GCM_SHA384. - /// - internal const int SampleCipherSuite = 0x1302; - - /// - /// Creates a new array holding the DER encoding of the sample certificate. - /// - /// A new array that the caller may mutate. - internal static byte[] CreateSampleCertificate() => - Convert.FromBase64String(SampleCertificateBase64); - - /// - /// Creates a snapshot with only the negotiated cipher suite set, passing it to the internal - /// constructor as the type it takes on the current target framework. - /// - /// The IANA cipher suite identifier. - /// The snapshot. - internal static SqlConnectionEncryptionInfo CreateWithCipherSuite(int cipherSuite) => - new(null, null, null, null, null, ToConstructorCipherSuite(cipherSuite)); - - /// - /// Creates a snapshot with every field populated with a distinct non-default value. - /// - /// The populated snapshot. - internal static SqlConnectionEncryptionInfo CreatePopulated() => - new( - SqlConnectionEncryptionMode.Strict, - SslProtocols.Tls12, - CreateSampleCertificate(), - SqlServerCertificateValidationErrors.HostNameMismatch, - X509ChainStatusFlags.UntrustedRoot, - ToConstructorCipherSuite(SampleCipherSuite)); - -#if NET - /// - /// Converts an IANA identifier to the cipher suite type the internal constructor takes on .NET. - /// - /// The IANA cipher suite identifier. - /// The identifier as a . - internal static System.Net.Security.TlsCipherSuite ToConstructorCipherSuite(int cipherSuite) => - (System.Net.Security.TlsCipherSuite)cipherSuite; -#else - /// - /// Returns the IANA identifier unchanged, matching the type the internal constructor takes on - /// .NET Framework. - /// - /// The IANA cipher suite identifier. - /// The identifier. - internal static int ToConstructorCipherSuite(int cipherSuite) => cipherSuite; -#endif - - /// - /// Creates a server error used to build exceptions through the internal factories. - /// - /// The error. - internal static SqlError CreateError() => - new( - infoNumber: 50000, - errorState: 1, - errorClass: 16, - server: "server", - errorMessage: "Test error message.", - procedure: "proc", - lineNumber: 1, - exception: null, - batchIndex: -1); - - /// - /// Creates an error collection holding a single error from . - /// - /// The error collection. - internal static SqlErrorCollection CreateErrorCollection() => new() { CreateError() }; - - /// - /// Asserts that a snapshot is non-null, reports itself as empty, and has every field - /// unavailable. - /// - /// The snapshot to check. - internal static void AssertEmpty([NotNull] SqlConnectionEncryptionInfo? info) - { - Assert.NotNull(info); - Assert.True(info.IsEmpty); - Assert.Null(info.NegotiatedEncryptionMode); - Assert.Null(info.NegotiatedEncryptionProtocol); - Assert.Null(info.NegotiatedCipherSuiteId); -#if NET - Assert.Null(info.NegotiatedCipherSuite); -#endif - Assert.Null(info.PresentedServerCertificateRawData); - Assert.Null(info.GetServerCertificate()); - Assert.Null(info.ValidationErrors); - Assert.Null(info.ChainStatus); - } -}