serviceaccount.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 oracle
  13. import (
  14. "context"
  15. "github.com/oracle/oci-go-sdk/v65/common/auth"
  16. authv1 "k8s.io/api/authentication/v1"
  17. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  18. "k8s.io/client-go/kubernetes"
  19. esmeta "github.com/external-secrets/external-secrets/apis/meta/v1"
  20. )
  21. // TokenProvider implements the ServiceAccountTokenProvider interface to create service account tokens for OCI authentication.
  22. type TokenProvider struct {
  23. Name string
  24. Namespace string
  25. Audiences []string
  26. Clientset kubernetes.Interface
  27. }
  28. var _ auth.ServiceAccountTokenProvider = &TokenProvider{}
  29. // NewTokenProvider creates a new TokenProvider for a given service account.
  30. func NewTokenProvider(clientset kubernetes.Interface, serviceAccountRef *esmeta.ServiceAccountSelector, namespace string) *TokenProvider {
  31. // "api" is the default OCI workload identity audience.
  32. audiences := []string{"api"}
  33. if len(serviceAccountRef.Audiences) > 0 {
  34. audiences = append(audiences, serviceAccountRef.Audiences...)
  35. }
  36. if serviceAccountRef.Namespace != nil {
  37. namespace = *serviceAccountRef.Namespace
  38. }
  39. return &TokenProvider{
  40. Name: serviceAccountRef.Name,
  41. Namespace: namespace,
  42. Audiences: audiences,
  43. Clientset: clientset,
  44. }
  45. }
  46. // ServiceAccountToken creates a new service account token for OCI authentication.
  47. func (t *TokenProvider) ServiceAccountToken() (string, error) {
  48. tok, err := t.Clientset.CoreV1().ServiceAccounts(t.Namespace).CreateToken(context.Background(), t.Name, &authv1.TokenRequest{
  49. Spec: authv1.TokenRequestSpec{
  50. Audiences: t.Audiences,
  51. },
  52. }, metav1.CreateOptions{})
  53. if err != nil {
  54. return "", err
  55. }
  56. return tok.Status.Token, nil
  57. }