utils.go 27 KB

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