utils.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. case esv1beta1.ExternalSecretDecodeAuto:
  64. out, err := Decode(esv1beta1.ExternalSecretDecodeBase64, in)
  65. if err != nil {
  66. out, err := Decode(esv1beta1.ExternalSecretDecodeBase64URL, in)
  67. if err != nil {
  68. return Decode(esv1beta1.ExternalSecretDecodeNone, in)
  69. }
  70. return out, nil
  71. }
  72. return out, nil
  73. default:
  74. return nil, fmt.Errorf("decoding strategy %v is not supported", strategy)
  75. }
  76. }
  77. // ConvertKeys converts a secret map into a valid key.
  78. // Replaces any non-alphanumeric characters depending on convert strategy.
  79. func ConvertKeys(strategy esv1beta1.ExternalSecretConversionStrategy, in map[string][]byte) (map[string][]byte, error) {
  80. out := make(map[string][]byte, len(in))
  81. for k, v := range in {
  82. key := convert(strategy, k)
  83. if _, exists := out[key]; exists {
  84. return nil, fmt.Errorf("secret name collision during conversion: %s", key)
  85. }
  86. out[key] = v
  87. }
  88. return out, nil
  89. }
  90. func convert(strategy esv1beta1.ExternalSecretConversionStrategy, str string) string {
  91. rs := []rune(str)
  92. newName := make([]string, len(rs))
  93. for rk, rv := range rs {
  94. if !unicode.IsNumber(rv) &&
  95. !unicode.IsLetter(rv) &&
  96. rv != '-' &&
  97. rv != '.' &&
  98. rv != '_' {
  99. switch strategy {
  100. case esv1beta1.ExternalSecretConversionDefault:
  101. newName[rk] = "_"
  102. case esv1beta1.ExternalSecretConversionUnicode:
  103. newName[rk] = fmt.Sprintf("_U%04x_", rv)
  104. }
  105. } else {
  106. newName[rk] = string(rv)
  107. }
  108. }
  109. return strings.Join(newName, "")
  110. }
  111. // MergeStringMap performs a deep clone from src to dest.
  112. func MergeStringMap(dest, src map[string]string) {
  113. for k, v := range src {
  114. dest[k] = v
  115. }
  116. }
  117. // IsNil checks if an Interface is nil.
  118. func IsNil(i interface{}) bool {
  119. if i == nil {
  120. return true
  121. }
  122. value := reflect.ValueOf(i)
  123. if value.Type().Kind() == reflect.Ptr {
  124. return value.IsNil()
  125. }
  126. return false
  127. }
  128. // ObjectHash calculates md5 sum of the data contained in the secret.
  129. // nolint:gosec
  130. func ObjectHash(object interface{}) string {
  131. textualVersion := fmt.Sprintf("%+v", object)
  132. return fmt.Sprintf("%x", md5.Sum([]byte(textualVersion)))
  133. }
  134. func ErrorContains(out error, want string) bool {
  135. if out == nil {
  136. return want == ""
  137. }
  138. if want == "" {
  139. return false
  140. }
  141. return strings.Contains(out.Error(), want)
  142. }
  143. var (
  144. errNamespaceNotAllowed = errors.New("namespace not allowed with namespaced SecretStore")
  145. errRequireNamespace = errors.New("cluster scope requires namespace")
  146. )
  147. // ValidateSecretSelector just checks if the namespace field is present/absent
  148. // depending on the secret store type.
  149. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  150. func ValidateSecretSelector(store esv1beta1.GenericStore, ref esmeta.SecretKeySelector) error {
  151. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  152. if clusterScope && ref.Namespace == nil {
  153. return errRequireNamespace
  154. }
  155. if !clusterScope && ref.Namespace != nil {
  156. return errNamespaceNotAllowed
  157. }
  158. return nil
  159. }
  160. // ValidateReferentSecretSelector allows
  161. // cluster scoped store without namespace
  162. // this should replace above ValidateServiceAccountSelector once all providers
  163. // support referent auth.
  164. func ValidateReferentSecretSelector(store esv1beta1.GenericStore, ref esmeta.SecretKeySelector) error {
  165. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  166. if !clusterScope && ref.Namespace != nil {
  167. return errNamespaceNotAllowed
  168. }
  169. return nil
  170. }
  171. // ValidateServiceAccountSelector just checks if the namespace field is present/absent
  172. // depending on the secret store type.
  173. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  174. func ValidateServiceAccountSelector(store esv1beta1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  175. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  176. if clusterScope && ref.Namespace == nil {
  177. return errRequireNamespace
  178. }
  179. if !clusterScope && ref.Namespace != nil {
  180. return errNamespaceNotAllowed
  181. }
  182. return nil
  183. }
  184. // ValidateReferentServiceAccountSelector allows
  185. // cluster scoped store without namespace
  186. // this should replace above ValidateServiceAccountSelector once all providers
  187. // support referent auth.
  188. func ValidateReferentServiceAccountSelector(store esv1beta1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  189. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  190. if !clusterScope && ref.Namespace != nil {
  191. return errNamespaceNotAllowed
  192. }
  193. return nil
  194. }
  195. func NetworkValidate(endpoint string, timeout time.Duration) error {
  196. hostname, err := url.Parse(endpoint)
  197. if err != nil {
  198. return fmt.Errorf("could not parse url: %w", err)
  199. }
  200. host := hostname.Hostname()
  201. port := hostname.Port()
  202. if port == "" {
  203. port = "443"
  204. }
  205. url := fmt.Sprintf("%v:%v", host, port)
  206. conn, err := net.DialTimeout("tcp", url, timeout)
  207. if err != nil {
  208. return fmt.Errorf("error accessing external store: %w", err)
  209. }
  210. defer conn.Close()
  211. return nil
  212. }