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

[Templates] Diagnostics improvements and certificate fixes #21493

Merged
merged 6 commits into from
May 6, 2020
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
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<!-- Shared testing infrastructure for running E2E tests using selenium -->
<Import Project="$(SharedSourceRoot)E2ETesting\E2ETesting.props" />
Expand Down Expand Up @@ -28,6 +28,7 @@
<ItemGroup>
<EmbeddedResource Include="template-baselines.json" />
<Compile Include="$(SharedSourceRoot)Process\*.cs" LinkBase="shared\Process" />
<Compile Include="..\Shared\**" LinkBase="Helpers" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Threading.Tasks;
using AngleSharp.Dom.Html;
using AngleSharp.Parser.Html;
Expand All @@ -33,6 +34,7 @@ public class AspNetProcess : IDisposable

private string _certificatePath;
private string _certificatePassword = Guid.NewGuid().ToString();
private string _certificateThumbprint;

internal readonly Uri ListeningUri;
internal ProcessEx Process { get; }
Expand All @@ -46,22 +48,21 @@ public AspNetProcess(
bool hasListeningUri = true,
ILogger logger = null)
{
_certificatePath = Path.Combine(workingDirectory, $"{Guid.NewGuid()}.pfx");
EnsureDevelopmentCertificates();

_output = output;
_httpClient = new HttpClient(new HttpClientHandler()
{
AllowAutoRedirect = true,
UseCookies = true,
CookieContainer = new CookieContainer(),
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
ServerCertificateCustomValidationCallback = (request, certificate, chain, errors) => (certificate.Subject != "CN=localhost" && errors == SslPolicyErrors.None) || certificate?.Thumbprint == _certificateThumbprint,
})
{
Timeout = TimeSpan.FromMinutes(2)
};

_certificatePath = Path.Combine(workingDirectory, $"{Guid.NewGuid()}.pfx");

EnsureDevelopmentCertificates();

output.WriteLine("Running ASP.NET application...");

var arguments = published ? $"exec {dllPath}" : "run";
Expand All @@ -70,8 +71,8 @@ public AspNetProcess(

var finalEnvironmentVariables = new Dictionary<string, string>(environmentVariables)
{
["ASPNETCORE_KESTREL__CERTIFICATES__DEFAULT__PATH"] = _certificatePath,
["ASPNETCORE_KESTREL__CERTIFICATES__DEFAULT__PASSWORD"] = _certificatePassword
["ASPNETCORE_Kestrel__Certificates__Default__Path"] = _certificatePath,
["ASPNETCORE_Kestrel__Certificates__Default__Password"] = _certificatePassword
};

Process = ProcessEx.Run(output, workingDirectory, DotNetMuxer.MuxerPathOrDefault(), arguments, envVars: finalEnvironmentVariables);
Expand All @@ -81,8 +82,8 @@ public AspNetProcess(
if (hasListeningUri)
{
logger?.LogInformation("AspNetProcess - Getting listening uri");
ListeningUri = GetListeningUri(output) ?? throw new InvalidOperationException("Couldn't find the listening URL.");
logger?.LogInformation($"AspNetProcess - Got {ListeningUri.ToString()}");
ListeningUri = ResolveListeningUrl(output);
logger?.LogInformation($"AspNetProcess - Got {ListeningUri}");
}
}

Expand All @@ -91,6 +92,7 @@ internal void EnsureDevelopmentCertificates()
var now = DateTimeOffset.Now;
var manager = CertificateManager.Instance;
var certificate = manager.CreateAspNetCoreHttpsDevelopmentCertificate(now, now.AddYears(1));
_certificateThumbprint = certificate.Thumbprint;
manager.ExportCertificate(certificate, path: _certificatePath, includePrivateKey: true, _certificatePassword);
}

Expand Down Expand Up @@ -134,13 +136,13 @@ public async Task AssertPagesOk(IEnumerable<Page> pages)

public async Task ContainsLinks(Page page)
{
var response = await RequestWithRetries(client =>
var response = await RetryHelper.RetryRequest(async () =>
{
var request = new HttpRequestMessage(
HttpMethod.Get,
new Uri(ListeningUri, page.Url));
return client.SendAsync(request);
}, _httpClient);
return await _httpClient.SendAsync(request);
}, logger: NullLogger.Instance);
javiercn marked this conversation as resolved.
Show resolved Hide resolved

Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var parser = new HtmlParser();
Expand Down Expand Up @@ -173,7 +175,7 @@ public async Task ContainsLinks(Page page)
Assert.True(string.Equals(anchor.Href, expectedLink), $"Expected next link to be {expectedLink} but it was {anchor.Href}.");
var result = await RetryHelper.RetryRequest(async () =>
{
return await RequestWithRetries(client => client.GetAsync(anchor.Href), _httpClient);
return await _httpClient.GetAsync(anchor.Href);
}, logger: NullLogger.Instance);

Assert.True(IsSuccessStatusCode(result), $"{anchor.Href} is a broken link!");
Expand Down Expand Up @@ -203,7 +205,7 @@ private async Task<T> RequestWithRetries<T>(Func<HttpClient, Task<T>> requester,
throw new InvalidOperationException("Max retries reached.");
}

private Uri GetListeningUri(ITestOutputHelper output)
private Uri ResolveListeningUrl(ITestOutputHelper output)
{
// Wait until the app is accepting HTTP requests
output.WriteLine("Waiting until ASP.NET application is accepting connections...");
Expand Down Expand Up @@ -232,21 +234,27 @@ private Uri GetListeningUri(ITestOutputHelper output)

private string GetListeningMessage()
{
var buffer = new List<string>();
try
{
return Process
// This will timeout at most after 5 minutes.
.OutputLinesAsEnumerable
.Where(line => line != null)
// This used to do StartsWith, but this is less strict and can prevent issues (very rare) where
// console logging interleaves with other console output in a bad way. For example:
// dbugNow listening on: http://127.0.0.1:12857
.FirstOrDefault(line => line.Trim().Contains(ListeningMessagePrefix, StringComparison.Ordinal));
foreach (var line in Process.OutputLinesAsEnumerable)
{
if (line != null)
{
buffer.Add(line);
if (line.Trim().Contains(ListeningMessagePrefix, StringComparison.Ordinal))
{
return line;
}
}
}
}
catch (OperationCanceledException)
{
return null;
}

throw new InvalidOperationException(@$"Couldn't find listening url:
{string.Join(Environment.NewLine, buffer)}");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

}

private bool IsSuccessStatusCode(HttpResponseMessage response)
Expand All @@ -260,14 +268,13 @@ public Task AssertOk(string requestUrl)
public Task AssertNotFound(string requestUrl)
=> AssertStatusCode(requestUrl, HttpStatusCode.NotFound);

internal Task<HttpResponseMessage> SendRequest(string path)
{
return RequestWithRetries(client => client.GetAsync(new Uri(ListeningUri, path)), _httpClient);
}
internal Task<HttpResponseMessage> SendRequest(string path) =>
RetryHelper.RetryRequest(() => _httpClient.GetAsync(new Uri(ListeningUri, path)), logger: NullLogger.Instance);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another question about hiding details here…


public async Task AssertStatusCode(string requestUrl, HttpStatusCode statusCode, string acceptContentType = null)
{
var response = await RequestWithRetries(client => {
var response = await RetryHelper.RetryRequest(() =>
{
var request = new HttpRequestMessage(
HttpMethod.Get,
new Uri(ListeningUri, requestUrl));
Expand All @@ -277,8 +284,9 @@ public async Task AssertStatusCode(string requestUrl, HttpStatusCode statusCode,
request.Headers.Add("Accept", acceptContentType);
}

return client.SendAsync(request);
}, _httpClient);
return _httpClient.SendAsync(request);
}, logger: NullLogger.Instance);
javiercn marked this conversation as resolved.
Show resolved Hide resolved

Assert.True(statusCode == response.StatusCode, $"Expected {requestUrl} to have status '{statusCode}' but it was '{response.StatusCode}'.");
}

Expand Down
3 changes: 2 additions & 1 deletion src/ProjectTemplates/test/ProjectTemplates.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<!-- Shared testing infrastructure for running E2E tests using selenium -->
<Import Project="$(SharedSourceRoot)E2ETesting\E2ETesting.props" />
Expand Down Expand Up @@ -28,6 +28,7 @@
<EmbeddedResource Include="template-baselines.json" />
<Compile Include="$(SharedSourceRoot)Process\*.cs" LinkBase="shared\Process" />
<Compile Include="$(SharedSourceRoot)test\SkipOnHelixAttribute.cs" />
<Compile Include="..\Shared\**" LinkBase="Helpers" />
</ItemGroup>

<ItemGroup>
Expand Down