Repository navigation
Expand file tree
/
Copy pathAlternatorHttpClientFactory.cs
More file actions
293 lines (254 loc) · 10.9 KB
/
Copy pathAlternatorHttpClientFactory.cs
File metadata and controls
293 lines (254 loc) · 10.9 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
// Copyright ScyllaDB, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace ScyllaDB.Alternator
{
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Amazon.Runtime;
internal sealed class AlternatorHttpClientFactory : HttpClientFactory
{
private readonly AlternatorConfig config;
private readonly AlternatorLiveNodes? liveNodes;
private readonly Action<HttpClientHandler>? configureHttpClientHandler;
private readonly Action<SocketsHttpHandler>? configureSocketsHttpHandler;
internal AlternatorHttpClientFactory(
AlternatorConfig config,
AlternatorLiveNodes? liveNodes = null,
Action<HttpClientHandler>? configureHttpClientHandler = null,
Action<SocketsHttpHandler>? configureSocketsHttpHandler = null)
{
this.config = config;
this.liveNodes = liveNodes;
this.configureHttpClientHandler = configureHttpClientHandler;
this.configureSocketsHttpHandler = configureSocketsHttpHandler;
}
public override HttpClient CreateHttpClient(IClientConfig clientConfig)
{
HttpMessageHandler handler = CreatePrimaryHandler(
this.config,
this.configureHttpClientHandler,
this.configureSocketsHttpHandler);
if (this.liveNodes != null)
{
handler = new NodeHealthReportingHttpMessageHandler(handler, this.liveNodes, this.config.NodeHealth);
}
if (this.config.OptimizeHeaders)
{
handler = new HeadersFilteringHttpMessageHandler(handler, this.config.HeadersWhitelist);
}
if (this.config.ResponseCompressionAlgorithms.Count > 0)
{
handler = new ResponseCompressionHttpMessageHandler(handler, this.config.ResponseCompressionAlgorithms);
}
return new HttpClient(handler);
}
internal static HttpMessageHandler CreatePrimaryHandler(
AlternatorConfig config,
Action<HttpClientHandler>? configureHttpClientHandler = null,
Action<SocketsHttpHandler>? configureSocketsHttpHandler = null)
{
if (configureHttpClientHandler != null && configureSocketsHttpHandler != null)
{
throw new InvalidOperationException(
"HttpClientHandler and SocketsHttpHandler customizers cannot be used together.");
}
if (configureHttpClientHandler != null)
{
return CreateHandler(config.TlsConfig, config.MaxConnections, configureHttpClientHandler);
}
return CreateSocketsHandler(config, configureSocketsHttpHandler);
}
internal static HttpClientHandler CreateHandler(
TlsConfig tlsConfig,
int maxConnections,
Action<HttpClientHandler>? configureHandler = null)
{
if (!tlsConfig.TlsSessionResumptionEnabled)
{
throw new NotSupportedException(
"Disabling TLS session resumption is only supported by the default SocketsHttpHandler transport.");
}
var handler = new HttpClientHandler
{
MaxConnectionsPerServer = maxConnections,
};
if (tlsConfig.hasClientCertificate())
{
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.AddRange(LoadClientCertificates(tlsConfig));
}
if (NeedsCustomCertificateValidation(tlsConfig))
{
handler.ServerCertificateCustomValidationCallback = (request, certificate, chain, sslPolicyErrors) =>
ValidateCertificate(tlsConfig, request, certificate, chain, sslPolicyErrors);
}
configureHandler?.Invoke(handler);
return handler;
}
internal static SocketsHttpHandler CreateSocketsHandler(
AlternatorConfig config,
Action<SocketsHttpHandler>? configureHandler = null)
{
var handler = new SocketsHttpHandler
{
MaxConnectionsPerServer = config.MaxConnections,
PooledConnectionIdleTimeout = ToTimeout(config.ConnectionMaxIdleTimeMs),
PooledConnectionLifetime = ToTimeout(config.ConnectionTimeToLiveMs),
};
handler.SslOptions.AllowTlsResume = config.TlsConfig.TlsSessionResumptionEnabled;
if (config.ConnectionTimeoutMs > 0)
{
handler.ConnectTimeout = TimeSpan.FromMilliseconds(config.ConnectionTimeoutMs);
}
if (config.TlsConfig.hasClientCertificate())
{
handler.SslOptions.ClientCertificates = LoadClientCertificates(config.TlsConfig);
}
if (NeedsCustomCertificateValidation(config.TlsConfig))
{
handler.SslOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
ValidateCertificate(config.TlsConfig, sender, certificate, chain, sslPolicyErrors);
}
configureHandler?.Invoke(handler);
return handler;
}
private static bool NeedsCustomCertificateValidation(TlsConfig tlsConfig)
{
return tlsConfig.CertificateValidationCallback != null
|| tlsConfig.TrustAllCertificates
|| tlsConfig.CustomCaCertPaths.Count > 0
|| tlsConfig.CustomCaCertificates.Count > 0
|| !tlsConfig.VerifyHostname;
}
private static X509CertificateCollection LoadClientCertificates(TlsConfig tlsConfig)
{
var certificates = new X509CertificateCollection();
foreach (var certificate in tlsConfig.ClientCertificates)
{
certificates.Add(certificate);
}
if (tlsConfig.ClientCertificatePath != null && tlsConfig.ClientPrivateKeyPath != null)
{
certificates.Add(X509Certificate2.CreateFromPemFile(
tlsConfig.ClientCertificatePath,
tlsConfig.ClientPrivateKeyPath));
}
return certificates;
}
private static TimeSpan ToTimeout(long timeoutMs)
{
return timeoutMs == 0
? System.Threading.Timeout.InfiniteTimeSpan
: TimeSpan.FromMilliseconds(timeoutMs);
}
private static bool ValidateCertificate(
TlsConfig tlsConfig,
X509Certificate? certificate,
X509Chain? chain,
SslPolicyErrors sslPolicyErrors)
{
return ValidateCertificate(tlsConfig, null, certificate, chain, sslPolicyErrors);
}
private static bool ValidateCertificate(
TlsConfig tlsConfig,
object? sender,
X509Certificate? certificate,
X509Chain? chain,
SslPolicyErrors sslPolicyErrors)
{
var certificate2 = certificate as X509Certificate2;
X509Certificate2? convertedCertificate = null;
if (certificate != null && certificate2 == null)
{
convertedCertificate = new X509Certificate2(certificate);
certificate2 = convertedCertificate;
}
try
{
return ValidateCertificate(tlsConfig, sender, certificate2, chain, sslPolicyErrors);
}
finally
{
convertedCertificate?.Dispose();
}
}
private static bool ValidateCertificate(
TlsConfig tlsConfig,
X509Certificate2? certificate,
X509Chain? chain,
SslPolicyErrors sslPolicyErrors)
{
return ValidateCertificate(tlsConfig, null, certificate, chain, sslPolicyErrors);
}
private static bool ValidateCertificate(
TlsConfig tlsConfig,
object? sender,
X509Certificate2? certificate,
X509Chain? chain,
SslPolicyErrors sslPolicyErrors)
{
if (tlsConfig.CertificateValidationCallback != null)
{
return tlsConfig.CertificateValidationCallback(sender ?? tlsConfig, certificate, chain, sslPolicyErrors);
}
if (tlsConfig.TrustAllCertificates)
{
return true;
}
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
var hasNameMismatch = (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0;
var errorsWithoutNameMismatch = sslPolicyErrors & ~SslPolicyErrors.RemoteCertificateNameMismatch;
if (!tlsConfig.VerifyHostname && errorsWithoutNameMismatch == SslPolicyErrors.None)
{
return true;
}
var unsupportedErrors = errorsWithoutNameMismatch & ~SslPolicyErrors.RemoteCertificateChainErrors;
if (unsupportedErrors != SslPolicyErrors.None)
{
return false;
}
if (certificate == null || (tlsConfig.CustomCaCertPaths.Count == 0 && tlsConfig.CustomCaCertificates.Count == 0))
{
return false;
}
var hostnameAccepted = !tlsConfig.VerifyHostname || !hasNameMismatch;
if (tlsConfig.TrustSystemCaCerts && chain != null && chain.Build(certificate))
{
return hostnameAccepted;
}
using var customChain = new X509Chain();
customChain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
customChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
foreach (var certPath in tlsConfig.CustomCaCertPaths)
{
customChain.ChainPolicy.CustomTrustStore.Add(new X509Certificate2(certPath));
}
foreach (var customCaCertificate in tlsConfig.CustomCaCertificates)
{
customChain.ChainPolicy.CustomTrustStore.Add(customCaCertificate);
}
var chainValid = customChain.Build(certificate);
if (chainValid)
{
return hostnameAccepted;
}
return false;
}
}
}