/// <summary>
        /// Deletes a certificate.
        /// </summary>
        public static void WaitForCertificateToFailDeletion(BatchController controller, BatchAccountContext context, string thumbprintAlgorithm, string thumbprint)
        {
            RequestInterceptor interceptor = CreateHttpRecordingInterceptor();

            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient           client    = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            ListCertificateOptions parameters = new ListCertificateOptions(context, behaviors)
            {
                ThumbprintAlgorithm = BatchTestHelpers.TestCertificateAlgorithm,
                Thumbprint          = thumbprint
            };

            PSCertificate cert = client.ListCertificates(parameters).First();

            DateTime timeout = DateTime.Now.AddMinutes(2);

            while (cert.State != CertificateState.DeleteFailed)
            {
                if (DateTime.Now > timeout)
                {
                    throw new TimeoutException("Timed out waiting for failed certificate deletion");
                }
                Sleep(10000);
                cert = client.ListCertificates(parameters).First();
            }
        }
        /// <summary>
        /// Adds a test certificate for use in Scenario tests. Returns the thumbprint of the cert.
        /// </summary>
        public static string AddTestCertificate(BatchController controller, BatchAccountContext context, string filePath)
        {
            RequestInterceptor interceptor = CreateHttpRecordingInterceptor();

            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient           client    = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            X509Certificate2       cert          = new X509Certificate2(filePath);
            ListCertificateOptions getParameters = new ListCertificateOptions(context, behaviors)
            {
                ThumbprintAlgorithm = BatchTestHelpers.TestCertificateAlgorithm,
                Thumbprint          = cert.Thumbprint,
                Select = "thumbprint,state"
            };

            try
            {
                PSCertificate existingCert = client.ListCertificates(getParameters).FirstOrDefault();
                DateTime      start        = DateTime.Now;
                DateTime      end          = start.AddMinutes(5);

                // Cert might still be deleting from other tests, so we wait for the delete to finish.
                while (existingCert != null && existingCert.State == CertificateState.Deleting)
                {
                    if (DateTime.Now > end)
                    {
                        throw new TimeoutException("Timed out waiting for existing cert to be deleted.");
                    }
                    Sleep(5000);
                    existingCert = client.ListCertificates(getParameters).FirstOrDefault();
                }
            }
            catch (AggregateException ex)
            {
                foreach (Exception inner in ex.InnerExceptions)
                {
                    BatchException batchEx = inner as BatchException;
                    // When the cert doesn't exist, we get a 404 error. For all other errors, throw.
                    if (batchEx == null || !batchEx.Message.Contains("CertificateNotFound"))
                    {
                        throw;
                    }
                }
            }

            NewCertificateParameters parameters = new NewCertificateParameters(context, null, cert.RawData, behaviors);

            client.AddCertificate(parameters);

            return(cert.Thumbprint);
        }
        /// <summary>
        /// Adds a test certificate for use in Scenario tests. Returns the thumbprint of the cert.
        /// </summary>
        public static string AddTestCertificate(BatchController controller, BatchAccountContext context, string filePath)
        {
            BatchClient client = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            X509Certificate2       cert          = new X509Certificate2(filePath);
            ListCertificateOptions getParameters = new ListCertificateOptions(context)
            {
                ThumbprintAlgorithm = BatchTestHelpers.TestCertificateAlgorithm,
                Thumbprint          = cert.Thumbprint,
                Select = "thumbprint,state"
            };

            try
            {
                PSCertificate existingCert = client.ListCertificates(getParameters).FirstOrDefault();
                DateTime      start        = DateTime.Now;
                TimeSpan      timeout      = GetTimeout(TimeSpan.FromMinutes(5));
                DateTime      end          = start.Add(timeout);

                // Cert might still be deleting from other tests, so we wait for the delete to finish.
                while (existingCert != null && existingCert.State == CertificateState.Deleting)
                {
                    if (DateTime.Now > end)
                    {
                        throw new TimeoutException("Timed out waiting for existing cert to be deleted.");
                    }
                    Sleep(5000);
                    existingCert = client.ListCertificates(getParameters).FirstOrDefault();
                }
            }
            catch (BatchException ex)
            {
                // When the cert doesn't exist, we get a 404 error. For all other errors, throw.
                if (ex == null || !ex.Message.Contains("NotFound"))
                {
                    throw;
                }
            }

            NewCertificateParameters parameters = new NewCertificateParameters(
                context, null, cert.RawData, PSCertificateKind.Cer);

            client.AddCertificate(parameters);

            return(cert.Thumbprint);
        }
Exemple #4
0
        public override void ExecuteCmdlet()
        {
            if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(WebAppName))
            {
                string         certName   = null;
                HttpStatusCode statusCode = HttpStatusCode.OK;
                var            webApp     = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, Slot));
                var            location   = webApp.Location;

                var certificate = new Certificate(
                    webApp.Location,
                    type: "Microsoft.Web/certificates",
                    canonicalName: HostName,
                    password: "",
                    serverFarmId: webApp.ServerFarmId);

                PSCertificate createdCertdetails = new PSCertificate(certificate);

                if (this.ShouldProcess(this.WebAppName, string.Format($"Creating an App service managed certificate for Web App '{WebAppName}'")))
                {
                    try
                    {
                        //Default certName is HostName
                        certName           = Name != null ? Name : HostName;
                        createdCertdetails = new PSCertificate(WebsitesClient.CreateCertificate(ResourceGroupName, certName, certificate));
                    }
                    catch (DefaultErrorResponseException e)
                    {
                        statusCode = e.Response.StatusCode;
                        // 'Conflict' exception is thrown when certificate already exists. Let's swallow it and continue.
                        //'Accepted' exception is thrown by default for create cert method.
                        if (e.Response.StatusCode != HttpStatusCode.Conflict &&
                            e.Response.StatusCode != HttpStatusCode.Accepted)
                        {
                            throw;
                        }
                        if (e.Response.StatusCode == HttpStatusCode.Accepted)
                        {
                            var        poll_url = e.Response.Headers["Location"].FirstOrDefault();
                            var        token    = WebsitesClient.GetAccessToken(DefaultContext);
                            HttpClient client   = new HttpClient();
                            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token.AccessToken);

                            HttpResponseMessage r;
                            int numChecks = 0;
                            do
                            {
                                Thread.Sleep(TimeSpan.FromSeconds(5));
                                r = client.GetAsync(poll_url).Result;
                                numChecks++;
                            } while (r.StatusCode == HttpStatusCode.Accepted && numChecks < NumStatusChecks);

                            if (r.StatusCode == HttpStatusCode.Accepted && numChecks >= NumStatusChecks)
                            {
                                var rec = new ErrorRecord(new Exception(string.Format($"The creation of the managed certificate '{this.HostName}' is taking longer than expected." +
                                                                                      $" Please re-try the operation '{CreateInputCommand()}'")),
                                                          string.Empty, ErrorCategory.OperationTimeout, null);
                                WriteError(rec);
                            }
                        }
                    }
                    createdCertdetails = new PSCertificate(WebsitesClient.GetCertificate(ResourceGroupName, certName));

                    //Add only when user is opted for Binding
                    if (AddBinding)
                    {
                        WebsitesClient.UpdateHostNameSslState(ResourceGroupName,
                                                              WebAppName,
                                                              Slot,
                                                              webApp.Location,
                                                              HostName, SslState.HasValue ? SslState.Value : Management.WebSites.Models.SslState.SniEnabled,
                                                              createdCertdetails.Thumbprint);
                    }
                    WriteObject(createdCertdetails);
                }
            }
        }