serviceaccount.go 2.2 KB

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