diff --git a/.apigentools-info b/.apigentools-info index ccc8f3e45ba..fbc599db717 100644 --- a/.apigentools-info +++ b/.apigentools-info @@ -4,13 +4,13 @@ "spec_versions": { "v1": { "apigentools_version": "1.6.6", - "regenerated": "2024-06-26 17:58:27.325217", - "spec_repo_commit": "bad4ef97" + "regenerated": "2024-06-26 20:44:46.006545", + "spec_repo_commit": "d588dddf" }, "v2": { "apigentools_version": "1.6.6", - "regenerated": "2024-06-26 17:58:27.343333", - "spec_repo_commit": "bad4ef97" + "regenerated": "2024-06-26 20:44:46.025733", + "spec_repo_commit": "d588dddf" } } } \ No newline at end of file diff --git a/.generator/schemas/v2/openapi.yaml b/.generator/schemas/v2/openapi.yaml index 0a3339c1540..5f143cc2dd1 100644 --- a/.generator/schemas/v2/openapi.yaml +++ b/.generator/schemas/v2/openapi.yaml @@ -17373,6 +17373,18 @@ components: required: - status type: object + SecurityMonitoringRuleConvertPayload: + description: Convert a rule from JSON to Terraform. + oneOf: + - $ref: '#/components/schemas/SecurityMonitoringStandardRulePayload' + - $ref: '#/components/schemas/SecurityMonitoringSignalRulePayload' + SecurityMonitoringRuleConvertResponse: + description: Result of the convert rule request containing Terraform content. + properties: + terraformContent: + description: Terraform string as a result of converting the rule from JSON. + type: string + type: object SecurityMonitoringRuleCreatePayload: description: Create a new rule. oneOf: @@ -33152,6 +33164,42 @@ paths: tags: - Security Monitoring x-codegen-request-body-name: body + /api/v2/security_monitoring/rules/convert: + post: + description: Convert a rule that doesn't (yet) exist from JSON to Terraform. + operationId: ConvertSecurityMonitoringRuleFromJSONToTerraform + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/SecurityMonitoringRuleConvertPayload' + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/SecurityMonitoringRuleConvertResponse' + description: OK + '400': + $ref: '#/components/responses/BadRequestResponse' + '401': + $ref: '#/components/responses/ConcurrentModificationResponse' + '403': + $ref: '#/components/responses/NotAuthorizedResponse' + '404': + $ref: '#/components/responses/NotFoundResponse' + '429': + $ref: '#/components/responses/TooManyRequestsResponse' + security: + - apiKeyAuth: [] + appKeyAuth: [] + - AuthZ: + - security_monitoring_rules_write + summary: Convert a rule from JSON to Terraform + tags: + - Security Monitoring + x-codegen-request-body-name: body /api/v2/security_monitoring/rules/test: post: description: Test a rule. @@ -33309,6 +33357,35 @@ paths: tags: - Security Monitoring x-codegen-request-body-name: body + /api/v2/security_monitoring/rules/{rule_id}/convert: + get: + description: Convert an existing rule from JSON to Terraform. + operationId: ConvertExistingSecurityMonitoringRule + parameters: + - $ref: '#/components/parameters/SecurityMonitoringRuleID' + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/SecurityMonitoringRuleConvertResponse' + description: OK + '400': + $ref: '#/components/responses/BadRequestResponse' + '403': + $ref: '#/components/responses/NotAuthorizedResponse' + '404': + $ref: '#/components/responses/NotFoundResponse' + '429': + $ref: '#/components/responses/TooManyRequestsResponse' + security: + - apiKeyAuth: [] + appKeyAuth: [] + - AuthZ: + - security_monitoring_rules_read + summary: Convert an existing rule from JSON to Terraform + tags: + - Security Monitoring /api/v2/security_monitoring/rules/{rule_id}/test: post: description: Test an existing rule. diff --git a/api/datadogV2/api_security_monitoring.go b/api/datadogV2/api_security_monitoring.go index b9262be9b73..adb8bb0d72f 100644 --- a/api/datadogV2/api_security_monitoring.go +++ b/api/datadogV2/api_security_monitoring.go @@ -19,6 +19,150 @@ import ( // SecurityMonitoringApi service type type SecurityMonitoringApi datadog.Service +// ConvertExistingSecurityMonitoringRule Convert an existing rule from JSON to Terraform. +// Convert an existing rule from JSON to Terraform. +func (a *SecurityMonitoringApi) ConvertExistingSecurityMonitoringRule(ctx _context.Context, ruleId string) (SecurityMonitoringRuleConvertResponse, *_nethttp.Response, error) { + var ( + localVarHTTPMethod = _nethttp.MethodGet + localVarPostBody interface{} + localVarReturnValue SecurityMonitoringRuleConvertResponse + ) + + localBasePath, err := a.Client.Cfg.ServerURLWithContext(ctx, "v2.SecurityMonitoringApi.ConvertExistingSecurityMonitoringRule") + if err != nil { + return localVarReturnValue, nil, datadog.GenericOpenAPIError{ErrorMessage: err.Error()} + } + + localVarPath := localBasePath + "/api/v2/security_monitoring/rules/{rule_id}/convert" + localVarPath = strings.Replace(localVarPath, "{"+"rule_id"+"}", _neturl.PathEscape(datadog.ParameterToString(ruleId, "")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := _neturl.Values{} + localVarFormParams := _neturl.Values{} + localVarHeaderParams["Accept"] = "application/json" + + datadog.SetAuthKeys( + ctx, + &localVarHeaderParams, + [2]string{"apiKeyAuth", "DD-API-KEY"}, + [2]string{"appKeyAuth", "DD-APPLICATION-KEY"}, + ) + req, err := a.Client.PrepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, nil) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.Client.CallAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := datadog.ReadBody(localVarHTTPResponse) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := datadog.GenericOpenAPIError{ + ErrorBody: localVarBody, + ErrorMessage: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 400 || localVarHTTPResponse.StatusCode == 403 || localVarHTTPResponse.StatusCode == 404 || localVarHTTPResponse.StatusCode == 429 { + var v APIErrorResponse + err = a.Client.Decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.ErrorModel = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.Client.Decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := datadog.GenericOpenAPIError{ + ErrorBody: localVarBody, + ErrorMessage: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +// ConvertSecurityMonitoringRuleFromJSONToTerraform Convert a rule from JSON to Terraform. +// Convert a rule that doesn't (yet) exist from JSON to Terraform. +func (a *SecurityMonitoringApi) ConvertSecurityMonitoringRuleFromJSONToTerraform(ctx _context.Context, body SecurityMonitoringRuleConvertPayload) (SecurityMonitoringRuleConvertResponse, *_nethttp.Response, error) { + var ( + localVarHTTPMethod = _nethttp.MethodPost + localVarPostBody interface{} + localVarReturnValue SecurityMonitoringRuleConvertResponse + ) + + localBasePath, err := a.Client.Cfg.ServerURLWithContext(ctx, "v2.SecurityMonitoringApi.ConvertSecurityMonitoringRuleFromJSONToTerraform") + if err != nil { + return localVarReturnValue, nil, datadog.GenericOpenAPIError{ErrorMessage: err.Error()} + } + + localVarPath := localBasePath + "/api/v2/security_monitoring/rules/convert" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := _neturl.Values{} + localVarFormParams := _neturl.Values{} + localVarHeaderParams["Content-Type"] = "application/json" + localVarHeaderParams["Accept"] = "application/json" + + // body params + localVarPostBody = &body + datadog.SetAuthKeys( + ctx, + &localVarHeaderParams, + [2]string{"apiKeyAuth", "DD-API-KEY"}, + [2]string{"appKeyAuth", "DD-APPLICATION-KEY"}, + ) + req, err := a.Client.PrepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, nil) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.Client.CallAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := datadog.ReadBody(localVarHTTPResponse) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := datadog.GenericOpenAPIError{ + ErrorBody: localVarBody, + ErrorMessage: localVarHTTPResponse.Status, + } + if localVarHTTPResponse.StatusCode == 400 || localVarHTTPResponse.StatusCode == 401 || localVarHTTPResponse.StatusCode == 403 || localVarHTTPResponse.StatusCode == 404 || localVarHTTPResponse.StatusCode == 429 { + var v APIErrorResponse + err = a.Client.Decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, newErr + } + newErr.ErrorModel = v + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.Client.Decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := datadog.GenericOpenAPIError{ + ErrorBody: localVarBody, + ErrorMessage: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + // CreateSecurityFilter Create a security filter. // Create a security filter. // diff --git a/api/datadogV2/doc.go b/api/datadogV2/doc.go index d98f3333db8..b60b3ae68e8 100644 --- a/api/datadogV2/doc.go +++ b/api/datadogV2/doc.go @@ -242,6 +242,8 @@ // - [RolesApi.RemovePermissionFromRole] // - [RolesApi.RemoveUserFromRole] // - [RolesApi.UpdateRole] +// - [SecurityMonitoringApi.ConvertExistingSecurityMonitoringRule] +// - [SecurityMonitoringApi.ConvertSecurityMonitoringRuleFromJSONToTerraform] // - [SecurityMonitoringApi.CreateSecurityFilter] // - [SecurityMonitoringApi.CreateSecurityMonitoringRule] // - [SecurityMonitoringApi.CreateSecurityMonitoringSuppression] diff --git a/api/datadogV2/model_security_monitoring_rule_convert_payload.go b/api/datadogV2/model_security_monitoring_rule_convert_payload.go new file mode 100644 index 00000000000..d2438eca736 --- /dev/null +++ b/api/datadogV2/model_security_monitoring_rule_convert_payload.go @@ -0,0 +1,105 @@ +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2019-Present Datadog, Inc. + +package datadogV2 + +import ( + "github.com/DataDog/datadog-api-client-go/v2/api/datadog" +) + +// SecurityMonitoringRuleConvertPayload - Convert a rule from JSON to Terraform. +type SecurityMonitoringRuleConvertPayload struct { + SecurityMonitoringStandardRulePayload *SecurityMonitoringStandardRulePayload + SecurityMonitoringSignalRulePayload *SecurityMonitoringSignalRulePayload + + // UnparsedObject contains the raw value of the object if there was an error when deserializing into the struct + UnparsedObject interface{} +} + +// SecurityMonitoringStandardRulePayloadAsSecurityMonitoringRuleConvertPayload is a convenience function that returns SecurityMonitoringStandardRulePayload wrapped in SecurityMonitoringRuleConvertPayload. +func SecurityMonitoringStandardRulePayloadAsSecurityMonitoringRuleConvertPayload(v *SecurityMonitoringStandardRulePayload) SecurityMonitoringRuleConvertPayload { + return SecurityMonitoringRuleConvertPayload{SecurityMonitoringStandardRulePayload: v} +} + +// SecurityMonitoringSignalRulePayloadAsSecurityMonitoringRuleConvertPayload is a convenience function that returns SecurityMonitoringSignalRulePayload wrapped in SecurityMonitoringRuleConvertPayload. +func SecurityMonitoringSignalRulePayloadAsSecurityMonitoringRuleConvertPayload(v *SecurityMonitoringSignalRulePayload) SecurityMonitoringRuleConvertPayload { + return SecurityMonitoringRuleConvertPayload{SecurityMonitoringSignalRulePayload: v} +} + +// UnmarshalJSON turns data into one of the pointers in the struct. +func (obj *SecurityMonitoringRuleConvertPayload) UnmarshalJSON(data []byte) error { + var err error + match := 0 + // try to unmarshal data into SecurityMonitoringStandardRulePayload + err = datadog.Unmarshal(data, &obj.SecurityMonitoringStandardRulePayload) + if err == nil { + if obj.SecurityMonitoringStandardRulePayload != nil && obj.SecurityMonitoringStandardRulePayload.UnparsedObject == nil { + jsonSecurityMonitoringStandardRulePayload, _ := datadog.Marshal(obj.SecurityMonitoringStandardRulePayload) + if string(jsonSecurityMonitoringStandardRulePayload) == "{}" { // empty struct + obj.SecurityMonitoringStandardRulePayload = nil + } else { + match++ + } + } else { + obj.SecurityMonitoringStandardRulePayload = nil + } + } else { + obj.SecurityMonitoringStandardRulePayload = nil + } + + // try to unmarshal data into SecurityMonitoringSignalRulePayload + err = datadog.Unmarshal(data, &obj.SecurityMonitoringSignalRulePayload) + if err == nil { + if obj.SecurityMonitoringSignalRulePayload != nil && obj.SecurityMonitoringSignalRulePayload.UnparsedObject == nil { + jsonSecurityMonitoringSignalRulePayload, _ := datadog.Marshal(obj.SecurityMonitoringSignalRulePayload) + if string(jsonSecurityMonitoringSignalRulePayload) == "{}" { // empty struct + obj.SecurityMonitoringSignalRulePayload = nil + } else { + match++ + } + } else { + obj.SecurityMonitoringSignalRulePayload = nil + } + } else { + obj.SecurityMonitoringSignalRulePayload = nil + } + + if match != 1 { // more than 1 match + // reset to nil + obj.SecurityMonitoringStandardRulePayload = nil + obj.SecurityMonitoringSignalRulePayload = nil + return datadog.Unmarshal(data, &obj.UnparsedObject) + } + return nil // exactly one match +} + +// MarshalJSON turns data from the first non-nil pointers in the struct to JSON. +func (obj SecurityMonitoringRuleConvertPayload) MarshalJSON() ([]byte, error) { + if obj.SecurityMonitoringStandardRulePayload != nil { + return datadog.Marshal(&obj.SecurityMonitoringStandardRulePayload) + } + + if obj.SecurityMonitoringSignalRulePayload != nil { + return datadog.Marshal(&obj.SecurityMonitoringSignalRulePayload) + } + + if obj.UnparsedObject != nil { + return datadog.Marshal(obj.UnparsedObject) + } + return nil, nil // no data in oneOf schemas +} + +// GetActualInstance returns the actual instance. +func (obj *SecurityMonitoringRuleConvertPayload) GetActualInstance() interface{} { + if obj.SecurityMonitoringStandardRulePayload != nil { + return obj.SecurityMonitoringStandardRulePayload + } + + if obj.SecurityMonitoringSignalRulePayload != nil { + return obj.SecurityMonitoringSignalRulePayload + } + + // all schemas are nil + return nil +} diff --git a/api/datadogV2/model_security_monitoring_rule_convert_response.go b/api/datadogV2/model_security_monitoring_rule_convert_response.go new file mode 100644 index 00000000000..6e83ec2e81b --- /dev/null +++ b/api/datadogV2/model_security_monitoring_rule_convert_response.go @@ -0,0 +1,102 @@ +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2019-Present Datadog, Inc. + +package datadogV2 + +import ( + "github.com/DataDog/datadog-api-client-go/v2/api/datadog" +) + +// SecurityMonitoringRuleConvertResponse Result of the convert rule request containing Terraform content. +type SecurityMonitoringRuleConvertResponse struct { + // Terraform string as a result of converting the rule from JSON. + TerraformContent *string `json:"terraformContent,omitempty"` + // UnparsedObject contains the raw value of the object if there was an error when deserializing into the struct + UnparsedObject map[string]interface{} `json:"-"` + AdditionalProperties map[string]interface{} +} + +// NewSecurityMonitoringRuleConvertResponse instantiates a new SecurityMonitoringRuleConvertResponse object. +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed. +func NewSecurityMonitoringRuleConvertResponse() *SecurityMonitoringRuleConvertResponse { + this := SecurityMonitoringRuleConvertResponse{} + return &this +} + +// NewSecurityMonitoringRuleConvertResponseWithDefaults instantiates a new SecurityMonitoringRuleConvertResponse object. +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set. +func NewSecurityMonitoringRuleConvertResponseWithDefaults() *SecurityMonitoringRuleConvertResponse { + this := SecurityMonitoringRuleConvertResponse{} + return &this +} + +// GetTerraformContent returns the TerraformContent field value if set, zero value otherwise. +func (o *SecurityMonitoringRuleConvertResponse) GetTerraformContent() string { + if o == nil || o.TerraformContent == nil { + var ret string + return ret + } + return *o.TerraformContent +} + +// GetTerraformContentOk returns a tuple with the TerraformContent field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *SecurityMonitoringRuleConvertResponse) GetTerraformContentOk() (*string, bool) { + if o == nil || o.TerraformContent == nil { + return nil, false + } + return o.TerraformContent, true +} + +// HasTerraformContent returns a boolean if a field has been set. +func (o *SecurityMonitoringRuleConvertResponse) HasTerraformContent() bool { + return o != nil && o.TerraformContent != nil +} + +// SetTerraformContent gets a reference to the given string and assigns it to the TerraformContent field. +func (o *SecurityMonitoringRuleConvertResponse) SetTerraformContent(v string) { + o.TerraformContent = &v +} + +// MarshalJSON serializes the struct using spec logic. +func (o SecurityMonitoringRuleConvertResponse) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.UnparsedObject != nil { + return datadog.Marshal(o.UnparsedObject) + } + if o.TerraformContent != nil { + toSerialize["terraformContent"] = o.TerraformContent + } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + return datadog.Marshal(toSerialize) +} + +// UnmarshalJSON deserializes the given payload. +func (o *SecurityMonitoringRuleConvertResponse) UnmarshalJSON(bytes []byte) (err error) { + all := struct { + TerraformContent *string `json:"terraformContent,omitempty"` + }{} + if err = datadog.Unmarshal(bytes, &all); err != nil { + return datadog.Unmarshal(bytes, &o.UnparsedObject) + } + additionalProperties := make(map[string]interface{}) + if err = datadog.Unmarshal(bytes, &additionalProperties); err == nil { + datadog.DeleteKeys(additionalProperties, &[]string{"terraformContent"}) + } else { + return err + } + o.TerraformContent = all.TerraformContent + + if len(additionalProperties) > 0 { + o.AdditionalProperties = additionalProperties + } + + return nil +} diff --git a/examples/v2/security-monitoring/ConvertExistingSecurityMonitoringRule.go b/examples/v2/security-monitoring/ConvertExistingSecurityMonitoringRule.go new file mode 100644 index 00000000000..bbd4909161d --- /dev/null +++ b/examples/v2/security-monitoring/ConvertExistingSecurityMonitoringRule.go @@ -0,0 +1,32 @@ +// Convert an existing rule from JSON to Terraform returns "OK" response + +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + + "github.com/DataDog/datadog-api-client-go/v2/api/datadog" + "github.com/DataDog/datadog-api-client-go/v2/api/datadogV2" +) + +func main() { + // there is a valid "security_rule" in the system + SecurityRuleID := os.Getenv("SECURITY_RULE_ID") + + ctx := datadog.NewDefaultContext(context.Background()) + configuration := datadog.NewConfiguration() + apiClient := datadog.NewAPIClient(configuration) + api := datadogV2.NewSecurityMonitoringApi(apiClient) + resp, r, err := api.ConvertExistingSecurityMonitoringRule(ctx, SecurityRuleID) + + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `SecurityMonitoringApi.ConvertExistingSecurityMonitoringRule`: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + + responseContent, _ := json.MarshalIndent(resp, "", " ") + fmt.Fprintf(os.Stdout, "Response from `SecurityMonitoringApi.ConvertExistingSecurityMonitoringRule`:\n%s\n", responseContent) +} diff --git a/examples/v2/security-monitoring/ConvertSecurityMonitoringRuleFromJSONToTerraform.go b/examples/v2/security-monitoring/ConvertSecurityMonitoringRuleFromJSONToTerraform.go new file mode 100644 index 00000000000..b9b65ffaf68 --- /dev/null +++ b/examples/v2/security-monitoring/ConvertSecurityMonitoringRuleFromJSONToTerraform.go @@ -0,0 +1,60 @@ +// Convert a rule from JSON to Terraform returns "OK" response + +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + + "github.com/DataDog/datadog-api-client-go/v2/api/datadog" + "github.com/DataDog/datadog-api-client-go/v2/api/datadogV2" +) + +func main() { + body := datadogV2.SecurityMonitoringRuleConvertPayload{ + SecurityMonitoringStandardRulePayload: &datadogV2.SecurityMonitoringStandardRulePayload{ + Name: "Example-Security-Monitoring", + Queries: []datadogV2.SecurityMonitoringStandardRuleQuery{ + { + Query: datadog.PtrString("@test:true"), + Aggregation: datadogV2.SECURITYMONITORINGRULEQUERYAGGREGATION_COUNT.Ptr(), + GroupByFields: []string{}, + DistinctFields: []string{}, + Metric: datadog.PtrString(""), + }, + }, + Filters: []datadogV2.SecurityMonitoringFilter{}, + Cases: []datadogV2.SecurityMonitoringRuleCaseCreate{ + { + Name: datadog.PtrString(""), + Status: datadogV2.SECURITYMONITORINGRULESEVERITY_INFO, + Condition: datadog.PtrString("a > 0"), + Notifications: []string{}, + }, + }, + Options: datadogV2.SecurityMonitoringRuleOptions{ + EvaluationWindow: datadogV2.SECURITYMONITORINGRULEEVALUATIONWINDOW_FIFTEEN_MINUTES.Ptr(), + KeepAlive: datadogV2.SECURITYMONITORINGRULEKEEPALIVE_ONE_HOUR.Ptr(), + MaxSignalDuration: datadogV2.SECURITYMONITORINGRULEMAXSIGNALDURATION_ONE_DAY.Ptr(), + }, + Message: "Test rule", + Tags: []string{}, + IsEnabled: true, + Type: datadogV2.SECURITYMONITORINGRULETYPECREATE_LOG_DETECTION.Ptr(), + }} + ctx := datadog.NewDefaultContext(context.Background()) + configuration := datadog.NewConfiguration() + apiClient := datadog.NewAPIClient(configuration) + api := datadogV2.NewSecurityMonitoringApi(apiClient) + resp, r, err := api.ConvertSecurityMonitoringRuleFromJSONToTerraform(ctx, body) + + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `SecurityMonitoringApi.ConvertSecurityMonitoringRuleFromJSONToTerraform`: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + + responseContent, _ := json.MarshalIndent(resp, "", " ") + fmt.Fprintf(os.Stdout, "Response from `SecurityMonitoringApi.ConvertSecurityMonitoringRuleFromJSONToTerraform`:\n%s\n", responseContent) +} diff --git a/tests/scenarios/cassettes/TestScenarios/v2/Feature_Security_Monitoring/Scenario_Convert_a_rule_from_JSON_to_Terraform_returns_OK_response.freeze b/tests/scenarios/cassettes/TestScenarios/v2/Feature_Security_Monitoring/Scenario_Convert_a_rule_from_JSON_to_Terraform_returns_OK_response.freeze new file mode 100644 index 00000000000..086ac5a06d1 --- /dev/null +++ b/tests/scenarios/cassettes/TestScenarios/v2/Feature_Security_Monitoring/Scenario_Convert_a_rule_from_JSON_to_Terraform_returns_OK_response.freeze @@ -0,0 +1 @@ +2024-06-24T19:47:12.909Z \ No newline at end of file diff --git a/tests/scenarios/cassettes/TestScenarios/v2/Feature_Security_Monitoring/Scenario_Convert_a_rule_from_JSON_to_Terraform_returns_OK_response.yaml b/tests/scenarios/cassettes/TestScenarios/v2/Feature_Security_Monitoring/Scenario_Convert_a_rule_from_JSON_to_Terraform_returns_OK_response.yaml new file mode 100644 index 00000000000..13de1b56e18 --- /dev/null +++ b/tests/scenarios/cassettes/TestScenarios/v2/Feature_Security_Monitoring/Scenario_Convert_a_rule_from_JSON_to_Terraform_returns_OK_response.yaml @@ -0,0 +1,31 @@ +interactions: +- request: + body: | + {"cases":[{"condition":"a \u003e 0","name":"","notifications":[],"status":"info"}],"filters":[],"isEnabled":true,"message":"Test rule","name":"Test-Convert_a_rule_from_JSON_to_Terraform_returns_OK_response-1719258432","options":{"evaluationWindow":900,"keepAlive":3600,"maxSignalDuration":86400},"queries":[{"aggregation":"count","distinctFields":[],"groupByFields":[],"metric":"","query":"@test:true"}],"tags":[],"type":"log_detection"} + form: {} + headers: + Accept: + - application/json + Content-Type: + - application/json + id: 0 + method: POST + url: https://api.datadoghq.com/api/v2/security_monitoring/rules/convert + response: + body: '{"terraformContent":"resource \"datadog_security_monitoring_rule\" \"test-convert_a_rule_from_json_to_terraform_returns_ok_response-1719258432\" + {\n\tname = \"Test-Convert_a_rule_from_JSON_to_Terraform_returns_OK_response-1719258432\"\n\tenabled + = true\n\tquery {\n\t\tquery = \"@test:true\"\n\t\tgroup_by_fields = []\n\t\tdistinct_fields + = []\n\t\taggregation = \"count\"\n\t\tname = \"\"\n\t}\n\toptions {\n\t\tkeep_alive + = 3600\n\t\tmax_signal_duration = 86400\n\t\tdetection_method = \"threshold\"\n\t\tevaluation_window + = 900\n\t}\n\tcase {\n\t\tname = \"\"\n\t\tstatus = \"info\"\n\t\tnotifications + = []\n\t\tcondition = \"a > 0\"\n\t}\n\tmessage = \"Test rule\"\n\ttags = []\n\thas_extended_title + = false\n\ttype = \"log_detection\"\n}\n"} + + ' + code: 200 + duration: 0ms + headers: + Content-Type: + - application/json + status: 200 OK +version: 2 diff --git a/tests/scenarios/cassettes/TestScenarios/v2/Feature_Security_Monitoring/Scenario_Convert_an_existing_rule_from_JSON_to_Terraform_returns_OK_response.freeze b/tests/scenarios/cassettes/TestScenarios/v2/Feature_Security_Monitoring/Scenario_Convert_an_existing_rule_from_JSON_to_Terraform_returns_OK_response.freeze new file mode 100644 index 00000000000..17c43a44b24 --- /dev/null +++ b/tests/scenarios/cassettes/TestScenarios/v2/Feature_Security_Monitoring/Scenario_Convert_an_existing_rule_from_JSON_to_Terraform_returns_OK_response.freeze @@ -0,0 +1 @@ +2024-06-24T19:55:06.421Z \ No newline at end of file diff --git a/tests/scenarios/cassettes/TestScenarios/v2/Feature_Security_Monitoring/Scenario_Convert_an_existing_rule_from_JSON_to_Terraform_returns_OK_response.yaml b/tests/scenarios/cassettes/TestScenarios/v2/Feature_Security_Monitoring/Scenario_Convert_an_existing_rule_from_JSON_to_Terraform_returns_OK_response.yaml new file mode 100644 index 00000000000..e7d0641f565 --- /dev/null +++ b/tests/scenarios/cassettes/TestScenarios/v2/Feature_Security_Monitoring/Scenario_Convert_an_existing_rule_from_JSON_to_Terraform_returns_OK_response.yaml @@ -0,0 +1,66 @@ +interactions: +- request: + body: | + {"cases":[{"condition":"a \u003e 0","name":"","notifications":[],"status":"info"}],"filters":[],"isEnabled":true,"message":"Test rule","name":"Test-Convert_an_existing_rule_from_JSON_to_Terraform_returns_OK_response-1719258906","options":{"evaluationWindow":900,"keepAlive":3600,"maxSignalDuration":86400},"queries":[{"aggregation":"count","distinctFields":[],"groupByFields":[],"metrics":[],"query":"@test:true"}],"tags":[],"type":"log_detection"} + form: {} + headers: + Accept: + - application/json + Content-Type: + - application/json + id: 0 + method: POST + url: https://api.datadoghq.com/api/v2/security_monitoring/rules + response: + body: '{"id":"eu8-b0k-wzc","version":1,"name":"Test-Convert_an_existing_rule_from_JSON_to_Terraform_returns_OK_response-1719258906","createdAt":1719258906588,"creationAuthorId":1445416,"isDefault":false,"isPartner":false,"isEnabled":true,"isDeleted":false,"isDeprecated":false,"queries":[{"query":"@test:true","groupByFields":[],"hasOptionalGroupByFields":false,"distinctFields":[],"aggregation":"count","name":""}],"options":{"keepAlive":3600,"maxSignalDuration":86400,"detectionMethod":"threshold","evaluationWindow":900},"cases":[{"name":"","status":"info","notifications":[],"condition":"a + > 0"}],"message":"Test rule","tags":[],"hasExtendedTitle":false,"type":"log_detection","filters":[]} + + ' + code: 200 + duration: 0ms + headers: + Content-Type: + - application/json + status: 200 OK +- request: + body: '' + form: {} + headers: + Accept: + - application/json + id: 1 + method: GET + url: https://api.datadoghq.com/api/v2/security_monitoring/rules/eu8-b0k-wzc/convert + response: + body: '{"terraformContent":"resource \"datadog_security_monitoring_rule\" \"test-convert_an_existing_rule_from_json_to_terraform_returns_ok_response-1719258906\" + {\n\tname = \"Test-Convert_an_existing_rule_from_JSON_to_Terraform_returns_OK_response-1719258906\"\n\tenabled + = true\n\tquery {\n\t\tquery = \"@test:true\"\n\t\tgroup_by_fields = []\n\t\tdistinct_fields + = []\n\t\taggregation = \"count\"\n\t\tname = \"\"\n\t}\n\toptions {\n\t\tkeep_alive + = 3600\n\t\tmax_signal_duration = 86400\n\t\tdetection_method = \"threshold\"\n\t\tevaluation_window + = 900\n\t}\n\tcase {\n\t\tname = \"\"\n\t\tstatus = \"info\"\n\t\tnotifications + = []\n\t\tcondition = \"a > 0\"\n\t}\n\tmessage = \"Test rule\"\n\ttags = []\n\thas_extended_title + = false\n\ttype = \"log_detection\"\n}\n"} + + ' + code: 200 + duration: 0ms + headers: + Content-Type: + - application/json + status: 200 OK +- request: + body: '' + form: {} + headers: + Accept: + - '*/*' + id: 2 + method: DELETE + url: https://api.datadoghq.com/api/v2/security_monitoring/rules/eu8-b0k-wzc + response: + body: '' + code: 204 + duration: 0ms + headers: {} + status: 204 No Content +version: 2 diff --git a/tests/scenarios/features/v2/security_monitoring.feature b/tests/scenarios/features/v2/security_monitoring.feature index 284dd5543cc..803f1056798 100644 --- a/tests/scenarios/features/v2/security_monitoring.feature +++ b/tests/scenarios/features/v2/security_monitoring.feature @@ -57,6 +57,51 @@ Feature: Security Monitoring When the request is sent Then the response status is 200 OK + @skip @team:DataDog/k9-cloud-security-platform + Scenario: Convert a rule from JSON to Terraform returns "Bad Request" response + Given new "ConvertSecurityMonitoringRuleFromJSONToTerraform" request + And body with value {"name":"{{ unique }}", "queries":[{"query":"@test:true","aggregation":"count","groupByFields":[],"distinctFields":[],"metric":""}],"filters":[],"cases":[{"name":"","status":"info","condition":"a > 0","notifications":[]}],"options":{"evaluationWindow":900,"keepAlive":3600,"maxSignalDuration":86400},"message":"Test rule","tags":[],"isEnabled":true, "type":"log_detection"} + When the request is sent + Then the response status is 400 Bad Request + + @skip @team:DataDog/k9-cloud-security-platform + Scenario: Convert a rule from JSON to Terraform returns "Not Found" response + Given new "ConvertSecurityMonitoringRuleFromJSONToTerraform" request + And body with value {"name":"{{ unique }}", "queries":[{"query":"@test:true","aggregation":"count","groupByFields":[],"distinctFields":[],"metric":""}],"filters":[],"cases":[{"name":"","status":"info","condition":"a > 0","notifications":[]}],"options":{"evaluationWindow":900,"keepAlive":3600,"maxSignalDuration":86400},"message":"Test rule","tags":[],"isEnabled":true, "type":"log_detection"} + When the request is sent + Then the response status is 404 Not Found + + @team:DataDog/k9-cloud-security-platform + Scenario: Convert a rule from JSON to Terraform returns "OK" response + Given new "ConvertSecurityMonitoringRuleFromJSONToTerraform" request + And body with value {"name":"{{ unique }}", "queries":[{"query":"@test:true","aggregation":"count","groupByFields":[],"distinctFields":[],"metric":""}],"filters":[],"cases":[{"name":"","status":"info","condition":"a > 0","notifications":[]}],"options":{"evaluationWindow":900,"keepAlive":3600,"maxSignalDuration":86400},"message":"Test rule","tags":[],"isEnabled":true, "type":"log_detection"} + When the request is sent + Then the response status is 200 OK + And the response "terraformContent" is equal to "resource \"datadog_security_monitoring_rule\" \"{{ unique_lower }}\" {\n\tname = \"{{ unique }}\"\n\tenabled = true\n\tquery {\n\t\tquery = \"@test:true\"\n\t\tgroup_by_fields = []\n\t\tdistinct_fields = []\n\t\taggregation = \"count\"\n\t\tname = \"\"\n\t}\n\toptions {\n\t\tkeep_alive = 3600\n\t\tmax_signal_duration = 86400\n\t\tdetection_method = \"threshold\"\n\t\tevaluation_window = 900\n\t}\n\tcase {\n\t\tname = \"\"\n\t\tstatus = \"info\"\n\t\tnotifications = []\n\t\tcondition = \"a > 0\"\n\t}\n\tmessage = \"Test rule\"\n\ttags = []\n\thas_extended_title = false\n\ttype = \"log_detection\"\n}\n" + + @skip @team:DataDog/k9-cloud-security-platform + Scenario: Convert an existing rule from JSON to Terraform returns "Bad Request" response + Given new "ConvertExistingSecurityMonitoringRule" request + And request contains "rule_id" parameter from "REPLACE.ME" + When the request is sent + Then the response status is 400 Bad Request + + @skip @team:DataDog/k9-cloud-security-platform + Scenario: Convert an existing rule from JSON to Terraform returns "Not Found" response + Given new "ConvertExistingSecurityMonitoringRule" request + And request contains "rule_id" parameter from "REPLACE.ME" + When the request is sent + Then the response status is 404 Not Found + + @team:DataDog/k9-cloud-security-platform + Scenario: Convert an existing rule from JSON to Terraform returns "OK" response + Given new "ConvertExistingSecurityMonitoringRule" request + And there is a valid "security_rule" in the system + And request contains "rule_id" parameter from "security_rule.id" + When the request is sent + Then the response status is 200 OK + And the response "terraformContent" is equal to "resource \"datadog_security_monitoring_rule\" \"{{ unique_lower }}\" {\n\tname = \"{{ unique }}\"\n\tenabled = true\n\tquery {\n\t\tquery = \"@test:true\"\n\t\tgroup_by_fields = []\n\t\tdistinct_fields = []\n\t\taggregation = \"count\"\n\t\tname = \"\"\n\t}\n\toptions {\n\t\tkeep_alive = 3600\n\t\tmax_signal_duration = 86400\n\t\tdetection_method = \"threshold\"\n\t\tevaluation_window = 900\n\t}\n\tcase {\n\t\tname = \"\"\n\t\tstatus = \"info\"\n\t\tnotifications = []\n\t\tcondition = \"a > 0\"\n\t}\n\tmessage = \"Test rule\"\n\ttags = []\n\thas_extended_title = false\n\ttype = \"log_detection\"\n}\n" + @skip-validation @team:DataDog/k9-cloud-security-platform Scenario: Create a cloud_configuration rule returns "OK" response Given new "CreateSecurityMonitoringRule" request diff --git a/tests/scenarios/features/v2/undo.json b/tests/scenarios/features/v2/undo.json index 0126ff4b812..e77fbd641c1 100644 --- a/tests/scenarios/features/v2/undo.json +++ b/tests/scenarios/features/v2/undo.json @@ -1775,6 +1775,12 @@ "type": "unsafe" } }, + "ConvertSecurityMonitoringRuleFromJSONToTerraform": { + "tag": "Security Monitoring", + "undo": { + "type": "idempotent" + } + }, "TestSecurityMonitoringRule": { "tag": "Security Monitoring", "undo": { @@ -1805,6 +1811,12 @@ "type": "idempotent" } }, + "ConvertExistingSecurityMonitoringRule": { + "tag": "Security Monitoring", + "undo": { + "type": "idempotent" + } + }, "TestExistingSecurityMonitoringRule": { "tag": "Security Monitoring", "undo": {