auth.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. // use credentials via service account token
  73. jwtAuth := prov.Auth.JWTAuth
  74. if jwtAuth != nil {
  75. creds, err = sessionFromServiceAccount(ctx, prov, store, kube, namespace, jwtProvider)
  76. if err != nil {
  77. return nil, err
  78. }
  79. }
  80. // use credentials from sercretRef
  81. secretRef := prov.Auth.SecretRef
  82. if secretRef != nil {
  83. log.V(1).Info("using credentials from secretRef")
  84. creds, err = sessionFromSecretRef(ctx, prov, store, kube, namespace)
  85. if err != nil {
  86. return nil, err
  87. }
  88. }
  89. config := aws.NewConfig().WithEndpointResolver(ResolveEndpoint())
  90. if creds != nil {
  91. config.WithCredentials(creds)
  92. }
  93. if prov.Region != "" {
  94. config.WithRegion(prov.Region)
  95. }
  96. sess, err := getAWSSession(config, store, namespace)
  97. if err != nil {
  98. return nil, err
  99. }
  100. if prov.Role != "" {
  101. stsclient := assumeRoler(sess)
  102. sess.Config.WithCredentials(stscreds.NewCredentialsWithClient(stsclient, prov.Role))
  103. }
  104. log.Info("using aws session", "region", *sess.Config.Region, "credentials", creds)
  105. return sess, nil
  106. }
  107. func sessionFromSecretRef(ctx context.Context, prov *esv1beta1.AWSProvider, store esv1beta1.GenericStore, kube client.Client, namespace string) (*credentials.Credentials, error) {
  108. ke := client.ObjectKey{
  109. Name: prov.Auth.SecretRef.AccessKeyID.Name,
  110. Namespace: namespace, // default to ExternalSecret namespace
  111. }
  112. // only ClusterStore is allowed to set namespace (and then it's required)
  113. if store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind {
  114. if prov.Auth.SecretRef.AccessKeyID.Namespace == nil {
  115. return nil, fmt.Errorf(errInvalidClusterStoreMissingAKIDNamespace)
  116. }
  117. ke.Namespace = *prov.Auth.SecretRef.AccessKeyID.Namespace
  118. }
  119. akSecret := v1.Secret{}
  120. err := kube.Get(ctx, ke, &akSecret)
  121. if err != nil {
  122. return nil, fmt.Errorf(errFetchAKIDSecret, err)
  123. }
  124. ke = client.ObjectKey{
  125. Name: prov.Auth.SecretRef.SecretAccessKey.Name,
  126. Namespace: namespace, // default to ExternalSecret namespace
  127. }
  128. // only ClusterStore is allowed to set namespace (and then it's required)
  129. if store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind {
  130. if prov.Auth.SecretRef.SecretAccessKey.Namespace == nil {
  131. return nil, fmt.Errorf(errInvalidClusterStoreMissingSAKNamespace)
  132. }
  133. ke.Namespace = *prov.Auth.SecretRef.SecretAccessKey.Namespace
  134. }
  135. sakSecret := v1.Secret{}
  136. err = kube.Get(ctx, ke, &sakSecret)
  137. if err != nil {
  138. return nil, fmt.Errorf(errFetchSAKSecret, err)
  139. }
  140. sak := string(sakSecret.Data[prov.Auth.SecretRef.SecretAccessKey.Key])
  141. aks := string(akSecret.Data[prov.Auth.SecretRef.AccessKeyID.Key])
  142. if sak == "" {
  143. return nil, fmt.Errorf(errMissingSAK)
  144. }
  145. if aks == "" {
  146. return nil, fmt.Errorf(errMissingAKID)
  147. }
  148. return credentials.NewStaticCredentials(aks, sak, ""), err
  149. }
  150. func sessionFromServiceAccount(ctx context.Context, prov *esv1beta1.AWSProvider, store esv1beta1.GenericStore, kube client.Client, namespace string, jwtProvider jwtProviderFactory) (*credentials.Credentials, error) {
  151. if store.GetObjectKind().GroupVersionKind().Kind == esv1beta1.ClusterSecretStoreKind {
  152. if prov.Auth.JWTAuth.ServiceAccountRef.Namespace == nil {
  153. return nil, fmt.Errorf("serviceAccountRef has no Namespace field (mandatory for ClusterSecretStore specs)")
  154. }
  155. namespace = *prov.Auth.JWTAuth.ServiceAccountRef.Namespace
  156. }
  157. name := prov.Auth.JWTAuth.ServiceAccountRef.Name
  158. sa := v1.ServiceAccount{}
  159. err := kube.Get(ctx, types.NamespacedName{
  160. Name: name,
  161. Namespace: namespace,
  162. }, &sa)
  163. if err != nil {
  164. return nil, err
  165. }
  166. // the service account is expected to have a well-known annotation
  167. // this is used as input to assumeRoleWithWebIdentity
  168. roleArn := sa.Annotations[roleARNAnnotation]
  169. if roleArn == "" {
  170. return nil, fmt.Errorf("an IAM role must be associated with service account %s (namespace: %s)", name, namespace)
  171. }
  172. tokenAud := sa.Annotations[audienceAnnotation]
  173. if tokenAud == "" {
  174. tokenAud = defaultTokenAudience
  175. }
  176. jwtProv, err := jwtProvider(name, namespace, roleArn, tokenAud, prov.Region)
  177. if err != nil {
  178. return nil, err
  179. }
  180. log.V(1).Info("using credentials via service account", "role", roleArn, "region", prov.Region)
  181. return credentials.NewCredentials(jwtProv), nil
  182. }
  183. type jwtProviderFactory func(name, namespace, roleArn, aud, region string) (credentials.Provider, error)
  184. // DefaultJWTProvider returns a credentials.Provider that calls the AssumeRoleWithWebidentity
  185. // controller-runtime/client does not support TokenRequest or other subresource APIs
  186. // so we need to construct our own client and use it to fetch tokens.
  187. func DefaultJWTProvider(name, namespace, roleArn, aud, region string) (credentials.Provider, error) {
  188. cfg, err := ctrlcfg.GetConfig()
  189. if err != nil {
  190. return nil, err
  191. }
  192. clientset, err := kubernetes.NewForConfig(cfg)
  193. if err != nil {
  194. return nil, err
  195. }
  196. handlers := defaults.Handlers()
  197. handlers.Build.PushBack(request.WithAppendUserAgent("external-secrets"))
  198. awscfg := aws.NewConfig().WithEndpointResolver(ResolveEndpoint())
  199. if region != "" {
  200. awscfg.WithRegion(region)
  201. }
  202. sess, err := session.NewSessionWithOptions(session.Options{
  203. Config: *awscfg,
  204. SharedConfigState: session.SharedConfigDisable,
  205. Handlers: handlers,
  206. })
  207. if err != nil {
  208. return nil, err
  209. }
  210. tokenFetcher := &authTokenFetcher{
  211. Namespace: namespace,
  212. Audience: aud,
  213. ServiceAccount: name,
  214. k8sClient: clientset.CoreV1(),
  215. }
  216. return stscreds.NewWebIdentityRoleProviderWithOptions(
  217. sts.New(sess), roleArn, "external-secrets-provider-aws", tokenFetcher), nil
  218. }
  219. type STSProvider func(*session.Session) stsiface.STSAPI
  220. func DefaultSTSProvider(sess *session.Session) stsiface.STSAPI {
  221. return sts.New(sess)
  222. }
  223. // getAWSSession check if an AWS session should be reused
  224. // it returns the aws session or an error.
  225. func getAWSSession(config *aws.Config, store esv1beta1.GenericStore, namespace string) (*session.Session, error) {
  226. tmpSession := SessionCache{
  227. Name: store.GetObjectMeta().Name,
  228. Namespace: namespace,
  229. Kind: store.GetTypeMeta().Kind,
  230. ResourceVersion: store.GetObjectMeta().ResourceVersion,
  231. }
  232. if EnableCache {
  233. sess, ok := sessions[tmpSession]
  234. if ok {
  235. log.Info("reusing aws session", "SecretStore", tmpSession.Name, "namespace", tmpSession.Namespace, "kind", tmpSession.Kind, "resourceversion", tmpSession.ResourceVersion)
  236. return sess, nil
  237. }
  238. }
  239. handlers := defaults.Handlers()
  240. handlers.Build.PushBack(request.WithAppendUserAgent("external-secrets"))
  241. sess, err := session.NewSessionWithOptions(session.Options{
  242. Config: *config,
  243. Handlers: handlers,
  244. SharedConfigState: session.SharedConfigDisable,
  245. })
  246. if err != nil {
  247. return nil, err
  248. }
  249. if EnableCache {
  250. sessions[tmpSession] = sess
  251. }
  252. return sess, nil
  253. }