diff --git a/GVFS/GVFS.Common/Git/GitAuthentication.cs b/GVFS/GVFS.Common/Git/GitAuthentication.cs index c24db5728..dbb67f1a8 100644 --- a/GVFS/GVFS.Common/Git/GitAuthentication.cs +++ b/GVFS/GVFS.Common/Git/GitAuthentication.cs @@ -329,6 +329,7 @@ internal bool TryInitializeAndRequireAuth(ITracer tracer, out string errorMessag throw new InvalidOperationException("Already initialized"); } + this.IsAnonymous = false; if (this.TryCallGitCredential(tracer, out errorMessage)) { this.MarkInitialized(); diff --git a/GVFS/GVFS.Common/Http/HttpRequestor.cs b/GVFS/GVFS.Common/Http/HttpRequestor.cs index 0f9b66aa8..005a2386e 100644 --- a/GVFS/GVFS.Common/Http/HttpRequestor.cs +++ b/GVFS/GVFS.Common/Http/HttpRequestor.cs @@ -38,6 +38,11 @@ static HttpRequestor() } protected HttpRequestor(ITracer tracer, RetryConfig retryConfig, Enlistment enlistment) + : this(tracer, retryConfig, enlistment, handlerOverride: null) + { + } + + internal HttpRequestor(ITracer tracer, RetryConfig retryConfig, Enlistment enlistment, HttpMessageHandler handlerOverride) { this.RetryConfig = retryConfig; @@ -61,14 +66,19 @@ protected HttpRequestor(ITracer tracer, RetryConfig retryConfig, Enlistment enli // GVFS cache servers and Azure DevOps accept PAT/OAuth tokens via the // "Authorization: Basic " header that SendRequest already attaches. // Transport-level credentials are redundant and purely wasteful. - SocketsHttpHandler handler = new SocketsHttpHandler() + HttpMessageHandler handler = handlerOverride; + if (handler == null) { - MaxConnectionsPerServer = Environment.ProcessorCount, - PooledConnectionLifetime = Timeout.InfiniteTimeSpan, - PooledConnectionIdleTimeout = TimeSpan.FromMinutes(5), - }; + SocketsHttpHandler socketsHandler = new SocketsHttpHandler() + { + MaxConnectionsPerServer = Environment.ProcessorCount, + PooledConnectionLifetime = Timeout.InfiniteTimeSpan, + PooledConnectionIdleTimeout = TimeSpan.FromMinutes(5), + }; - this.authentication.ConfigureSocketsHandlerSslIfNeeded(this.Tracer, handler, enlistment.CreateGitProcess()); + this.authentication.ConfigureSocketsHandlerSslIfNeeded(this.Tracer, socketsHandler, enlistment.CreateGitProcess()); + handler = socketsHandler; + } this.client = new HttpClient(handler) { @@ -274,20 +284,13 @@ protected GitEndPointResponseData SendRequest( errorMessage += ". " + bodyReadFailure; } } - else if (ShouldRejectCredentials(response.StatusCode, errorMessage)) + else { - this.authentication.RejectCredentials(this.Tracer, authString); - if (!this.authentication.IsBackingOff) - { - errorMessage = string.Format("Server returned error code {0} ({1}). Your PAT may be expired and we are asking for a new one. Original error message from server: {2}", statusInt, response.StatusCode, errorMessage); - } - else + if (ShouldRejectCredentials(response.StatusCode, errorMessage)) { - errorMessage = string.Format("Server returned error code {0} ({1}) after successfully renewing your PAT. You may not have access to this repo. Original error message from server: {2}", statusInt, response.StatusCode, errorMessage); + this.authentication.RejectCredentials(this.Tracer, authString); } - } - else - { + errorMessage = string.Format("Server returned error code {0} ({1}). Original error message from server: {2}", statusInt, response.StatusCode, errorMessage); } diff --git a/GVFS/GVFS.UnitTests/Http/HttpRequestorTests.cs b/GVFS/GVFS.UnitTests/Http/HttpRequestorTests.cs index a88d2fdd3..45c2fca89 100644 --- a/GVFS/GVFS.UnitTests/Http/HttpRequestorTests.cs +++ b/GVFS/GVFS.UnitTests/Http/HttpRequestorTests.cs @@ -1,14 +1,59 @@ +using GVFS.Common; +using GVFS.Common.Git; using GVFS.Common.Http; using GVFS.Tests.Should; +using GVFS.UnitTests.Mock.Common; +using GVFS.UnitTests.Mock.Git; using NUnit.Framework; using System; using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; namespace GVFS.UnitTests.Http { [TestFixture] public class HttpRequestorTests { + [TestCase(HttpStatusCode.Unauthorized, "The credential is invalid.", true)] + [TestCase(HttpStatusCode.Unauthorized, "Authorization failed for repository 00000000-0000-0000-0000-000000000001", true)] + [TestCase(HttpStatusCode.Redirect, "Sign in to continue.", false)] + [TestCase(HttpStatusCode.BadRequest, HttpRequestor.CacheServerAuthRequiredBadRequestMessage, false)] + public void AuthenticationFailuresDoNotInferCredentialRenewal(HttpStatusCode statusCode, string serverMessage, bool shouldRetry) + { + const string RepoUrl = "mock://repoUrl"; + MockGitProcess gitProcess = new MockGitProcess(); + gitProcess.SetExpectedCommandResult( + "config ", + () => new GitProcess.Result(string.Empty, string.Empty, GitProcess.Result.GenericFailureCode), + matchPrefix: true); + gitProcess.SetExpectedCommandResult( + "-c credential.\"https://dev.azure.com\".useHttpPath=true credential fill", + () => new GitProcess.Result("username=test\r\npassword=unchanged\r\n", string.Empty, GitProcess.Result.SuccessCode)); + gitProcess.SetExpectedCommandResult( + "-c credential.\"https://dev.azure.com\".useHttpPath=true credential reject", + () => new GitProcess.Result(string.Empty, string.Empty, GitProcess.Result.SuccessCode)); + + using MockTracer tracer = new MockTracer(); + GitAuthentication authentication = new GitAuthentication(gitProcess, RepoUrl); + authentication.TryInitializeAndRequireAuth(tracer, out string error).ShouldEqual(true, error); + MockGVFSEnlistment enlistment = new MockGVFSEnlistment( + @"mock:\repo", RepoUrl, @"mock:\git", gitProcess, authentication); + using TestHttpRequestor requestor = new TestHttpRequestor(tracer, enlistment, new ErrorResponseHandler(statusCode, serverMessage)); + + for (int rejection = 1; rejection <= 2; ++rejection) + { + using GitEndPointResponseData response = requestor.Send(); + response.Error.Message.ShouldEqual( + $"Server returned error code {(int)statusCode} ({statusCode}). Original error message from server: {serverMessage}"); + response.StatusCode.ShouldEqual(statusCode); + response.ShouldRetry.ShouldEqual(shouldRetry); + gitProcess.CredentialRejections[RepoUrl].Count.ShouldEqual(rejection); + authentication.IsBackingOff.ShouldEqual(rejection == 2); + } + } + [TestCase] public void Unauthorized401RejectsCredentials() { @@ -98,5 +143,37 @@ public void CacheNameTelemetryHasABoundedLength() { HttpRequestor.GetCacheNameForTelemetry(new string('a', 1000)).ShouldEqual(new string('a', 128)); } + + private class TestHttpRequestor : HttpRequestor + { + public TestHttpRequestor(MockTracer tracer, MockGVFSEnlistment enlistment, HttpMessageHandler handler) + : base(tracer, new RetryConfig(), enlistment, handler) + { + } + + public GitEndPointResponseData Send() + { + return this.SendRequest( + GetNewRequestId(), new Uri("https://cache.example.com/objects"), HttpMethod.Get, null, CancellationToken.None); + } + } + + private class ErrorResponseHandler : HttpMessageHandler + { + private readonly HttpStatusCode statusCode; + private readonly string serverMessage; + + public ErrorResponseHandler(HttpStatusCode statusCode, string serverMessage) + { + this.statusCode = statusCode; + this.serverMessage = serverMessage; + } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + request.Headers.Authorization.Scheme.ShouldEqual("Basic"); + return Task.FromResult(new HttpResponseMessage(this.statusCode) { Content = new StringContent(this.serverMessage) }); + } + } } }