device42_api.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. "fmt"
  19. "net/http"
  20. "strconv"
  21. "time"
  22. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  23. )
  24. const (
  25. DoRequestError = "error: do request: %w"
  26. errJSONSecretUnmarshal = "unable to unmarshal secret: %w"
  27. )
  28. type HTTPClient interface {
  29. Do(*http.Request) (*http.Response, error)
  30. }
  31. type API struct {
  32. client HTTPClient
  33. baseURL string
  34. hostPort string
  35. password string
  36. username string
  37. }
  38. type D42PasswordResponse struct {
  39. Passwords []D42Password
  40. }
  41. type D42Password struct {
  42. Password string `json:"password"`
  43. ID int `json:"id"`
  44. }
  45. func NewAPI(baseURL, username, password, hostPort string) *API {
  46. api := &API{
  47. baseURL: baseURL,
  48. hostPort: hostPort,
  49. username: username,
  50. password: password,
  51. }
  52. tr := &http.Transport{
  53. TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
  54. }
  55. api.client = &http.Client{Transport: tr}
  56. return api
  57. }
  58. func (api *API) doAuthenticatedRequest(r *http.Request) (*http.Response, error) {
  59. r.SetBasicAuth(api.username, api.password)
  60. return api.client.Do(r)
  61. }
  62. func ReadAndUnmarshal(resp *http.Response, target any) error {
  63. var buf bytes.Buffer
  64. defer func() {
  65. err := resp.Body.Close()
  66. if err != nil {
  67. return
  68. }
  69. }()
  70. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  71. return fmt.Errorf("failed to authenticate with the given credentials: %d %s", resp.StatusCode, buf.String())
  72. }
  73. _, err := buf.ReadFrom(resp.Body)
  74. if err != nil {
  75. return err
  76. }
  77. return json.Unmarshal(buf.Bytes(), target)
  78. }
  79. func (api *API) GetSecret(secretID string) (D42Password, error) {
  80. // https://api.device42.com/#!/Passwords/getPassword
  81. endpointURL := fmt.Sprintf("https://%s:%s/api/1.0/passwords/?id=%s&plain_text=yes", api.baseURL, api.hostPort, secretID)
  82. ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
  83. defer cancel()
  84. readSecretRequest, err := http.NewRequestWithContext(ctx, "GET", endpointURL, http.NoBody)
  85. if err != nil {
  86. return D42Password{}, fmt.Errorf("error: creating secrets request: %w", err)
  87. }
  88. respSecretRead, err := api.doAuthenticatedRequest(readSecretRequest) //nolint:bodyclose // linters bug
  89. if err != nil {
  90. return D42Password{}, fmt.Errorf(DoRequestError, err)
  91. }
  92. d42PasswordResponse := D42PasswordResponse{}
  93. err = ReadAndUnmarshal(respSecretRead, &d42PasswordResponse)
  94. if err != nil {
  95. return D42Password{}, fmt.Errorf(errJSONSecretUnmarshal, err)
  96. }
  97. if len(d42PasswordResponse.Passwords) == 0 {
  98. return D42Password{}, err
  99. }
  100. // There should only be one response
  101. return d42PasswordResponse.Passwords[0], err
  102. }
  103. func (api *API) GetSecretMap(_ context.Context, _ esv1beta1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  104. return nil, fmt.Errorf(errNotImplemented)
  105. }
  106. func (s D42Password) ToMap() map[string][]byte {
  107. m := make(map[string][]byte)
  108. m["password"] = []byte(s.Password)
  109. m["id"] = []byte(strconv.Itoa(s.ID))
  110. return m
  111. }