passbolt.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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 passbolt implements a provider for Passbolt password manager.
  14. // It allows fetching secrets stored in Passbolt using their REST API.
  15. package passbolt
  16. import (
  17. "context"
  18. "errors"
  19. "fmt"
  20. "net/url"
  21. "regexp"
  22. "github.com/passbolt/go-passbolt/api"
  23. "github.com/passbolt/go-passbolt/helper"
  24. corev1 "k8s.io/api/core/v1"
  25. kclient "sigs.k8s.io/controller-runtime/pkg/client"
  26. "sigs.k8s.io/controller-runtime/pkg/webhook/admission"
  27. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  28. "github.com/external-secrets/external-secrets/runtime/esutils"
  29. "github.com/external-secrets/external-secrets/runtime/esutils/resolvers"
  30. )
  31. const (
  32. errPassboltStoreMissingProvider = "missing: spec.provider.passbolt"
  33. errPassboltStoreMissingAuth = "missing: spec.provider.passbolt.auth"
  34. errPassboltStoreMissingAuthPassword = "missing: spec.provider.passbolt.auth.passwordSecretRef"
  35. errPassboltStoreMissingAuthPrivateKey = "missing: spec.provider.passbolt.auth.privateKeySecretRef"
  36. errPassboltStoreMissingHost = "missing: spec.provider.passbolt.host"
  37. errPassboltExternalSecretMissingFindNameRegExp = "missing: find.name.regexp"
  38. errPassboltStoreHostSchemeNotHTTPS = "host Url has to be https scheme"
  39. errPassboltSecretPropertyInvalid = "property must be one of name, username, uri, password or description"
  40. errNotImplemented = "not implemented"
  41. )
  42. // ProviderPassbolt implements the External Secrets provider interface for Passbolt.
  43. type ProviderPassbolt struct {
  44. client *api.Client
  45. }
  46. // Capabilities return the provider supported capabilities (ReadOnly, WriteOnly, ReadWrite).
  47. func (provider *ProviderPassbolt) Capabilities() esv1.SecretStoreCapabilities {
  48. return esv1.SecretStoreReadOnly
  49. }
  50. // NewClient constructs a new secrets client based on the provided store.
  51. func (provider *ProviderPassbolt) NewClient(ctx context.Context, store esv1.GenericStore, kube kclient.Client, namespace string) (esv1.SecretsClient, error) {
  52. config := store.GetSpec().Provider.Passbolt
  53. password, err := resolvers.SecretKeyRef(
  54. ctx,
  55. kube,
  56. store.GetKind(),
  57. namespace,
  58. config.Auth.PasswordSecretRef,
  59. )
  60. if err != nil {
  61. return nil, err
  62. }
  63. privateKey, err := resolvers.SecretKeyRef(
  64. ctx,
  65. kube,
  66. store.GetKind(),
  67. namespace,
  68. config.Auth.PrivateKeySecretRef,
  69. )
  70. if err != nil {
  71. return nil, err
  72. }
  73. client, err := api.NewClient(nil, "", config.Host, privateKey, password)
  74. if err != nil {
  75. return nil, err
  76. }
  77. // Login immediately (like CLI does)
  78. if err := client.Login(ctx); err != nil {
  79. return nil, err
  80. }
  81. // Prefetch caches for V5 metadata decryption performance (CLI pattern)
  82. // This caches session keys and metadata keys for fast V5 decryption
  83. if _, _, err := client.PreFetchCaches(ctx); err != nil {
  84. fmt.Printf("passbolt: prefetch caches failed (non-fatal): %v\n", err)
  85. }
  86. provider.client = client
  87. return provider, nil
  88. }
  89. // SecretExists checks if a secret exists in Passbolt.
  90. func (provider *ProviderPassbolt) SecretExists(_ context.Context, _ esv1.PushSecretRemoteRef) (bool, error) {
  91. return false, errors.New(errNotImplemented)
  92. }
  93. // GetSecret retrieves a secret from Passbolt.
  94. func (provider *ProviderPassbolt) GetSecret(ctx context.Context, ref esv1.ExternalSecretDataRemoteRef) ([]byte, error) {
  95. if err := assureLoggedIn(ctx, provider.client); err != nil {
  96. return nil, err
  97. }
  98. secret, err := provider.getPassboltSecret(ctx, ref.Key)
  99. if err != nil {
  100. return nil, err
  101. }
  102. if ref.Property == "" {
  103. return esutils.JSONMarshal(secret)
  104. }
  105. return secret.GetProp(ref.Property)
  106. }
  107. // PushSecret is not implemented for Passbolt as it is read-only.
  108. func (provider *ProviderPassbolt) PushSecret(_ context.Context, _ *corev1.Secret, _ esv1.PushSecretData) error {
  109. return errors.New(errNotImplemented)
  110. }
  111. // DeleteSecret is not implemented for Passbolt as it is read-only.
  112. func (provider *ProviderPassbolt) DeleteSecret(_ context.Context, _ esv1.PushSecretRemoteRef) error {
  113. return errors.New(errNotImplemented)
  114. }
  115. // Validate performs validation of the Passbolt provider configuration.
  116. func (provider *ProviderPassbolt) Validate() (esv1.ValidationResult, error) {
  117. return esv1.ValidationResultUnknown, nil
  118. }
  119. // GetSecretMap retrieves a secret and returns it as a map of key/value pairs.
  120. func (provider *ProviderPassbolt) GetSecretMap(_ context.Context, _ esv1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  121. return nil, errors.New(errNotImplemented)
  122. }
  123. // GetAllSecrets retrieves all secrets from Passbolt that match the given criteria.
  124. func (provider *ProviderPassbolt) GetAllSecrets(ctx context.Context, ref esv1.ExternalSecretFind) (map[string][]byte, error) {
  125. res := make(map[string][]byte)
  126. if ref.Name == nil || ref.Name.RegExp == "" {
  127. return res, errors.New(errPassboltExternalSecretMissingFindNameRegExp)
  128. }
  129. if err := assureLoggedIn(ctx, provider.client); err != nil {
  130. return nil, err
  131. }
  132. resources, err := provider.client.GetResources(ctx, &api.GetResourcesOptions{})
  133. if err != nil {
  134. return nil, err
  135. }
  136. nameRegexp, err := regexp.Compile(ref.Name.RegExp)
  137. if err != nil {
  138. return nil, err
  139. }
  140. // NOTE: For V5 resources, metadata (including name) is encrypted, so we must
  141. // decrypt each resource before filtering. This means all secrets are decrypted
  142. // even if they don't match the filter, which may impact performance with large
  143. // secret stores.
  144. for _, resource := range resources {
  145. secret, err := provider.getPassboltSecret(ctx, resource.ID)
  146. if err != nil {
  147. return nil, err
  148. }
  149. // Filter by decrypted name (works for both V4 and V5)
  150. if !nameRegexp.MatchString(secret.Name) {
  151. continue
  152. }
  153. marshaled, err := esutils.JSONMarshal(secret)
  154. if err != nil {
  155. return nil, err
  156. }
  157. res[resource.ID] = marshaled
  158. }
  159. return res, nil
  160. }
  161. // Close implements cleanup operations for the Passbolt provider.
  162. func (provider *ProviderPassbolt) Close(ctx context.Context) error {
  163. // Save any pending session keys discovered during decryption (CLI pattern)
  164. // This improves performance for future connections
  165. _, _ = provider.client.SavePendingSessionKeys(ctx) // Best effort
  166. return provider.client.Logout(ctx)
  167. }
  168. // ValidateStore validates the Passbolt SecretStore resource configuration.
  169. func (provider *ProviderPassbolt) ValidateStore(store esv1.GenericStore) (admission.Warnings, error) {
  170. config := store.GetSpec().Provider.Passbolt
  171. if config == nil {
  172. return nil, errors.New(errPassboltStoreMissingProvider)
  173. }
  174. if config.Auth == nil {
  175. return nil, errors.New(errPassboltStoreMissingAuth)
  176. }
  177. if config.Auth.PasswordSecretRef == nil || config.Auth.PasswordSecretRef.Name == "" || config.Auth.PasswordSecretRef.Key == "" {
  178. return nil, errors.New(errPassboltStoreMissingAuthPassword)
  179. }
  180. if config.Auth.PrivateKeySecretRef == nil || config.Auth.PrivateKeySecretRef.Name == "" || config.Auth.PrivateKeySecretRef.Key == "" {
  181. return nil, errors.New(errPassboltStoreMissingAuthPrivateKey)
  182. }
  183. if config.Host == "" {
  184. return nil, errors.New(errPassboltStoreMissingHost)
  185. }
  186. host, err := url.Parse(config.Host)
  187. if err != nil {
  188. return nil, err
  189. }
  190. if host.Scheme != "https" {
  191. return nil, errors.New(errPassboltStoreHostSchemeNotHTTPS)
  192. }
  193. return nil, nil
  194. }
  195. // Secret represents a Passbolt secret with its properties.
  196. type Secret struct {
  197. Name string `json:"name"`
  198. Username string `json:"username"`
  199. Password string `json:"password"`
  200. URI string `json:"uri"`
  201. Description string `json:"description"`
  202. }
  203. // GetProp retrieves a specific property from the Passbolt secret.
  204. func (ps Secret) GetProp(key string) ([]byte, error) {
  205. switch key {
  206. case "name":
  207. return []byte(ps.Name), nil
  208. case "username":
  209. return []byte(ps.Username), nil
  210. case "uri":
  211. return []byte(ps.URI), nil
  212. case "password":
  213. return []byte(ps.Password), nil
  214. case "description":
  215. return []byte(ps.Description), nil
  216. default:
  217. return nil, errors.New(errPassboltSecretPropertyInvalid)
  218. }
  219. }
  220. func (provider *ProviderPassbolt) getPassboltSecret(ctx context.Context, id string) (*Secret, error) {
  221. _, name, username, uri, password, description, err := helper.GetResource(ctx, provider.client, id)
  222. if err != nil {
  223. return nil, err
  224. }
  225. return &Secret{
  226. Name: name,
  227. Username: username,
  228. URI: uri,
  229. Password: password,
  230. Description: description,
  231. }, nil
  232. }
  233. func assureLoggedIn(ctx context.Context, client *api.Client) error {
  234. if client.CheckSession(ctx) {
  235. return nil
  236. }
  237. return client.Login(ctx)
  238. }
  239. // NewProvider creates a new Provider instance.
  240. func NewProvider() esv1.Provider {
  241. return &ProviderPassbolt{}
  242. }
  243. // ProviderSpec returns the provider specification for registration.
  244. func ProviderSpec() *esv1.SecretStoreProvider {
  245. return &esv1.SecretStoreProvider{
  246. Passbolt: &esv1.PassboltProvider{},
  247. }
  248. }
  249. // MaintenanceStatus returns the maintenance status of the provider.
  250. func MaintenanceStatus() esv1.MaintenanceStatus {
  251. return esv1.MaintenanceStatusMaintained
  252. }