Repository: VictoriaMetrics/VictoriaMetrics
Pull request #1614 (2021-09-13 12:38:54)

vmalert: support bearer token for datasource, remotewrite and remoteread
https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1608

hagen1778: Thanks @valyala @f41gh7  - updated!

Patch:
diff --git a/app/vmalert/README.md b/app/vmalert/README.md
index db7012a47..3eef9bc1f 100644
--- a/app/vmalert/README.md
+++ b/app/vmalert/README.md
@@ -368,199 +368,217 @@ command-line flags with their descriptions.
 The shortlist of configuration flags is the following:
 ```
   -datasource.appendTypePrefix
-    	Whether to add type prefix to -datasource.url based on the query type. Set to true if sending different query types to the vmselect URL.
+        Whether to add type prefix to -datasource.url based on the query type. Set to true if sending different query types to the vmselect URL.
   -datasource.basicAuth.password string
-    	Optional basic auth password for -datasource.url
+        Optional basic auth password for -datasource.url
+  -datasource.basicAuth.passwordFile string
+        Optional path to basic auth password to use for -datasource.url
   -datasource.basicAuth.username string
-    	Optional basic auth username for -datasource.url
+        Optional basic auth username for -datasource.url
+  -datasource.bearerToken string
+        Optional bearer auth token to use for -datasource.url.
+  -datasource.bearerTokenFile string
+        Optional path to bearer token file to use for -datasource.url.
   -datasource.lookback duration
-    	Lookback defines how far into the past to look when evaluating queries. For example, if the datasource.lookback=5m then param "time" with value now()-5m will be added to every query.
+        Lookback defines how far into the past to look when evaluating queries. For example, if the datasource.lookback=5m then param "time" with value now()-5m will be added to every query.
   -datasource.maxIdleConnections int
-    	Defines the number of idle (keep-alive connections) to each configured datasource. Consider setting this value equal to the value: groups_total * group.concurrency. Too low a value may result in a high number of sockets in TIME_WAIT state. (default 100)
+        Defines the number of idle (keep-alive connections) to each configured datasource. Consider setting this value equal to the value: groups_total * group.concurrency. Too low a value may result in a high number of sockets in TIME_WAIT state. (default 100)
   -datasource.queryStep duration
-    	queryStep defines how far a value can fallback to when evaluating queries. For example, if datasource.queryStep=15s then param "step" with value "15s" will be added to every query.If queryStep isn't specified, rule's evaluationInterval will be used instead.
+        queryStep defines how far a value can fallback to when evaluating queries. For example, if datasource.queryStep=15s then param "step" with value "15s" will be added to every query.If queryStep isn't specified, rule's evaluationInterval will be used instead.
   -datasource.roundDigits int
-    	Adds "round_digits" GET param to datasource requests. In VM "round_digits" limits the number of digits after the decimal point in response values.
+        Adds "round_digits" GET param to datasource requests. In VM "round_digits" limits the number of digits after the decimal point in response values.
   -datasource.tlsCAFile string
-    	Optional path to TLS CA file to use for verifying connections to -datasource.url. By default, system CA is used
+        Optional path to TLS CA file to use for verifying connections to -datasource.url. By default, system CA is used
   -datasource.tlsCertFile string
-    	Optional path to client-side TLS certificate file to use when connecting to -datasource.url
+        Optional path to client-side TLS certificate file to use when connecting to -datasource.url
   -datasource.tlsInsecureSkipVerify
-    	Whether to skip tls verification when connecting to -datasource.url
+        Whether to skip tls verification when connecting to -datasource.url
   -datasource.tlsKeyFile string
-    	Optional path to client-side TLS certificate key to use when connecting to -datasource.url
+        Optional path to client-side TLS certificate key to use when connecting to -datasource.url
   -datasource.tlsServerName string
-    	Optional TLS server name to use for connections to -datasource.url. By default, the server name from -datasource.url is used
+        Optional TLS server name to use for connections to -datasource.url. By default, the server name from -datasource.url is used
   -datasource.url string
-    	VictoriaMetrics or vmselect url. Required parameter. E.g. http://127.0.0.1:8428
+        VictoriaMetrics or vmselect url. Required parameter. E.g. http://127.0.0.1:8428
   -disableAlertgroupLabel
-    	Whether to disable adding group's name as label to generated alerts and time series.
+        Whether to disable adding group's name as label to generated alerts and time series.
   -dryRun -rule
-    	Whether to check only config files without running vmalert. The rules file are validated. The -rule flag must be specified.
+        Whether to check only config files without running vmalert. The rules file are validated. The -rule flag must be specified.
   -enableTCP6
-    	Whether to enable IPv6 for listening and dialing. By default only IPv4 TCP and UDP is used
+        Whether to enable IPv6 for listening and dialing. By default only IPv4 TCP and UDP is used
   -envflag.enable
-    	Whether to enable reading flags from environment variables additionally to command line. Command line flag values have priority over values from environment vars. Flags are read only from command line if this flag isn't set. See https://docs.victoriametrics.com/#environment-variables for more details
+        Whether to enable reading flags from environment variables additionally to command line. Command line flag values have priority over values from environment vars. Flags are read only from command line if this flag isn't set. See https://docs.victoriametrics.com/#environment-variables for more details
   -envflag.prefix string
-    	Prefix for environment variables if -envflag.enable is set
+        Prefix for environment variables if -envflag.enable is set
   -evaluationInterval duration
-    	How often to evaluate the rules (default 1m0s)
+        How often to evaluate the rules (default 1m0s)
   -external.alert.source string
-    	External Alert Source allows to override the Source link for alerts sent to AlertManager for cases where you want to build a custom link to Grafana, Prometheus or any other service.
-    	eg. 'explore?orgId=1&left=[\"now-1h\",\"now\",\"VictoriaMetrics\",{\"expr\": \"{{$expr|quotesEscape|crlfEscape|queryEscape}}\"},{\"mode\":\"Metrics\"},{\"ui\":[true,true,true,\"none\"]}]'.If empty '/api/v1/:groupID/alertID/status' is used
+        External Alert Source allows to override the Source link for alerts sent to AlertManager for cases where you want to build a custom link to Grafana, Prometheus or any other service.
+        eg. 'explore?orgId=1&left=[\"now-1h\",\"now\",\"VictoriaMetrics\",{\"expr\": \"{{$expr|quotesEscape|crlfEscape|queryEscape}}\"},{\"mode\":\"Metrics\"},{\"ui\":[true,true,true,\"none\"]}]'.If empty '/api/v1/:groupID/alertID/status' is used
   -external.label array
-    	Optional label in the form 'name=value' to add to all generated recording rules and alerts. Pass multiple -label flags in order to add multiple label sets.
-    	Supports an array of values separated by comma or specified via multiple flags.
+        Optional label in the form 'name=value' to add to all generated recording rules and alerts. Pass multiple -label flags in order to add multiple label sets.
+        Supports an array of values separated by comma or specified via multiple flags.
   -external.url string
-    	External URL is used as alert's source for sent alerts to the notifier
+        External URL is used as alert's source for sent alerts to the notifier
   -fs.disableMmap
-    	Whether to use pread() instead of mmap() for reading data files. By default mmap() is used for 64-bit arches and pread() is used for 32-bit arches, since they cannot read data files bigger than 2^32 bytes in memory. mmap() is usually faster for reading small data chunks than pread()
+        Whether to use pread() instead of mmap() for reading data files. By default mmap() is used for 64-bit arches and pread() is used for 32-bit arches, since they cannot read data files bigger than 2^32 bytes in memory. mmap() is usually faster for reading small data chunks than pread()
   -http.connTimeout duration
-    	Incoming http connections are closed after the configured timeout. This may help to spread the incoming load among a cluster of services behind a load balancer. Please note that the real timeout may be bigger by up to 10% as a protection against the thundering herd problem (default 2m0s)
+        Incoming http connections are closed after the configured timeout. This may help to spread the incoming load among a cluster of services behind a load balancer. Please note that the real timeout may be bigger by up to 10% as a protection against the thundering herd problem (default 2m0s)
   -http.disableResponseCompression
-    	Disable compression of HTTP responses to save CPU resources. By default compression is enabled to save network bandwidth
+        Disable compression of HTTP responses to save CPU resources. By default compression is enabled to save network bandwidth
   -http.idleConnTimeout duration
-    	Timeout for incoming idle http connections (default 1m0s)
+        Timeout for incoming idle http connections (default 1m0s)
   -http.maxGracefulShutdownDuration duration
-    	The maximum duration for a graceful shutdown of the HTTP server. A highly loaded server may require increased value for a graceful shutdown (default 7s)
+        The maximum duration for a graceful shutdown of the HTTP server. A highly loaded server may require increased value for a graceful shutdown (default 7s)
   -http.pathPrefix string
-    	An optional prefix to add to all the paths handled by http server. For example, if '-http.pathPrefix=/foo/bar' is set, then all the http requests will be handled on '/foo/bar/*' paths. This may be useful for proxied requests. See https://www.robustperception.io/using-external-urls-and-proxies-with-prometheus
+        An optional prefix to add to all the paths handled by http server. For example, if '-http.pathPrefix=/foo/bar' is set, then all the http requests will be handled on '/foo/bar/*' paths. This may be useful for proxied requests. See https://www.robustperception.io/using-external-urls-and-proxies-with-prometheus
   -http.shutdownDelay duration
-    	Optional delay before http server shutdown. During this delay, the server returns non-OK responses from /health page, so load balancers can route new requests to other servers
+        Optional delay before http server shutdown. During this delay, the server returns non-OK responses from /health page, so load balancers can route new requests to other servers
   -httpAuth.password string
-    	Password for HTTP Basic Auth. The authentication is disabled if -httpAuth.username is empty
+        Password for HTTP Basic Auth. The authentication is disabled if -httpAuth.username is empty
   -httpAuth.username string
-    	Username for HTTP Basic Auth. The authentication is disabled if empty. See also -httpAuth.password
+        Username for HTTP Basic Auth. The authentication is disabled if empty. See also -httpAuth.password
   -httpListenAddr string
-    	Address to listen for http connections (default ":8880")
+        Address to listen for http connections (default ":8880")
   -loggerDisableTimestamps
-    	Whether to disable writing timestamps in logs
+        Whether to disable writing timestamps in logs
   -loggerErrorsPerSecondLimit int
-    	Per-second limit on the number of ERROR messages. If more than the given number of errors are emitted per second, the remaining errors are suppressed. Zero values disable the rate limit
+        Per-second limit on the number of ERROR messages. If more than the given number of errors are emitted per second, the remaining errors are suppressed. Zero values disable the rate limit
   -loggerFormat string
-    	Format for logs. Possible values: default, json (default "default")
+        Format for logs. Possible values: default, json (default "default")
   -loggerLevel string
-    	Minimum level of errors to log. Possible values: INFO, WARN, ERROR, FATAL, PANIC (default "INFO")
+        Minimum level of errors to log. Possible values: INFO, WARN, ERROR, FATAL, PANIC (default "INFO")
   -loggerOutput string
-    	Output for the logs. Supported values: stderr, stdout (default "stderr")
+        Output for the logs. Supported values: stderr, stdout (default "stderr")
   -loggerTimezone string
-    	Timezone to use for timestamps in logs. Timezone must be a valid IANA Time Zone. For example: America/New_York, Europe/Berlin, Etc/GMT+3 or Local (default "UTC")
+        Timezone to use for timestamps in logs. Timezone must be a valid IANA Time Zone. For example: America/New_York, Europe/Berlin, Etc/GMT+3 or Local (default "UTC")
   -loggerWarnsPerSecondLimit int
-    	Per-second limit on the number of WARN messages. If more than the given number of warns are emitted per second, then the remaining warns are suppressed. Zero values disable the rate limit
+        Per-second limit on the number of WARN messages. If more than the given number of warns are emitted per second, then the remaining warns are suppressed. Zero values disable the rate limit
   -memory.allowedBytes size
-    	Allowed size of system memory VictoriaMetrics caches may occupy. This option overrides -memory.allowedPercent if set to a non-zero value. Too low a value may increase the cache miss rate usually resulting in higher CPU and disk IO usage. Too high a value may evict too much data from OS page cache resulting in higher disk IO usage
-    	Supports the following optional suffixes for size values: KB, MB, GB, KiB, MiB, GiB (default 0)
+        Allowed size of system memory VictoriaMetrics caches may occupy. This option overrides -memory.allowedPercent if set to a non-zero value. Too low a value may increase the cache miss rate usually resulting in higher CPU and disk IO usage. Too high a value may evict too much data from OS page cache resulting in higher disk IO usage
+        Supports the following optional suffixes for size values: KB, MB, GB, KiB, MiB, GiB (default 0)
   -memory.allowedPercent float
-    	Allowed percent of system memory VictoriaMetrics caches may occupy. See also -memory.allowedBytes. Too low a value may increase cache miss rate usually resulting in higher CPU and disk IO usage. Too high a value may evict too much data from OS page cache which will result in higher disk IO usage (default 60)
+        Allowed percent of system memory VictoriaMetrics caches may occupy. See also -memory.allowedBytes. Too low a value may increase cache miss rate usually resulting in higher CPU and disk IO usage. Too high a value may evict too much data from OS page cache which will result in higher disk IO usage (default 60)
   -metricsAuthKey string
-    	Auth key for /metrics. It overrides httpAuth settings
+        Auth key for /metrics. It overrides httpAuth settings
   -notifier.basicAuth.password array
-    	Optional basic auth password for -notifier.url
-    	Supports an array of values separated by comma or specified via multiple flags.
+        Optional basic auth password for -notifier.url
+        Supports an array of values separated by comma or specified via multiple flags.
   -notifier.basicAuth.username array
-    	Optional basic auth username for -notifier.url
-    	Supports an array of values separated by comma or specified via multiple flags.
+        Optional basic auth username for -notifier.url
+        Supports an array of values separated by comma or specified via multiple flags.
   -notifier.tlsCAFile array
-    	Optional path to TLS CA file to use for verifying connections to -notifier.url. By default system CA is used
-    	Supports an array of values separated by comma or specified via multiple flags.
+        Optional path to TLS CA file to use for verifying connections to -notifier.url. By default system CA is used
+        Supports an array of values separated by comma or specified via multiple flags.
   -notifier.tlsCertFile array
-    	Optional path to client-side TLS certificate file to use when connecting to -notifier.url
-    	Supports an array of values separated by comma or specified via multiple flags.
+        Optional path to client-side TLS certificate file to use when connecting to -notifier.url
+        Supports an array of values separated by comma or specified via multiple flags.
   -notifier.tlsInsecureSkipVerify array
-    	Whether to skip tls verification when connecting to -notifier.url
-    	Supports array of values separated by comma or specified via multiple flags.
+        Whether to skip tls verification when connecting to -notifier.url
+        Supports array of values separated by comma or specified via multiple flags.
   -notifier.tlsKeyFile array
-    	Optional path to client-side TLS certificate key to use when connecting to -notifier.url
-    	Supports an array of values separated by comma or specified via multiple flags.
+        Optional path to client-side TLS certificate key to use when connecting to -notifier.url
+        Supports an array of values separated by comma or specified via multiple flags.
   -notifier.tlsServerName array
-    	Optional TLS server name to use for connections to -notifier.url. By default the server name from -notifier.url is used
-    	Supports an array of values separated by comma or specified via multiple flags.
+        Optional TLS server name to use for connections to -notifier.url. By default the server name from -notifier.url is used
+        Supports an array of values separated by comma or specified via multiple flags.
   -notifier.url array
-    	Prometheus alertmanager URL. Required parameter. e.g. http://127.0.0.1:9093
-    	Supports an array of values separated by comma or specified via multiple flags.
+        Prometheus alertmanager URL. Required parameter. e.g. http://127.0.0.1:9093
+        Supports an array of values separated by comma or specified via multiple flags.
   -pprofAuthKey string
-    	Auth key for /debug/pprof. It overrides httpAuth settings
+        Auth key for /debug/pprof. It overrides httpAuth settings
   -remoteRead.basicAuth.password string
-    	Optional basic auth password for -remoteRead.url
+        Optional basic auth password for -remoteRead.url
+  -remoteRead.basicAuth.passwordFile string
+        Optional path to basic auth password to use for -remoteRead.url
   -remoteRead.basicAuth.username string
-    	Optional basic auth username for -remoteRead.url
+        Optional basic auth username for -remoteRead.url
+  -remoteRead.bearerToken string
+        Optional bearer auth token to use for -remoteRead.url.
+  -remoteRead.bearerTokenFile string
+        Optional path to bearer token file to use for -remoteRead.url.
   -remoteRead.ignoreRestoreErrors
-    	Whether to ignore errors from remote storage when restoring alerts state on startup. (default true)
+        Whether to ignore errors from remote storage when restoring alerts state on startup. (default true)
   -remoteRead.lookback duration
-    	Lookback defines how far to look into past for alerts timeseries. For example, if lookback=1h then range from now() to now()-1h will be scanned. (default 1h0m0s)
+        Lookback defines how far to look into past for alerts timeseries. For example, if lookback=1h then range from now() to now()-1h will be scanned. (default 1h0m0s)
   -remoteRead.tlsCAFile string
-    	Optional path to TLS CA file to use for verifying connections to -remoteRead.url. By default system CA is used
+        Optional path to TLS CA file to use for verifying connections to -remoteRead.url. By default system CA is used
   -remoteRead.tlsCertFile string
-    	Optional path to client-side TLS certificate file to use when connecting to -remoteRead.url
+        Optional path to client-side TLS certificate file to use when connecting to -remoteRead.url
   -remoteRead.tlsInsecureSkipVerify
-    	Whether to skip tls verification when connecting to -remoteRead.url
+        Whether to skip tls verification when connecting to -remoteRead.url
   -remoteRead.tlsKeyFile string
-    	Optional path to client-side TLS certificate key to use when connecting to -remoteRead.url
+        Optional path to client-side TLS certificate key to use when connecting to -remoteRead.url
   -remoteRead.tlsServerName string
-    	Optional TLS server name to use for connections to -remoteRead.url. By default the server name from -remoteRead.url is used
+        Optional TLS server name to use for connections to -remoteRead.url. By default the server name from -remoteRead.url is used
   -remoteRead.url vmalert
-    	Optional URL to VictoriaMetrics or vmselect that will be used to restore alerts state. This configuration makes sense only if vmalert was configured with `remoteWrite.url` before and has been successfully persisted its state. E.g. http://127.0.0.1:8428
+        Optional URL to VictoriaMetrics or vmselect that will be used to restore alerts state. This configuration makes sense only if vmalert was configured with `remoteWrite.url` before and has been successfully persisted its state. E.g. http://127.0.0.1:8428
   -remoteWrite.basicAuth.password string
-    	Optional basic auth password for -remoteWrite.url
+        Optional basic auth password for -remoteWrite.url
+  -remoteWrite.basicAuth.passwordFile string
+        Optional path to basic auth password to use for -remoteWrite.url
   -remoteWrite.basicAuth.username string
-    	Optional basic auth username for -remoteWrite.url
+        Optional basic auth username for -remoteWrite.url
+  -remoteWrite.bearerToken string
+        Optional bearer auth token to use for -remoteWrite.url.
+  -remoteWrite.bearerTokenFile string
+        Optional path to bearer token file to use for -remoteWrite.url.
   -remoteWrite.concurrency int
-    	Defines number of writers for concurrent writing into remote querier (default 1)
+        Defines number of writers for concurrent writing into remote querier (default 1)
   -remoteWrite.disablePathAppend
-    	Whether to disable automatic appending of '/api/v1/write' path to the configured -remoteWrite.url.
+        Whether to disable automatic appending of '/api/v1/write' path to the configured -remoteWrite.url.
   -remoteWrite.flushInterval duration
-    	Defines interval of flushes to remote write endpoint (default 5s)
+        Defines interval of flushes to remote write endpoint (default 5s)
   -remoteWrite.maxBatchSize int
-    	Defines defines max number of timeseries to be flushed at once (default 1000)
+        Defines defines max number of timeseries to be flushed at once (default 1000)
   -remoteWrite.maxQueueSize int
-    	Defines the max number of pending datapoints to remote write endpoint (default 100000)
+        Defines the max number of pending datapoints to remote write endpoint (default 100000)
   -remoteWrite.tlsCAFile string
-    	Optional path to TLS CA file to use for verifying connections to -remoteWrite.url. By default system CA is used
+        Optional path to TLS CA file to use for verifying connections to -remoteWrite.url. By default system CA is used
   -remoteWrite.tlsCertFile string
-    	Optional path to client-side TLS certificate file to use when connecting to -remoteWrite.url
+        Optional path to client-side TLS certificate file to use when connecting to -remoteWrite.url
   -remoteWrite.tlsInsecureSkipVerify
-    	Whether to skip tls verification when connecting to -remoteWrite.url
+        Whether to skip tls verification when connecting to -remoteWrite.url
   -remoteWrite.tlsKeyFile string
-    	Optional path to client-side TLS certificate key to use when connecting to -remoteWrite.url
+        Optional path to client-side TLS certificate key to use when connecting to -remoteWrite.url
   -remoteWrite.tlsServerName string
-    	Optional TLS server name to use for connections to -remoteWrite.url. By default the server name from -remoteWrite.url is used
+        Optional TLS server name to use for connections to -remoteWrite.url. By default the server name from -remoteWrite.url is used
   -remoteWrite.url string
-    	Optional URL to VictoriaMetrics or vminsert where to persist alerts state and recording rules results in form of timeseries. For example, if -remoteWrite.url=http://127.0.0.1:8428 is specified, then the alerts state will be written to http://127.0.0.1:8428/api/v1/write . See also -remoteWrite.disablePathAppend
+        Optional URL to VictoriaMetrics or vminsert where to persist alerts state and recording rules results in form of timeseries. For example, if -remoteWrite.url=http://127.0.0.1:8428 is specified, then the alerts state will be written to http://127.0.0.1:8428/api/v1/write . See also -remoteWrite.disablePathAppend
   -replay.maxDatapointsPerQuery int
-    	Max number of data points expected in one request. The higher the value, the less requests will be made during replay. (default 1000)
+        Max number of data points expected in one request. The higher the value, the less requests will be made during replay. (default 1000)
   -replay.ruleRetryAttempts int
-    	Defines how many retries to make before giving up on rule if request for it returns an error. (default 5)
+        Defines how many retries to make before giving up on rule if request for it returns an error. (default 5)
   -replay.rulesDelay duration
-    	Delay between rules evaluation within the group. Could be important if there are chained rules inside of the groupand processing need to wait for previous rule results to be persisted by remote storage before evaluating the next rule.Keep it equal or bigger than -remoteWrite.flushInterval. (default 1s)
+        Delay between rules evaluation within the group. Could be important if there are chained rules inside of the groupand processing need to wait for previous rule results to be persisted by remote storage before evaluating the next rule.Keep it equal or bigger than -remoteWrite.flushInterval. (default 1s)
   -replay.timeFrom string
-    	The time filter in RFC3339 format to select time series with timestamp equal or higher than provided value. E.g. '2020-01-01T20:07:00Z'
+        The time filter in RFC3339 format to select time series with timestamp equal or higher than provided value. E.g. '2020-01-01T20:07:00Z'
   -replay.timeTo string
-    	The time filter in RFC3339 format to select timeseries with timestamp equal or lower than provided value. E.g. '2020-01-01T20:07:00Z'
+        The time filter in RFC3339 format to select timeseries with timestamp equal or lower than provided value. E.g. '2020-01-01T20:07:00Z'
   -rule array
-    	Path to the file with alert rules.
-    	Supports patterns. Flag can be specified multiple times.
-    	Examples:
-    	 -rule="/path/to/file". Path to a single file with alerting rules
-    	 -rule="dir/*.yaml" -rule="/*.yaml". Relative path to all .yaml files in "dir" folder,
-    	absolute path to all .yaml files in root.
-    	Rule files may contain %{ENV_VAR} placeholders, which are substituted by the corresponding env vars.
-    	Supports an array of values separated by comma or specified via multiple flags.
+        Path to the file with alert rules.
+        Supports patterns. Flag can be specified multiple times.
+        Examples:
+         -rule="/path/to/file". Path to a single file with alerting rules
+         -rule="dir/*.yaml" -rule="/*.yaml". Relative path to all .yaml files in "dir" folder,
+        absolute path to all .yaml files in root.
+        Rule files may contain %{ENV_VAR} placeholders, which are substituted by the corresponding env vars.
+        Supports an array of values separated by comma or specified via multiple flags.
   -rule.configCheckInterval duration
-    	Interval for checking for changes in '-rule' files. By default the checking is disabled. Send SIGHUP signal in order to force config check for changes
+        Interval for checking for changes in '-rule' files. By default the checking is disabled. Send SIGHUP signal in order to force config check for changes
   -rule.maxResolveDuration duration
     	Limits the maximum duration for automatic alert expiration, which is by default equal to 3 evaluation intervals of the parent group.
   -rule.validateExpressions
-    	Whether to validate rules expressions via MetricsQL engine (default true)
+        Whether to validate rules expressions via MetricsQL engine (default true)
   -rule.validateTemplates
-    	Whether to validate annotation and label templates (default true)
+        Whether to validate annotation and label templates (default true)
   -tls
-    	Whether to enable TLS (aka HTTPS) for incoming requests. -tlsCertFile and -tlsKeyFile must be set if -tls is set
+        Whether to enable TLS (aka HTTPS) for incoming requests. -tlsCertFile and -tlsKeyFile must be set if -tls is set
   -tlsCertFile string
-    	Path to file with TLS certificate. Used only if -tls is set. Prefer ECDSA certs instead of RSA certs as RSA certs are slower
+        Path to file with TLS certificate. Used only if -tls is set. Prefer ECDSA certs instead of RSA certs as RSA certs are slower
   -tlsKeyFile string
-    	Path to file with TLS key. Used only if -tls is set
+        Path to file with TLS key. Used only if -tls is set
   -version
-    	Show VictoriaMetrics version
+        Show VictoriaMetrics version
 ```
 
 `vmalert` supports "hot" config reload via the following methods:
diff --git a/app/vmalert/datasource/init.go b/app/vmalert/datasource/init.go
index 95029744e..905938e00 100644
--- a/app/vmalert/datasource/init.go
+++ b/app/vmalert/datasource/init.go
@@ -7,14 +7,18 @@ import (
 	"strings"
 
 	"github.com/VictoriaMetrics/VictoriaMetrics/app/vmalert/utils"
+	"github.com/VictoriaMetrics/VictoriaMetrics/lib/promauth"
 )
 
 var (
 	addr = flag.String("datasource.url", "", "VictoriaMetrics or vmselect url. Required parameter. "+
 		"E.g. http://127.0.0.1:8428")
-	appendTypePrefix  = flag.Bool("datasource.appendTypePrefix", false, "Whether to add type prefix to -datasource.url based on the query type. Set to true if sending different query types to the vmselect URL.")
-	basicAuthUsername = flag.String("datasource.basicAuth.username", "", "Optional basic auth username for -datasource.url")
-	basicAuthPassword = flag.String("datasource.basicAuth.password", "", "Optional basic auth password for -datasource.url")
+	appendTypePrefix      = flag.Bool("datasource.appendTypePrefix", false, "Whether to add type prefix to -datasource.url based on the query type. Set to true if sending different query types to the vmselect URL.")
+	basicAuthUsername     = flag.String("datasource.basicAuth.username", "", "Optional basic auth username for -datasource.url")
+	basicAuthPassword     = flag.String("datasource.basicAuth.password", "", "Optional basic auth password for -datasource.url")
+	basicAuthPasswordFile = flag.String("datasource.basicAuth.passwordFile", "", "Optional path to basic auth password to use for -datasource.url")
+	bearerToken           = flag.String("datasource.bearerToken", "", "Optional bearer auth token to use for -datasource.url.")
+	bearerTokenFile       = flag.String("datasource.bearerTokenFile", "", "Optional path to bearer token file to use for -datasource.url.")
 
 	tlsInsecureSkipVerify = flag.Bool("datasource.tlsInsecureSkipVerify", false, "Whether to skip tls verification when connecting to -datasource.url")
 	tlsCertFile           = flag.String("datasource.tlsCertFile", "", "Optional path to client-side TLS certificate file to use when connecting to -datasource.url")
@@ -57,10 +61,19 @@ func Init(extraParams []Param) (QuerierBuilder, error) {
 		})
 	}
 
+	baCfg := &promauth.BasicAuthConfig{
+		Username:     *basicAuthUsername,
+		Password:     *basicAuthPassword,
+		PasswordFile: *basicAuthPasswordFile,
+	}
+	authCfg, err := promauth.NewConfig(".", nil, baCfg, *bearerToken, *bearerTokenFile, nil, nil)
+	if err != nil {
+		return nil, fmt.Errorf("failed to configure auth: %w", err)
+	}
+
 	return &VMStorage{
 		c:                &http.Client{Transport: tr},
-		basicAuthUser:    *basicAuthUsername,
-		basicAuthPass:    *basicAuthPassword,
+		authCfg:          authCfg,
 		datasourceURL:    strings.TrimSuffix(*addr, "/"),
 		appendTypePrefix: *appendTypePrefix,
 		lookBack:         *lookBack,
diff --git a/app/vmalert/datasource/vm.go b/app/vmalert/datasource/vm.go
index 389a60ba2..a6058dec8 100644
--- a/app/vmalert/datasource/vm.go
+++ b/app/vmalert/datasource/vm.go
@@ -7,14 +7,15 @@ import (
 	"net/http"
 	"strings"
 	"time"
+
+	"github.com/VictoriaMetrics/VictoriaMetrics/lib/promauth"
 )
 
 // VMStorage represents vmstorage entity with ability to read and write metrics
 type VMStorage struct {
 	c                *http.Client
+	authCfg          *promauth.Config
 	datasourceURL    string
-	basicAuthUser    string
-	basicAuthPass    string
 	appendTypePrefix bool
 	lookBack         time.Duration
 	queryStep        time.Duration
@@ -29,9 +30,8 @@ type VMStorage struct {
 func (s *VMStorage) Clone() *VMStorage {
 	return &VMStorage{
 		c:                s.c,
+		authCfg:          s.authCfg,
 		datasourceURL:    s.datasourceURL,
-		basicAuthUser:    s.basicAuthUser,
-		basicAuthPass:    s.basicAuthPass,
 		lookBack:         s.lookBack,
 		queryStep:        s.queryStep,
 		appendTypePrefix: s.appendTypePrefix,
@@ -57,11 +57,10 @@ func (s *VMStorage) BuildWithParams(params QuerierParams) Querier {
 }
 
 // NewVMStorage is a constructor for VMStorage
-func NewVMStorage(baseURL, basicAuthUser, basicAuthPass string, lookBack time.Duration, queryStep time.Duration, appendTypePrefix bool, c *http.Client) *VMStorage {
+func NewVMStorage(baseURL string, authCfg *promauth.Config, lookBack time.Duration, queryStep time.Duration, appendTypePrefix bool, c *http.Client) *VMStorage {
 	return &VMStorage{
 		c:                c,
-		basicAuthUser:    basicAuthUser,
-		basicAuthPass:    basicAuthPass,
+		authCfg:          authCfg,
 		datasourceURL:    strings.TrimSuffix(baseURL, "/"),
 		appendTypePrefix: appendTypePrefix,
 		lookBack:         lookBack,
@@ -149,8 +148,10 @@ func (s *VMStorage) newRequestPOST() (*http.Request, error) {
 		return nil, err
 	}
 	req.Header.Set("Content-Type", "application/json; charset=utf-8")
-	if s.basicAuthPass != "" {
-		req.SetBasicAuth(s.basicAuthUser, s.basicAuthPass)
+	if s.authCfg != nil {
+		if auth := s.authCfg.GetAuthHeader(); auth != "" {
+			req.Header.Set("Authorization", auth)
+		}
 	}
 	return req, nil
 }
diff --git a/app/vmalert/remoteread/init.go b/app/vmalert/remoteread/init.go
index 3900989b4..7a739d16d 100644
--- a/app/vmalert/remoteread/init.go
+++ b/app/vmalert/remoteread/init.go
@@ -7,6 +7,7 @@ import (
 
 	"github.com/VictoriaMetrics/VictoriaMetrics/app/vmalert/datasource"
 	"github.com/VictoriaMetrics/VictoriaMetrics/app/vmalert/utils"
+	"github.com/VictoriaMetrics/VictoriaMetrics/lib/promauth"
 )
 
 var (
@@ -15,6 +16,10 @@ var (
 		"E.g. http://127.0.0.1:8428")
 	basicAuthUsername     = flag.String("remoteRead.basicAuth.username", "", "Optional basic auth username for -remoteRead.url")
 	basicAuthPassword     = flag.String("remoteRead.basicAuth.password", "", "Optional basic auth password for -remoteRead.url")
+	basicAuthPasswordFile = flag.String("remoteRead.basicAuth.passwordFile", "", "Optional path to basic auth password to use for -remoteRead.url")
+	bearerToken           = flag.String("remoteRead.bearerToken", "", "Optional bearer auth token to use for -remoteRead.url.")
+	bearerTokenFile       = flag.String("remoteRead.bearerTokenFile", "", "Optional path to bearer token file to use for -remoteRead.url.")
+
 	tlsInsecureSkipVerify = flag.Bool("remoteRead.tlsInsecureSkipVerify", false, "Whether to skip tls verification when connecting to -remoteRead.url")
 	tlsCertFile           = flag.String("remoteRead.tlsCertFile", "", "Optional path to client-side TLS certificate file to use when connecting to -remoteRead.url")
 	tlsKeyFile            = flag.String("remoteRead.tlsKeyFile", "", "Optional path to client-side TLS certificate key to use when connecting to -remoteRead.url")
@@ -34,6 +39,15 @@ func Init() (datasource.QuerierBuilder, error) {
 	if err != nil {
 		return nil, fmt.Errorf("failed to create transport: %w", err)
 	}
+	baCfg := &promauth.BasicAuthConfig{
+		Username:     *basicAuthUsername,
+		Password:     *basicAuthPassword,
+		PasswordFile: *basicAuthPasswordFile,
+	}
+	authCfg, err := promauth.NewConfig(".", nil, baCfg, *bearerToken, *bearerTokenFile, nil, nil)
+	if err != nil {
+		return nil, fmt.Errorf("failed to configure auth: %w", err)
+	}
 	c := &http.Client{Transport: tr}
-	return datasource.NewVMStorage(*addr, *basicAuthUsername, *basicAuthPassword, 0, 0, false, c), nil
+	return datasource.NewVMStorage(*addr, authCfg, 0, 0, false, c), nil
 }
diff --git a/app/vmalert/remotewrite/init.go b/app/vmalert/remotewrite/init.go
index 1b4bb5979..aa0b70ba2 100644
--- a/app/vmalert/remotewrite/init.go
+++ b/app/vmalert/remotewrite/init.go
@@ -7,14 +7,18 @@ import (
 	"time"
 
 	"github.com/VictoriaMetrics/VictoriaMetrics/app/vmalert/utils"
+	"github.com/VictoriaMetrics/VictoriaMetrics/lib/promauth"
 )
 
 var (
 	addr = flag.String("remoteWrite.url", "", "Optional URL to VictoriaMetrics or vminsert where to persist alerts state "+
 		"and recording rules results in form of timeseries. For example, if -remoteWrite.url=http://127.0.0.1:8428 is specified, "+
 		"then the alerts state will be written to http://127.0.0.1:8428/api/v1/write . See also -remoteWrite.disablePathAppend")
-	basicAuthUsername = flag.String("remoteWrite.basicAuth.username", "", "Optional basic auth username for -remoteWrite.url")
-	basicAuthPassword = flag.String("remoteWrite.basicAuth.password", "", "Optional basic auth password for -remoteWrite.url")
+	basicAuthUsername     = flag.String("remoteWrite.basicAuth.username", "", "Optional basic auth username for -remoteWrite.url")
+	basicAuthPassword     = flag.String("remoteWrite.basicAuth.password", "", "Optional basic auth password for -remoteWrite.url")
+	basicAuthPasswordFile = flag.String("remoteWrite.basicAuth.passwordFile", "", "Optional path to basic auth password to use for -remoteWrite.url")
+	bearerToken           = flag.String("remoteWrite.bearerToken", "", "Optional bearer auth token to use for -remoteWrite.url.")
+	bearerTokenFile       = flag.String("remoteWrite.bearerTokenFile", "", "Optional path to bearer token file to use for -remoteWrite.url.")
 
 	maxQueueSize  = flag.Int("remoteWrite.maxQueueSize", 1e5, "Defines the max number of pending datapoints to remote write endpoint")
 	maxBatchSize  = flag.Int("remoteWrite.maxBatchSize", 1e3, "Defines defines max number of timeseries to be flushed at once")
@@ -43,14 +47,23 @@ func Init(ctx context.Context) (*Client, error) {
 		return nil, fmt.Errorf("failed to create transport: %w", err)
 	}
 
+	baCfg := &promauth.BasicAuthConfig{
+		Username:     *basicAuthUsername,
+		Password:     *basicAuthPassword,
+		PasswordFile: *basicAuthPasswordFile,
+	}
+	authCfg, err := promauth.NewConfig(".", nil, baCfg, *bearerToken, *bearerTokenFile, nil, nil)
+	if err != nil {
+		return nil, fmt.Errorf("failed to configure auth: %w", err)
+	}
+
 	return NewClient(ctx, Config{
 		Addr:              *addr,
+		AuthCfg:           authCfg,
 		Concurrency:       *concurrency,
 		MaxQueueSize:      *maxQueueSize,
 		MaxBatchSize:      *maxBatchSize,
 		FlushInterval:     *flushInterval,
-		BasicAuthUser:     *basicAuthUsername,
-		BasicAuthPass:     *basicAuthPassword,
 		DisablePathAppend: *disablePathAppend,
 		Transport:         t,
 	})
diff --git a/app/vmalert/remotewrite/remotewrite.go b/app/vmalert/remotewrite/remotewrite.go
index 8df1a1941..eaac3a4bb 100644
--- a/app/vmalert/remotewrite/remotewrite.go
+++ b/app/vmalert/remotewrite/remotewrite.go
@@ -10,10 +10,12 @@ import (
 	"sync"
 	"time"
 
+	"github.com/golang/snappy"
+
 	"github.com/VictoriaMetrics/VictoriaMetrics/lib/logger"
+	"github.com/VictoriaMetrics/VictoriaMetrics/lib/promauth"
 	"github.com/VictoriaMetrics/VictoriaMetrics/lib/prompbmarshal"
 	"github.com/VictoriaMetrics/metrics"
-	"github.com/golang/snappy"
 )
 
 // Client is an asynchronous HTTP client for writing
@@ -21,8 +23,8 @@ import (
 type Client struct {
 	addr              string
 	c                 *http.Client
+	authCfg           *promauth.Config
 	input             chan prompbmarshal.TimeSeries
-	baUser, baPass    string
 	flushInterval     time.Duration
 	maxBatchSize      int
 	maxQueueSize      int
@@ -35,10 +37,8 @@ type Client struct {
 // Config is config for remote write.
 type Config struct {
 	// Addr of remote storage
-	Addr string
-
-	BasicAuthUser string
-	BasicAuthPass string
+	Addr    string
+	AuthCfg *promauth.Config
 
 	// Concurrency defines number of readers that
 	// concurrently read from the queue and flush data
@@ -98,8 +98,7 @@ func NewClient(ctx context.Context, cfg Config) (*Client, error) {
 			Transport: cfg.Transport,
 		},
 		addr:              strings.TrimSuffix(cfg.Addr, "/"),
-		baUser:            cfg.BasicAuthUser,
-		baPass:            cfg.BasicAuthPass,
+		authCfg:           cfg.AuthCfg,
 		flushInterval:     cfg.FlushInterval,
 		maxBatchSize:      cfg.MaxBatchSize,
 		maxQueueSize:      cfg.MaxQueueSize,
@@ -232,8 +231,10 @@ func (c *Client) send(ctx context.Context, data []byte) error {
 	if err != nil {
 		return fmt.Errorf("failed to create new HTTP request: %w", err)
 	}
-	if c.baPass != "" {
-		req.SetBasicAuth(c.baUser, c.baPass)
+	if c.authCfg != nil {
+		if auth := c.authCfg.GetAuthHeader(); auth != "" {
+			req.Header.Set("Authorization", auth)
+		}
 	}
 	if !c.disablePathAppend {
 		req.URL.Path += writePath
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index b7fe9a910..ae8af1f5a 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -19,6 +19,7 @@ sort: 15
 * FEATURE: vmagent: reduce CPU usage when applying `series_limit` to scrape targets with constant set of metrics. See more information about `series_limit` [here](https://docs.victoriametrics.com/vmagent.html#cardinality-limiter).
 * FEATURE: vminsert: disable rerouting by default when a few of `vmstorage` nodes start accepting data at lower speed than the rest of `vmstorage` nodes. This should improve VictoriaMetrics cluster stability during rolling restarts and during spikes in [time series churn rate](https://docs.victoriametrics.com/FAQ.html#what-is-high-churn-rate). The rerouting can be enabled by passing `-disableRerouting=false` command-line flag to `vminsert`.
 * FEATURE: vmauth: do not put invalid auth tokens into log by default due to security reasons. The logging can be returned back by passing `-logInvalidAuthTokens` command-line flag to `vmauth`. Requests with invalid auth tokens are counted at `vmagent_http_request_errors_total{reason="invalid_auth_token"}` metric exposed by `vmauth` at `/metrics` page.
+* FEATURE: optimize performance for queries with regexp filters on metric name like `{__name__=~"metric1|...|metricN"}`. See [this pull request](https://github.com/VictoriaMetrics/VictoriaMetrics/pull/1610) from @faceair.
 
 * BUGFIX: properly handle queries with multiple filters matching empty labels such as `metric{label1=~"foo|",label2="bar|"}`. This filter must match the following series: `metric`, `metric{label1="foo"}`, `metric{label2="bar"}` and `metric{label1="foo",label2="bar"}`. Previously it was matching only `metric{label1="foo",label2="bar"}`. See [this issue](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1601).
 * BUGFIX: vmselect: reset connection timeouts after each request to `vmstorage`. This should prevent from `cannot read data in 0.000 seconds: unexpected EOF` warning in logs. See [this issue](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1562). Thanks to @mxlxm .
diff --git a/docs/MetricsQL.md b/docs/MetricsQL.md
index 3560fa7cd..711ac0ff2 100644
--- a/docs/MetricsQL.md
+++ b/docs/MetricsQL.md
@@ -24,7 +24,7 @@ Other PromQL functionality should work the same in MetricsQL. [File an issue](ht
 
 MetricsQL implements [PromQL](https://medium.com/@valyala/promql-tutorial-for-beginners-9ab455142085) and provides additional functionality mentioned below, which is aimed towards solving practical cases. Feel free [filing a feature request](https://github.com/VictoriaMetrics/VictoriaMetrics/issues) if you think MetricsQL misses certain useful functionality.
 
-This functionality can be evaluated at [an editable Grafana dashboard](http://play-grafana.victoriametrics.com:3000/d/4ome8yJmz/node-exporter-on-victoriametrics-demo) or at your own [VcitoriaMetrics instance](https://docs.victoriametrics.com/#how-to-start-victoriametrics).
+This functionality can be evaluated at [an editable Grafana dashboard](https://play-grafana.victoriametrics.com/d/4ome8yJmz/node-exporter-on-victoriametrics-demo) or at your own [VictoriaMetrics instance](https://docs.victoriametrics.com/#how-to-start-victoriametrics).
 
 - Graphite-compatible filters can be passed via `{__graphite__="foo.*.bar"}` syntax. This is equivalent to `{__name__=~"foo[.][^.]*[.]bar"}`, but usually works faster and is easier to use when migrating from Graphite. VictoriaMetrics also can be used as Graphite datasource in Grafana. See [these docs](https://docs.victoriametrics.com/#graphite-api-usage) for details.
 - Lookbehind window in square brackets may be omitted. VictoriaMetrics automatically selects the lookbehind window depending on the current step used for building the graph (e.g. `step` query arg passed to [/api/v1/query_range](https://prometheus.io/docs/prometheus/latest/querying/api/#range-queries)). For instance, the following query is valid in VictoriaMetrics: `rate(node_network_receive_bytes_total)`. It is equivalent to `rate(node_network_receive_bytes_total[$__interval])` when used in Grafana.
diff --git a/lib/storage/tag_filters.go b/lib/storage/tag_filters.go
index 2503afb2f..5511d3fd7 100644
--- a/lib/storage/tag_filters.go
+++ b/lib/storage/tag_filters.go
@@ -20,65 +20,80 @@ import (
 func convertToCompositeTagFilterss(tfss []*TagFilters) []*TagFilters {
 	tfssNew := make([]*TagFilters, 0, len(tfss))
 	for _, tfs := range tfss {
-		tfssNew = append(tfss, convertToCompositeTagFilters(tfs)...)
+		tfssNew = append(tfssNew, convertToCompositeTagFilters(tfs)...)
 	}
 	return tfssNew
 }
 
 func convertToCompositeTagFilters(tfs *TagFilters) []*TagFilters {
-	tfssCompiled := make([]*TagFilters, 0)
-
+	var tfssCompiled []*TagFilters
 	// Search for filters on metric name, which will be used for creating composite filters.
 	var names [][]byte
 	hasPositiveFilter := false
 	for _, tf := range tfs.tfs {
-		if len(tf.key) == 0 && !tf.isNegative && !tf.isRegexp {
-			names = [][]byte{tf.value}
-		} else if len(tf.key) == 0 && !tf.isNegative && tf.isRegexp && len(tf.orSuffixes) > 0 {
-			// Split the filter {__name__=~"name1|...|nameN", other_filters}
-			// into `name1{other_filters}`, ..., `nameN{other_filters}`
-			// and generate composite filters for each of them
-			names = names[:0]
-			for _, orSuffix := range tf.orSuffixes {
-				names = append(names, []byte(orSuffix))
+		if len(tf.key) == 0 {
+			if !tf.isNegative && !tf.isRegexp {
+				names = [][]byte{tf.value}
+			} else if !tf.isNegative && tf.isRegexp && len(tf.orSuffixes) > 0 {
+				// Split the filter {__name__=~"name1|...|nameN", other_filters}
+				// into name1{other_filters}, ..., nameN{other_filters}
+				// and generate composite filters for each of them.
+				names = names[:0] // override the previous filters on metric name
+				for _, orSuffix := range tf.orSuffixes {
+					names = append(names, []byte(orSuffix))
+				}
 			}
 		} else if !tf.isNegative && !tf.isEmptyMatch {
 			hasPositiveFilter = true
 		}
 	}
 	if len(names) == 0 {
-		tfssCompiled = append(tfssCompiled, tfs)
 		atomic.AddUint64(&compositeFilterMissingConversions, 1)
-		return tfssCompiled
+		return []*TagFilters{tfs}
 	}
 
+	// Create composite filters for the found names.
 	var compositeKey []byte
-	compositeFilters := 0
 	for _, name := range names {
+		compositeFilters := 0
 		tfsNew := make([]tagFilter, 0, len(tfs.tfs))
 		for _, tf := range tfs.tfs {
 			if len(tf.key) == 0 {
-				sameOrSuffixes := true
-				if len(names) != len(tf.orSuffixes) {
-					sameOrSuffixes = false
-				} else {
-					for i, orSuffix := range tf.orSuffixes {
-						if string(names[i]) != orSuffix {
-							sameOrSuffixes = false
+				if !hasPositiveFilter || tf.isNegative {
+					// Negative filters on metric name cannot be used for building composite filter, so leave them as is.
+					tfsNew = append(tfsNew, tf)
+					continue
+				}
+				if tf.isRegexp {
+					matchName := false
+					for _, orSuffix := range tf.orSuffixes {
+						if orSuffix == string(name) {
+							matchName = true
 							break
 						}
 					}
+					if !matchName {
+						// Leave as is the regexp filter on metric name if it doesn't match the current name.
+						tfsNew = append(tfsNew, tf)
+						continue
+					}
+					// Skip the tf, since its part (name) is used as a prefix in composite filter.
+					continue
 				}
-				if !hasPositiveFilter || tf.isNegative || tf.isRegexp && !sameOrSuffixes || !tf.isRegexp && string(tf.value) != string(name) {
+				if string(tf.value) != string(name) {
+					// Leave as is the filter on another metric name.
 					tfsNew = append(tfsNew, tf)
+					continue
 				}
+				// Skip the tf, since it is used as a prefix in composite filter.
 				continue
 			}
 			if string(tf.key) == "__graphite__" || bytes.Equal(tf.key, graphiteReverseTagKey) {
+				// Leave as is __graphite__ filters, since they cannot be used for building composite filter.
 				tfsNew = append(tfsNew, tf)
 				continue
 			}
-
+			// Create composite filter on (name, tf)
 			compositeKey = marshalCompositeTagKey(compositeKey[:0], name, tf.key)
 			var tfNew tagFilter
 			if err := tfNew.Init(tfs.commonPrefix, compositeKey, tf.value, tf.isNegative, tf.isRegexp); err != nil {
@@ -87,15 +102,16 @@ func convertToCompositeTagFilters(tfs *TagFilters) []*TagFilters {
 			tfsNew = append(tfsNew, tfNew)
 			compositeFilters++
 		}
+		if compositeFilters == 0 {
+			// Cannot use tfsNew, since it doesn't contain composite filters, e.g. it may match broader set of series.
+			// Fall back to the original tfs.
+			atomic.AddUint64(&compositeFilterMissingConversions, 1)
+			return []*TagFilters{tfs}
+		}
 		tfsCompiled := NewTagFilters()
 		tfsCompiled.tfs = tfsNew
 		tfssCompiled = append(tfssCompiled, tfsCompiled)
 	}
-	if compositeFilters == 0 {
-		tfssCompiled = append(tfssCompiled[:0], tfs)
-		atomic.AddUint64(&compositeFilterMissingConversions, 1)
-		return tfssCompiled
-	}
 	atomic.AddUint64(&compositeFilterSuccessConversions, 1)
 	return tfssCompiled
 }


Test patch:
diff --git a/app/vmalert/datasource/vm_test.go b/app/vmalert/datasource/vm_test.go
index 8dbf61698..801974d9c 100644
--- a/app/vmalert/datasource/vm_test.go
+++ b/app/vmalert/datasource/vm_test.go
@@ -10,14 +10,20 @@ import (
 	"strings"
 	"testing"
 	"time"
+
+	"github.com/VictoriaMetrics/VictoriaMetrics/lib/promauth"
 )
 
 var (
 	ctx           = context.Background()
 	basicAuthName = "foo"
 	basicAuthPass = "bar"
-	query         = "vm_rows"
-	queryRender   = "constantLine(10)"
+	baCfg         = &promauth.BasicAuthConfig{
+		Username: basicAuthName,
+		Password: basicAuthPass,
+	}
+	query       = "vm_rows"
+	queryRender = "constantLine(10)"
 )
 
 func TestVMInstantQuery(t *testing.T) {
@@ -73,7 +79,11 @@ func TestVMInstantQuery(t *testing.T) {
 	srv := httptest.NewServer(mux)
 	defer srv.Close()
 
-	s := NewVMStorage(srv.URL, basicAuthName, basicAuthPass, time.Minute, 0, false, srv.Client())
+	authCfg, err := promauth.NewConfig(".", nil, baCfg, "", "", nil, nil)
+	if err != nil {
+		t.Fatalf("unexpected: %s", err)
+	}
+	s := NewVMStorage(srv.URL, authCfg, time.Minute, 0, false, srv.Client())
 
 	p := NewPrometheusType()
 	pq := s.BuildWithParams(QuerierParams{DataSourceType: &p, EvaluationInterval: 15 * time.Second})
@@ -179,12 +189,16 @@ func TestVMRangeQuery(t *testing.T) {
 	srv := httptest.NewServer(mux)
 	defer srv.Close()
 
-	s := NewVMStorage(srv.URL, basicAuthName, basicAuthPass, time.Minute, 0, false, srv.Client())
+	authCfg, err := promauth.NewConfig(".", nil, baCfg, "", "", nil, nil)
+	if err != nil {
+		t.Fatalf("unexpected: %s", err)
+	}
+	s := NewVMStorage(srv.URL, authCfg, time.Minute, 0, false, srv.Client())
 
 	p := NewPrometheusType()
 	pq := s.BuildWithParams(QuerierParams{DataSourceType: &p, EvaluationInterval: 15 * time.Second})
 
-	_, err := pq.QueryRange(ctx, query, time.Now(), time.Time{})
+	_, err = pq.QueryRange(ctx, query, time.Now(), time.Time{})
 	expectError(t, err, "is missing")
 
 	_, err = pq.QueryRange(ctx, query, time.Time{}, time.Now())
@@ -216,6 +230,10 @@ func TestVMRangeQuery(t *testing.T) {
 }
 
 func TestRequestParams(t *testing.T) {
+	authCfg, err := promauth.NewConfig(".", nil, baCfg, "", "", nil, nil)
+	if err != nil {
+		t.Fatalf("unexpected: %s", err)
+	}
 	query := "up"
 	timestamp := time.Date(2001, 2, 3, 4, 5, 6, 0, time.UTC)
 	testCases := []struct {
@@ -308,10 +326,7 @@ func TestRequestParams(t *testing.T) {
 		{
 			"basic auth",
 			false,
-			&VMStorage{
-				basicAuthUser: "foo",
-				basicAuthPass: "bar",
-			},
+			&VMStorage{authCfg: authCfg},
 			func(t *testing.T, r *http.Request) {
 				u, p, _ := r.BasicAuth()
 				checkEqualString(t, "foo", u)
@@ -321,10 +336,7 @@ func TestRequestParams(t *testing.T) {
 		{
 			"basic auth range",
 			true,
-			&VMStorage{
-				basicAuthUser: "foo",
-				basicAuthPass: "bar",
-			},
+			&VMStorage{authCfg: authCfg},
 			func(t *testing.T, r *http.Request) {
 				u, p, _ := r.BasicAuth()
 				checkEqualString(t, "foo", u)
diff --git a/lib/storage/tag_filters_test.go b/lib/storage/tag_filters_test.go
index 2ac1f501d..9fe164f86 100644
--- a/lib/storage/tag_filters_test.go
+++ b/lib/storage/tag_filters_test.go
@@ -15,9 +15,9 @@ func TestConvertToCompositeTagFilters(t *testing.T) {
 				t.Fatalf("cannot add tf=%s: %s", tf.String(), err)
 			}
 		}
-		resultCompileds := convertToCompositeTagFilters(tfsCompiled)
-		result := make([][]TagFilter, len(resultCompileds))
-		for i, resultCompiled := range resultCompileds {
+		resultsCompiled := convertToCompositeTagFilterss([]*TagFilters{tfsCompiled})
+		result := make([][]TagFilter, len(resultsCompiled))
+		for i, resultCompiled := range resultsCompiled {
 			tfs := make([]TagFilter, len(resultCompiled.tfs))
 			for i, tf := range resultCompiled.tfs {
 				tfs[i] = TagFilter{