utils.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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 json.RawMessage:
  243. return t, nil
  244. case []byte:
  245. return t, nil
  246. // also covers int and float32 due to json.Marshal
  247. case float64:
  248. return []byte(strconv.FormatFloat(t, 'f', -1, 64)), nil
  249. case json.Number:
  250. return []byte(t.String()), nil
  251. case []interface{}:
  252. return json.Marshal(t)
  253. case bool:
  254. return []byte(strconv.FormatBool(t)), nil
  255. case nil:
  256. return []byte(nil), nil
  257. default:
  258. return nil, fmt.Errorf("%w: %T", ErrSecretType, t)
  259. }
  260. }
  261. // IsNil checks if an Interface is nil.
  262. func IsNil(i interface{}) bool {
  263. if i == nil {
  264. return true
  265. }
  266. value := reflect.ValueOf(i)
  267. if value.Type().Kind() == reflect.Ptr {
  268. return value.IsNil()
  269. }
  270. return false
  271. }
  272. // ObjectHash calculates md5 sum of the data contained in the secret.
  273. //
  274. //nolint:gosec
  275. func ObjectHash(object interface{}) string {
  276. textualVersion := fmt.Sprintf("%+v", object)
  277. return fmt.Sprintf("%x", md5.Sum([]byte(textualVersion)))
  278. }
  279. func ErrorContains(out error, want string) bool {
  280. if out == nil {
  281. return want == ""
  282. }
  283. if want == "" {
  284. return false
  285. }
  286. return strings.Contains(out.Error(), want)
  287. }
  288. var (
  289. errNamespaceNotAllowed = errors.New("namespace not allowed with namespaced SecretStore")
  290. errRequireNamespace = errors.New("cluster scope requires namespace")
  291. )
  292. // ValidateSecretSelector just checks if the namespace field is present/absent
  293. // depending on the secret store type.
  294. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  295. func ValidateSecretSelector(store esv1beta1.GenericStore, ref esmeta.SecretKeySelector) error {
  296. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  297. if clusterScope && ref.Namespace == nil {
  298. return errRequireNamespace
  299. }
  300. if !clusterScope && ref.Namespace != nil {
  301. return errNamespaceNotAllowed
  302. }
  303. return nil
  304. }
  305. // ValidateReferentSecretSelector allows
  306. // cluster scoped store without namespace
  307. // this should replace above ValidateServiceAccountSelector once all providers
  308. // support referent auth.
  309. func ValidateReferentSecretSelector(store esv1beta1.GenericStore, ref esmeta.SecretKeySelector) error {
  310. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  311. if !clusterScope && ref.Namespace != nil {
  312. return errNamespaceNotAllowed
  313. }
  314. return nil
  315. }
  316. // ValidateServiceAccountSelector just checks if the namespace field is present/absent
  317. // depending on the secret store type.
  318. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  319. func ValidateServiceAccountSelector(store esv1beta1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  320. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  321. if clusterScope && ref.Namespace == nil {
  322. return errRequireNamespace
  323. }
  324. if !clusterScope && ref.Namespace != nil {
  325. return errNamespaceNotAllowed
  326. }
  327. return nil
  328. }
  329. // ValidateReferentServiceAccountSelector allows
  330. // cluster scoped store without namespace
  331. // this should replace above ValidateServiceAccountSelector once all providers
  332. // support referent auth.
  333. func ValidateReferentServiceAccountSelector(store esv1beta1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  334. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  335. if !clusterScope && ref.Namespace != nil {
  336. return errNamespaceNotAllowed
  337. }
  338. return nil
  339. }
  340. func NetworkValidate(endpoint string, timeout time.Duration) error {
  341. hostname, err := url.Parse(endpoint)
  342. if err != nil {
  343. return fmt.Errorf("could not parse url: %w", err)
  344. }
  345. host := hostname.Hostname()
  346. port := hostname.Port()
  347. if port == "" {
  348. port = "443"
  349. }
  350. url := fmt.Sprintf("%v:%v", host, port)
  351. conn, err := net.DialTimeout("tcp", url, timeout)
  352. if err != nil {
  353. return fmt.Errorf("error accessing external store: %w", err)
  354. }
  355. defer conn.Close()
  356. return nil
  357. }
  358. func Deref[V any](v *V) V {
  359. if v == nil {
  360. // Create zero value
  361. var res V
  362. return res
  363. }
  364. return *v
  365. }
  366. func Ptr[T any](i T) *T {
  367. return &i
  368. }
  369. func ConvertToType[T any](obj interface{}) (T, error) {
  370. var v T
  371. data, err := json.Marshal(obj)
  372. if err != nil {
  373. return v, fmt.Errorf("failed to marshal object: %w", err)
  374. }
  375. if err = json.Unmarshal(data, &v); err != nil {
  376. return v, fmt.Errorf("failed to unmarshal object: %w", err)
  377. }
  378. return v, nil
  379. }
  380. // FetchValueFromMetadata fetches a key from a metadata if it exists. It will recursively look in
  381. // embedded values as well. Must be a unique key, otherwise it will just return the first
  382. // occurrence.
  383. func FetchValueFromMetadata[T any](key string, data *apiextensionsv1.JSON, def T) (t T, _ error) {
  384. if data == nil {
  385. return def, nil
  386. }
  387. m := map[string]any{}
  388. if err := json.Unmarshal(data.Raw, &m); err != nil {
  389. return t, fmt.Errorf("failed to parse JSON raw data: %w", err)
  390. }
  391. v, err := dig[T](key, m)
  392. if err != nil {
  393. if errors.Is(err, errKeyNotFound) {
  394. return def, nil
  395. }
  396. }
  397. return v, nil
  398. }
  399. func dig[T any](key string, data map[string]any) (t T, _ error) {
  400. if v, ok := data[key]; ok {
  401. c, k := v.(T)
  402. if !k {
  403. return t, fmt.Errorf("failed to convert value to the desired type; was: %T", v)
  404. }
  405. return c, nil
  406. }
  407. for _, v := range data {
  408. if ty, ok := v.(map[string]any); ok {
  409. return dig[T](key, ty)
  410. }
  411. }
  412. return t, errKeyNotFound
  413. }