Skip to content

Commit

Permalink
debugging
Browse files Browse the repository at this point in the history
  • Loading branch information
Wraith2 committed Feb 8, 2023
1 parent 1f7063a commit d920c94
Show file tree
Hide file tree
Showing 68 changed files with 17,380 additions and 17,359 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -440,17 +440,24 @@ internal bool TryReadChars(char[] chars, int charsOffset, int charsCount, out in
{
charsCopied = 0;
int count = 0;
StringBuilder build = new StringBuilder();
build.AppendLine($"TryReadChars({chars.Length}, {charsOffset}, {charsCount}, out int charsCopied)");
while (charsCopied < charsCount)
{
// check if the current buffer contains some bytes we need to copy and copy them
// in a block
int bytesAvailable = _inBytesRead - _inBytesUsed;
int bytesToRead = Math.Min(
(charsCount - charsCopied) * 2,
unchecked((_inBytesRead - _inBytesUsed) & (int)0xFFFFFFFE) // if the result is odd take off the 0 to make it even
unchecked(bytesAvailable & (int)0xFFFFFFFE) // if the result is odd take off the 0 to make it even
);


if (bytesToRead > 0)
{
build.AppendLine($" ({count} bulk) bytesToRead {bytesToRead} = Math.Min(({charsCount} - {charsCopied}) * 2, unchecked({bytesAvailable} & (int)0xFFFFFFFE)");
build.AppendLine($" ({count} before)(bytesAvailable {bytesAvailable}, _inBytesPacket {_inBytesPacket}, _inBytesRead {_inBytesRead}, _inBytesUsed {_inBytesUsed} ");

Buffer.BlockCopy(
_inBuff,
_inBytesUsed,
Expand All @@ -459,15 +466,19 @@ internal bool TryReadChars(char[] chars, int charsOffset, int charsCount, out in
bytesToRead
);

if ((_inBytesPacket - bytesToRead) < 0)
{
throw new Exception($"TryReadChars() {count} _inBytesPacket {_inBytesPacket}\n" +
$" bytesToRead = Math.Min(({charsCount} - {charsCopied}) * 2, unchecked(({_inBytesRead} - {_inBytesUsed}) & (int)0xFFFFFFFE)");
}

charsCopied = bytesToRead / 2;
_inBytesUsed += bytesToRead;
_inBytesPacket -= bytesToRead;

bytesAvailable = _inBytesRead - _inBytesUsed;
build.AppendLine($" ({count} after )(bytesAvailable {bytesAvailable}, _inBytesPacket {_inBytesPacket}, _inBytesRead {_inBytesRead}, _inBytesUsed {_inBytesUsed} ");

if (_inBytesPacket < 0)
{
//throw new Exception($"TryReadChars() {count} _inBytesPacket {_inBytesPacket}\n" +
//$" bytesToRead = Math.Min(({charsCount} - {charsCopied}) * 2, unchecked(({_inBytesRead} - {_inBytesUsed}) & (int)0xFFFFFFFE)");
throw new Exception("not enough bytes available to read" + Environment.NewLine + build.ToString());
}
}

// if the number of chars requested is lower than the number copied then we need
Expand All @@ -476,6 +487,10 @@ internal bool TryReadChars(char[] chars, int charsOffset, int charsCount, out in

if (charsCopied < charsCount)
{
bytesAvailable = _inBytesRead - _inBytesUsed;
build.AppendLine($" ({count} char) read 1 char and new packet");
build.AppendLine($" ({count} before)(bytesAvailable {bytesAvailable}, _inBytesPacket {_inBytesPacket}, _inBytesRead {_inBytesRead}, _inBytesUsed {_inBytesUsed} ");

bool result = TryReadChar(out chars[charsOffset + charsCopied]);
if (result)
{
Expand All @@ -485,7 +500,13 @@ internal bool TryReadChars(char[] chars, int charsOffset, int charsCount, out in
{
return false;
}

bytesAvailable = _inBytesRead - _inBytesUsed;
build.AppendLine($" ({count} after )(bytesAvailable {bytesAvailable}, _inBytesPacket {_inBytesPacket}, _inBytesRead {_inBytesRead}, _inBytesUsed {_inBytesUsed} ");
}

build.AppendLine($" ({count} end) charsCopied {charsCopied}");

count += 1;
}
return true;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,124 +1,124 @@
// 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.Collections.Generic;
using System.Linq;
using Azure.Identity;
using Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider;
using Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted.Setup;
using Xunit;

namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted
{
public class AKVTest : IClassFixture<SQLSetupStrategyAzureKeyVault>
{
private readonly SQLSetupStrategyAzureKeyVault _fixture;
private readonly string _akvTableName;

public AKVTest(SQLSetupStrategyAzureKeyVault fixture)
{
_fixture = fixture;
_akvTableName = fixture.AKVTestTable.Name;

// Disable the cache to avoid false failures.
SqlConnection.ColumnEncryptionQueryMetadataCacheEnabled = false;
}

[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE), nameof(DataTestUtility.IsAKVSetupAvailable))]
public void TestEncryptDecryptWithAKV()
{
SqlConnectionStringBuilder builder = new(DataTestUtility.TCPConnectionStringHGSVBS)
{
ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Enabled,
AttestationProtocol = SqlConnectionAttestationProtocol.NotSpecified,
EnclaveAttestationUrl = ""
};
using SqlConnection sqlConnection = new (builder.ConnectionString);

sqlConnection.Open();
Customer customer = new(45, "Microsoft", "Corporation");

// Start a transaction and either commit or rollback based on the test variation.
using (SqlTransaction sqlTransaction = sqlConnection.BeginTransaction())
{
DatabaseHelper.InsertCustomerData(sqlConnection, sqlTransaction, _akvTableName, customer);
sqlTransaction.Commit();
}

// Test INPUT parameter on an encrypted parameter
using SqlCommand sqlCommand = new ($"SELECT CustomerId, FirstName, LastName FROM [{_akvTableName}] WHERE FirstName = @firstName",
sqlConnection);
SqlParameter customerFirstParam = sqlCommand.Parameters.AddWithValue(@"firstName", @"Microsoft");
customerFirstParam.Direction = System.Data.ParameterDirection.Input;
customerFirstParam.ForceColumnEncryption = true;

using SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
DatabaseHelper.ValidateResultSet(sqlDataReader);
}

[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsAKVSetupAvailable))]
[PlatformSpecific(TestPlatforms.Windows)]
public void TestRoundTripWithAKVAndCertStoreProvider()
{
using SQLSetupStrategyCertStoreProvider certStoreFixture = new ();
byte[] plainTextColumnEncryptionKey = ColumnEncryptionKey.GenerateRandomBytes(ColumnEncryptionKey.KeySizeInBytes);
byte[] encryptedColumnEncryptionKeyUsingAKV = _fixture.AkvStoreProvider.EncryptColumnEncryptionKey(DataTestUtility.AKVUrl, @"RSA_OAEP", plainTextColumnEncryptionKey);
byte[] columnEncryptionKeyReturnedAKV2Cert = certStoreFixture.CertStoreProvider.DecryptColumnEncryptionKey(certStoreFixture.CspColumnMasterKey.KeyPath, @"RSA_OAEP", encryptedColumnEncryptionKeyUsingAKV);
Assert.True(plainTextColumnEncryptionKey.SequenceEqual(columnEncryptionKeyReturnedAKV2Cert), @"Roundtrip failed");

// Try the opposite.
byte[] encryptedColumnEncryptionKeyUsingCert = certStoreFixture.CertStoreProvider.EncryptColumnEncryptionKey(certStoreFixture.CspColumnMasterKey.KeyPath, @"RSA_OAEP", plainTextColumnEncryptionKey);
byte[] columnEncryptionKeyReturnedCert2AKV = _fixture.AkvStoreProvider.DecryptColumnEncryptionKey(DataTestUtility.AKVUrl, @"RSA_OAEP", encryptedColumnEncryptionKeyUsingCert);
Assert.True(plainTextColumnEncryptionKey.SequenceEqual(columnEncryptionKeyReturnedCert2AKV), @"Roundtrip failed");
}

[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE), nameof(DataTestUtility.IsAKVSetupAvailable))]
public void TestLocalCekCacheIsScopedToProvider()
{
SqlConnectionStringBuilder builder = new(DataTestUtility.TCPConnectionStringHGSVBS)
{
ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Enabled,
AttestationProtocol = SqlConnectionAttestationProtocol.NotSpecified,
EnclaveAttestationUrl = ""
};

using SqlConnection sqlConnection = new(builder.ConnectionString);

sqlConnection.Open();

// Test INPUT parameter on an encrypted parameter
using SqlCommand sqlCommand = new($"SELECT CustomerId, FirstName, LastName FROM [{_akvTableName}] WHERE FirstName = @firstName",
sqlConnection);
SqlParameter customerFirstParam = sqlCommand.Parameters.AddWithValue(@"firstName", @"Microsoft");
customerFirstParam.Direction = System.Data.ParameterDirection.Input;
customerFirstParam.ForceColumnEncryption = true;

SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
sqlDataReader.Close();

SqlColumnEncryptionAzureKeyVaultProvider sqlColumnEncryptionAzureKeyVaultProvider =
new(new SqlClientCustomTokenCredential());

Dictionary<string, SqlColumnEncryptionKeyStoreProvider> customProvider = new()
{
{ SqlColumnEncryptionAzureKeyVaultProvider.ProviderName, sqlColumnEncryptionAzureKeyVaultProvider }
};

// execute a query using provider from command-level cache. this will cache the cek in the local cek cache
sqlCommand.RegisterColumnEncryptionKeyStoreProvidersOnCommand(customProvider);
SqlDataReader sqlDataReader2 = sqlCommand.ExecuteReader();
sqlDataReader2.Close();

// global cek cache and local cek cache are populated above
// when using a new per-command provider, it will only use its local cek cache
// the following query should fail due to an empty cek cache and invalid credentials
customProvider[SqlColumnEncryptionAzureKeyVaultProvider.ProviderName] =
new SqlColumnEncryptionAzureKeyVaultProvider(new ClientSecretCredential("tenant", "client", "secret"));
sqlCommand.RegisterColumnEncryptionKeyStoreProvidersOnCommand(customProvider);
Exception ex = Assert.Throws<SqlException>(() => sqlCommand.ExecuteReader());
Assert.StartsWith("The current credential is not configured to acquire tokens for tenant", ex.InnerException.Message);
}
}
}
//// 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.Collections.Generic;
//using System.Linq;
//using Azure.Identity;
//using Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider;
//using Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted.Setup;
//using Xunit;

//namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted
//{
// public class AKVTest : IClassFixture<SQLSetupStrategyAzureKeyVault>
// {
// private readonly SQLSetupStrategyAzureKeyVault _fixture;
// private readonly string _akvTableName;

// public AKVTest(SQLSetupStrategyAzureKeyVault fixture)
// {
// _fixture = fixture;
// _akvTableName = fixture.AKVTestTable.Name;

// // Disable the cache to avoid false failures.
// SqlConnection.ColumnEncryptionQueryMetadataCacheEnabled = false;
// }

// [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE), nameof(DataTestUtility.IsAKVSetupAvailable))]
// public void TestEncryptDecryptWithAKV()
// {
// SqlConnectionStringBuilder builder = new(DataTestUtility.TCPConnectionStringHGSVBS)
// {
// ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Enabled,
// AttestationProtocol = SqlConnectionAttestationProtocol.NotSpecified,
// EnclaveAttestationUrl = ""
// };
// using SqlConnection sqlConnection = new (builder.ConnectionString);

// sqlConnection.Open();
// Customer customer = new(45, "Microsoft", "Corporation");

// // Start a transaction and either commit or rollback based on the test variation.
// using (SqlTransaction sqlTransaction = sqlConnection.BeginTransaction())
// {
// DatabaseHelper.InsertCustomerData(sqlConnection, sqlTransaction, _akvTableName, customer);
// sqlTransaction.Commit();
// }

// // Test INPUT parameter on an encrypted parameter
// using SqlCommand sqlCommand = new ($"SELECT CustomerId, FirstName, LastName FROM [{_akvTableName}] WHERE FirstName = @firstName",
// sqlConnection);
// SqlParameter customerFirstParam = sqlCommand.Parameters.AddWithValue(@"firstName", @"Microsoft");
// customerFirstParam.Direction = System.Data.ParameterDirection.Input;
// customerFirstParam.ForceColumnEncryption = true;

// using SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
// DatabaseHelper.ValidateResultSet(sqlDataReader);
// }

// [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsAKVSetupAvailable))]
// [PlatformSpecific(TestPlatforms.Windows)]
// public void TestRoundTripWithAKVAndCertStoreProvider()
// {
// using SQLSetupStrategyCertStoreProvider certStoreFixture = new ();
// byte[] plainTextColumnEncryptionKey = ColumnEncryptionKey.GenerateRandomBytes(ColumnEncryptionKey.KeySizeInBytes);
// byte[] encryptedColumnEncryptionKeyUsingAKV = _fixture.AkvStoreProvider.EncryptColumnEncryptionKey(DataTestUtility.AKVUrl, @"RSA_OAEP", plainTextColumnEncryptionKey);
// byte[] columnEncryptionKeyReturnedAKV2Cert = certStoreFixture.CertStoreProvider.DecryptColumnEncryptionKey(certStoreFixture.CspColumnMasterKey.KeyPath, @"RSA_OAEP", encryptedColumnEncryptionKeyUsingAKV);
// Assert.True(plainTextColumnEncryptionKey.SequenceEqual(columnEncryptionKeyReturnedAKV2Cert), @"Roundtrip failed");

// // Try the opposite.
// byte[] encryptedColumnEncryptionKeyUsingCert = certStoreFixture.CertStoreProvider.EncryptColumnEncryptionKey(certStoreFixture.CspColumnMasterKey.KeyPath, @"RSA_OAEP", plainTextColumnEncryptionKey);
// byte[] columnEncryptionKeyReturnedCert2AKV = _fixture.AkvStoreProvider.DecryptColumnEncryptionKey(DataTestUtility.AKVUrl, @"RSA_OAEP", encryptedColumnEncryptionKeyUsingCert);
// Assert.True(plainTextColumnEncryptionKey.SequenceEqual(columnEncryptionKeyReturnedCert2AKV), @"Roundtrip failed");
// }

// [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE), nameof(DataTestUtility.IsAKVSetupAvailable))]
// public void TestLocalCekCacheIsScopedToProvider()
// {
// SqlConnectionStringBuilder builder = new(DataTestUtility.TCPConnectionStringHGSVBS)
// {
// ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Enabled,
// AttestationProtocol = SqlConnectionAttestationProtocol.NotSpecified,
// EnclaveAttestationUrl = ""
// };

// using SqlConnection sqlConnection = new(builder.ConnectionString);

// sqlConnection.Open();

// // Test INPUT parameter on an encrypted parameter
// using SqlCommand sqlCommand = new($"SELECT CustomerId, FirstName, LastName FROM [{_akvTableName}] WHERE FirstName = @firstName",
// sqlConnection);
// SqlParameter customerFirstParam = sqlCommand.Parameters.AddWithValue(@"firstName", @"Microsoft");
// customerFirstParam.Direction = System.Data.ParameterDirection.Input;
// customerFirstParam.ForceColumnEncryption = true;

// SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
// sqlDataReader.Close();

// SqlColumnEncryptionAzureKeyVaultProvider sqlColumnEncryptionAzureKeyVaultProvider =
// new(new SqlClientCustomTokenCredential());

// Dictionary<string, SqlColumnEncryptionKeyStoreProvider> customProvider = new()
// {
// { SqlColumnEncryptionAzureKeyVaultProvider.ProviderName, sqlColumnEncryptionAzureKeyVaultProvider }
// };

// // execute a query using provider from command-level cache. this will cache the cek in the local cek cache
// sqlCommand.RegisterColumnEncryptionKeyStoreProvidersOnCommand(customProvider);
// SqlDataReader sqlDataReader2 = sqlCommand.ExecuteReader();
// sqlDataReader2.Close();

// // global cek cache and local cek cache are populated above
// // when using a new per-command provider, it will only use its local cek cache
// // the following query should fail due to an empty cek cache and invalid credentials
// customProvider[SqlColumnEncryptionAzureKeyVaultProvider.ProviderName] =
// new SqlColumnEncryptionAzureKeyVaultProvider(new ClientSecretCredential("tenant", "client", "secret"));
// sqlCommand.RegisterColumnEncryptionKeyStoreProvidersOnCommand(customProvider);
// Exception ex = Assert.Throws<SqlException>(() => sqlCommand.ExecuteReader());
// Assert.StartsWith("The current credential is not configured to acquire tokens for tenant", ex.InnerException.Message);
// }
// }
//}
Loading

0 comments on commit d920c94

Please sign in to comment.