workload_identity.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 secretmanager
  14. import (
  15. "bytes"
  16. "context"
  17. "encoding/json"
  18. "fmt"
  19. "io"
  20. "net/http"
  21. "time"
  22. "cloud.google.com/go/compute/metadata"
  23. iam "cloud.google.com/go/iam/credentials/apiv1"
  24. "cloud.google.com/go/iam/credentials/apiv1/credentialspb"
  25. gsmapiv1 "cloud.google.com/go/secretmanager/apiv1"
  26. "github.com/googleapis/gax-go/v2"
  27. "golang.org/x/oauth2"
  28. "google.golang.org/api/option"
  29. "google.golang.org/grpc"
  30. "google.golang.org/grpc/credentials"
  31. "grpc.go4.org/credentials/oauth"
  32. authenticationv1 "k8s.io/api/authentication/v1"
  33. v1 "k8s.io/api/core/v1"
  34. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  35. "k8s.io/apimachinery/pkg/types"
  36. "k8s.io/client-go/kubernetes"
  37. clientcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
  38. kclient "sigs.k8s.io/controller-runtime/pkg/client"
  39. ctrlcfg "sigs.k8s.io/controller-runtime/pkg/client/config"
  40. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  41. "github.com/external-secrets/external-secrets/runtime/constants"
  42. "github.com/external-secrets/external-secrets/runtime/metrics"
  43. )
  44. const (
  45. gcpSAAnnotation = "iam.gke.io/gcp-service-account"
  46. errFetchPodToken = "unable to fetch pod token: %w"
  47. errFetchIBToken = "unable to fetch identitybindingtoken: %w"
  48. errGenAccessToken = "unable to generate gcp access token: %w"
  49. errLookupIdentity = "unable to lookup workload identity: %w"
  50. errNoProjectID = "unable to find ProjectID in storeSpec"
  51. )
  52. var (
  53. // defaultUniverseDomain is the domain which will be used in the STS token URL.
  54. defaultUniverseDomain = "googleapis.com"
  55. // workloadIdentitySubjectTokenType is the STS token type used in Oauth2.0 token exchange.
  56. workloadIdentitySubjectTokenType = "urn:ietf:params:oauth:token-type:jwt"
  57. // workloadIdentitySubjectTokenType is the STS token type used in Oauth2.0 token exchange with AWS.
  58. workloadIdentitySubjectTokenTypeAWS = "urn:ietf:params:aws:token-type:aws4_request"
  59. // workloadIdentityTokenGrantType is the grant type for OAuth 2.0 token exchange .
  60. workloadIdentityTokenGrantType = "urn:ietf:params:oauth:grant-type:token-exchange"
  61. // workloadIdentityRequestedTokenType is the requested type for OAuth 2.0 access token.
  62. workloadIdentityRequestedTokenType = "urn:ietf:params:oauth:token-type:access_token"
  63. // workloadIdentityTokenURL is the token service endpoint.
  64. workloadIdentityTokenURL = "https://sts.googleapis.com/v1/token"
  65. // workloadIdentityTokenInfoURL is the STS introspection service endpoint.
  66. workloadIdentityTokenInfoURL = "https://sts.googleapis.com/v1/introspect"
  67. )
  68. // workloadIdentity holds all clients and generators needed
  69. // to create a gcp oauth token.
  70. type workloadIdentity struct {
  71. iamClient IamClient
  72. metadataClient MetadataClient
  73. idBindTokenGenerator idBindTokenGenerator
  74. saTokenGenerator saTokenGenerator
  75. clusterProjectID string
  76. }
  77. // IamClient provides an interface to the GCP IAM API.
  78. type IamClient interface {
  79. GenerateAccessToken(ctx context.Context, req *credentialspb.GenerateAccessTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateAccessTokenResponse, error)
  80. Close() error
  81. }
  82. // MetadataClient defines the interface for interacting with GCP Metadata service.
  83. // It provides access to instance metadata and project information.
  84. type MetadataClient interface {
  85. InstanceAttributeValueWithContext(ctx context.Context, attr string) (string, error)
  86. ProjectIDWithContext(ctx context.Context) (string, error)
  87. }
  88. // interface to securetoken/identitybindingtoken API.
  89. type idBindTokenGenerator interface {
  90. Generate(context.Context, *http.Client, string, string, string) (*oauth2.Token, error)
  91. }
  92. // interface to kubernetes serviceaccount token request API.
  93. type saTokenGenerator interface {
  94. Generate(context.Context, []string, string, string) (*authenticationv1.TokenRequest, error)
  95. }
  96. func newWorkloadIdentity(ctx context.Context, projectID string) (*workloadIdentity, error) {
  97. satg, err := newSATokenGenerator()
  98. if err != nil {
  99. return nil, err
  100. }
  101. iamc, err := newIAMClient(ctx)
  102. if err != nil {
  103. return nil, err
  104. }
  105. return &workloadIdentity{
  106. iamClient: iamc,
  107. metadataClient: newMetadataClient(),
  108. idBindTokenGenerator: newIDBindTokenGenerator(),
  109. saTokenGenerator: satg,
  110. clusterProjectID: projectID,
  111. }, nil
  112. }
  113. func (w *workloadIdentity) gcpWorkloadIdentity(ctx context.Context, id *esv1.GCPWorkloadIdentity) (string, string, error) {
  114. var err error
  115. projectID := id.ClusterProjectID
  116. if projectID == "" {
  117. if projectID, err = w.metadataClient.ProjectIDWithContext(ctx); err != nil {
  118. return "", "", fmt.Errorf("unable to get project id: %w", err)
  119. }
  120. }
  121. clusterLocation := id.ClusterLocation
  122. if clusterLocation == "" {
  123. if clusterLocation, err = w.metadataClient.InstanceAttributeValueWithContext(ctx, "cluster-location"); err != nil {
  124. return "", "", fmt.Errorf("unable to determine cluster location: %w", err)
  125. }
  126. }
  127. clusterName := id.ClusterName
  128. if clusterName == "" {
  129. if clusterName, err = w.metadataClient.InstanceAttributeValueWithContext(ctx, "cluster-name"); err != nil {
  130. return "", "", fmt.Errorf("unable to determine cluster name: %w", err)
  131. }
  132. }
  133. idPool := fmt.Sprintf("%s.svc.id.goog", projectID)
  134. idProvider := fmt.Sprintf("https://container.googleapis.com/v1/projects/%s/locations/%s/clusters/%s",
  135. projectID,
  136. clusterLocation,
  137. clusterName,
  138. )
  139. return idPool, idProvider, nil
  140. }
  141. func (w *workloadIdentity) TokenSource(ctx context.Context, auth esv1.GCPSMAuth, isClusterKind bool, kube kclient.Client, namespace string) (oauth2.TokenSource, error) {
  142. wi := auth.WorkloadIdentity
  143. if wi == nil {
  144. return nil, nil
  145. }
  146. saKey := types.NamespacedName{
  147. Name: wi.ServiceAccountRef.Name,
  148. Namespace: namespace,
  149. }
  150. // only ClusterStore is allowed to set namespace (and then it's required)
  151. if isClusterKind && wi.ServiceAccountRef.Namespace != nil {
  152. saKey.Namespace = *wi.ServiceAccountRef.Namespace
  153. }
  154. sa := &v1.ServiceAccount{}
  155. err := kube.Get(ctx, saKey, sa)
  156. if err != nil {
  157. return nil, err
  158. }
  159. idPool, idProvider, err := w.gcpWorkloadIdentity(ctx, wi)
  160. if err != nil {
  161. return nil, fmt.Errorf(errLookupIdentity, err)
  162. }
  163. audiences := []string{idPool}
  164. if len(wi.ServiceAccountRef.Audiences) > 0 {
  165. audiences = append(audiences, wi.ServiceAccountRef.Audiences...)
  166. }
  167. gcpSA := sa.Annotations[gcpSAAnnotation]
  168. resp, err := w.saTokenGenerator.Generate(ctx, audiences, saKey.Name, saKey.Namespace)
  169. metrics.ObserveAPICall(constants.ProviderGCPSM, constants.CallGCPSMGenerateSAToken, err)
  170. if err != nil {
  171. return nil, fmt.Errorf(errFetchPodToken, err)
  172. }
  173. idBindToken, err := w.idBindTokenGenerator.Generate(ctx, http.DefaultClient, resp.Status.Token, idPool, idProvider)
  174. metrics.ObserveAPICall(constants.ProviderGCPSM, constants.CallGCPSMGenerateIDBindToken, err)
  175. if err != nil {
  176. return nil, fmt.Errorf(errFetchIBToken, err)
  177. }
  178. // If no `iam.gke.io/gcp-service-account` annotation is present the
  179. // identitybindingtoken will be used directly, allowing bindings on secrets
  180. // of the form "serviceAccount:<project>.svc.id.goog[<namespace>/<sa>]".
  181. if gcpSA == "" {
  182. return oauth2.StaticTokenSource(idBindToken), nil
  183. }
  184. gcpSAResp, err := w.iamClient.GenerateAccessToken(ctx, &credentialspb.GenerateAccessTokenRequest{
  185. Name: fmt.Sprintf("projects/-/serviceAccounts/%s", gcpSA),
  186. Scope: gsmapiv1.DefaultAuthScopes(),
  187. }, gax.WithGRPCOptions(grpc.PerRPCCredentials(oauth.TokenSource{TokenSource: oauth2.StaticTokenSource(idBindToken)})))
  188. metrics.ObserveAPICall(constants.ProviderGCPSM, constants.CallGCPSMGenerateAccessToken, err)
  189. if err != nil {
  190. return nil, fmt.Errorf(errGenAccessToken, err)
  191. }
  192. return oauth2.StaticTokenSource(&oauth2.Token{
  193. AccessToken: gcpSAResp.GetAccessToken(),
  194. }), nil
  195. }
  196. func (w *workloadIdentity) Close() error {
  197. if w.iamClient != nil {
  198. return w.iamClient.Close()
  199. }
  200. return nil
  201. }
  202. func newIAMClient(ctx context.Context) (IamClient, error) {
  203. iamOpts := []option.ClientOption{
  204. option.WithUserAgent("external-secrets-operator"),
  205. // tell the secretmanager library to not add transport-level ADC since
  206. // we need to override on a per call basis
  207. option.WithoutAuthentication(),
  208. // grpc oauth TokenSource credentials require transport security, so
  209. // this must be set explicitly even though TLS is used
  210. option.WithGRPCDialOption(grpc.WithTransportCredentials(credentials.NewTLS(nil))),
  211. option.WithGRPCConnectionPool(5),
  212. }
  213. return iam.NewIamCredentialsClient(ctx, iamOpts...)
  214. }
  215. func newMetadataClient() MetadataClient {
  216. return metadata.NewClient(&http.Client{
  217. Timeout: 5 * time.Second,
  218. })
  219. }
  220. type k8sSATokenGenerator struct {
  221. corev1 clientcorev1.CoreV1Interface
  222. }
  223. func (g *k8sSATokenGenerator) Generate(ctx context.Context, audiences []string, name, namespace string) (*authenticationv1.TokenRequest, error) {
  224. // Request a serviceaccount token for the pod
  225. ttl := int64((15 * time.Minute).Seconds())
  226. return g.corev1.
  227. ServiceAccounts(namespace).
  228. CreateToken(ctx, name,
  229. &authenticationv1.TokenRequest{
  230. Spec: authenticationv1.TokenRequestSpec{
  231. ExpirationSeconds: &ttl,
  232. Audiences: audiences,
  233. },
  234. },
  235. metav1.CreateOptions{},
  236. )
  237. }
  238. func newSATokenGenerator() (saTokenGenerator, error) {
  239. cfg, err := ctrlcfg.GetConfig()
  240. if err != nil {
  241. return nil, err
  242. }
  243. clientset, err := kubernetes.NewForConfig(cfg)
  244. if err != nil {
  245. return nil, err
  246. }
  247. return &k8sSATokenGenerator{
  248. corev1: clientset.CoreV1(),
  249. }, nil
  250. }
  251. // Trades the kubernetes token for an identitybindingtoken token.
  252. type gcpIDBindTokenGenerator struct {
  253. targetURL string
  254. }
  255. func newIDBindTokenGenerator() idBindTokenGenerator {
  256. return &gcpIDBindTokenGenerator{
  257. targetURL: "https://securetoken.googleapis.com/v1/identitybindingtoken",
  258. }
  259. }
  260. func (g *gcpIDBindTokenGenerator) Generate(ctx context.Context, client *http.Client, k8sToken, idPool, idProvider string) (*oauth2.Token, error) {
  261. body, err := json.Marshal(map[string]string{
  262. "grant_type": workloadIdentityTokenGrantType,
  263. "subject_token_type": workloadIdentitySubjectTokenType,
  264. "requested_token_type": workloadIdentityRequestedTokenType,
  265. "subject_token": k8sToken,
  266. "audience": fmt.Sprintf("identitynamespace:%s:%s", idPool, idProvider),
  267. "scope": CloudPlatformRole,
  268. })
  269. if err != nil {
  270. return nil, err
  271. }
  272. req, err := http.NewRequestWithContext(ctx, "POST", g.targetURL, bytes.NewBuffer(body))
  273. if err != nil {
  274. return nil, err
  275. }
  276. req.Header.Set("Content-Type", "application/json")
  277. resp, err := client.Do(req)
  278. if err != nil {
  279. return nil, err
  280. }
  281. if resp.StatusCode != http.StatusOK {
  282. return nil, fmt.Errorf("could not get idbindtoken token, status: %v", resp.StatusCode)
  283. }
  284. defer func() {
  285. _ = resp.Body.Close()
  286. }()
  287. respBody, err := io.ReadAll(resp.Body)
  288. if err != nil {
  289. return nil, err
  290. }
  291. idBindToken := &oauth2.Token{}
  292. if err := json.Unmarshal(respBody, idBindToken); err != nil {
  293. return nil, err
  294. }
  295. return idBindToken, nil
  296. }