-
Notifications
You must be signed in to change notification settings - Fork 329
Expand file tree
/
Copy pathConversionTests.cs
More file actions
1473 lines (1287 loc) · 69.5 KB
/
ConversionTests.cs
File metadata and controls
1473 lines (1287 loc) · 69.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted.Setup;
using Microsoft.Data.SqlClient.Tests.Common.Fixtures;
namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted
{
[Trait("Set", "AE")]
public sealed class ConversionTests : IDisposable, IClassFixture<ColumnMasterKeyCertificateFixture>
{
private const string IdentityColumnName = "IdentityColumn";
private const string FirstColumnName = "Column1";
private const string FirstParamName = "@Param1";
private const string ColumnEncryptionAlgorithmName = @"AEAD_AES_256_CBC_HMAC_SHA_256";
private const decimal SmallMoneyMaxValue = 214748.3647M;
private const decimal SmallMoneyMinValue = -214748.3648M;
private const int MaxLength = 10000;
private int NumberOfRows = DataTestUtility.EnclaveEnabled ? 10 : 100;
private ColumnEncryptionKey columnEncryptionKey;
private SqlColumnEncryptionCertificateStoreProvider certStoreProvider = new SqlColumnEncryptionCertificateStoreProvider();
private List<DbObject> _databaseObjects = new List<DbObject>();
private List<string> _tables = new();
private class ColumnMetaData
{
public ColumnMetaData(SqlDbType columnType, int columnSize, int precision, int scale, bool useMax)
{
ColumnType = columnType;
ColumnSize = columnSize;
Precision = precision;
Scale = scale;
UseMax = useMax;
}
public SqlDbType ColumnType { get; set; }
public int ColumnSize { get; set; }
public int Precision { get; set; }
public int Scale { get; set; }
public bool UseMax { get; set; }
}
public ConversionTests(ColumnMasterKeyCertificateFixture fixture)
{
X509Certificate2 certificate = fixture.ColumnMasterKeyCertificate;
ColumnMasterKey columnMasterKey1 = new CspColumnMasterKey(
DatabaseHelper.GenerateUniqueName("CMK"),
certificate.Thumbprint,
certStoreProvider,
DataTestUtility.EnclaveEnabled);
_databaseObjects.Add(columnMasterKey1);
columnEncryptionKey = new ColumnEncryptionKey(
DatabaseHelper.GenerateUniqueName("CEK"),
columnMasterKey1,
certStoreProvider);
_databaseObjects.Add(columnEncryptionKey);
foreach (string connectionStr in DataTestUtility.AEConnStringsSetup)
{
var connectionString = new SqlConnectionStringBuilder(connectionStr);
connectionString.ConnectTimeout = Math.Max(connectionString.ConnectTimeout, 30); // The AE tests often fail with a connect timeout in this constructor. Making sure we have a reasonable timeout.
using (SqlConnection sqlConnection = new SqlConnection(connectionString.ConnectionString))
{
sqlConnection.Open();
_databaseObjects.ForEach(o => o.Create(sqlConnection));
}
}
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[MemberData(
nameof(ConversionSmallerToLargerInsertAndSelectData)
#if NETFRAMEWORK
// .NET Framework puts system enums in something called the Global
// Assembly Cache (GAC), and xUnit refuses to serialize enums that
// live there. So for .NET Framework, we disable enumeration of the
// test data to avoid warnings on the console when running tests.
, DisableDiscoveryEnumeration = true
#endif
)]
public void ConversionSmallerToLargerInsertAndSelect(string connString, SqlDbType smallDbType, SqlDbType largeDbType)
{
ColumnMetaData largeColumnInfo = new ColumnMetaData(largeDbType, 0, 1, 1, false);
ColumnMetaData smallColumnInfo = new ColumnMetaData(smallDbType, 0, 1, 1, false);
// Adjust the size, precision and scale for data types that have one.
AdjustSizePrecisionAndScale(ref largeColumnInfo, ref smallColumnInfo);
// Create the encrypted and unencrypted table with the proper column types.
string encryptedTableName = DatabaseHelper.GenerateUniqueName("encrypted");
string unencryptedTableName = DatabaseHelper.GenerateUniqueName("unencrypted");
// Create the encrypted and unencrypted table with the proper column types.
CreateTable(connString, largeColumnInfo, encryptedTableName, isEncrypted: true);
CreateTable(connString, largeColumnInfo, unencryptedTableName, isEncrypted: false);
// Insert data using the smaller type to the tables with the large type.
object[] rawValues = PopulateTablesAndReturnRandomValue(connString, encryptedTableName, unencryptedTableName, smallColumnInfo);
// Keep the values from unencryptedTable other than the rawValues to perform a select later for DateTime2 and DateTimeOffset.
object[] valuesToSelect = RetriveDataFromDatabase(connString, unencryptedTableName);
// Now read back everything and make sure the values and types are identical.
CompareTables(connString, encryptedTableName, unencryptedTableName);
// Now send a query with a predicate using the larger type and confirm that the row that was inserted with the smaller type can still be found.
using (SqlConnection sqlConnectionEncrypted = new SqlConnection(connString))
using (SqlConnection sqlConnectionUnencrypted = new SqlConnection(connString))
{
sqlConnectionEncrypted.Open();
sqlConnectionUnencrypted.Open();
// Select each value we just inserted with a predicate and verify that encrypted and unencrypted return the same result.
for (int i = 0; i < NumberOfRows; i++)
{
object value;
// Use the retrieved values for DateTime2 and DateTimeOffset due to fractional insertion adjustment
if (smallColumnInfo.ColumnType is SqlDbType.DateTime2 || smallColumnInfo.ColumnType is SqlDbType.DateTimeOffset)
{
value = valuesToSelect[i];
}
else
{
value = rawValues[i];
}
using (SqlCommand cmdEncrypted = new SqlCommand(string.Format(@"SELECT {0} FROM [{1}] WHERE {0} = {2}", FirstColumnName, encryptedTableName, FirstParamName), sqlConnectionEncrypted, null, SqlCommandColumnEncryptionSetting.Enabled))
using (SqlCommand cmdUnencrypted = new SqlCommand(string.Format(@"SELECT {0} FROM [{1}] WHERE {0} = {2}", FirstColumnName, unencryptedTableName, FirstParamName), sqlConnectionUnencrypted, null, SqlCommandColumnEncryptionSetting.Disabled))
{
SqlParameter paramEncrypted = new SqlParameter();
paramEncrypted.ParameterName = FirstParamName;
paramEncrypted.SqlDbType = largeDbType;
SetParamSizeScalePrecision(ref paramEncrypted, largeColumnInfo);
paramEncrypted.Value = value;
cmdEncrypted.Parameters.Add(paramEncrypted);
SqlParameter paramUnencrypted = new SqlParameter();
paramUnencrypted.ParameterName = FirstParamName;
paramUnencrypted.SqlDbType = largeDbType;
SetParamSizeScalePrecision(ref paramUnencrypted, largeColumnInfo);
paramUnencrypted.Value = value;
cmdUnencrypted.Parameters.Add(paramUnencrypted);
using (SqlDataReader readerUnencrypted = cmdUnencrypted.ExecuteReader())
using (SqlDataReader readerEncrypted = cmdEncrypted.ExecuteReader())
{
// First check that we found some rows.
Assert.True(readerEncrypted.HasRows, @"We didn't find any rows.");
// Now compare the result.
CompareResults(readerEncrypted, readerUnencrypted);
}
}
}
}
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[MemberData(
nameof(ConversionSmallerToLargerInsertAndSelectBulkData)
#if NETFRAMEWORK
, DisableDiscoveryEnumeration = true
#endif
)]
public void ConversionSmallerToLargerInsertAndSelectBulk(string connString, SqlDbType smallDbType, SqlDbType largeDbType)
{
ColumnMetaData largeColumnInfo = new ColumnMetaData(largeDbType, 0, 1, 1, false);
ColumnMetaData smallColumnInfo = new ColumnMetaData(smallDbType, 0, 1, 1, false);
// Adjust the size, precision and scale for data types that have one.
AdjustSizePrecisionAndScale(ref largeColumnInfo, ref smallColumnInfo);
string originTableName = DatabaseHelper.GenerateUniqueName("small_type_pt");
string targetTableName = DatabaseHelper.GenerateUniqueName("large_type_enc");
string witnessTableName = DatabaseHelper.GenerateUniqueName("large_type_pt");
// Create the encrypted and unencrypted table with the proper column types.
CreateTable(connString, smallColumnInfo, originTableName, isEncrypted: false);
CreateTable(connString, largeColumnInfo, targetTableName, isEncrypted: true);
CreateTable(connString, largeColumnInfo, witnessTableName, isEncrypted: false);
// Insert data using the smaller type to the tables with the large type.
// Also keep the values on the side to perform a select later.
object[] rawValues = PopulateTablesAndReturnRandomValuePlaintextOnly(connString, originTableName, smallColumnInfo);
// Keep the values from originTable other than the rawValues to perform a select later for DateTime2 and DateTimeOffset.
object[] valuesToSelect = RetriveDataFromDatabase(connString, originTableName);
// populate the witness table & the target table using bulk insert
portDataToTablePairViaBulkCopy(connString, originTableName, SqlConnectionColumnEncryptionSetting.Disabled, targetTableName, SqlConnectionColumnEncryptionSetting.Enabled);
portDataToTablePairViaBulkCopy(connString, originTableName, SqlConnectionColumnEncryptionSetting.Disabled, witnessTableName, SqlConnectionColumnEncryptionSetting.Disabled);
// Now read back everything and make sure the values and types are identical.
CompareTables(connString, targetTableName, witnessTableName);
// Now send a query with a predicate using the larger type and confirm that the row that was inserted with the smaller type can still be found.
using (SqlConnection sqlConnectionEncrypted = new SqlConnection(connString))
using (SqlConnection sqlConnectionUnencrypted = new SqlConnection(connString))
{
sqlConnectionEncrypted.Open();
sqlConnectionUnencrypted.Open();
// Select each value we just inserted with a predicate and verify that encrypted and unencrypted return the same result.
for (int i = 0; i < NumberOfRows; i++)
{
object value;
// Use the retrieved values for DateTime2 and DateTimeOffset due to fractional insertion adjustment
if (smallColumnInfo.ColumnType is SqlDbType.DateTime2 ||
smallColumnInfo.ColumnType is SqlDbType.DateTimeOffset ||
smallColumnInfo.ColumnType is SqlDbType.Char ||
smallColumnInfo.ColumnType is SqlDbType.NChar)
{
value = valuesToSelect[i];
}
else
{
value = rawValues[i];
}
using (SqlCommand cmdEncrypted = new SqlCommand(string.Format(@"SELECT {0} FROM [{1}] WHERE {0} = {2}", FirstColumnName, targetTableName, FirstParamName), sqlConnectionEncrypted, null, SqlCommandColumnEncryptionSetting.Enabled))
using (SqlCommand cmdUnencrypted = new SqlCommand(string.Format(@"SELECT {0} FROM [{1}] WHERE {0} = {2}", FirstColumnName, witnessTableName, FirstParamName), sqlConnectionUnencrypted, null, SqlCommandColumnEncryptionSetting.Disabled))
{
SqlParameter paramEncrypted = new SqlParameter();
paramEncrypted.ParameterName = FirstParamName;
paramEncrypted.SqlDbType = largeDbType;
SetParamSizeScalePrecision(ref paramEncrypted, largeColumnInfo);
paramEncrypted.Value = value;
cmdEncrypted.Parameters.Add(paramEncrypted);
SqlParameter paramUnencrypted = new SqlParameter();
paramUnencrypted.ParameterName = FirstParamName;
paramUnencrypted.SqlDbType = largeDbType;
SetParamSizeScalePrecision(ref paramUnencrypted, largeColumnInfo);
paramUnencrypted.Value = value;
cmdUnencrypted.Parameters.Add(paramUnencrypted);
using (SqlDataReader readerUnencrypted = cmdUnencrypted.ExecuteReader())
using (SqlDataReader readerEncrypted = cmdEncrypted.ExecuteReader())
{
// First check that we found some rows.
Assert.True(readerEncrypted.HasRows, @"We didn't find any rows.");
// Now compare the result.
CompareResults(readerEncrypted, readerUnencrypted);
}
}
}
}
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[MemberData(
nameof(TestOutOfRangeValuesData)
#if NETFRAMEWORK
, DisableDiscoveryEnumeration = true
#endif
)]
public void TestOutOfRangeValues(string connString, SqlDbType currentDbType)
{
ColumnMetaData currentColumnInfo = new ColumnMetaData(currentDbType, 0, 1, 1, false);
ColumnMetaData dummyColumnInfo = null;
// Adjust size, precision and scale if the type has one.
AdjustSizePrecisionAndScale(ref currentColumnInfo, ref dummyColumnInfo);
// Create the encrypted and unencrypted table with the proper column types.
string encryptedTableName = DatabaseHelper.GenerateUniqueName("encrypted");
string unencryptedTableName = DatabaseHelper.GenerateUniqueName("unencrypted");
// Create the encrypted and unencrypted table with the proper column types.
CreateTable(connString, currentColumnInfo, encryptedTableName, isEncrypted: true);
CreateTable(connString, currentColumnInfo, unencryptedTableName, isEncrypted: false);
// Generate a list of out of range values, indicating which should fail and which shouldn't.
List<ValueErrorTuple> valueList = GenerateOutOfRangeValuesForType(currentDbType, currentColumnInfo.ColumnSize, currentColumnInfo.Precision, currentColumnInfo.Scale);
Assert.True(valueList.Count != 0, "Test bug, the list is empty!");
using (SqlConnection sqlConnectionEncrypted = new SqlConnection(connString))
using (SqlConnection sqlConnectionUnencrypted = new SqlConnection(connString))
{
sqlConnectionEncrypted.Open();
sqlConnectionUnencrypted.Open();
foreach (ValueErrorTuple tuple in valueList)
{
using (SqlCommand sqlCmd = new SqlCommand(String.Format("INSERT INTO [{0}] VALUES ({1})", encryptedTableName, FirstParamName), sqlConnectionEncrypted, null, SqlCommandColumnEncryptionSetting.Enabled))
{
SqlParameter param = new SqlParameter();
param.ParameterName = FirstParamName;
param.SqlDbType = currentColumnInfo.ColumnType;
SetParamSizeScalePrecision(ref param, currentColumnInfo);
param.Value = tuple.Value;
sqlCmd.Parameters.Add(param);
ExecuteAndCheckForError(sqlCmd, tuple.ExpectsError);
}
// Add same value to the unencrypted table
using (SqlCommand sqlCmd = new SqlCommand(String.Format("INSERT INTO [{0}] VALUES ({1})", unencryptedTableName, FirstParamName), sqlConnectionUnencrypted, null, SqlCommandColumnEncryptionSetting.Disabled))
{
SqlParameter param = new SqlParameter();
param.ParameterName = FirstParamName;
param.SqlDbType = currentColumnInfo.ColumnType;
SetParamSizeScalePrecision(ref param, currentColumnInfo);
param.Value = tuple.Value;
sqlCmd.Parameters.Add(param);
ExecuteAndCheckForError(sqlCmd, tuple.ExpectsError);
}
CompareTables(connString, encryptedTableName, unencryptedTableName);
}
}
}
/// <summary>
/// Internal class to store a tupple of the value to insert and whether an exception is expected.
/// </summary>
private class ValueErrorTuple
{
public ValueErrorTuple(object value, bool expectsError)
{
Value = value;
ExpectsError = expectsError;
}
public object Value { get; set; }
public bool ExpectsError { get; set; }
}
/// <summary>
/// Generate out of bound values for each data type.
/// </summary>
/// <param name="type"></param>
/// <param name="length"></param>
/// <param name="precision"></param>
/// <param name="scale"></param>
/// <returns></returns>
List<ValueErrorTuple> GenerateOutOfRangeValuesForType(SqlDbType type, int length, int precision, int scale)
{
List<ValueErrorTuple> list = new List<ValueErrorTuple>();
switch (type)
{
case SqlDbType.Bit:
// Sql actually allows to insert out of bound values for bit and it converts them to a bit value.
list.Add(new ValueErrorTuple(2, false));
list.Add(new ValueErrorTuple(-1, false));
break;
case SqlDbType.BigInt:
list.Add(new ValueErrorTuple("9223372036854775808", true));
list.Add(new ValueErrorTuple("-9223372036854775809", true));
break;
case SqlDbType.Binary:
case SqlDbType.VarBinary:
{
byte[] upperValueArray = new byte[length + 1];
Random random = new Random();
random.NextBytes(upperValueArray);
list.Add(new ValueErrorTuple(upperValueArray, false));
break;
}
case SqlDbType.Char:
case SqlDbType.NChar:
case SqlDbType.VarChar:
case SqlDbType.NVarChar:
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length + 1; i++)
{
sb.Append('a');
}
list.Add(new ValueErrorTuple(sb.ToString(), false));
break;
}
case SqlDbType.DateTime:
// This value is out of range and should fail.
list.Add(new ValueErrorTuple(new DateTime(1752, 12, 31, 23, 59, 59, 997), true));
// This value has greater scale and it should get truncated, but not fail.
list.Add(new ValueErrorTuple(new DateTime(2014, 1, 1, 23, 59, 59, 998), false));
break;
case SqlDbType.Int:
list.Add(new ValueErrorTuple((Int64)Int32.MaxValue + 1, true));
list.Add(new ValueErrorTuple((Int64)Int32.MinValue - 1, true));
break;
case SqlDbType.Money:
list.Add(new ValueErrorTuple(SqlMoney.MaxValue.Value + (decimal)0.0001, true));
list.Add(new ValueErrorTuple(SqlMoney.MinValue.Value - (decimal)0.0001, true));
// This value has greater scale and it should get truncated, but not fail.
list.Add(new ValueErrorTuple(1.00001, false));
break;
case SqlDbType.UniqueIdentifier:
list.Add(new ValueErrorTuple(new Guid().ToString() + "1", true));
list.Add(new ValueErrorTuple(new Guid().ToString().Substring(0, new Guid().ToString().Length - 1), true));
break;
case SqlDbType.SmallDateTime:
list.Add(new ValueErrorTuple(new DateTime(2079, 6, 7, 0, 0, 0), true));
// This value is out of range and should fail.
list.Add(new ValueErrorTuple(new DateTime(1899, 12, 31, 23, 59, 29), true));
// This is rounded and inserted properly for both encrypted and unencrypted.
list.Add(new ValueErrorTuple(new DateTime(1899, 12, 31, 23, 59, 59), false));
// This value has greater scale and it should get truncated, but not fail.
list.Add(new ValueErrorTuple(new DateTime(2014, 1, 1, 23, 59, 59, 1), false));
break;
case SqlDbType.SmallInt:
list.Add(new ValueErrorTuple((Int32)Int16.MaxValue + 1, true));
list.Add(new ValueErrorTuple((Int32)Int16.MinValue - 1, true));
break;
case SqlDbType.SmallMoney:
list.Add(new ValueErrorTuple((decimal)214748.3648, true));
list.Add(new ValueErrorTuple((decimal)-214748.3649, true));
// This value has greater scale and it should get truncated, but not fail.
list.Add(new ValueErrorTuple((decimal)1.00001, false));
break;
case SqlDbType.TinyInt:
list.Add(new ValueErrorTuple((Int16)byte.MaxValue + 1, true));
list.Add(new ValueErrorTuple(-1, true));
break;
case SqlDbType.Date:
// These values are out of range and should fail.
list.Add(new ValueErrorTuple("10000/1/1", true));
list.Add(new ValueErrorTuple("0/12/31", true));
break;
case SqlDbType.Time:
case SqlDbType.DateTime2:
case SqlDbType.DateTimeOffset:
// All values with higher precision will get truncated but not fail.
String timeStringUpper = "23:59:59.";
String timeStringLower = "00:00:00.";
for (int i = 0; i < scale; i++)
{
timeStringUpper = timeStringUpper + "9";
timeStringLower = timeStringLower + "0";
}
timeStringUpper = timeStringUpper + "1";
timeStringLower = timeStringLower + "1";
if (type == SqlDbType.Time)
{
TimeSpan temp = new TimeSpan();
TimeSpan.TryParse(timeStringUpper, out temp);
list.Add(new ValueErrorTuple(temp, false));
TimeSpan.TryParse(timeStringLower, out temp);
list.Add(new ValueErrorTuple(temp, false));
}
else if (type == SqlDbType.DateTime2)
{
// These values are out of range and should fail.
list.Add(new ValueErrorTuple("10000/1/1 00:00:00", true));
list.Add(new ValueErrorTuple("0/12/31 23::59:59:999", true));
timeStringUpper = "2014/1/1 " + timeStringUpper;
timeStringLower = "2014/1/1 " + timeStringLower;
DateTime temp = new DateTime();
DateTime.TryParse(timeStringUpper, out temp);
list.Add(new ValueErrorTuple(temp, false));
DateTime.TryParse(timeStringLower, out temp);
list.Add(new ValueErrorTuple(temp, false));
}
else if (type == SqlDbType.DateTimeOffset)
{
// These values are out of range and should fail.
list.Add(new ValueErrorTuple("10000/1/1 00:00:00 -14:00", true));
list.Add(new ValueErrorTuple("0/12/31 23::59:59:999 +14:00", true));
timeStringUpper = "2014/1/1 " + timeStringUpper;
timeStringLower = "2014/1/1 " + timeStringLower;
DateTime temp = new DateTime();
DateTime.TryParse(timeStringUpper, out temp);
list.Add(new ValueErrorTuple(temp, false));
DateTime.TryParse(timeStringLower, out temp);
list.Add(new ValueErrorTuple(temp, false));
// These values are out of range and should fail.
list.Add(new ValueErrorTuple("2014/1/1 10:00 +14:01", true));
list.Add(new ValueErrorTuple("2014/1/1 10:00 -14:01", true));
}
break;
case SqlDbType.Decimal:
decimal highPart = 0;
decimal lowPart = 1;
for (int i = 0; i < precision - scale; i++)
{
if (i == 0)
{
highPart = 1;
}
else
{
highPart *= 10;
}
}
for (int i = 0; i < scale; i++)
{
lowPart /= 10;
}
// Construct a value with higher precision than allowed.
list.Add(new ValueErrorTuple(highPart == 0 ? 1 : highPart * 10 + lowPart, true));
// This value has greater scale and it should get truncated, but not fail.
// If scale is 0 then this actually fails because of how .NET internally calculates the state.
list.Add(new ValueErrorTuple(highPart + lowPart / 10, scale == 0 ? true : false));
break;
case SqlDbType.Float:
list.Add(new ValueErrorTuple("1.79770e+308", true));
list.Add(new ValueErrorTuple("-1.79770e+308", true));
list.Add(new ValueErrorTuple(Double.PositiveInfinity, true));
list.Add(new ValueErrorTuple(Double.NegativeInfinity, true));
list.Add(new ValueErrorTuple(Double.NaN, true));
list.Add(new ValueErrorTuple(Double.Epsilon, false));
break;
case SqlDbType.Real:
list.Add(new ValueErrorTuple((double)3.40283e+038, true));
list.Add(new ValueErrorTuple((double)-3.40283e+038, true));
list.Add(new ValueErrorTuple(Single.PositiveInfinity, true));
list.Add(new ValueErrorTuple(Single.NegativeInfinity, true));
list.Add(new ValueErrorTuple(Single.NaN, true));
list.Add(new ValueErrorTuple(Single.Epsilon, false));
break;
default:
Assert.Fail("We should never get here");
break;
}
return list;
}
/// <summary>
/// Check if this exception is expected.
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
private bool IsExpectedException(Exception e)
{
return e is OverflowException ||
e is InvalidCastException ||
e is SqlTypeException ||
e is ArgumentException ||
e is FormatException ||
e is SqlException;
}
/// <summary>
/// Try to execute the command and check if there was an error if one was expected.
/// </summary>
/// <param name="sqlCmd"></param>
/// <param name="expectError"></param>
private void ExecuteAndCheckForError(SqlCommand sqlCmd, bool expectError)
{
if (!expectError)
{
sqlCmd.ExecuteNonQuery();
}
else
{
try
{
sqlCmd.ExecuteNonQuery();
StringBuilder builder = new(
"We should have gotten an error but passed instead; " +
$"command: {sqlCmd.CommandText}; parameters: ");
foreach (SqlParameter param in sqlCmd.Parameters)
{
builder.Append('(');
builder.Append(param.ParameterName);
builder.Append(' ');
builder.Append(param.SqlDbType);
builder.Append(' ');
builder.Append(param.Value);
builder.Append(") ");
}
Assert.Fail(builder.ToString());
}
catch (Exception e)
{
Type exceptionType = e.GetType();
if (!IsExpectedException(e))
{
throw;
}
}
}
}
/// <summary>
/// Adjust the size, scale and precision for the data types that have one.
/// </summary>
/// <param name="largeColumnMeta"></param>
/// <param name="smallColumnMeta"></param>
private void AdjustSizePrecisionAndScale(ref ColumnMetaData largeColumnMeta, ref ColumnMetaData smallColumnMeta)
{
Random random = new Random();
if (TypeHasSize(largeColumnMeta.ColumnType))
{
// 20% of the time use (max) as the length.
largeColumnMeta.UseMax = (largeColumnMeta.ColumnType is SqlDbType.VarChar ||
largeColumnMeta.ColumnType is SqlDbType.NVarChar ||
largeColumnMeta.ColumnType is SqlDbType.VarBinary) &&
random.Next(0, 100) < 20;
int unicodeMaxLength = 3500;
int maxLength = 7500;
if (largeColumnMeta.UseMax)
{
largeColumnMeta.ColumnSize = -1;
if (smallColumnMeta != null)
{
if (largeColumnMeta.ColumnType is SqlDbType.NChar || largeColumnMeta.ColumnType is SqlDbType.NVarChar)
{
smallColumnMeta.ColumnSize = random.Next(1, unicodeMaxLength);
}
else
{
smallColumnMeta.ColumnSize = random.Next(1, maxLength);
}
}
}
else
{
if (largeColumnMeta.ColumnType is SqlDbType.NChar || largeColumnMeta.ColumnType is SqlDbType.NVarChar)
{
largeColumnMeta.ColumnSize = random.Next(2, unicodeMaxLength);
}
else
{
largeColumnMeta.ColumnSize = random.Next(2, maxLength);
}
if (smallColumnMeta != null)
{
smallColumnMeta.ColumnSize = random.Next(1, largeColumnMeta.ColumnSize);
}
}
}
else if (TypeHasScale(largeColumnMeta.ColumnType))
{
int precision = 0;
int scale = random.Next(1, 8);
int minScale = 1;
if (largeColumnMeta.ColumnType is SqlDbType.Decimal)
{
precision = random.Next(1, 28);
scale = random.Next(0, precision + 1);
minScale = 0;
}
largeColumnMeta.Precision = precision;
largeColumnMeta.Scale = scale;
if (smallColumnMeta != null)
{
smallColumnMeta.Precision = 0;
// For Time / DateTime2 / DateTimeOffset types, actual scale is set to 7 when parameter.scale is zero.
// Active Issue in SQLParameter.cs when user wants to specify zero as the actual scale.
smallColumnMeta.Scale = random.Next(minScale, largeColumnMeta.Scale);
}
}
else if (TypeHasPrecision(largeColumnMeta.ColumnType))
{
largeColumnMeta.Precision = random.Next(2, 54);
largeColumnMeta.Scale = 0;
if (smallColumnMeta != null)
{
smallColumnMeta.Precision = random.Next(1, largeColumnMeta.Precision);
smallColumnMeta.Scale = 0;
}
}
}
/// <summary>
/// Check if this data type has size.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private bool TypeHasSize(SqlDbType type)
{
return type is SqlDbType.Binary ||
type is SqlDbType.VarBinary ||
type is SqlDbType.Char ||
type is SqlDbType.VarChar ||
type is SqlDbType.NChar ||
type is SqlDbType.NVarChar;
}
/// <summary>
/// Check if this data type has scale.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private bool TypeHasScale(SqlDbType type)
{
return type is SqlDbType.Time ||
type is SqlDbType.DateTime2 ||
type is SqlDbType.DateTimeOffset ||
type is SqlDbType.Decimal;
}
/// <summary>
/// Check if this data type has precision.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private bool TypeHasPrecision(SqlDbType type)
{
return type is SqlDbType.Decimal;
}
/// <summary>
/// Populate the tables with data of the provided data type.
/// </summary>
/// <param name="encryptedTableName"></param>
/// <param name="unencryptedTableName"></param>
/// <param name="columnInfo"></param>
/// <returns></returns>
private object[] PopulateTablesAndReturnRandomValue(string connString, string encryptedTableName, string unencryptedTableName, ColumnMetaData columnInfo)
{
object[] valueArray = new object[NumberOfRows];
using (SqlConnection sqlConnection = new SqlConnection(connString))
{
sqlConnection.Open();
for (int i = 0; i < NumberOfRows; i++)
{
valueArray[i] = GenerateRandomValue(columnInfo);
// Add value to the encrypted table
using (SqlCommand sqlCmd = new SqlCommand(String.Format("INSERT INTO [{0}] VALUES ({1})", encryptedTableName, FirstParamName), sqlConnection, null, SqlCommandColumnEncryptionSetting.Enabled))
{
SqlParameter param = new SqlParameter();
param.ParameterName = FirstParamName;
param.SqlDbType = columnInfo.ColumnType;
SetParamSizeScalePrecision(ref param, columnInfo);
param.Value = valueArray[i];
sqlCmd.Parameters.Add(param);
sqlCmd.ExecuteNonQuery();
}
// Add same value to the unencrypted table
using (SqlCommand sqlCmd = new SqlCommand(String.Format("INSERT INTO [{0}] VALUES ({1})", unencryptedTableName, FirstParamName), sqlConnection, null, SqlCommandColumnEncryptionSetting.Enabled))
{
SqlParameter param = new SqlParameter();
param.ParameterName = FirstParamName;
param.SqlDbType = columnInfo.ColumnType;
SetParamSizeScalePrecision(ref param, columnInfo);
param.Value = valueArray[i];
sqlCmd.Parameters.Add(param);
sqlCmd.ExecuteNonQuery();
}
}
}
return valueArray;
}
/// <summary>
/// Populate the tables with data of the provided data type.
/// </summary>
/// <param name="unencryptedTableName"></param>
/// <param name="columnInfo"></param>
/// <returns></returns>
private object[] PopulateTablesAndReturnRandomValuePlaintextOnly(string connSting, string unencryptedTableName, ColumnMetaData columnInfo)
{
object[] valueArray = new object[NumberOfRows];
using (SqlConnection sqlConnection = new SqlConnection(connSting))
{
sqlConnection.Open();
for (int i = 0; i < NumberOfRows; i++)
{
valueArray[i] = GenerateRandomValue(columnInfo);
// Add same value to the unencrypted table
using (SqlCommand sqlCmd = new SqlCommand(String.Format("INSERT INTO [{0}] VALUES ({1})", unencryptedTableName, FirstParamName), sqlConnection, null, SqlCommandColumnEncryptionSetting.Disabled))
{
SqlParameter param = new SqlParameter();
param.ParameterName = FirstParamName;
param.SqlDbType = columnInfo.ColumnType;
SetParamSizeScalePrecision(ref param, columnInfo);
param.Value = valueArray[i];
sqlCmd.Parameters.Add(param);
sqlCmd.ExecuteNonQuery();
}
}
}
return valueArray;
}
/// <summary>
/// Inserts identical data into two tables (for comparison purposes)
/// </summary>
/// <param name="sourceName"></param>
/// <param name="sourceConnectionFlag"></param>
/// <param name="targetName"></param>
/// <param name="targetConnectionFlag"></param>
private void portDataToTablePairViaBulkCopy(string connString, string sourceName, SqlConnectionColumnEncryptionSetting sourceConnectionFlag, string targetName, SqlConnectionColumnEncryptionSetting targetConnectionFlag)
{
SqlConnectionStringBuilder strbld = new SqlConnectionStringBuilder(connString);
strbld.ColumnEncryptionSetting = sourceConnectionFlag;
using (SqlConnection sourceConnection = new SqlConnection(strbld.ToString()))
{
sourceConnection.Open();
SqlCommand sourceCmd = sourceConnection.CreateCommand();
sourceCmd.CommandText = String.Format(@"SELECT * FROM [{0}]", sourceName);
SqlDataReader reader = sourceCmd.ExecuteReader();
strbld.ColumnEncryptionSetting = targetConnectionFlag;
using (SqlConnection targetConnection = new SqlConnection(strbld.ToString()))
{
targetConnection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(targetConnection))
{
bulkCopy.DestinationTableName = targetName;
try
{
bulkCopy.WriteToServer(reader);
}
finally
{
reader.Close();
}
}
}
}
}
/// <summary>
/// Retrive data from unecrypted table for comparison
/// </summary>
/// <param name="unencryptedTableName"></param>
/// <returns></returns>
private object[] RetriveDataFromDatabase(string connString, string unencryptedTableName)
{
object[] valueArray = new object[NumberOfRows];
int index = 0;
using (SqlConnection sqlConnection = new SqlConnection(connString))
{
sqlConnection.Open();
using (SqlCommand cmdUnencrypted = new SqlCommand(String.Format("SELECT {0} FROM [{1}] ORDER BY {2}", FirstColumnName, unencryptedTableName, IdentityColumnName), sqlConnection, null, SqlCommandColumnEncryptionSetting.Disabled))
{
using (SqlDataReader readerUnencrypted = cmdUnencrypted.ExecuteReader())
{
Assert.True(readerUnencrypted.HasRows, "We didn't find any rows in unEncryptedTable.");
while (readerUnencrypted.Read())
{
valueArray[index] = readerUnencrypted.GetValue(0);
index++;
}
Assert.True(NumberOfRows == index, String.Format("The number of rows retrieved is {0}", index));
}
}
}
return valueArray;
}
/// <summary>
/// Compare the two tables to check that they have identical rows.
/// </summary>
/// <param name="encryptedTableName"></param>
/// <param name="unencryptedTableName"></param>
private void CompareTables(string connString, string encryptedTableName, string unencryptedTableName)
{
using (SqlConnection sqlConnectionEncrypted = new SqlConnection(connString))
using (SqlConnection sqlConnectionUnencrypted = new SqlConnection(connString))
{
sqlConnectionEncrypted.Open();
sqlConnectionUnencrypted.Open();
// Check that the tables contain identical data for the small types.
using (SqlCommand cmdEncrypted = new SqlCommand(String.Format("SELECT * FROM [{0}] ORDER BY {1}", encryptedTableName, IdentityColumnName), sqlConnectionEncrypted, null, SqlCommandColumnEncryptionSetting.Enabled))
using (SqlCommand cmdUnencrypted = new SqlCommand(String.Format("SELECT * FROM [{0}] ORDER BY {1}", unencryptedTableName, IdentityColumnName), sqlConnectionUnencrypted, null, SqlCommandColumnEncryptionSetting.Disabled))
{
using (SqlDataReader readerUnencrypted = cmdUnencrypted.ExecuteReader())
using (SqlDataReader readerEncrypted = cmdEncrypted.ExecuteReader())
{
CompareResults(readerEncrypted, readerUnencrypted);
}
}
}
}
/// <summary>
/// Read data using two sqlDataReaders and compare the results.
/// </summary>
/// <param name="sqlDataReaderEncrypted"></param>
/// <param name="sqlDataReaderUnencrypted"></param>
private void CompareResults(SqlDataReader sqlDataReaderEncrypted, SqlDataReader sqlDataReaderUnencrypted)
{
int rowId = 0;
while (sqlDataReaderEncrypted.Read())
{
rowId++;
Assert.True(sqlDataReaderUnencrypted.HasRows, "Unencrypted reader has less rows than the encrypted.");
sqlDataReaderUnencrypted.Read();
for (int i = 0; i < sqlDataReaderEncrypted.FieldCount; i++)
{
Assert.True(sqlDataReaderEncrypted.GetDataTypeName(i).Equals(sqlDataReaderUnencrypted.GetDataTypeName(i)), string.Format("The types for column '{0}' are not identical.", sqlDataReaderEncrypted.GetName(i)));
Assert.True(sqlDataReaderEncrypted.GetValue(i).GetType().Equals(sqlDataReaderUnencrypted.GetValue(i).GetType()), string.Format("The types of the value read for row '{0}' column '{1}' are not identical", rowId, sqlDataReaderEncrypted.GetName(i)));
object encryptedValue = sqlDataReaderEncrypted.GetValue(i);
object unencryptedValue = sqlDataReaderUnencrypted.GetValue(i);
if (sqlDataReaderEncrypted.GetDataTypeName(i) == "binary" || sqlDataReaderEncrypted.GetDataTypeName(i) == "varbinary")
{
Assert.True(((byte[])encryptedValue).SequenceEqual((byte[])unencryptedValue), string.Format("The values read for row '{0}' column '{1}' are not identical", rowId, sqlDataReaderEncrypted.GetName(i)));
}
else if (sqlDataReaderEncrypted.GetDataTypeName(i) == "char" || sqlDataReaderEncrypted.GetDataTypeName(i) == "varchar" ||
sqlDataReaderEncrypted.GetDataTypeName(i) == "nchar" || sqlDataReaderEncrypted.GetDataTypeName(i) == "nvarchar")
{
Assert.True(((string)encryptedValue).TrimEnd().Equals(((string)unencryptedValue).TrimEnd()), string.Format("The values read for row '{0}' column '{1}' are not identical", rowId, sqlDataReaderEncrypted.GetName(i)));
}
else
{
Assert.True(encryptedValue.Equals(unencryptedValue), string.Format("The values read for row '{0}' column '{1}' are not identical", rowId, sqlDataReaderEncrypted.GetName(i)));
}
}
}
Assert.False(sqlDataReaderUnencrypted.Read(), "Unencrypted reader has more rows than the encrypted.");
}
/// <summary>
/// Generate random value for insertion according to database column
/// </summary>
/// <param name="columnInfo"></param>
/// <returns></returns>
private object GenerateRandomValue(ColumnMetaData columnInfo)
{
object returnValue;
int year;
int month;
int day;
int hour;
int minute;
int second;
int millisecond;
int count;
long ticks;
Random rand = new Random();
bool isNegative = Convert.ToBoolean(rand.Next(0, 2));
StringBuilder strBuilder = new StringBuilder();
TimeSpan tempTime;
switch (columnInfo.ColumnType)
{