From e3eb569b8133ceb92be873fe45a9f47cf1aa541e Mon Sep 17 00:00:00 2001 From: dobarx Date: Wed, 3 Apr 2024 16:41:45 +0300 Subject: [PATCH] elastic: use cty/json marshal --- .../elastic/data_elastic_security_cases_test.go | 2 +- internal/elastic/plugin.go | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/internal/elastic/data_elastic_security_cases_test.go b/internal/elastic/data_elastic_security_cases_test.go index c24831f5..3cf62e26 100644 --- a/internal/elastic/data_elastic_security_cases_test.go +++ b/internal/elastic/data_elastic_security_cases_test.go @@ -29,7 +29,7 @@ func TestReportsDataSourceTestSuite(t *testing.T) { func (s *ReportsDataSourceTestSuite) SetupSuite() { s.schema = makeElasticSecurityCasesDataSource(func(url string, apiKey *string) kbclient.Client { s.storedUrl = url - s.storedApiKey = *&apiKey + s.storedApiKey = apiKey return s.cli }) s.ctx = context.Background() diff --git a/internal/elastic/plugin.go b/internal/elastic/plugin.go index fe19fa4b..81c453e2 100644 --- a/internal/elastic/plugin.go +++ b/internal/elastic/plugin.go @@ -10,6 +10,7 @@ import ( es "github.com/elastic/go-elasticsearch/v8" "github.com/elastic/go-elasticsearch/v8/esapi" "github.com/zclconf/go-cty/cty" + ctyjson "github.com/zclconf/go-cty/cty/json" "github.com/blackstork-io/fabric/internal/elastic/kbclient" "github.com/blackstork-io/fabric/plugin" @@ -133,10 +134,19 @@ func search(fn esapi.Search, args cty.Value) (plugin.Data, error) { } body := map[string]any{} if query := args.GetAttr("query"); !query.IsNull() { - body["query"] = query.AsValueMap() + raw, err := ctyjson.Marshal(query, query.Type()) + if err != nil { + return nil, fmt.Errorf("failed to marshal query: %s", err) + } + body["query"] = json.RawMessage(raw) + } if aggs := args.GetAttr("aggs"); !aggs.IsNull() { - body["aggs"] = aggs.AsValueMap() + raw, err := ctyjson.Marshal(aggs, aggs.Type()) + if err != nil { + return nil, fmt.Errorf("failed to marshal aggs: %s", err) + } + body["aggs"] = json.RawMessage(raw) } if len(body) > 0 { rawBody, err := json.Marshal(body) @@ -147,7 +157,7 @@ func search(fn esapi.Search, args cty.Value) (plugin.Data, error) { } if size := args.GetAttr("size"); !size.IsNull() { n, _ := size.AsBigFloat().Int64() - if n <= 0 { + if n < 0 { return nil, fmt.Errorf("size must be greater than 0") } opts = append(opts, fn.WithSize(int(n)))