blob: 0054e702e119a652c928312e2172231d609c5f51 [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Lorenz Brun705a4022021-12-23 11:51:06 +01004package main
5
6import (
7 "crypto/x509"
8 "encoding/json"
9 "encoding/pem"
Tim Windelschmidtd5f851b2024-04-23 14:59:37 +020010 "errors"
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020011 "fmt"
Lorenz Brun705a4022021-12-23 11:51:06 +010012 "os"
13
14 "github.com/spf13/cobra"
15 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Lorenz Brun20d1dd12022-07-01 12:21:42 +000016 clientauthentication "k8s.io/client-go/pkg/apis/clientauthentication/v1"
Serge Bazanskicf23ebc2023-03-14 17:02:04 +010017
18 "source.monogon.dev/metropolis/cli/metroctl/core"
Lorenz Brun705a4022021-12-23 11:51:06 +010019)
20
21var k8scredpluginCmd = &cobra.Command{
22 Use: "k8scredplugin",
23 Short: "Kubernetes client-go credential plugin [internal use]",
24 Long: `This implements a Kubernetes client-go credential plugin to
25authenticate client-go based callers including kubectl against a Metropolis
26cluster. This should never be directly called by end users.`,
Tim Windelschmidtfc6e1cf2024-09-18 17:34:07 +020027 Args: PrintUsageOnWrongArgs(cobra.ExactArgs(0)),
Serge Bazanski1f8cad72023-03-20 16:58:10 +010028 Hidden: true,
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020029 RunE: func(cmd *cobra.Command, args []string) error {
30 cert, key, err := core.GetOwnerCredentials(flags.configPath)
31 if errors.Is(err, core.ErrNoCredentials) {
32 return fmt.Errorf("no credentials found on your machine")
33 }
34 if err != nil {
35 return fmt.Errorf("failed to get Metropolis credentials: %w", err)
36 }
Lorenz Brun705a4022021-12-23 11:51:06 +010037
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020038 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 }
Lorenz Brun705a4022021-12-23 11:51:06 +010043
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020044 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 return fmt.Errorf("failed to encode ExecCredential: %w", err)
56 }
57 return nil
58 },
Lorenz Brun705a4022021-12-23 11:51:06 +010059}
60
61func init() {
62 rootCmd.AddCommand(k8scredpluginCmd)
63}