blob: 7d69a20f54edcc0c3545996a69d38c8f7d45f783 [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Tim Windelschmidtf0ec0f62023-07-17 13:43:38 +02004package main
5
6import (
7 "crypto/x509"
8 "encoding/pem"
Tim Windelschmidtd5f851b2024-04-23 14:59:37 +02009 "errors"
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020010 "fmt"
Tim Windelschmidtf0ec0f62023-07-17 13:43:38 +020011 "log"
12 "os"
13
14 "github.com/spf13/cobra"
15
16 "source.monogon.dev/metropolis/cli/metroctl/core"
17)
18
19func init() {
20 certCmd.AddCommand(certExportCmd)
21
22 rootCmd.AddCommand(certCmd)
23}
24
25var certCmd = &cobra.Command{
26 Short: "Certificate utilities",
27 Use: "cert",
28}
29
30var certExportCmd = &cobra.Command{
31 Short: "Exports certificates for use in other programs",
32 Use: "export",
33 Example: "metroctl cert export",
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020034 RunE: func(cmd *cobra.Command, args []string) error {
Tim Windelschmidtf0ec0f62023-07-17 13:43:38 +020035 ocert, opkey, err := core.GetOwnerCredentials(flags.configPath)
Tim Windelschmidt513df182024-04-18 23:44:50 +020036 if errors.Is(err, core.ErrNoCredentials) {
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020037 return fmt.Errorf("you have to take ownership of the cluster first: %w", err)
Tim Windelschmidtf0ec0f62023-07-17 13:43:38 +020038 }
39
40 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(opkey)
41 if err != nil {
42 // We explicitly pass an Ed25519 private key in, so this can't happen
43 panic(err)
44 }
45
46 if err := os.WriteFile("owner.crt", pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ocert.Raw}), 0755); err != nil {
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020047 return err
Tim Windelschmidtf0ec0f62023-07-17 13:43:38 +020048 }
49
50 if err := os.WriteFile("owner.key", pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}), 0755); err != nil {
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020051 return err
Tim Windelschmidtf0ec0f62023-07-17 13:43:38 +020052 }
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020053
Tim Windelschmidtf0ec0f62023-07-17 13:43:38 +020054 log.Println("Wrote files to current dir: cert.pem, key.pem")
Tim Windelschmidt0b4fb8c2024-09-18 17:34:23 +020055 return nil
Tim Windelschmidtf0ec0f62023-07-17 13:43:38 +020056 },
Tim Windelschmidtfc6e1cf2024-09-18 17:34:07 +020057 Args: PrintUsageOnWrongArgs(cobra.NoArgs),
Tim Windelschmidtf0ec0f62023-07-17 13:43:38 +020058}