client.go 14 KB

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