Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CredentialService.cs « NuGet.Credentials « MonoDevelop.PackageManagement « addins « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f189f6243963d65c52df1f6692eae93a7c808061 (plain)
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using MonoDevelop.Core;
using NuGet.Common;
using NuGet.Configuration;

namespace NuGet.Credentials
{
	/// <summary>
	/// This service manages orchestrates credential providers and supplies credentials
	/// for use in http requests
	/// </summary>
	class CustomCredentialService : ICredentialService
	{
		readonly ConcurrentDictionary<string, bool> _retryCache
			= new ConcurrentDictionary<string, bool> ();
		readonly ConcurrentDictionary<string, CredentialResponse> _providerCredentialCache
			= new ConcurrentDictionary<string, CredentialResponse> ();
		readonly bool _nonInteractive;

		/// <summary>
		/// This semaphore ensures only one provider active per process, in order
		/// to prevent multiple concurrent interactive login dialogues.
		/// Unnamed semaphores are local to the current process.
		/// </summary>
		static readonly Semaphore ProviderSemaphore = new Semaphore (1, 1);

		Action<string> ErrorDelegate { get; }

		public bool HandlesDefaultCredentials { get; }

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="providers">All available credential providers.</param>
		/// <param name="nonInteractive">If true, the nonInteractive flag will be passed to providers.
		/// NonInteractive requests must not promt the user for credentials.</param>
		public CustomCredentialService (IEnumerable<ICredentialProvider> providers, bool nonInteractive)
		{
			if (providers == null) {
				throw new ArgumentNullException (nameof (providers));
			}

			_nonInteractive = nonInteractive;
			Providers = new List<ICredentialProvider> (providers);
			HandlesDefaultCredentials = Providers.Any (provider => provider is DefaultNetworkCredentialsCredentialProvider);
		}

		/// <summary>
		/// Provides credentials for http requests.
		/// </summary>
		/// <param name="uri">
		/// The URI of a web resource for which credentials are needed.
		/// </param>
		/// <param name="proxy">
		/// The currently configured proxy. It may be necessary for CredentialProviders
		/// to use this proxy in order to acquire credentials from their authentication source.
		/// </param>
		/// <param name="type">
		/// The type of credential request that is being made.
		/// </param>
		/// <param name="message">
		/// A default, user-readable message explaining why they are being prompted for credentials.
		/// The credential provider can choose to ignore this value and write their own message.
		/// </param>
		/// <param name="cancellationToken">A cancellation token.</param>
		/// <returns>A credential object, or null if no credentials could be acquired.</returns>
		public async Task<ICredentials> GetCredentialsAsync (
			Uri uri,
			IWebProxy proxy,
			CredentialRequestType type,
			string message,
			CancellationToken cancellationToken)
		{
			if (uri == null) {
				throw new ArgumentNullException (nameof (uri));
			}

			ICredentials creds = null;

			foreach (var provider in Providers) {
				cancellationToken.ThrowIfCancellationRequested ();

				var retryKey = RetryCacheKey (uri, type, provider);
				var isRetry = _retryCache.ContainsKey (retryKey);

				try {
					// This local semaphore ensures one provider active per process.
					// We can consider other ways to allow more concurrency between providers, but need to
					// ensure that only one interactive dialogue is ever presented at a time, and that
					// providers are not writing shared resources.
					// Since this service is called only when cached credentials are not available to the caller,
					// such an optimization is likely not necessary.
					ProviderSemaphore.WaitOne ();

					CredentialResponse response;
					if (!TryFromCredentialCache (uri, type, isRetry, provider, out response)) {
						response = await provider.GetAsync (
							uri,
							proxy,
							type,
							message,
							isRetry,
							_nonInteractive,
							cancellationToken);

						// Check that the provider gave us a valid response.
						if (response == null || (response.Status != CredentialStatus.Success &&
							response.Status != CredentialStatus.ProviderNotApplicable &&
							response.Status != CredentialStatus.UserCanceled)) {
							throw new ProviderException (GettextCatalog.GetString ("Credential provider gave an invalid response."));
						}

						if (response.Status != CredentialStatus.UserCanceled) {
							AddToCredentialCache (uri, type, provider, response);
						}
					}

					if (response.Status == CredentialStatus.Success) {
						_retryCache [retryKey] = true;
						creds = response.Credentials;
						break;
					}
				} finally {
					ProviderSemaphore.Release ();
				}
			}

			return creds;
		}

		public CredentialService CreateNonInteractive ()
		{
			bool handlesDefaultCredentials = Providers.Any (provider => provider is DefaultNetworkCredentialsCredentialProvider);
			var lazyProviders = AsyncLazy.New (() => Providers)
;			return new CredentialService (lazyProviders, nonInteractive: true, handlesDefaultCredentials: handlesDefaultCredentials);
		}

		/// <summary>
		/// Attempts to retrieve last known good credentials for a URI from a credentials cache.
		/// </summary>
		/// <remarks>
		/// When the return value is <c>true</c>, <paramref name="credentials" /> will have last known
		/// good credentials from the credentials cache.  These credentials may have become invalid
		/// since their last use, so there is no guarantee that the credentials are currently valid.
		/// </remarks>
		/// <param name="uri">The URI for which cached credentials should be retrieved.</param>
		/// <param name="isProxy"><c>true</c> for proxy credentials; otherwise, <c>false</c>.</param>
		/// <param name="credentials">Cached credentials or <c>null</c>.</param>
		/// <returns><c>true</c> if a result is returned from the cache; otherwise, false.</returns>
		/// <exception cref="ArgumentNullException">Thrown if <paramref name="uri" /> is <c>null</c>.</exception>
		public bool TryGetLastKnownGoodCredentialsFromCache (
			Uri uri,
			bool isProxy,
			out ICredentials credentials)
		{
			if (uri == null) {
				throw new ArgumentNullException (nameof (uri));
			}

			credentials = null;

			var rootUri = GetRootUri (uri);
			var ending = $"_{isProxy}_{rootUri}";

			foreach (var entry in _providerCredentialCache) {
				if (entry.Value.Status == CredentialStatus.Success && entry.Key.EndsWith (ending)) {
					credentials = entry.Value.Credentials;

					return true;
				}
			}

			return false;
		}

		/// <summary>
		/// Gets the currently configured providers.
		/// </summary>
		IEnumerable<ICredentialProvider> Providers { get; }

		bool TryFromCredentialCache (Uri uri, CredentialRequestType type, bool isRetry, ICredentialProvider provider,
			out CredentialResponse credentials)
		{
			credentials = null;

			var key = CredentialCacheKey (uri, type, provider);
			if (isRetry) {
				CredentialResponse removed;
				_providerCredentialCache.TryRemove (key, out removed);
				return false;
			}

			return _providerCredentialCache.TryGetValue (key, out credentials);
		}

		void AddToCredentialCache (Uri uri, CredentialRequestType type, ICredentialProvider provider,
			CredentialResponse credentials)
		{
			_providerCredentialCache [CredentialCacheKey (uri, type, provider)] = credentials;
		}

		static string RetryCacheKey (Uri uri, CredentialRequestType type, ICredentialProvider provider)
		{
			return GetUriKey (uri, type, provider);
		}

		static string CredentialCacheKey(Uri uri, CredentialRequestType type, ICredentialProvider provider)
		{
			var rootUri = GetRootUri (uri);
			return GetUriKey (rootUri, type, provider);
		}

		static Uri GetRootUri (Uri uri)
		{
			return new Uri (uri.GetComponents (UriComponents.SchemeAndServer, UriFormat.SafeUnescaped));
		}

		static string GetUriKey (Uri uri, CredentialRequestType type, ICredentialProvider provider)
		{
			return $"{provider.Id}_{type == CredentialRequestType.Proxy}_{uri}";
		}

		/// <summary>
		/// Clears the retry cache so credentials will be tried again from the key chain
		/// instead of defaulting to showing the credential dialog.
		/// </summary>
		public void Reset ()
		{
			_retryCache.Clear ();
		}
	}
}