Skip to content

DelegatingHandler now works with Kubernetes clients #50

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 60 additions & 39 deletions src/Kubernetes.Auth.cs → src/Kubernetes.ConfigInit.cs
Original file line number Diff line number Diff line change
@@ -1,38 +1,36 @@
using k8s.Models;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using k8s.Exceptions;
using Microsoft.Rest;

namespace k8s
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using k8s.Exceptions;
using Microsoft.Rest;

public partial class Kubernetes : ServiceClient<Kubernetes>, IKubernetes
public partial class Kubernetes
{
/// <summary>
/// Initializes a new instance of the <see cref="Kubernetes"/> class.
/// Initializes a new instance of the <see cref="Kubernetes" /> class.
/// </summary>
/// <param name='config'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <param name="handlers">
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public Kubernetes(KubernetesClientConfiguration config)
public Kubernetes(KubernetesClientConfiguration config, params DelegatingHandler[] handlers) : this(handlers)
{
this.Initialize();

this.CaCert = config.SslCaCert;
this.BaseUri = new Uri(config.Host);

var handler = new HttpClientHandler();
CaCert = config.SslCaCert;
BaseUri = new Uri(config.Host);

if (BaseUri.Scheme == "https")
{
if (config.SkipTlsVerify)
{
handler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
HttpClientHandler.ServerCertificateCustomValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true;
}
else
{
Expand All @@ -41,21 +39,47 @@ public Kubernetes(KubernetesClientConfiguration config)
throw new KubeConfigException("a CA must be set when SkipTlsVerify === false");
}

handler.ServerCertificateCustomValidationCallback = CertificateValidationCallBack;
HttpClientHandler.ServerCertificateCustomValidationCallback = CertificateValidationCallBack;
}
}

// set credentails for the kubernernet client
this.SetCredentials(config, handler);
this.InitializeHttpClient(handler, new DelegatingHandler[]{new WatcherDelegatingHandler()});

DeserializationSettings.Converters.Add(new V1Status.V1StatusObjectViewConverter());
SetCredentials(config, HttpClientHandler);
}

private X509Certificate2 CaCert { get; }

partial void CustomInitialize()
{
AppendDelegatingHandler<WatcherDelegatingHandler>();
DeserializationSettings.Converters.Add(new V1Status.V1StatusObjectViewConverter());
}

private X509Certificate2 CaCert { get; set; }
private void AppendDelegatingHandler<T>() where T : DelegatingHandler, new()
{
var cur = FirstMessageHandler as DelegatingHandler;

while (cur != null)
{
var next = cur.InnerHandler as DelegatingHandler;

if (next == null)
{
// last one
// append watcher handler between to last handler
cur.InnerHandler = new T
{
InnerHandler = cur.InnerHandler
};
break;
}

cur = next;
}
}

/// <summary>
/// Set credentials for the Client
/// Set credentials for the Client
/// </summary>
/// <param name="config">k8s client configuration</param>
/// <param name="handler">http client handler for the rest client</param>
Expand Down Expand Up @@ -88,7 +112,7 @@ private void SetCredentials(KubernetesClientConfiguration config, HttpClientHand
}

/// <summary>
/// SSl Cert Validation Callback
/// SSl Cert Validation Callback
/// </summary>
/// <param name="sender">sender</param>
/// <param name="certificate">client certificate</param>
Expand All @@ -97,10 +121,10 @@ private void SetCredentials(KubernetesClientConfiguration config, HttpClientHand
/// <returns>true if valid cert</returns>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Unused by design")]
private bool CertificateValidationCallBack(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == SslPolicyErrors.None)
Expand All @@ -114,16 +138,13 @@ private bool CertificateValidationCallBack(
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

// add all your extra certificate chain
chain.ChainPolicy.ExtraStore.Add(this.CaCert);
chain.ChainPolicy.ExtraStore.Add(CaCert);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
var isValid = chain.Build((X509Certificate2)certificate);
var isValid = chain.Build((X509Certificate2) certificate);
return isValid;
}
else
{
// In all other cases, return false.
return false;
}
// In all other cases, return false.
return false;
}
}
}
15 changes: 2 additions & 13 deletions src/KubernetesClientConfiguration.ConfigFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,6 @@ public partial class KubernetesClientConfiguration
? Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), @".kube\config")
: Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".kube/config");

/// <summary>
/// Initializes a new instance of the <see cref="KubernetesClientConfiguration"/> class.
/// </summary>
/// <param name="kubeconfig">kubeconfig file info</param>
/// <param name="currentContext">Context to use from kube config</param>
public KubernetesClientConfiguration(FileInfo kubeconfig = null, string currentContext = null)
{
var k8SConfig = LoadKubeConfig(kubeconfig ?? new FileInfo(KubeConfigDefaultLocation));
this.Initialize(k8SConfig, currentContext);
}

/// <summary>
/// Initializes a new instance of the <see cref="KubernetesClientConfiguration"/> from config file
/// </summary>
Expand All @@ -60,7 +49,7 @@ public static KubernetesClientConfiguration BuildConfigFromConfigFile(FileInfo k

var k8SConfig = LoadKubeConfig(kubeconfig);
var k8SConfiguration = new KubernetesClientConfiguration();
k8SConfiguration.Initialize(k8SConfig);
k8SConfiguration.Initialize(k8SConfig, currentContext);

if (!string.IsNullOrWhiteSpace(masterUrl))
{
Expand Down Expand Up @@ -200,7 +189,7 @@ private void SetUserDetails(K8SConfiguration k8SConfig, Context activeContext)
/// <summary>
/// Loads Kube Config
/// </summary>
/// <param name="config">Kube config file contents</param>
/// <param name="kubeconfig">Kube config file contents</param>
/// <returns>Instance of the <see cref="K8SConfiguration"/> class</returns>
private static K8SConfiguration LoadKubeConfig(FileInfo kubeconfig)
{
Expand Down
39 changes: 14 additions & 25 deletions src/KubernetesClientConfiguration.cs
Original file line number Diff line number Diff line change
@@ -1,78 +1,67 @@
using System.Security.Cryptography.X509Certificates;

namespace k8s
{
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using k8s.Exceptions;
using k8s.KubeConfigModels;
using YamlDotNet.Serialization;
using System.Runtime.InteropServices;

/// <summary>
/// Represents a set of kubernetes client configuration settings
/// Represents a set of kubernetes client configuration settings
/// </summary>
public partial class KubernetesClientConfiguration
{
public KubernetesClientConfiguration()
{
}

/// <summary>
/// Gets Host
/// Gets Host
/// </summary>
public string Host { get; set; }

/// <summary>
/// Gets SslCaCert
/// Gets SslCaCert
/// </summary>
public X509Certificate2 SslCaCert { get; set; }

/// <summary>
/// Gets ClientCertificateData
/// Gets ClientCertificateData
/// </summary>
public string ClientCertificateData { get; set; }

/// <summary>
/// Gets ClientCertificate Key
/// Gets ClientCertificate Key
/// </summary>
public string ClientCertificateKeyData { get; set; }

/// <summary>
/// Gets ClientCertificate filename
/// Gets ClientCertificate filename
/// </summary>
public string ClientCertificateFilePath { get; set; }

/// <summary>
/// Gets ClientCertificate Key filename
/// Gets ClientCertificate Key filename
/// </summary>
public string ClientKeyFilePath { get; set; }

/// <summary>
/// Gets a value indicating whether to skip ssl server cert validation
/// Gets a value indicating whether to skip ssl server cert validation
/// </summary>
public bool SkipTlsVerify { get; set; }

/// <summary>
/// Gets or sets the HTTP user agent.
/// Gets or sets the HTTP user agent.
/// </summary>
/// <value>Http user agent.</value>
public string UserAgent { get; set; }

/// <summary>
/// Gets or sets the username (HTTP basic authentication).
/// Gets or sets the username (HTTP basic authentication).
/// </summary>
/// <value>The username.</value>
public string Username { get; set; }

/// <summary>
/// Gets or sets the password (HTTP basic authentication).
/// Gets or sets the password (HTTP basic authentication).
/// </summary>
/// <value>The password.</value>
public string Password { get; set; }

/// <summary>
/// Gets or sets the access token for OAuth2 authentication.
/// Gets or sets the access token for OAuth2 authentication.
/// </summary>
/// <value>The access token.</value>
public string AccessToken { get; set; }
Expand Down
4 changes: 2 additions & 2 deletions tests/CertUtilsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class CertUtilsTests
public void LoadFromFiles()
{
var fi = new FileInfo(kubeConfigFileName);
var cfg = new KubernetesClientConfiguration(fi, "federal-context");
var cfg = KubernetesClientConfiguration.BuildConfigFromConfigFile(fi, "federal-context");

// Just validate that this doesn't throw and private key is non-null
var cert = CertUtils.GeneratePfx(cfg);
Expand All @@ -33,7 +33,7 @@ public void LoadFromFiles()
public void LoadFromInlineData()
{
var fi = new FileInfo(kubeConfigFileName);
var cfg = new KubernetesClientConfiguration(fi, "victorian-context");
var cfg = KubernetesClientConfiguration.BuildConfigFromConfigFile(fi, "victorian-context");

// Just validate that this doesn't throw and private key is non-null
var cert = CertUtils.GeneratePfx(cfg);
Expand Down
Loading