auth.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 auth
  13. import (
  14. "context"
  15. "fmt"
  16. "github.com/aws/aws-sdk-go/aws"
  17. "github.com/aws/aws-sdk-go/aws/credentials"
  18. "github.com/aws/aws-sdk-go/aws/credentials/stscreds"
  19. "github.com/aws/aws-sdk-go/aws/defaults"
  20. "github.com/aws/aws-sdk-go/aws/request"
  21. "github.com/aws/aws-sdk-go/aws/session"
  22. "github.com/aws/aws-sdk-go/service/sts"
  23. "github.com/aws/aws-sdk-go/service/sts/stsiface"
  24. v1 "k8s.io/api/core/v1"
  25. "k8s.io/apimachinery/pkg/types"
  26. "k8s.io/client-go/kubernetes"
  27. ctrl "sigs.k8s.io/controller-runtime"
  28. "sigs.k8s.io/controller-runtime/pkg/client"
  29. ctrlcfg "sigs.k8s.io/controller-runtime/pkg/client/config"
  30. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  31. "github.com/external-secrets/external-secrets/pkg/provider/aws/util"
  32. )
  33. // Config contains configuration to create a new AWS provider.
  34. type Config struct {
  35. AssumeRole string
  36. Region string
  37. APIRetries int
  38. }
  39. var log = ctrl.Log.WithName("provider").WithName("aws")
  40. const (
  41. roleARNAnnotation = "eks.amazonaws.com/role-arn"
  42. audienceAnnotation = "eks.amazonaws.com/audience"
  43. defaultTokenAudience = "sts.amazonaws.com"
  44. errInvalidClusterStoreMissingAKIDNamespace = "invalid ClusterSecretStore: missing AWS AccessKeyID Namespace"
  45. errInvalidClusterStoreMissingSAKNamespace = "invalid ClusterSecretStore: missing AWS SecretAccessKey Namespace"
  46. errFetchAKIDSecret = "could not fetch accessKeyID secret: %w"
  47. errFetchSAKSecret = "could not fetch SecretAccessKey secret: %w"
  48. errMissingSAK = "missing SecretAccessKey"
  49. errMissingAKID = "missing AccessKeyID"
  50. )
  51. // New creates a new aws session based on the provided store
  52. // it uses the following authentication mechanisms in order:
  53. // * service-account token authentication via AssumeRoleWithWebIdentity
  54. // * static credentials from a Kind=Secret, optionally with doing a AssumeRole.
  55. // * sdk default provider chain, see: https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html#credentials-default
  56. func New(ctx context.Context, store esv1beta1.GenericStore, kube client.Client, namespace string, assumeRoler STSProvider, jwtProvider jwtProviderFactory) (*session.Session, error) {
  57. prov, err := util.GetAWSProvider(store)
  58. if err != nil {
  59. return nil, err
  60. }
  61. var creds *credentials.Credentials
  62. // use credentials via service account token
  63. jwtAuth := prov.Auth.JWTAuth
  64. if jwtAuth != nil {
  65. creds, err = sessionFromServiceAccount(ctx, prov, store, kube, namespace, jwtProvider)
  66. if err != nil {
  67. return nil, err
  68. }
  69. }
  70. // use credentials from sercretRef
  71. secretRef := prov.Auth.SecretRef
  72. if secretRef != nil {
  73. log.V(1).Info("using credentials from secretRef")
  74. creds, err = sessionFromSecretRef(ctx, prov, store, kube, namespace)
  75. if err != nil {
  76. return nil, err
  77. }
  78. }
  79. config := aws.NewConfig().WithEndpointResolver(ResolveEndpoint())
  80. if creds != nil {
  81. config.WithCredentials(creds)
  82. }
  83. if prov.Region != "" {
  84. config.WithRegion(prov.Region)
  85. }
  86. handlers := defaults.Handlers()
  87. handlers.Build.PushBack(request.WithAppendUserAgent("external-secrets"))
  88. sess, err := session.NewSessionWithOptions(session.Options{
  89. Config: *config,
  90. Handlers: handlers,
  91. SharedConfigState: session.SharedConfigDisable,
  92. })
  93. if err != nil {
  94. return nil, err
  95. }
  96. if prov.Role != "" {
  97. stsclient := assumeRoler(sess)
  98. sess.Config.WithCredentials(stscreds.NewCredentialsWithClient(stsclient, prov.Role))
  99. }
  100. log.Info("using aws session", "region", *sess.Config.Region, "credentials", creds)
  101. return sess, nil
  102. }
  103. func sessionFromSecretRef(ctx context.Context, prov *esv1beta1.AWSProvider, store esv1beta1.GenericStore, kube client.Client, namespace string) (*credentials.Credentials, error) {
  104. ke := client.ObjectKey{
  105. Name: prov.Auth.SecretRef.AccessKeyID.Name,
  106. Namespace: namespace, // default to ExternalSecret namespace
  107. }
  108. // only ClusterStore is allowed to set namespace (and then it's required)
  109. if store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind {
  110. if prov.Auth.SecretRef.AccessKeyID.Namespace == nil {
  111. return nil, fmt.Errorf(errInvalidClusterStoreMissingAKIDNamespace)
  112. }
  113. ke.Namespace = *prov.Auth.SecretRef.AccessKeyID.Namespace
  114. }
  115. akSecret := v1.Secret{}
  116. err := kube.Get(ctx, ke, &akSecret)
  117. if err != nil {
  118. return nil, fmt.Errorf(errFetchAKIDSecret, err)
  119. }
  120. ke = client.ObjectKey{
  121. Name: prov.Auth.SecretRef.SecretAccessKey.Name,
  122. Namespace: namespace, // default to ExternalSecret namespace
  123. }
  124. // only ClusterStore is allowed to set namespace (and then it's required)
  125. if store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind {
  126. if prov.Auth.SecretRef.SecretAccessKey.Namespace == nil {
  127. return nil, fmt.Errorf(errInvalidClusterStoreMissingSAKNamespace)
  128. }
  129. ke.Namespace = *prov.Auth.SecretRef.SecretAccessKey.Namespace
  130. }
  131. sakSecret := v1.Secret{}
  132. err = kube.Get(ctx, ke, &sakSecret)
  133. if err != nil {
  134. return nil, fmt.Errorf(errFetchSAKSecret, err)
  135. }
  136. sak := string(sakSecret.Data[prov.Auth.SecretRef.SecretAccessKey.Key])
  137. aks := string(akSecret.Data[prov.Auth.SecretRef.AccessKeyID.Key])
  138. if sak == "" {
  139. return nil, fmt.Errorf(errMissingSAK)
  140. }
  141. if aks == "" {
  142. return nil, fmt.Errorf(errMissingAKID)
  143. }
  144. return credentials.NewStaticCredentials(aks, sak, ""), err
  145. }
  146. func sessionFromServiceAccount(ctx context.Context, prov *esv1beta1.AWSProvider, store esv1beta1.GenericStore, kube client.Client, namespace string, jwtProvider jwtProviderFactory) (*credentials.Credentials, error) {
  147. if store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind {
  148. if prov.Auth.JWTAuth.ServiceAccountRef.Namespace == nil {
  149. return nil, fmt.Errorf("serviceAccountRef has no Namespace field (mandatory for ClusterSecretStore specs)")
  150. }
  151. namespace = *prov.Auth.JWTAuth.ServiceAccountRef.Namespace
  152. }
  153. name := prov.Auth.JWTAuth.ServiceAccountRef.Name
  154. sa := v1.ServiceAccount{}
  155. err := kube.Get(ctx, types.NamespacedName{
  156. Name: name,
  157. Namespace: namespace,
  158. }, &sa)
  159. if err != nil {
  160. return nil, err
  161. }
  162. // the service account is expected to have a well-known annotation
  163. // this is used as input to assumeRoleWithWebIdentity
  164. roleArn := sa.Annotations[roleARNAnnotation]
  165. if roleArn == "" {
  166. return nil, fmt.Errorf("an IAM role must be associated with service account %s (namespace: %s)", name, namespace)
  167. }
  168. tokenAud := sa.Annotations[audienceAnnotation]
  169. if tokenAud == "" {
  170. tokenAud = defaultTokenAudience
  171. }
  172. jwtProv, err := jwtProvider(name, namespace, roleArn, tokenAud, prov.Region)
  173. if err != nil {
  174. return nil, err
  175. }
  176. log.V(1).Info("using credentials via service account", "role", roleArn, "region", prov.Region)
  177. return credentials.NewCredentials(jwtProv), nil
  178. }
  179. type jwtProviderFactory func(name, namespace, roleArn, aud, region string) (credentials.Provider, error)
  180. // DefaultJWTProvider returns a credentials.Provider that calls the AssumeRoleWithWebidentity
  181. // controller-runtime/client does not support TokenRequest or other subresource APIs
  182. // so we need to construct our own client and use it to fetch tokens.
  183. func DefaultJWTProvider(name, namespace, roleArn, aud, region string) (credentials.Provider, error) {
  184. cfg, err := ctrlcfg.GetConfig()
  185. if err != nil {
  186. return nil, err
  187. }
  188. clientset, err := kubernetes.NewForConfig(cfg)
  189. if err != nil {
  190. return nil, err
  191. }
  192. handlers := defaults.Handlers()
  193. handlers.Build.PushBack(request.WithAppendUserAgent("external-secrets"))
  194. awscfg := aws.NewConfig().WithEndpointResolver(ResolveEndpoint())
  195. if region != "" {
  196. awscfg.WithRegion(region)
  197. }
  198. sess, err := session.NewSessionWithOptions(session.Options{
  199. Config: *awscfg,
  200. SharedConfigState: session.SharedConfigDisable,
  201. Handlers: handlers,
  202. })
  203. if err != nil {
  204. return nil, err
  205. }
  206. tokenFetcher := &authTokenFetcher{
  207. Namespace: namespace,
  208. Audience: aud,
  209. ServiceAccount: name,
  210. k8sClient: clientset.CoreV1(),
  211. }
  212. return stscreds.NewWebIdentityRoleProviderWithOptions(
  213. sts.New(sess), roleArn, "external-secrets-provider-aws", tokenFetcher), nil
  214. }
  215. type STSProvider func(*session.Session) stsiface.STSAPI
  216. func DefaultSTSProvider(sess *session.Session) stsiface.STSAPI {
  217. return sts.New(sess)
  218. }