utils.go 27 KB

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