auth.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  21. "github.com/external-secrets/external-secrets/pkg/utils/resolvers"
  22. )
  23. func NewTokenSource(ctx context.Context, auth esv1beta1.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 wi.Close()
  33. isClusterKind := storeKind == esv1beta1.ClusterSecretStoreKind
  34. ts, err = wi.TokenSource(ctx, auth, isClusterKind, kube, namespace)
  35. if ts != nil || err != nil {
  36. return ts, err
  37. }
  38. return google.DefaultTokenSource(ctx, CloudPlatformRole)
  39. }
  40. func serviceAccountTokenSource(ctx context.Context, auth esv1beta1.GCPSMAuth, storeKind string, kube kclient.Client, namespace string) (oauth2.TokenSource, error) {
  41. sr := auth.SecretRef
  42. if sr == nil {
  43. return nil, nil
  44. }
  45. credentials, err := resolvers.SecretKeyRef(
  46. ctx,
  47. kube,
  48. storeKind,
  49. namespace,
  50. &auth.SecretRef.SecretAccessKey)
  51. if err != nil {
  52. return nil, err
  53. }
  54. config, err := google.JWTConfigFromJSON([]byte(credentials), CloudPlatformRole)
  55. if err != nil {
  56. return nil, fmt.Errorf(errUnableProcessJSONCredentials, err)
  57. }
  58. return config.TokenSource(ctx), nil
  59. }