utils.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package utils
  13. import (
  14. // nolint:gosec
  15. "crypto/md5"
  16. "encoding/base64"
  17. "errors"
  18. "fmt"
  19. "net"
  20. "net/url"
  21. "reflect"
  22. "strings"
  23. "time"
  24. "unicode"
  25. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  26. esmeta "github.com/external-secrets/external-secrets/apis/meta/v1"
  27. )
  28. // MergeByteMap merges map of byte slices.
  29. func MergeByteMap(dst, src map[string][]byte) map[string][]byte {
  30. for k, v := range src {
  31. dst[k] = v
  32. }
  33. return dst
  34. }
  35. // DecodeValues decodes values from a secretMap.
  36. func DecodeMap(strategy esv1beta1.ExternalSecretDecodingStrategy, in map[string][]byte) (map[string][]byte, error) {
  37. out := make(map[string][]byte, len(in))
  38. for k, v := range in {
  39. val, err := Decode(strategy, v)
  40. if err != nil {
  41. return nil, fmt.Errorf("failure decoding key %v: %w", k, err)
  42. }
  43. out[k] = val
  44. }
  45. return out, nil
  46. }
  47. func Decode(strategy esv1beta1.ExternalSecretDecodingStrategy, in []byte) ([]byte, error) {
  48. switch strategy {
  49. case esv1beta1.ExternalSecretDecodeBase64:
  50. out, err := base64.StdEncoding.DecodeString(string(in))
  51. if err != nil {
  52. return nil, err
  53. }
  54. return out, nil
  55. case esv1beta1.ExternalSecretDecodeBase64URL:
  56. out, err := base64.URLEncoding.DecodeString(string(in))
  57. if err != nil {
  58. return nil, err
  59. }
  60. return out, nil
  61. case esv1beta1.ExternalSecretDecodeNone:
  62. return in, nil
  63. // default when stored version is v1alpha1
  64. case "":
  65. return in, nil
  66. case esv1beta1.ExternalSecretDecodeAuto:
  67. out, err := Decode(esv1beta1.ExternalSecretDecodeBase64, in)
  68. if err != nil {
  69. out, err := Decode(esv1beta1.ExternalSecretDecodeBase64URL, in)
  70. if err != nil {
  71. return Decode(esv1beta1.ExternalSecretDecodeNone, in)
  72. }
  73. return out, nil
  74. }
  75. return out, nil
  76. default:
  77. return nil, fmt.Errorf("decoding strategy %v is not supported", strategy)
  78. }
  79. }
  80. // ConvertKeys converts a secret map into a valid key.
  81. // Replaces any non-alphanumeric characters depending on convert strategy.
  82. func ConvertKeys(strategy esv1beta1.ExternalSecretConversionStrategy, in map[string][]byte) (map[string][]byte, error) {
  83. out := make(map[string][]byte, len(in))
  84. for k, v := range in {
  85. key := convert(strategy, k)
  86. if _, exists := out[key]; exists {
  87. return nil, fmt.Errorf("secret name collision during conversion: %s", key)
  88. }
  89. out[key] = v
  90. }
  91. return out, nil
  92. }
  93. func convert(strategy esv1beta1.ExternalSecretConversionStrategy, str string) string {
  94. rs := []rune(str)
  95. newName := make([]string, len(rs))
  96. for rk, rv := range rs {
  97. if !unicode.IsNumber(rv) &&
  98. !unicode.IsLetter(rv) &&
  99. rv != '-' &&
  100. rv != '.' &&
  101. rv != '_' {
  102. switch strategy {
  103. case esv1beta1.ExternalSecretConversionDefault:
  104. newName[rk] = "_"
  105. case esv1beta1.ExternalSecretConversionUnicode:
  106. newName[rk] = fmt.Sprintf("_U%04x_", rv)
  107. }
  108. } else {
  109. newName[rk] = string(rv)
  110. }
  111. }
  112. return strings.Join(newName, "")
  113. }
  114. // MergeStringMap performs a deep clone from src to dest.
  115. func MergeStringMap(dest, src map[string]string) {
  116. for k, v := range src {
  117. dest[k] = v
  118. }
  119. }
  120. // IsNil checks if an Interface is nil.
  121. func IsNil(i interface{}) bool {
  122. if i == nil {
  123. return true
  124. }
  125. value := reflect.ValueOf(i)
  126. if value.Type().Kind() == reflect.Ptr {
  127. return value.IsNil()
  128. }
  129. return false
  130. }
  131. // ObjectHash calculates md5 sum of the data contained in the secret.
  132. // nolint:gosec
  133. func ObjectHash(object interface{}) string {
  134. textualVersion := fmt.Sprintf("%+v", object)
  135. return fmt.Sprintf("%x", md5.Sum([]byte(textualVersion)))
  136. }
  137. func ErrorContains(out error, want string) bool {
  138. if out == nil {
  139. return want == ""
  140. }
  141. if want == "" {
  142. return false
  143. }
  144. return strings.Contains(out.Error(), want)
  145. }
  146. var (
  147. errNamespaceNotAllowed = errors.New("namespace not allowed with namespaced SecretStore")
  148. errRequireNamespace = errors.New("cluster scope requires namespace")
  149. )
  150. // ValidateSecretSelector just checks if the namespace field is present/absent
  151. // depending on the secret store type.
  152. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  153. func ValidateSecretSelector(store esv1beta1.GenericStore, ref esmeta.SecretKeySelector) error {
  154. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  155. if clusterScope && ref.Namespace == nil {
  156. return errRequireNamespace
  157. }
  158. if !clusterScope && ref.Namespace != nil {
  159. return errNamespaceNotAllowed
  160. }
  161. return nil
  162. }
  163. // ValidateReferentSecretSelector allows
  164. // cluster scoped store without namespace
  165. // this should replace above ValidateServiceAccountSelector once all providers
  166. // support referent auth.
  167. func ValidateReferentSecretSelector(store esv1beta1.GenericStore, ref esmeta.SecretKeySelector) error {
  168. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  169. if !clusterScope && ref.Namespace != nil {
  170. return errNamespaceNotAllowed
  171. }
  172. return nil
  173. }
  174. // ValidateServiceAccountSelector just checks if the namespace field is present/absent
  175. // depending on the secret store type.
  176. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  177. func ValidateServiceAccountSelector(store esv1beta1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  178. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  179. if clusterScope && ref.Namespace == nil {
  180. return errRequireNamespace
  181. }
  182. if !clusterScope && ref.Namespace != nil {
  183. return errNamespaceNotAllowed
  184. }
  185. return nil
  186. }
  187. // ValidateReferentServiceAccountSelector allows
  188. // cluster scoped store without namespace
  189. // this should replace above ValidateServiceAccountSelector once all providers
  190. // support referent auth.
  191. func ValidateReferentServiceAccountSelector(store esv1beta1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  192. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  193. if !clusterScope && ref.Namespace != nil {
  194. return errNamespaceNotAllowed
  195. }
  196. return nil
  197. }
  198. func NetworkValidate(endpoint string, timeout time.Duration) error {
  199. hostname, err := url.Parse(endpoint)
  200. if err != nil {
  201. return fmt.Errorf("could not parse url: %w", err)
  202. }
  203. host := hostname.Hostname()
  204. port := hostname.Port()
  205. if port == "" {
  206. port = "443"
  207. }
  208. url := fmt.Sprintf("%v:%v", host, port)
  209. conn, err := net.DialTimeout("tcp", url, timeout)
  210. if err != nil {
  211. return fmt.Errorf("error accessing external store: %w", err)
  212. }
  213. defer conn.Close()
  214. return nil
  215. }