Files
cozystack/internal/observabilityproxy/metricslookback.go
T
ZverGuy 79ea8561de fix(observability-proxy): end a backquoted string only at an unescaped quote
The string tracking treated a backslash inside backquotes as literal,
but metricsql's scanString lets a backslash escape the closing quote
in all three quote kinds, and a quoted label name keeps that escape
({`\``=""} parses). The proxy ended such a string early, read the rest
of the query as string content, and accepted an escaped
rollup_candlestick after it with the lookup ending too soon.

Inside any quote a backslash now skips the next character, as
scanString does, and the comment no longer claims metricsql refuses
an escaped backquote.

Assisted-by: LLM
Signed-off-by: ZverGuy <maximbel2003@gmail.com>
2026-11-10 04:03:24 +07:00

322 lines
11 KiB
Go

/*
Copyright 2026 The Cozystack Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package observabilityproxy
import (
"regexp"
"strconv"
"strings"
"time"
)
// instantDefaultStep is the step vmselect uses for an instant query without
// one (defaultStep in app/vmselect/prometheus); it is also the implicit
// rollup window of a bare selector.
const instantDefaultStep = 5 * time.Minute
// silenceInterval is how far before a rollup or subquery window vmselect
// starts reading (maxSilenceInterval in app/vmselect/promql: the value of
// -search.minStalenessInterval, 5m when unset; cozystack does not set it).
const silenceInterval = 5 * time.Minute
// latencyOffset is how far vmselect moves an instant query evaluated within
// it of the current time back (-search.latencyOffset, 30s by default and
// not set by cozystack); the proxy forwards neither nocache nor
// latency_offset.
const latencyOffset = 30 * time.Second
// queryDurationPart is the subset of the MetricsQL duration grammar
// (scanSingleDuration in metricsql) the scan understands. Step multiples
// (5i, $__interval) and negative parts are left out on purpose: anything
// else makes the bound unknown. Offsets are scanned lower-cased, as
// metricsql reads units in any case; windows and steps in brackets are
// not, so an upper-case unit there is unknown.
var (
queryDurationPart = regexp.MustCompile(`(\d+(?:\.\d+)?)(ms|s|m|h|d|w|y)`)
queryDuration = regexp.MustCompile(`^(?:\d+(?:\.\d+)?(?:ms|s|m|h|d|w|y))+$`)
querySeconds = regexp.MustCompile(`^\d+(?:\.\d+)?$`)
)
// offsetTerminators may follow an offset's duration: whitespace, a
// closing bracket or separator, or a binary operator other than minus.
const offsetTerminators = " \t\n\r)]},+*/^%<>=!"
var queryDurationUnits = map[string]time.Duration{
"ms": time.Millisecond, "s": time.Second, "m": time.Minute, "h": time.Hour,
"d": 24 * time.Hour, "w": 7 * 24 * time.Hour, "y": 365 * 24 * time.Hour,
}
// queryStart is the earliest instant a query evaluated from start may read;
// zero when the bound is unknown.
func queryStart(query string, start time.Time, step time.Duration) time.Time {
lookback, ok := queryLookback(query, step)
if !ok {
return time.Time{}
}
return start.Add(-lookback)
}
// queryLookback is an upper bound on how far before its evaluation window
// a query reads, from a lexical scan that never parses the query. Every
// [...], offset and "(" counts, including ones inside quoted label values:
// an extra hit only makes the bound larger or unknown, never smaller.
// Windows and offsets are summed rather than maxed, which covers nesting;
// WITH is refused because a template applies one window several times.
// vmselect starts a rollup max(window, step) plus the silence interval
// before the first point, a subquery window+step+silence before it and
// aligns both down to a step. A rollup function or offset over anything
// but a selector is an implicit subquery (getRollupExprArg), so every "("
// is counted as one. Each step term uses the largest step seen.
func queryLookback(query string, step time.Duration) (time.Duration, bool) {
if strings.Contains(query, "@") {
return 0, false
}
var sum float64
subqueries := 0
maxStep := float64(step)
for rest := query; ; {
open := strings.IndexByte(rest, '[')
if open < 0 {
break
}
closing := strings.IndexByte(rest[open:], ']')
if closing < 0 {
return 0, false
}
window, subStep, isSubquery := strings.Cut(rest[open+1:open+closing], ":")
rest = rest[open+closing+1:]
if isSubquery {
subqueries++
if strings.TrimSpace(window) == "" {
window = "0s"
}
if strings.TrimSpace(subStep) != "" {
d, ok := parseQueryDuration(subStep)
if !ok {
return 0, false
}
maxStep = max(maxStep, d)
}
}
d, ok := parseQueryDuration(window)
if !ok {
return 0, false
}
sum += d
}
lower := strings.ToLower(query)
back, _, ok := scanOffsets(lower)
if !ok {
return 0, false
}
sum += back
if hasKeyword(lower, "with") {
return 0, false
}
n := float64(subqueries + strings.Count(query, "("))
sum += (2+3*n)*maxStep + (1+n)*float64(silenceInterval)
if sum > float64(maxMetricsDuration) {
return 0, false
}
return time.Duration(sum), true
}
// queryLookahead is an upper bound on how far after its evaluation window
// a query reads, from the same lexical scan, with step the query's step.
// A negative offset reads forward; the negative offsets are summed, which
// covers nesting. vmselect also evaluates a subquery up to its end plus
// its step, rounded up to the step (evalRollupFuncWithSubquery), and
// range_* transforms and keep_next_value carry those later values back
// onto earlier points, so each subquery level adds two steps; as for the
// lookback, every "(" counts as a possible implicit subquery and each
// term uses the largest step seen. Any @ makes the bound unknown, as it
// does for queryLookback, and so does WITH, which can apply one offset
// several times, and a backslash or a comment outside a string, which can
// hide what the scan looks for. vmselect also evaluates
// rollup_candlestick one step ahead of the evaluation time
// (evalRollupFuncWithoutAt), so it makes the bound unknown too.
func queryLookahead(query string, step time.Duration) (time.Duration, bool) {
if strings.Contains(query, "@") || unscannableOutsideString(query) {
return 0, false
}
lower := strings.ToLower(query)
if hasKeyword(lower, "rollup_candlestick") {
return 0, false
}
_, ahead, ok := scanOffsets(lower)
if !ok || ahead > 0 && hasKeyword(lower, "with") {
return 0, false
}
subqueries := 0
maxStep := float64(step)
for rest := query; ; {
open := strings.IndexByte(rest, '[')
if open < 0 {
break
}
closing := strings.IndexByte(rest[open:], ']')
if closing < 0 {
return 0, false
}
_, subStep, isSubquery := strings.Cut(rest[open+1:open+closing], ":")
rest = rest[open+closing+1:]
if !isSubquery {
continue
}
subqueries++
if strings.TrimSpace(subStep) != "" {
d, ok := parseQueryDuration(subStep)
if !ok {
return 0, false
}
maxStep = max(maxStep, d)
}
}
ahead += 2 * float64(subqueries+strings.Count(query, "(")) * maxStep
if ahead > float64(maxMetricsDuration) {
return 0, false
}
return time.Duration(ahead), true
}
// scanOffsets sums every offset of the lowercased query, the positive ones
// into back and the negative ones into ahead, in nanoseconds; ok is false
// when one is not a plain duration.
func scanOffsets(lower string) (back, ahead float64, ok bool) {
for i := 0; ; {
k := strings.Index(lower[i:], "offset")
if k < 0 {
return back, ahead, true
}
k += i
i = k + len("offset")
if !isKeyword(lower, k, i) {
continue
}
arg := strings.TrimLeft(lower[i:], " \t\n\r")
negative := strings.HasPrefix(arg, "-")
if negative {
arg = strings.TrimLeft(arg[1:], " \t\n\r")
}
end := strings.IndexFunc(arg, func(r rune) bool { return !inDuration(r) })
if end < 0 {
end = len(arg)
}
// metricsql lexes 1h-30m as one duration whose parts after the
// first negative one all subtract (DurationValue), so -1h-30m is
// -90m and 1h-2h is -1h; the scan does not read such compounds.
// metricsql continues a duration token in more forms than the scan
// reads: after a minus (-30m, -1.h, -.5h) and with a trailing
// $__interval, all summed by DurationValue. Only what certainly
// ends the token is accepted after the duration.
if end < len(arg) && !strings.ContainsRune(offsetTerminators, rune(arg[end])) {
return 0, 0, false
}
d, ok := parseQueryDuration(arg[:end])
if !ok {
return 0, 0, false
}
if negative {
ahead += d
} else {
back += d
}
}
}
// unscannableOutsideString reports a backslash or a "#" outside a string
// literal. metricsql unescapes identifiers (unescapeIdent), so
// rollup\_candlestick or offs\et name what the lexical scan looks for
// without its spelling; "#" starts a comment to the end of the line, and
// quotes or brackets inside one would mislead the string tracking here and
// the bracket and offset scans. Inside any of the three quotes a backslash
// skips the next character, as metricsql's scanString does: an escaped
// closing quote does not end the string, backquotes included (a quoted
// label name keeps such an escape).
func unscannableOutsideString(query string) bool {
var quote byte
for i := 0; i < len(query); i++ {
c := query[i]
switch {
case quote == 0 && (c == '\\' || c == '#'):
return true
case quote == 0 && (c == '"' || c == '\'' || c == '`'):
quote = c
case quote != 0 && c == '\\':
i++
case quote != 0 && c == quote:
quote = 0
}
}
return false
}
// isKeyword reports whether lower[start:end] stands on its own rather than
// inside an identifier.
func isKeyword(lower string, start, end int) bool {
return (start == 0 || !continuesIdent(lower[start-1], false)) &&
(end == len(lower) || !continuesIdent(lower[end], true))
}
func inDuration(r rune) bool {
return r >= '0' && r <= '9' || r >= 'a' && r <= 'z' || r == '.' || r == '_'
}
func hasKeyword(lower, word string) bool {
for i := 0; ; {
k := strings.Index(lower[i:], word)
if k < 0 {
return false
}
k += i
i = k + len(word)
if isKeyword(lower, k, i) {
return true
}
}
}
// continuesIdent reports whether c, next to "offset", makes it part of an
// identifier rather than the keyword. Digits and dots only continue an
// identifier after it, so before it they still count as a keyword hit.
func continuesIdent(c byte, after bool) bool {
return c >= 'a' && c <= 'z' || c == '_' || c == ':' || c >= 0x80 ||
after && (c >= '0' && c <= '9' || c == '.' || c == '\\')
}
// parseQueryDuration returns nanoseconds as a float so that a sum of huge
// durations cannot wrap; the caller compares it against the bound.
func parseQueryDuration(s string) (float64, bool) {
s = strings.TrimSpace(s)
if querySeconds.MatchString(s) {
f, err := strconv.ParseFloat(s, 64)
return f * float64(time.Second), err == nil
}
if !queryDuration.MatchString(s) {
return 0, false
}
var d float64
for _, m := range queryDurationPart.FindAllStringSubmatch(s, -1) {
f, err := strconv.ParseFloat(m[1], 64)
if err != nil {
return 0, false
}
d += f * float64(queryDurationUnits[m[2]])
}
return d, true
}