client.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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 keepersecurity
  14. import (
  15. "context"
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "maps"
  20. "regexp"
  21. "strings"
  22. ksm "github.com/keeper-security/secrets-manager-go/core"
  23. corev1 "k8s.io/api/core/v1"
  24. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  25. )
  26. const (
  27. errKeeperSecuritySecretsNotFound = "unable to find secrets. %w"
  28. errKeeperSecuritySecretNotFound = "unable to find secret %s. Error: %w"
  29. errKeeperSecuritySecretNotUnique = "more than 1 secret %s found"
  30. errKeeperSecurityNoSecretsFound = "no secrets found"
  31. errKeeperSecurityInvalidSecretInvalidFormat = "invalid secret. Invalid format: %w"
  32. errKeeperSecurityInvalidSecretDuplicatedKey = "invalid Secret. Following keys are duplicated %s"
  33. errKeeperSecurityInvalidProperty = "invalid Property. Secret %s does not have any key matching %s"
  34. errKeeperSecurityInvalidField = "invalid Field. Key %s does not exists"
  35. errKeeperSecurityNoFields = "invalid Secret. Secret %s does not contain any valid field/file"
  36. keeperSecurityFileRef = "fileRef"
  37. keeperSecurityMfa = "oneTimeCode"
  38. errTagsNotImplemented = "'find.tags' is not implemented in the KeeperSecurity provider"
  39. errPathNotImplemented = "'find.path' is not implemented in the KeeperSecurity provider"
  40. errInvalidJSONSecret = "invalid Secret. Secret %s can not be converted to JSON. %w"
  41. errInvalidRegex = "find.name.regex. Invalid Regular expresion %s. %w"
  42. errInvalidRemoteRefKey = "match.remoteRef.remoteKey. Invalid format. Format should match secretName/key got %s"
  43. errInvalidSecretType = "ESO can only push/delete records of type %s. Secret %s is type %s"
  44. errFieldNotFound = "secret %s does not contain any custom field with label %s"
  45. externalSecretType = "externalSecrets"
  46. secretType = "secret"
  47. // LoginType represents the login field type.
  48. LoginType = "login"
  49. // LoginTypeExpr is the regex expression for matching login/username fields.
  50. LoginTypeExpr = "login|username"
  51. // PasswordType represents the password field type.
  52. PasswordType = "password"
  53. // URLTypeExpr is the regex expression for matching URL/baseurl fields.
  54. URLTypeExpr = "url|baseurl"
  55. // URLType represents the URL field type.
  56. URLType = "url"
  57. )
  58. // Client represents a KeeperSecurity client that can interact with the KeeperSecurity API.
  59. type Client struct {
  60. ksmClient SecurityClient
  61. folderID string
  62. getByTitleFallback bool
  63. }
  64. // SecurityClient defines the interface for interacting with KeeperSecurity's API.
  65. type SecurityClient interface {
  66. GetSecrets(filter []string) ([]*ksm.Record, error)
  67. GetSecretByTitle(recordTitle string) (*ksm.Record, error)
  68. GetSecretsByTitle(recordTitle string) (records []*ksm.Record, err error)
  69. CreateSecretWithRecordData(recUID, folderUID string, recordData *ksm.RecordCreate) (string, error)
  70. DeleteSecrets(recrecordUids []string) (map[string]string, error)
  71. Save(record *ksm.Record) error
  72. }
  73. // Field represents a KeeperSecurity field with its type, label (optional), and value.
  74. type Field struct {
  75. Type string `json:"type"`
  76. Label string `json:"label,omitempty"`
  77. Value []any `json:"value"`
  78. }
  79. // CustomField represents a custom field in KeeperSecurity with its type, label and value.
  80. type CustomField struct {
  81. Type string `json:"type"`
  82. Label string `json:"label"`
  83. Value []any `json:"value"`
  84. }
  85. // File represents a file stored in KeeperSecurity with its title and content.
  86. type File struct {
  87. Title string `json:"type"`
  88. Content string `json:"content"`
  89. }
  90. // Secret represents a KeeperSecurity secret with its metadata and content.
  91. type Secret struct {
  92. Title string `json:"title"`
  93. Type string `json:"type"`
  94. Fields []Field `json:"fields"`
  95. Custom []CustomField `json:"custom"`
  96. Files []File `json:"files"`
  97. }
  98. // Validate performs validation of the Keeper Security client configuration.
  99. func (c *Client) Validate() (esv1.ValidationResult, error) {
  100. return esv1.ValidationResultReady, nil
  101. }
  102. // GetSecret retrieves a secret from Keeper Security by ID or name.
  103. // It first attempts to find the secret by ID, then falls back to name lookup.
  104. // The name lookup must be opted in by setting getByTitleFallback on the provider.
  105. func (c *Client) GetSecret(_ context.Context, ref esv1.ExternalSecretDataRemoteRef) ([]byte, error) {
  106. secret, err := c.findByIDWithNameFallback(ref.Key)
  107. if err != nil {
  108. return nil, err
  109. }
  110. return secret.getItem(ref)
  111. }
  112. // GetSecretMap retrieves a secret from Keeper Security and returns it as a map.
  113. func (c *Client) GetSecretMap(_ context.Context, ref esv1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  114. secret, err := c.findByIDWithNameFallback(ref.Key)
  115. if err != nil {
  116. return nil, err
  117. }
  118. return secret.getItems(ref)
  119. }
  120. // It first attempts to find the secret by ID, then falls back to name lookup.
  121. // The name lookup must be opted in by setting getByTitleFallback on the provider.
  122. func (c *Client) findByIDWithNameFallback(key string) (*Secret, error) {
  123. record, err := c.findSecretByID(key)
  124. if err != nil {
  125. return nil, err
  126. }
  127. if record == nil && c.getByTitleFallback {
  128. records, err := c.ksmClient.GetSecretsByTitle(key)
  129. if err != nil {
  130. return nil, err
  131. }
  132. if len(records) > 1 {
  133. return nil, errors.New(errKeeperSecuritySecretNotUnique)
  134. } else if len(records) == 1 {
  135. record = records[0]
  136. }
  137. }
  138. if record == nil {
  139. return nil, errors.New(errKeeperSecurityNoSecretsFound)
  140. }
  141. secret, err := c.getValidKeeperSecret(record)
  142. if err != nil {
  143. return nil, err
  144. }
  145. return secret, nil
  146. }
  147. // GetAllSecrets retrieves all secrets from Keeper Security that match the given criteria.
  148. func (c *Client) GetAllSecrets(_ context.Context, ref esv1.ExternalSecretFind) (map[string][]byte, error) {
  149. if ref.Tags != nil {
  150. return nil, errors.New(errTagsNotImplemented)
  151. }
  152. if ref.Path != nil {
  153. return nil, errors.New(errPathNotImplemented)
  154. }
  155. secretData := make(map[string][]byte)
  156. records, err := c.findSecrets()
  157. // GetAllSecrets retrieves all secrets from Keeper Security that match the given criteria.
  158. // Currently supports filtering by name pattern only.
  159. if err != nil {
  160. return nil, err
  161. }
  162. for _, record := range records {
  163. secret, err := c.getValidKeeperSecret(record)
  164. if err != nil {
  165. return nil, err
  166. }
  167. match, err := regexp.MatchString(ref.Name.RegExp, secret.Title)
  168. if err != nil {
  169. return nil, fmt.Errorf(errInvalidRegex, ref.Name.RegExp, err)
  170. }
  171. if !match {
  172. continue
  173. }
  174. secretData[secret.Title], err = secret.getItem(esv1.ExternalSecretDataRemoteRef{})
  175. if err != nil {
  176. return nil, err
  177. }
  178. }
  179. return secretData, nil
  180. }
  181. // Close implements cleanup operations for the Keeper Security client.
  182. func (c *Client) Close(_ context.Context) error {
  183. return nil
  184. }
  185. // PushSecret creates or updates a secret in Keeper Security.
  186. func (c *Client) PushSecret(_ context.Context, secret *corev1.Secret, data esv1.PushSecretData) error {
  187. if data.GetSecretKey() == "" {
  188. return errors.New("pushing the whole secret is not yet implemented")
  189. }
  190. // Close implements cleanup operations for the Keeper Security client
  191. value := secret.Data[data.GetSecretKey()]
  192. parts, err := c.buildSecretNameAndKey(data)
  193. if err != nil {
  194. return err
  195. // PushSecret creates or updates a secret in Keeper Security.
  196. // Currently only supports pushing individual secret values, not entire secrets.
  197. }
  198. record, err := c.findSecretByName(parts[0])
  199. if err != nil {
  200. return err
  201. }
  202. if record != nil {
  203. if record.Type() != externalSecretType {
  204. return fmt.Errorf(errInvalidSecretType, externalSecretType, record.Title(), record.Type())
  205. }
  206. return c.updateSecret(record, parts[1], value)
  207. }
  208. _, err = c.createSecret(parts[0], parts[1], value)
  209. return err
  210. }
  211. // DeleteSecret removes a secret from Keeper Security.
  212. func (c *Client) DeleteSecret(_ context.Context, remoteRef esv1.PushSecretRemoteRef) error {
  213. parts, err := c.buildSecretNameAndKey(remoteRef)
  214. if err != nil {
  215. return err
  216. }
  217. secret, err := c.findSecretByName(parts[0])
  218. if err != nil {
  219. return err
  220. } else if secret == nil {
  221. // DeleteSecret removes a secret from Keeper Security.
  222. // Returns nil if the secret doesn't exist (already deleted).
  223. return nil // not found == already deleted (success)
  224. }
  225. if secret.Type() != externalSecretType {
  226. return fmt.Errorf(errInvalidSecretType, externalSecretType, secret.Title(), secret.Type())
  227. }
  228. _, err = c.ksmClient.DeleteSecrets([]string{secret.Uid})
  229. return err
  230. }
  231. // SecretExists checks if a secret exists in Keeper Security.
  232. func (c *Client) SecretExists(_ context.Context, _ esv1.PushSecretRemoteRef) (bool, error) {
  233. return false, errors.New("not implemented")
  234. }
  235. func (c *Client) buildSecretNameAndKey(remoteRef esv1.PushSecretRemoteRef) ([]string, error) {
  236. parts := strings.Split(remoteRef.GetRemoteKey(), "/")
  237. if len(parts) != 2 {
  238. return nil, fmt.Errorf(errInvalidRemoteRefKey, remoteRef.GetRemoteKey())
  239. }
  240. // SecretExists checks if a secret exists in Keeper Security.
  241. // This method is not implemented yet.
  242. return parts, nil
  243. }
  244. func (c *Client) createSecret(name, key string, value []byte) (string, error) {
  245. normalizedKey := strings.ToLower(key)
  246. externalSecretRecord := ksm.NewRecordCreate(externalSecretType, name)
  247. login := regexp.MustCompile(LoginTypeExpr)
  248. pass := regexp.MustCompile(PasswordType)
  249. url := regexp.MustCompile(URLTypeExpr)
  250. switch {
  251. case login.MatchString(normalizedKey):
  252. externalSecretRecord.Fields = append(externalSecretRecord.Fields,
  253. ksm.NewLogin(string(value)),
  254. )
  255. case pass.MatchString(normalizedKey):
  256. externalSecretRecord.Fields = append(externalSecretRecord.Fields,
  257. ksm.NewPassword(string(value)),
  258. )
  259. case url.MatchString(normalizedKey):
  260. externalSecretRecord.Fields = append(externalSecretRecord.Fields,
  261. ksm.NewUrl(string(value)),
  262. )
  263. default:
  264. field := ksm.KeeperRecordField{Type: secretType, Label: key}
  265. externalSecretRecord.Custom = append(externalSecretRecord.Custom,
  266. ksm.Secret{KeeperRecordField: field, Value: []string{string(value)}},
  267. )
  268. }
  269. return c.ksmClient.CreateSecretWithRecordData("", c.folderID, externalSecretRecord)
  270. }
  271. func (c *Client) updateSecret(secret *ksm.Record, key string, value []byte) error {
  272. normalizedKey := strings.ToLower(key)
  273. login := regexp.MustCompile(LoginTypeExpr)
  274. pass := regexp.MustCompile(PasswordType)
  275. url := regexp.MustCompile(URLTypeExpr)
  276. custom := false
  277. switch {
  278. case login.MatchString(normalizedKey):
  279. secret.SetFieldValueSingle(LoginType, string(value))
  280. case pass.MatchString(normalizedKey):
  281. secret.SetPassword(string(value))
  282. case url.MatchString(normalizedKey):
  283. secret.SetFieldValueSingle(URLType, string(value))
  284. default:
  285. custom = true
  286. }
  287. if custom {
  288. field := secret.GetCustomFieldValueByLabel(key)
  289. if field != "" {
  290. secret.SetCustomFieldValueSingle(key, string(value))
  291. } else {
  292. return fmt.Errorf(errFieldNotFound, secret.Title(), key)
  293. }
  294. }
  295. return c.ksmClient.Save(secret)
  296. }
  297. func (c *Client) getValidKeeperSecret(secret *ksm.Record) (*Secret, error) {
  298. keeperSecret := Secret{}
  299. err := json.Unmarshal([]byte(secret.RawJson), &keeperSecret)
  300. if err != nil {
  301. return nil, fmt.Errorf(errKeeperSecurityInvalidSecretInvalidFormat, err)
  302. }
  303. keeperSecret.addFiles(secret.Files)
  304. err = keeperSecret.validate()
  305. if err != nil {
  306. return nil, err
  307. }
  308. return &keeperSecret, nil
  309. }
  310. func (c *Client) findSecrets() ([]*ksm.Record, error) {
  311. records, err := c.ksmClient.GetSecrets([]string{})
  312. if err != nil {
  313. return nil, fmt.Errorf(errKeeperSecuritySecretsNotFound, err)
  314. }
  315. return records, nil
  316. }
  317. func (c *Client) findSecretByID(id string) (*ksm.Record, error) {
  318. records, err := c.ksmClient.GetSecrets([]string{id})
  319. if err != nil {
  320. return nil, fmt.Errorf(errKeeperSecuritySecretNotFound, id, err)
  321. }
  322. if len(records) == 0 {
  323. return nil, nil
  324. }
  325. return records[0], nil
  326. }
  327. func (c *Client) findSecretByName(name string) (*ksm.Record, error) {
  328. records, err := c.ksmClient.GetSecretsByTitle(name)
  329. if err != nil {
  330. return nil, err
  331. }
  332. // filter in-place, preserve only records of type externalSecretType
  333. n := 0
  334. for _, record := range records {
  335. if record.Type() == externalSecretType {
  336. records[n] = record
  337. n++
  338. }
  339. }
  340. records = records[:n]
  341. // record not found is not an error - handled differently:
  342. // PushSecret will create new record instead
  343. // DeleteSecret will consider record already deleted (no error)
  344. if len(records) == 0 {
  345. return nil, nil
  346. } else if len(records) == 1 {
  347. return records[0], nil
  348. }
  349. // len(records) > 1
  350. return nil, fmt.Errorf(errKeeperSecuritySecretNotUnique, name)
  351. }
  352. func (s *Secret) validate() error {
  353. fields := make(map[string]int)
  354. for _, field := range s.Fields {
  355. fieldKey := field.Label
  356. if fieldKey == "" {
  357. fieldKey = field.Type
  358. }
  359. fields[fieldKey]++
  360. }
  361. for _, customField := range s.Custom {
  362. fields[customField.Label]++
  363. }
  364. for _, file := range s.Files {
  365. fields[file.Title]++
  366. }
  367. var duplicates []string
  368. for key, ocurrences := range fields {
  369. if ocurrences > 1 {
  370. duplicates = append(duplicates, key)
  371. }
  372. }
  373. if len(duplicates) != 0 {
  374. return fmt.Errorf(errKeeperSecurityInvalidSecretDuplicatedKey, strings.Join(duplicates, ", "))
  375. }
  376. return nil
  377. }
  378. func (s *Secret) addFiles(keeperFiles []*ksm.KeeperFile) {
  379. for _, f := range keeperFiles {
  380. s.Files = append(
  381. s.Files,
  382. File{
  383. Title: f.Title,
  384. Content: string(f.GetFileData()),
  385. },
  386. )
  387. }
  388. }
  389. func (s *Secret) getItem(ref esv1.ExternalSecretDataRemoteRef) ([]byte, error) {
  390. if ref.Property != "" {
  391. return s.getProperty(ref.Property)
  392. }
  393. secret, err := s.toString()
  394. return []byte(secret), err
  395. }
  396. func (s *Secret) getItems(ref esv1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  397. secretData := make(map[string][]byte)
  398. if ref.Property != "" {
  399. value, err := s.getProperty(ref.Property)
  400. if err != nil {
  401. return nil, err
  402. }
  403. secretData[ref.Property] = value
  404. return secretData, nil
  405. }
  406. fields := s.getFields()
  407. maps.Copy(secretData, fields)
  408. customFields := s.getCustomFields()
  409. maps.Copy(secretData, customFields)
  410. files := s.getFiles()
  411. maps.Copy(secretData, files)
  412. if len(secretData) == 0 {
  413. return nil, fmt.Errorf(errKeeperSecurityNoFields, s.Title)
  414. }
  415. return secretData, nil
  416. }
  417. func getFieldValue(value []any) []byte {
  418. if len(value) < 1 {
  419. return []byte{}
  420. }
  421. if len(value) == 1 {
  422. res, _ := json.Marshal(value[0])
  423. if str, ok := value[0].(string); ok {
  424. res = []byte(str)
  425. }
  426. return res
  427. }
  428. res, _ := json.Marshal(value)
  429. return res
  430. }
  431. func (s *Secret) getField(key string) ([]byte, error) {
  432. for _, field := range s.Fields {
  433. fieldKey := field.Label
  434. if fieldKey == "" {
  435. fieldKey = field.Type
  436. }
  437. if fieldKey == key && field.Type != keeperSecurityFileRef && field.Type != keeperSecurityMfa && len(field.Value) > 0 {
  438. return getFieldValue(field.Value), nil
  439. }
  440. }
  441. return nil, fmt.Errorf(errKeeperSecurityInvalidField, key)
  442. }
  443. func (s *Secret) getFields() map[string][]byte {
  444. secretData := make(map[string][]byte)
  445. for _, field := range s.Fields {
  446. if len(field.Value) > 0 {
  447. fieldKey := field.Label
  448. if fieldKey == "" {
  449. fieldKey = field.Type
  450. }
  451. secretData[fieldKey] = getFieldValue(field.Value)
  452. }
  453. }
  454. return secretData
  455. }
  456. func (s *Secret) getCustomField(key string) ([]byte, error) {
  457. for _, field := range s.Custom {
  458. if field.Label == key && len(field.Value) > 0 {
  459. return getFieldValue(field.Value), nil
  460. }
  461. }
  462. return nil, fmt.Errorf(errKeeperSecurityInvalidField, key)
  463. }
  464. func (s *Secret) getCustomFields() map[string][]byte {
  465. secretData := make(map[string][]byte)
  466. for _, field := range s.Custom {
  467. if len(field.Value) > 0 {
  468. secretData[field.Label] = getFieldValue(field.Value)
  469. }
  470. }
  471. return secretData
  472. }
  473. func (s *Secret) getFile(key string) ([]byte, error) {
  474. for _, file := range s.Files {
  475. if file.Title == key {
  476. return []byte(file.Content), nil
  477. }
  478. }
  479. return nil, fmt.Errorf(errKeeperSecurityInvalidField, key)
  480. }
  481. func (s *Secret) getProperty(key string) ([]byte, error) {
  482. field, _ := s.getField(key)
  483. if field != nil {
  484. return field, nil
  485. }
  486. customField, _ := s.getCustomField(key)
  487. if customField != nil {
  488. return customField, nil
  489. }
  490. file, _ := s.getFile(key)
  491. if file != nil {
  492. return file, nil
  493. }
  494. return nil, fmt.Errorf(errKeeperSecurityInvalidProperty, s.Title, key)
  495. }
  496. func (s *Secret) getFiles() map[string][]byte {
  497. secretData := make(map[string][]byte)
  498. for _, file := range s.Files {
  499. secretData[file.Title] = []byte(file.Content)
  500. }
  501. return secretData
  502. }
  503. func (s *Secret) toString() (string, error) {
  504. secretJSON, err := json.Marshal(s)
  505. if err != nil {
  506. return "", fmt.Errorf(errInvalidJSONSecret, s.Title, err)
  507. }
  508. return string(secretJSON), nil
  509. }