token_fetcher.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package auth
  14. import (
  15. "context"
  16. "fmt"
  17. authv1 "k8s.io/api/authentication/v1"
  18. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  19. corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
  20. )
  21. // mostly taken from:
  22. // https://github.com/aws/secrets-store-csi-driver-provider-aws/blob/main/auth/auth.go#L140-L145
  23. type authTokenFetcher struct {
  24. Namespace string
  25. // Audience is the token aud claim
  26. // which is verified by the aws oidc provider
  27. // see: https://github.com/external-secrets/external-secrets/issues/1251#issuecomment-1161745849
  28. Audiences []string
  29. ServiceAccount string
  30. k8sClient corev1.CoreV1Interface
  31. }
  32. // GetIdentityToken satisfies the stscreds.IdentityTokenRetriever interface
  33. // it is used to generate service account tokens which are consumed by the aws sdk.
  34. func (p authTokenFetcher) GetIdentityToken() ([]byte, error) {
  35. log.V(1).Info("fetching token", "ns", p.Namespace, "sa", p.ServiceAccount)
  36. tokRsp, err := p.k8sClient.ServiceAccounts(p.Namespace).CreateToken(context.Background(), p.ServiceAccount, &authv1.TokenRequest{
  37. Spec: authv1.TokenRequestSpec{
  38. Audiences: p.Audiences,
  39. },
  40. }, metav1.CreateOptions{})
  41. if err != nil {
  42. return nil, fmt.Errorf("error creating service account token: %w", err)
  43. }
  44. return []byte(tokRsp.Status.Token), nil
  45. }