utils.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. /*
  2. Copyright © The ESO Authors
  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/runtime/esutils/resolvers"
  52. estemplate "github.com/external-secrets/external-secrets/runtime/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. maps.Copy(dst, src)
  71. return dst
  72. }
  73. // RewriteMap applies a series of rewrite operations to the input map.
  74. func RewriteMap(operations []esv1.ExternalSecretRewrite, in map[string][]byte) (map[string][]byte, error) {
  75. out := in
  76. var err error
  77. for i, op := range operations {
  78. out, err = handleRewriteOperation(op, out)
  79. if err != nil {
  80. return nil, fmt.Errorf("failed rewrite operation[%v]: %w", i, err)
  81. }
  82. }
  83. return out, nil
  84. }
  85. func handleRewriteOperation(op esv1.ExternalSecretRewrite, in map[string][]byte) (map[string][]byte, error) {
  86. switch {
  87. case op.Merge != nil:
  88. return RewriteMerge(*op.Merge, in)
  89. case op.Regexp != nil:
  90. return RewriteRegexp(*op.Regexp, in)
  91. case op.Transform != nil:
  92. return RewriteTransform(*op.Transform, in)
  93. default:
  94. return in, nil
  95. }
  96. }
  97. // RewriteMerge merges input values according to the operation's strategy and conflict policy.
  98. func RewriteMerge(operation esv1.ExternalSecretRewriteMerge, in map[string][]byte) (map[string][]byte, error) {
  99. var out map[string][]byte
  100. mergedMap, conflicts, err := merge(operation, in)
  101. if err != nil {
  102. return nil, err
  103. }
  104. if operation.ConflictPolicy != esv1.ExternalSecretRewriteMergeConflictPolicyIgnore {
  105. if len(conflicts) > 0 {
  106. return nil, fmt.Errorf("merge failed with conflicts: %v", strings.Join(conflicts, ", "))
  107. }
  108. }
  109. switch operation.Strategy {
  110. case esv1.ExternalSecretRewriteMergeStrategyExtract, "":
  111. out = make(map[string][]byte)
  112. for k, v := range mergedMap {
  113. byteValue, err := GetByteValue(v)
  114. if err != nil {
  115. return nil, fmt.Errorf("merge failed with failed to convert value to []byte: %w", err)
  116. }
  117. out[k] = byteValue
  118. }
  119. case esv1.ExternalSecretRewriteMergeStrategyJSON:
  120. out = make(map[string][]byte)
  121. if operation.Into == "" {
  122. return nil, fmt.Errorf("merge failed with missing 'into' field")
  123. }
  124. mergedBytes, err := JSONMarshal(mergedMap)
  125. if err != nil {
  126. return nil, fmt.Errorf("merge failed with failed to marshal merged map: %w", err)
  127. }
  128. maps.Copy(out, in)
  129. out[operation.Into] = mergedBytes
  130. }
  131. return out, nil
  132. }
  133. // merge merges the input maps and returns the merged map and a list of conflicting keys.
  134. func merge(operation esv1.ExternalSecretRewriteMerge, in map[string][]byte) (map[string]any, []string, error) {
  135. mergedMap := make(map[string]any)
  136. conflicts := make([]string, 0)
  137. // sort keys with priority keys at the end in their specified order
  138. keys := sortKeysWithPriority(operation, in)
  139. for _, key := range keys {
  140. value, exists := in[key]
  141. if !exists {
  142. if operation.PriorityPolicy == esv1.ExternalSecretRewriteMergePriorityPolicyIgnoreNotFound {
  143. continue
  144. }
  145. return nil, nil, fmt.Errorf("merge failed with key %q not found in input map", key)
  146. }
  147. var jsonMap map[string]any
  148. if err := json.Unmarshal(value, &jsonMap); err != nil {
  149. return nil, nil, fmt.Errorf("merge failed with failed to unmarshal JSON: %w", err)
  150. }
  151. for k, v := range jsonMap {
  152. if _, conflict := mergedMap[k]; conflict {
  153. conflicts = append(conflicts, k)
  154. }
  155. mergedMap[k] = v
  156. }
  157. }
  158. return mergedMap, conflicts, nil
  159. }
  160. // sortKeysWithPriority sorts keys with priority keys at the end in their specified order.
  161. // Non-priority keys are sorted alphabetically and placed before priority keys.
  162. func sortKeysWithPriority(operation esv1.ExternalSecretRewriteMerge, in map[string][]byte) []string {
  163. keys := make([]string, 0, len(in))
  164. for k := range in {
  165. if !slices.Contains(operation.Priority, k) {
  166. keys = append(keys, k)
  167. }
  168. }
  169. sort.Strings(keys)
  170. keys = append(keys, operation.Priority...)
  171. return keys
  172. }
  173. // RewriteRegexp rewrites a single Regexp Rewrite Operation.
  174. func RewriteRegexp(operation esv1.ExternalSecretRewriteRegexp, in map[string][]byte) (map[string][]byte, error) {
  175. out := make(map[string][]byte)
  176. re, err := regexp.Compile(operation.Source)
  177. if err != nil {
  178. return nil, fmt.Errorf("regexp failed with failed to compile: %w", err)
  179. }
  180. for key, value := range in {
  181. newKey := re.ReplaceAllString(key, operation.Target)
  182. out[newKey] = value
  183. }
  184. return out, nil
  185. }
  186. // RewriteTransform applies string transformation on each secret key name to rewrite.
  187. func RewriteTransform(operation esv1.ExternalSecretRewriteTransform, in map[string][]byte) (map[string][]byte, error) {
  188. out := make(map[string][]byte)
  189. tmpl, err := template.New("transform").Funcs(estemplate.FuncMap()).Parse(operation.Template)
  190. if err != nil {
  191. return nil, fmt.Errorf("transform failed with failed to parse template: %w", err)
  192. }
  193. for key, value := range in {
  194. var buf bytes.Buffer
  195. if err := tmpl.Execute(&buf, map[string]string{"value": key}); err != nil {
  196. return nil, fmt.Errorf("transform failed with failed to execute template for key %q: %w", key, err)
  197. }
  198. out[buf.String()] = value
  199. }
  200. return out, nil
  201. }
  202. // DecodeMap decodes values from a secretMap.
  203. func DecodeMap(strategy esv1.ExternalSecretDecodingStrategy, in map[string][]byte) (map[string][]byte, error) {
  204. out := make(map[string][]byte, len(in))
  205. for k, v := range in {
  206. val, err := Decode(strategy, v)
  207. if err != nil {
  208. return nil, fmt.Errorf("failure decoding key %v: %w", k, err)
  209. }
  210. out[k] = val
  211. }
  212. return out, nil
  213. }
  214. // Decode decodes the input byte slice according to the provided decoding strategy.
  215. func Decode(strategy esv1.ExternalSecretDecodingStrategy, in []byte) ([]byte, error) {
  216. switch strategy {
  217. case esv1.ExternalSecretDecodeBase64:
  218. out, err := base64.StdEncoding.DecodeString(string(in))
  219. if err != nil {
  220. return nil, err
  221. }
  222. return out, nil
  223. case esv1.ExternalSecretDecodeBase64URL:
  224. out, err := base64.URLEncoding.DecodeString(string(in))
  225. if err != nil {
  226. return nil, err
  227. }
  228. return out, nil
  229. case esv1.ExternalSecretDecodeNone:
  230. return in, nil
  231. // default when stored version is v1alpha1
  232. case "":
  233. return in, nil
  234. case esv1.ExternalSecretDecodeAuto:
  235. out, err := Decode(esv1.ExternalSecretDecodeBase64, in)
  236. if err != nil {
  237. out, err := Decode(esv1.ExternalSecretDecodeBase64URL, in)
  238. if err != nil {
  239. return Decode(esv1.ExternalSecretDecodeNone, in)
  240. }
  241. return out, nil
  242. }
  243. return out, nil
  244. default:
  245. return nil, fmt.Errorf("decoding strategy %v is not supported", strategy)
  246. }
  247. }
  248. // ValidateKeys checks if the keys in the secret map are valid keys for a Kubernetes secret.
  249. func ValidateKeys(log logr.Logger, in map[string][]byte) error {
  250. for key := range in {
  251. keyLength := len(key)
  252. if keyLength == 0 {
  253. delete(in, key)
  254. log.V(1).Info("key was deleted from the secret output because it did not exist upstream", "key", key)
  255. continue
  256. }
  257. if keyLength > 253 {
  258. return fmt.Errorf("key has length %d but max is 253: (following is truncated): %s", keyLength, key[:253])
  259. }
  260. for _, c := range key {
  261. if !unicode.IsLetter(c) && !unicode.IsNumber(c) && c != '-' && c != '.' && c != '_' {
  262. return fmt.Errorf("key has invalid character %c, only alphanumeric, '-', '.' and '_' are allowed: %s", c, key)
  263. }
  264. }
  265. }
  266. return nil
  267. }
  268. // ConvertKeys converts a secret map into a valid key.
  269. // Replaces any non-alphanumeric characters depending on convert strategy.
  270. func ConvertKeys(strategy esv1.ExternalSecretConversionStrategy, in map[string][]byte) (map[string][]byte, error) {
  271. out := make(map[string][]byte, len(in))
  272. for k, v := range in {
  273. key := convert(strategy, k)
  274. if _, exists := out[key]; exists {
  275. return nil, fmt.Errorf("secret name collision during conversion: %s", key)
  276. }
  277. out[key] = v
  278. }
  279. return out, nil
  280. }
  281. func convert(strategy esv1.ExternalSecretConversionStrategy, str string) string {
  282. rs := []rune(str)
  283. newName := make([]string, len(rs))
  284. for rk, rv := range rs {
  285. if !unicode.IsNumber(rv) &&
  286. !unicode.IsLetter(rv) &&
  287. rv != '-' &&
  288. rv != '.' &&
  289. rv != '_' {
  290. switch strategy {
  291. case esv1.ExternalSecretConversionDefault:
  292. newName[rk] = "_"
  293. case esv1.ExternalSecretConversionUnicode:
  294. newName[rk] = fmt.Sprintf("_U%04x_", rv)
  295. default:
  296. newName[rk] = string(rv)
  297. }
  298. } else {
  299. newName[rk] = string(rv)
  300. }
  301. }
  302. return strings.Join(newName, "")
  303. }
  304. // ReverseKeys reverses a secret map into a valid key map as expected by push secrets.
  305. // Replaces the unicode encoded representation characters back to the actual unicode character depending on convert strategy.
  306. func ReverseKeys(strategy esv1alpha1.PushSecretConversionStrategy, in map[string][]byte) (map[string][]byte, error) {
  307. out := make(map[string][]byte, len(in))
  308. for k, v := range in {
  309. key := reverse(strategy, k)
  310. if _, exists := out[key]; exists {
  311. return nil, fmt.Errorf("secret name collision during conversion: %s", key)
  312. }
  313. out[key] = v
  314. }
  315. return out, nil
  316. }
  317. // ReverseKey applies the conversion strategy to a single key name.
  318. func ReverseKey(strategy esv1alpha1.PushSecretConversionStrategy, key string) string {
  319. return reverse(strategy, key)
  320. }
  321. func reverse(strategy esv1alpha1.PushSecretConversionStrategy, str string) string {
  322. switch strategy {
  323. case esv1alpha1.PushSecretConversionReverseUnicode:
  324. matches := unicodeRegex.FindAllStringSubmatchIndex(str, -1)
  325. for i := len(matches) - 1; i >= 0; i-- {
  326. match := matches[i]
  327. start := match[0]
  328. end := match[1]
  329. unicodeHex := str[match[2]:match[3]]
  330. unicodeInt, err := strconv.ParseInt(unicodeHex, 16, 32)
  331. if err != nil {
  332. continue // Skip invalid unicode representations
  333. }
  334. unicodeChar := fmt.Sprintf("%c", unicodeInt)
  335. str = str[:start] + unicodeChar + str[end:]
  336. }
  337. return str
  338. case esv1alpha1.PushSecretConversionNone:
  339. return str
  340. default:
  341. return str
  342. }
  343. }
  344. // MergeStringMap performs a deep clone from src to dest.
  345. func MergeStringMap(dest, src map[string]string) {
  346. maps.Copy(dest, src)
  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. //
  500. //go:fix inline
  501. func Ptr[T any](i T) *T {
  502. return new(i)
  503. }
  504. // ConvertToType converts an object to the specified type using JSON marshaling.
  505. func ConvertToType[T any](obj any) (T, error) {
  506. var v T
  507. data, err := json.Marshal(obj)
  508. if err != nil {
  509. return v, fmt.Errorf("failed to marshal object: %w", err)
  510. }
  511. if err = json.Unmarshal(data, &v); err != nil {
  512. return v, fmt.Errorf("failed to unmarshal object: %w", err)
  513. }
  514. return v, nil
  515. }
  516. // FetchValueFromMetadata fetches a key from a metadata if it exists. It will recursively look in
  517. // embedded values as well. Must be a unique key, otherwise it will just return the first
  518. // occurrence.
  519. func FetchValueFromMetadata[T any](key string, data *apiextensionsv1.JSON, def T) (t T, _ error) {
  520. if data == nil {
  521. return def, nil
  522. }
  523. m := map[string]any{}
  524. if err := json.Unmarshal(data.Raw, &m); err != nil {
  525. return t, fmt.Errorf("failed to parse JSON raw data: %w", err)
  526. }
  527. v, err := dig[T](key, m)
  528. if err != nil {
  529. if errors.Is(err, errKeyNotFound) {
  530. return def, nil
  531. }
  532. }
  533. return v, nil
  534. }
  535. func dig[T any](key string, data map[string]any) (t T, _ error) {
  536. if v, ok := data[key]; ok {
  537. c, k := v.(T)
  538. if !k {
  539. return t, fmt.Errorf("failed to convert value to the desired type; was: %T", v)
  540. }
  541. return c, nil
  542. }
  543. for _, v := range data {
  544. if ty, ok := v.(map[string]any); ok {
  545. return dig[T](key, ty)
  546. }
  547. }
  548. return t, errKeyNotFound
  549. }
  550. // CompareStringAndByteSlices compares a string pointer and a byte slice for equality.
  551. func CompareStringAndByteSlices(valueString *string, valueByte []byte) bool {
  552. if valueString == nil {
  553. return false
  554. }
  555. return bytes.Equal(valueByte, []byte(*valueString))
  556. }
  557. // ExtractSecretData extracts secret data from a Kubernetes Secret based on PushSecretData configuration.
  558. func ExtractSecretData(data esv1.PushSecretData, secret *corev1.Secret) ([]byte, error) {
  559. var (
  560. err error
  561. value []byte
  562. ok bool
  563. )
  564. if data.GetSecretKey() == "" {
  565. decodedMap := make(map[string]string)
  566. for k, v := range secret.Data {
  567. decodedMap[k] = string(v)
  568. }
  569. value, err = JSONMarshal(decodedMap)
  570. if err != nil {
  571. return nil, fmt.Errorf("failed to marshal secret data: %w", err)
  572. }
  573. } else {
  574. value, ok = secret.Data[data.GetSecretKey()]
  575. if !ok {
  576. return nil, fmt.Errorf("failed to find secret key in secret with key: %s", data.GetSecretKey())
  577. }
  578. }
  579. return value, nil
  580. }
  581. // CreateCertOpts contains options for a cert pool creation.
  582. type CreateCertOpts struct {
  583. CABundle []byte
  584. CAProvider *esv1.CAProvider
  585. StoreKind string
  586. Namespace string
  587. Client client.Client
  588. }
  589. // FetchCACertFromSource creates a CertPool using either a CABundle directly, or
  590. // a ConfigMap / Secret.
  591. func FetchCACertFromSource(ctx context.Context, opts CreateCertOpts) ([]byte, error) {
  592. if len(opts.CABundle) == 0 && opts.CAProvider == nil {
  593. return nil, nil
  594. }
  595. if len(opts.CABundle) > 0 {
  596. pem, err := base64decode(opts.CABundle)
  597. if err != nil {
  598. return nil, fmt.Errorf("failed to decode ca bundle: %w", err)
  599. }
  600. return pem, nil
  601. }
  602. if opts.CAProvider != nil &&
  603. opts.StoreKind == esv1.ClusterSecretStoreKind &&
  604. opts.CAProvider.Namespace == nil {
  605. return nil, errors.New("missing namespace on caProvider secret")
  606. }
  607. switch opts.CAProvider.Type {
  608. case esv1.CAProviderTypeSecret:
  609. cert, err := getCertFromSecret(ctx, opts.Client, opts.CAProvider, opts.StoreKind, opts.Namespace)
  610. if err != nil {
  611. return nil, fmt.Errorf("failed to get cert from secret: %w", err)
  612. }
  613. return cert, nil
  614. case esv1.CAProviderTypeConfigMap:
  615. cert, err := getCertFromConfigMap(ctx, opts.Namespace, opts.Client, opts.CAProvider)
  616. if err != nil {
  617. return nil, fmt.Errorf("failed to get cert from configmap: %w", err)
  618. }
  619. return cert, nil
  620. }
  621. return nil, fmt.Errorf("unsupported CA provider type: %s", opts.CAProvider.Type)
  622. }
  623. // GetTargetNamespaces extracts namespaces based on selectors.
  624. func GetTargetNamespaces(ctx context.Context, cl client.Client, namespaceList []string, lbs []*metav1.LabelSelector) ([]corev1.Namespace, error) {
  625. // make sure we don't alter the passed in slice.
  626. selectors := make([]*metav1.LabelSelector, 0, len(namespaceList)+len(lbs))
  627. for _, ns := range namespaceList {
  628. selectors = append(selectors, &metav1.LabelSelector{
  629. MatchLabels: map[string]string{
  630. "kubernetes.io/metadata.name": ns,
  631. },
  632. })
  633. }
  634. selectors = append(selectors, lbs...)
  635. var namespaces []corev1.Namespace
  636. namespaceSet := make(map[string]struct{})
  637. for _, selector := range selectors {
  638. labelSelector, err := metav1.LabelSelectorAsSelector(selector)
  639. if err != nil {
  640. return nil, fmt.Errorf("failed to convert label selector %s: %w", selector, err)
  641. }
  642. var nl corev1.NamespaceList
  643. err = cl.List(ctx, &nl, &client.ListOptions{LabelSelector: labelSelector})
  644. if err != nil {
  645. return nil, fmt.Errorf("failed to list namespaces by label selector %s: %w", selector, err)
  646. }
  647. for _, n := range nl.Items {
  648. if _, exist := namespaceSet[n.Name]; exist {
  649. continue
  650. }
  651. namespaceSet[n.Name] = struct{}{}
  652. namespaces = append(namespaces, n)
  653. }
  654. }
  655. return namespaces, nil
  656. }
  657. // NamespacePredicate can be used to watch for new or updated or deleted namespaces.
  658. func NamespacePredicate() predicate.Predicate {
  659. return predicate.Funcs{
  660. CreateFunc: func(_ event.CreateEvent) bool {
  661. return true
  662. },
  663. UpdateFunc: func(e event.UpdateEvent) bool {
  664. if e.ObjectOld == nil || e.ObjectNew == nil {
  665. return false
  666. }
  667. return !reflect.DeepEqual(e.ObjectOld.GetLabels(), e.ObjectNew.GetLabels())
  668. },
  669. DeleteFunc: func(_ event.DeleteEvent) bool {
  670. return true
  671. },
  672. }
  673. }
  674. func base64decode(cert []byte) ([]byte, error) {
  675. if c, err := parseCertificateBytes(cert); err == nil {
  676. return c, nil
  677. }
  678. // try decoding and test for validity again...
  679. certificate, err := Decode(esv1.ExternalSecretDecodeAuto, cert)
  680. if err != nil {
  681. return nil, fmt.Errorf("failed to decode base64: %w", err)
  682. }
  683. return parseCertificateBytes(certificate)
  684. }
  685. func parseCertificateBytes(certBytes []byte) ([]byte, error) {
  686. block, _ := pem.Decode(certBytes)
  687. if block == nil {
  688. return nil, errors.New("failed to parse the new certificate, not valid pem data")
  689. }
  690. if _, err := x509.ParseCertificate(block.Bytes); err != nil {
  691. return nil, fmt.Errorf("failed to validate certificate: %w", err)
  692. }
  693. return certBytes, nil
  694. }
  695. func getCertFromSecret(ctx context.Context, c client.Client, provider *esv1.CAProvider, storeKind, namespace string) ([]byte, error) {
  696. secretRef := esmeta.SecretKeySelector{
  697. Name: provider.Name,
  698. Key: provider.Key,
  699. }
  700. if provider.Namespace != nil {
  701. secretRef.Namespace = provider.Namespace
  702. }
  703. cert, err := resolvers.SecretKeyRef(ctx, c, storeKind, namespace, &secretRef)
  704. if err != nil {
  705. return nil, fmt.Errorf("failed to resolve secret key ref: %w", err)
  706. }
  707. return []byte(cert), nil
  708. }
  709. func getCertFromConfigMap(ctx context.Context, namespace string, c client.Client, provider *esv1.CAProvider) ([]byte, error) {
  710. objKey := client.ObjectKey{
  711. Name: provider.Name,
  712. Namespace: namespace,
  713. }
  714. if provider.Namespace != nil {
  715. objKey.Namespace = *provider.Namespace
  716. }
  717. configMapRef := &corev1.ConfigMap{}
  718. err := c.Get(ctx, objKey, configMapRef)
  719. if err != nil {
  720. return nil, fmt.Errorf("failed to get caProvider secret %s: %w", objKey.Name, err)
  721. }
  722. val, ok := configMapRef.Data[provider.Key]
  723. if !ok {
  724. return nil, fmt.Errorf("failed to get caProvider configMap %s -> %s", objKey.Name, provider.Key)
  725. }
  726. return []byte(val), nil
  727. }
  728. // CheckEndpointSlicesReady checks if there are any EndpointSlice objects for the given service
  729. // that have ready addresses.
  730. func CheckEndpointSlicesReady(ctx context.Context, c client.Client, svcName, svcNamespace string) error {
  731. var sliceList discoveryv1.EndpointSliceList
  732. err := c.List(ctx, &sliceList,
  733. client.InNamespace(svcNamespace),
  734. client.MatchingLabels{"kubernetes.io/service-name": svcName},
  735. )
  736. if err != nil {
  737. return err
  738. }
  739. if len(sliceList.Items) == 0 {
  740. return errEndpointSlicesNotReady
  741. }
  742. readyAddresses := 0
  743. for _, slice := range sliceList.Items {
  744. for _, ep := range slice.Endpoints {
  745. if ep.Conditions.Ready != nil && *ep.Conditions.Ready {
  746. readyAddresses += len(ep.Addresses)
  747. }
  748. }
  749. }
  750. if readyAddresses == 0 {
  751. return errAddressesNotReady
  752. }
  753. return nil
  754. }
  755. // ParseJWTClaims extracts claims from a JWT token string.
  756. func ParseJWTClaims(tokenString string) (map[string]any, error) {
  757. // Split the token into its three parts
  758. parts := strings.Split(tokenString, ".")
  759. if len(parts) != 3 {
  760. return nil, fmt.Errorf("invalid token format")
  761. }
  762. // Decode the payload (the second part of the token)
  763. payload, err := base64.RawURLEncoding.DecodeString(parts[1])
  764. if err != nil {
  765. return nil, fmt.Errorf("error decoding payload: %w", err)
  766. }
  767. var claims map[string]any
  768. if err := json.Unmarshal(payload, &claims); err != nil {
  769. return nil, fmt.Errorf("error un-marshaling claims: %w", err)
  770. }
  771. return claims, nil
  772. }
  773. // ExtractJWTExpiration extracts the expiration time from a JWT token string.
  774. func ExtractJWTExpiration(tokenString string) (string, error) {
  775. claims, err := ParseJWTClaims(tokenString)
  776. if err != nil {
  777. return "", fmt.Errorf("error getting claims: %w", err)
  778. }
  779. exp, ok := claims["exp"].(float64)
  780. if ok {
  781. return strconv.FormatFloat(exp, 'f', -1, 64), nil
  782. }
  783. return "", fmt.Errorf("exp claim not found or wrong type")
  784. }
  785. // FetchServiceAccountToken creates a service account token for the specified service account.
  786. func FetchServiceAccountToken(ctx context.Context, saRef esmeta.ServiceAccountSelector, namespace string) (string, error) {
  787. cfg, err := ctrlcfg.GetConfig()
  788. if err != nil {
  789. return "", err
  790. }
  791. kubeClient, err := kubernetes.NewForConfig(cfg)
  792. if err != nil {
  793. return "", fmt.Errorf("failed to create kubernetes client: %w", err)
  794. }
  795. tokenRequest := &authv1.TokenRequest{
  796. Spec: authv1.TokenRequestSpec{
  797. Audiences: saRef.Audiences,
  798. },
  799. }
  800. tokenResponse, err := kubeClient.CoreV1().ServiceAccounts(namespace).CreateToken(ctx, saRef.Name, tokenRequest, metav1.CreateOptions{})
  801. if err != nil {
  802. return "", fmt.Errorf("failed to create token: %w", err)
  803. }
  804. return tokenResponse.Status.Token, nil
  805. }