Lorenz Brun | 705a402 | 2021-12-23 11:51:06 +0100 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "crypto/x509" |
| 5 | "encoding/json" |
| 6 | "encoding/pem" |
| 7 | "log" |
| 8 | "os" |
| 9 | |
| 10 | "github.com/spf13/cobra" |
| 11 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
Lorenz Brun | 20d1dd1 | 2022-07-01 12:21:42 +0000 | [diff] [blame] | 12 | clientauthentication "k8s.io/client-go/pkg/apis/clientauthentication/v1" |
Serge Bazanski | cf23ebc | 2023-03-14 17:02:04 +0100 | [diff] [blame] | 13 | |
| 14 | "source.monogon.dev/metropolis/cli/metroctl/core" |
Lorenz Brun | 705a402 | 2021-12-23 11:51:06 +0100 | [diff] [blame] | 15 | ) |
| 16 | |
| 17 | var k8scredpluginCmd = &cobra.Command{ |
| 18 | Use: "k8scredplugin", |
| 19 | Short: "Kubernetes client-go credential plugin [internal use]", |
| 20 | Long: `This implements a Kubernetes client-go credential plugin to |
| 21 | authenticate client-go based callers including kubectl against a Metropolis |
| 22 | cluster. This should never be directly called by end users.`, |
| 23 | Args: cobra.ExactArgs(0), |
| 24 | Run: doK8sCredPlugin, |
| 25 | } |
| 26 | |
| 27 | func doK8sCredPlugin(cmd *cobra.Command, args []string) { |
Serge Bazanski | cf23ebc | 2023-03-14 17:02:04 +0100 | [diff] [blame] | 28 | cert, key, err := core.GetOwnerCredentials(flags.configPath) |
| 29 | if err == core.NoCredentialsError { |
Lorenz Brun | 705a402 | 2021-12-23 11:51:06 +0100 | [diff] [blame] | 30 | log.Fatal("No credentials found on your machine") |
| 31 | } |
| 32 | if err != nil { |
| 33 | log.Fatalf("failed to get Metropolis credentials: %v", err) |
| 34 | } |
| 35 | |
| 36 | pkcs8Key, err := x509.MarshalPKCS8PrivateKey(key) |
| 37 | if err != nil { |
| 38 | // We explicitly pass an Ed25519 private key in, so this can't happen |
| 39 | panic(err) |
| 40 | } |
| 41 | |
| 42 | cred := clientauthentication.ExecCredential{ |
| 43 | TypeMeta: metav1.TypeMeta{ |
| 44 | APIVersion: clientauthentication.SchemeGroupVersion.String(), |
| 45 | Kind: "ExecCredential", |
| 46 | }, |
| 47 | Status: &clientauthentication.ExecCredentialStatus{ |
| 48 | ClientCertificateData: string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})), |
| 49 | ClientKeyData: string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key})), |
| 50 | }, |
| 51 | } |
| 52 | if err := json.NewEncoder(os.Stdout).Encode(cred); err != nil { |
| 53 | log.Fatalf("failed to encode ExecCredential: %v", err) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | func init() { |
| 58 | rootCmd.AddCommand(k8scredpluginCmd) |
| 59 | } |