Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
sjkp committed Feb 10, 2019
1 parent 6f89f87 commit 7e51e56
Show file tree
Hide file tree
Showing 8 changed files with 112 additions and 20 deletions.
19 changes: 19 additions & 0 deletions LetsEncrypt.Azure.DotNetCore.sln
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
Dockerfile = Dockerfile
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LetsEncrypt.Azure.FunctionV2", "examples\LetsEncrypt.Azure.FunctionV2\LetsEncrypt.Azure.FunctionV2.csproj", "{FF8A14C9-8AC7-4057-A2EC-BA31C3965079}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{33597FE6-D5E9-4F8E-9009-294BFC3D5F9A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -62,10 +66,25 @@ Global
{6C89066E-0418-4303-809D-9F3F9BBB1013}.Release|x64.Build.0 = Release|Any CPU
{6C89066E-0418-4303-809D-9F3F9BBB1013}.Release|x86.ActiveCfg = Release|Any CPU
{6C89066E-0418-4303-809D-9F3F9BBB1013}.Release|x86.Build.0 = Release|Any CPU
{FF8A14C9-8AC7-4057-A2EC-BA31C3965079}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FF8A14C9-8AC7-4057-A2EC-BA31C3965079}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FF8A14C9-8AC7-4057-A2EC-BA31C3965079}.Debug|x64.ActiveCfg = Debug|Any CPU
{FF8A14C9-8AC7-4057-A2EC-BA31C3965079}.Debug|x64.Build.0 = Debug|Any CPU
{FF8A14C9-8AC7-4057-A2EC-BA31C3965079}.Debug|x86.ActiveCfg = Debug|Any CPU
{FF8A14C9-8AC7-4057-A2EC-BA31C3965079}.Debug|x86.Build.0 = Debug|Any CPU
{FF8A14C9-8AC7-4057-A2EC-BA31C3965079}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FF8A14C9-8AC7-4057-A2EC-BA31C3965079}.Release|Any CPU.Build.0 = Release|Any CPU
{FF8A14C9-8AC7-4057-A2EC-BA31C3965079}.Release|x64.ActiveCfg = Release|Any CPU
{FF8A14C9-8AC7-4057-A2EC-BA31C3965079}.Release|x64.Build.0 = Release|Any CPU
{FF8A14C9-8AC7-4057-A2EC-BA31C3965079}.Release|x86.ActiveCfg = Release|Any CPU
{FF8A14C9-8AC7-4057-A2EC-BA31C3965079}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{FF8A14C9-8AC7-4057-A2EC-BA31C3965079} = {33597FE6-D5E9-4F8E-9009-294BFC3D5F9A}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5AC649FA-BB48-4484-993B-2BBCFC05742D}
EndGlobalSection
Expand Down
66 changes: 62 additions & 4 deletions LetsEncrypt.SiteExtension.Core/ArmHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
using Microsoft.Rest;
using Polly;
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

Expand All @@ -16,11 +18,11 @@ namespace LetsEncrypt.Azure.Core
public static class ArmHelper
{
public static async Task<WebSiteManagementClient> GetWebSiteManagementClient(IAzureWebAppEnvironment model)
{
{
AuthenticationResult token = await GetToken(model);
var creds = new TokenCredentials(token.AccessToken);

var websiteClient = new WebSiteManagementClient(model.ManagementEndpoint, creds);
var websiteClient = new WebSiteManagementClient(model.ManagementEndpoint, creds, new TraceLoggingHandler());
websiteClient.SubscriptionId = model.SubscriptionId.ToString();
return websiteClient;
}
Expand All @@ -44,7 +46,7 @@ private static async Task<AuthenticationResult> GetToken(IAzureEnvironment model
}

public static async Task<HttpClient> GetHttpClient(IAzureWebAppEnvironment model)
{
{
AuthenticationResult token = await GetToken(model);

var client = HttpClientFactory.Create(new HttpClientHandler(), new TimeoutHandler());
Expand All @@ -60,7 +62,7 @@ public static Polly.Retry.RetryPolicy<HttpResponseMessage> ExponentialBackoff(in
.HandleResult<HttpResponseMessage>((resp) =>
{
return IsTransient(resp.StatusCode);
})
.WaitAndRetryAsync(retryCount, retryAttempt =>
TimeSpan.FromSeconds(Math.Pow(firstBackOffDelay, retryAttempt))
Expand Down Expand Up @@ -103,4 +105,60 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
}
}
}

public abstract class MessageHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var corrId = string.Format("{0}{1}", DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId);
var requestInfo = string.Format("{0} {1}, headers {2}", request.Method, request.RequestUri, string.Join(",", request.Headers
.Where(s => !string.Equals(s.Key, "Authorization", StringComparison.InvariantCultureIgnoreCase))
.Select(s => $"{s.Key} = {string.Join("|", s.Value)}")
));

byte[] requestMessage = null;
if (request.Content != null)
{
requestMessage = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(continueOnCapturedContext: false);
}

LogIncommingMessage(corrId, requestInfo, requestMessage);

var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);

byte[] responseMessage = null;
if (response.Content != null)
{
responseMessage = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(continueOnCapturedContext: false);
}

LogOutgoingMessage(corrId, requestInfo, responseMessage);

return response;
}


protected abstract void LogIncommingMessage(string correlationId, string requestInfo, byte[] message);
protected abstract void LogOutgoingMessage(string correlationId, string requestInfo, byte[] message);
}



public class TraceLoggingHandler : MessageHandler
{

public TraceLoggingHandler()
{
}
protected override void LogIncommingMessage(string correlationId, string requestInfo, byte[] message)
{
Trace.TraceInformation(string.Format("{0} - Request: {1}\r\n{2}", correlationId, requestInfo, message != null ? Encoding.UTF8.GetString(message) : String.Empty));
}


protected override void LogOutgoingMessage(string correlationId, string requestInfo, byte[] message)
{
Trace.TraceInformation(string.Format("{0} - Response: {1}\r\n{2}", correlationId, requestInfo, message != null ? Encoding.UTF8.GetString(message) : String.Empty));
}
}
}
20 changes: 15 additions & 5 deletions LetsEncrypt.SiteExtension.Core/KuduHelper.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
using LetsEncrypt.Azure.Core.Models;
using Microsoft.Azure.Management.WebSites;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LetsEncrypt.Azure.Core
{
Expand All @@ -13,8 +9,22 @@ public static class KuduHelper
public static KuduRestClient GetKuduClient(this WebSiteManagementClient client, IAzureWebAppEnvironment settings)
{
var user = client.WebApps.GetPublsihingCredentialSiteOrSlot(settings.ResourceGroupName, settings.WebAppName, settings.SiteSlotName);
var site = client.WebApps.GetSiteOrSlot(settings.ResourceGroupName, settings.WebAppName, settings.SiteSlotName);
var defaultHostName = site.DefaultHostName;

return new KuduRestClient(settings, user.PublishingUserName, user.PublishingPassword);
return new KuduRestClient(MakeScmUri(defaultHostName,settings), user.PublishingUserName, user.PublishingPassword);
}

/// <summary>
/// TODO; should also work for APP service environment, which uses a different format for scm site uri https://blogs.msdn.microsoft.com/benjaminperkins/2017/11/08/how-to-access-kudu-scm-for-an-azure-app-service-environment-ase/
/// </summary>
/// <param name="defaultHostName"></param>
/// <param name="settings"></param>
/// <returns></returns>
public static Uri MakeScmUri(string defaultHostName, IAzureWebAppEnvironment settings)
{
var i = defaultHostName.IndexOf("." + settings.AzureWebSitesDefaultDomainName);
return new Uri($"https://{defaultHostName.Insert(i, ".scm")}");
}
}
}
12 changes: 4 additions & 8 deletions LetsEncrypt.SiteExtension.Core/KuduRestClient.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using LetsEncrypt.Azure.Core.Models;
using Newtonsoft.Json;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
Expand All @@ -14,17 +13,14 @@ public class KuduRestClient
private readonly string baseUri;
private HttpClient client;
private string publishingPassword;
private string publishingUserName;
private string webAppName;
private string publishingUserName;

public KuduRestClient(IAzureWebAppEnvironment azureEnvironment, string publishingUserName, string publishingPassword)
public KuduRestClient(Uri scmUri, string publishingUserName, string publishingPassword)
{
this.webAppName = string.IsNullOrEmpty(azureEnvironment.SiteSlotName) ? azureEnvironment.WebAppName : azureEnvironment.WebAppName + "-" + azureEnvironment.SiteSlotName;
this.publishingUserName = publishingUserName;
this.publishingPassword = publishingPassword;
this.baseUri = $"https://{this.webAppName}.scm.{azureEnvironment.AzureWebSitesDefaultDomainName}";
this.client = new HttpClient();
client.BaseAddress = new System.Uri(baseUri);
client.BaseAddress = scmUri;
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", CreateToken());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<metadata>
<id>letsencrypt.azure.core</id>
<title>Azure Let's Encrypt</title>
<version>0.9.0</version>
<version>0.9.3</version>
<authors>SJKP</authors>
<licenseUrl>http://opensource.org/licenses/Apache-2.0</licenseUrl>
<projectUrl>https://github.com/sjkp/letsencrypt-siteextension</projectUrl>
Expand Down
9 changes: 9 additions & 0 deletions LetsEncrypt.SiteExtension.Test/PublishingCrendentialsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,14 @@ public async Task GetPublishingCredentials()
}

}

[TestMethod]
public void TestScmUri()
{
var model = new AppSettingsAuthConfig();
var uri = "letsencrypt.azurewebsites.net";
var result = KuduHelper.MakeScmUri(uri, model);
Assert.AreEqual(new Uri("https://letsencrypt.scm.azurewebsites.net"), result);
}
}
}
2 changes: 1 addition & 1 deletion LetsEncrypt.WebAppOnly.nuspec
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<metadata>
<id>letsencrypt.webapponly</id>
<title>Azure Let's Encrypt (No Web Jobs)</title>
<version>0.9.2</version>
<version>0.9.3</version>
<authors>SJKP</authors>
<licenseUrl>http://opensource.org/licenses/Apache-2.0</licenseUrl>
<projectUrl>https://github.com/sjkp/letsencrypt-siteextension</projectUrl>
Expand Down
2 changes: 1 addition & 1 deletion LetsEncrypt.nuspec
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<metadata>
<id>letsencrypt</id>
<title>Azure Let's Encrypt</title>
<version>0.9.2</version>
<version>0.9.3</version>
<authors>SJKP</authors>
<licenseUrl>http://opensource.org/licenses/Apache-2.0</licenseUrl>
<projectUrl>https://github.com/sjkp/letsencrypt-siteextension</projectUrl>
Expand Down

0 comments on commit 7e51e56

Please sign in to comment.