utils.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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. "context"
  16. "crypto/sha3"
  17. "crypto/x509"
  18. "encoding/base64"
  19. "encoding/json"
  20. "encoding/pem"
  21. "errors"
  22. "fmt"
  23. "maps"
  24. "net"
  25. "net/url"
  26. "reflect"
  27. "regexp"
  28. "slices"
  29. "sort"
  30. "strconv"
  31. "strings"
  32. tpl "text/template"
  33. "time"
  34. "unicode"
  35. "github.com/go-logr/logr"
  36. corev1 "k8s.io/api/core/v1"
  37. apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  38. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  39. "sigs.k8s.io/controller-runtime/pkg/client"
  40. "sigs.k8s.io/controller-runtime/pkg/event"
  41. "sigs.k8s.io/controller-runtime/pkg/predicate"
  42. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  43. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  44. esmeta "github.com/external-secrets/external-secrets/apis/meta/v1"
  45. "github.com/external-secrets/external-secrets/pkg/template/v2"
  46. "github.com/external-secrets/external-secrets/pkg/utils/resolvers"
  47. )
  48. const (
  49. errParse = "unable to parse transform template: %s"
  50. errExecute = "unable to execute transform template: %s"
  51. )
  52. var (
  53. errKeyNotFound = errors.New("key not found")
  54. unicodeRegex = regexp.MustCompile(`_U([0-9a-fA-F]{4,5})_`)
  55. )
  56. // JSONMarshal takes an interface and returns a new escaped and encoded byte slice.
  57. func JSONMarshal(t any) ([]byte, error) {
  58. buffer := &bytes.Buffer{}
  59. encoder := json.NewEncoder(buffer)
  60. encoder.SetEscapeHTML(false)
  61. err := encoder.Encode(t)
  62. return bytes.TrimRight(buffer.Bytes(), "\n"), err
  63. }
  64. // MergeByteMap merges map of byte slices.
  65. func MergeByteMap(dst, src map[string][]byte) map[string][]byte {
  66. for k, v := range src {
  67. dst[k] = v
  68. }
  69. return dst
  70. }
  71. func RewriteMap(operations []esv1.ExternalSecretRewrite, in map[string][]byte) (map[string][]byte, error) {
  72. out := in
  73. var err error
  74. for i, op := range operations {
  75. out, err = handleRewriteOperation(op, out)
  76. if err != nil {
  77. return nil, fmt.Errorf("failed rewrite operation[%v]: %w", i, err)
  78. }
  79. }
  80. return out, nil
  81. }
  82. func handleRewriteOperation(op esv1.ExternalSecretRewrite, in map[string][]byte) (map[string][]byte, error) {
  83. switch {
  84. case op.Merge != nil:
  85. return RewriteMerge(*op.Merge, in)
  86. case op.Regexp != nil:
  87. return RewriteRegexp(*op.Regexp, in)
  88. case op.Transform != nil:
  89. return RewriteTransform(*op.Transform, in)
  90. default:
  91. return in, nil
  92. }
  93. }
  94. // RewriteMerge merges input values according to the operation's strategy and conflict policy.
  95. func RewriteMerge(operation esv1.ExternalSecretRewriteMerge, in map[string][]byte) (map[string][]byte, error) {
  96. var out map[string][]byte
  97. mergedMap, conflicts, err := merge(operation, in)
  98. if err != nil {
  99. return nil, err
  100. }
  101. if operation.ConflictPolicy != esv1.ExternalSecretRewriteMergeConflictPolicyIgnore {
  102. if len(conflicts) > 0 {
  103. return nil, fmt.Errorf("merge failed with conflicts: %v", strings.Join(conflicts, ", "))
  104. }
  105. }
  106. switch operation.Strategy {
  107. case esv1.ExternalSecretRewriteMergeStrategyExtract, "":
  108. out = make(map[string][]byte)
  109. for k, v := range mergedMap {
  110. byteValue, err := GetByteValue(v)
  111. if err != nil {
  112. return nil, fmt.Errorf("merge failed with failed to convert value to []byte: %w", err)
  113. }
  114. out[k] = byteValue
  115. }
  116. case esv1.ExternalSecretRewriteMergeStrategyJSON:
  117. out = make(map[string][]byte)
  118. if operation.Into == "" {
  119. return nil, fmt.Errorf("merge failed with missing 'into' field")
  120. }
  121. mergedBytes, err := JSONMarshal(mergedMap)
  122. if err != nil {
  123. return nil, fmt.Errorf("merge failed with failed to marshal merged map: %w", err)
  124. }
  125. maps.Copy(out, in)
  126. out[operation.Into] = mergedBytes
  127. }
  128. return out, nil
  129. }
  130. // merge merges the input maps and returns the merged map and a list of conflicting keys.
  131. func merge(operation esv1.ExternalSecretRewriteMerge, in map[string][]byte) (map[string]any, []string, error) {
  132. mergedMap := make(map[string]any)
  133. conflicts := make([]string, 0)
  134. // sort keys with priority keys at the end in their specified order
  135. keys := sortKeysWithPriority(operation, in)
  136. for _, key := range keys {
  137. value, exists := in[key]
  138. if !exists {
  139. return nil, nil, fmt.Errorf("merge failed with key %q not found in input map", key)
  140. }
  141. var jsonMap map[string]any
  142. if err := json.Unmarshal(value, &jsonMap); err != nil {
  143. return nil, nil, fmt.Errorf("merge failed with failed to unmarshal JSON: %w", err)
  144. }
  145. for k, v := range jsonMap {
  146. if _, conflict := mergedMap[k]; conflict {
  147. conflicts = append(conflicts, k)
  148. }
  149. mergedMap[k] = v
  150. }
  151. }
  152. return mergedMap, conflicts, nil
  153. }
  154. // sortKeysWithPriority sorts keys with priority keys at the end in their specified order.
  155. // Non-priority keys are sorted alphabetically and placed before priority keys.
  156. func sortKeysWithPriority(operation esv1.ExternalSecretRewriteMerge, in map[string][]byte) []string {
  157. keys := make([]string, 0, len(in))
  158. for k := range in {
  159. if !slices.Contains(operation.Priority, k) {
  160. keys = append(keys, k)
  161. }
  162. }
  163. sort.Strings(keys)
  164. keys = append(keys, operation.Priority...)
  165. return keys
  166. }
  167. // RewriteRegexp rewrites a single Regexp Rewrite Operation.
  168. func RewriteRegexp(operation esv1.ExternalSecretRewriteRegexp, in map[string][]byte) (map[string][]byte, error) {
  169. out := make(map[string][]byte)
  170. re, err := regexp.Compile(operation.Source)
  171. if err != nil {
  172. return nil, fmt.Errorf("regexp failed with failed to compile: %w", err)
  173. }
  174. for key, value := range in {
  175. newKey := re.ReplaceAllString(key, operation.Target)
  176. out[newKey] = value
  177. }
  178. return out, nil
  179. }
  180. // RewriteTransform applies string transformation on each secret key name to rewrite.
  181. func RewriteTransform(operation esv1.ExternalSecretRewriteTransform, in map[string][]byte) (map[string][]byte, error) {
  182. out := make(map[string][]byte)
  183. for key, value := range in {
  184. data := map[string][]byte{
  185. "value": []byte(key),
  186. }
  187. result, err := transform(operation.Template, data)
  188. if err != nil {
  189. return nil, fmt.Errorf("transform failed with failed to transform key: %w", err)
  190. }
  191. newKey := string(result)
  192. out[newKey] = value
  193. }
  194. return out, nil
  195. }
  196. func transform(val string, data map[string][]byte) ([]byte, error) {
  197. strValData := make(map[string]string, len(data))
  198. for k := range data {
  199. strValData[k] = string(data[k])
  200. }
  201. t, err := tpl.New("transform").
  202. Funcs(template.FuncMap()).
  203. Parse(val)
  204. if err != nil {
  205. return nil, fmt.Errorf(errParse, err)
  206. }
  207. buf := bytes.NewBuffer(nil)
  208. err = t.Execute(buf, strValData)
  209. if err != nil {
  210. return nil, fmt.Errorf(errExecute, err)
  211. }
  212. return buf.Bytes(), nil
  213. }
  214. // DecodeMap decodes values from a secretMap.
  215. func DecodeMap(strategy esv1.ExternalSecretDecodingStrategy, in map[string][]byte) (map[string][]byte, error) {
  216. out := make(map[string][]byte, len(in))
  217. for k, v := range in {
  218. val, err := Decode(strategy, v)
  219. if err != nil {
  220. return nil, fmt.Errorf("failure decoding key %v: %w", k, err)
  221. }
  222. out[k] = val
  223. }
  224. return out, nil
  225. }
  226. func Decode(strategy esv1.ExternalSecretDecodingStrategy, in []byte) ([]byte, error) {
  227. switch strategy {
  228. case esv1.ExternalSecretDecodeBase64:
  229. out, err := base64.StdEncoding.DecodeString(string(in))
  230. if err != nil {
  231. return nil, err
  232. }
  233. return out, nil
  234. case esv1.ExternalSecretDecodeBase64URL:
  235. out, err := base64.URLEncoding.DecodeString(string(in))
  236. if err != nil {
  237. return nil, err
  238. }
  239. return out, nil
  240. case esv1.ExternalSecretDecodeNone:
  241. return in, nil
  242. // default when stored version is v1alpha1
  243. case "":
  244. return in, nil
  245. case esv1.ExternalSecretDecodeAuto:
  246. out, err := Decode(esv1.ExternalSecretDecodeBase64, in)
  247. if err != nil {
  248. out, err := Decode(esv1.ExternalSecretDecodeBase64URL, in)
  249. if err != nil {
  250. return Decode(esv1.ExternalSecretDecodeNone, in)
  251. }
  252. return out, nil
  253. }
  254. return out, nil
  255. default:
  256. return nil, fmt.Errorf("decoding strategy %v is not supported", strategy)
  257. }
  258. }
  259. // ValidateKeys checks if the keys in the secret map are valid keys for a Kubernetes secret.
  260. func ValidateKeys(log logr.Logger, in map[string][]byte) error {
  261. for key := range in {
  262. keyLength := len(key)
  263. if keyLength == 0 {
  264. delete(in, key)
  265. log.V(1).Info("key was deleted from the secret output because it did not exist upstream", "key", key)
  266. continue
  267. }
  268. if keyLength > 253 {
  269. return fmt.Errorf("key has length %d but max is 253: (following is truncated): %s", keyLength, key[:253])
  270. }
  271. for _, c := range key {
  272. if !unicode.IsLetter(c) && !unicode.IsNumber(c) && c != '-' && c != '.' && c != '_' {
  273. return fmt.Errorf("key has invalid character %c, only alphanumeric, '-', '.' and '_' are allowed: %s", c, key)
  274. }
  275. }
  276. }
  277. return nil
  278. }
  279. // ConvertKeys converts a secret map into a valid key.
  280. // Replaces any non-alphanumeric characters depending on convert strategy.
  281. func ConvertKeys(strategy esv1.ExternalSecretConversionStrategy, in map[string][]byte) (map[string][]byte, error) {
  282. out := make(map[string][]byte, len(in))
  283. for k, v := range in {
  284. key := convert(strategy, k)
  285. if _, exists := out[key]; exists {
  286. return nil, fmt.Errorf("secret name collision during conversion: %s", key)
  287. }
  288. out[key] = v
  289. }
  290. return out, nil
  291. }
  292. func convert(strategy esv1.ExternalSecretConversionStrategy, str string) string {
  293. rs := []rune(str)
  294. newName := make([]string, len(rs))
  295. for rk, rv := range rs {
  296. if !unicode.IsNumber(rv) &&
  297. !unicode.IsLetter(rv) &&
  298. rv != '-' &&
  299. rv != '.' &&
  300. rv != '_' {
  301. switch strategy {
  302. case esv1.ExternalSecretConversionDefault:
  303. newName[rk] = "_"
  304. case esv1.ExternalSecretConversionUnicode:
  305. newName[rk] = fmt.Sprintf("_U%04x_", rv)
  306. default:
  307. newName[rk] = string(rv)
  308. }
  309. } else {
  310. newName[rk] = string(rv)
  311. }
  312. }
  313. return strings.Join(newName, "")
  314. }
  315. // ReverseKeys reverses a secret map into a valid key map as expected by push secrets.
  316. // Replaces the unicode encoded representation characters back to the actual unicode character depending on convert strategy.
  317. func ReverseKeys(strategy esv1alpha1.PushSecretConversionStrategy, in map[string][]byte) (map[string][]byte, error) {
  318. out := make(map[string][]byte, len(in))
  319. for k, v := range in {
  320. key := reverse(strategy, k)
  321. if _, exists := out[key]; exists {
  322. return nil, fmt.Errorf("secret name collision during conversion: %s", key)
  323. }
  324. out[key] = v
  325. }
  326. return out, nil
  327. }
  328. func reverse(strategy esv1alpha1.PushSecretConversionStrategy, str string) string {
  329. switch strategy {
  330. case esv1alpha1.PushSecretConversionReverseUnicode:
  331. matches := unicodeRegex.FindAllStringSubmatchIndex(str, -1)
  332. for i := len(matches) - 1; i >= 0; i-- {
  333. match := matches[i]
  334. start := match[0]
  335. end := match[1]
  336. unicodeHex := str[match[2]:match[3]]
  337. unicodeInt, err := strconv.ParseInt(unicodeHex, 16, 32)
  338. if err != nil {
  339. continue // Skip invalid unicode representations
  340. }
  341. unicodeChar := fmt.Sprintf("%c", unicodeInt)
  342. str = str[:start] + unicodeChar + str[end:]
  343. }
  344. return str
  345. case esv1alpha1.PushSecretConversionNone:
  346. return str
  347. default:
  348. return str
  349. }
  350. }
  351. // MergeStringMap performs a deep clone from src to dest.
  352. func MergeStringMap(dest, src map[string]string) {
  353. for k, v := range src {
  354. dest[k] = v
  355. }
  356. }
  357. var (
  358. ErrUnexpectedKey = errors.New("unexpected key in data")
  359. ErrSecretType = errors.New("can not handle secret value with type")
  360. )
  361. func GetByteValueFromMap(data map[string]any, key string) ([]byte, error) {
  362. v, ok := data[key]
  363. if !ok {
  364. return nil, fmt.Errorf("%w: %s", ErrUnexpectedKey, key)
  365. }
  366. return GetByteValue(v)
  367. }
  368. func GetByteValue(v any) ([]byte, error) {
  369. switch t := v.(type) {
  370. case string:
  371. return []byte(t), nil
  372. case map[string]any:
  373. return json.Marshal(t)
  374. case []string:
  375. return []byte(strings.Join(t, "\n")), nil
  376. case json.RawMessage:
  377. return t, nil
  378. case []byte:
  379. return t, nil
  380. // also covers int and float32 due to json.Marshal
  381. case float64:
  382. return []byte(strconv.FormatFloat(t, 'f', -1, 64)), nil
  383. case json.Number:
  384. return []byte(t.String()), nil
  385. case []any:
  386. return json.Marshal(t)
  387. case bool:
  388. return []byte(strconv.FormatBool(t)), nil
  389. case nil:
  390. return []byte(nil), nil
  391. default:
  392. return nil, fmt.Errorf("%w: %T", ErrSecretType, t)
  393. }
  394. }
  395. // IsNil checks if an Interface is nil.
  396. func IsNil(i any) bool {
  397. if i == nil {
  398. return true
  399. }
  400. value := reflect.ValueOf(i)
  401. if value.Type().Kind() == reflect.Ptr {
  402. return value.IsNil()
  403. }
  404. return false
  405. }
  406. // ObjectHash calculates sha3 sum of the data contained in the secret.
  407. func ObjectHash(object any) string {
  408. textualVersion := fmt.Sprintf("%+v", object)
  409. return fmt.Sprintf("%x", sha3.Sum224([]byte(textualVersion)))
  410. }
  411. func ErrorContains(out error, want string) bool {
  412. if out == nil {
  413. return want == ""
  414. }
  415. if want == "" {
  416. return false
  417. }
  418. return strings.Contains(out.Error(), want)
  419. }
  420. var (
  421. errNamespaceNotAllowed = errors.New("namespace should either be empty or match the namespace of the SecretStore for a namespaced SecretStore")
  422. errRequireNamespace = errors.New("cluster scope requires namespace")
  423. )
  424. // ValidateSecretSelector just checks if the namespace field is present/absent
  425. // depending on the secret store type.
  426. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  427. func ValidateSecretSelector(store esv1.GenericStore, ref esmeta.SecretKeySelector) error {
  428. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1.ClusterSecretStoreKind
  429. if clusterScope && ref.Namespace == nil {
  430. return errRequireNamespace
  431. }
  432. if !clusterScope && ref.Namespace != nil && *ref.Namespace != store.GetNamespace() {
  433. return errNamespaceNotAllowed
  434. }
  435. return nil
  436. }
  437. // ValidateReferentSecretSelector allows
  438. // cluster scoped store without namespace
  439. // this should replace above ValidateServiceAccountSelector once all providers
  440. // support referent auth.
  441. func ValidateReferentSecretSelector(store esv1.GenericStore, ref esmeta.SecretKeySelector) error {
  442. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1.ClusterSecretStoreKind
  443. if !clusterScope && ref.Namespace != nil && *ref.Namespace != store.GetNamespace() {
  444. return errNamespaceNotAllowed
  445. }
  446. return nil
  447. }
  448. // ValidateServiceAccountSelector just checks if the namespace field is present/absent
  449. // depending on the secret store type.
  450. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  451. func ValidateServiceAccountSelector(store esv1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  452. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1.ClusterSecretStoreKind
  453. if clusterScope && ref.Namespace == nil {
  454. return errRequireNamespace
  455. }
  456. if !clusterScope && ref.Namespace != nil && *ref.Namespace != store.GetNamespace() {
  457. return errNamespaceNotAllowed
  458. }
  459. return nil
  460. }
  461. // ValidateReferentServiceAccountSelector allows
  462. // cluster scoped store without namespace
  463. // this should replace above ValidateServiceAccountSelector once all providers
  464. // support referent auth.
  465. func ValidateReferentServiceAccountSelector(store esv1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  466. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1.ClusterSecretStoreKind
  467. if !clusterScope && ref.Namespace != nil && *ref.Namespace != store.GetNamespace() {
  468. return errNamespaceNotAllowed
  469. }
  470. return nil
  471. }
  472. func NetworkValidate(endpoint string, timeout time.Duration) error {
  473. hostname, err := url.Parse(endpoint)
  474. if err != nil {
  475. return fmt.Errorf("could not parse url: %w", err)
  476. }
  477. host := hostname.Hostname()
  478. port := hostname.Port()
  479. if port == "" {
  480. port = "443"
  481. }
  482. url := fmt.Sprintf("%v:%v", host, port)
  483. conn, err := net.DialTimeout("tcp", url, timeout)
  484. if err != nil {
  485. return fmt.Errorf("error accessing external store: %w", err)
  486. }
  487. defer func() {
  488. _ = conn.Close()
  489. }()
  490. return nil
  491. }
  492. func Deref[V any](v *V) V {
  493. if v == nil {
  494. // Create zero value
  495. var res V
  496. return res
  497. }
  498. return *v
  499. }
  500. func Ptr[T any](i T) *T {
  501. return &i
  502. }
  503. func ConvertToType[T any](obj any) (T, error) {
  504. var v T
  505. data, err := json.Marshal(obj)
  506. if err != nil {
  507. return v, fmt.Errorf("failed to marshal object: %w", err)
  508. }
  509. if err = json.Unmarshal(data, &v); err != nil {
  510. return v, fmt.Errorf("failed to unmarshal object: %w", err)
  511. }
  512. return v, nil
  513. }
  514. // FetchValueFromMetadata fetches a key from a metadata if it exists. It will recursively look in
  515. // embedded values as well. Must be a unique key, otherwise it will just return the first
  516. // occurrence.
  517. func FetchValueFromMetadata[T any](key string, data *apiextensionsv1.JSON, def T) (t T, _ error) {
  518. if data == nil {
  519. return def, nil
  520. }
  521. m := map[string]any{}
  522. if err := json.Unmarshal(data.Raw, &m); err != nil {
  523. return t, fmt.Errorf("failed to parse JSON raw data: %w", err)
  524. }
  525. v, err := dig[T](key, m)
  526. if err != nil {
  527. if errors.Is(err, errKeyNotFound) {
  528. return def, nil
  529. }
  530. }
  531. return v, nil
  532. }
  533. func dig[T any](key string, data map[string]any) (t T, _ error) {
  534. if v, ok := data[key]; ok {
  535. c, k := v.(T)
  536. if !k {
  537. return t, fmt.Errorf("failed to convert value to the desired type; was: %T", v)
  538. }
  539. return c, nil
  540. }
  541. for _, v := range data {
  542. if ty, ok := v.(map[string]any); ok {
  543. return dig[T](key, ty)
  544. }
  545. }
  546. return t, errKeyNotFound
  547. }
  548. func CompareStringAndByteSlices(valueString *string, valueByte []byte) bool {
  549. if valueString == nil {
  550. return false
  551. }
  552. return bytes.Equal(valueByte, []byte(*valueString))
  553. }
  554. func ExtractSecretData(data esv1.PushSecretData, secret *corev1.Secret) ([]byte, error) {
  555. var (
  556. err error
  557. value []byte
  558. ok bool
  559. )
  560. if data.GetSecretKey() == "" {
  561. decodedMap := make(map[string]string)
  562. for k, v := range secret.Data {
  563. decodedMap[k] = string(v)
  564. }
  565. value, err = JSONMarshal(decodedMap)
  566. if err != nil {
  567. return nil, fmt.Errorf("failed to marshal secret data: %w", err)
  568. }
  569. } else {
  570. value, ok = secret.Data[data.GetSecretKey()]
  571. if !ok {
  572. return nil, fmt.Errorf("failed to find secret key in secret with key: %s", data.GetSecretKey())
  573. }
  574. }
  575. return value, nil
  576. }
  577. // CreateCertOpts contains options for a cert pool creation.
  578. type CreateCertOpts struct {
  579. CABundle []byte
  580. CAProvider *esv1.CAProvider
  581. StoreKind string
  582. Namespace string
  583. Client client.Client
  584. }
  585. // FetchCACertFromSource creates a CertPool using either a CABundle directly, or
  586. // a ConfigMap / Secret.
  587. func FetchCACertFromSource(ctx context.Context, opts CreateCertOpts) ([]byte, error) {
  588. if len(opts.CABundle) == 0 && opts.CAProvider == nil {
  589. return nil, nil
  590. }
  591. if len(opts.CABundle) > 0 {
  592. pem, err := base64decode(opts.CABundle)
  593. if err != nil {
  594. return nil, fmt.Errorf("failed to decode ca bundle: %w", err)
  595. }
  596. return pem, nil
  597. }
  598. if opts.CAProvider != nil &&
  599. opts.StoreKind == esv1.ClusterSecretStoreKind &&
  600. opts.CAProvider.Namespace == nil {
  601. return nil, errors.New("missing namespace on caProvider secret")
  602. }
  603. switch opts.CAProvider.Type {
  604. case esv1.CAProviderTypeSecret:
  605. cert, err := getCertFromSecret(ctx, opts.Client, opts.CAProvider, opts.StoreKind, opts.Namespace)
  606. if err != nil {
  607. return nil, fmt.Errorf("failed to get cert from secret: %w", err)
  608. }
  609. return cert, nil
  610. case esv1.CAProviderTypeConfigMap:
  611. cert, err := getCertFromConfigMap(ctx, opts.Namespace, opts.Client, opts.CAProvider)
  612. if err != nil {
  613. return nil, fmt.Errorf("failed to get cert from configmap: %w", err)
  614. }
  615. return cert, nil
  616. }
  617. return nil, fmt.Errorf("unsupported CA provider type: %s", opts.CAProvider.Type)
  618. }
  619. // GetTargetNamespaces extracts namespaces based on selectors.
  620. func GetTargetNamespaces(ctx context.Context, cl client.Client, namespaceList []string, lbs []*metav1.LabelSelector) ([]corev1.Namespace, error) {
  621. // make sure we don't alter the passed in slice.
  622. selectors := make([]*metav1.LabelSelector, 0, len(namespaceList)+len(lbs))
  623. for _, ns := range namespaceList {
  624. selectors = append(selectors, &metav1.LabelSelector{
  625. MatchLabels: map[string]string{
  626. "kubernetes.io/metadata.name": ns,
  627. },
  628. })
  629. }
  630. selectors = append(selectors, lbs...)
  631. var namespaces []corev1.Namespace
  632. namespaceSet := make(map[string]struct{})
  633. for _, selector := range selectors {
  634. labelSelector, err := metav1.LabelSelectorAsSelector(selector)
  635. if err != nil {
  636. return nil, fmt.Errorf("failed to convert label selector %s: %w", selector, err)
  637. }
  638. var nl corev1.NamespaceList
  639. err = cl.List(ctx, &nl, &client.ListOptions{LabelSelector: labelSelector})
  640. if err != nil {
  641. return nil, fmt.Errorf("failed to list namespaces by label selector %s: %w", selector, err)
  642. }
  643. for _, n := range nl.Items {
  644. if _, exist := namespaceSet[n.Name]; exist {
  645. continue
  646. }
  647. namespaceSet[n.Name] = struct{}{}
  648. namespaces = append(namespaces, n)
  649. }
  650. }
  651. return namespaces, nil
  652. }
  653. // NamespacePredicate can be used to watch for new or updated or deleted namespaces.
  654. func NamespacePredicate() predicate.Predicate {
  655. return predicate.Funcs{
  656. CreateFunc: func(e event.CreateEvent) bool {
  657. return true
  658. },
  659. UpdateFunc: func(e event.UpdateEvent) bool {
  660. if e.ObjectOld == nil || e.ObjectNew == nil {
  661. return false
  662. }
  663. return !reflect.DeepEqual(e.ObjectOld.GetLabels(), e.ObjectNew.GetLabels())
  664. },
  665. DeleteFunc: func(deleteEvent event.DeleteEvent) bool {
  666. return true
  667. },
  668. }
  669. }
  670. func base64decode(cert []byte) ([]byte, error) {
  671. if c, err := parseCertificateBytes(cert); err == nil {
  672. return c, nil
  673. }
  674. // try decoding and test for validity again...
  675. certificate, err := Decode(esv1.ExternalSecretDecodeAuto, cert)
  676. if err != nil {
  677. return nil, fmt.Errorf("failed to decode base64: %w", err)
  678. }
  679. return parseCertificateBytes(certificate)
  680. }
  681. func parseCertificateBytes(certBytes []byte) ([]byte, error) {
  682. block, _ := pem.Decode(certBytes)
  683. if block == nil {
  684. return nil, errors.New("failed to parse the new certificate, not valid pem data")
  685. }
  686. if _, err := x509.ParseCertificate(block.Bytes); err != nil {
  687. return nil, fmt.Errorf("failed to validate certificate: %w", err)
  688. }
  689. return certBytes, nil
  690. }
  691. func getCertFromSecret(ctx context.Context, c client.Client, provider *esv1.CAProvider, storeKind, namespace string) ([]byte, error) {
  692. secretRef := esmeta.SecretKeySelector{
  693. Name: provider.Name,
  694. Key: provider.Key,
  695. }
  696. if provider.Namespace != nil {
  697. secretRef.Namespace = provider.Namespace
  698. }
  699. cert, err := resolvers.SecretKeyRef(ctx, c, storeKind, namespace, &secretRef)
  700. if err != nil {
  701. return nil, fmt.Errorf("failed to resolve secret key ref: %w", err)
  702. }
  703. return []byte(cert), nil
  704. }
  705. func getCertFromConfigMap(ctx context.Context, namespace string, c client.Client, provider *esv1.CAProvider) ([]byte, error) {
  706. objKey := client.ObjectKey{
  707. Name: provider.Name,
  708. Namespace: namespace,
  709. }
  710. if provider.Namespace != nil {
  711. objKey.Namespace = *provider.Namespace
  712. }
  713. configMapRef := &corev1.ConfigMap{}
  714. err := c.Get(ctx, objKey, configMapRef)
  715. if err != nil {
  716. return nil, fmt.Errorf("failed to get caProvider secret %s: %w", objKey.Name, err)
  717. }
  718. val, ok := configMapRef.Data[provider.Key]
  719. if !ok {
  720. return nil, fmt.Errorf("failed to get caProvider configMap %s -> %s", objKey.Name, provider.Key)
  721. }
  722. return []byte(val), nil
  723. }