|
| 1 | +using System; |
| 2 | +using System.Diagnostics; |
| 3 | +using System.Net.Http.Headers; |
| 4 | +using System.Threading; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using k8s.Exceptions; |
| 7 | +using Microsoft.Rest; |
| 8 | +using Newtonsoft.Json.Linq; |
| 9 | + |
| 10 | +namespace k8s.Authentication |
| 11 | +{ |
| 12 | + public class GcpTokenProvider : ITokenProvider |
| 13 | + { |
| 14 | + private readonly string _gcloudCli; |
| 15 | + private string _token; |
| 16 | + private DateTime _expiry; |
| 17 | + |
| 18 | + public GcpTokenProvider(string gcloudCli) |
| 19 | + { |
| 20 | + _gcloudCli = gcloudCli; |
| 21 | + } |
| 22 | + |
| 23 | + public async Task<AuthenticationHeaderValue> GetAuthenticationHeaderAsync(CancellationToken cancellationToken) |
| 24 | + { |
| 25 | + if (DateTime.UtcNow.AddSeconds(30) > _expiry) |
| 26 | + { |
| 27 | + await RefreshToken(); |
| 28 | + } |
| 29 | + return new AuthenticationHeaderValue("Bearer", _token); |
| 30 | + } |
| 31 | + |
| 32 | + private async Task RefreshToken() |
| 33 | + { |
| 34 | + var process = new Process |
| 35 | + { |
| 36 | + StartInfo = |
| 37 | + { |
| 38 | + FileName = _gcloudCli, |
| 39 | + Arguments = "config config-helper --format=json", |
| 40 | + UseShellExecute = false, |
| 41 | + CreateNoWindow = true, |
| 42 | + RedirectStandardOutput = true, |
| 43 | + RedirectStandardError = true |
| 44 | + }, |
| 45 | + EnableRaisingEvents = true |
| 46 | + }; |
| 47 | + var tcs = new TaskCompletionSource<bool>(); |
| 48 | + process.Exited += (sender, arg) => |
| 49 | + { |
| 50 | + tcs.SetResult(true); |
| 51 | + }; |
| 52 | + process.Start(); |
| 53 | + var output = process.StandardOutput.ReadToEndAsync(); |
| 54 | + var err = process.StandardError.ReadToEndAsync(); |
| 55 | + |
| 56 | + await Task.WhenAll(tcs.Task, output, err); |
| 57 | + |
| 58 | + if (process.ExitCode != 0) |
| 59 | + { |
| 60 | + throw new KubernetesClientException($"Unable to obtain a token via gcloud command. Error code {process.ExitCode}. \n {err}"); |
| 61 | + } |
| 62 | + |
| 63 | + var json = JToken.Parse(await output); |
| 64 | + _token = json["credential"]["access_token"].Value<string>(); |
| 65 | + _expiry = json["credential"]["token_expiry"].Value<DateTime>(); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments