-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathGitLabAuthentication.cs
More file actions
313 lines (249 loc) · 12.5 KB
/
GitLabAuthentication.cs
File metadata and controls
313 lines (249 loc) · 12.5 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
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
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using GitCredentialManager;
using GitCredentialManager.Authentication;
using GitCredentialManager.Authentication.OAuth;
using GitCredentialManager.UI;
using GitLab.UI.ViewModels;
using GitLab.UI.Views;
namespace GitLab
{
public interface IGitLabAuthentication : IDisposable
{
Task<AuthenticationPromptResult> GetAuthenticationAsync(Uri targetUri, string userName, AuthenticationModes modes);
Task<OAuth2TokenResult> GetOAuthTokenViaBrowserAsync(Uri targetUri, IEnumerable<string> scopes);
Task<OAuth2TokenResult> GetOAuthTokenViaRefresh(Uri targetUri, string refreshToken);
}
public class AuthenticationPromptResult
{
public AuthenticationPromptResult(AuthenticationModes mode)
{
AuthenticationMode = mode;
}
public AuthenticationPromptResult(AuthenticationModes mode, ICredential credential)
: this(mode)
{
Credential = credential;
}
public AuthenticationModes AuthenticationMode { get; }
public ICredential Credential { get; set; }
}
[Flags]
public enum AuthenticationModes
{
None = 0,
Basic = 1,
Browser = 1 << 1,
Pat = 1 << 2,
All = Basic | Browser | Pat
}
public class GitLabAuthentication : AuthenticationBase, IGitLabAuthentication
{
public GitLabAuthentication(ICommandContext context)
: base(context) { }
public async Task<AuthenticationPromptResult> GetAuthenticationAsync(Uri targetUri, string userName, AuthenticationModes modes)
{
// If we cannot start a browser then don't offer the option
if (!Context.SessionManager.IsWebBrowserAvailable)
{
modes = modes & ~AuthenticationModes.Browser;
}
// We need at least one mode!
if (modes == AuthenticationModes.None)
{
throw new ArgumentException(@$"Must specify at least one {nameof(AuthenticationModes)}", nameof(modes));
}
ThrowIfUserInteractionDisabled();
if (Context.Settings.IsGuiPromptsEnabled && Context.SessionManager.IsDesktopSession)
{
if (TryFindHelperCommand(out string helperCommand, out string args))
{
return await GetAuthenticationViaHelperAsync(targetUri, userName, modes, helperCommand, args);
}
return await GetAuthenticationViaUiAsync(targetUri, userName, modes);
}
return GetAuthenticationViaTty(targetUri, userName, modes);
}
private async Task<AuthenticationPromptResult> GetAuthenticationViaUiAsync(
Uri targetUri, string userName, AuthenticationModes modes)
{
var viewModel = new CredentialsViewModel(Context.Environment)
{
ShowBrowserLogin = (modes & AuthenticationModes.Browser) != 0,
ShowTokenLogin = (modes & AuthenticationModes.Pat) != 0,
ShowBasicLogin = (modes & AuthenticationModes.Basic) != 0,
};
if (!GitLabConstants.IsGitLabDotCom(targetUri))
{
viewModel.Url = targetUri.ToString();
}
if (!string.IsNullOrWhiteSpace(userName))
{
viewModel.UserName = userName;
viewModel.TokenUserName = userName;
}
await AvaloniaUi.ShowViewAsync<CredentialsView>(viewModel, GetParentWindowHandle(), CancellationToken.None);
ThrowIfWindowCancelled(viewModel);
switch (viewModel.SelectedMode)
{
case AuthenticationModes.Basic:
return new AuthenticationPromptResult(
AuthenticationModes.Basic,
new GitCredential(viewModel.UserName, viewModel.Password)
);
case AuthenticationModes.Browser:
return new AuthenticationPromptResult(AuthenticationModes.Browser);
case AuthenticationModes.Pat:
return new AuthenticationPromptResult(
AuthenticationModes.Pat,
new GitCredential(viewModel.TokenUserName, viewModel.Token)
);
default:
throw new ArgumentOutOfRangeException();
}
}
private AuthenticationPromptResult GetAuthenticationViaTty(Uri targetUri, string userName, AuthenticationModes modes)
{
ThrowIfTerminalPromptsDisabled();
switch (modes)
{
case AuthenticationModes.Basic:
Context.Terminal.WriteLine("Enter GitLab credentials for '{0}'...", targetUri);
if (string.IsNullOrWhiteSpace(userName))
{
userName = Context.Terminal.Prompt("Username");
}
else
{
Context.Terminal.WriteLine("Username: {0}", userName);
}
string password = Context.Terminal.PromptSecret("Password");
return new AuthenticationPromptResult(AuthenticationModes.Basic, new GitCredential(userName, password));
case AuthenticationModes.Pat:
Context.Terminal.WriteLine("Enter GitLab credentials for '{0}'...", targetUri);
if (string.IsNullOrWhiteSpace(userName))
{
userName = Context.Terminal.Prompt("Username");
}
else
{
Context.Terminal.WriteLine("Username: {0}", userName);
}
string token = Context.Terminal.PromptSecret("Personal access token");
return new AuthenticationPromptResult(AuthenticationModes.Pat, new GitCredential(userName, token));
case AuthenticationModes.Browser:
return new AuthenticationPromptResult(AuthenticationModes.Browser);
case AuthenticationModes.None:
throw new ArgumentOutOfRangeException(nameof(modes),
@$"At least one {nameof(AuthenticationModes)} must be supplied");
default:
var menuTitle = $"Select an authentication method for '{targetUri}'";
var menu = new TerminalMenu(Context.Terminal, menuTitle);
TerminalMenuItem browserItem = null;
TerminalMenuItem basicItem = null;
TerminalMenuItem patItem = null;
if ((modes & AuthenticationModes.Browser) != 0) browserItem = menu.Add("Web browser");
if ((modes & AuthenticationModes.Pat) != 0) patItem = menu.Add("Personal access token");
if ((modes & AuthenticationModes.Basic) != 0) basicItem = menu.Add("Username/password");
// Default to the 'first' choice in the menu
TerminalMenuItem choice = menu.Show(0);
if (choice == browserItem) goto case AuthenticationModes.Browser;
if (choice == basicItem) goto case AuthenticationModes.Basic;
if (choice == patItem) goto case AuthenticationModes.Pat;
throw new Exception();
}
}
private async Task<AuthenticationPromptResult> GetAuthenticationViaHelperAsync(
Uri targetUri, string userName, AuthenticationModes modes, string helperCommand, string args)
{
var promptArgs = new StringBuilder(args);
promptArgs.Append("prompt");
if (!string.IsNullOrWhiteSpace(userName))
{
promptArgs.AppendFormat(" --username {0}", QuoteCmdArg(userName));
}
promptArgs.AppendFormat(" --url {0}", QuoteCmdArg(targetUri.ToString()));
if ((modes & AuthenticationModes.Basic) != 0) promptArgs.Append(" --basic");
if ((modes & AuthenticationModes.Browser) != 0) promptArgs.Append(" --browser");
if ((modes & AuthenticationModes.Pat) != 0) promptArgs.Append(" --pat");
IDictionary<string, string> resultDict = await InvokeHelperAsync(helperCommand, promptArgs.ToString());
if (!resultDict.TryGetValue("mode", out string responseMode))
{
throw new Trace2Exception(Context.Trace2, "Missing 'mode' in response");
}
switch (responseMode.ToLowerInvariant())
{
case "pat":
if (!resultDict.TryGetValue("pat", out string pat))
{
throw new Trace2Exception(Context.Trace2, "Missing 'pat' in response");
}
if (!resultDict.TryGetValue("username", out string patUserName))
{
// Username is optional for PATs
}
return new AuthenticationPromptResult(
AuthenticationModes.Pat, new GitCredential(patUserName, pat));
case "browser":
return new AuthenticationPromptResult(AuthenticationModes.Browser);
case "basic":
if (!resultDict.TryGetValue("username", out userName))
{
throw new Trace2Exception(Context.Trace2, "Missing 'username' in response");
}
if (!resultDict.TryGetValue("password", out string password))
{
throw new Trace2Exception(Context.Trace2, "Missing 'password' in response");
}
return new AuthenticationPromptResult(
AuthenticationModes.Basic, new GitCredential(userName, password));
default:
throw new Trace2Exception(Context.Trace2,
$"Unknown mode value in response '{responseMode}'");
}
}
public async Task<OAuth2TokenResult> GetOAuthTokenViaBrowserAsync(Uri targetUri, IEnumerable<string> scopes)
{
ThrowIfUserInteractionDisabled();
var oauthClient = new GitLabOAuth2Client(HttpClient, Context.Settings, targetUri, Context.Trace2);
// We require a desktop session to launch the user's default web browser
if (!Context.SessionManager.IsDesktopSession)
{
throw new Trace2InvalidOperationException(Context.Trace2,
"Browser authentication requires a desktop session");
}
var browserOptions = new OAuth2WebBrowserOptions { };
var browser = new OAuth2SystemWebBrowser(Context.Environment, browserOptions);
// Write message to the terminal (if any is attached) for some feedback that we're waiting for a web response
Context.Terminal.WriteLine("info: please complete authentication in your browser...");
Context.Terminal.WriteLine($"uri: {oauthClient.RedirectUri}");
OAuth2AuthorizationCodeResult authCodeResult =
await oauthClient.GetAuthorizationCodeAsync(scopes, browser, CancellationToken.None);
return await oauthClient.GetTokenByAuthorizationCodeAsync(authCodeResult, CancellationToken.None);
}
public async Task<OAuth2TokenResult> GetOAuthTokenViaRefresh(Uri targetUri, string refreshToken)
{
var oauthClient = new GitLabOAuth2Client(HttpClient, Context.Settings, targetUri, Context.Trace2);
return await oauthClient.GetTokenByRefreshTokenAsync(refreshToken, CancellationToken.None);
}
private bool TryFindHelperCommand(out string command, out string args)
{
return TryFindHelperCommand(
GitLabConstants.EnvironmentVariables.AuthenticationHelper,
GitLabConstants.GitConfiguration.Credential.AuthenticationHelper,
GitLabConstants.DefaultAuthenticationHelper,
out command,
out args);
}
private HttpClient _httpClient;
private HttpClient HttpClient => _httpClient ?? (_httpClient = Context.HttpClientFactory.CreateClient());
public void Dispose()
{
_httpClient?.Dispose();
}
}
}