github.com/drone/go-convert@v0.0.0-20240307072510-6bd371c65e61/convert/travis/yaml/secure.go (about) 1 // Copyright 2022 Harness, Inc. 2 // 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 package yaml 16 17 import ( 18 "encoding/json" 19 "errors" 20 ) 21 22 type ( 23 // Secure represents a secure variable. 24 Secure struct { 25 Decrypted string 26 Encrypted string 27 } 28 29 // secure is a temporary structure used for 30 // encoding and decoding. 31 secure struct { 32 Secure string `yaml:"secure,omitempty" json:"secure,omitempty"` 33 } 34 ) 35 36 // UnmarshalYAML implements the unmarshal interface. 37 func (v *Secure) UnmarshalYAML(unmarshal func(interface{}) error) error { 38 var out1 string 39 var out2 *secure 40 if err := unmarshal(&out1); err == nil { 41 v.Decrypted = out1 42 return nil 43 } 44 if err := unmarshal(&out2); err == nil { 45 v.Encrypted = out2.Secure 46 return nil 47 } 48 return errors.New("failed to unmarshal secure variable") 49 } 50 51 // MarshalYAML implements the marshal interface. 52 func (v *Secure) MarshalYAML() (interface{}, error) { 53 if v.Encrypted != "" { 54 return secure{v.Encrypted}, nil 55 } 56 return v.Decrypted, nil 57 } 58 59 // UnmarshalJSON implements the unmarshal interface. 60 func (v *Secure) UnmarshalJSON(data []byte) error { 61 var out1 string 62 var out2 *secure 63 if err := json.Unmarshal(data, &out1); err == nil { 64 v.Decrypted = out1 65 return nil 66 } 67 if err := json.Unmarshal(data, &out2); err == nil { 68 v.Encrypted = out2.Secure 69 return nil 70 } 71 return errors.New("failed to unmarshal secure variable") 72 } 73 74 // MarshalJSON implements the marshal interface. 75 func (v *Secure) MarshalJSON() ([]byte, error) { 76 if v.Encrypted != "" { 77 return json.Marshal( 78 &secure{v.Encrypted}, 79 ) 80 } 81 return json.Marshal(v.Decrypted) 82 }