client.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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 impliec.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package infisical
  13. import (
  14. "context"
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "strings"
  19. "github.com/tidwall/gjson"
  20. corev1 "k8s.io/api/core/v1"
  21. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  22. "github.com/external-secrets/external-secrets/pkg/find"
  23. "github.com/external-secrets/external-secrets/pkg/provider/infisical/api"
  24. )
  25. var (
  26. errNotImplemented = errors.New("not implemented")
  27. errPropertyNotFound = "property %s does not exist in secret %s"
  28. errTagsNotImplemented = errors.New("find by tags not supported")
  29. )
  30. func getPropertyValue(jsonData, propertyName, keyName string) ([]byte, error) {
  31. result := gjson.Get(jsonData, propertyName)
  32. if !result.Exists() {
  33. return nil, fmt.Errorf(errPropertyNotFound, propertyName, keyName)
  34. }
  35. return []byte(result.Str), nil
  36. }
  37. // getSecretAddress returns the path and key from the given key.
  38. //
  39. // Users can configure a root path, and when a SecretKey is provided with a slash we assume that it is
  40. // within a path appended to the root path.
  41. //
  42. // If the key is not addressing a path at all (i.e. has no `/`), simply return the original
  43. // path and key.
  44. func getSecretAddress(defaultPath, key string) (string, string, error) {
  45. if !strings.Contains(key, "/") {
  46. return defaultPath, key, nil
  47. }
  48. // Check if `key` starts with a `/`, and throw and error if it does not.
  49. if !strings.HasPrefix(key, "/") {
  50. return "", "", fmt.Errorf("a secret key referencing a folder must start with a '/' as it is an absolute path, key: %s", key)
  51. }
  52. // Otherwise, take the prefix from `key` and use that as the path. We intentionally discard
  53. // `defaultPath`.
  54. lastIndex := strings.LastIndex(key, "/")
  55. return key[:lastIndex], key[lastIndex+1:], nil
  56. }
  57. // GetSecret if this returns an error with type NoSecretError then the secret entry will be deleted depending on the
  58. // deletionPolicy.
  59. func (p *Provider) GetSecret(ctx context.Context, ref esv1.ExternalSecretDataRemoteRef) ([]byte, error) {
  60. path, key, err := getSecretAddress(p.apiScope.SecretPath, ref.Key)
  61. if err != nil {
  62. return nil, err
  63. }
  64. secret, err := p.apiClient.GetSecretByKeyV3(api.GetSecretByKeyV3Request{
  65. EnvironmentSlug: p.apiScope.EnvironmentSlug,
  66. ProjectSlug: p.apiScope.ProjectSlug,
  67. SecretKey: key,
  68. SecretPath: path,
  69. ExpandSecretReferences: p.apiScope.ExpandSecretReferences,
  70. })
  71. if err != nil {
  72. return nil, err
  73. }
  74. if ref.Property != "" {
  75. propertyValue, err := getPropertyValue(secret, ref.Property, ref.Key)
  76. if err != nil {
  77. return nil, err
  78. }
  79. return propertyValue, nil
  80. }
  81. return []byte(secret), nil
  82. }
  83. // GetSecretMap returns multiple k/v pairs from the provider.
  84. func (p *Provider) GetSecretMap(ctx context.Context, ref esv1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  85. secret, err := p.GetSecret(ctx, ref)
  86. if err != nil {
  87. return nil, err
  88. }
  89. kv := make(map[string]json.RawMessage)
  90. err = json.Unmarshal(secret, &kv)
  91. if err != nil {
  92. return nil, fmt.Errorf("unable to unmarshal secret %s: %w", ref.Key, err)
  93. }
  94. secretData := make(map[string][]byte)
  95. for k, v := range kv {
  96. var strVal string
  97. err = json.Unmarshal(v, &strVal)
  98. if err == nil {
  99. secretData[k] = []byte(strVal)
  100. } else {
  101. secretData[k] = v
  102. }
  103. }
  104. return secretData, nil
  105. }
  106. // GetAllSecrets returns multiple k/v pairs from the provider.
  107. func (p *Provider) GetAllSecrets(ctx context.Context, ref esv1.ExternalSecretFind) (map[string][]byte, error) {
  108. if ref.Tags != nil {
  109. return nil, errTagsNotImplemented
  110. }
  111. secrets, err := p.apiClient.GetSecretsV3(api.GetSecretsV3Request{
  112. EnvironmentSlug: p.apiScope.EnvironmentSlug,
  113. ProjectSlug: p.apiScope.ProjectSlug,
  114. SecretPath: p.apiScope.SecretPath,
  115. Recursive: p.apiScope.Recursive,
  116. ExpandSecretReferences: p.apiScope.ExpandSecretReferences,
  117. })
  118. if err != nil {
  119. return nil, err
  120. }
  121. secretMap := make(map[string][]byte)
  122. for key, value := range secrets {
  123. secretMap[key] = []byte(value)
  124. }
  125. if ref.Name == nil && ref.Path == nil {
  126. return secretMap, nil
  127. }
  128. var matcher *find.Matcher
  129. if ref.Name != nil {
  130. m, err := find.New(*ref.Name)
  131. if err != nil {
  132. return nil, err
  133. }
  134. matcher = m
  135. }
  136. selected := map[string][]byte{}
  137. for key, value := range secrets {
  138. if (matcher != nil && !matcher.MatchName(key)) || (ref.Path != nil && !strings.HasPrefix(key, *ref.Path)) {
  139. continue
  140. }
  141. selected[key] = []byte(value)
  142. }
  143. return selected, nil
  144. }
  145. // Validate checks if the client is configured correctly.
  146. // and is able to retrieve secrets from the provider.
  147. // If the validation result is unknown it will be ignored.
  148. func (p *Provider) Validate() (esv1.ValidationResult, error) {
  149. // try to fetch the secrets to ensure provided credentials has access to read secrets
  150. _, err := p.apiClient.GetSecretsV3(api.GetSecretsV3Request{
  151. EnvironmentSlug: p.apiScope.EnvironmentSlug,
  152. ProjectSlug: p.apiScope.ProjectSlug,
  153. Recursive: p.apiScope.Recursive,
  154. SecretPath: p.apiScope.SecretPath,
  155. ExpandSecretReferences: p.apiScope.ExpandSecretReferences,
  156. })
  157. if err != nil {
  158. return esv1.ValidationResultError, fmt.Errorf("cannot read secrets with provided project scope project:%s environment:%s secret-path:%s recursive:%t, %w", p.apiScope.ProjectSlug, p.apiScope.EnvironmentSlug, p.apiScope.SecretPath, p.apiScope.Recursive, err)
  159. }
  160. return esv1.ValidationResultReady, nil
  161. }
  162. // PushSecret will write a single secret into the provider.
  163. func (p *Provider) PushSecret(ctx context.Context, secret *corev1.Secret, data esv1.PushSecretData) error {
  164. return errNotImplemented
  165. }
  166. // DeleteSecret will delete the secret from a provider.
  167. func (p *Provider) DeleteSecret(ctx context.Context, remoteRef esv1.PushSecretRemoteRef) error {
  168. return errNotImplemented
  169. }
  170. // SecretExists checks if a secret is already present in the provider at the given location.
  171. func (p *Provider) SecretExists(ctx context.Context, remoteRef esv1.PushSecretRemoteRef) (bool, error) {
  172. return false, errNotImplemented
  173. }