utils.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. "regexp"
  23. "strings"
  24. "time"
  25. "unicode"
  26. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  27. esmeta "github.com/external-secrets/external-secrets/apis/meta/v1"
  28. )
  29. // MergeByteMap merges map of byte slices.
  30. func MergeByteMap(dst, src map[string][]byte) map[string][]byte {
  31. for k, v := range src {
  32. dst[k] = v
  33. }
  34. return dst
  35. }
  36. func RewriteMap(operations []esv1beta1.ExternalSecretRewrite, in map[string][]byte) (map[string][]byte, error) {
  37. out := in
  38. var err error
  39. for i, op := range operations {
  40. if op.Regexp != nil {
  41. out, err = RewriteRegexp(*op.Regexp, out)
  42. if err != nil {
  43. return nil, fmt.Errorf("failed rewriting operation[%v]: %w", i, err)
  44. }
  45. }
  46. }
  47. return out, nil
  48. }
  49. // RewriteRegexp rewrites a single Regexp Rewrite Operation.
  50. func RewriteRegexp(operation esv1beta1.ExternalSecretRewriteRegexp, in map[string][]byte) (map[string][]byte, error) {
  51. out := make(map[string][]byte)
  52. re, err := regexp.Compile(operation.Source)
  53. if err != nil {
  54. return nil, err
  55. }
  56. for key, value := range in {
  57. newKey := re.ReplaceAllString(key, operation.Target)
  58. out[newKey] = value
  59. }
  60. return out, nil
  61. }
  62. // DecodeValues decodes values from a secretMap.
  63. func DecodeMap(strategy esv1beta1.ExternalSecretDecodingStrategy, in map[string][]byte) (map[string][]byte, error) {
  64. out := make(map[string][]byte, len(in))
  65. for k, v := range in {
  66. val, err := Decode(strategy, v)
  67. if err != nil {
  68. return nil, fmt.Errorf("failure decoding key %v: %w", k, err)
  69. }
  70. out[k] = val
  71. }
  72. return out, nil
  73. }
  74. func Decode(strategy esv1beta1.ExternalSecretDecodingStrategy, in []byte) ([]byte, error) {
  75. switch strategy {
  76. case esv1beta1.ExternalSecretDecodeBase64:
  77. out, err := base64.StdEncoding.DecodeString(string(in))
  78. if err != nil {
  79. return nil, err
  80. }
  81. return out, nil
  82. case esv1beta1.ExternalSecretDecodeBase64URL:
  83. out, err := base64.URLEncoding.DecodeString(string(in))
  84. if err != nil {
  85. return nil, err
  86. }
  87. return out, nil
  88. case esv1beta1.ExternalSecretDecodeNone:
  89. return in, nil
  90. // default when stored version is v1alpha1
  91. case "":
  92. return in, nil
  93. case esv1beta1.ExternalSecretDecodeAuto:
  94. out, err := Decode(esv1beta1.ExternalSecretDecodeBase64, in)
  95. if err != nil {
  96. out, err := Decode(esv1beta1.ExternalSecretDecodeBase64URL, in)
  97. if err != nil {
  98. return Decode(esv1beta1.ExternalSecretDecodeNone, in)
  99. }
  100. return out, nil
  101. }
  102. return out, nil
  103. default:
  104. return nil, fmt.Errorf("decoding strategy %v is not supported", strategy)
  105. }
  106. }
  107. func ValidateKeys(in map[string][]byte) bool {
  108. for key := range in {
  109. for _, v := range key {
  110. if !unicode.IsNumber(v) &&
  111. !unicode.IsLetter(v) &&
  112. v != '-' &&
  113. v != '.' &&
  114. v != '_' {
  115. return false
  116. }
  117. }
  118. }
  119. return true
  120. }
  121. // ConvertKeys converts a secret map into a valid key.
  122. // Replaces any non-alphanumeric characters depending on convert strategy.
  123. func ConvertKeys(strategy esv1beta1.ExternalSecretConversionStrategy, in map[string][]byte) (map[string][]byte, error) {
  124. out := make(map[string][]byte, len(in))
  125. for k, v := range in {
  126. key := convert(strategy, k)
  127. if _, exists := out[key]; exists {
  128. return nil, fmt.Errorf("secret name collision during conversion: %s", key)
  129. }
  130. out[key] = v
  131. }
  132. return out, nil
  133. }
  134. func convert(strategy esv1beta1.ExternalSecretConversionStrategy, str string) string {
  135. rs := []rune(str)
  136. newName := make([]string, len(rs))
  137. for rk, rv := range rs {
  138. if !unicode.IsNumber(rv) &&
  139. !unicode.IsLetter(rv) &&
  140. rv != '-' &&
  141. rv != '.' &&
  142. rv != '_' {
  143. switch strategy {
  144. case esv1beta1.ExternalSecretConversionDefault:
  145. newName[rk] = "_"
  146. case esv1beta1.ExternalSecretConversionUnicode:
  147. newName[rk] = fmt.Sprintf("_U%04x_", rv)
  148. default:
  149. newName[rk] = string(rv)
  150. }
  151. } else {
  152. newName[rk] = string(rv)
  153. }
  154. }
  155. return strings.Join(newName, "")
  156. }
  157. // MergeStringMap performs a deep clone from src to dest.
  158. func MergeStringMap(dest, src map[string]string) {
  159. for k, v := range src {
  160. dest[k] = v
  161. }
  162. }
  163. // IsNil checks if an Interface is nil.
  164. func IsNil(i interface{}) bool {
  165. if i == nil {
  166. return true
  167. }
  168. value := reflect.ValueOf(i)
  169. if value.Type().Kind() == reflect.Ptr {
  170. return value.IsNil()
  171. }
  172. return false
  173. }
  174. // ObjectHash calculates md5 sum of the data contained in the secret.
  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. }