blob: 9b3226edabdaddef4301a34adc335a87f33f45c0 [file] [log] [blame]
Lorenz Brun705a4022021-12-23 11:51:06 +01001package main
2
3import (
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 Brun20d1dd12022-07-01 12:21:42 +000012 clientauthentication "k8s.io/client-go/pkg/apis/clientauthentication/v1"
Serge Bazanskicf23ebc2023-03-14 17:02:04 +010013
14 "source.monogon.dev/metropolis/cli/metroctl/core"
Lorenz Brun705a4022021-12-23 11:51:06 +010015)
16
17var 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
21authenticate client-go based callers including kubectl against a Metropolis
22cluster. This should never be directly called by end users.`,
Serge Bazanski1f8cad72023-03-20 16:58:10 +010023 Args: cobra.ExactArgs(0),
24 Hidden: true,
25 Run: doK8sCredPlugin,
Lorenz Brun705a4022021-12-23 11:51:06 +010026}
27
28func doK8sCredPlugin(cmd *cobra.Command, args []string) {
Serge Bazanskicf23ebc2023-03-14 17:02:04 +010029 cert, key, err := core.GetOwnerCredentials(flags.configPath)
30 if err == core.NoCredentialsError {
Lorenz Brun705a4022021-12-23 11:51:06 +010031 log.Fatal("No credentials found on your machine")
32 }
33 if err != nil {
34 log.Fatalf("failed to get Metropolis credentials: %v", err)
35 }
36
37 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(key)
38 if err != nil {
39 // We explicitly pass an Ed25519 private key in, so this can't happen
40 panic(err)
41 }
42
43 cred := clientauthentication.ExecCredential{
44 TypeMeta: metav1.TypeMeta{
45 APIVersion: clientauthentication.SchemeGroupVersion.String(),
46 Kind: "ExecCredential",
47 },
48 Status: &clientauthentication.ExecCredentialStatus{
49 ClientCertificateData: string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})),
50 ClientKeyData: string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key})),
51 },
52 }
53 if err := json.NewEncoder(os.Stdout).Encode(cred); err != nil {
54 log.Fatalf("failed to encode ExecCredential: %v", err)
55 }
56}
57
58func init() {
59 rootCmd.AddCommand(k8scredpluginCmd)
60}