| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package remotecmd |
| 18 | |
| 19 | import ( |
| 20 | "encoding/json" |
| 21 | "errors" |
| 22 | "io/ioutil" |
| 23 | "net/url" |
| 24 | "os" |
| 25 | |
| 26 | "github.com/spf13/cobra" |
| 27 | |
| 28 | "github.com/sassoftware/relic/v7/cmdline/shared" |
| 29 | ) |
| 30 | |
| 31 | var GetKeyCmd = &cobra.Command{ |
| 32 | Use: "get-key", |
| 33 | Short: "Get a public key certificate from the remote server", |
| 34 | RunE: getKeyCmd, |
| 35 | } |
| 36 | |
| 37 | func init() { |
| 38 | RemoteCmd.AddCommand(GetKeyCmd) |
| 39 | } |
| 40 | |
| 41 | type keyInfo struct { |
| 42 | X509Certificate string |
| 43 | PGPCertificate string |
| 44 | } |
| 45 | |
| 46 | func getKeyInfo(keyName string) (keyInfo, error) { |
| 47 | response, err := CallRemote("keys/"+url.PathEscape(keyName), "GET", nil, nil) |
| 48 | if err != nil { |
| 49 | return keyInfo{}, err |
| 50 | } |
| 51 | blob, err := ioutil.ReadAll(response.Body) |
| 52 | if err != nil { |
| 53 | return keyInfo{}, err |
| 54 | } |
| 55 | response.Body.Close() |
| 56 | var info keyInfo |
| 57 | if err := json.Unmarshal(blob, &info); err != nil { |
| 58 | return keyInfo{}, err |
| 59 | } |
| 60 | return info, nil |
| 61 | } |
| 62 | |
| 63 | func getKeyCmd(cmd *cobra.Command, args []string) error { |
| 64 | if len(args) == 0 { |
| 65 | return errors.New("specify one or more key names. See also 'list-keys'") |
| 66 | } |
| 67 | for _, keyName := range args { |
| 68 | info, err := getKeyInfo(keyName) |
| 69 | if err != nil { |
| 70 | return shared.Fail(err) |
| 71 | } |
| 72 | os.Stdout.WriteString(info.X509Certificate) |
| 73 | os.Stdout.WriteString(info.PGPCertificate) |
| 74 | } |
| 75 | return nil |
| 76 | } |