frostfs-node/cmd/frostfs-cli/modules/util/sign_bearer.go

64 lines
1.7 KiB
Go
Raw Permalink Normal View History

package util
import (
"os"
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-cli/internal/common"
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-cli/internal/commonflags"
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-cli/internal/key"
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
"github.com/spf13/cobra"
)
const (
signBearerJSONFlag = commonflags.JSON
)
var signBearerCmd = &cobra.Command{
Use: "bearer-token",
Short: "Sign bearer token to use it in requests",
Run: signBearerToken,
}
func initSignBearerCmd() {
commonflags.InitWithoutRPC(signBearerCmd)
flags := signBearerCmd.Flags()
flags.String(signFromFlag, "", "File with JSON or binary encoded bearer token to sign")
_ = signBearerCmd.MarkFlagFilename(signFromFlag)
_ = signBearerCmd.MarkFlagRequired(signFromFlag)
flags.String(signToFlag, "", "File to dump signed bearer token (default: binary encoded)")
flags.Bool(signBearerJSONFlag, false, "Dump bearer token in JSON encoding")
}
func signBearerToken(cmd *cobra.Command, _ []string) {
btok := common.ReadBearerToken(cmd, signFromFlag)
pk := key.GetOrGenerate(cmd)
err := btok.Sign(*pk)
commonCmd.ExitOnErr(cmd, "", err)
to := cmd.Flag(signToFlag).Value.String()
jsonFlag, _ := cmd.Flags().GetBool(signBearerJSONFlag)
var data []byte
if jsonFlag || len(to) == 0 {
data, err = btok.MarshalJSON()
commonCmd.ExitOnErr(cmd, "can't JSON encode bearer token: %w", err)
} else {
data = btok.Marshal()
}
if len(to) == 0 {
common.PrettyPrintJSON(cmd, btok, "bearer token")
return
}
err = os.WriteFile(to, data, 0644)
commonCmd.ExitOnErr(cmd, "can't write signed bearer token to file: %w", err)
cmd.Printf("signed bearer token was successfully dumped to %s\n", to)
}