token_fetcher.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. type authTokenFetcher struct {
  23. Namespace string
  24. // Audience is the token aud claim
  25. // which is verified by the aws oidc provider
  26. // see: https://github.com/external-secrets/external-secrets/issues/1251#issuecomment-1161745849
  27. Audiences []string
  28. ServiceAccount string
  29. k8sClient corev1.CoreV1Interface
  30. }
  31. // FetchToken satisfies the stscreds.TokenFetcher interface
  32. // it is used to generate service account tokens which are consumed by the aws sdk.
  33. func (p authTokenFetcher) FetchToken(ctx credentials.Context) ([]byte, error) {
  34. log.V(1).Info("fetching token", "ns", p.Namespace, "sa", p.ServiceAccount)
  35. tokRsp, err := p.k8sClient.ServiceAccounts(p.Namespace).CreateToken(ctx, p.ServiceAccount, &authv1.TokenRequest{
  36. Spec: authv1.TokenRequestSpec{
  37. Audiences: p.Audiences,
  38. },
  39. }, metav1.CreateOptions{})
  40. if err != nil {
  41. return nil, fmt.Errorf("error creating service account token: %w", err)
  42. }
  43. return []byte(tokRsp.Status.Token), nil
  44. }