diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParser.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParser.cs index 41ee1e2236..d319b839b3 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParser.cs @@ -1500,7 +1500,10 @@ internal void TdsLogin( #nullable enable internal void ProcessSSPI(int receivedLength) { - Debug.Assert(_authenticationProvider is not null); + if (_authenticationProvider is null) + { + ThrowCorruptedTdsStream(); + } SniContext outerContext = _physicalStateObj.SniContext; _physicalStateObj.SniContext = SniContext.Snix_ProcessSspi; @@ -2453,7 +2456,8 @@ internal bool Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader } /// - /// Checks if the given token is a valid TDS token + /// Checks whether the token type is recognized. Its handler must also validate the + /// parser state required to process it. /// /// Token to check /// True if the token is a valid TDS token, otherwise false @@ -2491,6 +2495,19 @@ internal static bool IsValidTdsToken(byte token) token == TdsEnums.SQLFEDAUTHINFO); } + /// + /// Rejects invalid token prerequisites using the existing parsing error, after ensuring + /// the connection cannot be reused. This does not convert other failures to SqlException. + /// + internal void ThrowCorruptedTdsStream() + { + SqlClientEventSource.Log.TryTraceEvent( + " Invalid state for received TDS token. Object ID {0}", ObjectID); + _state = TdsParserState.Broken; + _connHandler.BreakConnection(); + throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); + } + // Main parse loop for the top-level tds tokens, calls back into the I*Handler interfaces internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, out bool dataReady) { @@ -2971,7 +2988,10 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle case TdsEnums.SQLROW: case TdsEnums.SQLNBCROW: { - Debug.Assert(stateObj._cleanupMetaData != null, "Reading a row, but the metadata is null"); + if (stateObj._cleanupMetaData == null) + { + ThrowCorruptedTdsStream(); + } if (token == TdsEnums.SQLNBCROW) { @@ -3128,6 +3148,11 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle } case TdsEnums.SQLALTROW: { + if (stateObj._cleanupAltMetaDataSetArray == null) + { + ThrowCorruptedTdsStream(); + } + result = stateObj.TryStartNewRow(isNullCompressed: false); if (result != TdsOperationStatus.Done) { @@ -3146,7 +3171,14 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle return result; } - result = TrySkipRow(stateObj._cleanupAltMetaDataSetArray.GetAltMetadata(altRowId), stateObj); + TdsColumnMetadataToken metadata = + stateObj._cleanupAltMetaDataSetArray.GetAltMetadata(altRowId); + if (metadata == null) + { + ThrowCorruptedTdsStream(); + } + + result = TrySkipRow(metadata, stateObj); if (result != TdsOperationStatus.Done) { // skip altRow diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/Tokens/TdsAltMetadataCollection.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/Tokens/TdsAltMetadataCollection.cs index 3d90496545..bfaaf14500 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/Tokens/TdsAltMetadataCollection.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/Tokens/TdsAltMetadataCollection.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; -using System.Diagnostics; namespace Microsoft.Data.SqlClient.Parser.Tokens { @@ -57,8 +56,6 @@ internal TdsColumnMetadataToken GetAltMetadata(int id) } } - // @TODO: Debug fail usage here isn't ideal. - Debug.Fail("Can't match up altMetaDataSet with given id"); return null; } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDataReader.cs index fb3da28196..08cb29d221 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -3328,6 +3328,11 @@ private TdsOperationStatus TryHasMoreResults(out bool moreResults) // deprecated case TdsEnums.SQLALTROW: + if (_altMetaDataSetCollection == null) + { + _parser.ThrowCorruptedTdsStream(); + } + if (_altRowStatus == ALTROWSTATUS.Null) { // cache the regular metadata @@ -3585,6 +3590,11 @@ private TdsOperationStatus TryNextResult(out bool more) switch (_altRowStatus) { case ALTROWSTATUS.AltRow: + if (_altMetaDataSetCollection == null) + { + _parser.ThrowCorruptedTdsStream(); + } + int altRowId; result = _parser.TryGetAltRowId(_stateObj, out altRowId); if (result != TdsOperationStatus.Done) @@ -3593,11 +3603,11 @@ private TdsOperationStatus TryNextResult(out bool more) return result; } TdsColumnMetadataToken altMetaDataSet = _altMetaDataSetCollection.GetAltMetadata(altRowId); - if (altMetaDataSet != null) + if (altMetaDataSet == null) { - _metaData = altMetaDataSet; + _parser.ThrowCorruptedTdsStream(); } - Debug.Assert((_metaData != null), "Can't match up altrowmetadata"); + _metaData = altMetaDataSet; break; case ALTROWSTATUS.Done: // restore the row-metaData diff --git a/src/Microsoft.Data.SqlClient/tests/Common/ConnectionPoolVersionScope.cs b/src/Microsoft.Data.SqlClient/tests/Common/ConnectionPoolVersionScope.cs new file mode 100644 index 0000000000..73cb0af9b7 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/Common/ConnectionPoolVersionScope.cs @@ -0,0 +1,64 @@ +// 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.Tests.Common; + +/// +/// Selects the connection pool implementation (WaitHandleDbConnectionPool or +/// ChannelDbConnectionPool) for the duration of a test. +/// +/// A pool is bound to an implementation when it is created, so simply flipping the +/// UseConnectionPoolV2 switch is not enough: pools created before the switch was flipped +/// keep their original implementation, and pools created inside the scope would otherwise outlive +/// it and leak the chosen implementation into unrelated tests. This scope therefore clears all +/// pools both on entry and on exit. +/// +/// This follows the RAII pattern; construct it at the start of a test and dispose it at the end. +/// Like , it manipulates global state and enforces a +/// single-instance policy, so it must not be held for longer than necessary. +/// +public sealed class ConnectionPoolVersionScope : IDisposable +{ + private readonly LocalAppContextSwitchesHelper _switches; + + /// + /// Clears all existing pools and selects the requested pool implementation. + /// + /// + /// True to use ChannelDbConnectionPool; false to use WaitHandleDbConnectionPool. + /// + public ConnectionPoolVersionScope(bool usePoolV2) + { + _switches = new LocalAppContextSwitchesHelper(); + + try + { + SqlConnection.ClearAllPools(); + _switches.UseConnectionPoolV2 = usePoolV2; + } + catch + { + _switches.Dispose(); + throw; + } + } + + /// + /// Clears all pools created under the selected implementation and restores the original + /// switch values. + /// + public void Dispose() + { + try + { + SqlConnection.ClearAllPools(); + } + finally + { + _switches.Dispose(); + } + } +} diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTests.csproj b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTests.csproj index 6d90a8beea..067fb8ea5b 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTests.csproj @@ -99,6 +99,7 @@ + diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/ParserResultProcessingTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/ParserResultProcessingTest.cs new file mode 100644 index 0000000000..6178a4f88b --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/ParserResultProcessingTest.cs @@ -0,0 +1,71 @@ +// 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.Data; +using System.Threading.Tasks; +using Xunit; + +namespace Microsoft.Data.SqlClient.ManualTesting.Tests; + +/// +/// Verifies that parser prerequisite validation preserves valid login, nullable rows, +/// result skipping, and subsequent commands against SQL Server. +/// +[Trait("Set", "2")] +public class ParserResultProcessingTest +{ + /// + /// Consumes null and non-null values, skips unread rows, and reuses the connection with + /// synchronous/asynchronous APIs and both buffered and sequential access. + /// + [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public async Task ValidResults_PreserveConnection(bool useAsync, bool sequential) + { + using SqlConnection connection = new(DataTestUtility.TCPConnectionString); + if (useAsync) + { + await connection.OpenAsync(); + } + else + { + connection.Open(); + } + + // Sorting puts NULL first and leaves a deterministic unread row before the second result. + using SqlCommand command = new( + "SELECT CAST(NULL AS int) AS value UNION ALL SELECT 1 UNION ALL SELECT 2 " + + "ORDER BY value; " + + "SELECT 42 AS value;", connection); + CommandBehavior behavior = sequential + ? CommandBehavior.SequentialAccess + : CommandBehavior.Default; + using (SqlDataReader reader = useAsync + ? await command.ExecuteReaderAsync(behavior) + : command.ExecuteReader(behavior)) + { + Assert.True(useAsync ? await reader.ReadAsync() : reader.Read()); + Assert.True(reader.IsDBNull(0)); + Assert.True(useAsync ? await reader.ReadAsync() : reader.Read()); + Assert.Equal(1, reader.GetInt32(0)); + // Skip the unread value 2 and verify that the next result uses its own metadata. + Assert.True(useAsync ? await reader.NextResultAsync() : reader.NextResult()); + Assert.True(useAsync ? await reader.ReadAsync() : reader.Read()); + Assert.Equal(42, reader.GetInt32(0)); + Assert.False(useAsync ? await reader.ReadAsync() : reader.Read()); + Assert.False(useAsync ? await reader.NextResultAsync() : reader.NextResult()); + } + + // A subsequent command proves valid result processing did not invalidate the connection. + command.CommandText = "SELECT 7"; + object result = useAsync + ? await command.ExecuteScalarAsync() + : command.ExecuteScalar(); + Assert.Equal(7, result); + Assert.Equal(ConnectionState.Open, connection.State); + } +} diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/Fixtures/SimulatedServerPoolScope.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/Fixtures/SimulatedServerPoolScope.cs new file mode 100644 index 0000000000..216d8c12c9 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/Fixtures/SimulatedServerPoolScope.cs @@ -0,0 +1,34 @@ +// 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.UnitTests.SimulatedServerTests; + +/// +/// Gives a scenario its own pool and clears it before its ephemeral servers are disposed. +/// Declare before the scenario's connections so they are returned before the pool is cleared. +/// +internal sealed class SimulatedServerPoolScope : IDisposable +{ + private readonly SqlConnection _poolKey; + + /// + /// Isolates the builder's pool from other test cases and previous uses of the same TCP port. + /// + public SimulatedServerPoolScope(SqlConnectionStringBuilder builder) + { + builder.ApplicationName = Guid.NewGuid().ToString(); + _poolKey = new SqlConnection(builder.ConnectionString); + } + + /// + /// Removes only this scenario's pool, without affecting other simulator clients. + /// + public void Dispose() + { + SqlConnection.ClearPool(_poolKey); + _poolKey.Dispose(); + } +} diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ParserPrerequisiteTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ParserPrerequisiteTests.cs new file mode 100644 index 0000000000..f68757b2c4 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ParserPrerequisiteTests.cs @@ -0,0 +1,714 @@ +// 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.Data; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Data.SqlClient.Parser; +using Microsoft.Data.SqlClient.Tests.Common; +using Microsoft.SqlServer.TDS; +using Microsoft.SqlServer.TDS.ColMetadata; +using Microsoft.SqlServer.TDS.Done; +using Microsoft.SqlServer.TDS.Info; +using Microsoft.SqlServer.TDS.Row; +using Microsoft.SqlServer.TDS.SSPI; +using Xunit; + +namespace Microsoft.Data.SqlClient.UnitTests.SimulatedServerTests; + +/// +/// Ensures server tokens cannot consume missing parser state and that rejected connections +/// are not reused, without changing valid login or result processing. +/// +[Collection(SimulatedServerTestCollection.Name)] +public class ParserPrerequisiteTests +{ + /// Open rejects tokens whose metadata or authentication state is missing. + [Theory] + [InlineData(TDSTokenType.Row)] + [InlineData(TDSTokenType.NBCRow)] + [InlineData(TDSTokenType.AlternativeRow)] + [InlineData(TDSTokenType.SSPI)] + public void Open_WithoutRequiredState_ThrowsParsingError(TDSTokenType tokenType) + { + // Arrange + using TdsServerFixture fixture = CreateInvalidLoginFixture(tokenType); + using SqlConnection connection = new(CreateBuilder(fixture).ConnectionString); + + // Act + InvalidOperationException error = Assert.Throws(connection.Open); + + // Assert + AssertRejectedConnection(error, connection); + Assert.Equal(1, fixture.TdsServer.PreLoginCount); + } + + /// OpenAsync rejects tokens missing metadata or authentication state. + [Theory] + [InlineData(TDSTokenType.Row)] + [InlineData(TDSTokenType.NBCRow)] + [InlineData(TDSTokenType.AlternativeRow)] + [InlineData(TDSTokenType.SSPI)] + public async Task OpenAsync_WithoutRequiredState_ThrowsParsingError(TDSTokenType tokenType) + { + // Arrange + using TdsServerFixture fixture = CreateInvalidLoginFixture(tokenType); + using SqlConnection connection = new(CreateBuilder(fixture).ConnectionString); + + // Act + InvalidOperationException error = await Assert.ThrowsAsync( + () => connection.OpenAsync()); + + // Assert + AssertRejectedConnection(error, connection); + Assert.Equal(1, fixture.TdsServer.PreLoginCount); + } + + /// Repeated sync parser failures release the sole slot in the supported pool. + [Theory] + [InlineData(false)] + [InlineData(true)] + public Task ParserFailure_DoesNotPoisonPool(bool duringLogin) => + AssertPoolRecovery(duringLogin, + connection => + { + connection.Open(); + return Task.CompletedTask; + }, + command => Task.FromResult(command.ExecuteNonQuery())); + + /// Repeated async parser failures release the sole slot in the supported pool. + [Theory] + [InlineData(false)] + [InlineData(true)] + public Task ParserFailureAsync_DoesNotPoisonPool(bool duringLogin) => + AssertPoolRecovery(duringLogin, + connection => connection.OpenAsync(), command => command.ExecuteNonQueryAsync()); + + /// Non-query row skipping rejects a batch without required row metadata. + [Theory] + [InlineData(TDSTokenType.Row)] + [InlineData(TDSTokenType.NBCRow)] + [InlineData(TDSTokenType.AlternativeRow)] + public void ExecuteNonQuery_WithoutRequiredState_ThrowsParsingError(TDSTokenType tokenType) + { + // Arrange + using BatchTestContext context = new(response => SetInvalidBatch(response, tokenType)); + context.Connection.Open(); + + // Act + InvalidOperationException error = Assert.Throws( + () => context.Command.ExecuteNonQuery()); + + // Assert + AssertRejectedConnection(error, context.Connection); + } + + /// Asynchronous non-query row skipping rejects missing row metadata. + [Theory] + [InlineData(TDSTokenType.Row)] + [InlineData(TDSTokenType.NBCRow)] + [InlineData(TDSTokenType.AlternativeRow)] + public async Task ExecuteNonQueryAsync_WithoutRequiredState_ThrowsParsingError( + TDSTokenType tokenType) + { + // Arrange + using BatchTestContext context = new(response => SetInvalidBatch(response, tokenType)); + await context.Connection.OpenAsync(); + + // Act + InvalidOperationException error = await Assert.ThrowsAsync( + () => context.Command.ExecuteNonQueryAsync()); + + // Assert + AssertRejectedConnection(error, context.Connection); + } + + /// Reader consumption rejects missing row metadata before disposal. + [Theory] + [InlineData(TDSTokenType.Row)] + [InlineData(TDSTokenType.NBCRow)] + [InlineData(TDSTokenType.AlternativeRow)] + public void ExecuteReader_WithoutRequiredState_ThrowsParsingError(TDSTokenType tokenType) + { + // Arrange + using BatchTestContext context = new(response => SetInvalidBatch(response, tokenType)); + context.Connection.Open(); + SqlDataReader? reader = null; + + // Act + Exception? error = Record.Exception(() => + { + reader = context.Command.ExecuteReader(); + reader.Read(); + }); + + // Assert / Cleanup + AssertRejectedReader(error, context.Connection, reader); + } + + /// Async reader consumption rejects missing row metadata before disposal. + [Theory] + [InlineData(TDSTokenType.Row)] + [InlineData(TDSTokenType.NBCRow)] + [InlineData(TDSTokenType.AlternativeRow)] + public async Task ExecuteReaderAsync_WithoutRequiredState_ThrowsParsingError( + TDSTokenType tokenType) + { + // Arrange + using BatchTestContext context = new(response => SetInvalidBatch(response, tokenType)); + await context.Connection.OpenAsync(); + SqlDataReader? reader = null; + + // Act + Exception? error = await Record.ExceptionAsync(async () => + { + reader = await context.Command.ExecuteReaderAsync(); + await reader.ReadAsync(); + }); + + // Assert / Cleanup + AssertRejectedReader(error, context.Connection, reader); + } + + /// Non-query execution rejects alternate rows without matching metadata. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ExecuteNonQuery_AlternateRowWithoutMatchingMetadata_ThrowsParsingError( + bool includeAlternateMetadata) + { + // Arrange + using BatchTestContext context = new(response => + SetResult(response, includeAlternateMetadata, alternateId: 2)); + context.Connection.Open(); + + // Act + InvalidOperationException error = Assert.Throws( + () => context.Command.ExecuteNonQuery()); + + // Assert + AssertRejectedConnection(error, context.Connection); + } + + /// Async non-query execution rejects unmatched alternate-row metadata. + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ExecuteNonQueryAsync_AlternateRowWithoutMatchingMetadata_ThrowsParsingError( + bool includeAlternateMetadata) + { + // Arrange + using BatchTestContext context = new(response => + SetResult(response, includeAlternateMetadata, alternateId: 2)); + await context.Connection.OpenAsync(); + + // Act + InvalidOperationException error = await Assert.ThrowsAsync( + () => context.Command.ExecuteNonQueryAsync()); + + // Assert + AssertRejectedConnection(error, context.Connection); + } + + /// Result transitions reject unmatched alternate rows before disposal. + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void NextResult_AlternateRowWithoutMatchingMetadata_ThrowsParsingError( + bool includeAlternateMetadata, bool readAllRows) + { + // Arrange + using BatchTestContext context = new(response => + SetResult(response, includeAlternateMetadata, alternateId: 2)); + context.Connection.Open(); + SqlDataReader? reader = null; + + // Act + Exception? error = Record.Exception(() => + { + reader = context.Command.ExecuteReader(); + ReadPrimaryRows(reader, readAllRows); + reader.NextResult(); + }); + + // Assert / Cleanup + AssertRejectedReader(error, context.Connection, reader); + } + + /// Async transitions reject unmatched alternate rows before disposal. + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public async Task NextResultAsync_AlternateRowWithoutMatchingMetadata_ThrowsParsingError( + bool includeAlternateMetadata, bool readAllRows) + { + // Arrange + using BatchTestContext context = new(response => + SetResult(response, includeAlternateMetadata, alternateId: 2)); + await context.Connection.OpenAsync(); + SqlDataReader? reader = null; + + // Act + Exception? error = await Record.ExceptionAsync(async () => + { + reader = await context.Command.ExecuteReaderAsync(); + await ReadPrimaryRowsAsync(reader, readAllRows); + await reader.NextResultAsync(); + }); + + // Assert / Cleanup + AssertRejectedReader(error, context.Connection, reader); + } + + /// Non-query execution skips valid primary and alternate results. + [Fact] + public void ExecuteNonQuery_ValidMetadata_PreservesConnection() + { + // Arrange + using BatchTestContext context = new(SetValidResult); + context.Connection.Open(); + + // Act + context.Command.ExecuteNonQuery(); + + // Assert + Assert.Equal(ConnectionState.Open, context.Connection.State); + } + + /// Asynchronous non-query execution skips valid results without rejection. + [Fact] + public async Task ExecuteNonQueryAsync_ValidMetadata_PreservesConnection() + { + // Arrange + using BatchTestContext context = new(SetValidResult); + await context.Connection.OpenAsync(); + + // Act + await context.Command.ExecuteNonQueryAsync(); + + // Assert + Assert.Equal(ConnectionState.Open, context.Connection.State); + } + + /// Result transitions skip a null row and consume the alternate result. + [Fact] + public void NextResult_ValidMetadata_PreservesResultProcessing() + { + // Arrange + using BatchTestContext context = new(SetValidResult); + context.Connection.Open(); + using (SqlDataReader reader = context.Command.ExecuteReader()) + { + ReadPrimaryRows(reader, readAllRows: false); + + // Act + bool hasAlternateResult = reader.NextResult(); + + // Assert + Assert.True(hasAlternateResult); + Assert.True(reader.Read()); + Assert.Equal(42, reader.GetInt32(0)); + Assert.False(reader.Read()); + Assert.False(reader.NextResult()); + } + + // Cleanup + Assert.Equal(ConnectionState.Open, context.Connection.State); + } + + /// Async transitions skip a null row and consume the alternate result. + [Fact] + public async Task NextResultAsync_ValidMetadata_PreservesResultProcessing() + { + // Arrange + using BatchTestContext context = new(SetValidResult); + await context.Connection.OpenAsync(); + using (SqlDataReader reader = await context.Command.ExecuteReaderAsync()) + { + await ReadPrimaryRowsAsync(reader, readAllRows: false); + + // Act + bool hasAlternateResult = await reader.NextResultAsync(); + + // Assert + Assert.True(hasAlternateResult); + Assert.True(await reader.ReadAsync()); + Assert.Equal(42, reader.GetInt32(0)); + Assert.False(await reader.ReadAsync()); + Assert.False(await reader.NextResultAsync()); + } + + // Cleanup + Assert.Equal(ConnectionState.Open, context.Connection.State); + } + + /// Packet continuation preserves lookup of a known alternate-row identifier. + [Fact] + public void ExecuteNonQuery_KnownAlternateRowIdAcrossPackets_PreservesConnection() + { + // Arrange + using BatchTestContext context = new(); + context.Connection.Open(); + context.SetPacketBoundaryResponse(alternateId: 1); + + // Act + context.Command.ExecuteNonQuery(); + + // Assert + Assert.Equal(ConnectionState.Open, context.Connection.State); + } + + /// Asynchronous packet continuation preserves lookup of a known identifier. + [Fact] + public async Task ExecuteNonQueryAsync_KnownAlternateRowIdAcrossPackets_PreservesConnection() + { + // Arrange + using BatchTestContext context = new(); + await context.Connection.OpenAsync(); + context.SetPacketBoundaryResponse(alternateId: 1); + + // Act + await context.Command.ExecuteNonQueryAsync(); + + // Assert + Assert.Equal(ConnectionState.Open, context.Connection.State); + } + + /// Packet continuation rejects an unknown alternate-row identifier. + [Fact] + public void ExecuteNonQuery_UnknownAlternateRowIdAcrossPackets_ThrowsParsingError() + { + // Arrange + using BatchTestContext context = new(); + context.Connection.Open(); + context.SetPacketBoundaryResponse(alternateId: 2); + + // Act + InvalidOperationException error = Assert.Throws( + () => context.Command.ExecuteNonQuery()); + + // Assert + AssertRejectedConnection(error, context.Connection); + } + + /// Asynchronous packet continuation rejects an unknown identifier. + [Fact] + public async Task ExecuteNonQueryAsync_UnknownAlternateRowIdAcrossPackets_ThrowsParsingError() + { + // Arrange + using BatchTestContext context = new(); + await context.Connection.OpenAsync(); + context.SetPacketBoundaryResponse(alternateId: 2); + + // Act + InvalidOperationException error = await Assert.ThrowsAsync( + () => context.Command.ExecuteNonQueryAsync()); + + // Assert + AssertRejectedConnection(error, context.Connection); + } + + /// Starts a server that sends a token missing its state during login. + /// The token to send without metadata or a provider. + /// A running fixture owned by the caller. + private static TdsServerFixture CreateInvalidLoginFixture(TDSTokenType tokenType) + { + TdsServerFixture fixture = new(); + fixture.TdsServer.OnAuthenticationResponseCompleted = response => + { + response.Clear(); + response.Add(CreateToken(tokenType)); + }; + return fixture; + } + + /// Checks rejection and recovery using the supplied public entry points. + /// Whether to inject the malformed token during login. + /// The synchronous or asynchronous connection-opening operation. + /// The corresponding non-query operation. + /// A task that completes after a fresh physical connection is verified. + private static async Task AssertPoolRecovery(bool duringLogin, + Func open, Func execute) + { + // Arrange + using ConnectionPoolVersionScope version = new(usePoolV2: false); + using TdsServerFixture fixture = new(); + SqlConnectionStringBuilder builder = CreateBuilder(fixture); + builder.Pooling = true; + builder.MaxPoolSize = 1; + builder.PoolBlockingPeriod = PoolBlockingPeriod.NeverBlock; + using SimulatedServerPoolScope pool = new(builder); + void SetInvalidResponse(TDSMessage response) + { + response.Clear(); + response.Add(CreateToken(TDSTokenType.Row)); + } + if (duringLogin) + { + fixture.TdsServer.OnAuthenticationResponseCompleted = SetInvalidResponse; + } + else + { + fixture.TdsServer.OnSQLBatchCompleted = SetInvalidResponse; + } + + // Act / Assert: repeated failures must release the sole pool slot. + for (int attempt = 0; attempt < 2; attempt++) + { + using SqlConnection failed = new(builder.ConnectionString); + InvalidOperationException error = await Assert.ThrowsAsync( + async () => + { + await open(failed); + using SqlCommand command = new("SELECT 1", failed); + await execute(command); + }); + AssertRejectedConnection(error, failed); + } + + // Cleanup / Assert: recovery requires a fresh physical login. + fixture.TdsServer.OnAuthenticationResponseCompleted = null; + fixture.TdsServer.OnSQLBatchCompleted = null; + using SqlConnection valid = new(builder.ConnectionString); + await open(valid); + Assert.Equal(ConnectionState.Open, valid.State); + Assert.Equal(3, fixture.TdsServer.PreLoginCount); + } + + /// Checks that the corrupted-stream error closes the connection. + /// The operation's exception, captured before cleanup. + /// The connection that consumed the malformed response. + private static void AssertRejectedConnection( + InvalidOperationException error, SqlConnection connection) + { + Assert.Contains("Error state: 18", error.Message); + Assert.Equal(ConnectionState.Closed, connection.State); + } + + /// Checks rejection and connection state independently of reader cleanup. + /// The exception captured while opening or consuming the reader. + /// The connection whose state must be closed before disposal. + /// The reader to dispose, if execution returned one. + private static void AssertRejectedReader( + Exception? error, SqlConnection connection, SqlDataReader? reader) + { + ConnectionState stateAfterOperation = connection.State; + Exception? disposeError = Record.Exception(() => reader?.Dispose()); + AssertRejectedConnection(Assert.IsType(error), connection); + Assert.Equal(ConnectionState.Closed, stateAfterOperation); + Assert.Null(disposeError); + } + + /// Consumes the primary value and optionally the null row. + /// The reader positioned before the primary rows. + /// Whether to consume the null row rather than skip it. + private static void ReadPrimaryRows(SqlDataReader reader, bool readAllRows) + { + Assert.True(reader.Read()); + Assert.Equal(1, reader.GetInt32(0)); + if (readAllRows) + { + Assert.True(reader.Read()); + Assert.True(reader.IsDBNull(0)); + } + } + + /// Asynchronously consumes the primary value and optionally the null row. + /// The reader positioned before the primary rows. + /// Whether to consume the null row rather than skip it. + /// A task that completes after the selected rows are checked. + private static async Task ReadPrimaryRowsAsync(SqlDataReader reader, bool readAllRows) + { + Assert.True(await reader.ReadAsync()); + Assert.Equal(1, reader.GetInt32(0)); + if (readAllRows) + { + Assert.True(await reader.ReadAsync()); + Assert.True(reader.IsDBNull(0)); + } + } + + /// Owns the repeated server, connection and command setup for batch tests. + private sealed class BatchTestContext : IDisposable + { + private readonly TdsServerFixture _fixture = new(); + + /// Creates an unopened connection and installs the batch response. + /// The override, or null for the normal response. + public BatchTestContext(Action? response = null) + { + _fixture.TdsServer.OnSQLBatchCompleted = response; + Connection = new SqlConnection(CreateBuilder(_fixture).ConnectionString); + Command = new SqlCommand("SELECT 1", Connection); + } + + public SqlConnection Connection { get; } + public SqlCommand Command { get; } + + /// Installs a response whose alternate-row identifier spans two packets. + /// The identifier to split across packets. + public void SetPacketBoundaryResponse(ushort alternateId) => + _fixture.TdsServer.OnSQLBatchCompleted = response => + SetPacketBoundaryResult(response, Connection.PacketSize, alternateId); + + /// Disposes the command, connection and server in ownership order. + public void Dispose() + { + try + { + Command.Dispose(); + } + finally + { + try + { + Connection.Dispose(); + } + finally + { + _fixture.Dispose(); + } + } + } + } + + /// Builds a bounded, unpooled connection to the test's ephemeral server. + /// The server fixture supplying the ephemeral port. + /// The connection settings used by the parser tests. + private static SqlConnectionStringBuilder CreateBuilder(TdsServerFixture fixture) => new() + { + DataSource = $"localhost,{fixture.TdsServer.EndPoint.Port}", + Encrypt = SqlConnectionEncryptOption.Optional, + Pooling = false, + ConnectTimeout = 5, + ConnectRetryCount = 0 + }; + + /// Writes a little-endian identifier without flushing the TDS message. + /// The stream receiving the identifier. + /// The identifier to serialize. + private static void WriteUInt16(Stream destination, ushort value) + { + destination.WriteByte((byte)value); + destination.WriteByte((byte)(value >> 8)); + } + + /// Creates a token without sending the state that would normally precede it. + /// The token whose prerequisite state is missing. + /// The malformed response token. + private static TDSPacketToken CreateToken(TDSTokenType tokenType) => tokenType switch + { + TDSTokenType.Row => new TDSRowToken(new TDSColMetadataToken()), + TDSTokenType.NBCRow => new TDSNBCRowToken(new TDSColMetadataToken()), + TDSTokenType.AlternativeRow => new AlternateRowToken(1), + TDSTokenType.SSPI => new TDSSSPIToken(Array.Empty()), + _ => throw new ArgumentOutOfRangeException(nameof(tokenType)) + }; + + /// Writes a token lacking its prerequisite state followed by a final DONE. + /// The response to replace. + /// The token to send without its required state. + private static void SetInvalidBatch(TDSMessage response, TDSTokenType tokenType) + { + response.Clear(); + response.Add(CreateToken(tokenType)); + response.Add(new TDSDoneToken(TDSDoneTokenStatusType.Final)); + } + + /// Writes ordinary and null rows followed by a matching alternate result. + /// The response to replace with the valid result stream. + private static void SetValidResult(TDSMessage response) => + SetResult(response, includeAlternateMetadata: true, alternateId: 1); + + /// Writes primary rows and an alternate row with optional metadata. + /// The response to replace. + /// Whether to declare metadata identifier one. + /// The identifier requested by the alternate row. + private static void SetResult( + TDSMessage response, bool includeAlternateMetadata, ushort alternateId) + { + response.Clear(); + TDSColMetadataToken metadata = new(); + metadata.Columns.Add(new TDSColumnData { DataType = TDSDataType.Int4, Name = "value" }); + response.Add(metadata); + if (includeAlternateMetadata) + { + response.Add(new AlternateMetadataToken()); + } + + TDSRowToken row = new(metadata); + row.Data.Add(1); + response.Add(row); + TDSNBCRowToken nullRow = new(metadata); + nullRow.Data.Add(null); + response.Add(nullRow); + response.Add(new AlternateRowToken(alternateId)); + response.Add(new TDSDoneToken(TDSDoneTokenStatusType.Final)); + } + + /// Pads a result so the alternate-row identifier spans two TDS packets. + /// The batch response to replace with the padded result. + /// The negotiated packet size, including its header. + /// The metadata identifier requested by the alternate row. + private static void SetPacketBoundaryResult( + TDSMessage response, int packetSize, ushort alternateId) + { + SetResult(response, includeAlternateMetadata: true, alternateId); + using MemoryStream prefix = new(); + for (int index = 0; index < response.Count - 2; index++) + { + response[index].Deflate(prefix); + } + + TDSInfoToken padding = new(0, 0, 0, string.Empty); + using MemoryStream emptyPadding = new(); + padding.Deflate(emptyPadding); + // Leave the ALTROW token and first identifier byte in this packet, and the next byte + // in the following packet. + int targetLength = packetSize - TdsEnums.HEADER_LEN - 2; + int textBytes = targetLength - (int)prefix.Length - (int)emptyPadding.Length; + Assert.True(textBytes >= 0); + Assert.Equal(0, textBytes % 2); + padding.Message = new string('x', textBytes / 2); + padding.Deflate(prefix); + Assert.Equal(targetLength, prefix.Length); + response.Insert(response.Count - 2, padding); + } + + /// Serializes one integer alternate column using metadata identifier one. + private sealed class AlternateMetadataToken : TDSPacketToken + { + public override bool Inflate(Stream source) => throw new NotSupportedException(); + + public override void Deflate(Stream destination) + { + destination.WriteByte(TdsEnums.SQLALTMETADATA); + WriteUInt16(destination, 1); + WriteUInt16(destination, 1); + destination.WriteByte(0); + destination.WriteByte(TdsEnums.AOPSUM); + WriteUInt16(destination, 0); + new TDSColumnData { DataType = TDSDataType.Int4, Name = "sum" }.Deflate(destination); + } + } + + /// Serializes an alternate row with the supplied metadata identifier. + private sealed class AlternateRowToken(ushort id) : TDSPacketToken + { + public override bool Inflate(Stream source) => throw new NotSupportedException(); + + public override void Deflate(Stream destination) + { + destination.WriteByte(TdsEnums.SQLALTROW); + WriteUInt16(destination, id); + TDSUtilities.WriteUInt(destination, 42); + } + } +}