github.com/kubri/kubri@v0.5.1-0.20240317001612-bda2aaef967e/pkg/cmd/keys_create.go (about)

     1  package cmd
     2  
     3  import (
     4  	"errors"
     5  
     6  	"github.com/spf13/cobra"
     7  
     8  	"github.com/kubri/kubri/pkg/crypto/dsa"
     9  	"github.com/kubri/kubri/pkg/crypto/ed25519"
    10  	"github.com/kubri/kubri/pkg/crypto/pgp"
    11  	"github.com/kubri/kubri/pkg/crypto/rsa"
    12  	"github.com/kubri/kubri/pkg/secret"
    13  )
    14  
    15  func keysCreateCmd() *cobra.Command {
    16  	var name, email string
    17  
    18  	cmd := &cobra.Command{
    19  		Use:     "create",
    20  		Short:   "Create private keys",
    21  		Long:    "Create private keys for signing update packages. If keys already exist, this is a no-op.",
    22  		Aliases: []string{"c"},
    23  		Args:    cobra.NoArgs,
    24  		RunE: func(*cobra.Command, []string) error {
    25  			if err := createPrivateKey("dsa_key", dsa.NewPrivateKey, dsa.MarshalPrivateKey); err != nil {
    26  				return err
    27  			}
    28  			if err := createPrivateKey("ed25519_key", ed25519.NewPrivateKey, ed25519.MarshalPrivateKey); err != nil {
    29  				return err
    30  			}
    31  			if err := createPrivateKey("pgp_key", newPGPKey(name, email), pgp.MarshalPrivateKey); err != nil {
    32  				return err
    33  			}
    34  			return createPrivateKey("rsa_key", rsa.NewPrivateKey, rsa.MarshalPrivateKey)
    35  		},
    36  	}
    37  
    38  	cmd.Flags().StringVar(&name, "name", "", "your name for the PGP key")
    39  	cmd.Flags().StringVar(&email, "email", "", "your email for the PGP key")
    40  
    41  	return cmd
    42  }
    43  
    44  func newPGPKey(name, email string) func() (*pgp.PrivateKey, error) {
    45  	return func() (*pgp.PrivateKey, error) {
    46  		if name == "" && email == "" {
    47  			return nil, errors.New("generating PGP key requires either name or email")
    48  		}
    49  		return pgp.NewPrivateKey(name, email)
    50  	}
    51  }
    52  
    53  func createPrivateKey[PrivateKey any](
    54  	name string,
    55  	newKey func() (PrivateKey, error),
    56  	marshal func(PrivateKey) ([]byte, error),
    57  ) error {
    58  	if _, err := secret.Get(name); !errors.Is(err, secret.ErrKeyNotFound) {
    59  		return err
    60  	}
    61  	key, err := newKey()
    62  	if err != nil {
    63  		return err
    64  	}
    65  	b, err := marshal(key)
    66  	if err != nil {
    67  		return err
    68  	}
    69  	return secret.Put(name, b)
    70  }