auth.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. type SessionCache struct {
  40. Name string
  41. Namespace string
  42. Kind string
  43. ResourceVersion string
  44. }
  45. var (
  46. log = ctrl.Log.WithName("provider").WithName("aws")
  47. sessions = make(map[SessionCache]*session.Session)
  48. EnableCache bool
  49. )
  50. const (
  51. roleARNAnnotation = "eks.amazonaws.com/role-arn"
  52. audienceAnnotation = "eks.amazonaws.com/audience"
  53. defaultTokenAudience = "sts.amazonaws.com"
  54. errInvalidClusterStoreMissingAKIDNamespace = "invalid ClusterSecretStore: missing AWS AccessKeyID Namespace"
  55. errInvalidClusterStoreMissingSAKNamespace = "invalid ClusterSecretStore: missing AWS SecretAccessKey Namespace"
  56. errFetchAKIDSecret = "could not fetch accessKeyID secret: %w"
  57. errFetchSAKSecret = "could not fetch SecretAccessKey secret: %w"
  58. errMissingSAK = "missing SecretAccessKey"
  59. errMissingAKID = "missing AccessKeyID"
  60. )
  61. // New creates a new aws session based on the provided store
  62. // it uses the following authentication mechanisms in order:
  63. // * service-account token authentication via AssumeRoleWithWebIdentity
  64. // * static credentials from a Kind=Secret, optionally with doing a AssumeRole.
  65. // * sdk default provider chain, see: https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html#credentials-default
  66. func New(ctx context.Context, store esv1beta1.GenericStore, kube client.Client, namespace string, assumeRoler STSProvider, jwtProvider jwtProviderFactory) (*session.Session, error) {
  67. prov, err := util.GetAWSProvider(store)
  68. if err != nil {
  69. return nil, err
  70. }
  71. var creds *credentials.Credentials
  72. isClusterKind := store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind
  73. // use credentials via service account token
  74. jwtAuth := prov.Auth.JWTAuth
  75. if jwtAuth != nil {
  76. creds, err = sessionFromServiceAccount(ctx, prov.Auth, prov.Region, isClusterKind, kube, namespace, jwtProvider)
  77. if err != nil {
  78. return nil, err
  79. }
  80. }
  81. // use credentials from sercretRef
  82. secretRef := prov.Auth.SecretRef
  83. if secretRef != nil {
  84. log.V(1).Info("using credentials from secretRef")
  85. creds, err = sessionFromSecretRef(ctx, prov.Auth, isClusterKind, kube, namespace)
  86. if err != nil {
  87. return nil, err
  88. }
  89. }
  90. config := aws.NewConfig().WithEndpointResolver(ResolveEndpoint())
  91. if creds != nil {
  92. config.WithCredentials(creds)
  93. }
  94. if prov.Region != "" {
  95. config.WithRegion(prov.Region)
  96. }
  97. sess, err := getAWSSession(config, EnableCache, store.GetName(), store.GetTypeMeta().Kind, namespace, store.GetObjectMeta().ResourceVersion)
  98. if err != nil {
  99. return nil, err
  100. }
  101. if prov.Role != "" {
  102. stsclient := assumeRoler(sess)
  103. sess.Config.WithCredentials(stscreds.NewCredentialsWithClient(stsclient, prov.Role))
  104. }
  105. log.Info("using aws session", "region", *sess.Config.Region, "credentials", creds)
  106. return sess, nil
  107. }
  108. func sessionFromSecretRef(ctx context.Context, auth esv1beta1.AWSAuth, isClusterKind bool, kube client.Client, namespace string) (*credentials.Credentials, error) {
  109. ke := client.ObjectKey{
  110. Name: auth.SecretRef.AccessKeyID.Name,
  111. Namespace: namespace, // default to ExternalSecret namespace
  112. }
  113. // only ClusterStore is allowed to set namespace (and then it's required)
  114. if isClusterKind {
  115. if auth.SecretRef.AccessKeyID.Namespace == nil {
  116. return nil, fmt.Errorf(errInvalidClusterStoreMissingAKIDNamespace)
  117. }
  118. ke.Namespace = *auth.SecretRef.AccessKeyID.Namespace
  119. }
  120. akSecret := v1.Secret{}
  121. err := kube.Get(ctx, ke, &akSecret)
  122. if err != nil {
  123. return nil, fmt.Errorf(errFetchAKIDSecret, err)
  124. }
  125. ke = client.ObjectKey{
  126. Name: auth.SecretRef.SecretAccessKey.Name,
  127. Namespace: namespace, // default to ExternalSecret namespace
  128. }
  129. // only ClusterStore is allowed to set namespace (and then it's required)
  130. if isClusterKind {
  131. if auth.SecretRef.SecretAccessKey.Namespace == nil {
  132. return nil, fmt.Errorf(errInvalidClusterStoreMissingSAKNamespace)
  133. }
  134. ke.Namespace = *auth.SecretRef.SecretAccessKey.Namespace
  135. }
  136. sakSecret := v1.Secret{}
  137. err = kube.Get(ctx, ke, &sakSecret)
  138. if err != nil {
  139. return nil, fmt.Errorf(errFetchSAKSecret, err)
  140. }
  141. sak := string(sakSecret.Data[auth.SecretRef.SecretAccessKey.Key])
  142. aks := string(akSecret.Data[auth.SecretRef.AccessKeyID.Key])
  143. if sak == "" {
  144. return nil, fmt.Errorf(errMissingSAK)
  145. }
  146. if aks == "" {
  147. return nil, fmt.Errorf(errMissingAKID)
  148. }
  149. return credentials.NewStaticCredentials(aks, sak, ""), err
  150. }
  151. func sessionFromServiceAccount(ctx context.Context, auth esv1beta1.AWSAuth, region string, isClusterKind bool, kube client.Client, namespace string, jwtProvider jwtProviderFactory) (*credentials.Credentials, error) {
  152. name := auth.JWTAuth.ServiceAccountRef.Name
  153. if isClusterKind {
  154. namespace = *auth.JWTAuth.ServiceAccountRef.Namespace
  155. }
  156. sa := v1.ServiceAccount{}
  157. err := kube.Get(ctx, types.NamespacedName{
  158. Name: name,
  159. Namespace: namespace,
  160. }, &sa)
  161. if err != nil {
  162. return nil, err
  163. }
  164. // the service account is expected to have a well-known annotation
  165. // this is used as input to assumeRoleWithWebIdentity
  166. roleArn := sa.Annotations[roleARNAnnotation]
  167. if roleArn == "" {
  168. return nil, fmt.Errorf("an IAM role must be associated with service account %s (namespace: %s)", name, namespace)
  169. }
  170. tokenAud := sa.Annotations[audienceAnnotation]
  171. if tokenAud == "" {
  172. tokenAud = defaultTokenAudience
  173. }
  174. audiences := []string{tokenAud}
  175. if len(auth.JWTAuth.ServiceAccountRef.Audiences) > 0 {
  176. audiences = append(audiences, auth.JWTAuth.ServiceAccountRef.Audiences...)
  177. }
  178. jwtProv, err := jwtProvider(name, namespace, roleArn, audiences, region)
  179. if err != nil {
  180. return nil, err
  181. }
  182. log.V(1).Info("using credentials via service account", "role", roleArn, "region", region)
  183. return credentials.NewCredentials(jwtProv), nil
  184. }
  185. type jwtProviderFactory func(name, namespace, roleArn string, aud []string, region string) (credentials.Provider, error)
  186. // DefaultJWTProvider returns a credentials.Provider that calls the AssumeRoleWithWebidentity
  187. // controller-runtime/client does not support TokenRequest or other subresource APIs
  188. // so we need to construct our own client and use it to fetch tokens.
  189. func DefaultJWTProvider(name, namespace, roleArn string, aud []string, region string) (credentials.Provider, error) {
  190. cfg, err := ctrlcfg.GetConfig()
  191. if err != nil {
  192. return nil, err
  193. }
  194. clientset, err := kubernetes.NewForConfig(cfg)
  195. if err != nil {
  196. return nil, err
  197. }
  198. handlers := defaults.Handlers()
  199. handlers.Build.PushBack(request.WithAppendUserAgent("external-secrets"))
  200. awscfg := aws.NewConfig().WithEndpointResolver(ResolveEndpoint())
  201. if region != "" {
  202. awscfg.WithRegion(region)
  203. }
  204. sess, err := session.NewSessionWithOptions(session.Options{
  205. Config: *awscfg,
  206. SharedConfigState: session.SharedConfigDisable,
  207. Handlers: handlers,
  208. })
  209. if err != nil {
  210. return nil, err
  211. }
  212. tokenFetcher := &authTokenFetcher{
  213. Namespace: namespace,
  214. Audiences: aud,
  215. ServiceAccount: name,
  216. k8sClient: clientset.CoreV1(),
  217. }
  218. return stscreds.NewWebIdentityRoleProviderWithOptions(
  219. sts.New(sess), roleArn, "external-secrets-provider-aws", tokenFetcher), nil
  220. }
  221. type STSProvider func(*session.Session) stsiface.STSAPI
  222. func DefaultSTSProvider(sess *session.Session) stsiface.STSAPI {
  223. return sts.New(sess)
  224. }
  225. // getAWSSession check if an AWS session should be reused
  226. // it returns the aws session or an error.
  227. func getAWSSession(config *aws.Config, enableCache bool, name, kind, namespace, resourceVersion string) (*session.Session, error) {
  228. tmpSession := SessionCache{
  229. Name: name,
  230. Namespace: namespace,
  231. Kind: kind,
  232. ResourceVersion: resourceVersion,
  233. }
  234. if enableCache {
  235. sess, ok := sessions[tmpSession]
  236. if ok {
  237. log.Info("reusing aws session", "SecretStore", tmpSession.Name, "namespace", tmpSession.Namespace, "kind", tmpSession.Kind, "resourceversion", tmpSession.ResourceVersion)
  238. return sess, nil
  239. }
  240. }
  241. handlers := defaults.Handlers()
  242. handlers.Build.PushBack(request.WithAppendUserAgent("external-secrets"))
  243. sess, err := session.NewSessionWithOptions(session.Options{
  244. Config: *config,
  245. Handlers: handlers,
  246. SharedConfigState: session.SharedConfigDisable,
  247. })
  248. if err != nil {
  249. return nil, err
  250. }
  251. if enableCache {
  252. sessions[tmpSession] = sess
  253. }
  254. return sess, nil
  255. }