auth_iam.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 vault
  14. import (
  15. "context"
  16. "errors"
  17. "fmt"
  18. "os"
  19. "path/filepath"
  20. "github.com/aws/aws-sdk-go-v2/aws"
  21. "github.com/aws/aws-sdk-go-v2/config"
  22. "github.com/aws/aws-sdk-go-v2/credentials/stscreds"
  23. "github.com/golang-jwt/jwt/v5"
  24. authaws "github.com/hashicorp/vault/api/auth/aws"
  25. kclient "sigs.k8s.io/controller-runtime/pkg/client"
  26. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  27. vaultiamauth "github.com/external-secrets/external-secrets/providers/v1/vault/iamauth"
  28. vaultutil "github.com/external-secrets/external-secrets/providers/v1/vault/util"
  29. "github.com/external-secrets/external-secrets/runtime/metrics"
  30. )
  31. const (
  32. defaultAWSRegion = "us-east-1"
  33. defaultAWSAuthMountPath = "aws"
  34. errNoAWSAuthMethodFound = "no AWS authentication method found: expected either IRSA or Pod Identity"
  35. errIrsaTokenFileNotFoundOnPod = "web identity token file not found at %s location: %w"
  36. errIrsaTokenFileNotReadable = "could not read the web identity token from the file %s: %w"
  37. errIrsaTokenNotValidJWT = "could not parse web identity token available at %s. not a valid jwt?: %w"
  38. errIrsaTokenNotValidClaims = "could not find pod identity info on token %s"
  39. )
  40. func setIamAuthToken(ctx context.Context, v *client, jwtProvider vaultutil.JwtProviderFactory, assumeRoler vaultiamauth.STSProvider) (bool, error) {
  41. iamAuth := v.store.Auth.Iam
  42. isClusterKind := v.storeKind == esv1.ClusterSecretStoreKind
  43. if iamAuth != nil {
  44. err := v.requestTokenWithIamAuth(ctx, iamAuth, isClusterKind, v.kube, v.namespace, jwtProvider, assumeRoler)
  45. if err != nil {
  46. return true, err
  47. }
  48. return true, nil
  49. }
  50. return false, nil
  51. }
  52. func (c *client) requestTokenWithIamAuth(
  53. ctx context.Context,
  54. iamAuth *esv1.VaultIamAuth,
  55. isClusterKind bool,
  56. k kclient.Client,
  57. n string,
  58. jwtProvider vaultutil.JwtProviderFactory,
  59. assumeRoler vaultiamauth.STSProvider,
  60. ) error {
  61. jwtAuth := iamAuth.JWTAuth
  62. secretRefAuth := iamAuth.SecretRef
  63. regionAWS := c.getRegionOrDefault(iamAuth.Region)
  64. awsAuthMountPath := c.getAuthMountPathOrDefault(iamAuth.Path)
  65. var credsProvider aws.CredentialsProvider
  66. var err error
  67. if jwtAuth != nil { // use credentials from a sa explicitly defined and referenced. Highest preference is given to this method/configuration.
  68. credsProvider, err = vaultiamauth.CredsFromServiceAccount(ctx, *iamAuth, regionAWS, isClusterKind, k, n, jwtProvider)
  69. if err != nil {
  70. return err
  71. }
  72. } else if secretRefAuth != nil { // if jwtAuth is not defined, check if secretRef is defined. Second preference.
  73. logger.V(1).Info("using credentials from secretRef")
  74. credsProvider, err = vaultiamauth.CredsFromSecretRef(ctx, *iamAuth, c.storeKind, k, n)
  75. if err != nil {
  76. return err
  77. }
  78. }
  79. // Neither of jwtAuth or secretRefAuth defined. Last preference.
  80. // Default to controller pod's identity
  81. if jwtAuth == nil && secretRefAuth == nil {
  82. credsProvider, err = c.getControllerPodCredentials(ctx, regionAWS, k, jwtProvider)
  83. if err != nil {
  84. return err
  85. }
  86. }
  87. var loadCfgOpts []func(*config.LoadOptions) error
  88. if credsProvider != nil {
  89. loadCfgOpts = append(loadCfgOpts, config.WithCredentialsProvider(credsProvider))
  90. }
  91. if regionAWS != "" {
  92. loadCfgOpts = append(loadCfgOpts, config.WithRegion(regionAWS))
  93. }
  94. cfg, err := config.LoadDefaultConfig(ctx, loadCfgOpts...)
  95. if err != nil {
  96. return err
  97. }
  98. if iamAuth.AWSIAMRole != "" {
  99. stsclient := assumeRoler(&cfg)
  100. if iamAuth.ExternalID != "" {
  101. cfg.Credentials = stscreds.NewAssumeRoleProvider(stsclient, iamAuth.AWSIAMRole, func(opts *stscreds.AssumeRoleOptions) {
  102. opts.ExternalID = aws.String(iamAuth.ExternalID)
  103. })
  104. } else {
  105. cfg.Credentials = stscreds.NewAssumeRoleProvider(stsclient, iamAuth.AWSIAMRole)
  106. }
  107. }
  108. getCreds, err := cfg.Credentials.Retrieve(ctx)
  109. if err != nil {
  110. return err
  111. }
  112. // Set environment variables. These would be fetched by Login
  113. _ = os.Setenv("AWS_ACCESS_KEY_ID", getCreds.AccessKeyID)
  114. _ = os.Setenv("AWS_SECRET_ACCESS_KEY", getCreds.SecretAccessKey)
  115. _ = os.Setenv("AWS_SESSION_TOKEN", getCreds.SessionToken)
  116. var awsAuthClient *authaws.AWSAuth
  117. if iamAuth.VaultAWSIAMServerID != "" {
  118. awsAuthClient, err = authaws.NewAWSAuth(
  119. authaws.WithRegion(regionAWS),
  120. authaws.WithIAMAuth(),
  121. authaws.WithRole(iamAuth.Role),
  122. authaws.WithMountPath(awsAuthMountPath),
  123. authaws.WithIAMServerIDHeader(iamAuth.VaultAWSIAMServerID),
  124. )
  125. if err != nil {
  126. return err
  127. }
  128. } else {
  129. awsAuthClient, err = authaws.NewAWSAuth(authaws.WithRegion(regionAWS), authaws.WithIAMAuth(), authaws.WithRole(iamAuth.Role), authaws.WithMountPath(awsAuthMountPath))
  130. if err != nil {
  131. return err
  132. }
  133. }
  134. _, err = c.auth.Login(ctx, awsAuthClient)
  135. metrics.ObserveAPICall(ProviderHCVault, CallHCVaultLogin, err)
  136. if err != nil {
  137. return err
  138. }
  139. return nil
  140. }
  141. func (c *client) getRegionOrDefault(region string) string {
  142. if region != "" {
  143. return region
  144. }
  145. return defaultAWSRegion
  146. }
  147. func (c *client) getAuthMountPathOrDefault(path string) string {
  148. if path != "" {
  149. return path
  150. }
  151. return defaultAWSAuthMountPath
  152. }
  153. func (c *client) getControllerPodCredentials(ctx context.Context, region string, k kclient.Client, jwtProvider vaultutil.JwtProviderFactory) (aws.CredentialsProvider, error) {
  154. // First try IRSA (Web Identity Token) - checking if controller pod's service account is IRSA enabled
  155. tokenFile := os.Getenv(vaultiamauth.AWSWebIdentityTokenFileEnvVar)
  156. if tokenFile != "" {
  157. logger.V(1).Info("using IRSA token for authentication")
  158. return c.getCredsFromIRSAToken(ctx, tokenFile, region, k, jwtProvider)
  159. }
  160. // Check for Pod Identity environment variables.
  161. podIdentityURI := os.Getenv(vaultiamauth.AWSContainerCredentialsFullURIEnvVar)
  162. if podIdentityURI != "" {
  163. logger.V(1).Info("using Pod Identity for authentication")
  164. // Return nil to let AWS SDK v2 container credential provider handle Pod Identity automatically
  165. return nil, nil
  166. }
  167. // No IRSA or Pod Identity found.
  168. return nil, errors.New(errNoAWSAuthMethodFound)
  169. }
  170. func (c *client) getCredsFromIRSAToken(ctx context.Context, tokenFile, region string, k kclient.Client, jwtProvider vaultutil.JwtProviderFactory) (aws.CredentialsProvider, error) {
  171. // IRSA enabled service account, let's check that the jwt token filemount and file exists
  172. if _, err := os.Stat(filepath.Clean(tokenFile)); err != nil {
  173. return nil, fmt.Errorf(errIrsaTokenFileNotFoundOnPod, tokenFile, err)
  174. }
  175. // everything looks good so far, let's fetch the jwt token from AWS_WEB_IDENTITY_TOKEN_FILE
  176. jwtByte, err := os.ReadFile(filepath.Clean(tokenFile))
  177. if err != nil {
  178. return nil, fmt.Errorf(errIrsaTokenFileNotReadable, tokenFile, err)
  179. }
  180. // Parse the JWT token to extract metadata (namespace and service account).
  181. // Note: Signature verification is intentionally skipped here as we only need to extract
  182. // claims from the IRSA token that comes from a trusted source (AWS-mounted file).
  183. // The token itself will be validated by AWS STS when used for authentication.
  184. parser := jwt.NewParser(jwt.WithoutClaimsValidation())
  185. token, _, err := parser.ParseUnverified(string(jwtByte), jwt.MapClaims{})
  186. if err != nil {
  187. return nil, fmt.Errorf(errIrsaTokenNotValidJWT, tokenFile, err) // JWT token parser error
  188. }
  189. var ns string
  190. var sa string
  191. // let's fetch the namespace and serviceaccount from parsed jwt token
  192. claims, ok := token.Claims.(jwt.MapClaims)
  193. if !ok {
  194. return nil, fmt.Errorf(errIrsaTokenNotValidClaims, tokenFile)
  195. }
  196. k8s, ok := claims["kubernetes.io"].(map[string]any)
  197. if !ok {
  198. return nil, fmt.Errorf(errIrsaTokenNotValidClaims, tokenFile)
  199. }
  200. ns, ok = k8s["namespace"].(string)
  201. if !ok {
  202. return nil, fmt.Errorf(errIrsaTokenNotValidClaims, tokenFile)
  203. }
  204. saMap, ok := k8s["serviceaccount"].(map[string]any)
  205. if !ok {
  206. return nil, fmt.Errorf(errIrsaTokenNotValidClaims, tokenFile)
  207. }
  208. sa, ok = saMap["name"].(string)
  209. if !ok {
  210. return nil, fmt.Errorf(errIrsaTokenNotValidClaims, tokenFile)
  211. }
  212. return vaultiamauth.CredsFromControllerServiceAccount(ctx, sa, ns, region, k, jwtProvider)
  213. }