align auth provider with go-client (#1415)

* remove unsupport provider

* fix build

* fix missing

* rm unused
This commit is contained in:
Boshi Lian
2023-10-02 08:38:46 -07:00
committed by GitHub
parent 2899a13cbf
commit da71e32d13
4 changed files with 2 additions and 143 deletions

View File

@@ -109,7 +109,6 @@
<Compile Include="..\KubernetesClient\Exceptions\KubernetesClientException.cs" /> <Compile Include="..\KubernetesClient\Exceptions\KubernetesClientException.cs" />
<Compile Include="..\KubernetesClient\Authentication\ExecTokenProvider.cs" /> <Compile Include="..\KubernetesClient\Authentication\ExecTokenProvider.cs" />
<Compile Include="..\KubernetesClient\Authentication\GcpTokenProvider.cs" />
<Compile Include="..\KubernetesClient\Authentication\OidcTokenProvider.cs" /> <Compile Include="..\KubernetesClient\Authentication\OidcTokenProvider.cs" />
<Compile Include="..\KubernetesClient\Authentication\TokenFileAuth.cs" /> <Compile Include="..\KubernetesClient\Authentication\TokenFileAuth.cs" />
<Compile Include="..\KubernetesClient\Authentication\BasicAuthenticationCredentials.cs" /> <Compile Include="..\KubernetesClient\Authentication\BasicAuthenticationCredentials.cs" />

View File

@@ -1,72 +0,0 @@
using k8s.Exceptions;
using System.Diagnostics;
using System.Net.Http.Headers;
namespace k8s.Authentication
{
public class GcpTokenProvider : ITokenProvider
{
private readonly string _gcloudCli;
private string _token;
private DateTime _expiry;
public GcpTokenProvider(string gcloudCli)
{
_gcloudCli = gcloudCli;
}
public async Task<AuthenticationHeaderValue> GetAuthenticationHeaderAsync(CancellationToken cancellationToken)
{
if (DateTime.UtcNow.AddSeconds(30) > _expiry)
{
await RefreshToken().ConfigureAwait(false);
}
return new AuthenticationHeaderValue("Bearer", _token);
}
private async Task RefreshToken()
{
var process = new Process
{
StartInfo =
{
FileName = _gcloudCli,
Arguments = "config config-helper --format=json",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
},
EnableRaisingEvents = true,
};
var tcs = new TaskCompletionSource<bool>();
process.Exited += (sender, arg) =>
{
tcs.SetResult(true);
};
process.Start();
var output = process.StandardOutput.ReadToEndAsync();
var err = process.StandardError.ReadToEndAsync();
await Task.WhenAll(tcs.Task, output, err).ConfigureAwait(false);
if (process.ExitCode != 0)
{
throw new KubernetesClientException($"Unable to obtain a token via gcloud command. Error code {process.ExitCode}. \n {err}");
}
dynamic json = JsonSerializer.Deserialize(await output.ConfigureAwait(false), new
{
credential = new
{
access_token = "",
token_expiry = DateTime.UtcNow,
},
}.GetType());
_token = json.credential.access_token;
_expiry = json.credential.token_expiry;
}
}
}

View File

@@ -384,45 +384,10 @@ namespace k8s
switch (userDetails.UserCredentials.AuthProvider.Name) switch (userDetails.UserCredentials.AuthProvider.Name)
{ {
case "azure": case "azure":
{ throw new Exception("Please use the https://github.com/Azure/kubelogin credential plugin instead. See https://kubernetes.io/docs/reference/access-authn-authz/authentication/#client-go-credential-plugins for further details`");
var config = userDetails.UserCredentials.AuthProvider.Config;
if (config.ContainsKey("expires-on"))
{
var expiresOn = int.Parse(config["expires-on"]);
DateTimeOffset expires;
expires = DateTimeOffset.FromUnixTimeSeconds(expiresOn);
if (DateTimeOffset.Compare(
expires,
DateTimeOffset.Now)
<= 0)
{
var tenantId = config["tenant-id"];
var clientId = config["client-id"];
var apiServerId = config["apiserver-id"];
var refresh = config["refresh-token"];
var newToken = RenewAzureToken(
tenantId,
clientId,
apiServerId,
refresh);
config["access-token"] = newToken;
}
}
AccessToken = config["access-token"];
userCredentialsFound = true;
break;
}
case "gcp": case "gcp":
{ throw new Exception("Please use the \"gke-gcloud-auth-plugin\" credential plugin instead. See https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke for further details");
// config
var config = userDetails.UserCredentials.AuthProvider.Config;
TokenProvider = new GcpTokenProvider(config["cmd-path"]);
userCredentialsFound = true;
break;
}
case "oidc": case "oidc":
{ {
@@ -487,11 +452,6 @@ namespace k8s
} }
} }
public static string RenewAzureToken(string tenantId, string clientId, string apiServerId, string refresh)
{
throw new KubeConfigException("Refresh not supported.");
}
public static Process CreateRunnableExternalProcess(ExternalExecution config, EventHandler<DataReceivedEventArgs> captureStdError = null) public static Process CreateRunnableExternalProcess(ExternalExecution config, EventHandler<DataReceivedEventArgs> captureStdError = null)
{ {
if (config == null) if (config == null)

View File

@@ -1,28 +0,0 @@
using FluentAssertions;
using k8s.Authentication;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace k8s.Tests
{
public class GcpTokenProviderTests
{
[OperatingSystemDependentFact(Exclude = OperatingSystems.OSX)]
public async Task GetToken()
{
var isWindows = Environment.OSVersion.Platform == PlatformID.Win32NT;
var cmd = Path.Combine(Directory.GetCurrentDirectory(), "assets", isWindows ? "mock-gcloud.cmd" : "mock-gcloud.sh");
if (!isWindows)
{
System.Diagnostics.Process.Start("chmod", $"+x {cmd}").WaitForExit();
}
var sut = new GcpTokenProvider(cmd);
var result = await sut.GetAuthenticationHeaderAsync(CancellationToken.None).ConfigureAwait(false);
result.Scheme.Should().Be("Bearer");
result.Parameter.Should().Be("ACCESS-TOKEN");
}
}
}