Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: introduce new elastic search parser (#15718)

h3n4l031d147358c6
diff --git a/backend/plugin/db/elasticsearch/elasticsearch.go b/backend/plugin/db/elasticsearch/elasticsearch.go
index 635f030074..8788d6ff70 100644
--- a/backend/plugin/db/elasticsearch/elasticsearch.go
+++ b/backend/plugin/db/elasticsearch/elasticsearch.go
@@ -20,6 +20,7 @@ import (
"google.golang.org/protobuf/types/known/durationpb"
"github.com/bytebase/bytebase/backend/plugin/db"
+ parser "github.com/bytebase/bytebase/backend/plugin/parser/elasticsearch"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
)
@@ -172,17 +173,22 @@ func (d *Driver) Execute(ctx context.Context, statement string, _ db.ExecuteOpti
}
func (d *Driver) QueryConn(_ context.Context, _ *sql.Conn, statement string, _ db.QueryContext) ([]*v1pb.QueryResult, error) {
- statements, err := splitElasticsearchStatements(statement)
+ parseResults, err := parser.ParseElasticsearchREST(statement)
if err != nil {
return nil, err
}
var results []*v1pb.QueryResult
- for _, s := range statements {
+ for _, parseResult := range parseResults {
if err := func() error {
startTime := time.Now()
// send HTTP request.
- resp, err := d.basicAuthClient.Do(string(s.method), s.route, s.queryBody)
+ var data []byte
+ for _, item := range parseResult.Request.Data {
+ data = append(data, []byte(item)...)
+ data = append(data, '\n')
+ }
+ resp, err := d.basicAuthClient.Do(parseResult.Request.Method, []byte(parseResult.Request.URL), data)
if err != nil {
return errors.Wrapf(err, "failed to send HTTP request")
}
@@ -220,7 +226,7 @@ func (d *Driver) QueryConn(_ context.Context, _ *sql.Conn, statement string, _ d
result.Rows = append(result.Rows, &row)
result.Latency = durationpb.New(time.Since(startTime))
result.RowsCount = int64(len(result.Rows))
- result.Statement = fmt.Sprintf("%s %s\n%s", s.method, s.route, s.queryBody)
+ result.Statement = fmt.Sprintf("%s %s\n%s", parseResult.Request.Method, parseResult.Request.URL, string(data))
// TODO(d): handle max size.
results = append(results, &result)
return nil
diff --git a/backend/plugin/db/elasticsearch/spliter.go b/backend/plugin/db/elasticsearch/spliter.go
deleted file mode 100644
index c9210827ff..0000000000
--- a/backend/plugin/db/elasticsearch/spliter.go
+++ /dev/null
@@ -1,238 +0,0 @@
-package elasticsearch
-
-import (
- "bufio"
- "io"
- "log/slog"
- "net/http"
- "strings"
-
- "github.com/pkg/errors"
-
- "github.com/bytebase/bytebase/backend/common/log"
-)
-
-func splitElasticsearchStatements(statementsStr string) ([]*statement, error) {
- var stmts []*statement
- sm := &stateMachine{}
-
- reader := bufio.NewReader(strings.NewReader(statementsStr))
-
- for {
- sm.reset()
- for sm.needMore() {
- sm.consume(reader)
- }
- if sm.error() != nil {
- return nil, sm.error()
- }
- if sm.statement() != nil {
- stmts = append(stmts, sm.statement())
- }
-
- if sm.eof {
- break
- }
- }
-
- return stmts, nil
-}
-
-type state int
-
-// States for FSM.
-const (
- statusInit state = iota
- statusMethod
- statusRoute
- statusQueryBody
-
- statusTerminate
-)
-
-// Supported HTTP methods for Elasticsearch API.
-var (
- supportedHTTPMethods = map[string]bool{
- http.MethodGet: true,
- http.MethodPost: true,
- http.MethodPut: true,
- http.MethodHead: true,
- http.MethodDelete: true,
- }
-)
-
-type statement struct {
- method []byte
- route []byte
- queryBody []byte
-}
-
-type stateMachine struct {
- state state
- methodBuf []byte
- routeBuf []byte
- queryBodyBuf []byte
- numLeftBraces int
- numRightBraces int
-
- stmt *statement
- err error
- eof bool
-}
-
-func (sm *stateMachine) reset() {
- sm.state = statusInit
- sm.methodBuf = nil
- sm.routeBuf = nil
- sm.queryBodyBuf = nil
- sm.numLeftBraces = 0
- sm.numRightBraces = 0
-
- sm.stmt = nil
- sm.err = nil
- sm.eof = false
-}
-
-// Perform logic checks and generate a statement.
-func (sm *stateMachine) generateStatement() (*statement, error) {
- // Case insensitive, similar to Kibana's approach.
- upperCaseMethod := strings.ToUpper(string(sm.methodBuf))
- if !supportedHTTPMethods[upperCaseMethod] {
- return nil, errors.Errorf("unsupported method type %q", string(sm.methodBuf))
- }
- if len(sm.routeBuf) == 0 {
- return nil, errors.New("required route is missing")
- }
- // It's ok for routes without the leading '/' in the editor.
- if sm.routeBuf[0] != '/' {
- sm.routeBuf = append([]byte{'/'}, sm.routeBuf...)
- }
- if sm.queryBodyBuf != nil {
- if sm.numLeftBraces != sm.numRightBraces {
- return nil, errors.New("unclosed brace")
- }
- // Elasticsearch Bulk APIs need a '\n' as the end character for the query body.
- if strings.Contains(string(sm.routeBuf), "_bulk") && sm.queryBodyBuf[len(sm.queryBodyBuf)-1] != '\n' {
- sm.queryBodyBuf = append(sm.queryBodyBuf, '\n')
- }
- }
- return &statement{
- method: []byte(upperCaseMethod),
- route: sm.routeBuf,
- queryBody: sm.queryBodyBuf,
- }, nil
-}
-
-func (sm *stateMachine) needMore() bool {
- if sm.err != nil {
- return false
- }
- if sm.state == statusTerminate {
- return false
- }
- return true
-}
-
-func (sm *stateMachine) error() error {
- return sm.err
-}
-
-func (sm *stateMachine) statement() *statement {
- return sm.stmt
-}
-
-func (sm *stateMachine) consume(reader *bufio.Reader) {
- c, _, err := reader.ReadRune()
- if err == io.EOF {
- sm.eof = true
- // maybe the previous run left us some empty chars to read.
- if sm.state == statusRoute || sm.state == statusQueryBody {
- stmt, err := sm.generateStatement()
- if err != nil {
- sm.err = err
- return
- }
- sm.stmt = stmt
- }
- sm.state = statusTerminate
- return
- } else if err != nil {
- sm.err = err
- return
- }
-
- switch sm.state {
- case statusInit:
- if isASCIIAlpha(c) {
- sm.state = statusMethod
- sm.methodBuf = append(sm.methodBuf, string(c)...)
- } else if c != '\r' && c != '\n' && c != ' ' {
- sm.err = errors.Errorf("invalid character %q for method", c)
- return
- }
-
- case statusMethod:
- if c == ' ' {
- sm.state = statusRoute
- } else if isASCIIAlpha(c) {
- sm.methodBuf = append(sm.methodBuf, string(c)...)
- } else {
- sm.err = errors.Errorf("invalid character %q for method", c)
- return
- }
-
- case statusRoute:
- if c == '\n' {
- if sm.routeBuf == nil {
- sm.err = errors.New("required route is missing")
- return
- }
- sm.state = statusQueryBody
- // Ignore CR characters produced by line breaks on Windows.
- } else if c != '\r' && c != ' ' {
- sm.routeBuf = append(sm.routeBuf, string(c)...)
- }
-
- case statusQueryBody:
- // Return a valid statement when:
- // 1. An alphabetic character is encountered, which represents the start of a method in the next statement.
- // 2. A newline character is encountered and there are no left braces.
- if (isASCIIAlpha(c) && (sm.numLeftBraces == sm.numRightBraces)) || (c == '\n' && sm.numLeftBraces == 0) {
- if isASCIIAlpha(c) {
- if err := reader.UnreadRune(); err != nil {
- slog.Warn("failed to unread rune", log.BBError(err))
- }
- }
- stmt, err := sm.generateStatement()
- if err != nil {
- sm.err = err
- return
- }
- sm.stmt = stmt
- sm.state = statusTerminate
- return
- }
-
- // Ignore any characters other than '\n', '{' and '}' outside the braces.
- if c == '\n' || c == '{' || c == '}' || sm.numLeftBraces > sm.numRightBraces {
- sm.queryBodyBuf = append(sm.queryBodyBuf, string(c)...)
- }
-
- switch c {
- case '{':
- sm.numLeftBraces++
- case '}':
- sm.numRightBraces++
- if sm.numLeftBraces < sm.numRightBraces {
- sm.err = errors.New("the curly braces '{}' are mismatched")
- return
- }
- }
- default:
- sm.err = errors.Errorf("unexpected state %v", sm.state)
- }
-}
-
-func isASCIIAlpha(c rune) bool {
- return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
-}
diff --git a/backend/plugin/db/elasticsearch/spliter_test.go b/backend/plugin/db/elasticsearch/spliter_test.go
deleted file mode 100644
index 9cb8f43593..0000000000
--- a/backend/plugin/db/elasticsearch/spliter_test.go
+++ /dev/null
@@ -1,114 +0,0 @@
-package elasticsearch
-
-import (
- "testing"
-
- "github.com/stretchr/testify/require"
-)
-
-func TestSpliter(t *testing.T) {
- tests := []struct {
- name string
- input string
- expected []*statement
- }{
- // Test 1: basic test.
- {
- name: "test 1",
- input: `POST /_bulk
-{ "index" : { "_index" : "books" } }
-{"name": "Revelation Space", "author": "天舟", "page_count": 585}
-{ "index" : { "_index" : "books" } }
-{"name": "1984", "author": "天舟", "page_count": 328}
-GET books/_search
-{
- "query": {
- "match_all": {}
- }
-}
-GET _cat/indices`,
- expected: []*statement{
- {
- method: []byte("POST"),
- route: []byte("/_bulk"),
- queryBody: []byte(`{ "index" : { "_index" : "books" } }
-{"name": "Revelation Space", "author": "天舟", "page_count": 585}
-{ "index" : { "_index" : "books" } }
-{"name": "1984", "author": "天舟", "page_count": 328}
-`),
- },
- {
- method: []byte("GET"),
- route: []byte(`/books/_search`),
- queryBody: []byte(`{
- "query": {
- "match_all": {}
- }
-}
-`),
- },
- {
- method: []byte("GET"),
- route: []byte(`/_cat/indices`),
- }},
- },
- // Test 2: with CR characters.
- {
- name: "test 2",
- input: "\nGET /_cat/indices\r\n\r\nget /_cat/indices\r\nget /_cat/indices\r\n\r\n",
- expected: []*statement{
- {
- method: []byte("GET"),
- route: []byte("/_cat/indices"),
- },
- {
- method: []byte("GET"),
- route: []byte("/_cat/indices"),
- },
- {
- method: []byte("GET"),
- route: []byte("/_cat/indices"),
- },
- },
- },
- // Test 3: with emojis.
- {
- name: "test 3",
- input: "\r\n\rPUT /my_index\r\n\r\nPOST /my_index/_doc\r\n{\r\n\t\"emoji\":\"😈😈😈😈\"}\r\nGET /",
- expected: []*statement{
- {
- method: []byte("PUT"),
- route: []byte("/my_index"),
- },
- {
- method: []byte("POST"),
- route: []byte("/my_index/_doc"),
- queryBody: []byte("{\r\n\t\"emoji\":\"😈😈😈😈\"}\n"),
- },
- {
- method: []byte("GET"),
- route: []byte("/"),
- },
- },
- },
- // Test 4: bulk APIs.
- {
- name: "test 4",
- input: "\r\nPOST /_bulk\r\n{ \"index\" : { \"_index\" : \"test\", \"_id\" : \"1\" } }\r\n{ \"field1\" : \"value1\" }\r\n\r\n",
- expected: []*statement{
- {
- method: []byte("POST"),
- route: []byte("/_bulk"),
- queryBody: []byte("{ \"index\" : { \"_index\" : \"test\", \"_id\" : \"1\" } }\n{ \"field1\" : \"value1\" }\n\n"),
- },
- },
- },
- }
-
- a := require.New(t)
- for _, test := range tests {
- stmts, err := splitElasticsearchStatements(test.input)
- a.NoError(err, test.name)
- a.Equal(test.expected, stmts, test.name)
- }
-}
diff --git a/backend/plugin/parser/elasticsearch/parser.go b/backend/plugin/parser/elasticsearch/parser.go
new file mode 100644
index 0000000000..6babd3a543
--- /dev/null
+++ b/backend/plugin/parser/elasticsearch/parser.go
@@ -0,0 +1,1099 @@
+package elasticsearch
+
+import (
+ "encoding/json"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+
+ hjson "github.com/hjson/hjson-go/v4"
+ "github.com/pkg/errors"
+)
+
+type ParseResult struct {
+ Request *Request
+ StartOffset int
+ EndOffset int
+}
+
+type Request struct {
+ Method string
+ URL string
+ Data []string `yaml:"data,omitempty"`
+}
+
+type editorRequest struct {
+ method string
+ url string
+ data []string
+}
+
+// parsedRequest is the range of a request, it is left inclusive and right exclusive.
+type parsedRequest struct {
+ // startOffset is the byte offset of the first character of the request.
+ startOffset int
+ // endOffset is the byte offset of the end position.
+ endOffset int
+}
+
+type adjustedParsedRequest struct {
+ // startLineNumber is the line number of the first character of the request, starting from 0.
+ startLineNumber int
+ // endLineNumber is the line number of the end position, starting from 0.
+ endLineNumber int
+}
+
+// See https://sourcegraph.com/github.com/elastic/kibana/-/blob/src/platform/plugins/shared/console/public/application/containers/editor/utils/requests_utils.ts?L76.
+// Combine getRequestStartLineNumber and getRequestEndLineNumber.
+func getAdjustedParsedRequest(r parsedRequest, text string) adjustedParsedRequest {
+ bs := []byte(text)
+ startLineNumber := 0
+ endLineNumber := 0
+ startOffset := r.startOffset
+ // The startOffset is out of range, returning the end of document like
+ // what the model.getPositionAt does.
+ if r.startOffset >= len(bs) {
+ startOffset = len(bs) - 1
+ }
+ for i := 0; i < r.startOffset; i++ {
+ if bs[i] == '\n' {
+ startLineNumber++
+ }
+ }
+
+ if r.endOffset > 0 {
+ // if the parser set an end offset for this request , then find the line number for it.
+ endLineNumber = startLineNumber
+ endOffset := r.endOffset
+ if endOffset >= len(bs) {
+ endOffset = len(bs) - 1
+ }
+ for i := startOffset; i < endOffset; i++ {
+ if bs[i] == '\n' {
+ endLineNumber++
+ }
+ }
+ }
+ // TODO(zp): if no end offset, try to find the line before the next request starts.
+ // if the end is empty, go up to find the first non-empty line.
+ lines := strings.Split(text, "\n")
+ for endLineNumber >= 0 && strings.TrimSpace(lines[endLineNumber]) == "" {
+ endLineNumber--
+ }
+ return adjustedParsedRequest{
+ startLineNumber: startLineNumber,
+ endLineNumber: endLineNumber,
+ }
+}
+
+type parser struct {
+ // at is the current rune's byte offset in the input string.
+ at int
+ ch rune
+ escapee map[rune]string
+ text string
+ errors []error
+ requests []parsedRequest
+ // requestStart is the byte offset of the first character of the request.
+ requestStartOffset int
+ // requestEnd is the byte offset of the first character of the next request.
+ requestEndOffset int
+}
+
+// ParseElasticsearchREST parses the Elasticsearch REST API request.
+func ParseElasticsearchREST(text string) ([]*ParseResult, error) {
+ p := newParser(text)
+ parsedResults, err := p.parse()
+ if err != nil {
+ return nil, err
+ }
+ var result []*ParseResult
+ for _, parsedResult := range parsedResults {
+ // See https://sourcegraph.com/github.com/elastic/kibana/-/blob/src/platform/plugins/shared/console/public/application/containers/editor/monaco_editor_actions_provider.ts?L261.
+ adjustedOffset := getAdjustedParsedRequest(parsedResult, text)
+ if adjustedOffset.startLineNumber > adjustedOffset.endLineNumber {
+ return nil, errors.Errorf("invalid request range")
+ }
+ editorRequest := getEditorRequest(text, adjustedOffset)
+ if editorRequest == nil {
+ continue
+ }
+ if len(editorRequest.data) > 0 {
+ for i, v := range editorRequest.data {
+ if containsComments(v) {
+ // parse and stringify to remove comments.
+ editorRequest.data[i] = indentData(v)
+ }
+ editorRequest.data[i] = collapseLiteralString(v)
+ }
+ }
+ result = append(result, &ParseResult{
+ Request: &Request{
+ Method: editorRequest.method,
+ URL: editorRequest.url,
+ Data: editorRequest.data,
+ },
+ StartOffset: parsedResult.startOffset,
+ EndOffset: parsedResult.endOffset,
+ })
+ }
+
+ return result, err
+}
+
+func collapseLiteralString(s string) string {
+ splitData := strings.Split(s, `"""`)
+ for idx := 1; idx < len(splitData)-1; idx += 2 {
+ v, err := json.Marshal(splitData[idx])
+ if err != nil {
+ continue
+ }
+ splitData[idx] = string(v)
+ }
+ return strings.Join(splitData, "")
+}
+
+func indentData(s string) string {
+ v := make(map[string]any)
+ if err := hjson.Unmarshal([]byte(s), &v); err != nil {
+ return s
+ }
+ m, err := json.MarshalIndent(v, "", " ")
+ if err != nil {
+ return s
+ }
+ return string(m)
+}
+
+func containsComments(s string) bool {
+ insideString := false
+ var prevR rune
+ rs := []rune(s)
+ for i, r := range rs {
+ nextR := rune(0)
+ if i+1 < len(rs) {
+ nextR = rs[i+1]
+ }
+
+ if !insideString && r == '"' {
+ insideString = true
+ } else if insideString && r == '"' && prevR != '\\' {
+ insideString = false
+ } else if !insideString {
+ if r == '/' && (nextR == '/' || nextR == '*') {
+ return true
+ }
+ }
+ prevR = r
+ }
+ return false
+}
+
+// See https://sourcegraph.com/github.com/elastic/kibana/-/blob/src/platform/plugins/shared/console/public/application/containers/editor/utils/requests_utils.ts?L204.
+func getEditorRequest(text string, a adjustedParsedRequest) *editorRequest {
+ e := &editorRequest{}
+ lines := strings.Split(text, "\n")
+ methodURLLine := strings.TrimSpace(lines[a.startLineNumber])
+ if methodURLLine == "" {
+ return nil
+ }
+ method, url := parseLine(methodURLLine)
+ if method == "" || url == "" {
+ return nil
+ }
+ e.method = method
+ e.url = url
+
+ if a.endLineNumber <= a.startLineNumber {
+ return e
+ }
+
+ dataString := ""
+ if a.startLineNumber < len(lines)-1 {
+ var validLines []string
+ for i := a.startLineNumber + 1; i <= a.endLineNumber; i++ {
+ validLines = append(validLines, lines[i])
+ }
+ dataString = strings.TrimSpace(strings.Join(validLines, "\n"))
+ }
+
+ data := splitDataIntoJSONObjects(dataString)
+ return &editorRequest{
+ method: method,
+ url: url,
+ data: data,
+ }
+}
+
+// Splits a concatenated string of JSON objects into individual JSON objects.
+// This function takes a string containing one or more JSON objects concatenated together,
+// separated by optional whitespace, and splits them into an array of individual JSON strings.
+// It ensures that nested objects and strings containing braces do not interfere with the splitting logic.
+//
+// Example inputs:
+// - '{ "query": "test"} { "query": "test" }' -> ['{ "query": "test"}', '{ "query": "test" }']
+// - '{ "query": "test"}' -> ['{ "query": "test"}']
+// - '{ "query": "{a} {b}"}' -> ['{ "query": "{a} {b}"}'].
+func splitDataIntoJSONObjects(s string) []string {
+ var jsonObjects []string
+ // Track the depth of nested braces
+ depth := 0
+ // Holds the current JSON object as we iterate
+ currentObject := ""
+ // Tracks whether the current position is inside a string
+ insideString := false
+ // Iterate through each character in the input string
+ rs := []rune(s)
+ for i, r := range rs {
+ // Append the character to the current JSON object string
+ currentObject += string(r)
+
+ // If the character is a double quote and it is not escaped, toggle the `insideString` state
+ if r == '"' && (i == 0 || rs[i-1] != '\\') {
+ insideString = !insideString
+ } else if !insideString {
+ // Only modify depth if not inside a string
+ switch r {
+ case '{':
+ depth++
+ case '}':
+ depth--
+ }
+
+ if depth == 0 {
+ jsonObjects = append(jsonObjects, strings.TrimSpace(currentObject))
+ currentObject = ""
+ }
+ }
+ }
+
+ // If there's remaining data in currentObject, add it as the last JSON object.
+ if strings.TrimSpace(currentObject) != "" {
+ jsonObjects = append(jsonObjects, strings.TrimSpace(currentObject))
+ }
+
+ // Filter out any empty strings from the result
+ var result []string
+ for i := 0; i < len(jsonObjects); i++ {
+ if jsonObjects[i] != "" {
+ result = append(result, jsonObjects[i])
+ }
+ }
+ return result
+}
+
+func parseLine(line string) (method string, url string) {
+ line = strings.TrimSpace(line)
+ firstWhitespaceIndex := strings.Index(line, " ")
+ if firstWhitespaceIndex < 0 {
+ // There is no url, only method
+ return line, ""
+ }
+
+ // 1st part is the method
+ method = strings.ToUpper(strings.TrimSpace(line[0:firstWhitespaceIndex]))
+ // 2nd part is the url
+ url, err := removeTrailingWhitespace(strings.TrimSpace(line[firstWhitespaceIndex:]))
+ if err != nil {
+ return "", ""
+ }
+ return method, url
+}
+
+// This function removes any trailing comments, for example:
+// "_search // comment" -> "_search"
+// Ideally the parser would do that, but currently they are included in the url.
+func removeTrailingWhitespace(s string) (string, error) {
+ index := 0
+ whitespaceIndex := -1
+ isQueryParam := false
+ for {
+ r, sz := utf8.DecodeRuneInString(s[index:])
+ if r == utf8.RuneError {
+ break
+ }
+ if r == '"' {
+ isQueryParam = !isQueryParam
+ } else if r == ' ' && !isQueryParam {
+ whitespaceIndex = index
+ break
+ }
+ index += sz
+ }
+ if whitespaceIndex > 0 {
+ return s[:whitespaceIndex], nil
+ }
+ return s, nil
+}
+
+func newParser(text string) *parser {
+ return &parser{
+ at: 0,
+ ch: 0,
+ escapee: map[rune]string{
+ '"': `"`,
+ '\\': `\`,
+ '/': `/`,
+ 'b': "\b",
+ 'f': "\f",
+ 'n': "\n",
+ 'r': "\r",
+ 't': "\t",
+ },
+ text: text,
+ errors: []error{},
+ }
+}
+
+// See https://sourcegraph.com/github.com/elastic/kibana/-/blob/src/platform/packages/shared/kbn-monaco/src/languages/console/parser.js.
+func (p *parser) parse() ([]parsedRequest, error) {
+ if _, err := p.nextEmptyInput(); err != nil {
+ return nil, err
+ }
+ if err := p.multiRequest(); err != nil {
+ return nil, err
+ }
+ if err := p.white(); err != nil {
+ return nil, err
+ }
+ if p.ch != 0 {
+ return nil, errors.Errorf("Syntax error")
+ }
+ return p.requests, nil
+}
+
+func (p *parser) multiRequest() error {
+ for p.ch != 0 {
+ if err := p.white(); err != nil {
+ return err
+ }
+ if p.ch == 0 {
+ continue
+ }
+ if err := p.comment(); err != nil {
+ return err
+ }
+ if err := p.white(); err != nil {
+ return err
+ }
+ if p.ch == 0 {
+ continue
+ }
+ if err := p.request(); err != nil {
+ return err
+ }
+ if err := p.white(); err != nil {
+ return err
+ }
+ }
+ // TODO(zp): nextMatch.
+ return nil
+}
+
+func (p *parser) updateRequestEnd() error {
+ if p.at >= len(p.text) {
+ p.requestEndOffset = p.at - 1
+ return nil
+ }
+ previousRune, sz := utf8.DecodeLastRuneInString(p.text[:p.at])
+ if previousRune == utf8.RuneError {
+ if sz == 0 {
+ return errors.Errorf("unexpected empty input")
+ }
+ if sz == 1 {
+ return errors.Errorf("invalid UTF-8 character")
+ }
+ return errors.Errorf("unknown decoding rune error")
+ }
+ p.requestEndOffset = p.at - sz
+ return nil
+}
+
+func (p *parser) request() error {
+ if err := p.white(); err != nil {
+ return err
+ }
+ if err := p.addRequestStart(); err != nil {
+ return err
+ }
+ if _, err := p.method(); err != nil {
+ return err
+ }
+ if err := p.updateRequestEnd(); err != nil {
+ return err
+ }
+ if err := p.strictWhite(); err != nil {
+ return err
+ }
+ if _, err := p.url(); err != nil {
+ return err
+ }
+ if err := p.updateRequestEnd(); err != nil {
+ return err
+ }
+ // advance to one new line
+ if err := p.strictWhite(); err != nil {
+ return err
+ }
+ if err := p.newLine(); err != nil {
+ return err
+ }
+ if err := p.strictWhite(); err != nil {
+ return err
+ }
+ if p.ch == '{' {
+ if _, err := p.object(); err != nil {
+ return err
+ }
+ if err := p.updateRequestEnd(); err != nil {
+ return err
+ }
+ }
+ // multi doc request
+ // advance to one new line
+ if err := p.strictWhite(); err != nil {
+ return err
+ }
+ if err := p.newLine(); err != nil {
+ return err
+ }
+ if err := p.strictWhite(); err != nil {
+ return err
+ }
+ for p.ch == '{' {
+ // another object
+ if _, err := p.object(); err != nil {
+ return err
+ }
+ if err := p.updateRequestEnd(); err != nil {
+ return err
+ }
+ if err := p.strictWhite(); err != nil {
+ return err
+ }
+ if err := p.newLine(); err != nil {
+ return err
+ }
+ if err := p.strictWhite(); err != nil {
+ return err
+ }
+ }
+ return p.addRequestEnd()
+}
+
+func (p *parser) url() (string, error) {
+ url := ""
+ for p.ch != 0 && p.ch != '\n' {
+ url += string(p.ch)
+ if _, err := p.nextEmptyInput(); err != nil {
+ return "", err
+ }
+ }
+ if url == "" {
+ return "", errors.Errorf("Missing url")
+ }
+ return url, nil
+}
+
+func (p *parser) object() (map[string]any, error) {
+ key := ""
+ object := make(map[string]any)
+
+ if p.ch == '{' {
+ if _, err := p.next('{'); err != nil {
+ return nil, err
+ }
+ if err := p.white(); err != nil {
+ return nil, err
+ }
+ if p.ch == '}' {
+ if _, err := p.next('}'); err != nil {
+ return nil, err
+ }
+ // empty object
+ return object, nil
+ }
+ for p.ch != 0 {
+ var err error
+ key, err = p.string()
+ if err != nil {
+ return nil, err
+ }
+ if err := p.white(); err != nil {
+ return nil, err
+ }
+ if _, err := p.next(':'); err != nil {
+ return nil, err
+ }
+ if _, ok := object[key]; ok {
+ return nil, errors.Errorf("duplicate key '%s'", key)
+ }
+ v, err := p.value()
+ if err != nil {
+ return nil, err
+ }
+ object[key] = v
+ if err := p.white(); err != nil {
+ return nil, err
+ }
+ if p.ch == '}' {
+ if _, err := p.next('}'); err != nil {
+ return nil, err
+ }
+ return object, nil
+ }
+ if _, err := p.next(','); err != nil {
+ return nil, err
+ }
+ if err := p.white(); err != nil {
+ return nil, err
+ }
+ }
+ }
+ return nil, errors.Errorf("bad object")
+}
+
+func (p *parser) value() (any, error) {
+ if err := p.white(); err != nil {
+ return nil, err
+ }
+ switch p.ch {
+ case '{':
+ return p.object()
+ case '[':
+ return p.array()
+ case '"':
+ return p.string()
+ case '-':
+ return p.number()
+ default:
+ if p.ch >= '0' && p.ch <= '9' {
+ return p.number()
+ }
+ return p.word()
+ }
+}
+
+func (p *parser) word() (any, error) {
+ switch p.ch {
+ case 't':
+ if _, err := p.next('t'); err != nil {
+ return nil, err
+ }
+ if _, err := p.next('r'); err != nil {
+ return nil, err
+ }
+ if _, err := p.next('u'); err != nil {
+ return nil, err
+ }
+ if _, err := p.next('e'); err != nil {
+ return nil, err
+ }
+ case 'f':
+ if _, err := p.next('f'); err != nil {
+ return nil, err
+ }
+ if _, err := p.next('a'); err != nil {
+ return nil, err
+ }
+ if _, err := p.next('l'); err != nil {
+ return nil, err
+ }
+ if _, err := p.next('s'); err != nil {
+ return nil, err
+ }
+ if _, err := p.next('e'); err != nil {
+ return nil, err
+ }
+ return false, nil
+ case 'n':
+ if _, err := p.next('n'); err != nil {
+ return nil, err
+ }
+ if _, err := p.next('u'); err != nil {
+ return nil, err
+ }
+ if _, err := p.next('l'); err != nil {
+ return nil, err
+ }
+ if _, err := p.next('l'); err != nil {
+ return nil, err
+ }
+ return nil, nil
+ }
+ return nil, errors.Errorf("unexpected '%c'", p.ch)
+}
+
+func (p *parser) number() (float64, error) {
+ s := ""
+ if p.ch == '-' {
+ s = "-"
+ if _, err := p.next('-'); err != nil {
+ return 0, err
+ }
+ }
+ for p.ch >= '0' && p.ch <= '9' {
+ s += string(p.ch)
+ if _, err := p.nextEmptyInput(); err != nil {
+ return 0, err
+ }
+ }
+ if p.ch == '.' {
+ s += "."
+ for {
+ if _, err := p.nextEmptyInput(); err != nil {
+ return 0, err
+ }
+ if p.ch >= '0' && p.ch <= '9' {
+ s += string(p.ch)
+ } else {
+ break
+ }
+ }
+ }
+ if p.ch == 'e' || p.ch == 'E' {
+ s += string(p.ch)
+ if _, err := p.nextEmptyInput(); err != nil {
+ return 0, err
+ }
+ if p.ch == '+' || p.ch == '-' {
+ s += string(p.ch)
+ if _, err := p.nextEmptyInput(); err != nil {
+ return 0, err
+ }
+ }
+ for p.ch >= '0' && p.ch <= '9' {
+ s += string(p.ch)
+ if _, err := p.nextEmptyInput(); err != nil {
+ return 0, err
+ }
+ }
+ }
+ num, err := strconv.ParseFloat(s, 64)
+ if err != nil {
+ return 0, errors.Errorf("bad number")
+ }
+ return num, nil
+}
+
+func (p *parser) array() ([]any, error) {
+ var array []any
+ if p.ch == '[' {
+ if _, err := p.next('['); err != nil {
+ return nil, err
+ }
+ if err := p.white(); err != nil {
+ return nil, err
+ }
+ if p.ch == ']' {
+ if _, err := p.next(']'); err != nil {
+ return nil, err
+ }
+ // empty array
+ return array, nil
+ }
+ for p.ch != 0 {
+ var err error
+ v, err := p.value()
+ if err != nil {
+ return nil, err
+ }
+ array = append(array, v)
+ if err := p.white(); err != nil {
+ return nil, err
+ }
+ if p.ch == ']' {
+ if _, err := p.next(']'); err != nil {
+ return nil, err
+ }
+ return array, nil
+ }
+ if _, err := p.next(','); err != nil {
+ return nil, err
+ }
+ if err := p.white(); err != nil {
+ return nil, err
+ }
+ }
+ }
+ return nil, errors.Errorf("bad array")
+}
+
+func (p *parser) string() (string, error) {
+ s := ""
+ uffff := 0
+ if p.ch == '"' {
+ if p.peek(0) == '"' && p.peek(1) == '"' {
+ // literal
+ if _, err := p.next('"'); err != nil {
+ return "", err
+ }
+ if _, err := p.next('"'); err != nil {
+ return "", err
+ }
+ return p.nextUpTo(`"""`, `failed to find closing '"""'`)
+ }
+ for {
+ r, err := p.nextEmptyInput()
+ if err != nil {
+ return "", err
+ }
+ if r == 0 {
+ break
+ }
+ if p.ch == '"' {
+ if _, err := p.nextEmptyInput(); err != nil {
+ return "", err
+ }
+ return s, nil
+ } else if p.ch == '\\' {
+ if _, err := p.nextEmptyInput(); err != nil {
+ return "", err
+ }
+ if p.ch == 'u' {
+ uffff = 0
+ for i := 0; i < 4; i++ {
+ nextRune, err := p.nextEmptyInput()
+ if err != nil {
+ return "", err
+ }
+ // Parse next rune into hex.
+ hex, err := strconv.ParseUint(string(nextRune), 16, 32)
+ if err != nil {
+ break
+ }
+ uffff = (uffff << 4) + int(hex)
+ }
+ // Treat uffff as UTF-16 encoded rune.
+ s += string(rune(uffff))
+ } else if v, ok := p.escapee[p.ch]; ok {
+ s += v
+ } else {
+ break
+ }
+ } else {
+ s += string(p.ch)
+ }
+ }
+ }
+
+ return "", errors.Errorf("bad string")
+}
+
+func (p *parser) nextUpTo(upTo string, errorMessage string) (string, error) {
+ currentAt := p.at
+ i := strings.Index(p.text[p.at:], upTo)
+ if i < 0 {
+ if errorMessage != "" {
+ return "", errors.New(errorMessage)
+ }
+ return "", errors.Errorf("expected '%s'", upTo)
+ }
+ i += currentAt
+ if err := p.reset(i + len(upTo)); err != nil {
+ return "", err
+ }
+ return p.text[currentAt:i], nil
+}
+
+func (p *parser) reset(newAt int) error {
+ ch, sz := utf8.DecodeRuneInString(p.text[newAt:])
+ if ch == utf8.RuneError {
+ if sz == 0 {
+ return errors.Errorf("unexpected empty input")
+ }
+ if sz == 1 {
+ return errors.Errorf("invalid UTF-8 character")
+ }
+ return errors.Errorf("unknown decoding rune error")
+ }
+ p.ch = ch
+ p.at = newAt + sz
+ return nil
+}
+
+func (p *parser) newLine() error {
+ if p.ch == '\n' {
+ if _, err := p.nextEmptyInput(); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (p *parser) strictWhite() error {
+ for p.ch != 0 && (p.ch == ' ' || p.ch == '\t') {
+ if _, err := p.nextEmptyInput(); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (p *parser) nextOneOf(rs []rune) (rune, error) {
+ if !includes(rs, p.ch) {
+ return 0, errors.Errorf("expected one of %+v instead of '%c'", rs, p.ch)
+ }
+ ch, sz := utf8.DecodeRuneInString(p.text[p.at:])
+ if ch == utf8.RuneError {
+ if sz == 0 {
+ return 0, errors.Errorf("unexpected empty input")
+ }
+ if sz == 1 {
+ return 0, errors.Errorf("invalid UTF-8 character")
+ }
+ return 0, errors.Errorf("unknown decoding rune error")
+ }
+ p.ch = ch
+ p.at += sz
+ return ch, nil
+}
+
+func (p *parser) method() (string, error) {
+ uppercase := strings.ToUpper(string(p.ch))
+ switch uppercase {
+ case "G":
+ if _, err := p.nextOneOf([]rune{'G', 'g'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'E', 'e'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'T', 't'}); err != nil {
+ return "", err
+ }
+ return "GET", nil
+ case "H":
+ if _, err := p.nextOneOf([]rune{'H', 'h'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'E', 'e'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'A', 'a'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'D', 'd'}); err != nil {
+ return "", err
+ }
+ return "HEAD", nil
+ case "D":
+ if _, err := p.nextOneOf([]rune{'D', 'd'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'E', 'e'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'L', 'l'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'E', 'e'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'T', 't'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'E', 'e'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'S', 's'}); err != nil {
+ return "", err
+ }
+ return "DELETE", nil
+ case "P":
+ if _, err := p.nextOneOf([]rune{'P', 'p'}); err != nil {
+ return "", err
+ }
+ nextUppercase := strings.ToUpper(string(p.ch))
+ switch nextUppercase {
+ case "A":
+ if _, err := p.nextOneOf([]rune{'A', 'a'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'T', 't'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'C', 'c'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'H', 'h'}); err != nil {
+ return "", err
+ }
+ return "PATCH", nil
+ case "U":
+ if _, err := p.nextOneOf([]rune{'U', 'u'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'T', 't'}); err != nil {
+ return "", err
+ }
+ return "PUT", nil
+ case "O":
+ if _, err := p.nextOneOf([]rune{'O', 'o'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'S', 's'}); err != nil {
+ return "", err
+ }
+ if _, err := p.nextOneOf([]rune{'T', 't'}); err != nil {
+ return "", err
+ }
+ return "POST", nil
+ default:
+ return "", errors.Errorf("unexpected '%c'", p.ch)
+ }
+ default:
+ return "", errors.Errorf("expected one of GET/POST/PUT/DELETE/HEAD/PATCH")
+ }
+}
+
+func (p *parser) addRequestStart() error {
+ previousRune, sz := utf8.DecodeLastRuneInString(p.text[:p.at])
+ if previousRune == utf8.RuneError {
+ if sz == 0 {
+ return errors.Errorf("unexpected empty input")
+ }
+ if sz == 1 {
+ return errors.Errorf("invalid UTF-8 character")
+ }
+ return errors.Errorf("unknown decoding rune error")
+ }
+ p.requestStartOffset = p.at - sz
+ p.requests = append(p.requests, parsedRequest{
+ startOffset: p.requestStartOffset,
+ })
+ return nil
+}
+
+func (p *parser) addRequestEnd() error {
+ if len(p.requests) == 0 {
+ return errors.Errorf("unexpected empty requests")
+ }
+ p.requests[len(p.requests)-1].endOffset = p.requestEndOffset
+ return nil
+}
+
+func (p *parser) comment() error {
+ for p.ch == '#' {
+ for p.ch != 0 && p.ch != '\n' {
+ if _, err := p.nextEmptyInput(); err != nil {
+ return err
+ }
+ }
+ if err := p.white(); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (p *parser) peek(offset uint) rune {
+ var peekCh rune
+ for i := uint(0); i <= offset; i++ {
+ peekCh, sz := utf8.DecodeRuneInString(p.text[p.at:])
+ if peekCh == utf8.RuneError {
+ if sz == 0 {
+ return 0
+ }
+ if sz == 1 {
+ return 0
+ }
+ return 0
+ }
+ }
+ return peekCh
+}
+
+func (p *parser) white() error {
+ for p.ch != 0 {
+ // Skip whitespace.
+ for p.ch != 0 && p.ch <= ' ' {
+ if _, err := p.nextEmptyInput(); err != nil {
+ return err
+ }
+ }
+
+ // if the current rune in iteration is '#' or the rune and the next rune is equal to '//'
+ // we are on the single line comment.
+ if p.ch == '#' || (p.ch == '/' && p.peek(0) == '/') {
+ // Until we are on the new line, skip to the next char.
+ for p.ch != 0 && p.ch != '\n' {
+ if _, err := p.nextEmptyInput(); err != nil {
+ return err
+ }
+ }
+ } else if p.ch == '/' && p.peek(0) == '*' {
+ // If the chars starts with '/*', we are on the multiline comment.
+ if _, err := p.nNextEmptyInput(2); err != nil {
+ return err
+ }
+ for p.ch != 0 && (p.ch != '*' || p.peek(0) != '/') {
+ // Until we have closing tags '*', skip to the next char.
+ if _, err := p.nextEmptyInput(); err != nil {
+ return err
+ }
+ }
+ if p.ch != 0 {
+ if _, err := p.nNextEmptyInput(2); err != nil {
+ return err
+ }
+ }
+ } else {
+ break
+ }
+ }
+
+ return nil
+}
+
+func (p *parser) next(c rune) (rune, error) {
+ if c != p.ch {
+ return 0, errors.Errorf("expected '%c' instead of '%c'", c, p.ch)
+ }
+
+ return p.nextEmptyInput()
+}
+
+func (p *parser) nextEmptyInput() (rune, error) {
+ if p.at >= len(p.text) {
+ // EOF
+ p.at++
+ p.ch = 0
+ return 0, nil
+ }
+ nextCh, sz := utf8.DecodeRuneInString(p.text[p.at:])
+ if nextCh == utf8.RuneError {
+ if sz == 0 {
+ return 0, errors.Errorf("unexpected empty input")
+ }
+ if sz == 1 {
+ return 0, errors.Errorf("invalid UTF-8 character")
+ }
+ return 0, errors.Errorf("unknown decoding rune error")
+ }
+ p.ch = nextCh
+
+ p.at += sz
+ return nextCh, nil
+}
+
+// call p.nextEmptyInput n times and return the last rune.
+func (p *parser) nNextEmptyInput(n int) (rune, error) {
+ var lastRune rune
+ var err error
+ for i := 0; i < n; i++ {
+ if lastRune, err = p.nextEmptyInput(); err != nil {
+ return 0, err
+ }
+ }
+ return lastRune, nil
+}
+
+func includes[T rune](s []T, e T) bool {
+ for _, v := range s {
+ if v == e {
+ return true
+ }
+ }
+ return false
+}
diff --git a/backend/plugin/parser/elasticsearch/parser_test.go b/backend/plugin/parser/elasticsearch/parser_test.go
new file mode 100644
index 0000000000..0118292d0d
--- /dev/null
+++ b/backend/plugin/parser/elasticsearch/parser_test.go
@@ -0,0 +1,428 @@
+package elasticsearch
+
+import (
+ "io"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "gopkg.in/yaml.v3"
+)
+
+func TestParseElasticsearchREST(t *testing.T) {
+ type testCase struct {
+ Description string `yaml:"description,omitempty"`
+ Statement string `yaml:"statement,omitempty"`
+ Result []*ParseResult `yaml:"result,omitempty"`
+ }
+
+ var (
+ filepath = "test-data/parse-elasticsearch-rest.yaml"
+ record = false
+ )
+
+ a := require.New(t)
+ yamlFile, err := os.Open(filepath)
+ a.NoError(err)
+ byteValue, err := io.ReadAll(yamlFile)
+ a.NoError(err)
+ a.NoError(yamlFile.Close())
+
+ var testCases []testCase
+ a.NoError(yaml.Unmarshal(byteValue, &testCases))
+
+ for i, tc := range testCases {
+ got, err := ParseElasticsearchREST(tc.Statement)
+ a.NoErrorf(err, "description: %s", tc.Description)
+ if record {
+ testCases[i].Result = got
+ } else {
+ a.Equalf(tc.Result, got, "description: %s", tc.Description)
+ }
+ }
+
+ if record {
+ byteValue, err := yaml.Marshal(testCases)
+ a.NoError(err)
+ err = os.WriteFile(filepath, byteValue, 0644)
+ a.NoError(err)
+ }
+}
+
+func TestParse(t *testing.T) {
+ // See https://sourcegraph.com/github.com/elastic/kibana/-/blob/src/platform/packages/shared/kbn-monaco/src/languages/console/parser.test.ts.
+ testCases := []struct {
+ description string
+ input string
+ got []parsedRequest
+ }{
+ {
+ description: "returns parsedRequests if the input is correct",
+ input: "GET _search",
+ got: []parsedRequest{
+ {
+ startOffset: 0,
+ endOffset: 11,
+ },
+ },
+ },
+ {
+ description: "parses several requests",
+ input: `GET _search
+POST _test_index`,
+ got: []parsedRequest{
+ {
+ startOffset: 0,
+ endOffset: 11,
+ },
+ {
+ startOffset: 12,
+ endOffset: 28,
+ },
+ },
+ },
+ {
+ description: "parses a request with a request body",
+ input: `GET _search
+{
+ "query": {
+ "match_all": {}
+ }
+}`,
+ got: []parsedRequest{
+ {
+ startOffset: 0,
+ endOffset: 52,
+ },
+ },
+ },
+ {
+ description: "allows upper case methods",
+ input: "GET _search\nPOST _search\nPATCH _search\nPUT _search\nHEAD _search",
+ got: []parsedRequest{
+ {
+ startOffset: 0,
+ endOffset: 11,
+ },
+ {
+ startOffset: 12,
+ endOffset: 24,
+ },
+ {
+ startOffset: 25,
+ endOffset: 38,
+ },
+ {
+ startOffset: 39,
+ endOffset: 50,
+ },
+ {
+ startOffset: 51,
+ endOffset: 63,
+ },
+ },
+ },
+ {
+ description: "allows lower case methods",
+ input: "get _search\npost _search\npatch _search\nput _search\nhead _search",
+ got: []parsedRequest{
+ {
+ startOffset: 0,
+ endOffset: 11,
+ },
+ {
+ startOffset: 12,
+ endOffset: 24,
+ },
+ {
+ startOffset: 25,
+ endOffset: 38,
+ },
+ {
+ startOffset: 39,
+ endOffset: 50,
+ },
+ {
+ startOffset: 51,
+ endOffset: 63,
+ },
+ },
+ },
+ {
+ description: "allows mixed case methods",
+ input: "GeT _search\npOSt _search\nPaTch _search\nPut _search\nheAD _search",
+ got: []parsedRequest{
+ {
+ startOffset: 0,
+ endOffset: 11,
+ },
+ {
+ startOffset: 12,
+ endOffset: 24,
+ },
+ {
+ startOffset: 25,
+ endOffset: 38,
+ },
+ {
+ startOffset: 39,
+ endOffset: 50,
+ },
+ {
+ startOffset: 51,
+ endOffset: 63,
+ },
+ },
+ },
+ }
+
+ a := require.New(t)
+ for _, tc := range testCases {
+ p := newParser(tc.input)
+ got, err := p.parse()
+ require.NoError(t, err)
+ a.Equal(tc.got, got, "description: %s", tc.description)
+ }
+}
+
+func TestGetEditorRequest(t *testing.T) {
+ testCases := []struct {
+ description string
+ content []string
+ adjustedParsedRequest adjustedParsedRequest
+ want *editorRequest
+ }{
+ {
+ description: "cleans up any text following the url",
+ content: []string{"GET _search // inline comment"},
+ adjustedParsedRequest: adjustedParsedRequest{
+ startLineNumber: 0,
+ endLineNumber: 0,
+ },
+ want: &editorRequest{
+ method: "GET",
+ url: "_search",
+ data: nil,
+ },
+ },
+ {
+ description: "doesn't incorrectly removes parts of url params that include whitespaces",
+ content: []string{`GET _search?query="test test"`},
+ adjustedParsedRequest: adjustedParsedRequest{
+ startLineNumber: 0,
+ endLineNumber: 0,
+ },
+ want: &editorRequest{
+ method: "GET",
+ url: `_search?query="test test"`,
+ data: nil,
+ },
+ },
+ {
+ description: "correctly includes the request body",
+ content: []string{
+ "GET _search",
+ "{",
+ " \"query\": {}",
+ "}",
+ },
+ adjustedParsedRequest: adjustedParsedRequest{
+ startLineNumber: 0,
+ endLineNumber: 3,
+ },
+ want: &editorRequest{
+ method: "GET",
+ url: `_search`,
+ data: []string{
+ "{\n \"query\": {}\n}",
+ },
+ },
+ },
+ {
+ description: "correctly handles nested braces",
+ content: []string{
+ "GET _search",
+ "{",
+ ` "query": "{a} {b}"`,
+ "}",
+ "{",
+ ` "query": {}`,
+ "}",
+ },
+ adjustedParsedRequest: adjustedParsedRequest{
+ startLineNumber: 0,
+ endLineNumber: 6,
+ },
+ want: &editorRequest{
+ method: "GET",
+ url: `_search`,
+ data: []string{
+ "{\n \"query\": \"{a} {b}\"\n}",
+ "{\n \"query\": {}\n}",
+ },
+ },
+ },
+ {
+ description: "works for several request bodies",
+ content: []string{
+ "GET _search",
+ "{",
+ ` "query": {}`,
+ "}",
+ "{",
+ ` "query": {}`,
+ "}",
+ },
+ adjustedParsedRequest: adjustedParsedRequest{
+ startLineNumber: 0,
+ endLineNumber: 6,
+ },
+ want: &editorRequest{
+ method: "GET",
+ url: `_search`,
+ data: []string{
+ "{\n \"query\": {}\n}",
+ "{\n \"query\": {}\n}",
+ },
+ },
+ },
+ {
+ description: "splits several json objects",
+ content: []string{
+ "GET _search",
+ `{"query":"test"}`,
+ `{`,
+ ` "query": "test"`,
+ `}`,
+ `{"query":"test"}`,
+ },
+ adjustedParsedRequest: adjustedParsedRequest{
+ startLineNumber: 0,
+ endLineNumber: 5,
+ },
+ want: &editorRequest{
+ method: "GET",
+ url: `_search`,
+ data: []string{
+ `{"query":"test"}`,
+ "{\n \"query\": \"test\"\n}",
+ `{"query":"test"}`,
+ },
+ },
+ },
+ {
+ description: "works for invalid json objects",
+ content: []string{
+ "GET _search",
+ `{"query":"test"}`,
+ `{`,
+ ` "query":`,
+ `{`,
+ },
+ adjustedParsedRequest: adjustedParsedRequest{
+ startLineNumber: 0,
+ endLineNumber: 4,
+ },
+ want: &editorRequest{
+ method: "GET",
+ url: `_search`,
+ data: []string{
+ `{"query":"test"}`,
+ "{\n \"query\":\n{",
+ },
+ },
+ },
+ }
+
+ a := require.New(t)
+ for _, tc := range testCases {
+ got := getEditorRequest(strings.Join(tc.content, "\n"), tc.adjustedParsedRequest)
+ a.Equal(tc.want, got, "description: %s", tc.description)
+ }
+}
+
+func TestContainsComments(t *testing.T) {
+ testCases := []struct {
+ description string
+ input string
+ want bool
+ }{
+ {
+ description: "should return false for JSON with // and /* inside strings",
+ input: `{
+ "docs": [
+ {
+ "_source": {
+ "trace": {
+ "name": "GET /actuator/health/**"
+ },
+ "transaction": {
+ "outcome": "success"
+ }
+ }
+ },
+ {
+ "_source": {
+ "vulnerability": {
+ "reference": [
+ "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-15778"
+ ]
+ }
+ }
+ }
+ ]
+ }`,
+ want: false,
+ },
+ {
+ description: "should return true for text with actual line comment",
+ input: `{
+ // This is a comment
+ "query": { "match_all": {} }
+ }`,
+ want: true,
+ },
+ {
+ description: "should return true for text with actual block comment",
+ input: `{
+ /* Bulk insert */
+ "index": { "_index": "test" },
+ "field1": "value1"
+ }`,
+ want: true,
+ },
+ {
+ description: "should return false for text without any comments",
+ input: `{
+ "field": "value"
+ }`,
+ want: false,
+ },
+ {
+ description: "should return false for empty string",
+ input: ``,
+ want: false,
+ },
+ {
+ description: "should correctly handle escaped quotes within strings",
+ input: `{
+ "field": \"value with \\\"escaped quotes\\\"\"
+ }`,
+ want: false,
+ },
+ {
+ description: "should return true if comment is outside of strings",
+ input: `{
+ "field": "value" // comment here
+ }`,
+ want: true,
+ },
+ }
+
+ a := require.New(t)
+ for _, tc := range testCases {
+ got := containsComments(tc.input)
+ a.Equal(tc.want, got, "description: %s", tc.description)
+ }
+}
diff --git a/backend/plugin/parser/elasticsearch/test-data/parse-elasticsearch-rest.yaml b/backend/plugin/parser/elasticsearch/test-data/parse-elasticsearch-rest.yaml
new file mode 100644
index 0000000000..19c61c344e
--- /dev/null
+++ b/backend/plugin/parser/elasticsearch/test-data/parse-elasticsearch-rest.yaml
@@ -0,0 +1,122 @@
+- description: simple
+ statement: GET _search
+ result:
+ - request:
+ method: GET
+ url: _search
+ startoffset: 0
+ endoffset: 11
+- description: several requests
+ statement: |-
+ GET _search
+ POST _test_index
+ result:
+ - request:
+ method: GET
+ url: _search
+ startoffset: 0
+ endoffset: 11
+ - request:
+ method: POST
+ url: _test_index
+ startoffset: 12
+ endoffset: 28
+- description: parses a request with a request body
+ statement: |-
+ GET _search
+ {
+ "query": {
+ "match_all": {}
+ }
+ }
+ result:
+ - request:
+ method: GET
+ url: _search
+ data:
+ - |-
+ {
+ "query": {
+ "match_all": {}
+ }
+ }
+ startoffset: 0
+ endoffset: 52
+- description: multiple request
+ statement: |-
+ GET _search
+ {
+ "query": {
+ "match_all": {}
+ }
+ }
+
+ GET _search
+ {
+ "query": {
+ "match_all": {}
+ }
+ }
+
+
+ GET _search
+ {
+ "query": {
+ "match_all": {}
+ }
+ }
+ GET _search
+ {
+ "query": {
+ "match_all": {}
+ }
+ }
+ result:
+ - request:
+ method: GET
+ url: _search
+ data:
+ - |-
+ {
+ "query": {
+ "match_all": {}
+ }
+ }
+ startoffset: 0
+ endoffset: 52
+ - request:
+ method: GET
+ url: _search
+ data:
+ - |-
+ {
+ "query": {
+ "match_all": {}
+ }
+ }
+ startoffset: 54
+ endoffset: 106
+ - request:
+ method: GET
+ url: _search
+ data:
+ - |-
+ {
+ "query": {
+ "match_all": {}
+ }
+ }
+ startoffset: 109
+ endoffset: 161
+ - request:
+ method: GET
+ url: _search
+ data:
+ - |-
+ {
+ "query": {
+ "match_all": {}
+ }
+ }
+ startoffset: 162
+ endoffset: 214
diff --git a/go.mod b/go.mod
index 8327d12e2e..17c7391d1d 100644
--- a/go.mod
+++ b/go.mod
@@ -307,6 +307,7 @@ require (
github.com/googleapis/gax-go/v2 v2.14.1 // indirect
github.com/gosimple/unidecode v1.0.1 // indirect
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect
+ github.com/hjson/hjson-go/v4 v4.4.0
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
diff --git a/go.sum b/go.sum
index 425af9e7d9..d9e5c0eac0 100644
--- a/go.sum
+++ b/go.sum
@@ -1393,6 +1393,8 @@ github.com/hashicorp/vault/api v1.16.0 h1:nbEYGJiAPGzT9U4oWgaaB0g+Rj8E59QuHKyA5L
github.com/hashicorp/vault/api v1.16.0/go.mod h1:KhuUhzOD8lDSk29AtzNjgAu2kxRA9jL9NAbkFlqvkBA=
github.com/hashicorp/vault/api/auth/approle v0.9.0 h1:FdpspwGVWnGiWmAxd5L1Yd+T+fX2kYnyAIvI5oGdvNs=
github.com/hashicorp/vault/api/auth/approle v0.9.0/go.mod h1:fvtJhBs3AYMs2fXk4U5+u+7unhUGuboiKzFpLPpIazw=
+github.com/hjson/hjson-go/v4 v4.4.0 h1:D/NPvqOCH6/eisTb5/ztuIS8GUvmpHaLOcNk1Bjr298=
+github.com/hjson/hjson-go/v4 v4.4.0/go.mod h1:KaYt3bTw3zhBjYqnXkYywcYctk0A2nxeEFTse3rH13E=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/huandu/xstrings v1.3.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg=