-
Notifications
You must be signed in to change notification settings - Fork 10.5k
[Templates] Diagnostics improvements and certificate fixes #21493
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
5647330
Move template specific helpers out of shared and into templates
javiercn 73a535b
More debug info, fix casing issues
javiercn b1b6fed
Keep test skipped
javiercn 6558f4e
Undo lock changes
javiercn 5170f8e
Standarize retry logic
javiercn a8a9593
Tweak certificate validation code
javiercn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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; | ||
|
|
@@ -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; } | ||
|
|
@@ -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"; | ||
|
|
@@ -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); | ||
|
|
@@ -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}"); | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -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); | ||
| } | ||
|
|
||
|
|
@@ -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); | ||
|
|
||
| Assert.Equal(HttpStatusCode.OK, response.StatusCode); | ||
| var parser = new HtmlParser(); | ||
|
|
@@ -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!"); | ||
|
|
@@ -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..."); | ||
|
|
@@ -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)}"); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 |
||
| } | ||
|
|
||
| private bool IsSuccessStatusCode(HttpResponseMessage response) | ||
|
|
@@ -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); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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)); | ||
|
|
@@ -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}'."); | ||
| } | ||
|
|
||
|
|
||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.