...

Source file src/github.com/in-toto/in-toto-golang/cmd/sign.go

Documentation: github.com/in-toto/in-toto-golang/cmd

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  
     6  	intoto "github.com/in-toto/in-toto-golang/in_toto"
     7  	"github.com/spf13/cobra"
     8  )
     9  
    10  var (
    11  	outputPath string
    12  	verifyFile bool
    13  )
    14  
    15  var signCmd = &cobra.Command{
    16  	Use:   "sign",
    17  	Short: "Provides command line interface to sign in-toto link or layout metadata",
    18  	Long:  `Provides command line interface to sign in-toto link or layout metadata`,
    19  	RunE:  sign,
    20  }
    21  
    22  func init() {
    23  	rootCmd.AddCommand(signCmd)
    24  
    25  	signCmd.Flags().StringVarP(
    26  		&outputPath,
    27  		"output",
    28  		"o",
    29  		"",
    30  		`Path to store metadata file after signing`,
    31  	)
    32  
    33  	signCmd.Flags().StringVarP(
    34  		&layoutPath,
    35  		"file",
    36  		"f",
    37  		"",
    38  		`Path to link or layout file to be signed or verified.`,
    39  	)
    40  
    41  	signCmd.Flags().StringVarP(
    42  		&keyPath,
    43  		"key",
    44  		"k",
    45  		"",
    46  		`Path to PEM formatted private key used to sign the passed 
    47  root layout's signature(s). Passing exactly one key using
    48  '--key' is required.`,
    49  	)
    50  
    51  	signCmd.Flags().BoolVar(
    52  		&verifyFile,
    53  		"verify",
    54  		false,
    55  		"Verify signature of signed file",
    56  	)
    57  
    58  	signCmd.MarkFlagRequired("file")
    59  	signCmd.MarkFlagRequired("key")
    60  }
    61  
    62  func sign(cmd *cobra.Command, args []string) error {
    63  	layoutEnv, err := intoto.LoadMetadata(layoutPath)
    64  	if err != nil {
    65  		return fmt.Errorf("failed to load layout at %s: %w", layoutPath, err)
    66  	}
    67  
    68  	key = intoto.Key{}
    69  	if err := key.LoadKeyDefaults(keyPath); err != nil {
    70  		return fmt.Errorf("invalid key at %s: %w", keyPath, err)
    71  	}
    72  
    73  	if verifyFile {
    74  		if err := layoutEnv.VerifySignature(key); err != nil {
    75  			return fmt.Errorf("signature verification failed: %w", err)
    76  		}
    77  		return nil
    78  	}
    79  
    80  	if len(outputPath) == 0 {
    81  		outputPath = layoutPath
    82  	}
    83  
    84  	if err := layoutEnv.Sign(key); err != nil {
    85  		return err
    86  	}
    87  	return layoutEnv.Dump(outputPath)
    88  }
    89  

View as plain text