blob: 50bf4746947a80040a8cceb1bbc5447adf005cb7 [file] [log] [blame]
Lorenz Brun705a4022021-12-23 11:51:06 +01001package main
2
3import (
4 "crypto/x509"
5 "encoding/json"
6 "encoding/pem"
Tim Windelschmidtd5f851b2024-04-23 14:59:37 +02007 "errors"
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +02008 "fmt"
Lorenz Brun705a4022021-12-23 11:51:06 +01009 "os"
10
11 "github.com/spf13/cobra"
12 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Lorenz Brun20d1dd12022-07-01 12:21:42 +000013 clientauthentication "k8s.io/client-go/pkg/apis/clientauthentication/v1"
Serge Bazanskicf23ebc2023-03-14 17:02:04 +010014
15 "source.monogon.dev/metropolis/cli/metroctl/core"
Lorenz Brun705a4022021-12-23 11:51:06 +010016)
17
18var k8scredpluginCmd = &cobra.Command{
19 Use: "k8scredplugin",
20 Short: "Kubernetes client-go credential plugin [internal use]",
21 Long: `This implements a Kubernetes client-go credential plugin to
22authenticate client-go based callers including kubectl against a Metropolis
23cluster. This should never be directly called by end users.`,
Tim Windelschmidtfc6e1cf2024-09-18 17:34:07 +020024 Args: PrintUsageOnWrongArgs(cobra.ExactArgs(0)),
Serge Bazanski1f8cad72023-03-20 16:58:10 +010025 Hidden: true,
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020026 RunE: func(cmd *cobra.Command, args []string) error {
27 cert, key, err := core.GetOwnerCredentials(flags.configPath)
28 if errors.Is(err, core.ErrNoCredentials) {
29 return fmt.Errorf("no credentials found on your machine")
30 }
31 if err != nil {
32 return fmt.Errorf("failed to get Metropolis credentials: %w", err)
33 }
Lorenz Brun705a4022021-12-23 11:51:06 +010034
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020035 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(key)
36 if err != nil {
37 // We explicitly pass an Ed25519 private key in, so this can't happen
38 panic(err)
39 }
Lorenz Brun705a4022021-12-23 11:51:06 +010040
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020041 cred := clientauthentication.ExecCredential{
42 TypeMeta: metav1.TypeMeta{
43 APIVersion: clientauthentication.SchemeGroupVersion.String(),
44 Kind: "ExecCredential",
45 },
46 Status: &clientauthentication.ExecCredentialStatus{
47 ClientCertificateData: string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})),
48 ClientKeyData: string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key})),
49 },
50 }
51 if err := json.NewEncoder(os.Stdout).Encode(cred); err != nil {
52 return fmt.Errorf("failed to encode ExecCredential: %w", err)
53 }
54 return nil
55 },
Lorenz Brun705a4022021-12-23 11:51:06 +010056}
57
58func init() {
59 rootCmd.AddCommand(k8scredpluginCmd)
60}