| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. See License.txt in the project root for license information. |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.Collections.Generic; |
| | 6 | | using System.Linq; |
| | 7 | | using System.Net.Http; |
| | 8 | | using System.Threading.Tasks; |
| | 9 | | using Microsoft.Azure.Graph.RBAC; |
| | 10 | | using Microsoft.Azure.Graph.RBAC.Models; |
| | 11 | | using Microsoft.Azure.KeyVault; |
| | 12 | | using Microsoft.Azure.KeyVault.Models; |
| | 13 | | using Microsoft.Azure.KeyVault.WebKey; |
| | 14 | | using Microsoft.Azure.Test.HttpRecorder; |
| | 15 | | using Microsoft.IdentityModel.Clients.ActiveDirectory; |
| | 16 | | using Microsoft.Rest.ClientRuntime.Azure.TestFramework; |
| | 17 | | using Microsoft.Azure.Management.ResourceManager; |
| | 18 | | using System.Net; |
| | 19 | | using Microsoft.Rest.TransientFaultHandling; |
| | 20 | | using System.Diagnostics; |
| | 21 | |
|
| | 22 | | namespace KeyVault.TestFramework |
| | 23 | | { |
| | 24 | | public class KeyVaultTestFixture : IDisposable |
| | 25 | | { |
| | 26 | | // Required in test code |
| | 27 | | public string vaultAddress; |
| | 28 | | public bool standardVaultOnly; |
| | 29 | | public bool softDeleteEnabled; |
| | 30 | | public string keyName; |
| | 31 | | public string keyVersion; |
| | 32 | | public KeyIdentifier keyIdentifier; |
| | 33 | | public ClientCredential clientCredential; |
| | 34 | | public RetryPolicy retryExecutor; |
| | 35 | | public string StorageResourceUrl1; |
| | 36 | | public string StorageResourceUrl2; |
| | 37 | |
|
| | 38 | | // Required for cleaning up at the end of the test |
| 8 | 39 | | private string rgName = "", appObjectId = ""; |
| | 40 | | private bool fromConfig; |
| | 41 | | private TokenCache tokenCache; |
| | 42 | | private DeviceCodeResult _deviceCodeForStorageTests; |
| | 43 | |
|
| 4 | 44 | | public KeyVaultTestFixture() |
| | 45 | | { |
| 4 | 46 | | Initialize(this.GetType()); |
| | 47 | |
|
| 4 | 48 | | if (vaultAddress != null && HttpMockServer.Mode == HttpRecorderMode.Record) |
| | 49 | | { |
| | 50 | | //Create one key to use for testing. Key creation is expensive. |
| 0 | 51 | | var myClient = new KeyVaultClient(new TestKeyVaultCredential(GetAccessToken), GetHandlers()); |
| 0 | 52 | | keyName = "sdktestkey"; |
| 0 | 53 | | var attributes = new KeyAttributes(); |
| 0 | 54 | | var createdKey = myClient.CreateKeyAsync(vaultAddress, keyName, JsonWebKeyType.Rsa, 2048, |
| 0 | 55 | | JsonWebKeyOperation.AllOperations, attributes).GetAwaiter().GetResult(); |
| 0 | 56 | | keyIdentifier = new KeyIdentifier(createdKey.Key.Kid); |
| 0 | 57 | | keyName = keyIdentifier.Name; |
| 0 | 58 | | keyVersion = keyIdentifier.Version; |
| 0 | 59 | | tokenCache = new TokenCache(); |
| 0 | 60 | | _deviceCodeForStorageTests = null; |
| 0 | 61 | | retryExecutor = new RetryPolicy<SoftDeleteErrorDetectionStrategy>(new ExponentialBackoffRetryStrategy(8, |
| | 62 | | } else |
| | 63 | | { |
| 4 | 64 | | retryExecutor = new RetryPolicy<SoftDeleteErrorDetectionStrategy>( new FixedIntervalRetryStrategy( 5, Ti |
| | 65 | | } |
| 4 | 66 | | } |
| | 67 | |
|
| | 68 | | public void Initialize(Type type) |
| | 69 | | { |
| 4 | 70 | | HttpMockServer.FileSystemUtilsObject = new FileSystemUtils(); |
| 4 | 71 | | HttpMockServer.Initialize(type, "InitialCreation", HttpRecorderMode.Record); |
| 4 | 72 | | HttpMockServer.CreateInstance(); |
| | 73 | |
|
| 4 | 74 | | if (HttpMockServer.Mode == HttpRecorderMode.Record) |
| | 75 | | { |
| 4 | 76 | | fromConfig = FromConfiguration(); |
| | 77 | | } |
| 4 | 78 | | } |
| | 79 | |
|
| | 80 | | private static string GetKeyVaultLocation(ResourceManagementClient resourcesClient) |
| | 81 | | { |
| 0 | 82 | | var providers = resourcesClient.Providers.Get("Microsoft.KeyVault"); |
| 0 | 83 | | var location = providers.ResourceTypes.Where( |
| 0 | 84 | | (resType) => |
| 0 | 85 | | { |
| 0 | 86 | | if (resType.ResourceType == "vaults") |
| 0 | 87 | | return true; |
| 0 | 88 | | else |
| 0 | 89 | | return false; |
| 0 | 90 | | } |
| 0 | 91 | | ).First().Locations.FirstOrDefault(); |
| 0 | 92 | | return location; |
| | 93 | | } |
| | 94 | |
|
| | 95 | | private static ServicePrincipal CreateServicePrincipal(Application app, |
| | 96 | | GraphRbacManagementClient graphClient) |
| | 97 | | { |
| 0 | 98 | | var parameters = new ServicePrincipalCreateParameters |
| 0 | 99 | | { |
| 0 | 100 | | AccountEnabled = true, |
| 0 | 101 | | AppId = app.AppId |
| 0 | 102 | | }; |
| 0 | 103 | | var servicePrincipal = graphClient.ServicePrincipal.Create(parameters); |
| 0 | 104 | | return servicePrincipal; |
| | 105 | | } |
| | 106 | |
|
| | 107 | | private static Application CreateApplication(GraphRbacManagementClient graphClient, string appDisplayName, strin |
| | 108 | | { |
| 0 | 109 | | return graphClient.Application.Create(new ApplicationCreateParameters |
| 0 | 110 | | { |
| 0 | 111 | | DisplayName = appDisplayName, |
| 0 | 112 | | IdentifierUris = new List<string>() { "http://" + Guid.NewGuid().ToString() + ".com" }, |
| 0 | 113 | | Homepage = "http://contoso.com", |
| 0 | 114 | | AvailableToOtherTenants = false, |
| 0 | 115 | | PasswordCredentials = new[] |
| 0 | 116 | | { |
| 0 | 117 | | new PasswordCredential |
| 0 | 118 | | { |
| 0 | 119 | | Value = secret, |
| 0 | 120 | | StartDate = DateTime.Now - TimeSpan.FromDays(1), |
| 0 | 121 | | EndDate = DateTime.Now + TimeSpan.FromDays(1), |
| 0 | 122 | | KeyId = Guid.NewGuid().ToString() |
| 0 | 123 | | } |
| 0 | 124 | | } |
| 0 | 125 | | }); |
| | 126 | | } |
| | 127 | |
|
| | 128 | | private bool FromConfiguration() |
| | 129 | | { |
| 4 | 130 | | string vault = TestConfigurationManager.TryGetEnvironmentOrAppSetting("VaultUrl"); |
| 4 | 131 | | string authClientId = TestConfigurationManager.TryGetEnvironmentOrAppSetting("AuthClientId"); |
| 4 | 132 | | string authSecret = TestConfigurationManager.TryGetEnvironmentOrAppSetting("AuthClientSecret"); |
| 4 | 133 | | string standardVaultOnlyString = TestConfigurationManager.TryGetEnvironmentOrAppSetting("StandardVaultOnly") |
| 4 | 134 | | string softDeleteEnabledString = TestConfigurationManager.TryGetEnvironmentOrAppSetting("SoftDeleteEnabled") |
| 4 | 135 | | string storageUrl1 = TestConfigurationManager.TryGetEnvironmentOrAppSetting("StorageResourceUrl1"); |
| 4 | 136 | | string storageUrl2 = TestConfigurationManager.TryGetEnvironmentOrAppSetting("StorageResourceUrl2"); |
| | 137 | | bool standardVaultOnlyresult; |
| 4 | 138 | | if (!bool.TryParse(standardVaultOnlyString, out standardVaultOnlyresult)) |
| | 139 | | { |
| 0 | 140 | | standardVaultOnlyresult = false; |
| | 141 | | } |
| | 142 | |
|
| | 143 | | bool softDeleteEnabledresult; |
| 4 | 144 | | if (!bool.TryParse(softDeleteEnabledString, out softDeleteEnabledresult)) |
| | 145 | | { |
| 0 | 146 | | softDeleteEnabledresult = false; |
| | 147 | | } |
| | 148 | |
|
| 4 | 149 | | if (string.IsNullOrWhiteSpace(vault) || string.IsNullOrWhiteSpace(authClientId) || string.IsNullOrWhiteSpace |
| 4 | 150 | | string.IsNullOrWhiteSpace(storageUrl1) || string.IsNullOrWhiteSpace(storageUrl2)) |
| 4 | 151 | | return false; |
| | 152 | | else |
| | 153 | | { |
| 0 | 154 | | this.vaultAddress = vault; |
| 0 | 155 | | this.clientCredential = new ClientCredential(authClientId, authSecret); |
| 0 | 156 | | this.standardVaultOnly = standardVaultOnlyresult; |
| 0 | 157 | | this.softDeleteEnabled = softDeleteEnabledresult; |
| 0 | 158 | | this.StorageResourceUrl1 = storageUrl1; |
| 0 | 159 | | this.StorageResourceUrl2 = storageUrl2; |
| 0 | 160 | | return true; |
| | 161 | | } |
| | 162 | | } |
| | 163 | |
|
| | 164 | | public async Task<string> GetAccessToken(string authority, string resource, string scope) |
| | 165 | | { |
| 0 | 166 | | var context = new AuthenticationContext(authority, tokenCache); |
| 0 | 167 | | var result = await context.AcquireTokenAsync(resource, clientCredential).ConfigureAwait(false); |
| | 168 | |
|
| 0 | 169 | | return result.AccessToken; |
| 0 | 170 | | } |
| | 171 | |
|
| | 172 | | public async Task<string> GetUserAccessToken(string authority, string resource, string scope) |
| | 173 | | { |
| 0 | 174 | | string clientId = TestConfigurationManager.TryGetEnvironmentOrAppSetting("NativeClientId"); |
| 0 | 175 | | var context = new AuthenticationContext(authority, tokenCache); |
| 0 | 176 | | if (_deviceCodeForStorageTests == null) |
| | 177 | | { |
| 0 | 178 | | _deviceCodeForStorageTests = |
| 0 | 179 | | await context.AcquireDeviceCodeAsync(resource, clientId).ConfigureAwait(false); |
| | 180 | |
|
| | 181 | | Debug.WriteLine("####################################################################################### |
| | 182 | | Debug.WriteLine("Test won't run until you perform following steps:"); |
| | 183 | | Debug.WriteLine($"1. Go to following url: {_deviceCodeForStorageTests.VerificationUrl}."); |
| | 184 | | Debug.WriteLine($"2. Insert following User Code: {_deviceCodeForStorageTests.UserCode}."); |
| | 185 | | Debug.WriteLine("3. Login with your username and password credentials."); |
| | 186 | | Debug.WriteLine("####################################################################################### |
| | 187 | | } |
| | 188 | |
|
| 0 | 189 | | var result = await context.AcquireTokenByDeviceCodeAsync(_deviceCodeForStorageTests).ConfigureAwait(false); |
| 0 | 190 | | return result.AccessToken; |
| 0 | 191 | | } |
| | 192 | |
|
| | 193 | | public KeyVaultClient CreateKeyVaultClient() |
| | 194 | | { |
| 106 | 195 | | var myclient = new KeyVaultClient(new TestKeyVaultCredential(GetAccessToken), GetHandlers()); |
| 106 | 196 | | return myclient; |
| | 197 | | } |
| | 198 | |
|
| | 199 | | public KeyVaultClient CreateKeyVaultUserClient() |
| | 200 | | { |
| 12 | 201 | | var myclient = new KeyVaultClient(new TestKeyVaultCredential(GetUserAccessToken), GetHandlers()); |
| 12 | 202 | | return myclient; |
| | 203 | | } |
| | 204 | |
|
| | 205 | | public void WaitOnDeletedKey(KeyVaultClient client, string vaultAddress, string keyName) |
| | 206 | | { |
| 104 | 207 | | this.retryExecutor.ExecuteAction(() => client.GetDeletedKeyAsync(vaultAddress, keyName).GetAwaiter().GetResu |
| 22 | 208 | | } |
| | 209 | |
|
| | 210 | | public void WaitOnDeletedSecret(KeyVaultClient client, string vaultAddress, string secretName) |
| | 211 | | { |
| 82 | 212 | | this.retryExecutor.ExecuteAction(() => client.GetDeletedSecretAsync(vaultAddress, secretName).GetAwaiter().G |
| 18 | 213 | | } |
| | 214 | |
|
| | 215 | | public void WaitOnDeletedCertificate(KeyVaultClient client, string vaultAddress, string certificateName) |
| | 216 | | { |
| 60 | 217 | | this.retryExecutor.ExecuteAction(() => client.GetDeletedCertificateAsync(vaultAddress, certificateName).GetA |
| 12 | 218 | | } |
| | 219 | |
|
| | 220 | | public void WaitOnKey(KeyVaultClient client, string vaultAddress, string keyName) |
| | 221 | | { |
| 4 | 222 | | this.retryExecutor.ExecuteAction(() => client.GetKeyAsync(vaultAddress, keyName).GetAwaiter().GetResult()); |
| 2 | 223 | | } |
| | 224 | |
|
| | 225 | | public void WaitOnSecret(KeyVaultClient client, string vaultAddress, string secretName) |
| | 226 | | { |
| 4 | 227 | | this.retryExecutor.ExecuteAction(() => client.GetSecretAsync(vaultAddress, secretName).GetAwaiter().GetResul |
| 2 | 228 | | } |
| | 229 | |
|
| | 230 | | public void WaitOnCertificate(KeyVaultClient client, string vaultAddress, string certificateName) |
| | 231 | | { |
| 0 | 232 | | this.retryExecutor.ExecuteAction(() => client.GetCertificateAsync(vaultAddress, certificateName).GetAwaiter( |
| 0 | 233 | | } |
| | 234 | |
|
| | 235 | | public DelegatingHandler[ ] GetHandlers() |
| | 236 | | { |
| 120 | 237 | | HttpMockServer server = HttpMockServer.CreateInstance(); |
| 120 | 238 | | var testHttpHandler = new TestHttpMessageHandler(); |
| 120 | 239 | | return new DelegatingHandler[] { server, testHttpHandler }; |
| | 240 | | } |
| | 241 | | public void Dispose() |
| | 242 | | { |
| 4 | 243 | | if (HttpMockServer.Mode == HttpRecorderMode.Record && !fromConfig) |
| | 244 | | { |
| 0 | 245 | | var testEnv = TestEnvironmentFactory.GetTestEnvironment(); |
| 0 | 246 | | var context = new MockContext(); |
| | 247 | |
|
| 0 | 248 | | var resourcesClient = context.GetServiceClient<ResourceManagementClient>(); |
| 0 | 249 | | var graphClient = context.GetServiceClient<GraphRbacManagementClient>(); |
| 0 | 250 | | graphClient.TenantID = testEnv.Tenant; |
| 0 | 251 | | graphClient.BaseUri = new Uri("https://graph.windows.net"); |
| | 252 | |
|
| 0 | 253 | | graphClient.Application.Delete(appObjectId); |
| 0 | 254 | | resourcesClient.ResourceGroups.Delete(rgName); |
| | 255 | | } |
| 4 | 256 | | } |
| | 257 | | } |
| | 258 | | } |