utils.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  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. return transformKeys(in, func(key string) string {
  227. return convert(strategy, key)
  228. })
  229. }
  230. func convert(strategy esv1.ExternalSecretConversionStrategy, str string) string {
  231. rs := []rune(str)
  232. newName := make([]string, len(rs))
  233. for rk, rv := range rs {
  234. if !unicode.IsNumber(rv) &&
  235. !unicode.IsLetter(rv) &&
  236. rv != '-' &&
  237. rv != '.' &&
  238. rv != '_' {
  239. switch strategy {
  240. case esv1.ExternalSecretConversionDefault:
  241. newName[rk] = "_"
  242. case esv1.ExternalSecretConversionUnicode:
  243. newName[rk] = fmt.Sprintf("_U%04x_", rv)
  244. default:
  245. newName[rk] = string(rv)
  246. }
  247. } else {
  248. newName[rk] = string(rv)
  249. }
  250. }
  251. return strings.Join(newName, "")
  252. }
  253. // ReverseKeys reverses a secret map into a valid key map as expected by push secrets.
  254. // Replaces the unicode encoded representation characters back to the actual unicode character depending on convert strategy.
  255. func ReverseKeys(strategy esv1alpha1.PushSecretConversionStrategy, in map[string][]byte) (map[string][]byte, error) {
  256. return transformKeys(in, func(key string) string {
  257. return reverse(strategy, key)
  258. })
  259. }
  260. func transformKeys(in map[string][]byte, transform func(string) string) (map[string][]byte, error) {
  261. out := make(map[string][]byte, len(in))
  262. for k, v := range in {
  263. key := transform(k)
  264. if _, exists := out[key]; exists {
  265. return nil, fmt.Errorf("secret name collision during conversion: %s", key)
  266. }
  267. out[key] = v
  268. }
  269. return out, nil
  270. }
  271. // ReverseKey applies the conversion strategy to a single key name.
  272. func ReverseKey(strategy esv1alpha1.PushSecretConversionStrategy, key string) string {
  273. return reverse(strategy, key)
  274. }
  275. func reverse(strategy esv1alpha1.PushSecretConversionStrategy, str string) string {
  276. switch strategy {
  277. case esv1alpha1.PushSecretConversionReverseUnicode:
  278. matches := unicodeRegex.FindAllStringSubmatchIndex(str, -1)
  279. for i := len(matches) - 1; i >= 0; i-- {
  280. match := matches[i]
  281. start := match[0]
  282. end := match[1]
  283. unicodeHex := str[match[2]:match[3]]
  284. unicodeInt, err := strconv.ParseInt(unicodeHex, 16, 32)
  285. if err != nil {
  286. continue // Skip invalid unicode representations
  287. }
  288. unicodeChar := fmt.Sprintf("%c", unicodeInt)
  289. str = str[:start] + unicodeChar + str[end:]
  290. }
  291. return str
  292. case esv1alpha1.PushSecretConversionNone:
  293. return str
  294. default:
  295. return str
  296. }
  297. }
  298. // MergeStringMap performs a deep clone from src to dest.
  299. func MergeStringMap(dest, src map[string]string) {
  300. maps.Copy(dest, src)
  301. }
  302. var (
  303. // ErrUnexpectedKey is returned when an unexpected key is found in the data.
  304. ErrUnexpectedKey = errors.New("unexpected key in data")
  305. // ErrSecretType is returned when a secret value cannot be handled due to its type.
  306. ErrSecretType = errors.New("can not handle secret value with type")
  307. )
  308. // JSONToSecretDataMap unmarshals a JSON object into secret key/value pairs.
  309. // String values are unquoted; all other JSON types are kept as raw JSON bytes.
  310. func JSONToSecretDataMap(data []byte) (map[string][]byte, error) {
  311. kv := make(map[string]json.RawMessage)
  312. if err := json.Unmarshal(data, &kv); err != nil {
  313. return nil, err
  314. }
  315. secretData := make(map[string][]byte, len(kv))
  316. for k, v := range kv {
  317. var strVal string
  318. if err := json.Unmarshal(v, &strVal); err == nil {
  319. secretData[k] = []byte(strVal)
  320. } else {
  321. secretData[k] = v
  322. }
  323. }
  324. return secretData, nil
  325. }
  326. // GetByteValueFromMap retrieves a byte value from a map by key.
  327. func GetByteValueFromMap(data map[string]any, key string) ([]byte, error) {
  328. v, ok := data[key]
  329. if !ok {
  330. return nil, fmt.Errorf("%w: %s", ErrUnexpectedKey, key)
  331. }
  332. return GetByteValue(v)
  333. }
  334. // GetByteValue converts an interface value to a byte slice.
  335. func GetByteValue(v any) ([]byte, error) {
  336. switch t := v.(type) {
  337. case string:
  338. return []byte(t), nil
  339. case map[string]any:
  340. return json.Marshal(t)
  341. case []string:
  342. return []byte(strings.Join(t, "\n")), nil
  343. case json.RawMessage:
  344. return t, nil
  345. case []byte:
  346. return t, nil
  347. // also covers int and float32 due to json.Marshal
  348. case float64:
  349. return []byte(strconv.FormatFloat(t, 'f', -1, 64)), nil
  350. case json.Number:
  351. return []byte(t.String()), nil
  352. case []any:
  353. return json.Marshal(t)
  354. case bool:
  355. return []byte(strconv.FormatBool(t)), nil
  356. case nil:
  357. return []byte(nil), nil
  358. default:
  359. return nil, fmt.Errorf("%w: %T", ErrSecretType, t)
  360. }
  361. }
  362. // IsNil checks if an Interface is nil.
  363. func IsNil(i any) bool {
  364. if i == nil {
  365. return true
  366. }
  367. value := reflect.ValueOf(i)
  368. if value.Type().Kind() == reflect.Ptr {
  369. return value.IsNil()
  370. }
  371. return false
  372. }
  373. // ObjectHash calculates sha3 sum of the data contained in the secret.
  374. func ObjectHash(object any) string {
  375. textualVersion := fmt.Sprintf("%+v", object)
  376. return fmt.Sprintf("%x", sha3.Sum224([]byte(textualVersion)))
  377. }
  378. // ErrorContains checks if the error message contains the specified substring.
  379. func ErrorContains(out error, want string) bool {
  380. if out == nil {
  381. return want == ""
  382. }
  383. if want == "" {
  384. return false
  385. }
  386. return strings.Contains(out.Error(), want)
  387. }
  388. var (
  389. errNamespaceNotAllowed = errors.New("namespace should either be empty or match the namespace of the SecretStore for a namespaced SecretStore")
  390. errRequireNamespace = errors.New("cluster scope requires namespace")
  391. )
  392. // ValidateSecretSelector just checks if the namespace field is present/absent
  393. // depending on the secret store type.
  394. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  395. func ValidateSecretSelector(store esv1.GenericStore, ref esmeta.SecretKeySelector) error {
  396. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1.ClusterSecretStoreKind
  397. if clusterScope && ref.Namespace == nil {
  398. return errRequireNamespace
  399. }
  400. if !clusterScope && ref.Namespace != nil && *ref.Namespace != store.GetNamespace() {
  401. return errNamespaceNotAllowed
  402. }
  403. return nil
  404. }
  405. // ValidateReferentSecretSelector allows
  406. // cluster scoped store without namespace
  407. // this should replace above ValidateServiceAccountSelector once all providers
  408. // support referent auth.
  409. func ValidateReferentSecretSelector(store esv1.GenericStore, ref esmeta.SecretKeySelector) error {
  410. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1.ClusterSecretStoreKind
  411. if !clusterScope && ref.Namespace != nil && *ref.Namespace != store.GetNamespace() {
  412. return errNamespaceNotAllowed
  413. }
  414. return nil
  415. }
  416. // ValidateServiceAccountSelector just checks if the namespace field is present/absent
  417. // depending on the secret store type.
  418. // We MUST NOT check the name or key property here. It MAY be defaulted by the provider.
  419. func ValidateServiceAccountSelector(store esv1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  420. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1.ClusterSecretStoreKind
  421. if clusterScope && ref.Namespace == nil {
  422. return errRequireNamespace
  423. }
  424. if !clusterScope && ref.Namespace != nil && *ref.Namespace != store.GetNamespace() {
  425. return errNamespaceNotAllowed
  426. }
  427. return nil
  428. }
  429. // ValidateReferentServiceAccountSelector allows
  430. // cluster scoped store without namespace
  431. // this should replace above ValidateServiceAccountSelector once all providers
  432. // support referent auth.
  433. func ValidateReferentServiceAccountSelector(store esv1.GenericStore, ref esmeta.ServiceAccountSelector) error {
  434. clusterScope := store.GetObjectKind().GroupVersionKind().Kind == esv1.ClusterSecretStoreKind
  435. if !clusterScope && ref.Namespace != nil && *ref.Namespace != store.GetNamespace() {
  436. return errNamespaceNotAllowed
  437. }
  438. return nil
  439. }
  440. // NetworkValidate checks if a network endpoint is reachable within the given timeout.
  441. func NetworkValidate(endpoint string, timeout time.Duration) error {
  442. hostname, err := url.Parse(endpoint)
  443. if err != nil {
  444. return fmt.Errorf("could not parse url: %w", err)
  445. }
  446. host := hostname.Hostname()
  447. port := hostname.Port()
  448. if port == "" {
  449. port = "443"
  450. }
  451. url := fmt.Sprintf("%v:%v", host, port)
  452. conn, err := net.DialTimeout("tcp", url, timeout)
  453. if err != nil {
  454. return fmt.Errorf("error accessing external store: %w", err)
  455. }
  456. defer func() {
  457. _ = conn.Close()
  458. }()
  459. return nil
  460. }
  461. // Deref returns the value pointed to by v, or the zero value if v is nil.
  462. func Deref[V any](v *V) V {
  463. if v == nil {
  464. // Create zero value
  465. var res V
  466. return res
  467. }
  468. return *v
  469. }
  470. // Ptr returns a pointer to the given value.
  471. //
  472. //go:fix inline
  473. func Ptr[T any](i T) *T {
  474. return new(i)
  475. }
  476. // ConvertToType converts an object to the specified type using JSON marshaling.
  477. func ConvertToType[T any](obj any) (T, error) {
  478. var v T
  479. data, err := json.Marshal(obj)
  480. if err != nil {
  481. return v, fmt.Errorf("failed to marshal object: %w", err)
  482. }
  483. if err = json.Unmarshal(data, &v); err != nil {
  484. return v, fmt.Errorf("failed to unmarshal object: %w", err)
  485. }
  486. return v, nil
  487. }
  488. // FetchValueFromMetadata fetches a key from a metadata if it exists. It will recursively look in
  489. // embedded values as well. Must be a unique key, otherwise it will just return the first
  490. // occurrence.
  491. func FetchValueFromMetadata[T any](key string, data *apiextensionsv1.JSON, def T) (t T, _ error) {
  492. if data == nil {
  493. return def, nil
  494. }
  495. m := map[string]any{}
  496. if err := json.Unmarshal(data.Raw, &m); err != nil {
  497. return t, fmt.Errorf("failed to parse JSON raw data: %w", err)
  498. }
  499. v, err := dig[T](key, m)
  500. if err != nil {
  501. if errors.Is(err, errKeyNotFound) {
  502. return def, nil
  503. }
  504. }
  505. return v, nil
  506. }
  507. func dig[T any](key string, data map[string]any) (t T, _ error) {
  508. if v, ok := data[key]; ok {
  509. c, k := v.(T)
  510. if !k {
  511. return t, fmt.Errorf("failed to convert value to the desired type; was: %T", v)
  512. }
  513. return c, nil
  514. }
  515. for _, v := range data {
  516. if ty, ok := v.(map[string]any); ok {
  517. return dig[T](key, ty)
  518. }
  519. }
  520. return t, errKeyNotFound
  521. }
  522. // CompareStringAndByteSlices compares a string pointer and a byte slice for equality.
  523. func CompareStringAndByteSlices(valueString *string, valueByte []byte) bool {
  524. if valueString == nil {
  525. return false
  526. }
  527. return bytes.Equal(valueByte, []byte(*valueString))
  528. }
  529. // ExtractSecretData extracts secret data from a Kubernetes Secret based on PushSecretData configuration.
  530. func ExtractSecretData(data esv1.PushSecretData, secret *corev1.Secret) ([]byte, error) {
  531. var (
  532. err error
  533. value []byte
  534. ok bool
  535. )
  536. if data.GetSecretKey() == "" {
  537. decodedMap := make(map[string]string)
  538. for k, v := range secret.Data {
  539. decodedMap[k] = string(v)
  540. }
  541. value, err = JSONMarshal(decodedMap)
  542. if err != nil {
  543. return nil, fmt.Errorf("failed to marshal secret data: %w", err)
  544. }
  545. } else {
  546. value, ok = secret.Data[data.GetSecretKey()]
  547. if !ok {
  548. return nil, fmt.Errorf("failed to find secret key in secret with key: %s", data.GetSecretKey())
  549. }
  550. }
  551. return value, nil
  552. }
  553. // CreateCertOpts contains options for a cert pool creation.
  554. type CreateCertOpts struct {
  555. CABundle []byte
  556. CAProvider *esv1.CAProvider
  557. StoreKind string
  558. Namespace string
  559. Client client.Client
  560. }
  561. // FetchCACertFromSource creates a CertPool using either a CABundle directly, or
  562. // a ConfigMap / Secret.
  563. func FetchCACertFromSource(ctx context.Context, opts CreateCertOpts) ([]byte, error) {
  564. if len(opts.CABundle) == 0 && opts.CAProvider == nil {
  565. return nil, nil
  566. }
  567. if len(opts.CABundle) > 0 {
  568. pem, err := base64decode(opts.CABundle)
  569. if err != nil {
  570. return nil, fmt.Errorf("failed to decode ca bundle: %w", err)
  571. }
  572. return pem, nil
  573. }
  574. if opts.CAProvider != nil &&
  575. opts.StoreKind != esv1.ClusterSecretStoreKind &&
  576. opts.CAProvider.Namespace != nil &&
  577. *opts.CAProvider.Namespace != opts.Namespace {
  578. return nil, errNamespaceNotAllowed
  579. }
  580. if opts.CAProvider != nil &&
  581. opts.StoreKind == esv1.ClusterSecretStoreKind &&
  582. opts.CAProvider.Namespace == nil {
  583. return nil, errors.New("missing namespace on caProvider secret")
  584. }
  585. switch opts.CAProvider.Type {
  586. case esv1.CAProviderTypeSecret:
  587. cert, err := getCertFromSecret(ctx, opts.Client, opts.CAProvider, opts.StoreKind, opts.Namespace)
  588. if err != nil {
  589. return nil, fmt.Errorf("failed to get cert from secret: %w", err)
  590. }
  591. return cert, nil
  592. case esv1.CAProviderTypeConfigMap:
  593. cert, err := getCertFromConfigMap(ctx, opts.Namespace, opts.Client, opts.CAProvider, opts.StoreKind)
  594. if err != nil {
  595. return nil, fmt.Errorf("failed to get cert from configmap: %w", err)
  596. }
  597. return cert, nil
  598. }
  599. return nil, fmt.Errorf("unsupported CA provider type: %s", opts.CAProvider.Type)
  600. }
  601. // GetTargetNamespaces extracts namespaces based on selectors.
  602. func GetTargetNamespaces(ctx context.Context, cl client.Client, namespaceList []string, lbs []*metav1.LabelSelector) ([]corev1.Namespace, error) {
  603. // make sure we don't alter the passed in slice.
  604. selectors := make([]*metav1.LabelSelector, 0, len(namespaceList)+len(lbs))
  605. for _, ns := range namespaceList {
  606. selectors = append(selectors, &metav1.LabelSelector{
  607. MatchLabels: map[string]string{
  608. "kubernetes.io/metadata.name": ns,
  609. },
  610. })
  611. }
  612. selectors = append(selectors, lbs...)
  613. var namespaces []corev1.Namespace
  614. namespaceSet := make(map[string]struct{})
  615. for _, selector := range selectors {
  616. labelSelector, err := metav1.LabelSelectorAsSelector(selector)
  617. if err != nil {
  618. return nil, fmt.Errorf("failed to convert label selector %s: %w", selector, err)
  619. }
  620. var nl corev1.NamespaceList
  621. err = cl.List(ctx, &nl, &client.ListOptions{LabelSelector: labelSelector})
  622. if err != nil {
  623. return nil, fmt.Errorf("failed to list namespaces by label selector %s: %w", selector, err)
  624. }
  625. for _, n := range nl.Items {
  626. if _, exist := namespaceSet[n.Name]; exist {
  627. continue
  628. }
  629. namespaceSet[n.Name] = struct{}{}
  630. namespaces = append(namespaces, n)
  631. }
  632. }
  633. return namespaces, nil
  634. }
  635. // NamespacePredicate can be used to watch for new or updated or deleted namespaces.
  636. func NamespacePredicate() predicate.Predicate {
  637. return predicate.Funcs{
  638. CreateFunc: func(_ event.CreateEvent) bool {
  639. return true
  640. },
  641. UpdateFunc: func(e event.UpdateEvent) bool {
  642. if e.ObjectOld == nil || e.ObjectNew == nil {
  643. return false
  644. }
  645. return !reflect.DeepEqual(e.ObjectOld.GetLabels(), e.ObjectNew.GetLabels())
  646. },
  647. DeleteFunc: func(_ event.DeleteEvent) bool {
  648. return true
  649. },
  650. }
  651. }
  652. func base64decode(cert []byte) ([]byte, error) {
  653. if c, err := parseCertificateBytes(cert); err == nil {
  654. return c, nil
  655. }
  656. // try decoding and test for validity again...
  657. certificate, err := decoding.Decode(esv1.ExternalSecretDecodeAuto, cert)
  658. if err != nil {
  659. return nil, fmt.Errorf("failed to decode base64: %w", err)
  660. }
  661. return parseCertificateBytes(certificate)
  662. }
  663. func parseCertificateBytes(certBytes []byte) ([]byte, error) {
  664. block, _ := pem.Decode(certBytes)
  665. if block == nil {
  666. return nil, errors.New("failed to parse the new certificate, not valid pem data")
  667. }
  668. if _, err := x509.ParseCertificate(block.Bytes); err != nil {
  669. return nil, fmt.Errorf("failed to validate certificate: %w", err)
  670. }
  671. return certBytes, nil
  672. }
  673. func getCertFromSecret(ctx context.Context, c client.Client, provider *esv1.CAProvider, storeKind, namespace string) ([]byte, error) {
  674. secretRef := esmeta.SecretKeySelector{
  675. Name: provider.Name,
  676. Key: provider.Key,
  677. }
  678. if provider.Namespace != nil {
  679. secretRef.Namespace = provider.Namespace
  680. }
  681. cert, err := resolvers.SecretKeyRef(ctx, c, storeKind, namespace, &secretRef)
  682. if err != nil {
  683. return nil, fmt.Errorf("failed to resolve secret key ref: %w", err)
  684. }
  685. return []byte(cert), nil
  686. }
  687. func getCertFromConfigMap(ctx context.Context, namespace string, c client.Client, provider *esv1.CAProvider, storeKind string) ([]byte, error) {
  688. objKey := client.ObjectKey{
  689. Name: provider.Name,
  690. Namespace: namespace,
  691. }
  692. if provider.Namespace != nil && storeKind == esv1.ClusterSecretStoreKind {
  693. objKey.Namespace = *provider.Namespace
  694. }
  695. configMapRef := &corev1.ConfigMap{}
  696. err := c.Get(ctx, objKey, configMapRef)
  697. if err != nil {
  698. return nil, fmt.Errorf("failed to get caProvider secret %s: %w", objKey.Name, err)
  699. }
  700. val, ok := configMapRef.Data[provider.Key]
  701. if !ok {
  702. return nil, fmt.Errorf("failed to get caProvider configMap %s -> %s", objKey.Name, provider.Key)
  703. }
  704. return []byte(val), nil
  705. }
  706. // CheckEndpointSlicesReady checks if there are any EndpointSlice objects for the given service
  707. // that have ready addresses.
  708. func CheckEndpointSlicesReady(ctx context.Context, c client.Client, svcName, svcNamespace string) error {
  709. var sliceList discoveryv1.EndpointSliceList
  710. err := c.List(ctx, &sliceList,
  711. client.InNamespace(svcNamespace),
  712. client.MatchingLabels{"kubernetes.io/service-name": svcName},
  713. )
  714. if err != nil {
  715. return err
  716. }
  717. if len(sliceList.Items) == 0 {
  718. return errEndpointSlicesNotReady
  719. }
  720. readyAddresses := 0
  721. for _, slice := range sliceList.Items {
  722. for _, ep := range slice.Endpoints {
  723. if ep.Conditions.Ready != nil && *ep.Conditions.Ready {
  724. readyAddresses += len(ep.Addresses)
  725. }
  726. }
  727. }
  728. if readyAddresses == 0 {
  729. return errAddressesNotReady
  730. }
  731. return nil
  732. }
  733. // ParseJWTClaims extracts claims from a JWT token string.
  734. func ParseJWTClaims(tokenString string) (map[string]any, error) {
  735. // Split the token into its three parts
  736. parts := strings.Split(tokenString, ".")
  737. if len(parts) != 3 {
  738. return nil, fmt.Errorf("invalid token format")
  739. }
  740. // Decode the payload (the second part of the token)
  741. payload, err := base64.RawURLEncoding.DecodeString(parts[1])
  742. if err != nil {
  743. return nil, fmt.Errorf("error decoding payload: %w", err)
  744. }
  745. var claims map[string]any
  746. if err := json.Unmarshal(payload, &claims); err != nil {
  747. return nil, fmt.Errorf("error un-marshaling claims: %w", err)
  748. }
  749. return claims, nil
  750. }
  751. // ExtractJWTExpiration extracts the expiration time from a JWT token string.
  752. func ExtractJWTExpiration(tokenString string) (string, error) {
  753. claims, err := ParseJWTClaims(tokenString)
  754. if err != nil {
  755. return "", fmt.Errorf("error getting claims: %w", err)
  756. }
  757. exp, ok := claims["exp"].(float64)
  758. if ok {
  759. return strconv.FormatFloat(exp, 'f', -1, 64), nil
  760. }
  761. return "", fmt.Errorf("exp claim not found or wrong type")
  762. }
  763. // FetchServiceAccountToken creates a service account token for the specified service account.
  764. func FetchServiceAccountToken(ctx context.Context, saRef esmeta.ServiceAccountSelector, namespace string) (string, error) {
  765. cfg, err := ctrlcfg.GetConfig()
  766. if err != nil {
  767. return "", err
  768. }
  769. kubeClient, err := kubernetes.NewForConfig(cfg)
  770. if err != nil {
  771. return "", fmt.Errorf("failed to create kubernetes client: %w", err)
  772. }
  773. tokenRequest := &authv1.TokenRequest{
  774. Spec: authv1.TokenRequestSpec{
  775. Audiences: saRef.Audiences,
  776. },
  777. }
  778. tokenResponse, err := kubeClient.CoreV1().ServiceAccounts(namespace).CreateToken(ctx, saRef.Name, tokenRequest, metav1.CreateOptions{})
  779. if err != nil {
  780. return "", fmt.Errorf("failed to create token: %w", err)
  781. }
  782. return tokenResponse.Status.Token, nil
  783. }