github.com/nats-io/nsc@v0.0.0-20221206222106-35db9400b257/cmd/describe.go (about) 1 /* 2 * Copyright 2018-2022 The NATS Authors 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 package cmd 17 18 import ( 19 "bytes" 20 "encoding/base64" 21 "encoding/json" 22 "errors" 23 "fmt" 24 25 "github.com/spf13/cobra" 26 ) 27 28 var Raw bool 29 var WideFlag bool 30 var Wide = noopNameFilter 31 var Json bool 32 var JsonPath string 33 34 type WideFun = func(a string) string 35 36 func noopNameFilter(a string) string { 37 return a 38 } 39 40 func friendlyNameFilter() (WideFun, error) { 41 m, err := friendlyNames(GetConfig().Operator) 42 if err != nil { 43 return nil, err 44 } 45 return func(a string) string { 46 v := m[a] 47 if v == "" { 48 v = a 49 } 50 return v 51 }, nil 52 } 53 54 var describeCmd = &cobra.Command{ 55 Use: "describe", 56 Short: "Describe assets such as operators, accounts, users, and jwt files", 57 PersistentPreRunE: func(cmd *cobra.Command, args []string) error { 58 // run the roots PersistentPreRun 59 if err := GetRootCmd().PersistentPreRunE(cmd, args); err != nil { 60 return err 61 } 62 var err error 63 if WideFlag { 64 Wide = noopNameFilter 65 } else { 66 Wide, err = friendlyNameFilter() 67 if err != nil { 68 return err 69 } 70 } 71 return nil 72 }, 73 } 74 75 func init() { 76 GetRootCmd().AddCommand(describeCmd) 77 describeCmd.PersistentFlags().BoolVarP(&Json, "json", "J", false, "display JWT body as JSON") 78 describeCmd.PersistentFlags().BoolVarP(&WideFlag, "long-ids", "W", false, "display account ids on imports") 79 describeCmd.PersistentFlags().BoolVarP(&Raw, "raw", "R", false, "output the raw JWT (exclusive of long-ids)") 80 describeCmd.PersistentFlags().StringVarP(&JsonPath, "field", "F", "", "extract value from specified field using json structure") 81 } 82 83 func bodyAsJson(data []byte) ([]byte, error) { 84 chunks := bytes.Split(data, []byte{'.'}) 85 if len(chunks) != 3 { 86 return nil, errors.New("data is not a jwt") 87 } 88 body := chunks[1] 89 d, err := base64.RawURLEncoding.DecodeString(string(body)) 90 if err != nil { 91 return nil, fmt.Errorf("error decoding base64: %v", err) 92 } 93 m := make(map[string]interface{}) 94 if err := json.Unmarshal(d, &m); err != nil { 95 return nil, fmt.Errorf("error parsing json: %v", err) 96 } 97 f, err := json.MarshalIndent(m, "", " ") 98 if err != nil { 99 return nil, fmt.Errorf("error formatting json: %v", err) 100 } 101 return f, nil 102 }