blob: 605bc871557eaf0d96433c0249ba1b057c9f91f3 [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.`,
23 Args: cobra.ExactArgs(0),
24 Run: doK8sCredPlugin,
25}
26
27func doK8sCredPlugin(cmd *cobra.Command, args []string) {
Serge Bazanskicf23ebc2023-03-14 17:02:04 +010028 cert, key, err := core.GetOwnerCredentials(flags.configPath)
29 if err == core.NoCredentialsError {
Lorenz Brun705a4022021-12-23 11:51:06 +010030 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
57func init() {
58 rootCmd.AddCommand(k8scredpluginCmd)
59}