Skip to content
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
1 change: 1 addition & 0 deletions GVFS/GVFS.Common/Git/GitAuthentication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
37 changes: 20 additions & 17 deletions GVFS/GVFS.Common/Http/HttpRequestor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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 <base64>" 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)
{
Expand Down Expand Up @@ -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);
}

Expand Down
77 changes: 77 additions & 0 deletions GVFS/GVFS.UnitTests/Http/HttpRequestorTests.cs
Original file line number Diff line number Diff line change
@@ -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()
{
Expand Down Expand Up @@ -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<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Headers.Authorization.Scheme.ShouldEqual("Basic");
return Task.FromResult(new HttpResponseMessage(this.statusCode) { Content = new StringContent(this.serverMessage) });
}
}
}
}
Loading