forked from microsoft/VFSForGit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitAuthentication.cs
More file actions
263 lines (223 loc) · 8.61 KB
/
GitAuthentication.cs
File metadata and controls
263 lines (223 loc) · 8.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
using GVFS.Common.Http;
using GVFS.Common.Tracing;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace GVFS.Common.Git
{
public class GitAuthentication
{
private const double MaxBackoffSeconds = 30;
private readonly object gitAuthLock = new object();
private readonly GitProcess git;
private readonly string repoUrl;
private int numberOfAttempts = 0;
private DateTime lastAuthAttempt = DateTime.MinValue;
private string cachedAuthString;
private bool isInitialized;
public GitAuthentication(GitProcess git, string repoUrl)
{
this.git = git;
this.repoUrl = repoUrl;
if (git.TryGetConfigUrlMatch("http", this.repoUrl, out Dictionary<string, GitConfigSetting> configSettings))
{
this.GitSsl = new GitSsl(configSettings);
}
}
public bool IsBackingOff
{
get
{
return this.GetNextAuthAttemptTime() > DateTime.Now;
}
}
public bool IsAnonymous { get; private set; } = true;
private GitSsl GitSsl { get; }
public void ConfirmCredentialsWorked(string usedCredential)
{
lock (this.gitAuthLock)
{
if (usedCredential == this.cachedAuthString)
{
this.numberOfAttempts = 0;
this.lastAuthAttempt = DateTime.MinValue;
}
}
}
public void Revoke(string usedCredential)
{
lock (this.gitAuthLock)
{
if (usedCredential != this.cachedAuthString)
{
// Don't stomp a different credential
return;
}
if (this.cachedAuthString != null)
{
this.cachedAuthString = null;
this.git.RevokeCredential(this.repoUrl);
this.UpdateBackoff();
}
}
}
public bool TryRefreshCredentials(ITracer tracer, out string errorMessage)
{
string authString;
return this.TryGetCredentials(tracer, out authString, out errorMessage);
}
public bool TryGetCredentials(ITracer tracer, out string gitAuthString, out string errorMessage)
{
if (!this.isInitialized)
{
throw new InvalidOperationException("This auth instance must be initialized before it can be used");
}
gitAuthString = this.cachedAuthString;
if (gitAuthString == null)
{
lock (this.gitAuthLock)
{
if (this.cachedAuthString == null)
{
if (this.IsBackingOff)
{
errorMessage = "Auth failed. No retries will be made until: " + this.GetNextAuthAttemptTime();
return false;
}
if (!this.TryCallGitCredential(tracer, out errorMessage))
{
return false;
}
}
gitAuthString = this.cachedAuthString;
}
}
errorMessage = null;
return true;
}
public bool TryInitialize(ITracer tracer, Enlistment enlistment, out string errorMessage)
{
if (this.isInitialized)
{
throw new InvalidOperationException("Already initialized");
}
errorMessage = null;
bool isAnonymous;
if (!this.TryAnonymousQuery(tracer, enlistment, out isAnonymous))
{
errorMessage = $"Unable to determine if authentication is required";
return false;
}
if (!isAnonymous &&
!this.TryCallGitCredential(tracer, out errorMessage))
{
return false;
}
this.IsAnonymous = isAnonymous;
this.isInitialized = true;
return true;
}
public bool TryInitializeAndRequireAuth(ITracer tracer, out string errorMessage)
{
if (this.isInitialized)
{
throw new InvalidOperationException("Already initialized");
}
if (this.TryCallGitCredential(tracer, out errorMessage))
{
this.isInitialized = true;
return true;
}
return false;
}
public void ConfigureHttpClientHandlerSslIfNeeded(ITracer tracer, HttpClientHandler httpClientHandler, GitProcess gitProcess)
{
X509Certificate2 cert = this.GitSsl?.GetCertificate(tracer, gitProcess);
if (cert != null)
{
if (this.GitSsl != null && !this.GitSsl.ShouldVerify)
{
httpClientHandler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, c, cetChain, policyErrors) =>
{
return true;
};
}
httpClientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
httpClientHandler.ClientCertificates.Add(cert);
}
}
private bool TryAnonymousQuery(ITracer tracer, Enlistment enlistment, out bool isAnonymous)
{
bool querySucceeded;
using (ITracer anonymousTracer = tracer.StartActivity("AttemptAnonymousAuth", EventLevel.Informational))
{
HttpStatusCode? httpStatus;
using (ConfigHttpRequestor configRequestor = new ConfigHttpRequestor(anonymousTracer, enlistment, new RetryConfig()))
{
ServerGVFSConfig gvfsConfig;
const bool LogErrors = false;
if (configRequestor.TryQueryGVFSConfig(LogErrors, out gvfsConfig, out httpStatus, out _))
{
querySucceeded = true;
isAnonymous = true;
}
else if (httpStatus == HttpStatusCode.Unauthorized)
{
querySucceeded = true;
isAnonymous = false;
}
else
{
querySucceeded = false;
isAnonymous = false;
}
}
anonymousTracer.Stop(new EventMetadata
{
{ "HttpStatus", httpStatus.HasValue ? ((int)httpStatus).ToString() : "None" },
{ "QuerySucceeded", querySucceeded },
{ "IsAnonymous", isAnonymous },
});
}
return querySucceeded;
}
private DateTime GetNextAuthAttemptTime()
{
if (this.numberOfAttempts <= 1)
{
return DateTime.MinValue;
}
double backoffSeconds = RetryBackoff.CalculateBackoffSeconds(this.numberOfAttempts, MaxBackoffSeconds);
return this.lastAuthAttempt + TimeSpan.FromSeconds(backoffSeconds);
}
private void UpdateBackoff()
{
this.lastAuthAttempt = DateTime.Now;
this.numberOfAttempts++;
}
private bool TryCallGitCredential(ITracer tracer, out string errorMessage)
{
string gitUsername;
string gitPassword;
if (!this.git.TryGetCredentials(tracer, this.repoUrl, out gitUsername, out gitPassword, out errorMessage))
{
this.UpdateBackoff();
return false;
}
if (!string.IsNullOrEmpty(gitUsername) && !string.IsNullOrEmpty(gitPassword))
{
this.cachedAuthString = Convert.ToBase64String(Encoding.ASCII.GetBytes(gitUsername + ":" + gitPassword));
}
else
{
errorMessage = "Got back empty credentials from git";
return false;
}
return true;
}
}
}