github.com/apptainer/singularity@v3.1.1+incompatible/cmd/internal/cli/sign.go (about)

     1  // Copyright (c) 2017-2019, Sylabs Inc. All rights reserved.
     2  // This software is licensed under a 3-clause BSD license. Please consult the
     3  // LICENSE.md file distributed with the sources of this project regarding your
     4  // rights to use or distribute this software.
     5  
     6  package cli
     7  
     8  import (
     9  	"fmt"
    10  	"os"
    11  
    12  	"github.com/spf13/cobra"
    13  	"github.com/sylabs/singularity/docs"
    14  	"github.com/sylabs/singularity/internal/pkg/sylog"
    15  	"github.com/sylabs/singularity/pkg/signing"
    16  )
    17  
    18  var (
    19  	privKey int // -k encryption key (index from 'keys list') specification
    20  )
    21  
    22  func init() {
    23  	SignCmd.Flags().SetInterspersed(false)
    24  
    25  	SignCmd.Flags().StringVarP(&keyServerURL, "url", "u", defaultKeyServer, "key server URL")
    26  	SignCmd.Flags().SetAnnotation("url", "envkey", []string{"URL"})
    27  	SignCmd.Flags().Uint32VarP(&sifGroupID, "groupid", "g", 0, "group ID to be signed")
    28  	SignCmd.Flags().Uint32VarP(&sifDescID, "id", "i", 0, "descriptor ID to be signed")
    29  	SignCmd.Flags().IntVarP(&privKey, "keyidx", "k", -1, "private key to use (index from 'keys list')")
    30  
    31  	SingularityCmd.AddCommand(SignCmd)
    32  }
    33  
    34  // SignCmd singularity sign
    35  var SignCmd = &cobra.Command{
    36  	DisableFlagsInUseLine: true,
    37  	Args:                  cobra.ExactArgs(1),
    38  	PreRun:                sylabsToken,
    39  
    40  	Run: func(cmd *cobra.Command, args []string) {
    41  		// args[0] contains image path
    42  		fmt.Printf("Signing image: %s\n", args[0])
    43  		if err := doSignCmd(args[0], keyServerURL); err != nil {
    44  			sylog.Errorf("signing container failed: %s", err)
    45  			os.Exit(2)
    46  		}
    47  		fmt.Printf("Signature created and applied to %v\n", args[0])
    48  	},
    49  
    50  	Use:     docs.SignUse,
    51  	Short:   docs.SignShort,
    52  	Long:    docs.SignLong,
    53  	Example: docs.SignExample,
    54  }
    55  
    56  func doSignCmd(cpath, url string) error {
    57  	if sifGroupID != 0 && sifDescID != 0 {
    58  		return fmt.Errorf("only one of -i or -g may be set")
    59  	}
    60  
    61  	var isGroup bool
    62  	var id uint32
    63  	if sifGroupID != 0 {
    64  		isGroup = true
    65  		id = sifGroupID
    66  	} else {
    67  		id = sifDescID
    68  	}
    69  
    70  	return signing.Sign(cpath, url, id, isGroup, privKey, authToken)
    71  }