client.go 7.0 KB

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