Skip to content
This repository was archived by the owner on Mar 20, 2024. It is now read-only.

Commit 420dfcd

Browse files
tg123JonJam
authored andcommitted
1 parent a8bfd29 commit 420dfcd

File tree

2 files changed

+181
-0
lines changed

2 files changed

+181
-0
lines changed

src/Kubernetes.Auth.cs

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
using k8s.Models;
2+
3+
namespace k8s
4+
{
5+
using System;
6+
using System.Diagnostics.CodeAnalysis;
7+
using System.Net.Http;
8+
using System.Net.Security;
9+
using System.Security.Cryptography.X509Certificates;
10+
using System.Threading.Tasks;
11+
using k8s.Exceptions;
12+
using Microsoft.Rest;
13+
14+
public partial class Kubernetes : ServiceClient<Kubernetes>, IKubernetes
15+
{
16+
/// <summary>
17+
/// Initializes a new instance of the <see cref="Kubernetes"/> class.
18+
/// </summary>
19+
/// <param name='config'>
20+
/// Optional. The delegating handlers to add to the http client pipeline.
21+
/// </param>
22+
public Kubernetes(KubernetesClientConfiguration config)
23+
{
24+
this.Initialize();
25+
26+
this.CaCert = config.SslCaCert;
27+
this.BaseUri = new Uri(config.Host);
28+
29+
var handler = new HttpClientHandler();
30+
31+
if (BaseUri.Scheme == "https")
32+
{
33+
if (config.SkipTlsVerify)
34+
{
35+
handler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
36+
}
37+
else
38+
{
39+
if (CaCert == null)
40+
{
41+
throw new KubeConfigException("a CA must be set when SkipTlsVerify === false");
42+
}
43+
44+
handler.ServerCertificateCustomValidationCallback = CertificateValidationCallBack;
45+
}
46+
}
47+
48+
// set credentails for the kubernernet client
49+
this.SetCredentials(config, handler);
50+
this.InitializeHttpClient(handler, new DelegatingHandler[]{new WatcherDelegatingHandler()});
51+
52+
DeserializationSettings.Converters.Add(new V1Status.V1StatusObjectViewConverter());
53+
}
54+
55+
private X509Certificate2 CaCert { get; set; }
56+
57+
/// <summary>
58+
/// Set credentials for the Client
59+
/// </summary>
60+
/// <param name="config">k8s client configuration</param>
61+
/// <param name="handler">http client handler for the rest client</param>
62+
/// <returns>Task</returns>
63+
private void SetCredentials(KubernetesClientConfiguration config, HttpClientHandler handler)
64+
{
65+
// set the Credentails for token based auth
66+
if (!string.IsNullOrWhiteSpace(config.AccessToken))
67+
{
68+
Credentials = new TokenCredentials(config.AccessToken);
69+
}
70+
else if (!string.IsNullOrWhiteSpace(config.Username) && !string.IsNullOrWhiteSpace(config.Password))
71+
{
72+
Credentials = new BasicAuthenticationCredentials
73+
{
74+
UserName = config.Username,
75+
Password = config.Password
76+
};
77+
}
78+
// othwerwise set handler for clinet cert based auth
79+
else if ((!string.IsNullOrWhiteSpace(config.ClientCertificateData) ||
80+
!string.IsNullOrWhiteSpace(config.ClientCertificateFilePath)) &&
81+
(!string.IsNullOrWhiteSpace(config.ClientCertificateKeyData) ||
82+
!string.IsNullOrWhiteSpace(config.ClientKeyFilePath)))
83+
{
84+
var cert = Utils.GeneratePfx(config);
85+
86+
handler.ClientCertificates.Add(cert);
87+
}
88+
}
89+
90+
/// <summary>
91+
/// SSl Cert Validation Callback
92+
/// </summary>
93+
/// <param name="sender">sender</param>
94+
/// <param name="certificate">client certificate</param>
95+
/// <param name="chain">chain</param>
96+
/// <param name="sslPolicyErrors">ssl policy errors</param>
97+
/// <returns>true if valid cert</returns>
98+
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Unused by design")]
99+
private bool CertificateValidationCallBack(
100+
object sender,
101+
X509Certificate certificate,
102+
X509Chain chain,
103+
SslPolicyErrors sslPolicyErrors)
104+
{
105+
// If the certificate is a valid, signed certificate, return true.
106+
if (sslPolicyErrors == SslPolicyErrors.None)
107+
{
108+
return true;
109+
}
110+
111+
// If there are errors in the certificate chain, look at each error to determine the cause.
112+
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
113+
{
114+
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
115+
116+
// add all your extra certificate chain
117+
chain.ChainPolicy.ExtraStore.Add(this.CaCert);
118+
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
119+
var isValid = chain.Build((X509Certificate2)certificate);
120+
return isValid;
121+
}
122+
else
123+
{
124+
// In all other cases, return false.
125+
return false;
126+
}
127+
}
128+
}
129+
}

src/V1Status.ObjectView.cs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
using System;
2+
using Newtonsoft.Json;
3+
using Newtonsoft.Json.Linq;
4+
5+
namespace k8s.Models
6+
{
7+
public partial class V1Status
8+
{
9+
internal class V1StatusObjectViewConverter : JsonConverter
10+
{
11+
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
12+
{
13+
serializer.Serialize(writer, value);
14+
}
15+
16+
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
17+
JsonSerializer serializer)
18+
{
19+
var obj = JToken.Load(reader);
20+
21+
try
22+
{
23+
return obj.ToObject(objectType);
24+
}
25+
catch (JsonException)
26+
{
27+
// should be an object
28+
}
29+
30+
return new V1Status
31+
{
32+
_original = obj,
33+
HasObject = true
34+
};
35+
}
36+
37+
public override bool CanConvert(Type objectType)
38+
{
39+
return typeof(V1Status) == objectType;
40+
}
41+
}
42+
43+
private JToken _original;
44+
45+
public bool HasObject { get; private set; }
46+
47+
public T ObjectView<T>()
48+
{
49+
return _original.ToObject<T>();
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)