diff --git a/docs/resources/inext_exceptions.md b/docs/resources/inext_exceptions.md index 117146e..2b825ec 100644 --- a/docs/resources/inext_exceptions.md +++ b/docs/resources/inext_exceptions.md @@ -57,7 +57,7 @@ resource "inext_exceptions" "my-exceptions-behavior" { ### Required -- `name` (String) The name of the resource, also acts as it's unique ID +- `name` (String) The name of the resource, also acts as its unique ID ### Optional diff --git a/docs/resources/inext_log_trigger.md b/docs/resources/inext_log_trigger.md index ecbb216..aa0e7dc 100644 --- a/docs/resources/inext_log_trigger.md +++ b/docs/resources/inext_log_trigger.md @@ -62,7 +62,7 @@ resource "inext_log_trigger" "mytrigger" { ### Required -- `name` (String) The name of the resource, also acts as it's unique ID +- `name` (String) The name of the resource, also acts as its unique ID ### Optional diff --git a/docs/resources/inext_trusted_sources.md b/docs/resources/inext_trusted_sources.md index 9a4bce1..f00f48e 100644 --- a/docs/resources/inext_trusted_sources.md +++ b/docs/resources/inext_trusted_sources.md @@ -41,7 +41,7 @@ resource "inext_trusted_sources" "my-trusted-source-behavior" { ### Required - `min_num_of_sources` (Number) Minimum number of users or addresses that must exhibit similar activity for the behavior to be considered benign -- `name` (String) The name of the resource, also acts as it's unique ID +- `name` (String) The name of the resource, also acts as its unique ID ### Optional diff --git a/docs/resources/inext_web_api_asset.md b/docs/resources/inext_web_api_asset.md index 4e54dab..efc2bf0 100644 --- a/docs/resources/inext_web_api_asset.md +++ b/docs/resources/inext_web_api_asset.md @@ -61,7 +61,7 @@ resource "inext_web_api_asset" "my-webapi-asset" { ### Required -- `name` (String) The name of the resource, also acts as it's unique ID +- `name` (String) The name of the resource, also acts as its unique ID - `urls` (Set of String) The application URLs ### Optional diff --git a/docs/resources/inext_web_api_practice.md b/docs/resources/inext_web_api_practice.md index eafff9c..551469a 100644 --- a/docs/resources/inext_web_api_practice.md +++ b/docs/resources/inext_web_api_practice.md @@ -60,7 +60,7 @@ resource "inext_web_api_practice" "my-webapi-practice" { ### Required -- `name` (String) The name of the resource, also acts as it's unique ID +- `name` (String) The name of the resource, also acts as its unique ID ### Optional diff --git a/docs/resources/inext_web_app_asset.md b/docs/resources/inext_web_app_asset.md index 7915456..b27a8f2 100644 --- a/docs/resources/inext_web_app_asset.md +++ b/docs/resources/inext_web_app_asset.md @@ -61,7 +61,7 @@ resource "inext_web_app_asset" "my-webapp-asset" { ### Required -- `name` (String) The name of the resource, also acts as it's unique ID +- `name` (String) The name of the resource, also acts as its unique ID - `urls` (Set of String) The application URLs ### Optional @@ -95,11 +95,11 @@ resource "inext_web_app_asset" "my-webapp-asset" { Required: - `id` (String) The ID of this resource. +- `main_mode` (String) The mode of the practice: Prevent, Inactive, Disabled or Learn Optional: - `exceptions` (Set of String) The exceptions used with the practice -- `main_mode` (String) The mode of the practice: Prevent, Inactive, Disabled or Learn - `sub_practices_modes` (Map of String) The name of the sub practice as the key and its mode as the value. Allowed modes: Detect, Prevent, Inactive, AccordingToPractice, Disabled, Learn or Active - `triggers` (Set of String) The triggers used with the practice diff --git a/docs/resources/inext_web_app_practice.md b/docs/resources/inext_web_app_practice.md index 078a9ae..898d664 100644 --- a/docs/resources/inext_web_app_practice.md +++ b/docs/resources/inext_web_app_practice.md @@ -63,7 +63,7 @@ resource "inext_web_app_practice" "my-webapp-practice" { ### Required -- `name` (String) The name of the resource, also acts as it's unique ID +- `name` (String) The name of the resource, also acts as its unique ID ### Optional diff --git a/docs/resources/inext_web_user_response.md b/docs/resources/inext_web_user_response.md new file mode 100644 index 0000000..eaf8c27 --- /dev/null +++ b/docs/resources/inext_web_user_response.md @@ -0,0 +1,58 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "inext_web_user_response Resource - terraform-provider-infinity-next" +subcategory: "" +description: |- + Determine the response returned to the client who initiated a blocked traffic.The response can be a simple HTTP error code, an HTTP redirect message, or a Block page that a user can view in their browser. +--- + +# inext_web_user_response (Resource) + +Determine the response returned to the client who initiated a blocked traffic.The response can be a simple HTTP error code, an HTTP redirect message, or a Block page that a user can view in their browser. + +## Example Usage + +```terraform +resource "inext_web_user_response" "web-user-response-blockpage" { + name = "web-user-response" + mode = "BlockPage" + http_response_code = 403 + message_title = "some message title" + message_body = "some message body" +} + +resource "inext_web_user_response" "web-user-response-redirect" { + name = "web-user-response-redirect" + mode = "Redirect" + redirect_url = "http://localhost:1234/test" + x_event_id = true +} + +resource "inext_web_user_response" "web-user-response-responsecodeonly" { + name = "web-user-response-responsecodeonly" + mode = "ResponseCodeOnly" + http_response_code = 403 +} +``` + + +## Schema + +### Required + +- `mode` (String) The type of the web user response object +- `name` (String) The name of the resource, also acts as its unique ID + +### Optional + +- `http_response_code` (Number) It is recommended to use a 403 (Forbidden) as a response code +- `message_body` (String) The body of the message to be shown to the user +- `message_title` (String) The title of the web page to be shown to the user sending the malicious traffic +- `redirect_url` (String) The client will be redirected to the provided URL where you can provide any customized web page +- `x_event_id` (Boolean) When selected the redirect message will include this header with a value that provides an internal reference ID that will match a security log generated by the incident, if log triggers are configured + +### Read-Only + +- `id` (String) The ID of this resource. + + diff --git a/examples/resources/inext_web_user_response/resource.tf b/examples/resources/inext_web_user_response/resource.tf new file mode 100644 index 0000000..206b70c --- /dev/null +++ b/examples/resources/inext_web_user_response/resource.tf @@ -0,0 +1,20 @@ +resource "inext_web_user_response" "web-user-response-blockpage" { + name = "web-user-response" + mode = "BlockPage" + http_response_code = 403 + message_title = "some message title" + message_body = "some message body" +} + +resource "inext_web_user_response" "web-user-response-redirect" { + name = "web-user-response-redirect" + mode = "Redirect" + redirect_url = "http://localhost:1234/test" + x_event_id = true +} + +resource "inext_web_user_response" "web-user-response-responsecodeonly" { + name = "web-user-response-responsecodeonly" + mode = "ResponseCodeOnly" + http_response_code = 403 +} \ No newline at end of file diff --git a/internal/acctest/helpers.go b/internal/acctest/helpers.go index 6d86415..7deb8c4 100644 --- a/internal/acctest/helpers.go +++ b/internal/acctest/helpers.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" + "github.com/CheckPointSW/terraform-provider-infinity-next/internal/utils" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -44,7 +45,8 @@ func CheckResourceDestroyed(resourcesNames []string) resource.TestCheckFunc { if rs, ok := s.RootModule().Resources[resourceName]; ok { rd := schema.ResourceData{} rd.SetId(rs.Primary.ID) - diags := Provider.ResourcesMap[resourceType].ReadContext(context.Background(), &rd, Provider.Meta()) + ctx := context.WithValue(context.Background(), utils.ExpectResourceNotFound, true) + diags := Provider.ResourcesMap[resourceType].ReadContext(ctx, &rd, Provider.Meta()) if diags.HasError() { for _, d := range diags { if !strings.Contains(d.Summary, api.ErrorNotFound.Error()) { diff --git a/internal/api/infinity_next_api.go b/internal/api/infinity_next_api.go index 521de21..8c451e9 100644 --- a/internal/api/infinity_next_api.go +++ b/internal/api/infinity_next_api.go @@ -2,12 +2,15 @@ package api import ( "bytes" + "context" "encoding/json" "fmt" "io" "net/http" "net/url" "time" + + "github.com/CheckPointSW/terraform-provider-infinity-next/internal/utils" ) type GraphQLRequest struct { @@ -49,40 +52,67 @@ func (c *Client) InfinityPortalAuthentication(clientId string, accessKey string) "accessKey": {accessKey}, } - resp, err := client.PostForm(c.host+"/auth/external", formData) - if err != nil { - return err - } + for retryCount := 1; retryCount <= maxNumOfRetries; retryCount++ { + resp, err := client.PostForm(c.host+"/auth/external", formData) + if err != nil { + if retryCount == maxNumOfRetries { + return err + } - defer resp.Body.Close() + time.Sleep(2 * time.Second * time.Duration(retryCount)) + continue + } - var result map[string]any - if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { - return err - } + defer resp.Body.Close() - data, err := json.Marshal(result["data"]) - if err != nil { - return err - } + var result map[string]any + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { + if retryCount == maxNumOfRetries { + return err + } - jsonStr := string(data) - var datamap map[string]any - if err := json.Unmarshal([]byte(jsonStr), &datamap); err != nil { - return err - } + time.Sleep(2 * time.Second * time.Duration(retryCount)) + continue + } - tokenInterface, ok := datamap["token"] - if !ok { - return fmt.Errorf("missing token in response %#v", result) - } + data, err := json.Marshal(result["data"]) + if err != nil { + if retryCount == maxNumOfRetries { + return err + } - c.token = tokenInterface.(string) + time.Sleep(2 * time.Second * time.Duration(retryCount)) + continue + } + + jsonStr := string(data) + var datamap map[string]any + if err := json.Unmarshal([]byte(jsonStr), &datamap); err != nil { + if retryCount == maxNumOfRetries { + return err + } + + time.Sleep(2 * time.Second * time.Duration(retryCount)) + continue + } + + tokenInterface, ok := datamap["token"] + if !ok { + if retryCount == maxNumOfRetries { + return fmt.Errorf("missing token in response %#v", result) + } + + time.Sleep(2 * time.Second * time.Duration(retryCount)) + continue + } + + c.token = tokenInterface.(string) + } return nil } -func (c *Client) MakeGraphQLRequest(gql, responseKey string, vars ...map[string]any) (any, error) { +func (c *Client) MakeGraphQLRequest(ctx context.Context, gql, responseKey string, vars ...map[string]any) (any, error) { variables := make(map[string]any) for _, varMap := range vars { for k, v := range varMap { @@ -175,15 +205,19 @@ func (c *Client) MakeGraphQLRequest(gql, responseKey string, vars ...map[string] } if ret == nil { - err := fmt.Errorf("%s - ReferenceID: %s", ErrorNotFound.Error(), getReferenceIDFromHeaders(res.Header)) - if retryCount == maxNumOfRetries { - return nil, err + // We need to retry only if it's expected to find the resource + // This is only used for test, because we ensure a resource is destroyed after a test using Read. + if v := ctx.Value(utils.ExpectResourceNotFound); v != nil && !v.(bool) { + err := fmt.Errorf("%s - ReferenceID: %s", ErrorNotFound.Error(), getReferenceIDFromHeaders(res.Header)) + if retryCount == maxNumOfRetries { + return nil, err + } + + res.Body.Close() + fmt.Printf("[WARN] GraphQL request failed with error %v, retrying...\n", err) + time.Sleep(time.Second * 2 * time.Duration(retryCount)) + continue } - - res.Body.Close() - fmt.Printf("[WARN] GraphQL request failed with error %v, retrying...\n", err) - time.Sleep(time.Second * 2 * time.Duration(retryCount)) - continue } return ret, nil @@ -249,7 +283,7 @@ func (c *Client) PublishChanges() (bool, error) { } func (c *Client) DiscardChanges() (bool, error) { - discardChanges, err := c.MakeGraphQLRequest(` + discardChanges, err := c.MakeGraphQLRequest(context.Background(), ` mutation discardChanges{ discardChanges }`, "discardChanges") diff --git a/internal/models/web-user-response/behavior.go b/internal/models/web-user-response/behavior.go new file mode 100644 index 0000000..2a8bb61 --- /dev/null +++ b/internal/models/web-user-response/behavior.go @@ -0,0 +1,12 @@ +package models + +type WebUserResponseBehavior struct { + ID string `json:"id"` + Name string `json:"name"` + Mode string `json:"mode"` + MessageTitle string `json:"messageTitle"` + MessageBody string `json:"messageBody"` + HTTPResponseCode int `json:"httpResponseCode"` + RedirectURL string `json:"redirectURL"` + XEventID bool `json:"xEventId"` +} diff --git a/internal/models/web-user-response/input.go b/internal/models/web-user-response/input.go new file mode 100644 index 0000000..4e25b6d --- /dev/null +++ b/internal/models/web-user-response/input.go @@ -0,0 +1,12 @@ +package models + +type CreateWebUserResponseBehaviorInput struct { + Name string `json:"name"` + Visibility string `json:"visibility"` + Mode string `json:"mode"` + MessageTitle string `json:"messageTitle"` + MessageBody string `json:"messageBody"` + HTTPResponseCode int `json:"httpResponseCode"` + RedirectURL string `json:"redirectURL"` + XEventID bool `json:"xEventId"` +} diff --git a/internal/models/web-user-response/update.go b/internal/models/web-user-response/update.go new file mode 100644 index 0000000..277ecde --- /dev/null +++ b/internal/models/web-user-response/update.go @@ -0,0 +1,11 @@ +package models + +type UpdateWebUserResponseBehaviorInput struct { + Name string `json:"name"` + Mode string `json:"mode"` + MessageTitle string `json:"messageTitle,omitempty"` + MessageBody string `json:"messageBody,omitempty"` + HTTPResponseCode int `json:"httpResponseCode,omitempty"` + RedirectURL string `json:"redirectURL,omitempty"` + XEventID bool `json:"xEventId"` +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 0bd1c4b..ba316c4 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -56,6 +56,7 @@ func Provider() *schema.Provider { "inext_trusted_sources": resources.ResourceTrustedSources(), "inext_exceptions": resources.ResourceExceptions(), "inext_access_token": resources.ResourceAccessToken(), + "inext_web_user_response": resources.ResourceWebUserResponse(), }, ConfigureContextFunc: providerConfigure, } diff --git a/internal/resources/appsec-gateway-profile.go b/internal/resources/appsec-gateway-profile.go index 9132838..90f48a0 100644 --- a/internal/resources/appsec-gateway-profile.go +++ b/internal/resources/appsec-gateway-profile.go @@ -151,7 +151,7 @@ func resourceAppSecGatewayProfileCreate(ctx context.Context, d *schema.ResourceD return utils.DiagError("unable to perform AppSecGatewayProfile Create", err, diags) } - profile, err := appsecgatewayprofile.NewAppSecGatewayProfile(c, createInput) + profile, err := appsecgatewayprofile.NewAppSecGatewayProfile(ctx, c, createInput) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -187,7 +187,7 @@ func resourceAppSecGatewayProfileRead(ctx context.Context, d *schema.ResourceDat id := d.Id() - profile, err := appsecgatewayprofile.GetCloudGuardAppSecGatewayProfile(c, id) + profile, err := appsecgatewayprofile.GetCloudGuardAppSecGatewayProfile(ctx, c, id) if err != nil { return utils.DiagError("unable to perform AppSecGatewayProfile Read", err, diags) } @@ -209,7 +209,7 @@ func resourceAppSecGatewayProfileUpdate(ctx context.Context, d *schema.ResourceD return utils.DiagError("unable to perform AppSecGatewayProfile Update", err, diags) } - result, err := appsecgatewayprofile.UpdateAppSecGatewayProfile(c, d.Id(), updateInput) + result, err := appsecgatewayprofile.UpdateAppSecGatewayProfile(ctx, c, d.Id(), updateInput) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -227,7 +227,7 @@ func resourceAppSecGatewayProfileUpdate(ctx context.Context, d *schema.ResourceD return utils.DiagError("failed to Publish following AppSecGatewayProfile Update", err, diags) } - profile, err := appsecgatewayprofile.GetCloudGuardAppSecGatewayProfile(c, d.Id()) + profile, err := appsecgatewayprofile.GetCloudGuardAppSecGatewayProfile(ctx, c, d.Id()) if err != nil { return utils.DiagError("failed get AppSecGatewayProfile after update", err, diags) } @@ -244,7 +244,7 @@ func resourceAppSecGatewayProfileDelete(ctx context.Context, d *schema.ResourceD c := meta.(*api.Client) ID := d.Id() - result, err := appsecgatewayprofile.DeleteAppSecGatewayProfile(c, ID) + result, err := appsecgatewayprofile.DeleteAppSecGatewayProfile(ctx, c, ID) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) diff --git a/internal/resources/appsec-gateway-profile/create.go b/internal/resources/appsec-gateway-profile/create.go index 6f0781e..f3f9e40 100644 --- a/internal/resources/appsec-gateway-profile/create.go +++ b/internal/resources/appsec-gateway-profile/create.go @@ -1,6 +1,7 @@ package appsecgatewayprofile import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -75,9 +76,9 @@ func handleScheduledUpgradeMode(d *schema.ResourceData) models.UpgradeTimeInput return res } -func NewAppSecGatewayProfile(c *api.Client, input models.CreateCloudGuardAppSecGatewayProfileInput) (models.CloudGuardAppSecGatewayProfile, error) { +func NewAppSecGatewayProfile(ctx context.Context, c *api.Client, input models.CreateCloudGuardAppSecGatewayProfileInput) (models.CloudGuardAppSecGatewayProfile, error) { vars := map[string]any{"profileInput": input} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation newCloudGuardAppSecGatewayProfile($profileInput: CloudGuardAppSecGatewayProfileInput) { newCloudGuardAppSecGatewayProfile (profileInput: $profileInput) { diff --git a/internal/resources/appsec-gateway-profile/delete.go b/internal/resources/appsec-gateway-profile/delete.go index f543393..676f7dd 100644 --- a/internal/resources/appsec-gateway-profile/delete.go +++ b/internal/resources/appsec-gateway-profile/delete.go @@ -1,13 +1,14 @@ package appsecgatewayprofile import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" ) -func DeleteAppSecGatewayProfile(c *api.Client, id string) (bool, error) { - res, err := c.MakeGraphQLRequest(` +func DeleteAppSecGatewayProfile(ctx context.Context, c *api.Client, id string) (bool, error) { + res, err := c.MakeGraphQLRequest(ctx, ` mutation deleteProfile { deleteProfile(id: "`+id+`") } diff --git a/internal/resources/appsec-gateway-profile/read.go b/internal/resources/appsec-gateway-profile/read.go index 67b7748..d81609d 100644 --- a/internal/resources/appsec-gateway-profile/read.go +++ b/internal/resources/appsec-gateway-profile/read.go @@ -1,6 +1,7 @@ package appsecgatewayprofile import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -55,8 +56,8 @@ func ReadCloudGuardAppSecGatewayProfileToResourceData(profile models.CloudGuardA return nil } -func GetCloudGuardAppSecGatewayProfile(c *api.Client, id string) (models.CloudGuardAppSecGatewayProfile, error) { - res, err := c.MakeGraphQLRequest(` +func GetCloudGuardAppSecGatewayProfile(ctx context.Context, c *api.Client, id string) (models.CloudGuardAppSecGatewayProfile, error) { + res, err := c.MakeGraphQLRequest(ctx, ` { getCloudGuardAppSecGatewayProfile(id: "`+id+`") { id diff --git a/internal/resources/appsec-gateway-profile/update.go b/internal/resources/appsec-gateway-profile/update.go index ad9e59e..a8671ca 100644 --- a/internal/resources/appsec-gateway-profile/update.go +++ b/internal/resources/appsec-gateway-profile/update.go @@ -1,6 +1,7 @@ package appsecgatewayprofile import ( + "context" "fmt" "log" "strings" @@ -11,9 +12,9 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func UpdateAppSecGatewayProfile(c *api.Client, id any, input models.UpdateCloudGuardAppSecGatewayProfileInput) (bool, error) { +func UpdateAppSecGatewayProfile(ctx context.Context, c *api.Client, id any, input models.UpdateCloudGuardAppSecGatewayProfileInput) (bool, error) { vars := map[string]any{"profileInput": input, "id": id} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation updateCloudGuardAppSecGatewayProfile($profileInput: CloudGuardAppSecGatewayProfileUpdateInput, $id: ID!) { updateCloudGuardAppSecGatewayProfile (profileInput: $profileInput, id: $id) diff --git a/internal/resources/docker-profile.go b/internal/resources/docker-profile.go index 0ec508a..4c5ad81 100644 --- a/internal/resources/docker-profile.go +++ b/internal/resources/docker-profile.go @@ -89,7 +89,7 @@ func resourceDockerProfileCreate(ctx context.Context, d *schema.ResourceData, me return utils.DiagError("unable to perform DockerProfile Create", err, diags) } - profile, err := dockerprofile.NewDockerProfile(c, createInput) + profile, err := dockerprofile.NewDockerProfile(ctx, c, createInput) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -125,7 +125,7 @@ func resourceDockerProfileRead(ctx context.Context, d *schema.ResourceData, meta id := d.Id() - profile, err := dockerprofile.GetDockerProfile(c, id) + profile, err := dockerprofile.GetDockerProfile(ctx, c, id) if err != nil { return utils.DiagError("unable to perform DockerProfile Read", err, diags) } @@ -147,7 +147,7 @@ func resourceDockerProfileUpdate(ctx context.Context, d *schema.ResourceData, me return utils.DiagError("unable to perform DockerProfile Update", err, diags) } - result, err := dockerprofile.UpdateDockerProfile(c, d.Id(), updateInput) + result, err := dockerprofile.UpdateDockerProfile(ctx, c, d.Id(), updateInput) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -165,7 +165,7 @@ func resourceDockerProfileUpdate(ctx context.Context, d *schema.ResourceData, me return utils.DiagError("failed to Publish following DockerProfile Update", err, diags) } - profile, err := dockerprofile.GetDockerProfile(c, d.Id()) + profile, err := dockerprofile.GetDockerProfile(ctx, c, d.Id()) if err != nil { return utils.DiagError("failed get DockerProfile after update", err, diags) } @@ -182,7 +182,7 @@ func resourceDockerProfileDelete(ctx context.Context, d *schema.ResourceData, me c := meta.(*api.Client) ID := d.Id() - result, err := dockerprofile.DeleteDockerProfile(c, ID) + result, err := dockerprofile.DeleteDockerProfile(ctx, c, ID) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) diff --git a/internal/resources/docker-profile/create.go b/internal/resources/docker-profile/create.go index 2b874e4..26d987e 100644 --- a/internal/resources/docker-profile/create.go +++ b/internal/resources/docker-profile/create.go @@ -1,6 +1,7 @@ package dockerprofile import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -35,9 +36,9 @@ func mapToKeyValueInput(d *schema.ResourceData, key string) []models.KeyValueInp return res } -func NewDockerProfile(c *api.Client, input models.CreateDockerProfileInput) (models.DockerProfile, error) { +func NewDockerProfile(ctx context.Context, c *api.Client, input models.CreateDockerProfileInput) (models.DockerProfile, error) { vars := map[string]any{"profileInput": input} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation newDockerProfile($profileInput: DockerProfileInput) { newDockerProfile (profileInput: $profileInput) { diff --git a/internal/resources/docker-profile/delete.go b/internal/resources/docker-profile/delete.go index 928dbec..cfc1dc9 100644 --- a/internal/resources/docker-profile/delete.go +++ b/internal/resources/docker-profile/delete.go @@ -1,13 +1,14 @@ package dockerprofile import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" ) -func DeleteDockerProfile(c *api.Client, id string) (bool, error) { - res, err := c.MakeGraphQLRequest(` +func DeleteDockerProfile(ctx context.Context, c *api.Client, id string) (bool, error) { + res, err := c.MakeGraphQLRequest(ctx, ` mutation deleteProfile { deleteProfile(id: "`+id+`") } diff --git a/internal/resources/docker-profile/read.go b/internal/resources/docker-profile/read.go index a9d2a9d..f20f10c 100644 --- a/internal/resources/docker-profile/read.go +++ b/internal/resources/docker-profile/read.go @@ -1,6 +1,7 @@ package dockerprofile import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -35,8 +36,8 @@ func ReadDockerProfileToResourceData(profile models.DockerProfile, d *schema.Res return nil } -func GetDockerProfile(c *api.Client, id string) (models.DockerProfile, error) { - res, err := c.MakeGraphQLRequest(` +func GetDockerProfile(ctx context.Context, c *api.Client, id string) (models.DockerProfile, error) { + res, err := c.MakeGraphQLRequest(ctx, ` { getDockerProfile(id: "`+id+`") { id diff --git a/internal/resources/docker-profile/update.go b/internal/resources/docker-profile/update.go index 45501c9..26eed70 100644 --- a/internal/resources/docker-profile/update.go +++ b/internal/resources/docker-profile/update.go @@ -1,6 +1,7 @@ package dockerprofile import ( + "context" "fmt" "log" "strings" @@ -11,9 +12,9 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func UpdateDockerProfile(c *api.Client, id any, input models.DockerProfileUpdateInput) (bool, error) { +func UpdateDockerProfile(ctx context.Context, c *api.Client, id any, input models.DockerProfileUpdateInput) (bool, error) { vars := map[string]any{"profileInput": input, "id": id} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation updateDockerProfile($profileInput: DockerProfileUpdateInput, $id: ID!) { updateDockerProfile (profileInput: $profileInput, id: $id) diff --git a/internal/resources/embedded-profile.go b/internal/resources/embedded-profile.go index 5b7ebad..2570a82 100644 --- a/internal/resources/embedded-profile.go +++ b/internal/resources/embedded-profile.go @@ -121,7 +121,7 @@ func resourceEmbeddedProfileCreate(ctx context.Context, d *schema.ResourceData, return utils.DiagError("unable to perform EmbeddedProfile Create", err, diags) } - profile, err := embeddedprofile.NewEmbeddedProfile(c, createInput) + profile, err := embeddedprofile.NewEmbeddedProfile(ctx, c, createInput) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -157,7 +157,7 @@ func resourceEmbeddedProfileRead(ctx context.Context, d *schema.ResourceData, me id := d.Id() - profile, err := embeddedprofile.GetEmbeddedProfile(c, id) + profile, err := embeddedprofile.GetEmbeddedProfile(ctx, c, id) if err != nil { return utils.DiagError("unable to perform EmbeddedProfile Read", err, diags) } @@ -179,7 +179,7 @@ func resourceEmbeddedProfileUpdate(ctx context.Context, d *schema.ResourceData, return utils.DiagError("unable to perform EmbeddedProfile Update", err, diags) } - result, err := embeddedprofile.UpdateEmbeddedProfile(c, d.Id(), updateInput) + result, err := embeddedprofile.UpdateEmbeddedProfile(ctx, c, d.Id(), updateInput) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -197,7 +197,7 @@ func resourceEmbeddedProfileUpdate(ctx context.Context, d *schema.ResourceData, return utils.DiagError("failed to Publish following EmbeddedProfile Update", err, diags) } - profile, err := embeddedprofile.GetEmbeddedProfile(c, d.Id()) + profile, err := embeddedprofile.GetEmbeddedProfile(ctx, c, d.Id()) if err != nil { return utils.DiagError("failed get EmbeddedProfile after update", err, diags) } @@ -214,7 +214,7 @@ func resourceEmbeddedProfileDelete(ctx context.Context, d *schema.ResourceData, c := meta.(*api.Client) ID := d.Id() - result, err := embeddedprofile.DeleteEmbeddedProfile(c, ID) + result, err := embeddedprofile.DeleteEmbeddedProfile(ctx, c, ID) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) diff --git a/internal/resources/embedded-profile/create.go b/internal/resources/embedded-profile/create.go index f6f5fef..5241454 100644 --- a/internal/resources/embedded-profile/create.go +++ b/internal/resources/embedded-profile/create.go @@ -1,6 +1,7 @@ package embeddedprofile import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -76,9 +77,9 @@ func handleScheduledUpgradeMode(d *schema.ResourceData) models.ScheduleTimeInput return res } -func NewEmbeddedProfile(c *api.Client, input models.CreateEmbeddedProfileInput) (models.EmbeddedProfile, error) { +func NewEmbeddedProfile(ctx context.Context, c *api.Client, input models.CreateEmbeddedProfileInput) (models.EmbeddedProfile, error) { vars := map[string]any{"profileInput": input} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation newEmbeddedProfile($profileInput: EmbeddedProfileInput) { newEmbeddedProfile (profileInput: $profileInput) { diff --git a/internal/resources/embedded-profile/delete.go b/internal/resources/embedded-profile/delete.go index 45c9b99..d6db45d 100644 --- a/internal/resources/embedded-profile/delete.go +++ b/internal/resources/embedded-profile/delete.go @@ -1,13 +1,14 @@ package embeddedprofile import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" ) -func DeleteEmbeddedProfile(c *api.Client, id string) (bool, error) { - res, err := c.MakeGraphQLRequest(` +func DeleteEmbeddedProfile(ctx context.Context, c *api.Client, id string) (bool, error) { + res, err := c.MakeGraphQLRequest(ctx, ` mutation deleteProfile { deleteProfile(id: "`+id+`") } diff --git a/internal/resources/embedded-profile/read.go b/internal/resources/embedded-profile/read.go index 3d174e2..6c4e573 100644 --- a/internal/resources/embedded-profile/read.go +++ b/internal/resources/embedded-profile/read.go @@ -1,6 +1,7 @@ package embeddedprofile import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -43,8 +44,8 @@ func ReadEmbeddedProfileToResourceData(profile models.EmbeddedProfile, d *schema return nil } -func GetEmbeddedProfile(c *api.Client, id string) (models.EmbeddedProfile, error) { - res, err := c.MakeGraphQLRequest(` +func GetEmbeddedProfile(ctx context.Context, c *api.Client, id string) (models.EmbeddedProfile, error) { + res, err := c.MakeGraphQLRequest(ctx, ` { getEmbeddedProfile(id: "`+id+`") { id diff --git a/internal/resources/embedded-profile/update.go b/internal/resources/embedded-profile/update.go index 180ac94..598f1fb 100644 --- a/internal/resources/embedded-profile/update.go +++ b/internal/resources/embedded-profile/update.go @@ -1,6 +1,7 @@ package embeddedprofile import ( + "context" "fmt" "log" "strings" @@ -11,9 +12,9 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func UpdateEmbeddedProfile(c *api.Client, id any, input models.EmbeddedProfileUpdateInput) (bool, error) { +func UpdateEmbeddedProfile(ctx context.Context, c *api.Client, id any, input models.EmbeddedProfileUpdateInput) (bool, error) { vars := map[string]any{"profileInput": input, "id": id} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation updateEmbeddedProfile($profileInput: EmbeddedProfileUpdateInput, $id: ID!) { updateEmbeddedProfile (profileInput: $profileInput, id: $id) diff --git a/internal/resources/exceptions.go b/internal/resources/exceptions.go index f208aa3..7c8ddc1 100644 --- a/internal/resources/exceptions.go +++ b/internal/resources/exceptions.go @@ -95,7 +95,7 @@ func ResourceExceptions() *schema.Resource { }, "name": { Type: schema.TypeString, - Description: "The name of the resource, also acts as it's unique ID", + Description: "The name of the resource, also acts as its unique ID", Required: true, }, "exception": { @@ -144,7 +144,7 @@ func resourceExceptionsCreate(ctx context.Context, d *schema.ResourceData, meta return utils.DiagError("unable to perform ExceptionBehavior Create", err, diags) } - behavior, err := exceptions.NewExceptionBehavior(c, createInput) + behavior, err := exceptions.NewExceptionBehavior(ctx, c, createInput) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -177,7 +177,7 @@ func resourceExceptionsRead(ctx context.Context, d *schema.ResourceData, meta an var diags diag.Diagnostics c := meta.(*api.Client) - behavior, err := exceptions.GetExceptionBehavior(c, d.Id()) + behavior, err := exceptions.GetExceptionBehavior(ctx, c, d.Id()) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -206,7 +206,7 @@ func resourceExceptionsUpdate(ctx context.Context, d *schema.ResourceData, meta return utils.DiagError("unable to perform ExceptionBehavior Update", err, diags) } - result, err := exceptions.UpdateExceptionBehavior(c, d.Id(), updateInput) + result, err := exceptions.UpdateExceptionBehavior(ctx, c, d.Id(), updateInput) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -224,7 +224,7 @@ func resourceExceptionsUpdate(ctx context.Context, d *schema.ResourceData, meta return utils.DiagError("failed to Publish following ExceptionBehavior Update", err, diags) } - behavior, err := exceptions.GetExceptionBehavior(c, d.Id()) + behavior, err := exceptions.GetExceptionBehavior(ctx, c, d.Id()) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -248,7 +248,7 @@ func resourceExceptionsDelete(ctx context.Context, d *schema.ResourceData, meta var diags diag.Diagnostics c := meta.(*api.Client) - result, err := exceptions.DeleteExceptionBehavior(c, d.Id()) + result, err := exceptions.DeleteExceptionBehavior(ctx, c, d.Id()) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) diff --git a/internal/resources/exceptions/create.go b/internal/resources/exceptions/create.go index f66c0dc..d6101a5 100644 --- a/internal/resources/exceptions/create.go +++ b/internal/resources/exceptions/create.go @@ -1,6 +1,7 @@ package exceptions import ( + "context" "encoding/json" "fmt" @@ -94,9 +95,9 @@ func CreateExceptionBehaviorInputFromResourceData(d *schema.ResourceData) (model return res, nil } -func NewExceptionBehavior(c *api.Client, input models.CreateExceptionBehaviorInput) (models.ExceptionBehavior, error) { +func NewExceptionBehavior(ctx context.Context, c *api.Client, input models.CreateExceptionBehaviorInput) (models.ExceptionBehavior, error) { vars := map[string]any{"ownerId": nil, "practiceId": nil, "behaviorInput": input} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation newExceptionBehavior($ownerId: ID, $practiceId: ID, $behaviorInput: ExceptionBehaviorInput) { newExceptionBehavior(ownerId: $ownerId, practiceId: $practiceId, behaviorInput: $behaviorInput) { diff --git a/internal/resources/exceptions/delete.go b/internal/resources/exceptions/delete.go index 3364230..a706291 100644 --- a/internal/resources/exceptions/delete.go +++ b/internal/resources/exceptions/delete.go @@ -1,13 +1,14 @@ package exceptions import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" ) -func DeleteExceptionBehavior(c *api.Client, id string) (bool, error) { - res, err := c.MakeGraphQLRequest(` +func DeleteExceptionBehavior(ctx context.Context, c *api.Client, id string) (bool, error) { + res, err := c.MakeGraphQLRequest(ctx, ` mutation deleteBehavior { deleteBehavior(id: "`+id+`") } diff --git a/internal/resources/exceptions/models.go b/internal/resources/exceptions/models.go deleted file mode 100644 index c46f3bb..0000000 --- a/internal/resources/exceptions/models.go +++ /dev/null @@ -1,164 +0,0 @@ -package exceptions - -import ( - "fmt" - - "github.com/CheckPointSW/terraform-provider-infinity-next/internal/utils" -) - -type ExceptionObjectInput struct { - Match string `json:"match"` - Actions []string `json:"actions"` - Comment string `json:"comment,omitempty"` -} - -type SchemaExceptionObject struct { - ID string `json:"id,omitempty"` - Match map[string]string `json:"match"` - Action string `json:"action"` - ActionID string `json:"action_id,omitempty"` - Comment string `json:"comment,omitempty"` -} - -type CreateExceptionBehaviorInput struct { - Name string `json:"name,omitempty"` - Visibility string `json:"visibility,omitempty"` - Exceptions []ExceptionObjectInput `json:"exceptions,omitempty"` -} - -type CreateExceptionBehaviorResponse struct { - ID string `json:"id"` -} - -type Match struct { - Type string `json:"type"` - Operator string `json:"op"` - Items []Match `json:"items,omitempty"` - Key string `json:"key,omitempty"` - Value []string `json:"value,omitempty"` -} - -type Action struct { - Key string `json:"key"` - Value string `json:"value"` -} - -type ExceptionObjectAction struct { - ID string `json:"id"` - Action string `json:"action"` -} - -type ExceptionObject struct { - ID string `json:"id"` - Match string `json:"match"` - Actions []ExceptionObjectAction `json:"actions"` - Comment string `json:"comment,omitempty"` -} - -type ExceptionBehavior struct { - ID string `json:"id"` - Name string `json:"name"` - Exceptions []ExceptionObject `json:"exceptions"` -} - -type SchemaExceptionBehavior struct { - ID string `json:"id"` - Match map[string]any `json:"match"` - Action string `json:"action"` - ActionID string `json:"action_id,omitempty"` - Comment string `json:"comment,omitempty"` -} - -type ExceptionBehaviorUpdateInput struct { - Name string `json:"name,omitempty"` - AddExceptions []ExceptionObjectInput `json:"addExceptions,omitempty"` - RemoveExceptions []string `json:"removeExceptions,omitempty"` -} - -type UpdateExceptionBehaviorInput struct { - ID string `json:"id"` - BehaviorInput ExceptionBehaviorUpdateInput `json:"behaviorInput"` -} - -func NewAction(action string) Action { - return Action{Key: "action", Value: action} -} - -func AndMatchFromMap(m map[string]string) Match { - matches := make([]Match, 0, len(m)) - for key, value := range m { - match := Match{ - Type: "condition", - Operator: "equals", - Key: key, - Value: []string{value}, - } - - matches = append(matches, match) - } - - // no need for an "and" operator if only one match - if len(matches) == 1 { - return matches[0] - } - - // else - create an "and" operator between all matches - var rootMatch Match - rootMatch.Type = "operator" - rootMatch.Operator = "and" - rootMatch.Items = matches - return rootMatch -} - -func (m Match) ToSchemaMap() map[string]interface{} { - if len(m.Items) == 0 { - return map[string]interface{}{ - m.Key: m.Value[0], - } - } - - result := make(map[string]interface{}, len(m.Items)) - for _, match := range m.Items { - if len(match.Value) > 0 { - result[match.Key] = match.Value[0] - } - } - - return result -} - -func (m Match) String() string { - return fmt.Sprintf("%#v", m) -} - -// ExceptionsDiff returns the diff of old and new -func ExceptionsDiff(old, new []SchemaExceptionBehavior) (added, removed []string) { - oldIDs := make([]string, 0, len(old)) - oldValues := make([]string, 0, len(old)) - for _, exception := range old { - oldIDs = append(oldIDs, exception.ID) - oldValues = append(oldValues, fmt.Sprintf("%#v", exception)) - } - - newIDs := make([]string, 0, len(new)) - newValues := make([]string, 0, len(new)) - - for _, exception := range new { - newIDs = append(newIDs, exception.ID) - newValues = append(newValues, fmt.Sprintf("%#v", exception)) - } - - added = utils.Added(oldValues, newValues) - removed = utils.Removed(oldIDs, newIDs) - - return -} - -// ExceptionsUpdate returns the exceptions update input for update operation, -// it deletes all the old exceptions and adds the new ones -func ExceptionsUpdate(oldIDs, newValues []string) (added, removed []string) { - added = newValues - removed = oldIDs - - return -} diff --git a/internal/resources/exceptions/read.go b/internal/resources/exceptions/read.go index 8b75982..6815e64 100644 --- a/internal/resources/exceptions/read.go +++ b/internal/resources/exceptions/read.go @@ -1,6 +1,7 @@ package exceptions import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -9,8 +10,8 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func GetExceptionBehavior(c *api.Client, id string) (models.ExceptionBehavior, error) { - res, err := c.MakeGraphQLRequest(` +func GetExceptionBehavior(ctx context.Context, c *api.Client, id string) (models.ExceptionBehavior, error) { + res, err := c.MakeGraphQLRequest(ctx, ` { getExceptionBehavior(id: "`+id+`") { id diff --git a/internal/resources/exceptions/update.go b/internal/resources/exceptions/update.go index 8975a01..2a4b0ec 100644 --- a/internal/resources/exceptions/update.go +++ b/internal/resources/exceptions/update.go @@ -1,6 +1,7 @@ package exceptions import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -28,9 +29,9 @@ func UpdateExceptionBehaviorInputFromResourceData(d *schema.ResourceData) (model return res, nil } -func UpdateExceptionBehavior(c *api.Client, id string, input models.UpdateExceptionBehaviorInput) (bool, error) { +func UpdateExceptionBehavior(ctx context.Context, c *api.Client, id string, input models.UpdateExceptionBehaviorInput) (bool, error) { vars := map[string]any{"behaviorInput": input, "id": id} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation updateExceptionBehavior($behaviorInput: ExceptionBehaviorUpdateInput, $id: ID!) { updateExceptionBehavior(behaviorInput: $behaviorInput, id: $id) diff --git a/internal/resources/kubernetes-profile.go b/internal/resources/kubernetes-profile.go index 6307bf0..ff0535d 100644 --- a/internal/resources/kubernetes-profile.go +++ b/internal/resources/kubernetes-profile.go @@ -94,7 +94,7 @@ func resourceKubernetesProfileCreate(ctx context.Context, d *schema.ResourceData return utils.DiagError("unable to perform KubernetesProfile Create", err, diags) } - profile, err := kubernetesprofile.NewKubernetesProfile(c, createInput) + profile, err := kubernetesprofile.NewKubernetesProfile(ctx, c, createInput) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -130,7 +130,7 @@ func resourceKubernetesProfileRead(ctx context.Context, d *schema.ResourceData, id := d.Id() - profile, err := kubernetesprofile.GetKubernetesProfile(c, id) + profile, err := kubernetesprofile.GetKubernetesProfile(ctx, c, id) if err != nil { return utils.DiagError("unable to perform KubernetesProfile Read", err, diags) } @@ -152,7 +152,7 @@ func resourceKubernetesProfileUpdate(ctx context.Context, d *schema.ResourceData return utils.DiagError("unable to perform KubernetesProfile Update", err, diags) } - result, err := kubernetesprofile.UpdateKubernetesProfile(c, d.Id(), updateInput) + result, err := kubernetesprofile.UpdateKubernetesProfile(ctx, c, d.Id(), updateInput) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -170,7 +170,7 @@ func resourceKubernetesProfileUpdate(ctx context.Context, d *schema.ResourceData return utils.DiagError("failed to Publish following KubernetesProfile Update", err, diags) } - profile, err := kubernetesprofile.GetKubernetesProfile(c, d.Id()) + profile, err := kubernetesprofile.GetKubernetesProfile(ctx, c, d.Id()) if err != nil { return utils.DiagError("failed get KubernetesProfile after update", err, diags) } @@ -187,7 +187,7 @@ func resourceKubernetesProfileDelete(ctx context.Context, d *schema.ResourceData c := meta.(*api.Client) ID := d.Id() - result, err := kubernetesprofile.DeleteKubernetesProfile(c, ID) + result, err := kubernetesprofile.DeleteKubernetesProfile(ctx, c, ID) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) diff --git a/internal/resources/kubernetes-profile/create.go b/internal/resources/kubernetes-profile/create.go index 96812d1..a51e00d 100644 --- a/internal/resources/kubernetes-profile/create.go +++ b/internal/resources/kubernetes-profile/create.go @@ -1,6 +1,7 @@ package kubernetesprofile import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -36,9 +37,9 @@ func mapToKeyValueInput(d *schema.ResourceData, key string) []models.KeyValueInp return res } -func NewKubernetesProfile(c *api.Client, input models.CreateKubernetesProfileInput) (models.KubernetesProfile, error) { +func NewKubernetesProfile(ctx context.Context, c *api.Client, input models.CreateKubernetesProfileInput) (models.KubernetesProfile, error) { vars := map[string]any{"profileInput": input} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation newKubernetesProfile($profileInput: KubernetesProfileInput) { newKubernetesProfile (profileInput: $profileInput) { diff --git a/internal/resources/kubernetes-profile/delete.go b/internal/resources/kubernetes-profile/delete.go index 375417c..2ddb044 100644 --- a/internal/resources/kubernetes-profile/delete.go +++ b/internal/resources/kubernetes-profile/delete.go @@ -1,13 +1,14 @@ package kubernetesprofile import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" ) -func DeleteKubernetesProfile(c *api.Client, id string) (bool, error) { - res, err := c.MakeGraphQLRequest(` +func DeleteKubernetesProfile(ctx context.Context, c *api.Client, id string) (bool, error) { + res, err := c.MakeGraphQLRequest(ctx, ` mutation deleteProfile { deleteProfile(id: "`+id+`") } diff --git a/internal/resources/kubernetes-profile/read.go b/internal/resources/kubernetes-profile/read.go index 8cc460a..958d67c 100644 --- a/internal/resources/kubernetes-profile/read.go +++ b/internal/resources/kubernetes-profile/read.go @@ -1,6 +1,7 @@ package kubernetesprofile import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -36,8 +37,8 @@ func ReadKubernetesProfileToResourceData(profile models.KubernetesProfile, d *sc return nil } -func GetKubernetesProfile(c *api.Client, id string) (models.KubernetesProfile, error) { - res, err := c.MakeGraphQLRequest(` +func GetKubernetesProfile(ctx context.Context, c *api.Client, id string) (models.KubernetesProfile, error) { + res, err := c.MakeGraphQLRequest(ctx, ` { getKubernetesProfile(id: "`+id+`") { id diff --git a/internal/resources/kubernetes-profile/update.go b/internal/resources/kubernetes-profile/update.go index e96c1f0..8f2628b 100644 --- a/internal/resources/kubernetes-profile/update.go +++ b/internal/resources/kubernetes-profile/update.go @@ -1,6 +1,7 @@ package kubernetesprofile import ( + "context" "fmt" "log" "strings" @@ -11,9 +12,9 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func UpdateKubernetesProfile(c *api.Client, id any, input models.KubernetesProfileUpdateInput) (bool, error) { +func UpdateKubernetesProfile(ctx context.Context, c *api.Client, id any, input models.KubernetesProfileUpdateInput) (bool, error) { vars := map[string]any{"profileInput": input, "id": id} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation updateKubernetesProfile($profileInput: KubernetesProfileUpdateInput, $id: ID!) { updateKubernetesProfile (profileInput: $profileInput, id: $id) diff --git a/internal/resources/log-trigger.go b/internal/resources/log-trigger.go index b151c43..7880d60 100644 --- a/internal/resources/log-trigger.go +++ b/internal/resources/log-trigger.go @@ -26,7 +26,7 @@ func ResourceLogTrigger() *schema.Resource { Computed: true, }, "name": { - Description: "The name of the resource, also acts as it's unique ID", + Description: "The name of the resource, also acts as its unique ID", Type: schema.TypeString, Required: true, }, @@ -155,7 +155,7 @@ func resourceLogTriggerCreate(ctx context.Context, d *schema.ResourceData, meta return utils.DiagError("Failed to create log trigger input struct from resource data", err, diags) } - logTrigger, err := logtrigger.NewLogTrigger(c, input) + logTrigger, err := logtrigger.NewLogTrigger(ctx, c, input) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -188,7 +188,7 @@ func resourceLogTriggerRead(ctx context.Context, d *schema.ResourceData, meta an var diags diag.Diagnostics c := meta.(*api.Client) - logTrigger, err := logtrigger.GetLogTrigger(c, d.Id()) + logTrigger, err := logtrigger.GetLogTrigger(ctx, c, d.Id()) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -217,7 +217,7 @@ func resourceLogTriggerUpdate(ctx context.Context, d *schema.ResourceData, meta return utils.DiagError("Unable to create log trigger update input struct from resource data", err, diags) } - result, err := logtrigger.UpdateLogTrigger(c, d.Id(), updateInput) + result, err := logtrigger.UpdateLogTrigger(ctx, c, d.Id(), updateInput) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -235,7 +235,7 @@ func resourceLogTriggerUpdate(ctx context.Context, d *schema.ResourceData, meta return utils.DiagError("Failed to Publish following LogTrigger Update", err, diags) } - logTrigger, err := logtrigger.GetLogTrigger(c, d.Id()) + logTrigger, err := logtrigger.GetLogTrigger(ctx, c, d.Id()) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -260,7 +260,7 @@ func resourceLogTriggerDelete(ctx context.Context, d *schema.ResourceData, meta c := meta.(*api.Client) ID := d.Id() - result, err := logtrigger.DeleteLogTrigger(c, ID) + result, err := logtrigger.DeleteLogTrigger(ctx, c, ID) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) diff --git a/internal/resources/log-trigger/create.go b/internal/resources/log-trigger/create.go index 43163ae..aaacb20 100644 --- a/internal/resources/log-trigger/create.go +++ b/internal/resources/log-trigger/create.go @@ -1,6 +1,7 @@ package logtrigger import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -38,9 +39,9 @@ func CreateLogTriggerInputFromResourceData(d *schema.ResourceData) (models.Creat return res, nil } -func NewLogTrigger(c *api.Client, triggerInput models.CreateLogTriggerInput) (models.LogTrigger, error) { +func NewLogTrigger(ctx context.Context, c *api.Client, triggerInput models.CreateLogTriggerInput) (models.LogTrigger, error) { vars := map[string]any{"triggerInput": triggerInput} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation newLogTrigger($triggerInput: LogTriggerInput) { newLogTrigger (triggerInput: $triggerInput) { diff --git a/internal/resources/log-trigger/delete.go b/internal/resources/log-trigger/delete.go index 71fd1b5..e4d436c 100644 --- a/internal/resources/log-trigger/delete.go +++ b/internal/resources/log-trigger/delete.go @@ -1,13 +1,14 @@ package logtrigger import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" ) -func DeleteLogTrigger(c *api.Client, id string) (bool, error) { - res, err := c.MakeGraphQLRequest(` +func DeleteLogTrigger(ctx context.Context, c *api.Client, id string) (bool, error) { + res, err := c.MakeGraphQLRequest(ctx, ` mutation deleteTrigger { deleteTrigger(id: "`+id+`") } diff --git a/internal/resources/log-trigger/read.go b/internal/resources/log-trigger/read.go index 692e01e..8f05489 100644 --- a/internal/resources/log-trigger/read.go +++ b/internal/resources/log-trigger/read.go @@ -1,6 +1,7 @@ package logtrigger import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -38,8 +39,8 @@ func ReadLogTriggerToResourceData(logTrigger models.LogTrigger, d *schema.Resour return nil } -func GetLogTrigger(c *api.Client, id string) (models.LogTrigger, error) { - res, err := c.MakeGraphQLRequest(` +func GetLogTrigger(ctx context.Context, c *api.Client, id string) (models.LogTrigger, error) { + res, err := c.MakeGraphQLRequest(ctx, ` { getLogTrigger(id: "`+id+`") { id diff --git a/internal/resources/log-trigger/update.go b/internal/resources/log-trigger/update.go index c05cc82..f0a1cec 100644 --- a/internal/resources/log-trigger/update.go +++ b/internal/resources/log-trigger/update.go @@ -1,6 +1,7 @@ package logtrigger import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -54,9 +55,9 @@ func UpdateLogTriggerInputFromResourceData(d *schema.ResourceData) (models.Updat } -func UpdateLogTrigger(c *api.Client, id any, triggerInput models.UpdateLogTriggerInput) (bool, error) { +func UpdateLogTrigger(ctx context.Context, c *api.Client, id any, triggerInput models.UpdateLogTriggerInput) (bool, error) { vars := map[string]any{"triggerInput": triggerInput, "id": id} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation updateLogTrigger($triggerInput: LogTriggerInput, $id: ID) { updateLogTrigger (triggerInput: $triggerInput, id: $id) diff --git a/internal/resources/tests/web-user-response_test.go b/internal/resources/tests/web-user-response_test.go new file mode 100644 index 0000000..3c5a8ee --- /dev/null +++ b/internal/resources/tests/web-user-response_test.go @@ -0,0 +1,137 @@ +package tests + +import ( + "fmt" + "testing" + + "github.com/CheckPointSW/terraform-provider-infinity-next/internal/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccWebUserResponseBasic(t *testing.T) { + nameAttribute := acctest.GenerateResourceName() + resourceName := "inext_web_user_response." + nameAttribute + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: acctest.CheckResourceDestroyed([]string{resourceName}), + Steps: []resource.TestStep{ + { + Config: webUserResponseBasicConfig(nameAttribute), + Check: resource.ComposeTestCheckFunc( + append(acctest.ComposeTestCheckResourceAttrsFromMap(resourceName, map[string]string{ + "name": nameAttribute, + "mode": "BlockPage", + "http_response_code": "403", + }), + resource.TestCheckResourceAttrSet(resourceName, "id"), + )..., + ), + }, + { + ResourceName: resourceName, + ImportState: true, + }, + { + Config: webUserResponseUpdateCreateSourceIdentifiersConfig(nameAttribute), + Check: resource.ComposeTestCheckFunc( + append(acctest.ComposeTestCheckResourceAttrsFromMap(resourceName, map[string]string{ + "name": nameAttribute, + "mode": "Redirect", + "redirect_url": "http://localhost:1234/test", + }), + resource.TestCheckResourceAttrSet(resourceName, "id"), + )..., + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccWebUserResponseFull(t *testing.T) { + nameAttribute := acctest.GenerateResourceName() + resourceName := "inext_web_user_response." + nameAttribute + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + CheckDestroy: acctest.CheckResourceDestroyed([]string{resourceName}), + Steps: []resource.TestStep{ + { + Config: webUserResponseWithIdentifiersConfig(nameAttribute), + Check: resource.ComposeTestCheckFunc( + append(acctest.ComposeTestCheckResourceAttrsFromMap(resourceName, map[string]string{ + "name": nameAttribute, + "mode": "BlockPage", + "http_response_code": "403", + "message_title": "some message title", + "message_body": "some message body", + }), + resource.TestCheckResourceAttrSet(resourceName, "id"), + )..., + ), + }, + { + ResourceName: resourceName, + ImportState: true, + }, + { + Config: webUserResponseUpdateSourceIdentifiersConfig(nameAttribute), + Check: resource.ComposeTestCheckFunc( + append(acctest.ComposeTestCheckResourceAttrsFromMap(resourceName, map[string]string{ + "name": nameAttribute, + "mode": "Redirect", + "redirect_url": "http://localhost:1234/test", + "x_event_id": "true", + }), + resource.TestCheckResourceAttrSet(resourceName, "id"), + )..., + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func webUserResponseBasicConfig(name string) string { + return fmt.Sprintf(` +resource "inext_web_user_response" %[1]q { + name = %[1]q + mode = "BlockPage" + http_response_code = 403 +} +`, name) +} + +func webUserResponseWithIdentifiersConfig(name string) string { + return fmt.Sprintf(` +resource "inext_web_user_response" %[1]q { + name = %[1]q + mode = "BlockPage" + http_response_code = 403 + message_title = "some message title" + message_body = "some message body" +} +`, name) +} + +func webUserResponseUpdateCreateSourceIdentifiersConfig(name string) string { + return fmt.Sprintf(` +resource "inext_web_user_response" %[1]q { + name = %[1]q + mode = "Redirect" + redirect_url = "http://localhost:1234/test" +} +`, name) +} + +func webUserResponseUpdateSourceIdentifiersConfig(name string) string { + return fmt.Sprintf(` +resource "inext_web_user_response" %[1]q { + name = %[1]q + mode = "Redirect" + redirect_url = "http://localhost:1234/test" + x_event_id = true +} +`, name) +} diff --git a/internal/resources/trusted-sources.go b/internal/resources/trusted-sources.go index 8dbdeb0..f07e726 100644 --- a/internal/resources/trusted-sources.go +++ b/internal/resources/trusted-sources.go @@ -36,7 +36,7 @@ func ResourceTrustedSources() *schema.Resource { }, "name": { Type: schema.TypeString, - Description: "The name of the resource, also acts as it's unique ID", + Description: "The name of the resource, also acts as its unique ID", Required: true, }, "min_num_of_sources": { @@ -72,7 +72,7 @@ func resourceTrustedSourcesCreate(ctx context.Context, d *schema.ResourceData, m return utils.DiagError("unable to perform TrustedSourceBehavior Create", err, diags) } - behavior, err := trustedsources.NewTrustedSourceBehavior(c, createInput) + behavior, err := trustedsources.NewTrustedSourceBehavior(ctx, c, createInput) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -105,7 +105,7 @@ func resourceTrustedSourcesRead(ctx context.Context, d *schema.ResourceData, met var diags diag.Diagnostics c := meta.(*api.Client) - behavior, err := trustedsources.GetTrustedSourceBehavior(c, d.Id()) + behavior, err := trustedsources.GetTrustedSourceBehavior(ctx, c, d.Id()) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -134,7 +134,7 @@ func resourceTrustedSourcesUpdate(ctx context.Context, d *schema.ResourceData, m return utils.DiagError("unable to perform TrustedSourceBehavior Update", err, diags) } - result, err := trustedsources.UpdateTrustedSourceBehavior(c, d.Id(), updateInput) + result, err := trustedsources.UpdateTrustedSourceBehavior(ctx, c, d.Id(), updateInput) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -152,7 +152,7 @@ func resourceTrustedSourcesUpdate(ctx context.Context, d *schema.ResourceData, m return utils.DiagError("failed to Publish following TrustedSourceBehavior Update", err, diags) } - behavior, err := trustedsources.GetTrustedSourceBehavior(c, d.Id()) + behavior, err := trustedsources.GetTrustedSourceBehavior(ctx, c, d.Id()) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -176,7 +176,7 @@ func resourceTrustedSourcesDelete(ctx context.Context, d *schema.ResourceData, m var diags diag.Diagnostics c := meta.(*api.Client) - result, err := trustedsources.DeleteTrustedSourceBehavior(c, d.Id()) + result, err := trustedsources.DeleteTrustedSourceBehavior(ctx, c, d.Id()) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) diff --git a/internal/resources/trusted-sources/create.go b/internal/resources/trusted-sources/create.go index 1902b5b..d7abf7e 100644 --- a/internal/resources/trusted-sources/create.go +++ b/internal/resources/trusted-sources/create.go @@ -1,6 +1,7 @@ package trustedsources import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -20,9 +21,9 @@ func CreateTrustedSourceBehaviorInputFromResourceData(d *schema.ResourceData) (m return input, nil } -func NewTrustedSourceBehavior(c *api.Client, input models.CreateTrustedSourceBehaviorInput) (models.TrustedSourceBehavior, error) { +func NewTrustedSourceBehavior(ctx context.Context, c *api.Client, input models.CreateTrustedSourceBehaviorInput) (models.TrustedSourceBehavior, error) { vars := map[string]any{"ownerId": nil, "practiceId": nil, "behaviorInput": input} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation newTrustedSourceBehavior($ownerId: ID, $practiceId: ID, $behaviorInput: TrustedSourceBehaviorInput) { newTrustedSourceBehavior(ownerId: $ownerId, practiceId: $practiceId, behaviorInput: $behaviorInput) { diff --git a/internal/resources/trusted-sources/delete.go b/internal/resources/trusted-sources/delete.go index 48d9fd4..c96a7e4 100644 --- a/internal/resources/trusted-sources/delete.go +++ b/internal/resources/trusted-sources/delete.go @@ -1,13 +1,14 @@ package trustedsources import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" ) -func DeleteTrustedSourceBehavior(c *api.Client, id string) (bool, error) { - res, err := c.MakeGraphQLRequest(` +func DeleteTrustedSourceBehavior(ctx context.Context, c *api.Client, id string) (bool, error) { + res, err := c.MakeGraphQLRequest(ctx, ` mutation deleteBehavior { deleteBehavior(id: "`+id+`") } diff --git a/internal/resources/trusted-sources/read.go b/internal/resources/trusted-sources/read.go index 8c3b99c..8d0e4fd 100644 --- a/internal/resources/trusted-sources/read.go +++ b/internal/resources/trusted-sources/read.go @@ -1,6 +1,7 @@ package trustedsources import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -9,8 +10,8 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func GetTrustedSourceBehavior(c *api.Client, id string) (models.TrustedSourceBehavior, error) { - res, err := c.MakeGraphQLRequest(` +func GetTrustedSourceBehavior(ctx context.Context, c *api.Client, id string) (models.TrustedSourceBehavior, error) { + res, err := c.MakeGraphQLRequest(ctx, ` { getTrustedSourceBehavior(id: "`+id+`") { id diff --git a/internal/resources/trusted-sources/update.go b/internal/resources/trusted-sources/update.go index 457178c..8af9c53 100644 --- a/internal/resources/trusted-sources/update.go +++ b/internal/resources/trusted-sources/update.go @@ -1,6 +1,7 @@ package trustedsources import ( + "context" "fmt" "strings" @@ -43,10 +44,10 @@ func UpdateTrustedSourceBehaviorInputFromResourceData(d *schema.ResourceData) (m return res, nil } -func UpdateTrustedSourceBehavior(c *api.Client, id string, input models.UpdateTrustedSourceBehaviorInput) (bool, error) { +func UpdateTrustedSourceBehavior(ctx context.Context, c *api.Client, id string, input models.UpdateTrustedSourceBehaviorInput) (bool, error) { vars := map[string]any{"behaviorInput": input, "id": id} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation updateTrustedSourceBehavior($behaviorInput: TrustedSourceBehaviorUpdateInput, $id: ID!) { updateTrustedSourceBehavior(behaviorInput: $behaviorInput, id: $id) diff --git a/internal/resources/web-api-asset.go b/internal/resources/web-api-asset.go index 7f7ba9d..254d2a7 100644 --- a/internal/resources/web-api-asset.go +++ b/internal/resources/web-api-asset.go @@ -65,7 +65,7 @@ func ResourceWebAPIAsset() *schema.Resource { }, "name": { Type: schema.TypeString, - Description: "The name of the resource, also acts as it's unique ID", + Description: "The name of the resource, also acts as its unique ID", Required: true, }, "profiles": { @@ -276,7 +276,7 @@ func resourceWebApiAssetCreate(ctx context.Context, d *schema.ResourceData, meta return utils.DiagError("unable to perform WebAPIAsset Create", err, diags) } - asset, err := webapiasset.NewWebAPIAsset(c, createInput) + asset, err := webapiasset.NewWebAPIAsset(ctx, c, createInput) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("Failed to discard changes", discardErr, diags) @@ -310,7 +310,7 @@ func resourceWebApiAssetRead(ctx context.Context, d *schema.ResourceData, meta a c := meta.(*api.Client) - asset, err := webapiasset.GetWebAPIAsset(c, d.Id()) + asset, err := webapiasset.GetWebAPIAsset(ctx, c, d.Id()) if err != nil { return utils.DiagError("unable to perform get WebAPIAsset", err, diags) } @@ -332,7 +332,7 @@ func resourceWebApiAssetUpdate(ctx context.Context, d *schema.ResourceData, meta return utils.DiagError("unable to perform WebAPIAsset update", err, diags) } - result, err := webapiasset.UpdateWebAPIAsset(c, d.Id(), updateInput) + result, err := webapiasset.UpdateWebAPIAsset(ctx, c, d.Id(), updateInput) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -351,7 +351,7 @@ func resourceWebApiAssetUpdate(ctx context.Context, d *schema.ResourceData, meta } // get the newly created asset and read it into the state - newAsset, err := webapiasset.GetWebAPIAsset(c, d.Id()) + newAsset, err := webapiasset.GetWebAPIAsset(ctx, c, d.Id()) if err != nil { return utils.DiagError("unable to perform get WebAPIAsset", err, diags) } @@ -368,7 +368,7 @@ func resourceWebApiAssetDelete(ctx context.Context, d *schema.ResourceData, meta c := meta.(*api.Client) ID := d.Id() - result, err := webapiasset.DeleteWebAPIAsset(c, ID) + result, err := webapiasset.DeleteWebAPIAsset(ctx, c, ID) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) diff --git a/internal/resources/web-api-asset/create.go b/internal/resources/web-api-asset/create.go index ee55d12..f4e97af 100644 --- a/internal/resources/web-api-asset/create.go +++ b/internal/resources/web-api-asset/create.go @@ -1,6 +1,7 @@ package webapiasset import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -25,9 +26,9 @@ func CreateWebAPIAssetInputFromResourceData(d *schema.ResourceData) (models.Crea } // NewWebAPIAsset sends a request to create the WebAPIAsset and retruns the newly created asset -func NewWebAPIAsset(c *api.Client, input models.CreateWebAPIAssetInput) (models.WebAPIAsset, error) { +func NewWebAPIAsset(ctx context.Context, c *api.Client, input models.CreateWebAPIAssetInput) (models.WebAPIAsset, error) { vars := map[string]any{"assetInput": input} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation newWebAPIAsset($assetInput: WebAPIAssetInput!) { newWebAPIAsset(assetInput: $assetInput) { diff --git a/internal/resources/web-api-asset/delete.go b/internal/resources/web-api-asset/delete.go index 98f977e..2c10700 100644 --- a/internal/resources/web-api-asset/delete.go +++ b/internal/resources/web-api-asset/delete.go @@ -1,13 +1,14 @@ package webapiasset import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" ) -func DeleteWebAPIAsset(c *api.Client, id string) (bool, error) { - res, err := c.MakeGraphQLRequest(` +func DeleteWebAPIAsset(ctx context.Context, c *api.Client, id string) (bool, error) { + res, err := c.MakeGraphQLRequest(ctx, ` mutation deleteAsset { deleteAsset(id: "`+id+`") } diff --git a/internal/resources/web-api-asset/read.go b/internal/resources/web-api-asset/read.go index 9b78806..49ea6b6 100644 --- a/internal/resources/web-api-asset/read.go +++ b/internal/resources/web-api-asset/read.go @@ -1,6 +1,7 @@ package webapiasset import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -57,8 +58,8 @@ func ReadWebAPIAssetToResourceData(asset models.WebAPIAsset, d *schema.ResourceD return nil } -func GetWebAPIAsset(c *api.Client, id string) (models.WebAPIAsset, error) { - res, err := c.MakeGraphQLRequest(` +func GetWebAPIAsset(ctx context.Context, c *api.Client, id string) (models.WebAPIAsset, error) { + res, err := c.MakeGraphQLRequest(ctx, ` { getWebAPIAsset(id: "`+id+`") { id diff --git a/internal/resources/web-api-asset/update.go b/internal/resources/web-api-asset/update.go index be69cd9..f7f6f73 100644 --- a/internal/resources/web-api-asset/update.go +++ b/internal/resources/web-api-asset/update.go @@ -1,6 +1,7 @@ package webapiasset import ( + "context" "fmt" "strings" @@ -10,9 +11,9 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func UpdateWebAPIAsset(c *api.Client, id any, input models.UpdateWebAPIAssetInput) (bool, error) { +func UpdateWebAPIAsset(ctx context.Context, c *api.Client, id any, input models.UpdateWebAPIAssetInput) (bool, error) { vars := map[string]any{"assetInput": input, "id": id} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation updateWebAPIAsset($assetInput: WebAPIAssetUpdateInput!, $id: ID!) { updateWebAPIAsset(assetInput: $assetInput, id: $id) diff --git a/internal/resources/web-api-practice.go b/internal/resources/web-api-practice.go index 739b834..ddff3a8 100644 --- a/internal/resources/web-api-practice.go +++ b/internal/resources/web-api-practice.go @@ -30,7 +30,7 @@ func ResourceWebAPIPractice() *schema.Resource { }, "name": { Type: schema.TypeString, - Description: "The name of the resource, also acts as it's unique ID", + Description: "The name of the resource, also acts as its unique ID", Required: true, }, "practice_type": { @@ -198,7 +198,7 @@ func resourceWebAPIPracticeCreate(ctx context.Context, d *schema.ResourceData, m return utils.DiagError("unable to perform WebAPIPractice Create", err, diags) } - practice, err := webapipractice.NewWebAPIPractice(c, createInput) + practice, err := webapipractice.NewWebAPIPractice(ctx, c, createInput) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -229,12 +229,10 @@ func resourceWebAPIPracticeCreate(ctx context.Context, d *schema.ResourceData, m func resourceWebAPIPracticeRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { var diags diag.Diagnostics - c := meta.(*api.Client) - id := d.Id() - practice, err := webapipractice.GetWebAPIPractice(c, id) + practice, err := webapipractice.GetWebAPIPractice(ctx, c, id) if err != nil { return utils.DiagError("unable to perform WebAPIPractice Read", err, diags) } @@ -256,7 +254,7 @@ func resourceWebAPIPracticeUpdate(ctx context.Context, d *schema.ResourceData, m return utils.DiagError("unable to perform WebAPIPractice Update", err, diags) } - result, err := webapipractice.UpdateWebAPIPractice(c, d.Id(), updateInput) + result, err := webapipractice.UpdateWebAPIPractice(ctx, c, d.Id(), updateInput) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -274,7 +272,7 @@ func resourceWebAPIPracticeUpdate(ctx context.Context, d *schema.ResourceData, m return utils.DiagError("failed to Publish following WebAPIPractice Update", err, diags) } - practice, err := webapipractice.GetWebAPIPractice(c, d.Id()) + practice, err := webapipractice.GetWebAPIPractice(ctx, c, d.Id()) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -298,7 +296,7 @@ func resourceWebAPIPracticeDelete(ctx context.Context, d *schema.ResourceData, m var diags diag.Diagnostics c := meta.(*api.Client) - result, err := webapipractice.DeleteWebAPIPractice(c, d.Id()) + result, err := webapipractice.DeleteWebAPIPractice(ctx, c, d.Id()) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) diff --git a/internal/resources/web-api-practice/create.go b/internal/resources/web-api-practice/create.go index 3ee028a..4c2827f 100644 --- a/internal/resources/web-api-practice/create.go +++ b/internal/resources/web-api-practice/create.go @@ -1,6 +1,7 @@ package webapipractice import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -32,9 +33,9 @@ func CreateWebAPIPracticeInputFromResourceData(d *schema.ResourceData) (models.C return res, nil } -func NewWebAPIPractice(c *api.Client, input models.CreateWebAPIPracticeInput) (models.WebAPIPractice, error) { +func NewWebAPIPractice(ctx context.Context, c *api.Client, input models.CreateWebAPIPracticeInput) (models.WebAPIPractice, error) { vars := map[string]any{"ownerId": nil, "mainMode": nil, "subPracticeModes": nil, "practiceInput": input} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation newWebAPIPractice($ownerId: ID, $mainMode: PracticeMode, $subPracticeModes: [PracticeModeInput], $practiceInput: WebAPIPracticeInput) { newWebAPIPractice(ownerId: $ownerId, subPracticeModes: $subPracticeModes, mainMode: $mainMode, practiceInput: $practiceInput) { diff --git a/internal/resources/web-api-practice/delete.go b/internal/resources/web-api-practice/delete.go index 37ce935..4a1f2bd 100644 --- a/internal/resources/web-api-practice/delete.go +++ b/internal/resources/web-api-practice/delete.go @@ -1,13 +1,14 @@ package webapipractice import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" ) -func DeleteWebAPIPractice(c *api.Client, id string) (bool, error) { - res, err := c.MakeGraphQLRequest(` +func DeleteWebAPIPractice(ctx context.Context, c *api.Client, id string) (bool, error) { + res, err := c.MakeGraphQLRequest(ctx, ` mutation deletePractice { deletePractice(id: "`+id+`") } diff --git a/internal/resources/web-api-practice/read.go b/internal/resources/web-api-practice/read.go index 56350ff..c0ab112 100644 --- a/internal/resources/web-api-practice/read.go +++ b/internal/resources/web-api-practice/read.go @@ -1,6 +1,7 @@ package webapipractice import ( + "context" "encoding/base64" "fmt" "strings" @@ -50,10 +51,8 @@ func ReadWebAPIPracticeToResourceData(practice models.WebAPIPractice, d *schema. switch practice.APIAttacks.AdvancedSetting.IllegalHttpMethods { case "Yes": advancedSettings.IllegalHttpMethods = true - case "No": - advancedSettings.IllegalHttpMethods = false default: - return fmt.Errorf("invalid illegalHttpMethods %s", practice.APIAttacks.AdvancedSetting.IllegalHttpMethods) + advancedSettings.IllegalHttpMethods = false } apiAttacks := models.SchemaAPIAttacks{ @@ -94,8 +93,8 @@ func ReadWebAPIPracticeToResourceData(practice models.WebAPIPractice, d *schema. return nil } -func GetWebAPIPractice(c *api.Client, id string) (models.WebAPIPractice, error) { - res, err := c.MakeGraphQLRequest(` +func GetWebAPIPractice(ctx context.Context, c *api.Client, id string) (models.WebAPIPractice, error) { + res, err := c.MakeGraphQLRequest(ctx, ` { getWebAPIPractice(id: "`+id+`") { id diff --git a/internal/resources/web-api-practice/update.go b/internal/resources/web-api-practice/update.go index bf17af9..bf84b96 100644 --- a/internal/resources/web-api-practice/update.go +++ b/internal/resources/web-api-practice/update.go @@ -1,6 +1,7 @@ package webapipractice import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -43,10 +44,10 @@ func UpdateWebAPIPracticeInputFromResourceData(d *schema.ResourceData) (models.U return updateInput, nil } -func UpdateWebAPIPractice(c *api.Client, id string, input models.UpdatePracticeInput) (bool, error) { +func UpdateWebAPIPractice(ctx context.Context, c *api.Client, id string, input models.UpdatePracticeInput) (bool, error) { vars := map[string]any{"practiceInput": input, "id": id, "ownerId": nil} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation updateWebAPIPractice($practiceInput: WebAPIPracticeUpdateInput, $id: ID!, $ownerId: ID) { updateWebAPIPractice(practiceInput: $practiceInput, id: $id, ownerId: $ownerId) diff --git a/internal/resources/web-app-asset.go b/internal/resources/web-app-asset.go index 1e2752b..ef5e68d 100644 --- a/internal/resources/web-app-asset.go +++ b/internal/resources/web-app-asset.go @@ -36,7 +36,7 @@ func ResourceWebAppAsset() *schema.Resource { }, "name": { Type: schema.TypeString, - Description: "The name of the resource, also acts as it's unique ID", + Description: "The name of the resource, also acts as its unique ID", Required: true, }, "profiles": { @@ -94,7 +94,7 @@ func ResourceWebAppAsset() *schema.Resource { "main_mode": { Type: schema.TypeString, Description: "The mode of the practice: Prevent, Inactive, Disabled or Learn", - Optional: true, + Required: true, }, "sub_practices_modes": { Type: schema.TypeMap, @@ -244,7 +244,7 @@ func resourceWebAppAssetCreate(ctx context.Context, d *schema.ResourceData, meta return utils.DiagError("unable to perform WebAppAsset Create", err, diags) } - asset, err := webappasset.NewWebApplicationAsset(c, createInput) + asset, err := webappasset.NewWebApplicationAsset(ctx, c, createInput) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -278,7 +278,7 @@ func resourceWebAppAssetRead(ctx context.Context, d *schema.ResourceData, meta a c := meta.(*api.Client) - asset, err := webappasset.GetWebApplicationAsset(c, d.Id()) + asset, err := webappasset.GetWebApplicationAsset(ctx, c, d.Id()) if err != nil { return utils.DiagError("unable to perform WebAppAsset Read", err, diags) } @@ -295,7 +295,7 @@ func resourceWebAppAssetUpdate(ctx context.Context, d *schema.ResourceData, meta c := meta.(*api.Client) - oldAsset, err := webappasset.GetWebApplicationAsset(c, d.Id()) + oldAsset, err := webappasset.GetWebApplicationAsset(ctx, c, d.Id()) if err != nil { return utils.DiagError("unable to perform get WebApplicationAsset for updating", err, diags) } @@ -305,7 +305,7 @@ func resourceWebAppAssetUpdate(ctx context.Context, d *schema.ResourceData, meta return utils.DiagError("unable to perform WebAppAsset Update", err, diags) } - result, err := webappasset.UpdateWebApplicationAsset(c, d.Id(), updateInput) + result, err := webappasset.UpdateWebApplicationAsset(ctx, c, d.Id(), updateInput) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -323,7 +323,7 @@ func resourceWebAppAssetUpdate(ctx context.Context, d *schema.ResourceData, meta return utils.DiagError("failed to Publish following WebAppAsset Update", err, diags) } - asset, err := webappasset.GetWebApplicationAsset(c, d.Id()) + asset, err := webappasset.GetWebApplicationAsset(ctx, c, d.Id()) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -348,7 +348,7 @@ func resourceWebAppAssetDelete(ctx context.Context, d *schema.ResourceData, meta c := meta.(*api.Client) ID := d.Id() - result, err := webappasset.DeleteWebApplicationAsset(c, ID) + result, err := webappasset.DeleteWebApplicationAsset(ctx, c, ID) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) diff --git a/internal/resources/web-app-asset/create.go b/internal/resources/web-app-asset/create.go index 118a002..e7f1be8 100644 --- a/internal/resources/web-app-asset/create.go +++ b/internal/resources/web-app-asset/create.go @@ -1,6 +1,7 @@ package webappasset import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -24,9 +25,9 @@ func CreateWebApplicationAssetInputFromResourceData(d *schema.ResourceData) (mod return res, nil } -func NewWebApplicationAsset(c *api.Client, input models.CreateWebApplicationAssetInput) (models.WebApplicationAsset, error) { +func NewWebApplicationAsset(ctx context.Context, c *api.Client, input models.CreateWebApplicationAssetInput) (models.WebApplicationAsset, error) { vars := map[string]any{"assetInput": input} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation newWebApplicationAsset($assetInput: WebApplicationAssetInput!) { newWebApplicationAsset(assetInput: $assetInput) { diff --git a/internal/resources/web-app-asset/delete.go b/internal/resources/web-app-asset/delete.go index 47edd3a..c43f00d 100644 --- a/internal/resources/web-app-asset/delete.go +++ b/internal/resources/web-app-asset/delete.go @@ -1,13 +1,14 @@ package webappasset import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" ) -func DeleteWebApplicationAsset(c *api.Client, id string) (bool, error) { - res, err := c.MakeGraphQLRequest(` +func DeleteWebApplicationAsset(ctx context.Context, c *api.Client, id string) (bool, error) { + res, err := c.MakeGraphQLRequest(ctx, ` mutation deleteAsset { deleteAsset(id: "`+id+`") } diff --git a/internal/resources/web-app-asset/read.go b/internal/resources/web-app-asset/read.go index 53ccfb9..7407dfe 100644 --- a/internal/resources/web-app-asset/read.go +++ b/internal/resources/web-app-asset/read.go @@ -1,6 +1,7 @@ package webappasset import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -57,8 +58,8 @@ func ReadWebApplicationAssetToResourceData(asset models.WebApplicationAsset, d * return nil } -func GetWebApplicationAsset(c *api.Client, id string) (models.WebApplicationAsset, error) { - res, err := c.MakeGraphQLRequest(` +func GetWebApplicationAsset(ctx context.Context, c *api.Client, id string) (models.WebApplicationAsset, error) { + res, err := c.MakeGraphQLRequest(ctx, ` { getWebApplicationAsset(id: "`+id+`") { id diff --git a/internal/resources/web-app-asset/update.go b/internal/resources/web-app-asset/update.go index 689d77a..6c639fc 100644 --- a/internal/resources/web-app-asset/update.go +++ b/internal/resources/web-app-asset/update.go @@ -1,6 +1,7 @@ package webappasset import ( + "context" "fmt" "strings" @@ -132,9 +133,9 @@ func UpdateWebApplicationAssetInputFromResourceData(d *schema.ResourceData, asse return updateInput, nil } -func UpdateWebApplicationAsset(c *api.Client, id any, input models.UpdateWebApplicationAssetInput) (bool, error) { +func UpdateWebApplicationAsset(ctx context.Context, c *api.Client, id any, input models.UpdateWebApplicationAssetInput) (bool, error) { vars := map[string]any{"assetInput": input, "id": id} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation updateWebApplicationAsset($assetInput: WebApplicationAssetUpdateInput!, $id: ID!) { updateWebApplicationAsset(assetInput: $assetInput, id: $id) diff --git a/internal/resources/web-app-practice.go b/internal/resources/web-app-practice.go index 272e6f6..9c2b29e 100644 --- a/internal/resources/web-app-practice.go +++ b/internal/resources/web-app-practice.go @@ -30,7 +30,7 @@ func ResourceWebAppPractice() *schema.Resource { }, "name": { Type: schema.TypeString, - Description: "The name of the resource, also acts as it's unique ID", + Description: "The name of the resource, also acts as its unique ID", Required: true, }, "practice_type": { @@ -274,7 +274,7 @@ func resourceWebAppPracticeCreate(ctx context.Context, d *schema.ResourceData, m return utils.DiagError("unable to perform WebAppPractice Create", err, diags) } - practice, err := webapppractice.NewWebApplicationPractice(c, createInput) + practice, err := webapppractice.NewWebApplicationPractice(ctx, c, createInput) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -310,7 +310,7 @@ func resourceWebAppPracticeRead(ctx context.Context, d *schema.ResourceData, met id := d.Id() - practice, err := webapppractice.GetWebApplicationPractice(c, id) + practice, err := webapppractice.GetWebApplicationPractice(ctx, c, id) if err != nil { return utils.DiagError("unable to perform WebAppPractice Read", err, diags) } @@ -332,7 +332,7 @@ func resourceWebAppPracticeUpdate(ctx context.Context, d *schema.ResourceData, m return utils.DiagError("Failed to parse WebAppPractice Update to struct", err, diags) } - result, err := webapppractice.UpdateWebApplicationPractice(c, d.Id(), updateInput) + result, err := webapppractice.UpdateWebApplicationPractice(ctx, c, d.Id(), updateInput) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -350,7 +350,7 @@ func resourceWebAppPracticeUpdate(ctx context.Context, d *schema.ResourceData, m return utils.DiagError("failed to Publish following WebAppPractice Update", err, diags) } - practice, err := webapppractice.GetWebApplicationPractice(c, d.Id()) + practice, err := webapppractice.GetWebApplicationPractice(ctx, c, d.Id()) if err != nil { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) @@ -374,7 +374,7 @@ func resourceWebAppPracticeDelete(ctx context.Context, d *schema.ResourceData, m var diags diag.Diagnostics c := meta.(*api.Client) - result, err := webapppractice.DeleteWebApplicationPractice(c, d.Id()) + result, err := webapppractice.DeleteWebApplicationPractice(ctx, c, d.Id()) if err != nil || !result { if _, discardErr := c.DiscardChanges(); discardErr != nil { diags = utils.DiagError("failed to discard changes", discardErr, diags) diff --git a/internal/resources/web-app-practice/create.go b/internal/resources/web-app-practice/create.go index 55c0188..0007f89 100644 --- a/internal/resources/web-app-practice/create.go +++ b/internal/resources/web-app-practice/create.go @@ -1,6 +1,7 @@ package webapppractice import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -80,9 +81,9 @@ func CreateWebApplicationPracticeInputFromResourceData(d *schema.ResourceData) ( return res, nil } -func NewWebApplicationPractice(c *api.Client, input models.CreateWebApplicationPracticeInput) (models.WebApplicationPractice, error) { +func NewWebApplicationPractice(ctx context.Context, c *api.Client, input models.CreateWebApplicationPracticeInput) (models.WebApplicationPractice, error) { vars := map[string]any{"ownerId": nil, "mainMode": nil, "subPracticeModes": []any{}, "practiceInput": input} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation newWebApplicationPractice($ownerId: ID, $mainMode: PracticeMode, $subPracticeModes: [PracticeModeInput], $practiceInput: WebApplicationPracticeInput) { newWebApplicationPractice(ownerId: $ownerId, subPracticeModes: $subPracticeModes, mainMode: $mainMode, practiceInput: $practiceInput) { diff --git a/internal/resources/web-app-practice/delete.go b/internal/resources/web-app-practice/delete.go index 43e5457..1c75e5d 100644 --- a/internal/resources/web-app-practice/delete.go +++ b/internal/resources/web-app-practice/delete.go @@ -1,13 +1,14 @@ package webapppractice import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" ) -func DeleteWebApplicationPractice(c *api.Client, id string) (bool, error) { - res, err := c.MakeGraphQLRequest(` +func DeleteWebApplicationPractice(ctx context.Context, c *api.Client, id string) (bool, error) { + res, err := c.MakeGraphQLRequest(ctx, ` mutation deletePractice { deletePractice(id: "`+id+`") } diff --git a/internal/resources/web-app-practice/read.go b/internal/resources/web-app-practice/read.go index 93a4633..8df3211 100644 --- a/internal/resources/web-app-practice/read.go +++ b/internal/resources/web-app-practice/read.go @@ -1,6 +1,7 @@ package webapppractice import ( + "context" "fmt" "strings" @@ -51,10 +52,8 @@ func ReadWebApplicationPracticeToResourceData(practice models.WebApplicationPrac switch practice.WebAttacks.AdvancedSetting.IllegalHttpMethods { case "Yes": advancedSettings.IllegalHttpMethods = true - case "No", "": - advancedSettings.IllegalHttpMethods = false default: - return fmt.Errorf("invalid illegalHttpMethods %s", practice.WebAttacks.AdvancedSetting.IllegalHttpMethods) + advancedSettings.IllegalHttpMethods = false } webAttacks := models.WebApplicationPracticeWebAttacksSchema{ @@ -102,8 +101,8 @@ func ReadWebApplicationPracticeToResourceData(practice models.WebApplicationPrac return nil } -func GetWebApplicationPractice(c *api.Client, id string) (models.WebApplicationPractice, error) { - res, err := c.MakeGraphQLRequest(` +func GetWebApplicationPractice(ctx context.Context, c *api.Client, id string) (models.WebApplicationPractice, error) { + res, err := c.MakeGraphQLRequest(ctx, ` { getWebApplicationPractice(id: "`+id+`") { id diff --git a/internal/resources/web-app-practice/update.go b/internal/resources/web-app-practice/update.go index 73e3558..f8c1c76 100644 --- a/internal/resources/web-app-practice/update.go +++ b/internal/resources/web-app-practice/update.go @@ -1,6 +1,7 @@ package webapppractice import ( + "context" "fmt" "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" @@ -97,10 +98,10 @@ func parseToSchemaWebBot(schemaWebBot any) []models.WebApplicationPracticeWebBot return utils.Map(utils.MustSchemaCollectionToSlice[map[string]any](schemaWebBot), parseFunc) } -func UpdateWebApplicationPractice(c *api.Client, id string, input models.UpdateWebApplicationPracticeInput) (bool, error) { +func UpdateWebApplicationPractice(ctx context.Context, c *api.Client, id string, input models.UpdateWebApplicationPracticeInput) (bool, error) { vars := map[string]any{"practiceInput": input, "id": id, "ownerId": nil} - res, err := c.MakeGraphQLRequest(` + res, err := c.MakeGraphQLRequest(ctx, ` mutation updateWebApplicationPractice($practiceInput: WebApplicationPracticeUpdateInput, $id: ID!, $ownerId: ID) { updateWebApplicationPractice(practiceInput: $practiceInput, id: $id, ownerId: $ownerId) diff --git a/internal/resources/web-user-response.go b/internal/resources/web-user-response.go new file mode 100644 index 0000000..343fc89 --- /dev/null +++ b/internal/resources/web-user-response.go @@ -0,0 +1,213 @@ +package resources + +import ( + "context" + + "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" + webuserresponse "github.com/CheckPointSW/terraform-provider-infinity-next/internal/resources/web-user-response" + "github.com/CheckPointSW/terraform-provider-infinity-next/internal/utils" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +func ResourceWebUserResponse() *schema.Resource { + return &schema.Resource{ + Description: "Determine the response returned to the client who initiated a blocked traffic." + + "The response can be a simple HTTP error code, an HTTP redirect message, or a Block page that a user can view in their browser.", + + CreateContext: resourceWebUserResponseCreate, + ReadContext: resourceWebUserResponseRead, + UpdateContext: resourceWebUserResponseUpdate, + DeleteContext: resourceWebUserResponseDelete, + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + CustomizeDiff: func(ctx context.Context, diff *schema.ResourceDiff, meta interface{}) error { + if diff.HasChange("sources_identifiers") { + return diff.SetNewComputed("sources_identifiers_ids") + } + + return nil + }, + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Description: "The name of the resource, also acts as its unique ID", + Required: true, + }, + "mode": { + Type: schema.TypeString, + Description: "The type of the web user response object", + Required: true, + ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"BlockPage", "Redirect", "ResponseCodeOnly"}, false)), + }, + "message_title": { + Type: schema.TypeString, + Description: "The title of the web page to be shown to the user sending the malicious traffic", + Optional: true, + }, + "message_body": { + Type: schema.TypeString, + Description: "The body of the message to be shown to the user", + Optional: true, + }, + "http_response_code": { + Type: schema.TypeInt, + Description: "It is recommended to use a 403 (Forbidden) as a response code", + Optional: true, + }, + "redirect_url": { + Type: schema.TypeString, + Description: "The client will be redirected to the provided URL where you can provide any customized web page", + Optional: true, + }, + "x_event_id": { + Type: schema.TypeBool, + Description: "When selected the redirect message will include this header with a value that provides an internal reference ID " + + "that will match a security log generated by the incident, if log triggers are configured", + Optional: true, + }, + }, + } +} + +func resourceWebUserResponseCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { + var diags diag.Diagnostics + c := meta.(*api.Client) + + createInput, err := webuserresponse.CreateWebUserResponseBehaviorInputFromResourceData(d) + if err != nil { + return utils.DiagError("unable to perform WebUserResponseBehavior Create", err, diags) + } + + behavior, err := webuserresponse.NewWebUserResponseBehavior(ctx, c, createInput) + if err != nil { + if _, discardErr := c.DiscardChanges(); discardErr != nil { + diags = utils.DiagError("failed to discard changes", discardErr, diags) + } + + return utils.DiagError("unable to perform WebUserResponseBehavior Create", err, diags) + } + + isValid, err := c.PublishChanges() + if err != nil || !isValid { + if _, discardErr := c.DiscardChanges(); discardErr != nil { + diags = utils.DiagError("failed to discard changes", discardErr, diags) + } + + return utils.DiagError("failed to Publish following WebUserResponseBehavior Create", err, diags) + } + + if err := webuserresponse.ReadWebUserResponseBehaviorToResourceData(behavior, d); err != nil { + if _, discardErr := c.DiscardChanges(); discardErr != nil { + diags = utils.DiagError("failed to discard changes", discardErr, diags) + } + + return utils.DiagError("Unable to perform WebUserResponseBehavior Read after Create", err, diags) + } + + return diags +} + +func resourceWebUserResponseRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { + var diags diag.Diagnostics + c := meta.(*api.Client) + + behavior, err := webuserresponse.GetWebUserResponseBehavior(ctx, c, d.Id()) + if err != nil { + if _, discardErr := c.DiscardChanges(); discardErr != nil { + diags = utils.DiagError("failed to discard changes", discardErr, diags) + } + + return utils.DiagError("Unable to perform WebUserResponseBehavior Get before read", err, diags) + } + + if err := webuserresponse.ReadWebUserResponseBehaviorToResourceData(behavior, d); err != nil { + if _, discardErr := c.DiscardChanges(); discardErr != nil { + diags = utils.DiagError("failed to discard changes", discardErr, diags) + } + + return utils.DiagError("Unable to perform WebUserResponseBehavior read to state file", err, diags) + } + + return diags +} + +func resourceWebUserResponseUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { + var diags diag.Diagnostics + c := meta.(*api.Client) + + updateInput, err := webuserresponse.UpdateWebUserResponseBehaviorInputFromResourceData(d) + if err != nil { + return utils.DiagError("unable to perform WebUserResponseBehavior Update", err, diags) + } + + result, err := webuserresponse.UpdateWebUserResponseBehavior(ctx, c, d.Id(), updateInput) + if err != nil || !result { + if _, discardErr := c.DiscardChanges(); discardErr != nil { + diags = utils.DiagError("failed to discard changes", discardErr, diags) + } + + return utils.DiagError("unable to perform WebUserResponseBehavior Update", err, diags) + } + + isValid, err := c.PublishChanges() + if err != nil || !isValid { + if _, discardErr := c.DiscardChanges(); discardErr != nil { + diags = utils.DiagError("failed to discard changes", discardErr, diags) + } + + return utils.DiagError("failed to Publish following WebUserResponseBehavior Update", err, diags) + } + + behavior, err := webuserresponse.GetWebUserResponseBehavior(ctx, c, d.Id()) + if err != nil { + if _, discardErr := c.DiscardChanges(); discardErr != nil { + diags = utils.DiagError("failed to discard changes", discardErr, diags) + } + + return utils.DiagError("Unable to perform WebUserResponseBehavior Get before read after update", err, diags) + } + + if err := webuserresponse.ReadWebUserResponseBehaviorToResourceData(behavior, d); err != nil { + if _, discardErr := c.DiscardChanges(); discardErr != nil { + diags = utils.DiagError("failed to discard changes", discardErr, diags) + } + + return utils.DiagError("Unable to perform WebUserResponseBehavior read to state file after update", err, diags) + } + + return diags +} + +func resourceWebUserResponseDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { + var diags diag.Diagnostics + c := meta.(*api.Client) + + result, err := webuserresponse.DeleteWebUserResponseBehavior(ctx, c, d.Id()) + if err != nil || !result { + if _, discardErr := c.DiscardChanges(); discardErr != nil { + diags = utils.DiagError("failed to discard changes", discardErr, diags) + } + + return utils.DiagError("unable to perform WebUserResponseBehavior Delete", err, diags) + } + + isValid, err := c.PublishChanges() + if err != nil || !isValid { + if _, discardErr := c.DiscardChanges(); discardErr != nil { + diags = utils.DiagError("failed to discard changes", discardErr, diags) + } + + return utils.DiagError("failed to Publish following WebUserResponseBehavior Delete", err, diags) + } + + d.SetId("") + + return diags +} diff --git a/internal/resources/web-user-response/create.go b/internal/resources/web-user-response/create.go new file mode 100644 index 0000000..24013b8 --- /dev/null +++ b/internal/resources/web-user-response/create.go @@ -0,0 +1,56 @@ +package webuserresponse + +import ( + "context" + "fmt" + + "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" + models "github.com/CheckPointSW/terraform-provider-infinity-next/internal/models/web-user-response" + "github.com/CheckPointSW/terraform-provider-infinity-next/internal/utils" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func CreateWebUserResponseBehaviorInputFromResourceData(d *schema.ResourceData) (models.CreateWebUserResponseBehaviorInput, error) { + var input models.CreateWebUserResponseBehaviorInput + + input.Name = d.Get("name").(string) + input.Visibility = "Shared" + input.Mode = d.Get("mode").(string) + input.MessageTitle = d.Get("message_title").(string) + input.MessageBody = d.Get("message_body").(string) + input.HTTPResponseCode = d.Get("http_response_code").(int) + input.RedirectURL = d.Get("redirect_url").(string) + input.XEventID = d.Get("x_event_id").(bool) + + return input, nil +} + +func NewWebUserResponseBehavior(ctx context.Context, c *api.Client, input models.CreateWebUserResponseBehaviorInput) (models.WebUserResponseBehavior, error) { + vars := map[string]any{"ownerId": nil, "practiceId": nil, "behaviorInput": input} + res, err := c.MakeGraphQLRequest(ctx, ` + mutation newWebUserResponseBehavior($ownerId: ID, $practiceId: ID, $behaviorInput: WebUserResponseBehaviorInput) + { + newWebUserResponseBehavior(ownerId: $ownerId, practiceId: $practiceId, behaviorInput: $behaviorInput) { + id + name + mode + messageTitle + messageBody + httpResponseCode + redirectURL + xEventId + } + } + `, "newWebUserResponseBehavior", vars) + + if err != nil { + return models.WebUserResponseBehavior{}, fmt.Errorf("failed to create new WebUserResponseBehavior: %w", err) + } + + behavior, err := utils.UnmarshalAs[models.WebUserResponseBehavior](res) + if err != nil { + return models.WebUserResponseBehavior{}, fmt.Errorf("failed to convert response to CreateWebUserResponseBehaviorResponse struct. Error: %w", err) + } + + return behavior, err +} diff --git a/internal/resources/web-user-response/delete.go b/internal/resources/web-user-response/delete.go new file mode 100644 index 0000000..eb5a3e7 --- /dev/null +++ b/internal/resources/web-user-response/delete.go @@ -0,0 +1,27 @@ +package webuserresponse + +import ( + "context" + "fmt" + + "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" +) + +func DeleteWebUserResponseBehavior(ctx context.Context, c *api.Client, id string) (bool, error) { + res, err := c.MakeGraphQLRequest(ctx, ` + mutation deleteBehavior { + deleteBehavior(id: "`+id+`") + } + `, "deleteBehavior") + + if err != nil { + return false, err + } + + value, ok := res.(bool) + if !ok { + return false, fmt.Errorf("invalid deleteBehavior response %#v should be of type bool", res) + } + + return value, err +} diff --git a/internal/resources/web-user-response/read.go b/internal/resources/web-user-response/read.go new file mode 100644 index 0000000..72f07e1 --- /dev/null +++ b/internal/resources/web-user-response/read.go @@ -0,0 +1,52 @@ +package webuserresponse + +import ( + "context" + "fmt" + + "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" + models "github.com/CheckPointSW/terraform-provider-infinity-next/internal/models/web-user-response" + "github.com/CheckPointSW/terraform-provider-infinity-next/internal/utils" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func GetWebUserResponseBehavior(ctx context.Context, c *api.Client, id string) (models.WebUserResponseBehavior, error) { + res, err := c.MakeGraphQLRequest(ctx, ` + { + getWebUserResponseBehavior(id: "`+id+`") { + id + name + mode + messageTitle + messageBody + httpResponseCode + redirectURL + xEventId + } + } + `, "getWebUserResponseBehavior") + + if err != nil { + return models.WebUserResponseBehavior{}, fmt.Errorf("failed to get WebUserResponseBehavior: %w", err) + } + + behavior, err := utils.UnmarshalAs[models.WebUserResponseBehavior](res) + if err != nil { + return models.WebUserResponseBehavior{}, fmt.Errorf("failed to convert response to WebUserResponseBehavior struct. Error: %w", err) + } + + return behavior, nil +} + +func ReadWebUserResponseBehaviorToResourceData(behavior models.WebUserResponseBehavior, d *schema.ResourceData) error { + d.SetId(behavior.ID) + d.Set("name", behavior.Name) + d.Set("mode", behavior.Mode) + d.Set("message_title", behavior.MessageTitle) + d.Set("message_body", behavior.MessageBody) + d.Set("http_response_code", behavior.HTTPResponseCode) + d.Set("redirect_url", behavior.RedirectURL) + d.Set("x_event_id", behavior.XEventID) + + return nil +} diff --git a/internal/resources/web-user-response/update.go b/internal/resources/web-user-response/update.go new file mode 100644 index 0000000..6e29ede --- /dev/null +++ b/internal/resources/web-user-response/update.go @@ -0,0 +1,45 @@ +package webuserresponse + +import ( + "context" + "fmt" + + "github.com/CheckPointSW/terraform-provider-infinity-next/internal/api" + models "github.com/CheckPointSW/terraform-provider-infinity-next/internal/models/web-user-response" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func UpdateWebUserResponseBehaviorInputFromResourceData(d *schema.ResourceData) (models.UpdateWebUserResponseBehaviorInput, error) { + var res models.UpdateWebUserResponseBehaviorInput + res.Name = d.Get("name").(string) + res.Mode = d.Get("mode").(string) + res.MessageTitle = d.Get("message_title").(string) + res.MessageBody = d.Get("message_body").(string) + res.HTTPResponseCode = d.Get("http_response_code").(int) + res.RedirectURL = d.Get("redirect_url").(string) + res.XEventID = d.Get("x_event_id").(bool) + + return res, nil +} + +func UpdateWebUserResponseBehavior(ctx context.Context, c *api.Client, id string, input models.UpdateWebUserResponseBehaviorInput) (bool, error) { + vars := map[string]any{"behaviorInput": input, "id": id} + + res, err := c.MakeGraphQLRequest(ctx, ` + mutation updateWebUserResponseBehavior($behaviorInput: WebUserResponseBehaviorUpdateInput, $id: ID!) + { + updateWebUserResponseBehavior(behaviorInput: $behaviorInput, id: $id) + } + `, "updateWebUserResponseBehavior", vars) + + if err != nil { + return false, err + } + + isUpdated, ok := res.(bool) + if !ok { + return false, fmt.Errorf("invalid updateWebUserResponseBehavior response %#v should be of type bool", res) + } + + return isUpdated, err +} diff --git a/internal/utils/consts.go b/internal/utils/consts.go new file mode 100644 index 0000000..f73cafe --- /dev/null +++ b/internal/utils/consts.go @@ -0,0 +1,5 @@ +package utils + +const ( + ExpectResourceNotFound = "expectNotFoundResource" +)