root.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 controller
  14. import (
  15. "crypto/tls"
  16. "fmt"
  17. "os"
  18. "strings"
  19. "time"
  20. "github.com/spf13/cobra"
  21. v1 "k8s.io/api/core/v1"
  22. apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  23. "k8s.io/apimachinery/pkg/runtime"
  24. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  25. clientgoscheme "k8s.io/client-go/kubernetes/scheme"
  26. ctrl "sigs.k8s.io/controller-runtime"
  27. "sigs.k8s.io/controller-runtime/pkg/cache"
  28. "sigs.k8s.io/controller-runtime/pkg/client"
  29. "sigs.k8s.io/controller-runtime/pkg/healthz"
  30. "sigs.k8s.io/controller-runtime/pkg/metrics/filters"
  31. "sigs.k8s.io/controller-runtime/pkg/metrics/server"
  32. "sigs.k8s.io/controller-runtime/pkg/webhook"
  33. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  34. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  35. genv1alpha1 "github.com/external-secrets/external-secrets/apis/generators/v1alpha1"
  36. "github.com/external-secrets/external-secrets/pkg/controllers/clusterexternalsecret"
  37. "github.com/external-secrets/external-secrets/pkg/controllers/clusterexternalsecret/cesmetrics"
  38. "github.com/external-secrets/external-secrets/pkg/controllers/clusterpushsecret"
  39. "github.com/external-secrets/external-secrets/pkg/controllers/clusterpushsecret/cpsmetrics"
  40. ctrlcommon "github.com/external-secrets/external-secrets/pkg/controllers/common"
  41. "github.com/external-secrets/external-secrets/pkg/controllers/externalsecret"
  42. "github.com/external-secrets/external-secrets/pkg/controllers/externalsecret/esmetrics"
  43. "github.com/external-secrets/external-secrets/pkg/controllers/generatorstate"
  44. ctrlmetrics "github.com/external-secrets/external-secrets/pkg/controllers/metrics"
  45. "github.com/external-secrets/external-secrets/pkg/controllers/pushsecret"
  46. "github.com/external-secrets/external-secrets/pkg/controllers/pushsecret/psmetrics"
  47. "github.com/external-secrets/external-secrets/pkg/controllers/secretstore"
  48. "github.com/external-secrets/external-secrets/pkg/controllers/secretstore/cssmetrics"
  49. "github.com/external-secrets/external-secrets/pkg/controllers/secretstore/ssmetrics"
  50. "github.com/external-secrets/external-secrets/runtime/esutils"
  51. "github.com/external-secrets/external-secrets/runtime/feature"
  52. // To allow using gcp auth.
  53. _ "k8s.io/client-go/plugin/pkg/client/auth"
  54. )
  55. var (
  56. scheme = runtime.NewScheme()
  57. setupLog = ctrl.Log.WithName("setup")
  58. dnsName string
  59. certDir string
  60. liveAddr string
  61. metricsAddr string
  62. metricsSecure bool
  63. metricsAuth bool
  64. metricsCertDir string
  65. metricsCertName string
  66. metricsKeyName string
  67. healthzAddr string
  68. controllerClass string
  69. enableLeaderElection bool
  70. leaderElectionID string
  71. leaderElectionLeaseDuration time.Duration
  72. leaderElectionRenewDeadline time.Duration
  73. leaderElectionRetryPeriod time.Duration
  74. enableSecretsCache bool
  75. enableConfigMapsCache bool
  76. enableManagedSecretsCache bool
  77. enableSecretAPIReadOnCacheMismatch bool
  78. enablePartialCache bool
  79. concurrent int
  80. port int
  81. clientQPS float32
  82. clientBurst int
  83. loglevel string
  84. zapTimeEncoding string
  85. namespace string
  86. enableClusterStoreReconciler bool
  87. enableSecretStoreReconciler bool
  88. enableClusterExternalSecretReconciler bool
  89. enableClusterPushSecretReconciler bool
  90. enablePushSecretReconciler bool
  91. enableFloodGate bool
  92. enableGeneratorState bool
  93. enableExtendedMetricLabels bool
  94. storeRequeueInterval time.Duration
  95. serviceName, serviceNamespace string
  96. secretName, secretNamespace string
  97. crdNames []string
  98. crdRequeueInterval time.Duration
  99. certCheckInterval time.Duration
  100. certLookaheadInterval time.Duration
  101. tlsCiphers string
  102. tlsMinVersion string
  103. tlsCurvePreferences []string
  104. enableHTTP2 bool
  105. allowGenericTargets bool
  106. )
  107. const (
  108. errCreateController = "unable to create controller"
  109. )
  110. func init() {
  111. // kubernetes schemes
  112. utilruntime.Must(clientgoscheme.AddToScheme(scheme))
  113. utilruntime.Must(apiextensionsv1.AddToScheme(scheme))
  114. // external-secrets schemes
  115. utilruntime.Must(esv1.AddToScheme(scheme))
  116. utilruntime.Must(esv1alpha1.AddToScheme(scheme))
  117. utilruntime.Must(genv1alpha1.AddToScheme(scheme))
  118. }
  119. var rootCmd = &cobra.Command{
  120. Use: "external-secrets",
  121. Short: "operator that reconciles ExternalSecrets and SecretStores",
  122. Long: `For more information visit https://external-secrets.io`,
  123. Run: func(cmd *cobra.Command, _ []string) {
  124. setupLogger()
  125. ctrlmetrics.SetUpLabelNames(enableExtendedMetricLabels)
  126. esmetrics.SetUpMetrics()
  127. config := ctrl.GetConfigOrDie()
  128. config.QPS = clientQPS
  129. config.Burst = clientBurst
  130. // the client creates a ListWatch for resources that are requested with .Get() or .List()
  131. // some users might want to completely disable caching of Secrets and ConfigMaps
  132. // to decrease memory usage at the expense of high Kubernetes API usage
  133. // see: https://github.com/external-secrets/external-secrets/issues/721
  134. clientCacheDisableFor := make([]client.Object, 0)
  135. if !enableSecretsCache {
  136. // dont cache any secrets
  137. clientCacheDisableFor = append(clientCacheDisableFor, &v1.Secret{})
  138. }
  139. if !enableConfigMapsCache {
  140. // dont cache any configmaps
  141. clientCacheDisableFor = append(clientCacheDisableFor, &v1.ConfigMap{})
  142. }
  143. metricsOpts := server.Options{
  144. BindAddress: metricsAddr,
  145. }
  146. if metricsSecure {
  147. metricsOpts.SecureServing = true
  148. metricsOpts.CertDir = metricsCertDir
  149. metricsOpts.CertName = metricsCertName
  150. metricsOpts.KeyName = metricsKeyName
  151. }
  152. if metricsAuth {
  153. metricsOpts.FilterProvider = filters.WithAuthenticationAndAuthorization
  154. }
  155. if metricsAuth && !metricsSecure {
  156. setupLog.Error(nil, "--metrics-auth requires --metrics-secure; bearer tokens over plaintext HTTP is not allowed")
  157. os.Exit(1)
  158. }
  159. metricsTLSOpts, err := buildTLSConfigFuncs(tlsCiphers, tlsMinVersion, tlsCurvePreferences, enableHTTP2)
  160. if err != nil {
  161. setupLog.Error(err, "unable to configure TLS for metrics server")
  162. os.Exit(1)
  163. }
  164. metricsOpts.TLSOpts = metricsTLSOpts
  165. mgrOpts := ctrl.Options{
  166. Scheme: scheme,
  167. Metrics: metricsOpts,
  168. HealthProbeBindAddress: liveAddr,
  169. WebhookServer: webhook.NewServer(webhook.Options{
  170. Port: 9443,
  171. }),
  172. Client: client.Options{
  173. Cache: &client.CacheOptions{
  174. DisableFor: clientCacheDisableFor,
  175. },
  176. },
  177. LeaderElection: enableLeaderElection,
  178. LeaderElectionID: leaderElectionID,
  179. LeaseDuration: &leaderElectionLeaseDuration,
  180. RenewDeadline: &leaderElectionRenewDeadline,
  181. RetryPeriod: &leaderElectionRetryPeriod,
  182. }
  183. if namespace != "" {
  184. mgrOpts.Cache.DefaultNamespaces = map[string]cache.Config{
  185. namespace: {},
  186. }
  187. }
  188. mgr, err := ctrl.NewManager(config, mgrOpts)
  189. if err != nil {
  190. setupLog.Error(err, "unable to start manager")
  191. os.Exit(1)
  192. }
  193. // we create a special client for accessing secrets in the ExternalSecret reconcile loop.
  194. // by default, it is the same as the normal client, but if `--enable-managed-secrets-caching`
  195. // is set, we use a special client that only caches secrets managed by an ExternalSecret.
  196. // if we are already caching all secrets, we don't need to use the special client.
  197. secretClient := mgr.GetClient()
  198. if enableManagedSecretsCache && !enableSecretsCache {
  199. secretClient, err = ctrlcommon.BuildManagedSecretClient(mgr, namespace)
  200. if err != nil {
  201. setupLog.Error(err, "unable to create managed secret client")
  202. os.Exit(1)
  203. }
  204. }
  205. if enableSecretStoreReconciler {
  206. ssmetrics.SetUpMetrics()
  207. if err = (&secretstore.StoreReconciler{
  208. Client: mgr.GetClient(),
  209. Log: ctrl.Log.WithName("controllers").WithName("SecretStore"),
  210. Scheme: mgr.GetScheme(),
  211. ControllerClass: controllerClass,
  212. RequeueInterval: storeRequeueInterval,
  213. PushSecretEnabled: enablePushSecretReconciler,
  214. }).SetupWithManager(mgr, ctrlcommon.BuildControllerOptions(concurrent)); err != nil {
  215. setupLog.Error(err, errCreateController, "controller", "SecretStore")
  216. os.Exit(1)
  217. }
  218. }
  219. if enableClusterStoreReconciler {
  220. cssmetrics.SetUpMetrics()
  221. if err = (&secretstore.ClusterStoreReconciler{
  222. Client: mgr.GetClient(),
  223. Log: ctrl.Log.WithName("controllers").WithName("ClusterSecretStore"),
  224. Scheme: mgr.GetScheme(),
  225. ControllerClass: controllerClass,
  226. RequeueInterval: storeRequeueInterval,
  227. PushSecretEnabled: enablePushSecretReconciler,
  228. }).SetupWithManager(mgr, ctrlcommon.BuildControllerOptions(concurrent)); err != nil {
  229. setupLog.Error(err, errCreateController, "controller", "ClusterSecretStore")
  230. os.Exit(1)
  231. }
  232. }
  233. if err = (&generatorstate.Reconciler{
  234. Client: mgr.GetClient(),
  235. Log: ctrl.Log.WithName("controllers").WithName("GeneratorState"),
  236. Scheme: mgr.GetScheme(),
  237. RestConfig: mgr.GetConfig(),
  238. }).SetupWithManager(mgr, ctrlcommon.BuildControllerOptions(concurrent)); err != nil {
  239. setupLog.Error(err, errCreateController, "controller", "GeneratorState")
  240. os.Exit(1)
  241. }
  242. if err = (&externalsecret.Reconciler{
  243. Client: mgr.GetClient(),
  244. SecretClient: secretClient,
  245. EnableSecretAPIReadOnCacheMismatch: enableSecretAPIReadOnCacheMismatch,
  246. Log: ctrl.Log.WithName("controllers").WithName("ExternalSecret"),
  247. Scheme: mgr.GetScheme(),
  248. RestConfig: mgr.GetConfig(),
  249. ControllerClass: controllerClass,
  250. RequeueInterval: time.Hour,
  251. ClusterSecretStoreEnabled: enableClusterStoreReconciler,
  252. EnableFloodGate: enableFloodGate,
  253. EnableGeneratorState: enableGeneratorState,
  254. AllowGenericTargets: allowGenericTargets,
  255. }).SetupWithManager(cmd.Context(), mgr, ctrlcommon.BuildControllerOptions(concurrent)); err != nil {
  256. setupLog.Error(err, errCreateController, "controller", "ExternalSecret")
  257. os.Exit(1)
  258. }
  259. if enablePushSecretReconciler {
  260. psmetrics.SetUpMetrics()
  261. if err = (&pushsecret.Reconciler{
  262. Client: mgr.GetClient(),
  263. Log: ctrl.Log.WithName("controllers").WithName("PushSecret"),
  264. Scheme: mgr.GetScheme(),
  265. ControllerClass: controllerClass,
  266. RestConfig: mgr.GetConfig(),
  267. RequeueInterval: time.Hour,
  268. }).SetupWithManager(cmd.Context(), mgr, ctrlcommon.BuildControllerOptions(concurrent)); err != nil {
  269. setupLog.Error(err, errCreateController, "controller", "PushSecret")
  270. os.Exit(1)
  271. }
  272. }
  273. if enableClusterExternalSecretReconciler {
  274. cesmetrics.SetUpMetrics()
  275. if err = (&clusterexternalsecret.Reconciler{
  276. Client: mgr.GetClient(),
  277. Log: ctrl.Log.WithName("controllers").WithName("ClusterExternalSecret"),
  278. Scheme: mgr.GetScheme(),
  279. RequeueInterval: time.Hour,
  280. }).SetupWithManager(mgr, ctrlcommon.BuildControllerOptions(concurrent)); err != nil {
  281. setupLog.Error(err, errCreateController, "controller", "ClusterExternalSecret")
  282. os.Exit(1)
  283. }
  284. }
  285. if enableClusterPushSecretReconciler {
  286. cpsmetrics.SetUpMetrics()
  287. if err = (&clusterpushsecret.Reconciler{
  288. Client: mgr.GetClient(),
  289. Log: ctrl.Log.WithName("controllers").WithName("ClusterPushSecret"),
  290. Scheme: mgr.GetScheme(),
  291. RequeueInterval: time.Hour,
  292. Recorder: mgr.GetEventRecorderFor("external-secrets-controller"),
  293. }).SetupWithManager(mgr, ctrlcommon.BuildControllerOptions(concurrent)); err != nil {
  294. setupLog.Error(err, errCreateController, "controller", "ClusterPushSecret")
  295. os.Exit(1)
  296. }
  297. }
  298. if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
  299. setupLog.Error(err, "unable to add controller healthz check")
  300. os.Exit(1)
  301. }
  302. if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
  303. setupLog.Error(err, "unable to add controller readyz check")
  304. os.Exit(1)
  305. }
  306. fs := feature.Features()
  307. for _, f := range fs {
  308. if f.Initialize == nil {
  309. continue
  310. }
  311. f.Initialize()
  312. }
  313. setupLog.Info("starting manager")
  314. if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
  315. setupLog.Error(err, "problem running manager")
  316. os.Exit(1)
  317. }
  318. },
  319. }
  320. // Execute starts the command execution process.
  321. func Execute() {
  322. cobra.CheckErr(rootCmd.Execute())
  323. }
  324. func init() {
  325. rootCmd.Flags().StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
  326. rootCmd.Flags().BoolVar(&metricsAuth, "metrics-auth", false, "Enable Kubernetes RBAC-based authentication and authorization for the metrics endpoint.")
  327. rootCmd.Flags().BoolVar(&metricsSecure, "metrics-secure", false, "Enable HTTPS for the metrics endpoint.")
  328. rootCmd.Flags().StringVar(&metricsCertDir, "metrics-cert-dir", "", "Directory containing TLS certificate and key for metrics endpoint.")
  329. rootCmd.Flags().StringVar(&metricsCertName, "metrics-cert-name", "tls.crt", "TLS certificate filename for metrics endpoint.")
  330. rootCmd.Flags().StringVar(&metricsKeyName, "metrics-key-name", "tls.key", "TLS key filename for metrics endpoint.")
  331. rootCmd.Flags().StringVar(&controllerClass, "controller-class", "default", "The controller is instantiated with a specific controller name and filters ES based on this property")
  332. rootCmd.Flags().BoolVar(&enableLeaderElection, "enable-leader-election", false,
  333. "Enable leader election for controller manager. "+
  334. "Enabling this will ensure there is only one active controller manager.")
  335. rootCmd.Flags().StringVar(&leaderElectionID, "leader-election-id", "external-secrets-controller",
  336. "The ID of the lease object used for leader election. Set this to a unique value when running multiple deployments in the same namespace.")
  337. rootCmd.Flags().DurationVar(&leaderElectionLeaseDuration, "leader-election-lease-duration", 15*time.Second,
  338. "The duration that non-leader candidates will wait to force acquire leadership. This is measured against time of last observed ack.")
  339. rootCmd.Flags().DurationVar(&leaderElectionRenewDeadline, "leader-election-renew-deadline", 10*time.Second,
  340. "The interval between attempts by the acting leader to renew its leadership before it stops leading. This must be less than the lease duration.")
  341. rootCmd.Flags().DurationVar(&leaderElectionRetryPeriod, "leader-election-retry-period", 2*time.Second,
  342. "The duration the clients should wait between attempting acquisition and renewal of a leadership.")
  343. rootCmd.Flags().IntVar(&concurrent, "concurrent", 1, "The number of concurrent reconciles.")
  344. rootCmd.Flags().Float32Var(&clientQPS, "client-qps", 50, "QPS configuration to be passed to rest.Client")
  345. rootCmd.Flags().IntVar(&clientBurst, "client-burst", 100, "Maximum Burst allowed to be passed to rest.Client")
  346. rootCmd.Flags().StringVar(&liveAddr, "live-addr", ":8082", "The address the live endpoint binds to.")
  347. rootCmd.Flags().StringVar(&loglevel, "loglevel", "info", "loglevel to use, one of: debug, info, warn, error, dpanic, panic, fatal")
  348. rootCmd.Flags().StringVar(&zapTimeEncoding, "zap-time-encoding", "epoch", "Zap time encoding (one of 'epoch', 'millis', 'nano', 'iso8601', 'rfc3339' or 'rfc3339nano')")
  349. rootCmd.Flags().
  350. StringVar(&namespace, "namespace", "", "watch external secrets scoped in the provided namespace only. ClusterSecretStore can be used but only work if it doesn't reference resources from other namespaces")
  351. rootCmd.Flags().BoolVar(&enableClusterStoreReconciler, "enable-cluster-store-reconciler", true, "Enable cluster store reconciler.")
  352. rootCmd.Flags().BoolVar(&enableSecretStoreReconciler, "enable-secret-store-reconciler", true, "Enable secret store reconciler.")
  353. rootCmd.Flags().BoolVar(&enableClusterExternalSecretReconciler, "enable-cluster-external-secret-reconciler", true, "Enable cluster external secret reconciler.")
  354. rootCmd.Flags().BoolVar(&enableClusterPushSecretReconciler, "enable-cluster-push-secret-reconciler", true, "Enable cluster push secret reconciler.")
  355. rootCmd.Flags().BoolVar(&enablePushSecretReconciler, "enable-push-secret-reconciler", true, "Enable push secret reconciler.")
  356. rootCmd.Flags().BoolVar(&enableSecretsCache, "enable-secrets-caching", false, "Enable secrets caching for ALL secrets in the cluster (WARNING: can increase memory usage).")
  357. rootCmd.Flags().BoolVar(&enableConfigMapsCache, "enable-configmaps-caching", false, "Enable configmaps caching for ALL configmaps in the cluster (WARNING: can increase memory usage).")
  358. rootCmd.Flags().BoolVar(&enableManagedSecretsCache, "enable-managed-secrets-caching", true, "Enable secrets caching for secrets managed by an ExternalSecret")
  359. rootCmd.Flags().BoolVar(
  360. &enableSecretAPIReadOnCacheMismatch,
  361. "enable-secret-api-read-on-cache-mismatch",
  362. true,
  363. "Enable a direct API read when the partial Secret cache and managed Secret cache disagree. Disable to rely on cache retry only.",
  364. )
  365. rootCmd.Flags().DurationVar(&storeRequeueInterval, "store-requeue-interval", time.Minute*5, "Default Time duration between reconciling (Cluster)SecretStores")
  366. rootCmd.Flags().BoolVar(&enableFloodGate, "enable-flood-gate", true, "Enable flood gate. External secret will be reconciled only if the ClusterStore or Store have an healthy or unknown state.")
  367. rootCmd.Flags().BoolVar(&enableGeneratorState, "enable-generator-state", true, "Whether the Controller should manage GeneratorState")
  368. rootCmd.Flags().BoolVar(&enableExtendedMetricLabels, "enable-extended-metric-labels", false, "Enable recommended kubernetes annotations as labels in metrics.")
  369. rootCmd.Flags().StringVar(&tlsCiphers, "tls-ciphers", "", "comma separated list of tls ciphers allowed for the metrics server. "+
  370. "This does not apply to TLS 1.3 as the ciphers are selected automatically. "+
  371. "Full lists of available ciphers can be found at https://pkg.go.dev/crypto/tls#pkg-constants")
  372. rootCmd.Flags().StringVar(&tlsMinVersion, "tls-min-version", "", "minimum version of TLS supported for the metrics server. "+
  373. "If not specified, Go's default minimum version is used. Valid values: 1.0, 1.1, 1.2, 1.3")
  374. rootCmd.Flags().StringSliceVar(&tlsCurvePreferences, "tls-curve-preferences", nil,
  375. "ordered list of TLS key exchange curves for the metrics server "+
  376. "(for example X25519,CurveP256, or decimal tls.CurveID values supported by this Go toolchain). "+
  377. "If omitted, Go defaults are used.")
  378. rootCmd.Flags().BoolVar(&enableHTTP2, "enable-http2", false,
  379. "If set, HTTP/2 will be enabled for the metrics server")
  380. rootCmd.Flags().
  381. BoolVar(&allowGenericTargets, "unsafe-allow-generic-targets", false, "Enable support for creating generic resources (ConfigMaps, Custom Resources). WARNING: Using generic resources, please sure all policies are correctly configured.")
  382. fs := feature.Features()
  383. for _, f := range fs {
  384. rootCmd.Flags().AddFlagSet(f.Flags)
  385. }
  386. }
  387. // disableHTTP2 is a TLS configuration function that disables HTTP/2.
  388. func disableHTTP2(cfg *tls.Config) {
  389. cfg.NextProtos = []string{"http/1.1"}
  390. }
  391. // parseTLSCurvePreferences converts human-readable curve names to tls.CurveID values.
  392. // It accepts well-known names (X25519, CurveP256, CurveP384, CurveP521 and aliases)
  393. // as well as decimal tls.CurveID values for forward-compat with new Go toolchains.
  394. func parseTLSCurvePreferences(names []string) ([]tls.CurveID, error) {
  395. filtered := make([]string, 0, len(names))
  396. for _, n := range names {
  397. n = strings.TrimSpace(n)
  398. if n == "" {
  399. continue
  400. }
  401. filtered = append(filtered, n)
  402. }
  403. if len(filtered) == 0 {
  404. return nil, nil
  405. }
  406. return esutils.ParseCurvePreferences(filtered)
  407. }
  408. // buildTLSConfigFuncs assembles a slice of tls.Config mutators from the current
  409. // flag values. It is shared across all subcommands (controller, webhook, certcontroller).
  410. func buildTLSConfigFuncs(ciphers, minVer string, curves []string, http2 bool) ([]func(*tls.Config), error) {
  411. var opts []func(*tls.Config)
  412. if !http2 {
  413. opts = append(opts, disableHTTP2)
  414. }
  415. if ciphers != "" {
  416. ids, err := getTLSCipherSuitesIDs(ciphers)
  417. if err != nil {
  418. return nil, fmt.Errorf("unable to parse tls ciphers: %w", err)
  419. }
  420. if len(ids) > 0 {
  421. opts = append(opts, func(cfg *tls.Config) {
  422. cfg.CipherSuites = ids
  423. })
  424. }
  425. }
  426. if minVer != "" {
  427. ver, err := tlsVersion(minVer)
  428. if err != nil {
  429. return nil, fmt.Errorf("unable to parse tls min version: %w", err)
  430. }
  431. opts = append(opts, func(cfg *tls.Config) {
  432. cfg.MinVersion = ver
  433. })
  434. }
  435. if len(curves) > 0 {
  436. curveIDs, err := parseTLSCurvePreferences(curves)
  437. if err != nil {
  438. return nil, fmt.Errorf("unable to parse tls curve preferences: %w", err)
  439. }
  440. if len(curveIDs) > 0 {
  441. opts = append(opts, func(cfg *tls.Config) {
  442. cfg.CurvePreferences = curveIDs
  443. })
  444. }
  445. }
  446. return opts, nil
  447. }