-
Notifications
You must be signed in to change notification settings - Fork 301
/
Copy pathKubernetes.ConfigInit.cs
271 lines (236 loc) · 9.82 KB
/
Kubernetes.ConfigInit.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
using k8s.Authentication;
using k8s.Exceptions;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace k8s
{
public partial class Kubernetes
{
private readonly JsonSerializerOptions jsonSerializerOptions;
/// <summary>
/// Initializes a new instance of the <see cref="Kubernetes" /> class.
/// </summary>
/// <param name='config'>
/// The kube config to use.
/// </param>
/// <param name="handlers">
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public Kubernetes(KubernetesClientConfiguration config, params DelegatingHandler[] handlers)
{
Initialize();
ValidateConfig(config);
if (config.SslCaCerts != null)
{
var caCerts = new X509Certificate2Collection();
foreach (var cert in config.SslCaCerts)
{
caCerts.Add(new X509Certificate2(cert));
}
CaCerts = caCerts;
}
SkipTlsVerify = config.SkipTlsVerify;
TlsServerName = config.TlsServerName;
CreateHttpClient(handlers, config);
InitializeFromConfig(config);
HttpClientTimeout = config.HttpClientTimeout;
jsonSerializerOptions = config.JsonSerializerOptions;
#if NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER
DisableHttp2 = config.DisableHttp2;
#endif
}
private void ValidateConfig(KubernetesClientConfiguration config)
{
if (config == null)
{
throw new KubeConfigException("KubeConfig must be provided");
}
if (string.IsNullOrWhiteSpace(config.Host))
{
throw new KubeConfigException("Host url must be set");
}
try
{
BaseUri = new Uri(config.Host);
}
catch (UriFormatException e)
{
throw new KubeConfigException("Bad host url", e);
}
}
private void InitializeFromConfig(KubernetesClientConfiguration config)
{
if (BaseUri.Scheme == "https")
{
if (config.SkipTlsVerify)
{
#if NET5_0_OR_GREATER
HttpClientHandler.SslOptions.RemoteCertificateValidationCallback =
#else
HttpClientHandler.ServerCertificateCustomValidationCallback =
#endif
(sender, certificate, chain, sslPolicyErrors) => true;
}
else
{
if (CaCerts != null)
{
#if NET5_0_OR_GREATER
HttpClientHandler.SslOptions.RemoteCertificateValidationCallback =
#else
HttpClientHandler.ServerCertificateCustomValidationCallback =
#endif
(sender, certificate, chain, sslPolicyErrors) =>
{
return CertificateValidationCallBack(sender, CaCerts, certificate, chain,
sslPolicyErrors);
};
}
}
}
// set credentails for the kubernetes client
SetCredentials(config);
ClientCert = CertUtils.GetClientCert(config);
if (ClientCert != null)
{
#if NET5_0_OR_GREATER
HttpClientHandler.SslOptions.ClientCertificates.Add(ClientCert);
// TODO this is workaround for net7.0, remove it when the issue is fixed
// seems the client certificate is cached and cannot be updated
HttpClientHandler.SslOptions.LocalCertificateSelectionCallback = (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) =>
{
return ClientCert;
};
#else
HttpClientHandler.ClientCertificates.Add(ClientCert);
#endif
}
}
private X509Certificate2Collection CaCerts { get; }
private X509Certificate2 ClientCert { get; set; }
private bool SkipTlsVerify { get; }
private string TlsServerName { get; }
// NOTE: this method replicates the logic that the base ServiceClient uses except that it doesn't insert the RetryDelegatingHandler
// and it does insert the WatcherDelegatingHandler. we don't want the RetryDelegatingHandler because it has a very broad definition
// of what requests have failed. it considers everything outside 2xx to be failed, including 1xx (e.g. 101 Switching Protocols) and
// 3xx. in particular, this prevents upgraded connections and certain generic/custom requests from working.
private void CreateHttpClient(DelegatingHandler[] handlers, KubernetesClientConfiguration config)
{
#if NET5_0_OR_GREATER
FirstMessageHandler = HttpClientHandler = new SocketsHttpHandler
{
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.WithActiveRequests,
KeepAlivePingDelay = TimeSpan.FromMinutes(3),
KeepAlivePingTimeout = TimeSpan.FromSeconds(30),
EnableMultipleHttp2Connections = true,
};
HttpClientHandler.SslOptions.ClientCertificates = new X509Certificate2Collection();
#else
FirstMessageHandler = HttpClientHandler = new HttpClientHandler();
#endif
config.FirstMessageHandlerSetup?.Invoke(HttpClientHandler);
if (handlers != null)
{
for (int i = handlers.Length - 1; i >= 0; i--)
{
DelegatingHandler handler = handlers[i];
while (handler.InnerHandler is DelegatingHandler d)
{
handler = d;
}
handler.InnerHandler = FirstMessageHandler;
FirstMessageHandler = handlers[i];
}
}
HttpClient = new HttpClient(FirstMessageHandler, false)
{
Timeout = Timeout.InfiniteTimeSpan,
};
}
/// <summary>
/// Set credentials for the Client
/// </summary>
/// <param name="config">k8s client configuration</param>
private void SetCredentials(KubernetesClientConfiguration config) => Credentials = CreateCredentials(config);
/// <summary>
/// SSl Cert Validation Callback
/// </summary>
/// <param name="sender">sender</param>
/// <param name="caCerts">client ca</param>
/// <param name="certificate">client certificate</param>
/// <param name="chain">chain</param>
/// <param name="sslPolicyErrors">ssl policy errors</param>
/// <returns>true if valid cert</returns>
public static bool CertificateValidationCallBack(
object sender,
X509Certificate2Collection caCerts,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (caCerts == null)
{
throw new ArgumentNullException(nameof(caCerts));
}
if (chain == null)
{
throw new ArgumentNullException(nameof(chain));
}
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
// If there are errors in the certificate chain, look at each error to determine the cause.
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
// Added our trusted certificates to the chain
//
chain.ChainPolicy.ExtraStore.AddRange(caCerts);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
var isValid = chain.Build((X509Certificate2)certificate);
var isTrusted = false;
// Make sure that one of our trusted certs exists in the chain provided by the server.
//
foreach (var cert in caCerts)
{
if (chain.Build(cert))
{
isTrusted = true;
break;
}
}
return isValid && isTrusted;
}
// In all other cases, return false.
return false;
}
/// <summary>
/// Creates <see cref="ServiceClientCredentials"/> based on the given config, or returns null if no such credentials are needed.
/// </summary>
/// <param name="config">kubenetes config object</param>
/// <returns>instance of <see cref="ServiceClientCredentials"/></returns>
public static ServiceClientCredentials CreateCredentials(KubernetesClientConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
if (config.TokenProvider != null)
{
return new TokenCredentials(config.TokenProvider);
}
else if (!string.IsNullOrEmpty(config.AccessToken))
{
return new TokenCredentials(config.AccessToken);
}
else if (!string.IsNullOrEmpty(config.Username))
{
return new BasicAuthenticationCredentials() { UserName = config.Username, Password = config.Password };
}
return null;
}
}
}