client.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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 onepasswordsdk implements a provider for 1Password secrets management service.
  14. package onepasswordsdk
  15. import (
  16. "bytes"
  17. "context"
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "strings"
  22. "github.com/1password/onepassword-sdk-go"
  23. corev1 "k8s.io/api/core/v1"
  24. "k8s.io/kube-openapi/pkg/validation/strfmt"
  25. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  26. "github.com/external-secrets/external-secrets/runtime/constants"
  27. "github.com/external-secrets/external-secrets/runtime/esutils/metadata"
  28. "github.com/external-secrets/external-secrets/runtime/metrics"
  29. )
  30. const (
  31. fieldPrefix = "field"
  32. filePrefix = "file"
  33. prefixSplitter = "/"
  34. errExpectedOneFieldMsgF = "found more than 1 fields with title '%s' in '%s', got %d"
  35. itemCachePrefix = "item:"
  36. fileCachePrefix = "file:"
  37. )
  38. // ErrKeyNotFound is returned when a key is not found in the 1Password Vaults.
  39. var ErrKeyNotFound = errors.New("key not found")
  40. // PushSecretMetadataSpec defines the metadata configuration for pushing secrets to 1Password.
  41. type PushSecretMetadataSpec struct {
  42. Tags []string `json:"tags,omitempty"`
  43. }
  44. // GetSecret returns a single secret from 1Password provider.
  45. // Follows syntax is used for the ref key: https://developer.1password.com/docs/cli/secret-reference-syntax/
  46. func (p *SecretsClient) GetSecret(ctx context.Context, ref esv1.ExternalSecretDataRemoteRef) ([]byte, error) {
  47. if ref.Version != "" {
  48. return nil, errors.New(errVersionNotImplemented)
  49. }
  50. key := p.constructRefKey(ref.Key)
  51. if cached, ok := p.cacheGet(key); ok {
  52. return cached, nil
  53. }
  54. secret, err := p.client.Secrets().Resolve(ctx, key)
  55. metrics.ObserveAPICall(constants.ProviderOnePasswordSDK, constants.CallOnePasswordSDKResolve, err)
  56. if err != nil {
  57. return nil, err
  58. }
  59. result := []byte(secret)
  60. p.cacheAdd(key, result)
  61. return result, nil
  62. }
  63. // Close closes the client connection.
  64. func (p *SecretsClient) Close(_ context.Context) error {
  65. return nil
  66. }
  67. // DeleteSecret implements Secret Deletion on the provider when PushSecret.spec.DeletionPolicy=Delete.
  68. func (p *SecretsClient) DeleteSecret(ctx context.Context, ref esv1.PushSecretRemoteRef) error {
  69. providerItem, err := p.findItem(ctx, ref.GetRemoteKey())
  70. if errors.Is(err, ErrKeyNotFound) {
  71. return nil
  72. }
  73. if err != nil {
  74. return err
  75. }
  76. var deleted bool
  77. providerItem.Fields, deleted, err = deleteField(providerItem.Fields, ref.GetProperty())
  78. if err != nil {
  79. return fmt.Errorf("failed to delete fields: %w", err)
  80. }
  81. if !deleted {
  82. // also invalidate the cache here, as this field might have been deleted
  83. // outside ESO.
  84. p.invalidateCacheByPrefix(p.constructRefKey(ref.GetRemoteKey()))
  85. p.invalidateItemCache(ref.GetRemoteKey())
  86. return nil
  87. }
  88. // There is a chance that there is an empty item left in the section like this: [{ID: Title:}].
  89. if len(providerItem.Sections) == 1 && providerItem.Sections[0].ID == "" && providerItem.Sections[0].Title == "" {
  90. providerItem.Sections = nil
  91. }
  92. if len(providerItem.Fields) == 0 && len(providerItem.Files) == 0 && len(providerItem.Sections) == 0 {
  93. err = p.client.Items().Delete(ctx, providerItem.VaultID, providerItem.ID)
  94. metrics.ObserveAPICall(constants.ProviderOnePasswordSDK, constants.CallOnePasswordSDKItemsDelete, err)
  95. if err != nil {
  96. return fmt.Errorf("failed to delete item: %w", err)
  97. }
  98. p.invalidateCacheByPrefix(p.constructRefKey(ref.GetRemoteKey()))
  99. p.invalidateItemCache(ref.GetRemoteKey())
  100. return nil
  101. }
  102. _, err = p.client.Items().Put(ctx, providerItem)
  103. metrics.ObserveAPICall(constants.ProviderOnePasswordSDK, constants.CallOnePasswordSDKItemsPut, err)
  104. if err != nil {
  105. return fmt.Errorf("failed to update item: %w", err)
  106. }
  107. p.invalidateCacheByPrefix(p.constructRefKey(ref.GetRemoteKey()))
  108. p.invalidateItemCache(ref.GetRemoteKey())
  109. return nil
  110. }
  111. func deleteField(fields []onepassword.ItemField, title string) ([]onepassword.ItemField, bool, error) {
  112. // This will always iterate over all items,
  113. // but it's done to ensure that two fields with the same label
  114. // exist resulting in undefined behavior
  115. var (
  116. found bool
  117. fieldsF = make([]onepassword.ItemField, 0, len(fields))
  118. )
  119. for _, item := range fields {
  120. if item.Title == title {
  121. if found {
  122. return nil, false, fmt.Errorf("found multiple labels on item %q", title)
  123. }
  124. found = true
  125. continue
  126. }
  127. fieldsF = append(fieldsF, item)
  128. }
  129. return fieldsF, found, nil
  130. }
  131. // GetAllSecrets Not Implemented.
  132. func (p *SecretsClient) GetAllSecrets(_ context.Context, _ esv1.ExternalSecretFind) (map[string][]byte, error) {
  133. return nil, fmt.Errorf(errOnePasswordSdkStore, errors.New(errNotImplemented))
  134. }
  135. // GetSecretMap returns multiple k/v pairs from the provider, for dataFrom.extract.
  136. func (p *SecretsClient) GetSecretMap(ctx context.Context, ref esv1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  137. if ref.Version != "" {
  138. return nil, errors.New(errVersionNotImplemented)
  139. }
  140. cacheKey := p.constructRefKey(ref.Key) + "|" + ref.Property
  141. if cached, ok := p.cacheGet(cacheKey); ok {
  142. var result map[string][]byte
  143. if err := json.Unmarshal(cached, &result); err == nil {
  144. return result, nil
  145. }
  146. // continue with fresh instead
  147. }
  148. item, err := p.findItem(ctx, ref.Key)
  149. if err != nil {
  150. return nil, err
  151. }
  152. var result map[string][]byte
  153. propertyType, property := getObjType(item.Category, ref.Property)
  154. if propertyType == filePrefix {
  155. result, err = p.getFiles(ctx, item, property)
  156. } else {
  157. result, err = p.getFields(item, property)
  158. }
  159. if err != nil {
  160. return nil, err
  161. }
  162. if serialized, err := json.Marshal(result); err == nil {
  163. p.cacheAdd(cacheKey, serialized)
  164. }
  165. return result, nil
  166. }
  167. func (p *SecretsClient) getFields(item onepassword.Item, property string) (map[string][]byte, error) {
  168. secretData := make(map[string][]byte)
  169. for _, field := range item.Fields {
  170. if property != "" && field.Title != property {
  171. continue
  172. }
  173. if length := countFieldsWithLabel(field.Title, item.Fields); length != 1 {
  174. return nil, fmt.Errorf(errExpectedOneFieldMsgF, field.Title, item.Title, length)
  175. }
  176. // caution: do not use client.GetValue here because it has undesirable behavior on keys with a dot in them
  177. secretData[field.Title] = []byte(field.Value)
  178. }
  179. return secretData, nil
  180. }
  181. func (p *SecretsClient) getFiles(ctx context.Context, item onepassword.Item, property string) (map[string][]byte, error) {
  182. secretData := make(map[string][]byte)
  183. for _, file := range item.Files {
  184. if property != "" && file.Attributes.Name != property {
  185. continue
  186. }
  187. cacheKey := fileCachePrefix + p.vaultID + ":" + item.ID + ":" + file.FieldID + ":" + file.Attributes.Name
  188. if cached, ok := p.cacheGet(cacheKey); ok {
  189. secretData[file.Attributes.Name] = cached
  190. continue
  191. }
  192. contents, err := p.client.Items().Files().Read(ctx, p.vaultID, file.FieldID, file.Attributes)
  193. metrics.ObserveAPICall(constants.ProviderOnePasswordSDK, constants.CallOnePasswordSDKFilesRead, err)
  194. if err != nil {
  195. return nil, fmt.Errorf("failed to read file: %w", err)
  196. }
  197. p.cacheAdd(cacheKey, contents)
  198. secretData[file.Attributes.Name] = contents
  199. }
  200. return secretData, nil
  201. }
  202. func countFieldsWithLabel(fieldLabel string, fields []onepassword.ItemField) int {
  203. count := 0
  204. for _, field := range fields {
  205. if field.Title == fieldLabel {
  206. count++
  207. }
  208. }
  209. return count
  210. }
  211. // Clean property string by removing property prefix if needed.
  212. func getObjType(documentType onepassword.ItemCategory, property string) (string, string) {
  213. if strings.HasPrefix(property, fieldPrefix+prefixSplitter) {
  214. return fieldPrefix, property[6:]
  215. }
  216. if strings.HasPrefix(property, filePrefix+prefixSplitter) {
  217. return filePrefix, property[5:]
  218. }
  219. if documentType == onepassword.ItemCategoryDocument {
  220. return filePrefix, property
  221. }
  222. return fieldPrefix, property
  223. }
  224. // createItem creates a new item in the first vault. If no vaults exist, it returns an error.
  225. func (p *SecretsClient) createItem(ctx context.Context, val []byte, ref esv1.PushSecretData) error {
  226. mdata, err := metadata.ParseMetadataParameters[PushSecretMetadataSpec](ref.GetMetadata())
  227. if err != nil {
  228. return fmt.Errorf("failed to parse push secret metadata: %w", err)
  229. }
  230. label := ref.GetProperty()
  231. if label == "" {
  232. label = "password"
  233. }
  234. var tags []string
  235. if mdata != nil && mdata.Spec.Tags != nil {
  236. tags = mdata.Spec.Tags
  237. }
  238. _, err = p.client.Items().Create(ctx, onepassword.ItemCreateParams{
  239. Category: onepassword.ItemCategoryServer,
  240. VaultID: p.vaultID,
  241. Title: ref.GetRemoteKey(),
  242. Fields: []onepassword.ItemField{
  243. generateNewItemField(label, string(val)),
  244. },
  245. Tags: tags,
  246. })
  247. metrics.ObserveAPICall(constants.ProviderOnePasswordSDK, constants.CallOnePasswordSDKItemsCreate, err)
  248. if err != nil {
  249. return fmt.Errorf("failed to create item: %w", err)
  250. }
  251. p.invalidateCacheByPrefix(p.constructRefKey(ref.GetRemoteKey()))
  252. p.invalidateItemCache(ref.GetRemoteKey())
  253. return nil
  254. }
  255. // updateFieldValue updates the fields value of an item with the given label.
  256. // If the label does not exist, a new field is created. If the label exists but
  257. // the value is different, the value is updated. If the label exists and the
  258. // value is the same, nothing is done.
  259. func updateFieldValue(fields []onepassword.ItemField, title, newVal string) ([]onepassword.ItemField, error) {
  260. // This will always iterate over all items.
  261. // This is done to ensure that two fields with the same label
  262. // exist resulting in undefined behavior.
  263. var (
  264. found bool
  265. index int
  266. )
  267. for i, item := range fields {
  268. if item.Title == title {
  269. if found {
  270. return nil, fmt.Errorf("found multiple labels with the same key")
  271. }
  272. found = true
  273. index = i
  274. }
  275. }
  276. if !found {
  277. return append(fields, generateNewItemField(title, newVal)), nil
  278. }
  279. if fields[index].Value != newVal {
  280. fields[index].Value = newVal
  281. }
  282. return fields, nil
  283. }
  284. // generateNewItemField generates a new item field with the given label and value.
  285. func generateNewItemField(title, newVal string) onepassword.ItemField {
  286. field := onepassword.ItemField{
  287. Title: title,
  288. Value: newVal,
  289. FieldType: onepassword.ItemFieldTypeConcealed,
  290. }
  291. return field
  292. }
  293. // PushSecret creates or updates a secret in 1Password.
  294. func (p *SecretsClient) PushSecret(ctx context.Context, secret *corev1.Secret, ref esv1.PushSecretData) error {
  295. val, ok := secret.Data[ref.GetSecretKey()]
  296. if !ok {
  297. return fmt.Errorf("secret %s/%s does not contain a key", secret.Namespace, secret.Name)
  298. }
  299. title := ref.GetRemoteKey()
  300. providerItem, err := p.findItem(ctx, title)
  301. if errors.Is(err, ErrKeyNotFound) {
  302. if err = p.createItem(ctx, val, ref); err != nil {
  303. return fmt.Errorf("failed to create item: %w", err)
  304. }
  305. return nil
  306. } else if err != nil {
  307. return fmt.Errorf("failed to find item: %w", err)
  308. }
  309. // TODO: We are only sending info to a specific label on a 1password item.
  310. // We should change this logic eventually to allow pushing whole kubernetes Secrets to 1password as multiple labels
  311. // OOTB.
  312. label := ref.GetProperty()
  313. if label == "" {
  314. label = "password"
  315. }
  316. mdata, err := metadata.ParseMetadataParameters[PushSecretMetadataSpec](ref.GetMetadata())
  317. if err != nil {
  318. return fmt.Errorf("failed to parse push secret metadata: %w", err)
  319. }
  320. if mdata != nil && mdata.Spec.Tags != nil {
  321. providerItem.Tags = mdata.Spec.Tags
  322. }
  323. providerItem.Fields, err = updateFieldValue(providerItem.Fields, label, string(val))
  324. if err != nil {
  325. return fmt.Errorf("failed to update field with label: %s: %w", label, err)
  326. }
  327. _, err = p.client.Items().Put(ctx, providerItem)
  328. metrics.ObserveAPICall(constants.ProviderOnePasswordSDK, constants.CallOnePasswordSDKItemsPut, err)
  329. if err != nil {
  330. return fmt.Errorf("failed to update item: %w", err)
  331. }
  332. p.invalidateCacheByPrefix(p.constructRefKey(title))
  333. p.invalidateItemCache(title)
  334. return nil
  335. }
  336. // GetVault retrieves a vault by its title or UUID from 1Password.
  337. func (p *SecretsClient) GetVault(ctx context.Context, titleOrUUID string) (string, error) {
  338. vaults, err := p.client.VaultsAPI.List(ctx)
  339. metrics.ObserveAPICall(constants.ProviderOnePasswordSDK, constants.CallOnePasswordSDKVaultsList, err)
  340. if err != nil {
  341. return "", fmt.Errorf("failed to list vaults: %w", err)
  342. }
  343. for _, v := range vaults {
  344. if v.Title == titleOrUUID || v.ID == titleOrUUID {
  345. return v.ID, nil
  346. }
  347. }
  348. return "", fmt.Errorf("vault %s not found", titleOrUUID)
  349. }
  350. func (p *SecretsClient) findItem(ctx context.Context, name string) (onepassword.Item, error) {
  351. cacheKey := itemCachePrefix + p.vaultID + ":" + name
  352. if cached, ok := p.cacheGet(cacheKey); ok {
  353. var item onepassword.Item
  354. if err := json.Unmarshal(cached, &item); err == nil {
  355. return item, nil
  356. }
  357. }
  358. var item onepassword.Item
  359. var err error
  360. if strfmt.IsUUID(name) {
  361. item, err = p.client.Items().Get(ctx, p.vaultID, name)
  362. metrics.ObserveAPICall(constants.ProviderOnePasswordSDK, constants.CallOnePasswordSDKItemsGet, err)
  363. if err != nil {
  364. if isNotFoundError(err) {
  365. return onepassword.Item{}, ErrKeyNotFound
  366. }
  367. return onepassword.Item{}, err
  368. }
  369. } else {
  370. items, err := p.client.Items().List(ctx, p.vaultID)
  371. metrics.ObserveAPICall(constants.ProviderOnePasswordSDK, constants.CallOnePasswordSDKItemsList, err)
  372. if err != nil {
  373. return onepassword.Item{}, fmt.Errorf("failed to list items: %w", err)
  374. }
  375. var itemUUID string
  376. for _, v := range items {
  377. if v.Title == name {
  378. if itemUUID != "" {
  379. return onepassword.Item{}, fmt.Errorf("found multiple items with name %s", name)
  380. }
  381. itemUUID = v.ID
  382. }
  383. }
  384. if itemUUID == "" {
  385. return onepassword.Item{}, ErrKeyNotFound
  386. }
  387. item, err = p.client.Items().Get(ctx, p.vaultID, itemUUID)
  388. metrics.ObserveAPICall(constants.ProviderOnePasswordSDK, constants.CallOnePasswordSDKItemsGet, err)
  389. if err != nil {
  390. return onepassword.Item{}, err
  391. }
  392. }
  393. if serialized, err := json.Marshal(item); err == nil {
  394. p.cacheAdd(cacheKey, serialized)
  395. }
  396. return item, nil
  397. }
  398. // SecretExists checks if a secret exists in 1Password.
  399. func (p *SecretsClient) SecretExists(_ context.Context, _ esv1.PushSecretRemoteRef) (bool, error) {
  400. return false, fmt.Errorf("not implemented")
  401. }
  402. // Validate does nothing here. It would be possible to ping the SDK to prove we're healthy, but
  403. // since the 1password SDK rate-limit is pretty aggressive, we prefer to do nothing.
  404. func (p *SecretsClient) Validate() (esv1.ValidationResult, error) {
  405. return esv1.ValidationResultReady, nil
  406. }
  407. func (p *SecretsClient) constructRefKey(key string) string {
  408. // remove any possible leading slashes because the vaultPrefix already contains it.
  409. return p.vaultPrefix + strings.TrimPrefix(key, "/")
  410. }
  411. // cacheGet retrieves a value from the cache. Returns false if cache is disabled or key not found.
  412. func (p *SecretsClient) cacheGet(key string) ([]byte, bool) {
  413. if p.cache == nil {
  414. return nil, false
  415. }
  416. v, ok := p.cache.Get(key)
  417. if !ok {
  418. return nil, false
  419. }
  420. return bytes.Clone(v), true
  421. }
  422. // cacheAdd stores a value in the cache. No-op if cache is disabled.
  423. func (p *SecretsClient) cacheAdd(key string, value []byte) {
  424. if p.cache == nil {
  425. return
  426. }
  427. p.cache.Add(key, value)
  428. }
  429. // invalidateCacheByPrefix removes all cache entries that start with the given prefix.
  430. // This is used to invalidate cache entries when an item is modified or deleted.
  431. // No-op if cache is disabled.
  432. // Why are we using a Prefix? Because items and properties are stored via prefixes using 1Password SDK.
  433. // This means when an item is deleted we delete the fields and properties that belong to the item as well.
  434. func (p *SecretsClient) invalidateCacheByPrefix(prefix string) {
  435. if p.cache == nil {
  436. return
  437. }
  438. keys := p.cache.Keys()
  439. for _, key := range keys {
  440. if strings.HasPrefix(key, prefix) {
  441. if len(key) == len(prefix) || key[len(prefix)] == '/' || key[len(prefix)] == '|' {
  442. p.cache.Remove(key)
  443. }
  444. }
  445. }
  446. }
  447. // invalidateItemCache removes cached item entries for the given item name.
  448. // No-op if cache is disabled.
  449. func (p *SecretsClient) invalidateItemCache(name string) {
  450. if p.cache == nil {
  451. return
  452. }
  453. cacheKey := itemCachePrefix + p.vaultID + ":" + name
  454. p.cache.Remove(cacheKey)
  455. }
  456. func isNotFoundError(err error) bool {
  457. msg := strings.ToLower(err.Error())
  458. return strings.Contains(msg, "couldn't be found") || strings.Contains(msg, "resource not found")
  459. }