utils.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. "crypto/md5" //nolint:gosec
  15. "encoding/base64"
  16. "errors"
  17. "fmt"
  18. "net"
  19. "net/url"
  20. "reflect"
  21. "regexp"
  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. func RewriteMap(operations []esv1beta1.ExternalSecretRewrite, in map[string][]byte) (map[string][]byte, error) {
  36. out := in
  37. var err error
  38. for i, op := range operations {
  39. if op.Regexp != nil {
  40. out, err = RewriteRegexp(*op.Regexp, out)
  41. if err != nil {
  42. return nil, fmt.Errorf("failed rewriting operation[%v]: %w", i, err)
  43. }
  44. }
  45. }
  46. return out, nil
  47. }
  48. // RewriteRegexp rewrites a single Regexp Rewrite Operation.
  49. func RewriteRegexp(operation esv1beta1.ExternalSecretRewriteRegexp, in map[string][]byte) (map[string][]byte, error) {
  50. out := make(map[string][]byte)
  51. re, err := regexp.Compile(operation.Source)
  52. if err != nil {
  53. return nil, err
  54. }
  55. for key, value := range in {
  56. newKey := re.ReplaceAllString(key, operation.Target)
  57. out[newKey] = value
  58. }
  59. return out, nil
  60. }
  61. // DecodeValues decodes values from a secretMap.
  62. func DecodeMap(strategy esv1beta1.ExternalSecretDecodingStrategy, in map[string][]byte) (map[string][]byte, error) {
  63. out := make(map[string][]byte, len(in))
  64. for k, v := range in {
  65. val, err := Decode(strategy, v)
  66. if err != nil {
  67. return nil, fmt.Errorf("failure decoding key %v: %w", k, err)
  68. }
  69. out[k] = val
  70. }
  71. return out, nil
  72. }
  73. func Decode(strategy esv1beta1.ExternalSecretDecodingStrategy, in []byte) ([]byte, error) {
  74. switch strategy {
  75. case esv1beta1.ExternalSecretDecodeBase64:
  76. out, err := base64.StdEncoding.DecodeString(string(in))
  77. if err != nil {
  78. return nil, err
  79. }
  80. return out, nil
  81. case esv1beta1.ExternalSecretDecodeBase64URL:
  82. out, err := base64.URLEncoding.DecodeString(string(in))
  83. if err != nil {
  84. return nil, err
  85. }
  86. return out, nil
  87. case esv1beta1.ExternalSecretDecodeNone:
  88. return in, nil
  89. // default when stored version is v1alpha1
  90. case "":
  91. return in, nil
  92. case esv1beta1.ExternalSecretDecodeAuto:
  93. out, err := Decode(esv1beta1.ExternalSecretDecodeBase64, in)
  94. if err != nil {
  95. out, err := Decode(esv1beta1.ExternalSecretDecodeBase64URL, in)
  96. if err != nil {
  97. return Decode(esv1beta1.ExternalSecretDecodeNone, in)
  98. }
  99. return out, nil
  100. }
  101. return out, nil
  102. default:
  103. return nil, fmt.Errorf("decoding strategy %v is not supported", strategy)
  104. }
  105. }
  106. func ValidateKeys(in map[string][]byte) bool {
  107. for key := range in {
  108. for _, v := range key {
  109. if !unicode.IsNumber(v) &&
  110. !unicode.IsLetter(v) &&
  111. v != '-' &&
  112. v != '.' &&
  113. v != '_' {
  114. return false
  115. }
  116. }
  117. }
  118. return true
  119. }
  120. // ConvertKeys converts a secret map into a valid key.
  121. // Replaces any non-alphanumeric characters depending on convert strategy.
  122. func ConvertKeys(strategy esv1beta1.ExternalSecretConversionStrategy, in map[string][]byte) (map[string][]byte, error) {
  123. out := make(map[string][]byte, len(in))
  124. for k, v := range in {
  125. key := convert(strategy, k)
  126. if _, exists := out[key]; exists {
  127. return nil, fmt.Errorf("secret name collision during conversion: %s", key)
  128. }
  129. out[key] = v
  130. }
  131. return out, nil
  132. }
  133. func convert(strategy esv1beta1.ExternalSecretConversionStrategy, str string) string {
  134. rs := []rune(str)
  135. newName := make([]string, len(rs))
  136. for rk, rv := range rs {
  137. if !unicode.IsNumber(rv) &&
  138. !unicode.IsLetter(rv) &&
  139. rv != '-' &&
  140. rv != '.' &&
  141. rv != '_' {
  142. switch strategy {
  143. case esv1beta1.ExternalSecretConversionDefault:
  144. newName[rk] = "_"
  145. case esv1beta1.ExternalSecretConversionUnicode:
  146. newName[rk] = fmt.Sprintf("_U%04x_", rv)
  147. default:
  148. newName[rk] = string(rv)
  149. }
  150. } else {
  151. newName[rk] = string(rv)
  152. }
  153. }
  154. return strings.Join(newName, "")
  155. }
  156. // MergeStringMap performs a deep clone from src to dest.
  157. func MergeStringMap(dest, src map[string]string) {
  158. for k, v := range src {
  159. dest[k] = v
  160. }
  161. }
  162. // IsNil checks if an Interface is nil.
  163. func IsNil(i interface{}) bool {
  164. if i == nil {
  165. return true
  166. }
  167. value := reflect.ValueOf(i)
  168. if value.Type().Kind() == reflect.Ptr {
  169. return value.IsNil()
  170. }
  171. return false
  172. }
  173. // ObjectHash calculates md5 sum of the data contained in the secret.
  174. //
  175. //nolint:gosec
  176. func ObjectHash(object interface{}) string {
  177. textualVersion := fmt.Sprintf("%+v", object)
  178. return fmt.Sprintf("%x", md5.Sum([]byte(textualVersion)))
  179. }
  180. func ErrorContains(out error, want string) bool {
  181. if out == nil {
  182. return want == ""
  183. }
  184. if want == "" {
  185. return false
  186. }
  187. return strings.Contains(out.Error(), want)
  188. }
  189. var (
  190. errNamespaceNotAllowed = errors.New("namespace not allowed with namespaced SecretStore")
  191. errRequireNamespace = errors.New("cluster scope requires namespace")
  192. )
  193. // ValidateSecretSelector just checks if the namespace field is present/absent
  194. // depending on the secret store type.
  195. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  196. func ValidateSecretSelector(store esv1beta1.GenericStore, ref esmeta.SecretKeySelector) error {
  197. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  198. if clusterScope && ref.Namespace == nil {
  199. return errRequireNamespace
  200. }
  201. if !clusterScope && ref.Namespace != nil {
  202. return errNamespaceNotAllowed
  203. }
  204. return nil
  205. }
  206. // ValidateReferentSecretSelector allows
  207. // cluster scoped store without namespace
  208. // this should replace above ValidateServiceAccountSelector once all providers
  209. // support referent auth.
  210. func ValidateReferentSecretSelector(store esv1beta1.GenericStore, ref esmeta.SecretKeySelector) error {
  211. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  212. if !clusterScope && ref.Namespace != nil {
  213. return errNamespaceNotAllowed
  214. }
  215. return nil
  216. }
  217. // ValidateServiceAccountSelector just checks if the namespace field is present/absent
  218. // depending on the secret store type.
  219. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  220. func ValidateServiceAccountSelector(store esv1beta1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  221. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  222. if clusterScope && ref.Namespace == nil {
  223. return errRequireNamespace
  224. }
  225. if !clusterScope && ref.Namespace != nil {
  226. return errNamespaceNotAllowed
  227. }
  228. return nil
  229. }
  230. // ValidateReferentServiceAccountSelector allows
  231. // cluster scoped store without namespace
  232. // this should replace above ValidateServiceAccountSelector once all providers
  233. // support referent auth.
  234. func ValidateReferentServiceAccountSelector(store esv1beta1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  235. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  236. if !clusterScope && ref.Namespace != nil {
  237. return errNamespaceNotAllowed
  238. }
  239. return nil
  240. }
  241. func NetworkValidate(endpoint string, timeout time.Duration) error {
  242. hostname, err := url.Parse(endpoint)
  243. if err != nil {
  244. return fmt.Errorf("could not parse url: %w", err)
  245. }
  246. host := hostname.Hostname()
  247. port := hostname.Port()
  248. if port == "" {
  249. port = "443"
  250. }
  251. url := fmt.Sprintf("%v:%v", host, port)
  252. conn, err := net.DialTimeout("tcp", url, timeout)
  253. if err != nil {
  254. return fmt.Errorf("error accessing external store: %w", err)
  255. }
  256. defer conn.Close()
  257. return nil
  258. }