iso.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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 auth
  13. import (
  14. "context"
  15. "crypto/tls"
  16. "encoding/json"
  17. "errors"
  18. "io"
  19. "net/http"
  20. "net/url"
  21. "strconv"
  22. "strings"
  23. "sigs.k8s.io/controller-runtime/pkg/client"
  24. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  25. "github.com/external-secrets/external-secrets/pkg/utils/resolvers"
  26. )
  27. type ISOInterface interface {
  28. IsoSessionFromSecretRef(ctx context.Context, provider *esv1.SenhaseguraProvider, store esv1.GenericStore, kube client.Client, namespace string) (*SenhaseguraIsoSession, error)
  29. GetIsoToken(clientID, clientSecret, systemURL string, ignoreSslCertificate bool) (token string, err error)
  30. }
  31. /*
  32. SenhaseguraIsoSession contains information about senhasegura ISO API for any request.
  33. */
  34. type SenhaseguraIsoSession struct {
  35. URL string
  36. Token string
  37. IgnoreSslCertificate bool
  38. isoClient ISOInterface
  39. }
  40. /*
  41. isoGetTokenResponse contains response from OAuth2 authentication endpoint in senhasegura API.
  42. */
  43. type isoGetTokenResponse struct {
  44. TokenType string `json:"token_type"`
  45. ExpiresIn int `json:"expires_in"`
  46. AccessToken string `json:"access_token"`
  47. }
  48. var (
  49. errCannotCreateRequest = errors.New("cannot create request to senhasegura resource /iso/oauth2/token")
  50. errCannotDoRequest = errors.New("cannot do request in senhasegura, SSL certificate is valid ?")
  51. errInvalidResponseBody = errors.New("invalid HTTP response body received from senhasegura")
  52. errInvalidHTTPCode = errors.New("received invalid HTTP code from senhasegura")
  53. )
  54. /*
  55. Authenticate check required authentication method based on provider spec and initialize ISO OAuth2 session.
  56. */
  57. func Authenticate(ctx context.Context, store esv1.GenericStore, provider *esv1.SenhaseguraProvider, kube client.Client, namespace string) (isoSession *SenhaseguraIsoSession, err error) {
  58. isoSession, err = isoSession.IsoSessionFromSecretRef(ctx, provider, store, kube, namespace)
  59. if err != nil {
  60. return nil, err
  61. }
  62. return isoSession, nil
  63. }
  64. /*
  65. IsoSessionFromSecretRef initialize an ISO OAuth2 flow with .spec.provider.senhasegura.auth.isoSecretRef parameters.
  66. */
  67. func (s *SenhaseguraIsoSession) IsoSessionFromSecretRef(ctx context.Context, provider *esv1.SenhaseguraProvider, store esv1.GenericStore, kube client.Client, namespace string) (*SenhaseguraIsoSession, error) {
  68. secret, err := resolvers.SecretKeyRef(
  69. ctx,
  70. kube,
  71. store.GetKind(),
  72. namespace,
  73. &provider.Auth.ClientSecret,
  74. )
  75. if err != nil {
  76. return &SenhaseguraIsoSession{}, err
  77. }
  78. isoToken, err := s.GetIsoToken(provider.Auth.ClientID, secret, provider.URL, provider.IgnoreSslCertificate)
  79. if err != nil {
  80. return &SenhaseguraIsoSession{}, err
  81. }
  82. return &SenhaseguraIsoSession{
  83. URL: provider.URL,
  84. Token: isoToken,
  85. IgnoreSslCertificate: provider.IgnoreSslCertificate,
  86. isoClient: &SenhaseguraIsoSession{},
  87. }, nil
  88. }
  89. /*
  90. GetIsoToken calls senhasegura OAuth2 endpoint to get a token.
  91. */
  92. func (s *SenhaseguraIsoSession) GetIsoToken(clientID, clientSecret, systemURL string, ignoreSslCertificate bool) (token string, err error) {
  93. data := url.Values{}
  94. data.Set("grant_type", "client_credentials")
  95. data.Set("client_id", clientID)
  96. data.Set("client_secret", clientSecret)
  97. u, _ := url.ParseRequestURI(systemURL)
  98. u.Path = "/iso/oauth2/token"
  99. tr := &http.Transport{
  100. //nolint
  101. TLSClientConfig: &tls.Config{InsecureSkipVerify: ignoreSslCertificate},
  102. }
  103. client := &http.Client{Transport: tr}
  104. r, err := http.NewRequest("POST", u.String(), strings.NewReader(data.Encode()))
  105. if err != nil {
  106. return "", errCannotCreateRequest
  107. }
  108. r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  109. r.Header.Set("Content-Length", strconv.Itoa(len(data.Encode())))
  110. resp, err := client.Do(r)
  111. if err != nil {
  112. return "", errCannotDoRequest
  113. }
  114. defer func() {
  115. _ = resp.Body.Close()
  116. }()
  117. if resp.StatusCode != 200 {
  118. return "", errInvalidHTTPCode
  119. }
  120. respData, err := io.ReadAll(resp.Body)
  121. if err != nil {
  122. return "", errInvalidResponseBody
  123. }
  124. var respObj isoGetTokenResponse
  125. err = json.Unmarshal(respData, &respObj)
  126. if err != nil {
  127. return "", errInvalidResponseBody
  128. }
  129. return respObj.AccessToken, nil
  130. }