auth.go 12 KB

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