-
Notifications
You must be signed in to change notification settings - Fork 449
/
GitAuthentication.cs
318 lines (275 loc) · 11.7 KB
/
GitAuthentication.cs
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
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 cachedCredentialString;
private bool isCachedCredentialStringApproved = false;
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 ApproveCredentials(ITracer tracer, string credentialString)
{
lock (this.gitAuthLock)
{
// Don't reset the backoff if this is for a different credential than we have cached
if (credentialString == this.cachedCredentialString)
{
this.numberOfAttempts = 0;
this.lastAuthAttempt = DateTime.MinValue;
// Tell Git to store the valid credential if we haven't already
// done so for this cached credential.
if (!this.isCachedCredentialStringApproved)
{
string username;
string password;
if (TryParseCredentialString(this.cachedCredentialString, out username, out password))
{
this.git.ApproveCredentials(this.repoUrl, username, password);
this.isCachedCredentialStringApproved = true;
}
else
{
EventMetadata metadata = new EventMetadata(new Dictionary<string, object>
{
["RepoUrl"] = this.repoUrl,
});
tracer.RelatedError(metadata, "Failed to parse credential string for approval");
}
}
}
}
}
public void RejectCredentials(ITracer tracer, string credentialString)
{
lock (this.gitAuthLock)
{
// Don't stomp a different credential
if (credentialString == this.cachedCredentialString && this.cachedCredentialString != null)
{
// If we can we should pass the actual username/password values we used (and found to be invalid)
// to `git-credential reject` so the credential helpers can attempt to check if they're erasing
// the expected credentials, if they so choose to.
string username;
string password;
if (TryParseCredentialString(this.cachedCredentialString, out username, out password))
{
this.git.RejectCredentials(this.repoUrl, username, password);
}
else
{
// We failed to parse the credential string so instead (as a recovery) we try to erase without
// specifying the particular username/password.
EventMetadata metadata = new EventMetadata(new Dictionary<string, object>
{
["RepoUrl"] = this.repoUrl,
});
tracer.RelatedWarning(metadata, "Failed to parse credential string for rejection. Rejecting any credential for this repo URL.");
this.git.RejectCredentials(this.repoUrl);
}
this.cachedCredentialString = null;
this.isCachedCredentialStringApproved = false;
this.UpdateBackoff();
}
}
}
public bool TryGetCredentials(ITracer tracer, out string credentialString, out string errorMessage)
{
if (!this.isInitialized)
{
throw new InvalidOperationException("This auth instance must be initialized before it can be used");
}
credentialString = this.cachedCredentialString;
if (credentialString == null)
{
lock (this.gitAuthLock)
{
if (this.cachedCredentialString == 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;
}
}
credentialString = this.cachedCredentialString;
}
}
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 static bool TryParseCredentialString(string credentialString, out string username, out string password)
{
if (credentialString != null)
{
byte[] data = Convert.FromBase64String(credentialString);
string rawCredString = Encoding.ASCII.GetString(data);
string[] usernamePassword = rawCredString.Split(':');
if (usernamePassword.Length == 2)
{
username = usernamePassword[0];
password = usernamePassword[1];
return true;
}
}
username = null;
password = null;
return false;
}
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.cachedCredentialString = Convert.ToBase64String(Encoding.ASCII.GetBytes(gitUsername + ":" + gitPassword));
this.isCachedCredentialStringApproved = false;
}
else
{
errorMessage = "Got back empty credentials from git";
return false;
}
return true;
}
}
}