go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers-sdk/v1/vault/vault.go (about) 1 // Copyright (c) Mondoo, Inc. 2 // SPDX-License-Identifier: BUSL-1.1 3 4 package vault 5 6 import ( 7 "encoding/json" 8 "strings" 9 10 "github.com/cockroachdb/errors" 11 "go.mondoo.com/ranger-rpc/codes" 12 "go.mondoo.com/ranger-rpc/status" 13 "google.golang.org/protobuf/proto" 14 ) 15 16 type Resolver interface { 17 GetCredential(cred *Credential) (*Credential, error) 18 } 19 20 //go:generate protoc --proto_path=../../../:. --go_out=. --go_opt=paths=source_relative --rangerrpc_out=. vault.proto 21 22 func EscapeSecretID(key string) string { 23 return strings.TrimPrefix(key, "//") 24 } 25 26 var NotFoundError = status.Error(codes.NotFound, "secret not found") 27 28 // Credential parses the secret data and creates a credential 29 func (x *Secret) Credential() (*Credential, error) { 30 var cred Credential 31 var err error 32 33 switch x.Encoding { 34 case SecretEncoding_encoding_proto: 35 err = proto.Unmarshal(x.Data, &cred) 36 case SecretEncoding_encoding_json: 37 err = json.Unmarshal(x.Data, &cred) 38 case SecretEncoding_encoding_binary: 39 cred = Credential{ 40 // if binary is used, it needs to be over-written from outside 41 Secret: x.Data, 42 } 43 default: 44 err = errors.New("unknown secret encoding") 45 } 46 47 if err != nil { 48 return nil, errors.Wrap(err, "unknown secret format") 49 } 50 51 cred.SecretId = x.Key 52 cred.PreProcess() 53 54 return &cred, nil 55 } 56 57 func NewSecret(cred *Credential, encoding SecretEncoding) (*Secret, error) { 58 // TODO: we also encode the ID, this may not be a good approach 59 var secretData []byte 60 var err error 61 62 switch encoding { 63 case SecretEncoding_encoding_json: 64 secretData, err = json.Marshal(cred) 65 case SecretEncoding_encoding_proto: 66 secretData, err = proto.Marshal(cred) 67 default: 68 return nil, errors.New("unknown secret encoding") 69 } 70 71 if err != nil { 72 return nil, err 73 } 74 75 return &Secret{ 76 Key: cred.SecretId, 77 Data: secretData, 78 Encoding: encoding, 79 }, nil 80 }