utils.go 27 KB

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