Skip to content

Commit

Permalink
Changes to support xamarin. (#200)
Browse files Browse the repository at this point in the history
  • Loading branch information
JonJam authored and k8s-ci-robot committed Sep 10, 2018
1 parent 397a582 commit 3cee7fb
Show file tree
Hide file tree
Showing 3 changed files with 119 additions and 15 deletions.
91 changes: 85 additions & 6 deletions src/KubernetesClient/Kubernetes.ConfigInit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,68 @@ namespace k8s
{
public partial class Kubernetes
{
#if MONOANDROID8_1
/// <summary>
/// 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.
/// </param>
/// <param name="handlers">
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public Kubernetes(KubernetesClientConfiguration config, params DelegatingHandler[] handlers) : this(new Xamarin.Android.Net.AndroidClientHandler(), handlers)
{
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);
}

CaCert = config.SslCaCert;
SkipTlsVerify = config.SkipTlsVerify;

if (BaseUri.Scheme == "https")
{
if (config.SkipTlsVerify)
{
System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
{
return true;
};
}
else
{
if (CaCert == null)
{
throw new KubeConfigException("a CA must be set when SkipTlsVerify === false");
}

using (System.IO.MemoryStream certStream = new System.IO.MemoryStream(config.SslCaCert.RawData))
{
Java.Security.Cert.Certificate cert = Java.Security.Cert.CertificateFactory.GetInstance("X509").GenerateCertificate(certStream);
Xamarin.Android.Net.AndroidClientHandler handler = (Xamarin.Android.Net.AndroidClientHandler)this.HttpClientHandler;

handler.TrustedCerts = new System.Collections.Generic.List<Java.Security.Cert.Certificate>()
{
cert
};
}
}
}

// set credentails for the kubernernet client
SetCredentials(config, HttpClientHandler);
}
#else
/// <summary>
/// Initializes a new instance of the <see cref="Kubernetes" /> class.
/// </summary>
Expand Down Expand Up @@ -48,6 +110,11 @@ public Kubernetes(KubernetesClientConfiguration config, params DelegatingHandler
#if NET452
((WebRequestHandler) HttpClientHandler).ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true;
#elif XAMARINIOS1_0
System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
{
return true;
};
#else
HttpClientHandler.ServerCertificateCustomValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true;
Expand All @@ -65,8 +132,14 @@ public Kubernetes(KubernetesClientConfiguration config, params DelegatingHandler
{
return Kubernetes.CertificateValidationCallBack(sender, CaCert, certificate, chain, sslPolicyErrors);
};
#elif XAMARINIOS1_0
System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
{
var cert = new X509Certificate2(certificate);
return Kubernetes.CertificateValidationCallBack(sender, CaCert, cert, chain, sslPolicyErrors);
};
#else
HttpClientHandler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
HttpClientHandler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
{
return Kubernetes.CertificateValidationCallBack(sender, CaCert, certificate, chain, sslPolicyErrors);
};
Expand All @@ -77,14 +150,15 @@ public Kubernetes(KubernetesClientConfiguration config, params DelegatingHandler
// set credentails for the kubernernet client
SetCredentials(config, HttpClientHandler);
}
#endif

private X509Certificate2 CaCert { get; }

private bool SkipTlsVerify { get; }

partial void CustomInitialize()
{
#if NET452
#if NET452 || XAMARINIOS1_0 || MONOANDROID8_1
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
#endif
AppendDelegatingHandler<WatcherDelegatingHandler>();
Expand Down Expand Up @@ -135,7 +209,12 @@ private void SetCredentials(KubernetesClientConfiguration config, HttpClientHand
Password = config.Password
};
}
// othwerwise set handler for clinet cert based auth

#if XAMARINIOS1_0 || MONOANDROID8_1
// handle.ClientCertificates is not implemented in Xamarin.
return;
#endif

if ((!string.IsNullOrWhiteSpace(config.ClientCertificateData) ||
!string.IsNullOrWhiteSpace(config.ClientCertificateFilePath)) &&
(!string.IsNullOrWhiteSpace(config.ClientCertificateKeyData) ||
Expand Down Expand Up @@ -181,10 +260,10 @@ public static bool CertificateValidationCallBack(
// add all your extra certificate chain
chain.ChainPolicy.ExtraStore.Add(caCert);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
var isValid = chain.Build((X509Certificate2) certificate);
var isValid = chain.Build((X509Certificate2)certificate);

var rootCert = chain.ChainElements[chain.ChainElements.Count - 1].Certificate;
isValid = isValid && rootCert.RawData.SequenceEqual(caCert.RawData);
isValid = isValid && rootCert.RawData.SequenceEqual(caCert.RawData);

return isValid;
}
Expand Down
18 changes: 15 additions & 3 deletions src/KubernetesClient/KubernetesClient.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Authors>The Kubernetes Project Authors</Authors>
<Copyright>2017 The Kubernetes Project Authors</Copyright>
Expand All @@ -9,7 +9,7 @@
<PackageIconUrl>https://raw.githubusercontent.com/kubernetes/kubernetes/master/logo/logo.png</PackageIconUrl>
<PackageTags>kubernetes;docker;containers;</PackageTags>

<TargetFrameworks>netstandard1.4;net452;netcoreapp2.1</TargetFrameworks>
<TargetFrameworks>netstandard1.4;net452;netcoreapp2.1;xamarinios10;monoandroid81</TargetFrameworks>
<TargetFrameworks Condition="'$(OS)' != 'Windows_NT'">netstandard1.4;netcoreapp2.1</TargetFrameworks>
<RootNamespace>k8s</RootNamespace>
<SignAssembly>true</SignAssembly>
Expand All @@ -24,6 +24,7 @@
<PackageReference Include="Portable.BouncyCastle" Version="1.8.1.3" />
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="1.1.2" />
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.10" />
<PackageReference Include="MSBuild.Sdk.Extras" Version="1.4.0" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
<PackageReference Include="System.ValueTuple" Version="4.4.0" />
<PackageReference Include="YamlDotNet.Signed" Version="4.2.3" />
Expand All @@ -34,4 +35,15 @@
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard1.4'">
<PackageReference Include="System.Net.WebSockets.Client" Version="4.3.2" />
</ItemGroup>
</Project>
<ItemGroup Condition="'$(TargetFramework)' == 'xamarinios10'">
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="Xamarin.iOS" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'monoandroid81'">
<Reference Include="Mono.Android" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.Serialization" />
</ItemGroup>
<Import Project="$(MSBuildSDKExtrasTargets)" Condition="Exists('$(MSBuildSDKExtrasTargets)')" />
</Project>
25 changes: 19 additions & 6 deletions src/KubernetesClient/KubernetesClientConfiguration.ConfigFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,14 +239,26 @@ private void SetUserDetails(K8SConfiguration k8SConfig, Context activeContext)
userCredentialsFound = true;
}

if (userDetails.UserCredentials.AuthProvider != null) {
if (userDetails.UserCredentials.AuthProvider != null)
{
if (userDetails.UserCredentials.AuthProvider.Name == "azure" &&
userDetails.UserCredentials.AuthProvider.Config != null &&
userDetails.UserCredentials.AuthProvider.Config.ContainsKey("access-token")) {
userDetails.UserCredentials.AuthProvider.Config.ContainsKey("access-token"))
{
var config = userDetails.UserCredentials.AuthProvider.Config;
if (config.ContainsKey("expires-on")) {
var expires = DateTimeOffset.FromUnixTimeSeconds(Int32.Parse(config["expires-on"]));
if (DateTimeOffset.Compare(expires, DateTimeOffset.Now) <= 0) {
if (config.ContainsKey("expires-on"))
{
var expiresOn = Int32.Parse(config["expires-on"]);
DateTimeOffset expires;
#if NET452
var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
expires = epoch.AddSeconds(expiresOn);
#else
expires = DateTimeOffset.FromUnixTimeSeconds(expiresOn);
#endif

if (DateTimeOffset.Compare(expires, DateTimeOffset.Now) <= 0)
{
var tenantId = config["tenant-id"];
var clientId = config["client-id"];
var apiServerId = config["apiserver-id"];
Expand All @@ -267,7 +279,8 @@ private void SetUserDetails(K8SConfiguration k8SConfig, Context activeContext)
}
}

public static string RenewAzureToken(string tenantId, string clientId, string apiServerId, string refresh) {
public static string RenewAzureToken(string tenantId, string clientId, string apiServerId, string refresh)
{
throw new KubeConfigException("Refresh not supported.");
}

Expand Down

0 comments on commit 3cee7fb

Please sign in to comment.