auth.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 secretmanager
  13. import (
  14. "context"
  15. "errors"
  16. "fmt"
  17. "golang.org/x/oauth2"
  18. "golang.org/x/oauth2/google"
  19. kclient "sigs.k8s.io/controller-runtime/pkg/client"
  20. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  21. "github.com/external-secrets/external-secrets/pkg/utils/resolvers"
  22. )
  23. func NewTokenSource(ctx context.Context, auth esv1.GCPSMAuth, projectID, storeKind string, kube kclient.Client, namespace string) (oauth2.TokenSource, error) {
  24. ts, err := serviceAccountTokenSource(ctx, auth, storeKind, kube, namespace)
  25. if ts != nil || err != nil {
  26. return ts, err
  27. }
  28. wi, err := newWorkloadIdentity(ctx, projectID)
  29. if err != nil {
  30. return nil, errors.New("unable to initialize workload identity")
  31. }
  32. defer func() {
  33. _ = wi.Close()
  34. }()
  35. isClusterKind := storeKind == esv1.ClusterSecretStoreKind
  36. ts, err = wi.TokenSource(ctx, auth, isClusterKind, kube, namespace)
  37. if ts != nil || err != nil {
  38. return ts, err
  39. }
  40. return google.DefaultTokenSource(ctx, CloudPlatformRole)
  41. }
  42. func serviceAccountTokenSource(ctx context.Context, auth esv1.GCPSMAuth, storeKind string, kube kclient.Client, namespace string) (oauth2.TokenSource, error) {
  43. sr := auth.SecretRef
  44. if sr == nil {
  45. return nil, nil
  46. }
  47. credentials, err := resolvers.SecretKeyRef(
  48. ctx,
  49. kube,
  50. storeKind,
  51. namespace,
  52. &auth.SecretRef.SecretAccessKey)
  53. if err != nil {
  54. return nil, err
  55. }
  56. config, err := google.JWTConfigFromJSON([]byte(credentials), CloudPlatformRole)
  57. if err != nil {
  58. return nil, fmt.Errorf(errUnableProcessJSONCredentials, err)
  59. }
  60. return config.TokenSource(ctx), nil
  61. }