auth_jwt.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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 conjur
  13. import (
  14. "context"
  15. "crypto/tls"
  16. "crypto/x509"
  17. "fmt"
  18. "net/http"
  19. "time"
  20. "github.com/cyberark/conjur-api-go/conjurapi"
  21. authenticationv1 "k8s.io/api/authentication/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  24. esmeta "github.com/external-secrets/external-secrets/apis/meta/v1"
  25. )
  26. const JwtLifespan = 600 // 10 minutes
  27. // getJWTToken retrieves a JWT token either using the TokenRequest API for a specified service account, or from a jwt stored in a k8s secret.
  28. func (p *Client) getJWTToken(ctx context.Context, conjurJWTConfig *esv1beta1.ConjurJWT) (string, error) {
  29. if conjurJWTConfig.ServiceAccountRef != nil {
  30. // Should work for Kubernetes >=v1.22: fetch token via TokenRequest API
  31. jwtToken, err := p.getJwtFromServiceAccountTokenRequest(ctx, *conjurJWTConfig.ServiceAccountRef, nil, JwtLifespan)
  32. if err != nil {
  33. return "", err
  34. }
  35. return jwtToken, nil
  36. } else if conjurJWTConfig.SecretRef != nil {
  37. tokenRef := conjurJWTConfig.SecretRef
  38. if tokenRef.Key == "" {
  39. tokenRef = conjurJWTConfig.SecretRef.DeepCopy()
  40. tokenRef.Key = "token"
  41. }
  42. jwtToken, err := p.secretKeyRef(ctx, tokenRef)
  43. if err != nil {
  44. return "", err
  45. }
  46. return jwtToken, nil
  47. }
  48. return "", fmt.Errorf("missing ServiceAccountRef or SecretRef")
  49. }
  50. // getJwtFromServiceAccountTokenRequest uses the TokenRequest API to get a JWT token for the given service account.
  51. func (p *Client) getJwtFromServiceAccountTokenRequest(ctx context.Context, serviceAccountRef esmeta.ServiceAccountSelector, additionalAud []string, expirationSeconds int64) (string, error) {
  52. audiences := serviceAccountRef.Audiences
  53. if len(additionalAud) > 0 {
  54. audiences = append(audiences, additionalAud...)
  55. }
  56. tokenRequest := &authenticationv1.TokenRequest{
  57. ObjectMeta: metav1.ObjectMeta{
  58. Namespace: p.namespace,
  59. },
  60. Spec: authenticationv1.TokenRequestSpec{
  61. Audiences: audiences,
  62. ExpirationSeconds: &expirationSeconds,
  63. },
  64. }
  65. if (p.StoreKind == esv1beta1.ClusterSecretStoreKind) &&
  66. (serviceAccountRef.Namespace != nil) {
  67. tokenRequest.Namespace = *serviceAccountRef.Namespace
  68. }
  69. tokenResponse, err := p.corev1.ServiceAccounts(tokenRequest.Namespace).CreateToken(ctx, serviceAccountRef.Name, tokenRequest, metav1.CreateOptions{})
  70. if err != nil {
  71. return "", fmt.Errorf(errGetKubeSATokenRequest, serviceAccountRef.Name, err)
  72. }
  73. return tokenResponse.Status.Token, nil
  74. }
  75. // newClientFromJwt creates a new Conjur client using the given JWT Auth Config.
  76. func (p *Client) newClientFromJwt(ctx context.Context, config conjurapi.Config, jwtAuth *esv1beta1.ConjurJWT) (SecretsClient, error) {
  77. jwtToken, getJWTError := p.getJWTToken(ctx, jwtAuth)
  78. if getJWTError != nil {
  79. return nil, getJWTError
  80. }
  81. client, clientError := p.clientAPI.NewClientFromJWT(config, jwtToken, jwtAuth.ServiceID)
  82. if clientError != nil {
  83. return nil, clientError
  84. }
  85. return client, nil
  86. }
  87. // newHTTPSClient creates a new HTTPS client with the given cert.
  88. func newHTTPSClient(cert []byte) (*http.Client, error) {
  89. pool := x509.NewCertPool()
  90. ok := pool.AppendCertsFromPEM(cert)
  91. if !ok {
  92. return nil, fmt.Errorf("can't append Conjur SSL cert")
  93. }
  94. tr := &http.Transport{
  95. TLSClientConfig: &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12},
  96. }
  97. return &http.Client{Transport: tr, Timeout: time.Second * 10}, nil
  98. }