|
| 1 | +package login |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/sha256" |
| 6 | + "crypto/x509" |
| 7 | + "encoding/json" |
| 8 | + "encoding/pem" |
| 9 | + "fmt" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/stackitcloud/stackit-cli/internal/pkg/cache" |
| 13 | + "k8s.io/client-go/rest" |
| 14 | + |
| 15 | + "github.com/stackitcloud/stackit-cli/internal/pkg/args" |
| 16 | + "github.com/stackitcloud/stackit-cli/internal/pkg/examples" |
| 17 | + "github.com/stackitcloud/stackit-cli/internal/pkg/services/ske/client" |
| 18 | + |
| 19 | + "github.com/spf13/cobra" |
| 20 | + "github.com/stackitcloud/stackit-sdk-go/services/ske" |
| 21 | + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 22 | + "k8s.io/client-go/kubernetes/scheme" |
| 23 | + clientauthenticationv1 "k8s.io/client-go/pkg/apis/clientauthentication/v1" |
| 24 | + "k8s.io/client-go/tools/auth/exec" |
| 25 | + "k8s.io/client-go/tools/clientcmd" |
| 26 | +) |
| 27 | + |
| 28 | +type inputModel struct { |
| 29 | + ProjectId string |
| 30 | + ClusterName string |
| 31 | + CacheKey string |
| 32 | +} |
| 33 | + |
| 34 | +func NewCmd() *cobra.Command { |
| 35 | + cmd := &cobra.Command{ |
| 36 | + Use: "login", |
| 37 | + Short: "login plugin for kubectl", |
| 38 | + Long: "login plugin for kubectl to create a short-lived kubeconfig to authenticate against a STACKIT Kubernetes Engine (SKE) cluster. To get a kubeconfig to use with the login command use the 'kubeconfig create' command", |
| 39 | + Args: args.NoArgs, |
| 40 | + Example: examples.Build( |
| 41 | + examples.NewExample( |
| 42 | + "login to a SKE cluster specified in the kubeconfig", |
| 43 | + "$ kubectl get pod"), |
| 44 | + ), |
| 45 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 46 | + ctx := context.Background() |
| 47 | + |
| 48 | + model, err := parseInput() |
| 49 | + if err != nil { |
| 50 | + return fmt.Errorf("login SKE kubeconfig: parseInput: %w", err) |
| 51 | + } |
| 52 | + |
| 53 | + // Configure API client |
| 54 | + apiClient, err := client.ConfigureClient(cmd) |
| 55 | + if err != nil { |
| 56 | + return err |
| 57 | + } |
| 58 | + |
| 59 | + kubeconfig := getCachedKubeConfig(model.CacheKey) |
| 60 | + |
| 61 | + if kubeconfig == nil { |
| 62 | + return getCacheAndOutputKubeconfig(ctx, cmd, apiClient, model, false, nil) |
| 63 | + } |
| 64 | + |
| 65 | + certPem, _ := pem.Decode(kubeconfig.CertData) |
| 66 | + if certPem == nil { |
| 67 | + _ = cache.DeleteObject(model.CacheKey) |
| 68 | + return getCacheAndOutputKubeconfig(ctx, cmd, apiClient, model, false, nil) |
| 69 | + } |
| 70 | + |
| 71 | + certificate, err := x509.ParseCertificate(certPem.Bytes) |
| 72 | + if err != nil { |
| 73 | + _ = cache.DeleteObject(model.CacheKey) |
| 74 | + return getCacheAndOutputKubeconfig(ctx, cmd, apiClient, model, false, nil) |
| 75 | + } |
| 76 | + |
| 77 | + if time.Now().After(certificate.NotAfter.UTC()) { |
| 78 | + // cert expired, request new |
| 79 | + _ = cache.DeleteObject(model.CacheKey) |
| 80 | + return getCacheAndOutputKubeconfig(ctx, cmd, apiClient, model, false, nil) |
| 81 | + } else if time.Now().Add(time.Minute * 15).After(certificate.NotAfter.UTC()) { |
| 82 | + // cert expires in 15min, refresh |
| 83 | + return getCacheAndOutputKubeconfig(ctx, cmd, apiClient, model, true, kubeconfig) |
| 84 | + } |
| 85 | + |
| 86 | + if err := output(cmd, model.CacheKey, kubeconfig); err != nil { |
| 87 | + return err |
| 88 | + } |
| 89 | + return nil |
| 90 | + }, |
| 91 | + } |
| 92 | + return cmd |
| 93 | +} |
| 94 | + |
| 95 | +func parseInput() (*inputModel, error) { |
| 96 | + obj, _, err := exec.LoadExecCredentialFromEnv() |
| 97 | + if err != nil { |
| 98 | + return nil, fmt.Errorf("LoadExecCredentialFromEnv: %w", err) |
| 99 | + } |
| 100 | + |
| 101 | + if err := clientauthenticationv1.AddToScheme(scheme.Scheme); err != nil { |
| 102 | + return nil, err |
| 103 | + } |
| 104 | + |
| 105 | + obj, err = scheme.Scheme.ConvertToVersion(obj, clientauthenticationv1.SchemeGroupVersion) |
| 106 | + if err != nil { |
| 107 | + return nil, fmt.Errorf("ConvertToVersion: %w", err) |
| 108 | + } |
| 109 | + |
| 110 | + execCredential, ok := obj.(*clientauthenticationv1.ExecCredential) |
| 111 | + if !ok { |
| 112 | + return nil, fmt.Errorf("Conversion to ExecCredential failed") |
| 113 | + } |
| 114 | + if execCredential == nil || execCredential.Spec.Cluster == nil { |
| 115 | + return nil, fmt.Errorf("ExecCredential contains not all needed fields") |
| 116 | + } |
| 117 | + config := &SKEClusterConfig{} |
| 118 | + err = json.Unmarshal(execCredential.Spec.Cluster.Config.Raw, config) |
| 119 | + if err != nil { |
| 120 | + return nil, fmt.Errorf("unmarshal: %w", err) |
| 121 | + } |
| 122 | + |
| 123 | + return &inputModel{ |
| 124 | + ClusterName: config.ClusterName, |
| 125 | + ProjectId: config.STACKITProjectID, |
| 126 | + CacheKey: fmt.Sprintf("ske-login-%x", sha256.Sum256([]byte(execCredential.Spec.Cluster.Server))), |
| 127 | + }, nil |
| 128 | +} |
| 129 | + |
| 130 | +func buildRequest(ctx context.Context, apiClient *ske.APIClient, model *inputModel) ske.ApiCreateKubeconfigRequest { |
| 131 | + req := apiClient.CreateKubeconfig(ctx, model.ProjectId, model.ClusterName) |
| 132 | + expirationSeconds := "1800" // 30 min |
| 133 | + |
| 134 | + return req.CreateKubeconfigPayload(ske.CreateKubeconfigPayload{ExpirationSeconds: &expirationSeconds}) |
| 135 | +} |
| 136 | + |
| 137 | +func parseKubeConfigToExecCredential(kubeconfig *rest.Config) (*clientauthenticationv1.ExecCredential, error) { |
| 138 | + certPem, _ := pem.Decode(kubeconfig.CertData) |
| 139 | + if certPem == nil { |
| 140 | + return nil, fmt.Errorf("login SKE kubeconfig") |
| 141 | + } |
| 142 | + |
| 143 | + certificate, err := x509.ParseCertificate(certPem.Bytes) |
| 144 | + if err != nil { |
| 145 | + return nil, fmt.Errorf("login SKE kubeconfig: %w", err) |
| 146 | + } |
| 147 | + |
| 148 | + outputExecCredential := clientauthenticationv1.ExecCredential{ |
| 149 | + TypeMeta: v1.TypeMeta{ |
| 150 | + APIVersion: clientauthenticationv1.SchemeGroupVersion.String(), |
| 151 | + Kind: "ExecCredential", |
| 152 | + }, |
| 153 | + Status: &clientauthenticationv1.ExecCredentialStatus{ |
| 154 | + ExpirationTimestamp: &v1.Time{Time: certificate.NotAfter.Add(-time.Minute * 15)}, |
| 155 | + ClientCertificateData: string(kubeconfig.CertData), |
| 156 | + ClientKeyData: string(kubeconfig.KeyData), |
| 157 | + }, |
| 158 | + } |
| 159 | + return &outputExecCredential, nil |
| 160 | +} |
| 161 | + |
| 162 | +func getCachedKubeConfig(key string) *rest.Config { |
| 163 | + cachedKubeconfig, err := cache.GetObject(key) |
| 164 | + if err != nil { |
| 165 | + return nil |
| 166 | + } |
| 167 | + |
| 168 | + restConfig, err := clientcmd.RESTConfigFromKubeConfig(cachedKubeconfig) |
| 169 | + if err != nil { |
| 170 | + return nil |
| 171 | + } |
| 172 | + |
| 173 | + return restConfig |
| 174 | +} |
| 175 | + |
| 176 | +type SKEClusterConfig struct { |
| 177 | + STACKITProjectID string `json:"stackitProjectId"` |
| 178 | + ClusterName string `json:"clusterName"` |
| 179 | +} |
| 180 | + |
| 181 | +func getCacheAndOutputKubeconfig(ctx context.Context, cmd *cobra.Command, apiClient *ske.APIClient, model *inputModel, refresh bool, oldKubeconfig *rest.Config) error { |
| 182 | + req := buildRequest(ctx, apiClient, model) |
| 183 | + kubeconfigResponse, err := req.Execute() |
| 184 | + if err != nil { |
| 185 | + if refresh { |
| 186 | + return output(cmd, model.CacheKey, oldKubeconfig) |
| 187 | + } |
| 188 | + return fmt.Errorf("login SKE kubeconfig: requesting kubeconfig: %w", err) |
| 189 | + } |
| 190 | + |
| 191 | + kubeconfig, err := clientcmd.RESTConfigFromKubeConfig([]byte(*kubeconfigResponse.Kubeconfig)) |
| 192 | + if err != nil { |
| 193 | + if refresh { |
| 194 | + return output(cmd, model.CacheKey, oldKubeconfig) |
| 195 | + } |
| 196 | + return fmt.Errorf("login SKE kubeconfig: parsing kubeconfig: %w", err) |
| 197 | + } |
| 198 | + if err = cache.PutObject(model.CacheKey, []byte(*kubeconfigResponse.Kubeconfig)); err != nil { |
| 199 | + if refresh { |
| 200 | + return output(cmd, model.CacheKey, oldKubeconfig) |
| 201 | + } |
| 202 | + return fmt.Errorf("login SKE kubeconfig: caching kubeconfig: %w", err) |
| 203 | + } |
| 204 | + |
| 205 | + return output(cmd, model.CacheKey, kubeconfig) |
| 206 | +} |
| 207 | + |
| 208 | +func output(cmd *cobra.Command, cacheKey string, kubeconfig *rest.Config) error { |
| 209 | + outputExecCredential, err := parseKubeConfigToExecCredential(kubeconfig) |
| 210 | + if err != nil { |
| 211 | + _ = cache.DeleteObject(cacheKey) |
| 212 | + return fmt.Errorf("login SKE kubeconfig: converting to ExecCredential: %w", err) |
| 213 | + } |
| 214 | + |
| 215 | + output, err := json.Marshal(outputExecCredential) |
| 216 | + if err != nil { |
| 217 | + _ = cache.DeleteObject(cacheKey) |
| 218 | + return fmt.Errorf("login SKE kubeconfig: marshal ExecCredential: %w", err) |
| 219 | + } |
| 220 | + |
| 221 | + cmd.Print(string(output)) |
| 222 | + return nil |
| 223 | +} |
0 commit comments