token_fetcher.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. "fmt"
  15. "github.com/aws/aws-sdk-go/aws/credentials"
  16. authv1 "k8s.io/api/authentication/v1"
  17. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  18. corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
  19. )
  20. // mostly taken from:
  21. // https://github.com/aws/secrets-store-csi-driver-provider-aws/blob/main/auth/auth.go#L140-L145
  22. const (
  23. tokenAudience = "sts.amazonaws.com"
  24. )
  25. type authTokenFetcher struct {
  26. Namespace string
  27. ServiceAccount string
  28. k8sClient corev1.CoreV1Interface
  29. }
  30. // FetchToken satisfies the stscreds.TokenFetcher interface
  31. // it is used to generate service account tokens which are consumed by the aws sdk.
  32. func (p authTokenFetcher) FetchToken(ctx credentials.Context) ([]byte, error) {
  33. log.V(1).Info("fetching token", "ns", p.Namespace, "sa", p.ServiceAccount)
  34. tokRsp, err := p.k8sClient.ServiceAccounts(p.Namespace).CreateToken(ctx, p.ServiceAccount, &authv1.TokenRequest{
  35. Spec: authv1.TokenRequestSpec{
  36. Audiences: []string{tokenAudience},
  37. },
  38. }, metav1.CreateOptions{})
  39. if err != nil {
  40. return nil, fmt.Errorf("error creating service account token: %w", err)
  41. }
  42. return []byte(tokRsp.Status.Token), nil
  43. }