client.go 17 KB

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