Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#10518-webapp: Support the new appservice Managed certificates #13441

Merged
merged 16 commits into from
Jan 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions src/Websites/Websites.Test/ScenarioTests/CertificatesTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.ServiceManagement.Common.Models;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
using Xunit;
using Xunit.Abstractions;

namespace Microsoft.Azure.Commands.Websites.Test.ScenarioTests
{
public class CertificatesTests : RMTestBase
{
public XunitTracingInterceptor _logger;
public CertificatesTests(ITestOutputHelper output)
{
_logger = new XunitTracingInterceptor(output);
XunitTracingInterceptor.AddToContext(_logger);
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestNewAzWebAppCertificate()
{
WebsitesController.NewInstance.RunPsTest(_logger, "Test-NewAzWebAppCertificate");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestNewAzWebAppCertificateWithSSLBinding()
{
WebsitesController.NewInstance.RunPsTest(_logger, "Test-NewAzWebAppCertificateWithSSLBinding");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestNewAzWebAppCertificateForSlot()
{
WebsitesController.NewInstance.RunPsTest(_logger, "Test-NewAzWebAppCertificateForSlot");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestRemoveAzWebAppCertificate()
{
WebsitesController.NewInstance.RunPsTest(_logger, "Test-RemoveAzWebAppCertificate");
}
}
}
142 changes: 142 additions & 0 deletions src/Websites/Websites.Test/ScenarioTests/CertificatesTests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------

<#
.SYNOPSIS
Tests creating a new managed cert for app.
#>
function Test-NewAzWebAppCertificate
{
$rgname = "lketmtestantps10"
$appname = "lketmtestantps10"
$certName = "adorenowcert"
$prodHostname = "www.adorenow.net"
$thumbprint=""

try{

$cert=New-AzWebAppCertificate -ResourceGroupName $rgname -Name $certName -WebAppName $appname -HostName $prodHostname
$thumbprint=$cert.ThumbPrint

# Assert
Assert-AreEqual $prodHostname $cert.SubjectName

}
finally{

# Cleanup
Remove-AzWebAppCertificate -ResourceGroupName $rgname -ThumbPrint $thumbprint
}
}

<#
.SYNOPSIS
Tests creating a new managed cert for app with SSL binding.
#>
function Test-NewAzWebAppCertificateWithSSLBinding
{
$rgname = "lketmtestantps10"
$appname = "lketmtestantps10"
$prodHostname = "www.adorenow.net"
$certName = "adorenowcert"
$thumbprint=""

try{

$cert=New-AzWebAppCertificate -ResourceGroupName $rgname -Name $certName -WebAppName $appname -HostName $prodHostname -AddBinding
$thumbprint=$cert.ThumbPrint

# Assert
Assert-AreEqual $prodHostname $cert.SubjectName

#Assert
$getResult = Get-AzWebAppSSLBinding -ResourceGroupName $rgname -WebAppName $appname
Assert-AreEqual 1 $getResult.Count
$currentHostNames = $getResult | Select -expand Name
Assert-True { $currentHostNames -contains $prodHostname }
$getResult = Get-AzWebAppSSLBinding -ResourceGroupName $rgname -WebAppName $appname -Name $prodHostname
Assert-AreEqual $getResult.Name $prodHostname

}
finally{

# Cleanup
Remove-AzWebAppSSLBinding -ResourceGroupName $rgname -WebAppName $appname -Name $prodHostname -Force
Remove-AzWebAppCertificate -ResourceGroupName $rgname -ThumbPrint $thumbprint
}
}

<#
.SYNOPSIS
Tests creating a new managed certfor slot.
#>
function Test-NewAzWebAppCertificateForSlot
{

$rgname = "lketmtestantps10"
$appname = "lketmtestantps10"
$slot = "testslot"
$slotHostname = "testslot.adorenow.net"
$certName = "adorenowcert"
$thumbprint=""

try{

$cert=New-AzWebAppCertificate -ResourceGroupName $rgname -Name $certName -WebAppName $appname -HostName $slotHostname -Slot $slot
$thumbprint=$cert.ThumbPrint

# Assert
Assert-AreEqual $slotHostname $cert.SubjectName

}
finally{

# Cleanup
Remove-AzWebAppCertificate -ResourceGroupName $rgname -ThumbPrint $thumbprint
}
}

<#
.SYNOPSIS
Tests removing a managed cert.
#>
function Test-RemoveAzWebAppCertificate
{

$rgname = "lketmtestantps10"
$appname = "lketmtestantps10"
$prodHostname = "www.adorenow.net"
$certName = "adorenowcert"
$thumbprint=""

try{

$cert=New-AzWebAppCertificate -ResourceGroupName $rgname -Name $certName -WebAppName $appname -HostName $prodHostname
$thumbprint=$cert.ThumbPrint

# Assert
Assert-AreEqual $prodHostname $cert.SubjectName

Remove-AzWebAppCertificate -ResourceGroupName $rgname -ThumbPrint $thumbprint

$certificate = Get-AzWebAppCertificate -Thumbprint $thumbprint

#Assert
$certificate.count -eq 0

}
finally{

}
}

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion src/Websites/Websites/Az.Websites.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ CmdletsToExport = 'Get-AzAppServicePlan', 'Set-AzAppServicePlan',
'Remove-AzWebAppAccessRestrictionRule',
'Update-AzWebAppAccessRestrictionConfig',
'Add-AzWebAppTrafficRouting', 'Remove-AzWebAppTrafficRouting',
'Get-AzWebAppTrafficRouting', 'Update-AzWebAppTrafficRouting'
'Get-AzWebAppTrafficRouting', 'Update-AzWebAppTrafficRouting',
'New-AzWebAppCertificate','Remove-AzWebAppCertificate'

# Variables to export from this module
# VariablesToExport = @()
Expand Down
6 changes: 5 additions & 1 deletion src/Websites/Websites/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@
- Additional information about change #1
-->
## Upcoming Release

* Added support for App Service Managed certificates
- New Cmdlets
- New-AzWebAppCertificate
- Remove-AzWebAppCertificate

## Version 2.1.1
* Prevent duplicate access restriction rules

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------


using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Commands.WebApps.Models;
using Microsoft.Azure.Commands.WebApps.Models.WebApp;
using Microsoft.Azure.Commands.WebApps.Utilities;
using Microsoft.Azure.Management.WebSites.Models;
using System;
using System.Linq;
using System.Management.Automation;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;

namespace Microsoft.Azure.Commands.WebApps.Cmdlets.Certificates
{

/// <summary>
/// This commandlet will let you create a new managed certificate
/// </summary>
[Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "WebAppCertificate", SupportsShouldProcess = true), OutputType(typeof(PSCertificate))]
public class NewAzureWebAppCertificate : WebAppBaseClientCmdLet
panchagnula marked this conversation as resolved.
Show resolved Hide resolved
{
// Poll status for a maximum of 6 minutes (360 seconds / 2 seconds per status check)
private const int NumStatusChecks = 72;
const string CertNamePostFixSeparator = "_";
const string ParameterSet1Name = "S1";

[Parameter(ParameterSetName = ParameterSet1Name, Position = 0, Mandatory = true, HelpMessage = "The name of the resource group.")]
[ResourceGroupCompleter]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }

[Parameter(ParameterSetName = ParameterSet1Name, Position = 1, Mandatory = true, HelpMessage = "The name of the web app.")]
[ResourceNameCompleter("Microsoft.Web/sites", "ResourceGroupName")]
[ValidateNotNullOrEmpty]
public string WebAppName { get; set; }

[Parameter(ParameterSetName = ParameterSet1Name, Mandatory = false, HelpMessage = "The name of the certificate")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }

[Parameter(ParameterSetName = ParameterSet1Name, Position = 2, Mandatory = false, HelpMessage = "The name of the web app slot.")]
[ResourceNameCompleter("Microsoft.Web/sites/slots", "ResourceGroupName", "WebAppName")]
[ValidateNotNullOrEmpty]
public string Slot { get; set; }

[Parameter(ParameterSetName = ParameterSet1Name, Position = 3, Mandatory = true, HelpMessage = "Custom hostnames associated with web app/slot.")]
[ValidateNotNullOrEmpty]
public string HostName { get; set; }

[Parameter(ParameterSetName = ParameterSet1Name, Mandatory = false, HelpMessage = "To add the created certificate to WebApp/slot.")]
[ValidateNotNullOrEmpty]
public SwitchParameter AddBinding { get; set; }

[Parameter(ParameterSetName = ParameterSet1Name, Mandatory = false, HelpMessage = "Ssl state option. Use either 'SniEnabled' or 'IpBasedEnabled'. Default option is 'SniEnabled'.")]
[ValidateNotNullOrEmpty]
public SslState? SslState { get; set; }

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;

Certificate createdCertdetails = new Certificate();

var certificate = new Certificate(
panchagnula marked this conversation as resolved.
Show resolved Hide resolved
webApp.Location,
type: "Microsoft.Web/certificates",
canonicalName: HostName,
password: "",
serverFarmId: webApp.ServerFarmId);
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 = (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 = 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);
}

}

}
private string CreateInputCommand()
{
StringBuilder command = new StringBuilder("New-AzWebAppCertificate ");
command.Append($"-ResourceGroupName {this.ResourceGroupName} -WebAppName {this.WebAppName} -HostName {this.HostName} ");
if (Slot != null)
command.Append($"-Slot {this.Slot} ");
if (AddBinding)
command.Append($"-AddBinding ");
if (SslState != null)
command.Append($"-SslState {this.SslState} ");
return command.ToString(); ;
}
}
}
Loading