internal static KeyVaultCertificateOperation FromCertificateOperation(CertificateOperation certificateOperation)
        {
            if (certificateOperation == null)
            {
                return null;
            }

            var kvCertificateOperation = new KeyVaultCertificateOperation
            {
                Id = certificateOperation.Id,
                Status = certificateOperation.Status,
                StatusDetais = certificateOperation.StatusDetails,
                RequestId = certificateOperation.RequestId,
                Target = certificateOperation.Target,
                Issuer = certificateOperation.IssuerReference.Name,
                CancellationRequested = certificateOperation.CancellationRequested,
            };

            if (certificateOperation.Csr != null && certificateOperation.Csr.Length != 0)
            {
                kvCertificateOperation.CertificateSigningRequest = Convert.ToBase64String(certificateOperation.Csr);
            }

            if (certificateOperation.Error != null)
            {
                kvCertificateOperation.ErrorCode = certificateOperation.Error.Code;
                kvCertificateOperation.ErrorMessage = certificateOperation.Error.Message;
            }

            return kvCertificateOperation;
        }
예제 #2
0
        public async Task VerifyCertificateOperationError()
        {
            string issuerName = Recording.GenerateId();
            string certName   = Recording.GenerateId();

            CertificateIssuer certIssuer = new CertificateIssuer(issuerName)
            {
                AccountId      = "test",
                Password       = "******",
                OrganizationId = "test",
            };

            certIssuer.Properties.Provider = "DigiCert";

            await Client.CreateIssuerAsync(certIssuer);

            CertificateOperation operation = null;

            try
            {
                CertificatePolicy certificatePolicy = DefaultPolicy;
                certificatePolicy.IssuerName = issuerName;

                operation = await Client.StartCreateCertificateAsync(certName, certificatePolicy);

                RegisterForCleanup(certName);

                using CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
                TimeSpan pollingInterval = TimeSpan.FromSeconds((Mode == RecordedTestMode.Playback) ? 0 : 1);

                while (!operation.HasCompleted)
                {
                    await Task.Delay(pollingInterval, cts.Token);

                    await operation.UpdateStatusAsync(cts.Token);
                }

                InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => { KeyVaultCertificateWithPolicy cert = operation.Value; });
                StringAssert.StartsWith("The certificate operation failed: ", ex.Message);

                Assert.IsTrue(operation.HasCompleted);
                Assert.IsFalse(operation.HasValue);
                Assert.AreEqual(200, operation.GetRawResponse().Status);
                Assert.AreEqual("failed", operation.Properties.Status);
            }
            catch (TaskCanceledException) when(operation != null)
            {
                Assert.Inconclusive("Timed out while waiting for operation {0}", operation.Id);
            }
            finally
            {
                await Client.DeleteIssuerAsync(issuerName);
            }
        }
        public async Task DownloadECDsaCertificateSignLocalVerifyRemote([EnumValues] CertificateContentType contentType, [EnumValues] CertificateKeyCurveName keyCurveName)
        {
#if NET461
            Assert.Ignore("ECC is not supported before .NET Framework 4.7");
#endif
            string name = Recording.GenerateId();

            CertificatePolicy policy = new CertificatePolicy
            {
                IssuerName   = WellKnownIssuerNames.Self,
                Subject      = "CN=default",
                KeyType      = CertificateKeyType.Ec,
                KeyCurveName = keyCurveName,
                Exportable   = true,
                KeyUsage     =
                {
                    CertificateKeyUsage.DigitalSignature,
                },
                ContentType = contentType,
            };

            CertificateOperation operation = await Client.StartCreateCertificateAsync(name, policy);

            RegisterForCleanup(name);

            await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);

            // Download the certificate and sign data locally.
            byte[] plaintext = Encoding.UTF8.GetBytes(nameof(DownloadECDsaCertificateSignRemoteVerifyLocal));

            X509Certificate2 certificate = null;
            try
            {
                certificate = await Client.DownloadCertificateAsync(name, operation.Value.Properties.Version);

                using ECDsa privateKey = certificate.GetECDsaPrivateKey();

                byte[] signature = privateKey.SignData(plaintext, keyCurveName.GetHashAlgorithmName());

                // Verify data remotely.
                CryptographyClient cryptoClient = GetCryptographyClient(operation.Value.KeyId);
                VerifyResult       result       = await cryptoClient.VerifyDataAsync(keyCurveName.GetSignatureAlgorithm(), plaintext, signature);

                Assert.IsTrue(result.IsValid);
            }
            catch (Exception ex) when(IsExpectedP256KException(ex, keyCurveName))
            {
                Assert.Ignore("The curve is not supported by the current platform");
            }
            finally
            {
                certificate?.Dispose();
            }
        }
        public async Task DownloadVersionedCertificate(string contentType)
        {
            string            name   = Recording.GenerateId();
            CertificatePolicy policy = new CertificatePolicy
            {
                IssuerName = WellKnownIssuerNames.Self,
                Subject    = "CN=default",
                KeyType    = CertificateKeyType.Rsa,
                Exportable = true,
                ReuseKey   = false,
                KeyUsage   =
                {
                    CertificateKeyUsage.DataEncipherment,
                },
                CertificateTransparency = false,
                ContentType             = contentType,
            };

            CertificateOperation operation = await Client.StartCreateCertificateAsync(name, policy);

            RegisterForCleanup(name);

            await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);

            KeyVaultCertificate certificate = await Client.GetCertificateAsync(name);

            string version = certificate.Properties.Version;

            using X509Certificate2 pub = new X509Certificate2(certificate.Cer);
            using RSA pubkey           = (RSA)pub.PublicKey.Key;

            byte[] plaintext  = Encoding.UTF8.GetBytes("Hello, world!");
            byte[] ciphertext = pubkey.Encrypt(plaintext, RSAEncryptionPadding.Pkcs1);

            // Create a new certificate version that is not exportable just to further prove we are not downloading it.
            policy.Exportable = false;
            operation         = await Client.StartCreateCertificateAsync(name, policy);

            await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);

            certificate = await Client.GetCertificateAsync(name);

            Assert.AreNotEqual(version, certificate.Properties.Version);

            // Now download the certificate and test decryption.
            using X509Certificate2 x509certificate = await Client.DownloadCertificateAsync(name, version);

            Assert.IsTrue(x509certificate.HasPrivateKey);

            using RSA rsa = (RSA)x509certificate.PrivateKey;
            byte[] decrypted = rsa.Decrypt(ciphertext, RSAEncryptionPadding.Pkcs1);

            CollectionAssert.AreEqual(plaintext, decrypted);
        }
예제 #5
0
        public async Task CreateCertificateAsync()
        {
            #region Snippet:CreateCertificateAsync
            // Create a certificate. This starts a long running operation to create and sign the certificate.
            CertificateOperation operation = await client.StartCreateCertificateAsync("MyCertificate", CertificatePolicy.Default);

            // You can await the completion of the create certificate operation.
            KeyVaultCertificateWithPolicy certificate = await operation.WaitForCompletionAsync();

            #endregion
        }
        public async Task HelloWorldAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            // Instantiate a certificate client that will be used to call the service. Notice that the client is using
            // default Azure credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
            // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
            var client = new CertificateClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // Let's create a self signed certifiate using the default policy. If the certificiate
            // already exists in the Key Vault, then a new version of the key is created.
            string certName = $"defaultCert-{Guid.NewGuid()}";

            CertificateOperation certOp = await client.StartCreateCertificateAsync(certName);

            // Next let's wait on the certificate operation to complete. Note that certificate creation can last an indeterministic
            // amount of time, so applications should only wait on the operation to complete in the case the issuance time is well
            // known and within the scope of the application lifetime. In this case we are creating a self-signed certificate which
            // should be issued in a relatively short amount of time.
            CertificateWithPolicy certificate = await certOp.WaitForCompletionAsync();

            // At some time later we could get the created certificate along with it's policy from the Key Vault.
            certificate = await client.GetCertificateAsync(certName);

            Debug.WriteLine($"Certificate was returned with name {certificate.Name} which expires {certificate.Properties.Expires}");

            // We find that the certificate has been compromised and we want to disable it so applications will no longer be able
            // to access the compromised version of the certificate.
            CertificateProperties certificateProperties = certificate.Properties;

            certificateProperties.Enabled = false;

            Certificate updatedCert = await client.UpdateCertificatePropertiesAsync(certificateProperties);

            Debug.WriteLine($"Certificate enabled set to '{updatedCert.Properties.Enabled}'");

            // We need to create a new version of the certificate that applications can use to replace the compromised certificate.
            // Creating a certificate with the same name and policy as the compromised certificate will create another version of the
            // certificate with similar properties to the original certificate
            CertificateOperation newCertOp = await client.StartCreateCertificateAsync(certificate.Name, certificate.Policy);

            CertificateWithPolicy newCert = await newCertOp.WaitForCompletionAsync();

            // The certificate is no longer needed, need to delete it from the Key Vault.
            await client.DeleteCertificateAsync(certName);

            // To ensure key is deleted on server side.
            Assert.IsTrue(await WaitForDeletedKeyAsync(client, certName));

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            await client.PurgeDeletedCertificateAsync(certName);
        }
예제 #7
0
        public async Task DownloadCertificateAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            CertificateClient client = new CertificateClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            string certificateName         = $"rsa-{Guid.NewGuid()}";
            CertificateOperation operation = await client.StartCreateCertificateAsync(certificateName, CertificatePolicy.Default);

            await operation.WaitForCompletionAsync();

            using SHA256 sha = SHA256.Create();
            byte[] data = Encoding.UTF8.GetBytes("test");
            byte[] hash = sha.ComputeHash(data);

            #region Snippet:CertificatesSample4DownloadCertificateAsync
            X509KeyStorageFlags keyStorageFlags = X509KeyStorageFlags.MachineKeySet;
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                keyStorageFlags |= X509KeyStorageFlags.EphemeralKeySet;
            }

            DownloadCertificateOptions options = new DownloadCertificateOptions
            {
                KeyStorageFlags = keyStorageFlags
            };

            using X509Certificate2 certificate = await client.DownloadCertificateAsync(certificateName, options : options);

            using RSA key = certificate.GetRSAPrivateKey();

            byte[] signature = key.SignHash(hash, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            Debug.WriteLine($"Signature: {Convert.ToBase64String(signature)}");
            #endregion

            Response <KeyVaultCertificateWithPolicy> certificateResponse = await client.GetCertificateAsync(certificateName);

            using X509Certificate2 publicCertificate = new X509Certificate2(certificateResponse.Value.Cer);
            using RSA publicKey = publicCertificate.GetRSAPublicKey();

            bool verified = publicKey.VerifyHash(hash, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            Debug.WriteLine($"Signature verified: {verified}");

            Assert.IsTrue(verified);

            DeleteCertificateOperation deleteOperation = await client.StartDeleteCertificateAsync(certificateName);

            await deleteOperation.WaitForCompletionAsync();

            client.PurgeDeletedCertificate(certificateName);
        }
예제 #8
0
        public async Task VerifyCertificateCreateDefaultPolicy()
        {
            string certName = Recording.GenerateId();

            CertificateOperation operation = await Client.StartCreateCertificateAsync(certName);

            RegisterForCleanup(certName);

            CertificateWithPolicy certificate = await WaitForCompletion(operation);

            Assert.NotNull(certificate);

            Assert.AreEqual(certificate.Name, certName);
        }
        public async Task UpdateStatusEventuallyCompleted()
        {
            var transport = new MockTransport(new[]
            {
                new MockResponse(202).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),

                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),
                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),
                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),
                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),
                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),
                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),
                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),
                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),
                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),

                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""completed""}}"),
                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/1"",""policy"":{s_policyJson}}}"),
            });

            CertificateClient    client    = CreateClient(transport);
            CertificateOperation operation = await client.StartCreateCertificateAsync(CertificateName, s_policy);

            await WaitForOperationAsync(operation);

            // Begin
            IEnumerable <EventWrittenEventArgs> messages = _listener.EventsById(CertificatesEventSource.BeginUpdateStatusEvent);

            Assert.AreEqual(10, messages.Count());

            EventWrittenEventArgs message = messages.Last();

            Assert.AreEqual(EventLevel.Verbose, message.Level);
            Assert.AreEqual("BeginUpdateStatus", message.EventName);
            Assert.AreEqual($"{CertificateId}/pending", message.GetProperty <string>("id"));
            Assert.AreEqual("inProgress", message.GetProperty <string>("status"));
            Assert.AreEqual("(none)", message.GetProperty <string>("error"));

            // End
            messages = _listener.EventsById(CertificatesEventSource.EndUpdateStatusEvent);
            Assert.AreEqual(10, messages.Count());

            message = messages.Last();
            Assert.AreEqual(EventLevel.Verbose, message.Level);
            Assert.AreEqual("EndUpdateStatus", message.EventName);
            Assert.AreEqual($"{CertificateId}/pending", message.GetProperty <string>("id"));
            Assert.AreEqual("completed", message.GetProperty <string>("status"));
            Assert.AreEqual("(none)", message.GetProperty <string>("error"));
        }
예제 #10
0
        public async Task VerifyDeleteCertificateOperation()
        {
            string certName = Recording.GenerateId();

            CertificatePolicy certificatePolicy = Client.CreateDefaultPolicy();

            certificatePolicy.IssuerName = "UNKNOWN";

            CertificateOperation operation = await Client.StartCreateCertificateAsync(certName);

            RegisterForCleanup(certName);

            await Client.DeleteCertificateOperationAsync(certName);

            Assert.ThrowsAsync <RequestFailedException>(() => WaitForCompletion(operation));
        }
        public async Task VerifyGetCertificateOperation()
        {
            string certName = Recording.GenerateId();

            CertificatePolicy certificatePolicy = DefaultPolicy;

            certificatePolicy.IssuerName = WellKnownIssuerNames.Unknown;

            await Client.StartCreateCertificateAsync(certName, certificatePolicy);

            RegisterForCleanup(certName);

            CertificateOperation getOperation = await Client.GetCertificateOperationAsync(certName);

            Assert.IsNotNull(getOperation);
        }
예제 #12
0
        public async Task VerifyGetCertificateOperation()
        {
            string certName = Recording.GenerateId();

            CertificatePolicy certificatePolicy = Client.CreateDefaultPolicy();

            certificatePolicy.IssuerName = "UNKNOWN";

            await Client.StartCreateCertificateAsync(certName);

            RegisterForCleanup(certName);

            CertificateOperation getOperation = await Client.GetCertificateOperationAsync(certName);

            Assert.IsNotNull(getOperation);
        }
        public async Task UpdateStatusErred()
        {
            var transport = new MockTransport(new[]
            {
                new MockResponse(202).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),

                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),
                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),
                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),
                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""inProgress""}}"),

                new MockResponse(200).WithContent($@"{{""id"":""{CertificateId}/pending"",""status"":""failed"",""error"":{{""code"":""mock failure code"",""message"":""mock failure message""}}}}"),
            });

            CertificateClient    client    = CreateClient(transport);
            CertificateOperation operation = await client.StartCreateCertificateAsync(CertificateName, s_policy);

            Exception ex = Assert.ThrowsAsync <InvalidOperationException>(async() => await WaitForOperationAsync(operation));

            Assert.AreEqual("The certificate operation failed: mock failure message", ex.Message);

            // Begin
            IEnumerable <EventWrittenEventArgs> messages = _listener.EventsById(CertificatesEventSource.BeginUpdateStatusEvent);

            Assert.AreEqual(5, messages.Count());

            EventWrittenEventArgs message = messages.Last();

            Assert.AreEqual(EventLevel.Verbose, message.Level);
            Assert.AreEqual("BeginUpdateStatus", message.EventName);
            Assert.AreEqual($"{CertificateId}/pending", message.GetProperty <string>("id"));
            Assert.AreEqual("inProgress", message.GetProperty <string>("status"));
            Assert.AreEqual("(none)", message.GetProperty <string>("error"));

            // End
            messages = _listener.EventsById(CertificatesEventSource.EndUpdateStatusEvent);
            Assert.AreEqual(5, messages.Count());

            message = messages.Last();
            Assert.AreEqual(EventLevel.Verbose, message.Level);
            Assert.AreEqual("EndUpdateStatus", message.EventName);
            Assert.AreEqual($"{CertificateId}/pending", message.GetProperty <string>("id"));
            Assert.AreEqual("failed", message.GetProperty <string>("status"));
            Assert.AreEqual("mock failure message", message.GetProperty <string>("error"));
        }
        public async Task DownloadLatestCertificate(string contentType)
        {
            string            name   = Recording.GenerateId();
            CertificatePolicy policy = new CertificatePolicy
            {
                IssuerName = WellKnownIssuerNames.Self,
                Subject    = "CN=default",
                KeyType    = CertificateKeyType.Rsa,
                Exportable = true,
                ReuseKey   = false,
                KeyUsage   =
                {
                    CertificateKeyUsage.DataEncipherment,
                },
                CertificateTransparency = false,
                ContentType             = contentType,
            };

            CertificateOperation operation = await Client.StartCreateCertificateAsync(name, policy);

            RegisterForCleanup(name);

            await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);

            KeyVaultCertificate certificate = await Client.GetCertificateAsync(name);

            using X509Certificate2 pub = new X509Certificate2(certificate.Cer);
#if NET6_0_OR_GREATER
            using RSA pubkey = (RSA)pub.PublicKey.GetRSAPublicKey();
#else
            using RSA pubkey = (RSA)pub.PublicKey.Key;
#endif

            byte[] plaintext  = Encoding.UTF8.GetBytes("Hello, world!");
            byte[] ciphertext = pubkey.Encrypt(plaintext, RSAEncryptionPadding.Pkcs1);

            using X509Certificate2 x509certificate = await Client.DownloadCertificateAsync(name);

            Assert.IsTrue(x509certificate.HasPrivateKey);

            using RSA rsa = (RSA)x509certificate.GetRSAPrivateKey();
            byte[] decrypted = rsa.Decrypt(ciphertext, RSAEncryptionPadding.Pkcs1);

            CollectionAssert.AreEqual(plaintext, decrypted);
        }
예제 #15
0
        public void CreateCertificate()
        {
            #region Snippet:CreateCertificate
            // Create a certificate. This starts a long running operation to create and sign the certificate.
            CertificateOperation operation = client.StartCreateCertificate("MyCertificate", CertificatePolicy.Default);

            // You can await the completion of the create certificate operation.
            // You should run UpdateStatus in another thread or do other work like pumping messages between calls.
            while (!operation.HasCompleted)
            {
                Thread.Sleep(2000);

                operation.UpdateStatus();
            }

            KeyVaultCertificateWithPolicy certificate = operation.Value;
            #endregion
        }
예제 #16
0
        public void CreateClient()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            #region Snippet:CreateCertificateClient
            // Create a new certificate client using the default credential from Azure.Identity using environment variables previously set,
            // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
            var client = new CertificateClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());

            // Create a certificate using the certificate client.
            CertificateOperation operation = client.StartCreateCertificate("MyCertificate", CertificatePolicy.Default);

            // Retrieve a certificate using the certificate client.
            KeyVaultCertificateWithPolicy certificate = client.GetCertificate("MyCertificate");
            #endregion

            this.client = client;
        }
        public async Task VerifyUnexpectedCancelCertificateOperation()
        {
            string certName = Recording.GenerateId();

            CertificatePolicy certificatePolicy = DefaultPolicy;

            CertificateOperation operation = await Client.StartCreateCertificateAsync(certName, certificatePolicy);

            RegisterForCleanup(certName);

            OperationCanceledException ex = null;

            try
            {
                // Calling through the CertificateClient directly won't affect the CertificateOperation, so subsequent status updates should throw.
                await Client.CancelCertificateOperationAsync(certName);

                await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);
            }
            catch (OperationCanceledException e)
            {
                ex = e;
            }
            catch (RequestFailedException e) when(e.Status == 403)
            {
                Assert.Inconclusive("The create operation completed before it could be canceled.");
            }
            catch (RequestFailedException e) when(e.Status == 409)
            {
                Assert.Inconclusive("There was a service timing issue when attempting to cancel the operation.");
            }

            if (operation.HasCompleted && !operation.Properties.CancellationRequested)
            {
                Assert.Inconclusive("The create operation completed before it could be canceled.");
            }

            Assert.AreEqual("The operation was canceled so no value is available.", ex?.Message);

            Assert.IsTrue(operation.HasCompleted);
            Assert.IsFalse(operation.HasValue);
            Assert.AreEqual(200, operation.GetRawResponse().Status);
        }
예제 #18
0
        protected async Task <CertificateWithPolicy> WaitForCompletion(CertificateOperation operation)
        {
            operation.PollingInterval = TimeSpan.FromSeconds((Mode == RecordedTestMode.Playback) ? 0 : 1);

            if (IsAsync)
            {
                await operation.WaitCompletionAsync();
            }
            else
            {
                while (!operation.HasValue)
                {
                    operation.UpdateStatus();

                    await Task.Delay(operation.PollingInterval);
                }
            }

            return(operation.Value);
        }
        public async Task VerifyCancelCertificateOperation()
        {
            string certName = Recording.GenerateId();

            CertificatePolicy certificatePolicy = DefaultPolicy;

            CertificateOperation operation = await Client.StartCreateCertificateAsync(certName, certificatePolicy);

            RegisterForCleanup(certName);

            // Give the service time to process the start request.
            await DelayAsync(TimeSpan.FromSeconds(2));

            OperationCanceledException ex = null;

            try
            {
                await operation.CancelAsync();

                await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);
            }
            catch (OperationCanceledException e)
            {
                ex = e;
            }
            catch (RequestFailedException e) when(e.Status == 403)
            {
                Assert.Inconclusive("The create operation completed before it could be canceled.");
            }

            if (operation.HasCompleted && !operation.Properties.CancellationRequested)
            {
                Assert.Inconclusive("The create operation completed before it could be canceled.");
            }

            Assert.AreEqual("The operation was canceled so no value is available.", ex?.Message);

            Assert.IsTrue(operation.HasCompleted);
            Assert.IsFalse(operation.HasValue);
            Assert.AreEqual(200, operation.GetRawResponse().Status);
        }
        public async Task VerifyCancelCertificateOperation()
        {
            string certName = Recording.GenerateId();

            CertificatePolicy certificatePolicy = DefaultPolicy;

            CertificateOperation operation = await Client.StartCreateCertificateAsync(certName, certificatePolicy);

            RegisterForCleanup(certName);

            try
            {
                await Client.CancelCertificateOperationAsync(certName);
            }
            catch (RequestFailedException ex) when(ex.Status == 403)
            {
                Assert.Inconclusive("The create operation completed before it could be canceled.");
            }

            Assert.ThrowsAsync <OperationCanceledException>(() => WaitForCompletion(operation));
        }
        public async Task VerifyGetCertificatePolicy()
        {
            string certName = Recording.GenerateId();

            CertificatePolicy certificatePolicy = DefaultPolicy;

            CertificateOperation operation = await Client.StartCreateCertificateAsync(certName, certificatePolicy);

            KeyVaultCertificateWithPolicy original = await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);

            Assert.NotNull(original);

            RegisterForCleanup(certName);

            CertificatePolicy policy = await Client.GetCertificatePolicyAsync(certName);

            Assert.NotNull(policy);
            Assert.AreEqual(DefaultPolicy.KeyType, policy.KeyType);
            Assert.AreEqual(DefaultPolicy.IssuerName, policy.IssuerName);
            Assert.AreEqual(DefaultPolicy.ReuseKey, policy.ReuseKey);
        }
        public async Task VerifyDeleteRecoverPurge()
        {
            string certName = Recording.GenerateId();

            CertificateOperation operation = await Client.StartCreateCertificateAsync(certName, DefaultPolicy);

            KeyVaultCertificateWithPolicy original = await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);

            Assert.NotNull(original);

            DeleteCertificateOperation deleteOperation = await Client.StartDeleteCertificateAsync(certName);

            DeletedCertificate deletedCert = deleteOperation.Value;

            Assert.IsNotNull(deletedCert);

            Assert.IsNotNull(deletedCert.RecoveryId);

            await WaitForDeletedCertificate(certName);

            _ = await Client.StartRecoverDeletedCertificateAsync(certName);

            Assert.NotNull(original);

            await PollForCertificate(certName);

            deleteOperation = await Client.StartDeleteCertificateAsync(certName);

            deletedCert = deleteOperation.Value;

            Assert.IsNotNull(deletedCert);

            Assert.IsNotNull(deletedCert.RecoveryId);

            await WaitForDeletedCertificate(certName);

            await Client.PurgeDeletedCertificateAsync(certName);

            await WaitForPurgedCertificate(certName);
        }
        public async Task VerifyDeleteCertificateOperation()
        {
            string certName = Recording.GenerateId();

            CertificatePolicy certificatePolicy = DefaultPolicy;

            certificatePolicy.IssuerName = WellKnownIssuerNames.Unknown;

            CertificateOperation operation = await Client.StartCreateCertificateAsync(certName, certificatePolicy);

            RegisterForCleanup(certName);

            await operation.DeleteAsync();

            InvalidOperationException ex = Assert.ThrowsAsync <InvalidOperationException>(() => WaitForCompletion(operation));

            Assert.AreEqual("The operation was deleted so no value is available.", ex.Message);

            Assert.IsTrue(operation.HasCompleted);
            Assert.IsFalse(operation.HasValue);
            Assert.AreEqual(404, operation.GetRawResponse().Status);
        }
예제 #24
0
        protected override void ProcessRecord()
        {
            CertificateOperation certificateOperation = null;

            ConfirmAction(
                Force.IsPresent,
                string.Format(
                    CultureInfo.InvariantCulture,
                    "Are you sure you want to stop certificate operation for '{0}'?",
                    Name),
                string.Format(
                    CultureInfo.InvariantCulture,
                    "Stop certificate operation for '{0}'",
                    Name),
                Name,
                () =>
            {
                certificateOperation       = this.DataServiceClient.CancelCertificateOperation(VaultName, Name);
                var kvCertificateOperation = KeyVaultCertificateOperation.FromCertificateOperation(certificateOperation);
                this.WriteObject(kvCertificateOperation);
            });
        }
예제 #25
0
        public async Task CreateClientAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            #region Snippet:CreateCertificateClient
            // Create a new certificate client using the default credential from Azure.Identity using environment variables previously set,
            // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
            var client = new CertificateClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());
            #endregion

            #region Snippet:CreateCertificate
            // Create a certificate. This starts a long running operation to create and sign the certificate.
            CertificateOperation operation = await client.StartCreateCertificateAsync("MyCertificate");

            // You can await the completion of the create certificate operation.
            CertificateWithPolicy certificate = await operation.WaitForCompletionAsync();

            #endregion

            this.client = client;
        }
예제 #26
0
        public async Task VerifyDeleteRecoverPurge()
        {
            string certName = Recording.GenerateId();

            CertificateOperation operation = await Client.StartCreateCertificateAsync(certName);

            CertificateWithPolicy original = await WaitForCompletion(operation);

            Assert.NotNull(original);

            DeletedCertificate deletedCert = await Client.DeleteCertificateAsync(certName);

            Assert.IsNotNull(deletedCert);

            Assert.IsNotNull(deletedCert.RecoveryId);

            await WaitForDeletedCertificate(certName);

            _ = await Client.RecoverDeletedCertificateAsync(certName);

            Assert.NotNull(original);

            await PollForCertificate(certName);

            deletedCert = await Client.DeleteCertificateAsync(certName);

            Assert.IsNotNull(deletedCert);

            Assert.IsNotNull(deletedCert.RecoveryId);

            await WaitForDeletedCertificate(certName);

            await Client.PurgeDeletedCertificateAsync(certName);

            await WaitForPurgedCertificate(certName);
        }
        public async Task VerifyCancelCertificateOperation()
        {
            // Log details why this fails often for live tests on net461.
            using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Verbose);

            string certName = Recording.GenerateId();

            CertificatePolicy certificatePolicy = DefaultPolicy;

            CertificateOperation operation = await Client.StartCreateCertificateAsync(certName, certificatePolicy);

            RegisterForCleanup(certName);

            try
            {
                await Client.CancelCertificateOperationAsync(certName);
            }
            catch (RequestFailedException ex) when(ex.Status == 403)
            {
                Assert.Inconclusive("The create operation completed before it could be canceled.");
            }

            Assert.ThrowsAsync <OperationCanceledException>(() => WaitForCompletion(operation));
        }
        public async Task VerifyGetCertificateCompleted()
        {
            string certName = Recording.GenerateId();

            CertificateOperation operation = await Client.StartCreateCertificateAsync(certName, DefaultPolicy);

            RegisterForCleanup(certName);

            await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);

            KeyVaultCertificateWithPolicy certificateWithPolicy = await Client.GetCertificateAsync(certName);

            Assert.NotNull(certificateWithPolicy);

            Assert.AreEqual(certificateWithPolicy.Name, certName);

            Assert.NotNull(certificateWithPolicy.Properties.Version);

            KeyVaultCertificate certificate = await Client.GetCertificateVersionAsync(certName, certificateWithPolicy.Properties.Version);

            Assert.NotNull(certificate);

            Assert.AreEqual(certificate.Name, certName);
        }
        public async Task VerifyGetCertificateCompletedSubsequently()
        {
            string certName = Recording.GenerateId();

            await Client.StartCreateCertificateAsync(certName, DefaultPolicy);

            RegisterForCleanup(certName);

            // Pretend a separate process was started subsequently and we need to get the operation again.
            CertificateOperation operation = new CertificateOperation(Client, certName);

            // Need to call the real async wait method or the sync version of this test fails because it's using the instrumented Client directly.
            using CancellationTokenSource cts = new CancellationTokenSource(DefaultCertificateOperationTimeout);
            await operation.WaitForCompletionAsync(PollingInterval, cts.Token);

            Assert.IsTrue(operation.HasCompleted);
            Assert.IsTrue(operation.HasValue);

            KeyVaultCertificateWithPolicy certificateWithPolicy = operation.Value;

            Assert.NotNull(certificateWithPolicy);
            Assert.AreEqual(certName, certificateWithPolicy.Name);
            Assert.NotNull(certificateWithPolicy.Properties.Version);
        }
 public CertificateOperationDeleter(CertificateOperation operation)
 {
     _operation = operation;
 }
 protected IAsyncDisposable EnsureDeleted(CertificateOperation operation) => new CertificateOperationDeleter(operation);