device42_api.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package device42
  13. import (
  14. "bytes"
  15. "context"
  16. "crypto/tls"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "net/http"
  21. "strconv"
  22. "time"
  23. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  24. )
  25. const (
  26. DoRequestError = "error: do request: %w"
  27. errJSONSecretUnmarshal = "unable to unmarshal secret: %w"
  28. )
  29. type HTTPClient interface {
  30. Do(*http.Request) (*http.Response, error)
  31. }
  32. type API struct {
  33. client HTTPClient
  34. baseURL string
  35. hostPort string
  36. password string
  37. username string
  38. }
  39. type D42PasswordResponse struct {
  40. Passwords []D42Password
  41. }
  42. type D42Password struct {
  43. Password string `json:"password"`
  44. ID int `json:"id"`
  45. }
  46. func NewAPI(baseURL, username, password, hostPort string) *API {
  47. api := &API{
  48. baseURL: baseURL,
  49. hostPort: hostPort,
  50. username: username,
  51. password: password,
  52. }
  53. tr := &http.Transport{
  54. TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
  55. }
  56. api.client = &http.Client{Transport: tr}
  57. return api
  58. }
  59. func (api *API) doAuthenticatedRequest(r *http.Request) (*http.Response, error) {
  60. r.SetBasicAuth(api.username, api.password)
  61. return api.client.Do(r)
  62. }
  63. func ReadAndUnmarshal(resp *http.Response, target any) error {
  64. var buf bytes.Buffer
  65. defer func() {
  66. err := resp.Body.Close()
  67. if err != nil {
  68. return
  69. }
  70. }()
  71. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  72. return fmt.Errorf("failed to authenticate with the given credentials: %d %s", resp.StatusCode, buf.String())
  73. }
  74. _, err := buf.ReadFrom(resp.Body)
  75. if err != nil {
  76. return err
  77. }
  78. return json.Unmarshal(buf.Bytes(), target)
  79. }
  80. func (api *API) GetSecret(secretID string) (D42Password, error) {
  81. // https://api.device42.com/#!/Passwords/getPassword
  82. endpointURL := fmt.Sprintf("https://%s:%s/api/1.0/passwords/?id=%s&plain_text=yes", api.baseURL, api.hostPort, secretID)
  83. ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
  84. defer cancel()
  85. readSecretRequest, err := http.NewRequestWithContext(ctx, "GET", endpointURL, http.NoBody)
  86. if err != nil {
  87. return D42Password{}, fmt.Errorf("error: creating secrets request: %w", err)
  88. }
  89. respSecretRead, err := api.doAuthenticatedRequest(readSecretRequest) //nolint:bodyclose // linters bug
  90. if err != nil {
  91. return D42Password{}, fmt.Errorf(DoRequestError, err)
  92. }
  93. d42PasswordResponse := D42PasswordResponse{}
  94. err = ReadAndUnmarshal(respSecretRead, &d42PasswordResponse)
  95. if err != nil {
  96. return D42Password{}, fmt.Errorf(errJSONSecretUnmarshal, err)
  97. }
  98. if len(d42PasswordResponse.Passwords) == 0 {
  99. return D42Password{}, err
  100. }
  101. // There should only be one response
  102. return d42PasswordResponse.Passwords[0], err
  103. }
  104. func (api *API) GetSecretMap(_ context.Context, _ esv1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  105. return nil, errors.New(errNotImplemented)
  106. }
  107. func (s D42Password) ToMap() map[string][]byte {
  108. m := make(map[string][]byte)
  109. m["password"] = []byte(s.Password)
  110. m["id"] = []byte(strconv.Itoa(s.ID))
  111. return m
  112. }