utils.go 26 KB

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