|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.Data; |
| 7 | +using System.Diagnostics.CodeAnalysis; |
| 8 | +using System.Runtime.CompilerServices; |
| 9 | +using Microsoft.Data.SqlClient.Tests.Common.Fixtures.DatabaseObjects; |
| 10 | +using Xunit; |
| 11 | + |
| 12 | +namespace Microsoft.Data.SqlClient.ManualTesting.Tests.SqlBulkCopyTests; |
| 13 | + |
| 14 | +#nullable enable |
| 15 | + |
| 16 | +/// <summary> |
| 17 | +/// Some unprivileged users may not have permissions to query sys.all_columns, which is used to |
| 18 | +/// handle column aliases. These tests verify that bulk copy operations can handle such situations |
| 19 | +/// gracefully, falling back and ignoring column aliases. |
| 20 | +/// </summary> |
| 21 | +public sealed class UnprivilegedLogin : IDisposable |
| 22 | +{ |
| 23 | + private readonly SqlConnection? _managementConnection; |
| 24 | + private readonly ServerLogin? _unprivilegedLogin; |
| 25 | + private readonly DatabaseUser? _unprivilegedMasterUser; |
| 26 | + private readonly DatabaseUser? _unprivilegedAppUser; |
| 27 | + |
| 28 | + private readonly string? _unprivilegedConnectionString; |
| 29 | + |
| 30 | + public static bool CanRunTests => |
| 31 | + DataTestUtility.AreConnStringsSetup() && DataTestUtility.IsNotAzureServer() |
| 32 | + && DataTestUtility.CanCreateLogins && DataTestUtility.CanUseSqlAuthentication; |
| 33 | + |
| 34 | + public UnprivilegedLogin() |
| 35 | + { |
| 36 | + // xUnit will instantiate the class before evaluating the test condition - make sure that we don't |
| 37 | + // attempt to make use of these capabilities if the server doesn't support them. |
| 38 | + // This has the expected nullability implications, so AssertEnvironmentCreated needs to be called |
| 39 | + // before any test logic. The compiler asserts these for us. |
| 40 | + if (!CanRunTests) |
| 41 | + { |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + // We require two connections: a "management" connection which has permissions to create logins, |
| 46 | + // create users and modify permissions; and an "unprivileged" connection, which is used to perform |
| 47 | + // the actual tests. The user associated with the latter connection will be denied SELECT permissions |
| 48 | + // over master.sys.all_columns. |
| 49 | + _managementConnection = new SqlConnection(DataTestUtility.TCPConnectionString); |
| 50 | + _managementConnection.Open(); |
| 51 | + |
| 52 | + _unprivilegedLogin = new ServerLogin(_managementConnection, nameof(UnprivilegedLogin), _managementConnection.Database); |
| 53 | + _unprivilegedAppUser = new DatabaseUser(_managementConnection, _managementConnection.Database, _unprivilegedLogin); |
| 54 | + _unprivilegedMasterUser = new DatabaseUser(_managementConnection, "master", _unprivilegedLogin); |
| 55 | + |
| 56 | + using (SqlCommand permissionsModificationCommand = _managementConnection.CreateCommand()) |
| 57 | + { |
| 58 | + permissionsModificationCommand.CommandText = $"DENY SELECT ON [master].[sys].[all_columns] TO {_unprivilegedMasterUser.Name}"; |
| 59 | + permissionsModificationCommand.ExecuteNonQuery(); |
| 60 | + |
| 61 | + permissionsModificationCommand.CommandText = $"DENY SELECT ON [{_managementConnection.Database}].[sys].[all_columns] TO {_unprivilegedMasterUser.Name}"; |
| 62 | + permissionsModificationCommand.ExecuteNonQuery(); |
| 63 | + } |
| 64 | + |
| 65 | + SqlConnectionStringBuilder tcpConnectionBuilder = new(DataTestUtility.TCPConnectionString) |
| 66 | + { |
| 67 | + IntegratedSecurity = false, |
| 68 | + UserID = _unprivilegedLogin.UnescapedName, |
| 69 | + Password = _unprivilegedLogin.Password, |
| 70 | + // Disable connection pooling - we'll be dropping this login once the tests complete, and this can only happen once all connections |
| 71 | + // using it are closed. |
| 72 | + Pooling = false |
| 73 | + }; |
| 74 | + |
| 75 | + _unprivilegedConnectionString = tcpConnectionBuilder.ConnectionString; |
| 76 | + } |
| 77 | + |
| 78 | + /// <summary> |
| 79 | + /// This method enables nullability assertions to operate as expected. It'll always pass if CanRunTests is |
| 80 | + /// true - the constructor will have initialized the relevant fields. |
| 81 | + /// </summary> |
| 82 | + [MemberNotNull(nameof(_managementConnection), |
| 83 | + nameof(_unprivilegedLogin), |
| 84 | + nameof(_unprivilegedMasterUser), |
| 85 | + nameof(_unprivilegedAppUser), |
| 86 | + nameof(_unprivilegedConnectionString))] |
| 87 | + private void AssertEnvironmentCreated() |
| 88 | + { |
| 89 | + Assert.NotNull(_managementConnection); |
| 90 | + Assert.NotNull(_unprivilegedLogin); |
| 91 | + Assert.NotNull(_unprivilegedMasterUser); |
| 92 | + Assert.NotNull(_unprivilegedAppUser); |
| 93 | + Assert.NotNull(_unprivilegedConnectionString); |
| 94 | + } |
| 95 | + |
| 96 | + /// <summary> |
| 97 | + /// Verifies that a bulk copy operation succeeds when performed by a user with only SELECT and INSERT permissions, |
| 98 | + /// without requiring access to metadata views. |
| 99 | + /// </summary> |
| 100 | + [ConditionalFact(nameof(CanRunTests))] |
| 101 | + public void BulkCopyWithoutMetadataPermission_Succeeds() |
| 102 | + { |
| 103 | + AssertEnvironmentCreated(); |
| 104 | + |
| 105 | + using DataTable srcDataTable = new() |
| 106 | + { |
| 107 | + Columns = { new DataColumn("Description", typeof(string)) } |
| 108 | + }; |
| 109 | + using Table dstTable = new(_managementConnection, nameof(BulkCopyWithoutMetadataPermission_Succeeds), "([Description] VARCHAR(100))"); |
| 110 | + using (SqlCommand permissionsConfigurationCommand = new($"GRANT SELECT, INSERT ON {dstTable.Name} TO {_unprivilegedAppUser.Name}", _managementConnection)) |
| 111 | + { |
| 112 | + permissionsConfigurationCommand.ExecuteNonQuery(); |
| 113 | + } |
| 114 | + |
| 115 | + using SqlBulkCopy nodeCopy = new(_unprivilegedConnectionString); |
| 116 | + |
| 117 | + for (int i = 0; i < 5; i++) |
| 118 | + { |
| 119 | + srcDataTable.Rows.Add($"Description {i}"); |
| 120 | + } |
| 121 | + |
| 122 | + nodeCopy.DestinationTableName = dstTable.Name; |
| 123 | + nodeCopy.ColumnMappings.Add("Description", "Description"); |
| 124 | + nodeCopy.WriteToServer(srcDataTable); |
| 125 | + } |
| 126 | + |
| 127 | + [ConditionalFact(nameof(CanRunTests))] |
| 128 | + public void BulkCopyWithoutMetadataPermission_FailsWhenUsingAliases() |
| 129 | + { |
| 130 | + AssertEnvironmentCreated(); |
| 131 | + |
| 132 | + using DataTable edges = new DataTable() |
| 133 | + { |
| 134 | + Columns = { new DataColumn("To_ID", typeof(string)), new DataColumn("From_ID", typeof(string)), new DataColumn("Description", typeof(string)) } |
| 135 | + }; |
| 136 | + |
| 137 | + // Use the management connection to create the source and the destination tables, grant the |
| 138 | + // unprivileged user permissions over them and insert some sample data into the source table. |
| 139 | + using Table srcNodeTable = new(_managementConnection, nameof(BulkCopyWithoutMetadataPermission_FailsWhenUsingAliases), "([Name] VARCHAR(100)) AS NODE"); |
| 140 | + using Table dstEdgeTable = new(_managementConnection, nameof(BulkCopyWithoutMetadataPermission_FailsWhenUsingAliases), "([Description] VARCHAR(100)) AS EDGE"); |
| 141 | + using (SqlCommand permissionsConfigurationCommand = _managementConnection.CreateCommand()) |
| 142 | + { |
| 143 | + permissionsConfigurationCommand.CommandText = $"GRANT SELECT, INSERT ON {srcNodeTable.Name} TO {_unprivilegedAppUser.Name}"; |
| 144 | + permissionsConfigurationCommand.ExecuteNonQuery(); |
| 145 | + |
| 146 | + permissionsConfigurationCommand.CommandText = $"GRANT SELECT, INSERT ON {dstEdgeTable.Name} TO {_unprivilegedAppUser.Name}"; |
| 147 | + permissionsConfigurationCommand.ExecuteNonQuery(); |
| 148 | + } |
| 149 | + |
| 150 | + string sampleNodeDataCommand = @$"INSERT INTO {srcNodeTable.Name} ([Name]) SELECT LEFT([name], 100) FROM sys.sysobjects"; |
| 151 | + using (SqlCommand insertSampleNodes = new(sampleNodeDataCommand, _managementConnection)) |
| 152 | + { |
| 153 | + insertSampleNodes.ExecuteNonQuery(); |
| 154 | + } |
| 155 | + |
| 156 | + using (SqlCommand nodeQuery = new($"SELECT $node_id FROM {srcNodeTable.Name}", _managementConnection)) |
| 157 | + using (SqlDataReader reader = nodeQuery.ExecuteReader()) |
| 158 | + { |
| 159 | + bool firstRead = reader.Read(); |
| 160 | + string toId; |
| 161 | + string fromId; |
| 162 | + |
| 163 | + Assert.True(firstRead); |
| 164 | + toId = reader.GetString(0); |
| 165 | + |
| 166 | + while (reader.Read()) |
| 167 | + { |
| 168 | + fromId = reader.GetString(0); |
| 169 | + |
| 170 | + edges.Rows.Add(toId, fromId, "Test Description"); |
| 171 | + toId = fromId; |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + // With all source data populated, try to use the unprivileged connection to perform a bulk copy |
| 176 | + // using aliases in the column mappings. This should fail - the permissions error will be caught, |
| 177 | + // and SqlBulkCopy should simply report that the destination column doesn't exist. |
| 178 | + using SqlBulkCopy edgeCopy = new(_unprivilegedConnectionString); |
| 179 | + |
| 180 | + edgeCopy.DestinationTableName = dstEdgeTable.Name; |
| 181 | + edgeCopy.ColumnMappings.Add("To_ID", "$to_id"); |
| 182 | + edgeCopy.ColumnMappings.Add("From_ID", "$from_id"); |
| 183 | + edgeCopy.ColumnMappings.Add("Description", "Description"); |
| 184 | + |
| 185 | + Action failingEdgeCopy = () => edgeCopy.WriteToServer(edges); |
| 186 | + InvalidOperationException missingColumnException = Assert.Throws<InvalidOperationException>(failingEdgeCopy); |
| 187 | + |
| 188 | + Assert.Contains("'$to_id,$from_id'", missingColumnException.Message); |
| 189 | + } |
| 190 | + |
| 191 | + public void Dispose() |
| 192 | + { |
| 193 | + _unprivilegedAppUser?.Dispose(); |
| 194 | + _unprivilegedMasterUser?.Dispose(); |
| 195 | + _unprivilegedLogin?.Dispose(); |
| 196 | + _managementConnection?.Dispose(); |
| 197 | + } |
| 198 | +} |
0 commit comments