blob: 8d84a9e19581895f4169a4c2c27521dd284d2a4e [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"
Lorenz Brun705a4022021-12-23 11:51:06 +01008 "log"
9 "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,
26 Run: doK8sCredPlugin,
Lorenz Brun705a4022021-12-23 11:51:06 +010027}
28
29func doK8sCredPlugin(cmd *cobra.Command, args []string) {
Serge Bazanskicf23ebc2023-03-14 17:02:04 +010030 cert, key, err := core.GetOwnerCredentials(flags.configPath)
Tim Windelschmidt513df182024-04-18 23:44:50 +020031 if errors.Is(err, core.ErrNoCredentials) {
Lorenz Brun705a4022021-12-23 11:51:06 +010032 log.Fatal("No credentials found on your machine")
33 }
34 if err != nil {
35 log.Fatalf("failed to get Metropolis credentials: %v", err)
36 }
37
38 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(key)
39 if err != nil {
40 // We explicitly pass an Ed25519 private key in, so this can't happen
41 panic(err)
42 }
43
44 cred := clientauthentication.ExecCredential{
45 TypeMeta: metav1.TypeMeta{
46 APIVersion: clientauthentication.SchemeGroupVersion.String(),
47 Kind: "ExecCredential",
48 },
49 Status: &clientauthentication.ExecCredentialStatus{
50 ClientCertificateData: string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})),
51 ClientKeyData: string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key})),
52 },
53 }
54 if err := json.NewEncoder(os.Stdout).Encode(cred); err != nil {
55 log.Fatalf("failed to encode ExecCredential: %v", err)
56 }
57}
58
59func init() {
60 rootCmd.AddCommand(k8scredpluginCmd)
61}