utils.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. "bytes"
  15. "crypto/md5" //nolint:gosec
  16. "encoding/base64"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "net"
  21. "net/url"
  22. "reflect"
  23. "regexp"
  24. "strconv"
  25. "strings"
  26. tpl "text/template"
  27. "time"
  28. "unicode"
  29. apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  30. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  31. esmeta "github.com/external-secrets/external-secrets/apis/meta/v1"
  32. "github.com/external-secrets/external-secrets/pkg/template/v2"
  33. )
  34. const (
  35. errParse = "unable to parse transform template: %s"
  36. errExecute = "unable to execute transform template: %s"
  37. )
  38. var (
  39. errKeyNotFound = errors.New("key not found")
  40. )
  41. // JSONMarshal takes an interface and returns a new escaped and encoded byte slice.
  42. func JSONMarshal(t interface{}) ([]byte, error) {
  43. buffer := &bytes.Buffer{}
  44. encoder := json.NewEncoder(buffer)
  45. encoder.SetEscapeHTML(false)
  46. err := encoder.Encode(t)
  47. return bytes.TrimRight(buffer.Bytes(), "\n"), err
  48. }
  49. // MergeByteMap merges map of byte slices.
  50. func MergeByteMap(dst, src map[string][]byte) map[string][]byte {
  51. for k, v := range src {
  52. dst[k] = v
  53. }
  54. return dst
  55. }
  56. func RewriteMap(operations []esv1beta1.ExternalSecretRewrite, in map[string][]byte) (map[string][]byte, error) {
  57. out := in
  58. var err error
  59. for i, op := range operations {
  60. if op.Regexp != nil {
  61. out, err = RewriteRegexp(*op.Regexp, out)
  62. if err != nil {
  63. return nil, fmt.Errorf("failed rewriting regexp operation[%v]: %w", i, err)
  64. }
  65. }
  66. if op.Transform != nil {
  67. out, err = RewriteTransform(*op.Transform, out)
  68. if err != nil {
  69. return nil, fmt.Errorf("failed rewriting transform operation[%v]: %w", i, err)
  70. }
  71. }
  72. }
  73. return out, nil
  74. }
  75. // RewriteRegexp rewrites a single Regexp Rewrite Operation.
  76. func RewriteRegexp(operation esv1beta1.ExternalSecretRewriteRegexp, in map[string][]byte) (map[string][]byte, error) {
  77. out := make(map[string][]byte)
  78. re, err := regexp.Compile(operation.Source)
  79. if err != nil {
  80. return nil, err
  81. }
  82. for key, value := range in {
  83. newKey := re.ReplaceAllString(key, operation.Target)
  84. out[newKey] = value
  85. }
  86. return out, nil
  87. }
  88. // RewriteTransform applies string transformation on each secret key name to rewrite.
  89. func RewriteTransform(operation esv1beta1.ExternalSecretRewriteTransform, in map[string][]byte) (map[string][]byte, error) {
  90. out := make(map[string][]byte)
  91. for key, value := range in {
  92. data := map[string][]byte{
  93. "value": []byte(key),
  94. }
  95. result, err := transform(operation.Template, data)
  96. if err != nil {
  97. return nil, err
  98. }
  99. newKey := string(result)
  100. out[newKey] = value
  101. }
  102. return out, nil
  103. }
  104. func transform(val string, data map[string][]byte) ([]byte, error) {
  105. strValData := make(map[string]string, len(data))
  106. for k := range data {
  107. strValData[k] = string(data[k])
  108. }
  109. t, err := tpl.New("transform").
  110. Funcs(template.FuncMap()).
  111. Parse(val)
  112. if err != nil {
  113. return nil, fmt.Errorf(errParse, err)
  114. }
  115. buf := bytes.NewBuffer(nil)
  116. err = t.Execute(buf, strValData)
  117. if err != nil {
  118. return nil, fmt.Errorf(errExecute, err)
  119. }
  120. return buf.Bytes(), nil
  121. }
  122. // DecodeValues decodes values from a secretMap.
  123. func DecodeMap(strategy esv1beta1.ExternalSecretDecodingStrategy, in map[string][]byte) (map[string][]byte, error) {
  124. out := make(map[string][]byte, len(in))
  125. for k, v := range in {
  126. val, err := Decode(strategy, v)
  127. if err != nil {
  128. return nil, fmt.Errorf("failure decoding key %v: %w", k, err)
  129. }
  130. out[k] = val
  131. }
  132. return out, nil
  133. }
  134. func Decode(strategy esv1beta1.ExternalSecretDecodingStrategy, in []byte) ([]byte, error) {
  135. switch strategy {
  136. case esv1beta1.ExternalSecretDecodeBase64:
  137. out, err := base64.StdEncoding.DecodeString(string(in))
  138. if err != nil {
  139. return nil, err
  140. }
  141. return out, nil
  142. case esv1beta1.ExternalSecretDecodeBase64URL:
  143. out, err := base64.URLEncoding.DecodeString(string(in))
  144. if err != nil {
  145. return nil, err
  146. }
  147. return out, nil
  148. case esv1beta1.ExternalSecretDecodeNone:
  149. return in, nil
  150. // default when stored version is v1alpha1
  151. case "":
  152. return in, nil
  153. case esv1beta1.ExternalSecretDecodeAuto:
  154. out, err := Decode(esv1beta1.ExternalSecretDecodeBase64, in)
  155. if err != nil {
  156. out, err := Decode(esv1beta1.ExternalSecretDecodeBase64URL, in)
  157. if err != nil {
  158. return Decode(esv1beta1.ExternalSecretDecodeNone, in)
  159. }
  160. return out, nil
  161. }
  162. return out, nil
  163. default:
  164. return nil, fmt.Errorf("decoding strategy %v is not supported", strategy)
  165. }
  166. }
  167. func ValidateKeys(in map[string][]byte) bool {
  168. for key := range in {
  169. for _, v := range key {
  170. if !unicode.IsNumber(v) &&
  171. !unicode.IsLetter(v) &&
  172. v != '-' &&
  173. v != '.' &&
  174. v != '_' {
  175. return false
  176. }
  177. }
  178. }
  179. return true
  180. }
  181. // ConvertKeys converts a secret map into a valid key.
  182. // Replaces any non-alphanumeric characters depending on convert strategy.
  183. func ConvertKeys(strategy esv1beta1.ExternalSecretConversionStrategy, in map[string][]byte) (map[string][]byte, error) {
  184. out := make(map[string][]byte, len(in))
  185. for k, v := range in {
  186. key := convert(strategy, k)
  187. if _, exists := out[key]; exists {
  188. return nil, fmt.Errorf("secret name collision during conversion: %s", key)
  189. }
  190. out[key] = v
  191. }
  192. return out, nil
  193. }
  194. func convert(strategy esv1beta1.ExternalSecretConversionStrategy, str string) string {
  195. rs := []rune(str)
  196. newName := make([]string, len(rs))
  197. for rk, rv := range rs {
  198. if !unicode.IsNumber(rv) &&
  199. !unicode.IsLetter(rv) &&
  200. rv != '-' &&
  201. rv != '.' &&
  202. rv != '_' {
  203. switch strategy {
  204. case esv1beta1.ExternalSecretConversionDefault:
  205. newName[rk] = "_"
  206. case esv1beta1.ExternalSecretConversionUnicode:
  207. newName[rk] = fmt.Sprintf("_U%04x_", rv)
  208. default:
  209. newName[rk] = string(rv)
  210. }
  211. } else {
  212. newName[rk] = string(rv)
  213. }
  214. }
  215. return strings.Join(newName, "")
  216. }
  217. // MergeStringMap performs a deep clone from src to dest.
  218. func MergeStringMap(dest, src map[string]string) {
  219. for k, v := range src {
  220. dest[k] = v
  221. }
  222. }
  223. var (
  224. ErrUnexpectedKey = errors.New("unexpected key in data")
  225. ErrSecretType = errors.New("can not handle secret value with type")
  226. )
  227. func GetByteValueFromMap(data map[string]interface{}, key string) ([]byte, error) {
  228. v, ok := data[key]
  229. if !ok {
  230. return nil, fmt.Errorf("%w: %s", ErrUnexpectedKey, key)
  231. }
  232. return GetByteValue(v)
  233. }
  234. func GetByteValue(v interface{}) ([]byte, error) {
  235. switch t := v.(type) {
  236. case string:
  237. return []byte(t), nil
  238. case map[string]interface{}:
  239. return json.Marshal(t)
  240. case []string:
  241. return []byte(strings.Join(t, "\n")), nil
  242. case []byte:
  243. return t, nil
  244. // also covers int and float32 due to json.Marshal
  245. case float64:
  246. return []byte(strconv.FormatFloat(t, 'f', -1, 64)), nil
  247. case json.Number:
  248. return []byte(t.String()), nil
  249. case []interface{}:
  250. return json.Marshal(t)
  251. case bool:
  252. return []byte(strconv.FormatBool(t)), nil
  253. case nil:
  254. return []byte(nil), nil
  255. default:
  256. return nil, fmt.Errorf("%w: %T", ErrSecretType, t)
  257. }
  258. }
  259. // IsNil checks if an Interface is nil.
  260. func IsNil(i interface{}) bool {
  261. if i == nil {
  262. return true
  263. }
  264. value := reflect.ValueOf(i)
  265. if value.Type().Kind() == reflect.Ptr {
  266. return value.IsNil()
  267. }
  268. return false
  269. }
  270. // ObjectHash calculates md5 sum of the data contained in the secret.
  271. //
  272. //nolint:gosec
  273. func ObjectHash(object interface{}) string {
  274. textualVersion := fmt.Sprintf("%+v", object)
  275. return fmt.Sprintf("%x", md5.Sum([]byte(textualVersion)))
  276. }
  277. func ErrorContains(out error, want string) bool {
  278. if out == nil {
  279. return want == ""
  280. }
  281. if want == "" {
  282. return false
  283. }
  284. return strings.Contains(out.Error(), want)
  285. }
  286. var (
  287. errNamespaceNotAllowed = errors.New("namespace not allowed with namespaced SecretStore")
  288. errRequireNamespace = errors.New("cluster scope requires namespace")
  289. )
  290. // ValidateSecretSelector just checks if the namespace field is present/absent
  291. // depending on the secret store type.
  292. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  293. func ValidateSecretSelector(store esv1beta1.GenericStore, ref esmeta.SecretKeySelector) error {
  294. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  295. if clusterScope && ref.Namespace == nil {
  296. return errRequireNamespace
  297. }
  298. if !clusterScope && ref.Namespace != nil {
  299. return errNamespaceNotAllowed
  300. }
  301. return nil
  302. }
  303. // ValidateReferentSecretSelector allows
  304. // cluster scoped store without namespace
  305. // this should replace above ValidateServiceAccountSelector once all providers
  306. // support referent auth.
  307. func ValidateReferentSecretSelector(store esv1beta1.GenericStore, ref esmeta.SecretKeySelector) error {
  308. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  309. if !clusterScope && ref.Namespace != nil {
  310. return errNamespaceNotAllowed
  311. }
  312. return nil
  313. }
  314. // ValidateServiceAccountSelector just checks if the namespace field is present/absent
  315. // depending on the secret store type.
  316. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  317. func ValidateServiceAccountSelector(store esv1beta1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  318. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  319. if clusterScope && ref.Namespace == nil {
  320. return errRequireNamespace
  321. }
  322. if !clusterScope && ref.Namespace != nil {
  323. return errNamespaceNotAllowed
  324. }
  325. return nil
  326. }
  327. // ValidateReferentServiceAccountSelector allows
  328. // cluster scoped store without namespace
  329. // this should replace above ValidateServiceAccountSelector once all providers
  330. // support referent auth.
  331. func ValidateReferentServiceAccountSelector(store esv1beta1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  332. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  333. if !clusterScope && ref.Namespace != nil {
  334. return errNamespaceNotAllowed
  335. }
  336. return nil
  337. }
  338. func NetworkValidate(endpoint string, timeout time.Duration) error {
  339. hostname, err := url.Parse(endpoint)
  340. if err != nil {
  341. return fmt.Errorf("could not parse url: %w", err)
  342. }
  343. host := hostname.Hostname()
  344. port := hostname.Port()
  345. if port == "" {
  346. port = "443"
  347. }
  348. url := fmt.Sprintf("%v:%v", host, port)
  349. conn, err := net.DialTimeout("tcp", url, timeout)
  350. if err != nil {
  351. return fmt.Errorf("error accessing external store: %w", err)
  352. }
  353. defer conn.Close()
  354. return nil
  355. }
  356. func Deref[V any](v *V) V {
  357. if v == nil {
  358. // Create zero value
  359. var res V
  360. return res
  361. }
  362. return *v
  363. }
  364. func Ptr[T any](i T) *T {
  365. return &i
  366. }
  367. func ConvertToType[T any](obj interface{}) (T, error) {
  368. var v T
  369. data, err := json.Marshal(obj)
  370. if err != nil {
  371. return v, fmt.Errorf("failed to marshal object: %w", err)
  372. }
  373. if err = json.Unmarshal(data, &v); err != nil {
  374. return v, fmt.Errorf("failed to unmarshal object: %w", err)
  375. }
  376. return v, nil
  377. }
  378. // FetchValueFromMetadata fetches a key from a metadata if it exists. It will recursively look in
  379. // embedded values as well. Must be a unique key, otherwise it will just return the first
  380. // occurrence.
  381. func FetchValueFromMetadata[T any](key string, data *apiextensionsv1.JSON, def T) (t T, _ error) {
  382. if data == nil {
  383. return def, nil
  384. }
  385. m := map[string]any{}
  386. if err := json.Unmarshal(data.Raw, &m); err != nil {
  387. return t, fmt.Errorf("failed to parse JSON raw data: %w", err)
  388. }
  389. v, err := dig[T](key, m)
  390. if err != nil {
  391. if errors.Is(err, errKeyNotFound) {
  392. return def, nil
  393. }
  394. }
  395. return v, nil
  396. }
  397. func dig[T any](key string, data map[string]any) (t T, _ error) {
  398. if v, ok := data[key]; ok {
  399. c, k := v.(T)
  400. if !k {
  401. return t, fmt.Errorf("failed to convert value to the desired type; was: %T", v)
  402. }
  403. return c, nil
  404. }
  405. for _, v := range data {
  406. if ty, ok := v.(map[string]any); ok {
  407. return dig[T](key, ty)
  408. }
  409. }
  410. return t, errKeyNotFound
  411. }