client_get.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package vault
  13. import (
  14. "context"
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "strings"
  19. "github.com/tidwall/gjson"
  20. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  21. "github.com/external-secrets/external-secrets/pkg/constants"
  22. "github.com/external-secrets/external-secrets/pkg/metrics"
  23. "github.com/external-secrets/external-secrets/pkg/utils"
  24. )
  25. const (
  26. errReadSecret = "cannot read secret data from Vault: %w"
  27. errDataField = "failed to find data field"
  28. errJSONUnmarshall = "failed to unmarshall JSON"
  29. errPathInvalid = "provided Path isn't a valid kv v2 path"
  30. errUnsupportedMetadataKvVersion = "cannot perform metadata fetch operations with kv version v1"
  31. errNotFound = "secret not found"
  32. errSecretKeyFmt = "cannot find secret data for key: %q"
  33. )
  34. // GetSecret supports two types:
  35. // 1. get the full secret as json-encoded value
  36. // by leaving the ref.Property empty.
  37. // 2. get a key from the secret.
  38. // Nested values are supported by specifying a gjson expression
  39. func (c *client) GetSecret(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) ([]byte, error) {
  40. var data map[string]interface{}
  41. var err error
  42. if ref.MetadataPolicy == esv1beta1.ExternalSecretMetadataPolicyFetch {
  43. if c.store.Version == esv1beta1.VaultKVStoreV1 {
  44. return nil, errors.New(errUnsupportedMetadataKvVersion)
  45. }
  46. metadata, err := c.readSecretMetadata(ctx, ref.Key)
  47. if err != nil {
  48. return nil, err
  49. }
  50. if len(metadata) == 0 {
  51. return nil, nil
  52. }
  53. data = make(map[string]interface{}, len(metadata))
  54. for k, v := range metadata {
  55. data[k] = v
  56. }
  57. } else {
  58. data, err = c.readSecret(ctx, ref.Key, ref.Version)
  59. if err != nil {
  60. return nil, err
  61. }
  62. }
  63. // Return nil if secret value is null
  64. if data == nil {
  65. return nil, esv1beta1.NoSecretError{}
  66. }
  67. jsonStr, err := json.Marshal(data)
  68. if err != nil {
  69. return nil, err
  70. }
  71. // (1): return raw json if no property is defined
  72. if ref.Property == "" {
  73. return jsonStr, nil
  74. }
  75. // For backwards compatibility we want the
  76. // actual keys to take precedence over gjson syntax
  77. // (2): extract key from secret with property
  78. if _, ok := data[ref.Property]; ok {
  79. return utils.GetByteValueFromMap(data, ref.Property)
  80. }
  81. // (3): extract key from secret using gjson
  82. val := gjson.Get(string(jsonStr), ref.Property)
  83. if !val.Exists() {
  84. return nil, fmt.Errorf(errSecretKeyFmt, ref.Property)
  85. }
  86. return []byte(val.String()), nil
  87. }
  88. // GetSecretMap supports two modes of operation:
  89. // 1. get the full secret from the vault data payload (by leaving .property empty).
  90. // 2. extract key/value pairs from a (nested) object.
  91. func (c *client) GetSecretMap(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  92. data, err := c.GetSecret(ctx, ref)
  93. if err != nil {
  94. return nil, err
  95. }
  96. var secretData map[string]interface{}
  97. err = json.Unmarshal(data, &secretData)
  98. if err != nil {
  99. return nil, err
  100. }
  101. byteMap := make(map[string][]byte, len(secretData))
  102. for k := range secretData {
  103. byteMap[k], err = utils.GetByteValueFromMap(secretData, k)
  104. if err != nil {
  105. return nil, err
  106. }
  107. }
  108. return byteMap, nil
  109. }
  110. func (c *client) readSecret(ctx context.Context, path, version string) (map[string]interface{}, error) {
  111. dataPath := c.buildPath(path)
  112. // path formated according to vault docs for v1 and v2 API
  113. // v1: https://www.vaultproject.io/api-docs/secret/kv/kv-v1#read-secret
  114. // v2: https://www.vaultproject.io/api/secret/kv/kv-v2#read-secret-version
  115. var params map[string][]string
  116. if version != "" {
  117. params = make(map[string][]string)
  118. params["version"] = []string{version}
  119. }
  120. vaultSecret, err := c.logical.ReadWithDataWithContext(ctx, dataPath, params)
  121. metrics.ObserveAPICall(constants.ProviderHCVault, constants.CallHCVaultReadSecretData, err)
  122. if err != nil {
  123. return nil, fmt.Errorf(errReadSecret, err)
  124. }
  125. if vaultSecret == nil {
  126. return nil, esv1beta1.NoSecretError{}
  127. }
  128. secretData := vaultSecret.Data
  129. if c.store.Version == esv1beta1.VaultKVStoreV2 {
  130. // Vault KV2 has data embedded within sub-field
  131. // reference - https://www.vaultproject.io/api/secret/kv/kv-v2#read-secret-version
  132. dataInt, ok := vaultSecret.Data["data"]
  133. if !ok {
  134. return nil, errors.New(errDataField)
  135. }
  136. if dataInt == nil {
  137. return nil, esv1beta1.NoSecretError{}
  138. }
  139. secretData, ok = dataInt.(map[string]interface{})
  140. if !ok {
  141. return nil, errors.New(errJSONUnmarshall)
  142. }
  143. }
  144. return secretData, nil
  145. }
  146. func (c *client) readSecretMetadata(ctx context.Context, path string) (map[string]string, error) {
  147. metadata := make(map[string]string)
  148. url, err := c.buildMetadataPath(path)
  149. if err != nil {
  150. return nil, err
  151. }
  152. secret, err := c.logical.ReadWithDataWithContext(ctx, url, nil)
  153. metrics.ObserveAPICall(constants.ProviderHCVault, constants.CallHCVaultReadSecretData, err)
  154. if err != nil {
  155. return nil, fmt.Errorf(errReadSecret, err)
  156. }
  157. if secret == nil {
  158. return nil, errors.New(errNotFound)
  159. }
  160. t, ok := secret.Data["custom_metadata"]
  161. if !ok {
  162. return nil, nil
  163. }
  164. d, ok := t.(map[string]interface{})
  165. if !ok {
  166. return metadata, nil
  167. }
  168. for k, v := range d {
  169. metadata[k] = v.(string)
  170. }
  171. return metadata, nil
  172. }
  173. func (c *client) buildMetadataPath(path string) (string, error) {
  174. var url string
  175. if c.store.Version == esv1beta1.VaultKVStoreV1 {
  176. url = fmt.Sprintf("%s/%s", *c.store.Path, path)
  177. } else { // KV v2 is used
  178. if c.store.Path == nil && !strings.Contains(path, "data") {
  179. return "", fmt.Errorf(errPathInvalid)
  180. }
  181. if c.store.Path == nil {
  182. path = strings.Replace(path, "data", "metadata", 1)
  183. url = path
  184. } else {
  185. url = fmt.Sprintf("%s/metadata/%s", *c.store.Path, path)
  186. }
  187. }
  188. return url, nil
  189. }
  190. /*
  191. buildPath is a helper method to build the vault equivalent path
  192. from ExternalSecrets and SecretStore manifests. the path build logic
  193. varies depending on the SecretStore KV version:
  194. Example inputs/outputs:
  195. # simple build:
  196. kv version == "v2":
  197. provider_path: "secret/path"
  198. input: "foo"
  199. output: "secret/path/data/foo" # provider_path and data are prepended
  200. kv version == "v1":
  201. provider_path: "secret/path"
  202. input: "foo"
  203. output: "secret/path/foo" # provider_path is prepended
  204. # inheriting paths:
  205. kv version == "v2":
  206. provider_path: "secret/path"
  207. input: "secret/path/foo"
  208. output: "secret/path/data/foo" #data is prepended
  209. kv version == "v2":
  210. provider_path: "secret/path"
  211. input: "secret/path/data/foo"
  212. output: "secret/path/data/foo" #noop
  213. kv version == "v1":
  214. provider_path: "secret/path"
  215. input: "secret/path/foo"
  216. output: "secret/path/foo" #noop
  217. # provider path not defined:
  218. kv version == "v2":
  219. provider_path: nil
  220. input: "secret/path/foo"
  221. output: "secret/data/path/foo" # data is prepended to secret/
  222. kv version == "v2":
  223. provider_path: nil
  224. input: "secret/path/data/foo"
  225. output: "secret/path/data/foo" #noop
  226. kv version == "v1":
  227. provider_path: nil
  228. input: "secret/path/foo"
  229. output: "secret/path/foo" #noop
  230. */
  231. func (c *client) buildPath(path string) string {
  232. optionalMount := c.store.Path
  233. out := path
  234. // if optionalMount is Set, remove it from path if its there
  235. if optionalMount != nil {
  236. cut := *optionalMount + "/"
  237. if strings.HasPrefix(out, cut) {
  238. // This current logic induces a bug when the actual secret resides on same path names as the mount path.
  239. _, out, _ = strings.Cut(out, cut)
  240. // if data succeeds optionalMount on v2 store, we should remove it as well
  241. if strings.HasPrefix(out, "data/") && c.store.Version == esv1beta1.VaultKVStoreV2 {
  242. _, out, _ = strings.Cut(out, "data/")
  243. }
  244. }
  245. buildPath := strings.Split(out, "/")
  246. buildMount := strings.Split(*optionalMount, "/")
  247. if c.store.Version == esv1beta1.VaultKVStoreV2 {
  248. buildMount = append(buildMount, "data")
  249. }
  250. buildMount = append(buildMount, buildPath...)
  251. out = strings.Join(buildMount, "/")
  252. return out
  253. }
  254. if !strings.Contains(out, "/data/") && c.store.Version == esv1beta1.VaultKVStoreV2 {
  255. buildPath := strings.Split(out, "/")
  256. buildMount := []string{buildPath[0], "data"}
  257. buildMount = append(buildMount, buildPath[1:]...)
  258. out = strings.Join(buildMount, "/")
  259. return out
  260. }
  261. return out
  262. }