filter.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. package logfilter
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strconv"
  6. "strings"
  7. "github.com/expr-lang/expr"
  8. "github.com/expr-lang/expr/vm"
  9. )
  10. const maxFilterLength = 512
  11. var (
  12. comparePattern = regexp.MustCompile(`(?i)\b(Status|Action|User|ExitCode|Blocked|TimedOut|Running)\s*(==|!=)\s*("[^"]*"|\S+)`)
  13. containsPattern = regexp.MustCompile(`(?i)\b(Status|Action|User|Output)\s+contains\s+("[^"]*"|\S+)`)
  14. fieldNameByLower = map[string]string{
  15. "status": "Status",
  16. "action": "Action",
  17. "user": "User",
  18. "exitcode": "ExitCode",
  19. "blocked": "Blocked",
  20. "timedout": "TimedOut",
  21. "running": "Running",
  22. "output": "Output",
  23. }
  24. )
  25. // Compile parses and compiles a filter expression. Returns an error for invalid syntax.
  26. func Compile(expression string) (*vm.Program, error) {
  27. trimmed := strings.TrimSpace(expression)
  28. if trimmed == "" {
  29. return nil, nil
  30. }
  31. if len(trimmed) > maxFilterLength {
  32. return nil, fmt.Errorf("filter expression exceeds maximum length of %d characters", maxFilterLength)
  33. }
  34. return compileNormalized(normalizeExpression(trimmed))
  35. }
  36. func compileNormalized(normalized string) (*vm.Program, error) {
  37. if err := checkAllowedSyntax(normalized); err != nil {
  38. return nil, err
  39. }
  40. return expr.Compile(normalized,
  41. expr.Env(Record{}),
  42. expr.AsBool(),
  43. expr.DisableAllBuiltins(),
  44. expr.MaxNodes(maxFilterNodes),
  45. expr.Function("includes", includes),
  46. expr.Function("hasTag", hasTag),
  47. )
  48. }
  49. func includes(params ...any) (any, error) {
  50. if len(params) < 2 {
  51. return nil, fmt.Errorf("includes expects 2 arguments, got %d", len(params))
  52. }
  53. haystack, ok := params[0].(string)
  54. if !ok {
  55. return nil, fmt.Errorf("expected string for haystack")
  56. }
  57. needle, ok := params[1].(string)
  58. if !ok {
  59. return nil, fmt.Errorf("expected string for needle")
  60. }
  61. return strings.Contains(strings.ToLower(haystack), strings.ToLower(needle)), nil
  62. }
  63. func hasTag(params ...any) (any, error) {
  64. if len(params) < 2 {
  65. return nil, fmt.Errorf("hasTag expects 2 arguments, got %d", len(params))
  66. }
  67. tags, ok := params[0].([]string)
  68. if !ok {
  69. return nil, fmt.Errorf("expected []string for tags")
  70. }
  71. needle, ok := params[1].(string)
  72. if !ok {
  73. return nil, fmt.Errorf("expected string for needle")
  74. }
  75. return tagListIncludes(tags, needle), nil
  76. }
  77. func tagListIncludes(tags []string, needle string) bool {
  78. needle = strings.ToLower(needle)
  79. for _, tag := range tags {
  80. if strings.Contains(strings.ToLower(tag), needle) {
  81. return true
  82. }
  83. }
  84. return false
  85. }
  86. // Matches evaluates a compiled filter against a log record.
  87. func Matches(program *vm.Program, record Record) (bool, error) {
  88. if program == nil {
  89. return true, nil
  90. }
  91. result, err := expr.Run(program, record)
  92. if err != nil {
  93. return false, err
  94. }
  95. matched, ok := result.(bool)
  96. if !ok {
  97. return false, fmt.Errorf("filter expression must return a boolean")
  98. }
  99. return matched, nil
  100. }
  101. func normalizeExpression(expression string) string {
  102. if isNegatedSearchTerm(expression) {
  103. term := quoteLiteral(strings.TrimPrefix(expression, "!"))
  104. return negatedSearchExpression(term)
  105. }
  106. if isPositiveSearchTerm(expression) {
  107. return positiveSearchExpression(quoteLiteral(expression))
  108. }
  109. normalized := replaceContainsOperators(expression)
  110. normalized = replaceComparisons(normalized)
  111. return replaceBooleanWords(normalized)
  112. }
  113. func isNegatedSearchTerm(expression string) bool {
  114. if !strings.HasPrefix(expression, "!") {
  115. return false
  116. }
  117. remainder := strings.TrimSpace(expression[1:])
  118. return remainder != "" && !containsExpressionOperators(remainder)
  119. }
  120. func isPositiveSearchTerm(expression string) bool {
  121. return expression != "" && !containsExpressionOperators(expression)
  122. }
  123. func containsExpressionOperators(expression string) bool {
  124. lower := strings.ToLower(expression)
  125. operators := []string{"==", "!=", "&&", "||", " contains ", "(", ")"}
  126. for _, operator := range operators {
  127. if strings.Contains(lower, operator) {
  128. return true
  129. }
  130. }
  131. return false
  132. }
  133. func negatedSearchExpression(term string) string {
  134. return "!(" + positiveSearchExpression(term) + ")"
  135. }
  136. func positiveSearchExpression(term string) string {
  137. return "includes(Action, " + term + ") || includes(User, " + term + ") || includes(Status, " + term + ") || includes(Output, " + term + ") || hasTag(Tags, " + term + ")"
  138. }
  139. func replaceContainsOperators(expression string) string {
  140. return containsPattern.ReplaceAllStringFunc(expression, func(match string) string {
  141. parts := containsPattern.FindStringSubmatch(match)
  142. field := normalizeFieldName(parts[1])
  143. value := quoteIfNeeded(parts[2])
  144. return fmt.Sprintf("includes(%s, %s)", field, value)
  145. })
  146. }
  147. func replaceComparisons(expression string) string {
  148. return comparePattern.ReplaceAllStringFunc(expression, func(match string) string {
  149. parts := comparePattern.FindStringSubmatch(match)
  150. field := normalizeFieldName(parts[1])
  151. operator := parts[2]
  152. value := quoteIfNeeded(parts[3])
  153. return fmt.Sprintf("%s %s %s", field, operator, value)
  154. })
  155. }
  156. func normalizeFieldName(field string) string {
  157. if canonical, ok := fieldNameByLower[strings.ToLower(field)]; ok {
  158. return canonical
  159. }
  160. return field
  161. }
  162. func replaceBooleanWords(expression string) string {
  163. replacer := strings.NewReplacer(" and ", " && ", " AND ", " && ", " or ", " || ", " OR ", " || ")
  164. return replacer.Replace(expression)
  165. }
  166. func quoteIfNeeded(value string) string {
  167. if strings.HasPrefix(value, "\"") {
  168. return value
  169. }
  170. if isBooleanLiteral(value) || isIntegerLiteral(value) {
  171. return strings.ToLower(value)
  172. }
  173. return quoteLiteral(value)
  174. }
  175. func isBooleanLiteral(value string) bool {
  176. lower := strings.ToLower(value)
  177. return lower == "true" || lower == "false"
  178. }
  179. func isIntegerLiteral(value string) bool {
  180. _, err := strconv.ParseInt(value, 10, 64)
  181. return err == nil
  182. }
  183. func quoteLiteral(value string) string {
  184. return "\"" + strings.ReplaceAll(value, "\"", "\\\"") + "\""
  185. }