From 7da1db3b666f395d582f875c83df487c490a4652 Mon Sep 17 00:00:00 2001 From: Kumar Ganesan Date: Tue, 10 Nov 2020 20:44:02 +0530 Subject: [PATCH 1/2] CIS Firewall vendor changes --- go.mod | 1 + .../user_agent_blocking_rules_v1.go | 943 ++++++++++++++ .../zone_firewall_access_rules_v1.go | 1099 +++++++++++++++++ .../zonelockdownv1/zone_lockdown_v1.go | 982 +++++++++++++++ vendor/modules.txt | 3 + 5 files changed, 3028 insertions(+) create mode 100644 vendor/github.com/IBM/networking-go-sdk/useragentblockingrulesv1/user_agent_blocking_rules_v1.go create mode 100644 vendor/github.com/IBM/networking-go-sdk/zonefirewallaccessrulesv1/zone_firewall_access_rules_v1.go create mode 100644 vendor/github.com/IBM/networking-go-sdk/zonelockdownv1/zone_lockdown_v1.go diff --git a/go.mod b/go.mod index 8afd2e1cf8..1f0ac9b1bb 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/IBM/apigateway-go-sdk v0.0.0-20200414212859-416e5948678a github.com/IBM/go-sdk-core v1.1.0 github.com/IBM/go-sdk-core/v3 v3.3.1 + github.com/IBM/go-sdk-core/v4 v4.5.1 github.com/IBM/ibm-cos-sdk-go v1.3.1 github.com/IBM/ibm-cos-sdk-go-config v1.0.1 github.com/IBM/networking-go-sdk v0.12.0 diff --git a/vendor/github.com/IBM/networking-go-sdk/useragentblockingrulesv1/user_agent_blocking_rules_v1.go b/vendor/github.com/IBM/networking-go-sdk/useragentblockingrulesv1/user_agent_blocking_rules_v1.go new file mode 100644 index 0000000000..e750a43984 --- /dev/null +++ b/vendor/github.com/IBM/networking-go-sdk/useragentblockingrulesv1/user_agent_blocking_rules_v1.go @@ -0,0 +1,943 @@ +/** + * (C) Copyright IBM Corp. 2020. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Package useragentblockingrulesv1 : Operations and models for the UserAgentBlockingRulesV1 service +package useragentblockingrulesv1 + +import ( + "encoding/json" + "fmt" + "github.com/IBM/go-sdk-core/v4/core" + common "github.com/IBM/networking-go-sdk/common" + "reflect" +) + +// UserAgentBlockingRulesV1 : User-Agent Blocking Rules +// +// Version: 1.0.1 +type UserAgentBlockingRulesV1 struct { + Service *core.BaseService + + // Full crn of the service instance. + Crn *string + + // Zone identifier (zone id). + ZoneIdentifier *string +} + +// DefaultServiceURL is the default URL to make service requests to. +const DefaultServiceURL = "https://api.cis.cloud.ibm.com" + +// DefaultServiceName is the default key used to find external configuration information. +const DefaultServiceName = "user_agent_blocking_rules" + +// UserAgentBlockingRulesV1Options : Service options +type UserAgentBlockingRulesV1Options struct { + ServiceName string + URL string + Authenticator core.Authenticator + + // Full crn of the service instance. + Crn *string `validate:"required"` + + // Zone identifier (zone id). + ZoneIdentifier *string `validate:"required"` +} + +// NewUserAgentBlockingRulesV1UsingExternalConfig : constructs an instance of UserAgentBlockingRulesV1 with passed in options and external configuration. +func NewUserAgentBlockingRulesV1UsingExternalConfig(options *UserAgentBlockingRulesV1Options) (userAgentBlockingRules *UserAgentBlockingRulesV1, err error) { + if options.ServiceName == "" { + options.ServiceName = DefaultServiceName + } + + if options.Authenticator == nil { + options.Authenticator, err = core.GetAuthenticatorFromEnvironment(options.ServiceName) + if err != nil { + return + } + } + + userAgentBlockingRules, err = NewUserAgentBlockingRulesV1(options) + if err != nil { + return + } + + err = userAgentBlockingRules.Service.ConfigureService(options.ServiceName) + if err != nil { + return + } + + if options.URL != "" { + err = userAgentBlockingRules.Service.SetServiceURL(options.URL) + } + return +} + +// NewUserAgentBlockingRulesV1 : constructs an instance of UserAgentBlockingRulesV1 with passed in options. +func NewUserAgentBlockingRulesV1(options *UserAgentBlockingRulesV1Options) (service *UserAgentBlockingRulesV1, err error) { + serviceOptions := &core.ServiceOptions{ + URL: DefaultServiceURL, + Authenticator: options.Authenticator, + } + + err = core.ValidateStruct(options, "options") + if err != nil { + return + } + + baseService, err := core.NewBaseService(serviceOptions) + if err != nil { + return + } + + if options.URL != "" { + err = baseService.SetServiceURL(options.URL) + if err != nil { + return + } + } + + service = &UserAgentBlockingRulesV1{ + Service: baseService, + Crn: options.Crn, + ZoneIdentifier: options.ZoneIdentifier, + } + + return +} + +// SetServiceURL sets the service URL +func (userAgentBlockingRules *UserAgentBlockingRulesV1) SetServiceURL(url string) error { + return userAgentBlockingRules.Service.SetServiceURL(url) +} + +// ListAllZoneUserAgentRules : List all user-agent blocking rules +// List all user agent blocking rules. +func (userAgentBlockingRules *UserAgentBlockingRulesV1) ListAllZoneUserAgentRules(listAllZoneUserAgentRulesOptions *ListAllZoneUserAgentRulesOptions) (result *ListUseragentRulesResp, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listAllZoneUserAgentRulesOptions, "listAllZoneUserAgentRulesOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/ua_rules"} + pathParameters := []string{*userAgentBlockingRules.Crn, *userAgentBlockingRules.ZoneIdentifier} + + builder := core.NewRequestBuilder(core.GET) + _, err = builder.ConstructHTTPURL(userAgentBlockingRules.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range listAllZoneUserAgentRulesOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("user_agent_blocking_rules", "V1", "ListAllZoneUserAgentRules") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + if listAllZoneUserAgentRulesOptions.Page != nil { + builder.AddQuery("page", fmt.Sprint(*listAllZoneUserAgentRulesOptions.Page)) + } + if listAllZoneUserAgentRulesOptions.PerPage != nil { + builder.AddQuery("per_page", fmt.Sprint(*listAllZoneUserAgentRulesOptions.PerPage)) + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = userAgentBlockingRules.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalListUseragentRulesResp) + if err != nil { + return + } + response.Result = result + + return +} + +// CreateZoneUserAgentRule : Create a new user-agent blocking rule +// Create a new user-agent blocking rule for a given zone under a service instance. +func (userAgentBlockingRules *UserAgentBlockingRulesV1) CreateZoneUserAgentRule(createZoneUserAgentRuleOptions *CreateZoneUserAgentRuleOptions) (result *UseragentRuleResp, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(createZoneUserAgentRuleOptions, "createZoneUserAgentRuleOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/ua_rules"} + pathParameters := []string{*userAgentBlockingRules.Crn, *userAgentBlockingRules.ZoneIdentifier} + + builder := core.NewRequestBuilder(core.POST) + _, err = builder.ConstructHTTPURL(userAgentBlockingRules.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range createZoneUserAgentRuleOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("user_agent_blocking_rules", "V1", "CreateZoneUserAgentRule") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if createZoneUserAgentRuleOptions.Paused != nil { + body["paused"] = createZoneUserAgentRuleOptions.Paused + } + if createZoneUserAgentRuleOptions.Description != nil { + body["description"] = createZoneUserAgentRuleOptions.Description + } + if createZoneUserAgentRuleOptions.Mode != nil { + body["mode"] = createZoneUserAgentRuleOptions.Mode + } + if createZoneUserAgentRuleOptions.Configuration != nil { + body["configuration"] = createZoneUserAgentRuleOptions.Configuration + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + return + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = userAgentBlockingRules.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalUseragentRuleResp) + if err != nil { + return + } + response.Result = result + + return +} + +// DeleteZoneUserAgentRule : Delete a user-agent blocking rule +// Delete a user-agent blocking rule for a particular zone, given its id. +func (userAgentBlockingRules *UserAgentBlockingRulesV1) DeleteZoneUserAgentRule(deleteZoneUserAgentRuleOptions *DeleteZoneUserAgentRuleOptions) (result *DeleteUseragentRuleResp, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteZoneUserAgentRuleOptions, "deleteZoneUserAgentRuleOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(deleteZoneUserAgentRuleOptions, "deleteZoneUserAgentRuleOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/ua_rules"} + pathParameters := []string{*userAgentBlockingRules.Crn, *userAgentBlockingRules.ZoneIdentifier, *deleteZoneUserAgentRuleOptions.UseragentRuleIdentifier} + + builder := core.NewRequestBuilder(core.DELETE) + _, err = builder.ConstructHTTPURL(userAgentBlockingRules.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range deleteZoneUserAgentRuleOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("user_agent_blocking_rules", "V1", "DeleteZoneUserAgentRule") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = userAgentBlockingRules.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDeleteUseragentRuleResp) + if err != nil { + return + } + response.Result = result + + return +} + +// GetUserAgentRule : Get a user-agent blocking rule's details by id +// For a given service instance, zone id and user-agent rule id, get the user-agent blocking rule details. +func (userAgentBlockingRules *UserAgentBlockingRulesV1) GetUserAgentRule(getUserAgentRuleOptions *GetUserAgentRuleOptions) (result *UseragentRuleResp, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getUserAgentRuleOptions, "getUserAgentRuleOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(getUserAgentRuleOptions, "getUserAgentRuleOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/ua_rules"} + pathParameters := []string{*userAgentBlockingRules.Crn, *userAgentBlockingRules.ZoneIdentifier, *getUserAgentRuleOptions.UseragentRuleIdentifier} + + builder := core.NewRequestBuilder(core.GET) + _, err = builder.ConstructHTTPURL(userAgentBlockingRules.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range getUserAgentRuleOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("user_agent_blocking_rules", "V1", "GetUserAgentRule") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = userAgentBlockingRules.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalUseragentRuleResp) + if err != nil { + return + } + response.Result = result + + return +} + +// UpdateUserAgentRule : Update a user-agent blocking rule +// Update an existing user-agent blocking rule for a given zone under a given service instance. +func (userAgentBlockingRules *UserAgentBlockingRulesV1) UpdateUserAgentRule(updateUserAgentRuleOptions *UpdateUserAgentRuleOptions) (result *UseragentRuleResp, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateUserAgentRuleOptions, "updateUserAgentRuleOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(updateUserAgentRuleOptions, "updateUserAgentRuleOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/ua_rules"} + pathParameters := []string{*userAgentBlockingRules.Crn, *userAgentBlockingRules.ZoneIdentifier, *updateUserAgentRuleOptions.UseragentRuleIdentifier} + + builder := core.NewRequestBuilder(core.PUT) + _, err = builder.ConstructHTTPURL(userAgentBlockingRules.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range updateUserAgentRuleOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("user_agent_blocking_rules", "V1", "UpdateUserAgentRule") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if updateUserAgentRuleOptions.Paused != nil { + body["paused"] = updateUserAgentRuleOptions.Paused + } + if updateUserAgentRuleOptions.Description != nil { + body["description"] = updateUserAgentRuleOptions.Description + } + if updateUserAgentRuleOptions.Mode != nil { + body["mode"] = updateUserAgentRuleOptions.Mode + } + if updateUserAgentRuleOptions.Configuration != nil { + body["configuration"] = updateUserAgentRuleOptions.Configuration + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + return + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = userAgentBlockingRules.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalUseragentRuleResp) + if err != nil { + return + } + response.Result = result + + return +} + +// CreateZoneUserAgentRuleOptions : The CreateZoneUserAgentRule options. +type CreateZoneUserAgentRuleOptions struct { + // Whether this user-agent rule is currently disabled. + Paused *bool `json:"paused,omitempty"` + + // Some useful information about this rule to help identify the purpose of it. + Description *string `json:"description,omitempty"` + + // The type of action to perform. + Mode *string `json:"mode,omitempty"` + + // Target/Value pair to use for this rule. The value is the exact UserAgent to match. + Configuration *UseragentRuleInputConfiguration `json:"configuration,omitempty"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// Constants associated with the CreateZoneUserAgentRuleOptions.Mode property. +// The type of action to perform. +const ( + CreateZoneUserAgentRuleOptions_Mode_Block = "block" + CreateZoneUserAgentRuleOptions_Mode_Challenge = "challenge" + CreateZoneUserAgentRuleOptions_Mode_JsChallenge = "js_challenge" +) + +// NewCreateZoneUserAgentRuleOptions : Instantiate CreateZoneUserAgentRuleOptions +func (*UserAgentBlockingRulesV1) NewCreateZoneUserAgentRuleOptions() *CreateZoneUserAgentRuleOptions { + return &CreateZoneUserAgentRuleOptions{} +} + +// SetPaused : Allow user to set Paused +func (options *CreateZoneUserAgentRuleOptions) SetPaused(paused bool) *CreateZoneUserAgentRuleOptions { + options.Paused = core.BoolPtr(paused) + return options +} + +// SetDescription : Allow user to set Description +func (options *CreateZoneUserAgentRuleOptions) SetDescription(description string) *CreateZoneUserAgentRuleOptions { + options.Description = core.StringPtr(description) + return options +} + +// SetMode : Allow user to set Mode +func (options *CreateZoneUserAgentRuleOptions) SetMode(mode string) *CreateZoneUserAgentRuleOptions { + options.Mode = core.StringPtr(mode) + return options +} + +// SetConfiguration : Allow user to set Configuration +func (options *CreateZoneUserAgentRuleOptions) SetConfiguration(configuration *UseragentRuleInputConfiguration) *CreateZoneUserAgentRuleOptions { + options.Configuration = configuration + return options +} + +// SetHeaders : Allow user to set Headers +func (options *CreateZoneUserAgentRuleOptions) SetHeaders(param map[string]string) *CreateZoneUserAgentRuleOptions { + options.Headers = param + return options +} + +// DeleteUseragentRuleRespResult : Container for response information. +type DeleteUseragentRuleRespResult struct { + // ID. + ID *string `json:"id" validate:"required"` +} + + +// UnmarshalDeleteUseragentRuleRespResult unmarshals an instance of DeleteUseragentRuleRespResult from the specified map of raw messages. +func UnmarshalDeleteUseragentRuleRespResult(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(DeleteUseragentRuleRespResult) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// DeleteZoneUserAgentRuleOptions : The DeleteZoneUserAgentRule options. +type DeleteZoneUserAgentRuleOptions struct { + // Identifier of the user-agent rule to be deleted. + UseragentRuleIdentifier *string `json:"useragent_rule_identifier" validate:"required"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewDeleteZoneUserAgentRuleOptions : Instantiate DeleteZoneUserAgentRuleOptions +func (*UserAgentBlockingRulesV1) NewDeleteZoneUserAgentRuleOptions(useragentRuleIdentifier string) *DeleteZoneUserAgentRuleOptions { + return &DeleteZoneUserAgentRuleOptions{ + UseragentRuleIdentifier: core.StringPtr(useragentRuleIdentifier), + } +} + +// SetUseragentRuleIdentifier : Allow user to set UseragentRuleIdentifier +func (options *DeleteZoneUserAgentRuleOptions) SetUseragentRuleIdentifier(useragentRuleIdentifier string) *DeleteZoneUserAgentRuleOptions { + options.UseragentRuleIdentifier = core.StringPtr(useragentRuleIdentifier) + return options +} + +// SetHeaders : Allow user to set Headers +func (options *DeleteZoneUserAgentRuleOptions) SetHeaders(param map[string]string) *DeleteZoneUserAgentRuleOptions { + options.Headers = param + return options +} + +// GetUserAgentRuleOptions : The GetUserAgentRule options. +type GetUserAgentRuleOptions struct { + // Identifier of user-agent blocking rule for the given zone. + UseragentRuleIdentifier *string `json:"useragent_rule_identifier" validate:"required"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewGetUserAgentRuleOptions : Instantiate GetUserAgentRuleOptions +func (*UserAgentBlockingRulesV1) NewGetUserAgentRuleOptions(useragentRuleIdentifier string) *GetUserAgentRuleOptions { + return &GetUserAgentRuleOptions{ + UseragentRuleIdentifier: core.StringPtr(useragentRuleIdentifier), + } +} + +// SetUseragentRuleIdentifier : Allow user to set UseragentRuleIdentifier +func (options *GetUserAgentRuleOptions) SetUseragentRuleIdentifier(useragentRuleIdentifier string) *GetUserAgentRuleOptions { + options.UseragentRuleIdentifier = core.StringPtr(useragentRuleIdentifier) + return options +} + +// SetHeaders : Allow user to set Headers +func (options *GetUserAgentRuleOptions) SetHeaders(param map[string]string) *GetUserAgentRuleOptions { + options.Headers = param + return options +} + +// ListAllZoneUserAgentRulesOptions : The ListAllZoneUserAgentRules options. +type ListAllZoneUserAgentRulesOptions struct { + // Page number of paginated results. + Page *int64 `json:"page,omitempty"` + + // Maximum number of user-agent rules per page. + PerPage *int64 `json:"per_page,omitempty"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewListAllZoneUserAgentRulesOptions : Instantiate ListAllZoneUserAgentRulesOptions +func (*UserAgentBlockingRulesV1) NewListAllZoneUserAgentRulesOptions() *ListAllZoneUserAgentRulesOptions { + return &ListAllZoneUserAgentRulesOptions{} +} + +// SetPage : Allow user to set Page +func (options *ListAllZoneUserAgentRulesOptions) SetPage(page int64) *ListAllZoneUserAgentRulesOptions { + options.Page = core.Int64Ptr(page) + return options +} + +// SetPerPage : Allow user to set PerPage +func (options *ListAllZoneUserAgentRulesOptions) SetPerPage(perPage int64) *ListAllZoneUserAgentRulesOptions { + options.PerPage = core.Int64Ptr(perPage) + return options +} + +// SetHeaders : Allow user to set Headers +func (options *ListAllZoneUserAgentRulesOptions) SetHeaders(param map[string]string) *ListAllZoneUserAgentRulesOptions { + options.Headers = param + return options +} + +// ListUseragentRulesRespResultInfo : Statistics of results. +type ListUseragentRulesRespResultInfo struct { + // Page number. + Page *int64 `json:"page" validate:"required"` + + // Number of results per page. + PerPage *int64 `json:"per_page" validate:"required"` + + // Number of results. + Count *int64 `json:"count" validate:"required"` + + // Total number of results. + TotalCount *int64 `json:"total_count" validate:"required"` +} + + +// UnmarshalListUseragentRulesRespResultInfo unmarshals an instance of ListUseragentRulesRespResultInfo from the specified map of raw messages. +func UnmarshalListUseragentRulesRespResultInfo(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ListUseragentRulesRespResultInfo) + err = core.UnmarshalPrimitive(m, "page", &obj.Page) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "per_page", &obj.PerPage) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "count", &obj.Count) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "total_count", &obj.TotalCount) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// UpdateUserAgentRuleOptions : The UpdateUserAgentRule options. +type UpdateUserAgentRuleOptions struct { + // Identifier of user-agent rule. + UseragentRuleIdentifier *string `json:"useragent_rule_identifier" validate:"required"` + + // Whether this user-agent rule is currently disabled. + Paused *bool `json:"paused,omitempty"` + + // Some useful information about this rule to help identify the purpose of it. + Description *string `json:"description,omitempty"` + + // The type of action to perform. + Mode *string `json:"mode,omitempty"` + + // Target/Value pair to use for this rule. The value is the exact UserAgent to match. + Configuration *UseragentRuleInputConfiguration `json:"configuration,omitempty"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// Constants associated with the UpdateUserAgentRuleOptions.Mode property. +// The type of action to perform. +const ( + UpdateUserAgentRuleOptions_Mode_Block = "block" + UpdateUserAgentRuleOptions_Mode_Challenge = "challenge" + UpdateUserAgentRuleOptions_Mode_JsChallenge = "js_challenge" +) + +// NewUpdateUserAgentRuleOptions : Instantiate UpdateUserAgentRuleOptions +func (*UserAgentBlockingRulesV1) NewUpdateUserAgentRuleOptions(useragentRuleIdentifier string) *UpdateUserAgentRuleOptions { + return &UpdateUserAgentRuleOptions{ + UseragentRuleIdentifier: core.StringPtr(useragentRuleIdentifier), + } +} + +// SetUseragentRuleIdentifier : Allow user to set UseragentRuleIdentifier +func (options *UpdateUserAgentRuleOptions) SetUseragentRuleIdentifier(useragentRuleIdentifier string) *UpdateUserAgentRuleOptions { + options.UseragentRuleIdentifier = core.StringPtr(useragentRuleIdentifier) + return options +} + +// SetPaused : Allow user to set Paused +func (options *UpdateUserAgentRuleOptions) SetPaused(paused bool) *UpdateUserAgentRuleOptions { + options.Paused = core.BoolPtr(paused) + return options +} + +// SetDescription : Allow user to set Description +func (options *UpdateUserAgentRuleOptions) SetDescription(description string) *UpdateUserAgentRuleOptions { + options.Description = core.StringPtr(description) + return options +} + +// SetMode : Allow user to set Mode +func (options *UpdateUserAgentRuleOptions) SetMode(mode string) *UpdateUserAgentRuleOptions { + options.Mode = core.StringPtr(mode) + return options +} + +// SetConfiguration : Allow user to set Configuration +func (options *UpdateUserAgentRuleOptions) SetConfiguration(configuration *UseragentRuleInputConfiguration) *UpdateUserAgentRuleOptions { + options.Configuration = configuration + return options +} + +// SetHeaders : Allow user to set Headers +func (options *UpdateUserAgentRuleOptions) SetHeaders(param map[string]string) *UpdateUserAgentRuleOptions { + options.Headers = param + return options +} + +// UseragentRuleInputConfiguration : Target/Value pair to use for this rule. The value is the exact UserAgent to match. +type UseragentRuleInputConfiguration struct { + // properties. + Target *string `json:"target" validate:"required"` + + // The exact UserAgent string to match with this rule. + Value *string `json:"value" validate:"required"` +} + +// Constants associated with the UseragentRuleInputConfiguration.Target property. +// properties. +const ( + UseragentRuleInputConfiguration_Target_Ua = "ua" +) + + +// NewUseragentRuleInputConfiguration : Instantiate UseragentRuleInputConfiguration (Generic Model Constructor) +func (*UserAgentBlockingRulesV1) NewUseragentRuleInputConfiguration(target string, value string) (model *UseragentRuleInputConfiguration, err error) { + model = &UseragentRuleInputConfiguration{ + Target: core.StringPtr(target), + Value: core.StringPtr(value), + } + err = core.ValidateStruct(model, "required parameters") + return +} + +// UnmarshalUseragentRuleInputConfiguration unmarshals an instance of UseragentRuleInputConfiguration from the specified map of raw messages. +func UnmarshalUseragentRuleInputConfiguration(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(UseragentRuleInputConfiguration) + err = core.UnmarshalPrimitive(m, "target", &obj.Target) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "value", &obj.Value) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// UseragentRuleObjectConfiguration : Target/Value pair to use for this rule. The value is the exact UserAgent to match. +type UseragentRuleObjectConfiguration struct { + // properties. + Target *string `json:"target" validate:"required"` + + // The exact UserAgent string to match with this rule. + Value *string `json:"value" validate:"required"` +} + +// Constants associated with the UseragentRuleObjectConfiguration.Target property. +// properties. +const ( + UseragentRuleObjectConfiguration_Target_Ua = "ua" +) + + +// UnmarshalUseragentRuleObjectConfiguration unmarshals an instance of UseragentRuleObjectConfiguration from the specified map of raw messages. +func UnmarshalUseragentRuleObjectConfiguration(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(UseragentRuleObjectConfiguration) + err = core.UnmarshalPrimitive(m, "target", &obj.Target) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "value", &obj.Value) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// DeleteUseragentRuleResp : user agent delete response. +type DeleteUseragentRuleResp struct { + // Operation success flag. + Success *bool `json:"success" validate:"required"` + + // Array of errors encountered. + Errors [][]string `json:"errors" validate:"required"` + + // Array of messages returned. + Messages [][]string `json:"messages" validate:"required"` + + // Container for response information. + Result *DeleteUseragentRuleRespResult `json:"result" validate:"required"` +} + + +// UnmarshalDeleteUseragentRuleResp unmarshals an instance of DeleteUseragentRuleResp from the specified map of raw messages. +func UnmarshalDeleteUseragentRuleResp(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(DeleteUseragentRuleResp) + err = core.UnmarshalPrimitive(m, "success", &obj.Success) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "errors", &obj.Errors) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "messages", &obj.Messages) + if err != nil { + return + } + err = core.UnmarshalModel(m, "result", &obj.Result, UnmarshalDeleteUseragentRuleRespResult) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// ListUseragentRulesResp : user agent rules response. +type ListUseragentRulesResp struct { + // Was operation successful. + Success *bool `json:"success" validate:"required"` + + // Array of errors encountered. + Errors [][]string `json:"errors" validate:"required"` + + // Array of messages returned. + Messages [][]string `json:"messages" validate:"required"` + + // Container for response information. + Result []UseragentRuleObject `json:"result" validate:"required"` + + // Statistics of results. + ResultInfo *ListUseragentRulesRespResultInfo `json:"result_info" validate:"required"` +} + + +// UnmarshalListUseragentRulesResp unmarshals an instance of ListUseragentRulesResp from the specified map of raw messages. +func UnmarshalListUseragentRulesResp(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ListUseragentRulesResp) + err = core.UnmarshalPrimitive(m, "success", &obj.Success) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "errors", &obj.Errors) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "messages", &obj.Messages) + if err != nil { + return + } + err = core.UnmarshalModel(m, "result", &obj.Result, UnmarshalUseragentRuleObject) + if err != nil { + return + } + err = core.UnmarshalModel(m, "result_info", &obj.ResultInfo, UnmarshalListUseragentRulesRespResultInfo) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// UseragentRuleObject : user agent rule object. +type UseragentRuleObject struct { + // Identifier of the user-agent blocking rule. + ID *string `json:"id" validate:"required"` + + // Whether this user-agent rule is currently disabled. + Paused *bool `json:"paused" validate:"required"` + + // Some useful information about this rule to help identify the purpose of it. + Description *string `json:"description" validate:"required"` + + // The type of action to perform. + Mode *string `json:"mode" validate:"required"` + + // Target/Value pair to use for this rule. The value is the exact UserAgent to match. + Configuration *UseragentRuleObjectConfiguration `json:"configuration" validate:"required"` +} + +// Constants associated with the UseragentRuleObject.Mode property. +// The type of action to perform. +const ( + UseragentRuleObject_Mode_Block = "block" + UseragentRuleObject_Mode_Challenge = "challenge" + UseragentRuleObject_Mode_JsChallenge = "js_challenge" +) + + +// UnmarshalUseragentRuleObject unmarshals an instance of UseragentRuleObject from the specified map of raw messages. +func UnmarshalUseragentRuleObject(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(UseragentRuleObject) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "paused", &obj.Paused) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "description", &obj.Description) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "mode", &obj.Mode) + if err != nil { + return + } + err = core.UnmarshalModel(m, "configuration", &obj.Configuration, UnmarshalUseragentRuleObjectConfiguration) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// UseragentRuleResp : user agent rule response. +type UseragentRuleResp struct { + // Was operation successful. + Success *bool `json:"success" validate:"required"` + + // Array of errors encountered. + Errors [][]string `json:"errors" validate:"required"` + + // Array of messages returned. + Messages [][]string `json:"messages" validate:"required"` + + // user agent rule object. + Result *UseragentRuleObject `json:"result" validate:"required"` +} + + +// UnmarshalUseragentRuleResp unmarshals an instance of UseragentRuleResp from the specified map of raw messages. +func UnmarshalUseragentRuleResp(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(UseragentRuleResp) + err = core.UnmarshalPrimitive(m, "success", &obj.Success) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "errors", &obj.Errors) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "messages", &obj.Messages) + if err != nil { + return + } + err = core.UnmarshalModel(m, "result", &obj.Result, UnmarshalUseragentRuleObject) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} diff --git a/vendor/github.com/IBM/networking-go-sdk/zonefirewallaccessrulesv1/zone_firewall_access_rules_v1.go b/vendor/github.com/IBM/networking-go-sdk/zonefirewallaccessrulesv1/zone_firewall_access_rules_v1.go new file mode 100644 index 0000000000..5ffbc6f939 --- /dev/null +++ b/vendor/github.com/IBM/networking-go-sdk/zonefirewallaccessrulesv1/zone_firewall_access_rules_v1.go @@ -0,0 +1,1099 @@ +/** + * (C) Copyright IBM Corp. 2020. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Package zonefirewallaccessrulesv1 : Operations and models for the ZoneFirewallAccessRulesV1 service +package zonefirewallaccessrulesv1 + +import ( + "encoding/json" + "fmt" + "reflect" + + "github.com/IBM/go-sdk-core/v4/core" + common "github.com/IBM/networking-go-sdk/common" +) + +// ZoneFirewallAccessRulesV1 : Zone Firewall Access Rules +// +// Version: 1.0.1 +type ZoneFirewallAccessRulesV1 struct { + Service *core.BaseService + + // Full crn of the service instance. + Crn *string + + // Identifier of zone whose access rule is to be deleted. + ZoneIdentifier *string +} + +// DefaultServiceURL is the default URL to make service requests to. +const DefaultServiceURL = "https://api.cis.cloud.ibm.com" + +// DefaultServiceName is the default key used to find external configuration information. +const DefaultServiceName = "zone_firewall_access_rules" + +// ZoneFirewallAccessRulesV1Options : Service options +type ZoneFirewallAccessRulesV1Options struct { + ServiceName string + URL string + Authenticator core.Authenticator + + // Full crn of the service instance. + Crn *string `validate:"required"` + + // Identifier of zone whose access rule is to be deleted. + ZoneIdentifier *string `validate:"required"` +} + +// NewZoneFirewallAccessRulesV1UsingExternalConfig : constructs an instance of ZoneFirewallAccessRulesV1 with passed in options and external configuration. +func NewZoneFirewallAccessRulesV1UsingExternalConfig(options *ZoneFirewallAccessRulesV1Options) (zoneFirewallAccessRules *ZoneFirewallAccessRulesV1, err error) { + if options.ServiceName == "" { + options.ServiceName = DefaultServiceName + } + + if options.Authenticator == nil { + options.Authenticator, err = core.GetAuthenticatorFromEnvironment(options.ServiceName) + if err != nil { + return + } + } + + zoneFirewallAccessRules, err = NewZoneFirewallAccessRulesV1(options) + if err != nil { + return + } + + err = zoneFirewallAccessRules.Service.ConfigureService(options.ServiceName) + if err != nil { + return + } + + if options.URL != "" { + err = zoneFirewallAccessRules.Service.SetServiceURL(options.URL) + } + return +} + +// NewZoneFirewallAccessRulesV1 : constructs an instance of ZoneFirewallAccessRulesV1 with passed in options. +func NewZoneFirewallAccessRulesV1(options *ZoneFirewallAccessRulesV1Options) (service *ZoneFirewallAccessRulesV1, err error) { + serviceOptions := &core.ServiceOptions{ + URL: DefaultServiceURL, + Authenticator: options.Authenticator, + } + + err = core.ValidateStruct(options, "options") + if err != nil { + return + } + + baseService, err := core.NewBaseService(serviceOptions) + if err != nil { + return + } + + if options.URL != "" { + err = baseService.SetServiceURL(options.URL) + if err != nil { + return + } + } + + service = &ZoneFirewallAccessRulesV1{ + Service: baseService, + Crn: options.Crn, + ZoneIdentifier: options.ZoneIdentifier, + } + + return +} + +// SetServiceURL sets the service URL +func (zoneFirewallAccessRules *ZoneFirewallAccessRulesV1) SetServiceURL(url string) error { + return zoneFirewallAccessRules.Service.SetServiceURL(url) +} + +// ListAllZoneAccessRules : List all firewall access rules for a zone +// List all firewall access rules for a zone. +func (zoneFirewallAccessRules *ZoneFirewallAccessRulesV1) ListAllZoneAccessRules(listAllZoneAccessRulesOptions *ListAllZoneAccessRulesOptions) (result *ListZoneAccessRulesResp, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listAllZoneAccessRulesOptions, "listAllZoneAccessRulesOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/access_rules/rules"} + pathParameters := []string{*zoneFirewallAccessRules.Crn, *zoneFirewallAccessRules.ZoneIdentifier} + + builder := core.NewRequestBuilder(core.GET) + _, err = builder.ConstructHTTPURL(zoneFirewallAccessRules.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range listAllZoneAccessRulesOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("zone_firewall_access_rules", "V1", "ListAllZoneAccessRules") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + if listAllZoneAccessRulesOptions.Notes != nil { + builder.AddQuery("notes", fmt.Sprint(*listAllZoneAccessRulesOptions.Notes)) + } + if listAllZoneAccessRulesOptions.Mode != nil { + builder.AddQuery("mode", fmt.Sprint(*listAllZoneAccessRulesOptions.Mode)) + } + if listAllZoneAccessRulesOptions.ConfigurationTarget != nil { + builder.AddQuery("configuration.target", fmt.Sprint(*listAllZoneAccessRulesOptions.ConfigurationTarget)) + } + if listAllZoneAccessRulesOptions.ConfigurationValue != nil { + builder.AddQuery("configuration.value", fmt.Sprint(*listAllZoneAccessRulesOptions.ConfigurationValue)) + } + if listAllZoneAccessRulesOptions.Page != nil { + builder.AddQuery("page", fmt.Sprint(*listAllZoneAccessRulesOptions.Page)) + } + if listAllZoneAccessRulesOptions.PerPage != nil { + builder.AddQuery("per_page", fmt.Sprint(*listAllZoneAccessRulesOptions.PerPage)) + } + if listAllZoneAccessRulesOptions.Order != nil { + builder.AddQuery("order", fmt.Sprint(*listAllZoneAccessRulesOptions.Order)) + } + if listAllZoneAccessRulesOptions.Direction != nil { + builder.AddQuery("direction", fmt.Sprint(*listAllZoneAccessRulesOptions.Direction)) + } + if listAllZoneAccessRulesOptions.Match != nil { + builder.AddQuery("match", fmt.Sprint(*listAllZoneAccessRulesOptions.Match)) + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = zoneFirewallAccessRules.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalListZoneAccessRulesResp) + if err != nil { + return + } + response.Result = result + + return +} + +// CreateZoneAccessRule : Create a firewall access rule for a zone +// Create a new firewall access rule for a given zone under a service instance. +func (zoneFirewallAccessRules *ZoneFirewallAccessRulesV1) CreateZoneAccessRule(createZoneAccessRuleOptions *CreateZoneAccessRuleOptions) (result *ZoneAccessRuleResp, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(createZoneAccessRuleOptions, "createZoneAccessRuleOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/access_rules/rules"} + pathParameters := []string{*zoneFirewallAccessRules.Crn, *zoneFirewallAccessRules.ZoneIdentifier} + + builder := core.NewRequestBuilder(core.POST) + _, err = builder.ConstructHTTPURL(zoneFirewallAccessRules.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range createZoneAccessRuleOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("zone_firewall_access_rules", "V1", "CreateZoneAccessRule") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if createZoneAccessRuleOptions.Mode != nil { + body["mode"] = createZoneAccessRuleOptions.Mode + } + if createZoneAccessRuleOptions.Notes != nil { + body["notes"] = createZoneAccessRuleOptions.Notes + } + if createZoneAccessRuleOptions.Configuration != nil { + body["configuration"] = createZoneAccessRuleOptions.Configuration + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + return + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = zoneFirewallAccessRules.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalZoneAccessRuleResp) + if err != nil { + return + } + response.Result = result + + return +} + +// DeleteZoneAccessRule : Delete an access rule +// Delete an access rule given its id. +func (zoneFirewallAccessRules *ZoneFirewallAccessRulesV1) DeleteZoneAccessRule(deleteZoneAccessRuleOptions *DeleteZoneAccessRuleOptions) (result *DeleteZoneAccessRuleResp, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteZoneAccessRuleOptions, "deleteZoneAccessRuleOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(deleteZoneAccessRuleOptions, "deleteZoneAccessRuleOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/access_rules/rules"} + pathParameters := []string{*zoneFirewallAccessRules.Crn, *zoneFirewallAccessRules.ZoneIdentifier, *deleteZoneAccessRuleOptions.AccessruleIdentifier} + + builder := core.NewRequestBuilder(core.DELETE) + _, err = builder.ConstructHTTPURL(zoneFirewallAccessRules.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range deleteZoneAccessRuleOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("zone_firewall_access_rules", "V1", "DeleteZoneAccessRule") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = zoneFirewallAccessRules.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDeleteZoneAccessRuleResp) + if err != nil { + return + } + response.Result = result + + return +} + +// GetZoneAccessRule : Get an access rule details by id +// Get the details of a firewall access rule for a given zone under a given service instance. +func (zoneFirewallAccessRules *ZoneFirewallAccessRulesV1) GetZoneAccessRule(getZoneAccessRuleOptions *GetZoneAccessRuleOptions) (result *ZoneAccessRuleResp, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getZoneAccessRuleOptions, "getZoneAccessRuleOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(getZoneAccessRuleOptions, "getZoneAccessRuleOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/access_rules/rules"} + pathParameters := []string{*zoneFirewallAccessRules.Crn, *zoneFirewallAccessRules.ZoneIdentifier, *getZoneAccessRuleOptions.AccessruleIdentifier} + + builder := core.NewRequestBuilder(core.GET) + _, err = builder.ConstructHTTPURL(zoneFirewallAccessRules.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range getZoneAccessRuleOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("zone_firewall_access_rules", "V1", "GetZoneAccessRule") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = zoneFirewallAccessRules.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalZoneAccessRuleResp) + if err != nil { + return + } + response.Result = result + + return +} + +// UpdateZoneAccessRule : Update a firewall access rule +// Update an existing firewall access rule for a given zone under a given service instance. +func (zoneFirewallAccessRules *ZoneFirewallAccessRulesV1) UpdateZoneAccessRule(updateZoneAccessRuleOptions *UpdateZoneAccessRuleOptions) (result *ZoneAccessRuleResp, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateZoneAccessRuleOptions, "updateZoneAccessRuleOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(updateZoneAccessRuleOptions, "updateZoneAccessRuleOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/access_rules/rules"} + pathParameters := []string{*zoneFirewallAccessRules.Crn, *zoneFirewallAccessRules.ZoneIdentifier, *updateZoneAccessRuleOptions.AccessruleIdentifier} + + builder := core.NewRequestBuilder(core.PATCH) + _, err = builder.ConstructHTTPURL(zoneFirewallAccessRules.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range updateZoneAccessRuleOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("zone_firewall_access_rules", "V1", "UpdateZoneAccessRule") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if updateZoneAccessRuleOptions.Mode != nil { + body["mode"] = updateZoneAccessRuleOptions.Mode + } + if updateZoneAccessRuleOptions.Notes != nil { + body["notes"] = updateZoneAccessRuleOptions.Notes + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + return + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = zoneFirewallAccessRules.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalZoneAccessRuleResp) + if err != nil { + return + } + response.Result = result + + return +} + +// CreateZoneAccessRuleOptions : The CreateZoneAccessRule options. +type CreateZoneAccessRuleOptions struct { + // The action to apply to a matched request. + Mode *string `json:"mode,omitempty"` + + // A personal note about the rule. Typically used as a reminder or explanation for the rule. + Notes *string `json:"notes,omitempty"` + + // Configuration object specifying access rule. + Configuration *ZoneAccessRuleInputConfiguration `json:"configuration,omitempty"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// Constants associated with the CreateZoneAccessRuleOptions.Mode property. +// The action to apply to a matched request. +const ( + CreateZoneAccessRuleOptions_Mode_Block = "block" + CreateZoneAccessRuleOptions_Mode_Challenge = "challenge" + CreateZoneAccessRuleOptions_Mode_JsChallenge = "js_challenge" + CreateZoneAccessRuleOptions_Mode_Whitelist = "whitelist" +) + +// NewCreateZoneAccessRuleOptions : Instantiate CreateZoneAccessRuleOptions +func (*ZoneFirewallAccessRulesV1) NewCreateZoneAccessRuleOptions() *CreateZoneAccessRuleOptions { + return &CreateZoneAccessRuleOptions{} +} + +// SetMode : Allow user to set Mode +func (options *CreateZoneAccessRuleOptions) SetMode(mode string) *CreateZoneAccessRuleOptions { + options.Mode = core.StringPtr(mode) + return options +} + +// SetNotes : Allow user to set Notes +func (options *CreateZoneAccessRuleOptions) SetNotes(notes string) *CreateZoneAccessRuleOptions { + options.Notes = core.StringPtr(notes) + return options +} + +// SetConfiguration : Allow user to set Configuration +func (options *CreateZoneAccessRuleOptions) SetConfiguration(configuration *ZoneAccessRuleInputConfiguration) *CreateZoneAccessRuleOptions { + options.Configuration = configuration + return options +} + +// SetHeaders : Allow user to set Headers +func (options *CreateZoneAccessRuleOptions) SetHeaders(param map[string]string) *CreateZoneAccessRuleOptions { + options.Headers = param + return options +} + +// DeleteZoneAccessRuleOptions : The DeleteZoneAccessRule options. +type DeleteZoneAccessRuleOptions struct { + // Identifier of the access rule to be deleted. + AccessruleIdentifier *string `json:"accessrule_identifier" validate:"required"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewDeleteZoneAccessRuleOptions : Instantiate DeleteZoneAccessRuleOptions +func (*ZoneFirewallAccessRulesV1) NewDeleteZoneAccessRuleOptions(accessruleIdentifier string) *DeleteZoneAccessRuleOptions { + return &DeleteZoneAccessRuleOptions{ + AccessruleIdentifier: core.StringPtr(accessruleIdentifier), + } +} + +// SetAccessruleIdentifier : Allow user to set AccessruleIdentifier +func (options *DeleteZoneAccessRuleOptions) SetAccessruleIdentifier(accessruleIdentifier string) *DeleteZoneAccessRuleOptions { + options.AccessruleIdentifier = core.StringPtr(accessruleIdentifier) + return options +} + +// SetHeaders : Allow user to set Headers +func (options *DeleteZoneAccessRuleOptions) SetHeaders(param map[string]string) *DeleteZoneAccessRuleOptions { + options.Headers = param + return options +} + +// DeleteZoneAccessRuleRespResult : Container for response information. +type DeleteZoneAccessRuleRespResult struct { + // ID. + ID *string `json:"id" validate:"required"` +} + + +// UnmarshalDeleteZoneAccessRuleRespResult unmarshals an instance of DeleteZoneAccessRuleRespResult from the specified map of raw messages. +func UnmarshalDeleteZoneAccessRuleRespResult(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(DeleteZoneAccessRuleRespResult) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// GetZoneAccessRuleOptions : The GetZoneAccessRule options. +type GetZoneAccessRuleOptions struct { + // Identifier of firewall access rule for the given zone. + AccessruleIdentifier *string `json:"accessrule_identifier" validate:"required"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewGetZoneAccessRuleOptions : Instantiate GetZoneAccessRuleOptions +func (*ZoneFirewallAccessRulesV1) NewGetZoneAccessRuleOptions(accessruleIdentifier string) *GetZoneAccessRuleOptions { + return &GetZoneAccessRuleOptions{ + AccessruleIdentifier: core.StringPtr(accessruleIdentifier), + } +} + +// SetAccessruleIdentifier : Allow user to set AccessruleIdentifier +func (options *GetZoneAccessRuleOptions) SetAccessruleIdentifier(accessruleIdentifier string) *GetZoneAccessRuleOptions { + options.AccessruleIdentifier = core.StringPtr(accessruleIdentifier) + return options +} + +// SetHeaders : Allow user to set Headers +func (options *GetZoneAccessRuleOptions) SetHeaders(param map[string]string) *GetZoneAccessRuleOptions { + options.Headers = param + return options +} + +// ListAllZoneAccessRulesOptions : The ListAllZoneAccessRules options. +type ListAllZoneAccessRulesOptions struct { + // Search access rules by note.(Not case sensitive). + Notes *string `json:"notes,omitempty"` + + // Search access rules by mode. + Mode *string `json:"mode,omitempty"` + + // Search access rules by configuration target. + ConfigurationTarget *string `json:"configuration.target,omitempty"` + + // Search access rules by configuration value which can be IP, IPrange, or country code. + ConfigurationValue *string `json:"configuration.value,omitempty"` + + // Page number of paginated results. + Page *int64 `json:"page,omitempty"` + + // Maximum number of access rules per page. + PerPage *int64 `json:"per_page,omitempty"` + + // Field by which to order list of access rules. + Order *string `json:"order,omitempty"` + + // Direction in which to order results [ascending/descending order]. + Direction *string `json:"direction,omitempty"` + + // Whether to match all (all) or atleast one search parameter (any). + Match *string `json:"match,omitempty"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// Constants associated with the ListAllZoneAccessRulesOptions.Mode property. +// Search access rules by mode. +const ( + ListAllZoneAccessRulesOptions_Mode_Block = "block" + ListAllZoneAccessRulesOptions_Mode_Challenge = "challenge" + ListAllZoneAccessRulesOptions_Mode_JsChallenge = "js_challenge" + ListAllZoneAccessRulesOptions_Mode_Whitelist = "whitelist" +) + +// Constants associated with the ListAllZoneAccessRulesOptions.ConfigurationTarget property. +// Search access rules by configuration target. +const ( + ListAllZoneAccessRulesOptions_ConfigurationTarget_Asn = "asn" + ListAllZoneAccessRulesOptions_ConfigurationTarget_Country = "country" + ListAllZoneAccessRulesOptions_ConfigurationTarget_Ip = "ip" + ListAllZoneAccessRulesOptions_ConfigurationTarget_IpRange = "ip_range" +) + +// Constants associated with the ListAllZoneAccessRulesOptions.Order property. +// Field by which to order list of access rules. +const ( + ListAllZoneAccessRulesOptions_Order_ConfigurationTarget = "configuration.target" + ListAllZoneAccessRulesOptions_Order_ConfigurationValue = "configuration.value" + ListAllZoneAccessRulesOptions_Order_Mode = "mode" +) + +// Constants associated with the ListAllZoneAccessRulesOptions.Direction property. +// Direction in which to order results [ascending/descending order]. +const ( + ListAllZoneAccessRulesOptions_Direction_Asc = "asc" + ListAllZoneAccessRulesOptions_Direction_Desc = "desc" +) + +// Constants associated with the ListAllZoneAccessRulesOptions.Match property. +// Whether to match all (all) or atleast one search parameter (any). +const ( + ListAllZoneAccessRulesOptions_Match_All = "all" + ListAllZoneAccessRulesOptions_Match_Any = "any" +) + +// NewListAllZoneAccessRulesOptions : Instantiate ListAllZoneAccessRulesOptions +func (*ZoneFirewallAccessRulesV1) NewListAllZoneAccessRulesOptions() *ListAllZoneAccessRulesOptions { + return &ListAllZoneAccessRulesOptions{} +} + +// SetNotes : Allow user to set Notes +func (options *ListAllZoneAccessRulesOptions) SetNotes(notes string) *ListAllZoneAccessRulesOptions { + options.Notes = core.StringPtr(notes) + return options +} + +// SetMode : Allow user to set Mode +func (options *ListAllZoneAccessRulesOptions) SetMode(mode string) *ListAllZoneAccessRulesOptions { + options.Mode = core.StringPtr(mode) + return options +} + +// SetConfigurationTarget : Allow user to set ConfigurationTarget +func (options *ListAllZoneAccessRulesOptions) SetConfigurationTarget(configurationTarget string) *ListAllZoneAccessRulesOptions { + options.ConfigurationTarget = core.StringPtr(configurationTarget) + return options +} + +// SetConfigurationValue : Allow user to set ConfigurationValue +func (options *ListAllZoneAccessRulesOptions) SetConfigurationValue(configurationValue string) *ListAllZoneAccessRulesOptions { + options.ConfigurationValue = core.StringPtr(configurationValue) + return options +} + +// SetPage : Allow user to set Page +func (options *ListAllZoneAccessRulesOptions) SetPage(page int64) *ListAllZoneAccessRulesOptions { + options.Page = core.Int64Ptr(page) + return options +} + +// SetPerPage : Allow user to set PerPage +func (options *ListAllZoneAccessRulesOptions) SetPerPage(perPage int64) *ListAllZoneAccessRulesOptions { + options.PerPage = core.Int64Ptr(perPage) + return options +} + +// SetOrder : Allow user to set Order +func (options *ListAllZoneAccessRulesOptions) SetOrder(order string) *ListAllZoneAccessRulesOptions { + options.Order = core.StringPtr(order) + return options +} + +// SetDirection : Allow user to set Direction +func (options *ListAllZoneAccessRulesOptions) SetDirection(direction string) *ListAllZoneAccessRulesOptions { + options.Direction = core.StringPtr(direction) + return options +} + +// SetMatch : Allow user to set Match +func (options *ListAllZoneAccessRulesOptions) SetMatch(match string) *ListAllZoneAccessRulesOptions { + options.Match = core.StringPtr(match) + return options +} + +// SetHeaders : Allow user to set Headers +func (options *ListAllZoneAccessRulesOptions) SetHeaders(param map[string]string) *ListAllZoneAccessRulesOptions { + options.Headers = param + return options +} + +// ListZoneAccessRulesRespResultInfo : Statistics of results. +type ListZoneAccessRulesRespResultInfo struct { + // Page number. + Page *int64 `json:"page" validate:"required"` + + // Number of results per page. + PerPage *int64 `json:"per_page" validate:"required"` + + // Number of results. + Count *int64 `json:"count" validate:"required"` + + // Total number of results. + TotalCount *int64 `json:"total_count" validate:"required"` +} + + +// UnmarshalListZoneAccessRulesRespResultInfo unmarshals an instance of ListZoneAccessRulesRespResultInfo from the specified map of raw messages. +func UnmarshalListZoneAccessRulesRespResultInfo(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ListZoneAccessRulesRespResultInfo) + err = core.UnmarshalPrimitive(m, "page", &obj.Page) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "per_page", &obj.PerPage) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "count", &obj.Count) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "total_count", &obj.TotalCount) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// UpdateZoneAccessRuleOptions : The UpdateZoneAccessRule options. +type UpdateZoneAccessRuleOptions struct { + // Identifier of firewall access rule. + AccessruleIdentifier *string `json:"accessrule_identifier" validate:"required"` + + // The action to apply to a matched request. + Mode *string `json:"mode,omitempty"` + + // A personal note about the rule. Typically used as a reminder or explanation for the rule. + Notes *string `json:"notes,omitempty"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// Constants associated with the UpdateZoneAccessRuleOptions.Mode property. +// The action to apply to a matched request. +const ( + UpdateZoneAccessRuleOptions_Mode_Block = "block" + UpdateZoneAccessRuleOptions_Mode_Challenge = "challenge" + UpdateZoneAccessRuleOptions_Mode_JsChallenge = "js_challenge" + UpdateZoneAccessRuleOptions_Mode_Whitelist = "whitelist" +) + +// NewUpdateZoneAccessRuleOptions : Instantiate UpdateZoneAccessRuleOptions +func (*ZoneFirewallAccessRulesV1) NewUpdateZoneAccessRuleOptions(accessruleIdentifier string) *UpdateZoneAccessRuleOptions { + return &UpdateZoneAccessRuleOptions{ + AccessruleIdentifier: core.StringPtr(accessruleIdentifier), + } +} + +// SetAccessruleIdentifier : Allow user to set AccessruleIdentifier +func (options *UpdateZoneAccessRuleOptions) SetAccessruleIdentifier(accessruleIdentifier string) *UpdateZoneAccessRuleOptions { + options.AccessruleIdentifier = core.StringPtr(accessruleIdentifier) + return options +} + +// SetMode : Allow user to set Mode +func (options *UpdateZoneAccessRuleOptions) SetMode(mode string) *UpdateZoneAccessRuleOptions { + options.Mode = core.StringPtr(mode) + return options +} + +// SetNotes : Allow user to set Notes +func (options *UpdateZoneAccessRuleOptions) SetNotes(notes string) *UpdateZoneAccessRuleOptions { + options.Notes = core.StringPtr(notes) + return options +} + +// SetHeaders : Allow user to set Headers +func (options *UpdateZoneAccessRuleOptions) SetHeaders(param map[string]string) *UpdateZoneAccessRuleOptions { + options.Headers = param + return options +} + +// ZoneAccessRuleInputConfiguration : Configuration object specifying access rule. +type ZoneAccessRuleInputConfiguration struct { + // The request property to target. + Target *string `json:"target" validate:"required"` + + // The value for the selected target.For ip the value is a valid ip address.For ip_range the value specifies ip range + // limited to /16 and /24. For asn the value is an AS number. For country the value is a country code for the country. + Value *string `json:"value" validate:"required"` +} + +// Constants associated with the ZoneAccessRuleInputConfiguration.Target property. +// The request property to target. +const ( + ZoneAccessRuleInputConfiguration_Target_Asn = "asn" + ZoneAccessRuleInputConfiguration_Target_Country = "country" + ZoneAccessRuleInputConfiguration_Target_Ip = "ip" + ZoneAccessRuleInputConfiguration_Target_IpRange = "ip_range" +) + + +// NewZoneAccessRuleInputConfiguration : Instantiate ZoneAccessRuleInputConfiguration (Generic Model Constructor) +func (*ZoneFirewallAccessRulesV1) NewZoneAccessRuleInputConfiguration(target string, value string) (model *ZoneAccessRuleInputConfiguration, err error) { + model = &ZoneAccessRuleInputConfiguration{ + Target: core.StringPtr(target), + Value: core.StringPtr(value), + } + err = core.ValidateStruct(model, "required parameters") + return +} + +// UnmarshalZoneAccessRuleInputConfiguration unmarshals an instance of ZoneAccessRuleInputConfiguration from the specified map of raw messages. +func UnmarshalZoneAccessRuleInputConfiguration(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ZoneAccessRuleInputConfiguration) + err = core.UnmarshalPrimitive(m, "target", &obj.Target) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "value", &obj.Value) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// ZoneAccessRuleObjectConfiguration : configuration. +type ZoneAccessRuleObjectConfiguration struct { + // target. + Target *string `json:"target" validate:"required"` + + // Value for the given target. For ip the value is a valid ip address.For ip_range the value specifies ip range limited + // to /16 and /24. For asn the value is an AS number. For country the value is a country code for the country. + Value *string `json:"value" validate:"required"` +} + +// Constants associated with the ZoneAccessRuleObjectConfiguration.Target property. +// target. +const ( + ZoneAccessRuleObjectConfiguration_Target_Asn = "asn" + ZoneAccessRuleObjectConfiguration_Target_Country = "country" + ZoneAccessRuleObjectConfiguration_Target_Ip = "ip" + ZoneAccessRuleObjectConfiguration_Target_IpRange = "ip_range" +) + + +// UnmarshalZoneAccessRuleObjectConfiguration unmarshals an instance of ZoneAccessRuleObjectConfiguration from the specified map of raw messages. +func UnmarshalZoneAccessRuleObjectConfiguration(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ZoneAccessRuleObjectConfiguration) + err = core.UnmarshalPrimitive(m, "target", &obj.Target) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "value", &obj.Value) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// ZoneAccessRuleObjectScope : The scope definition of the access rule. +type ZoneAccessRuleObjectScope struct { + // The scope of the access rule, indicating if its applicable at zone level("zone") or inherited from instance + // level("account"). + Type *string `json:"type" validate:"required"` +} + +// Constants associated with the ZoneAccessRuleObjectScope.Type property. +// The scope of the access rule, indicating if its applicable at zone level("zone") or inherited from instance +// level("account"). +const ( + ZoneAccessRuleObjectScope_Type_Account = "account" + ZoneAccessRuleObjectScope_Type_Zone = "zone" +) + + +// UnmarshalZoneAccessRuleObjectScope unmarshals an instance of ZoneAccessRuleObjectScope from the specified map of raw messages. +func UnmarshalZoneAccessRuleObjectScope(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ZoneAccessRuleObjectScope) + err = core.UnmarshalPrimitive(m, "type", &obj.Type) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// DeleteZoneAccessRuleResp : delete access rule response. +type DeleteZoneAccessRuleResp struct { + // Operation success flag. + Success *bool `json:"success" validate:"required"` + + // Array of errors encountered. + Errors [][]string `json:"errors" validate:"required"` + + // Array of messages returned. + Messages [][]string `json:"messages" validate:"required"` + + // Container for response information. + Result *DeleteZoneAccessRuleRespResult `json:"result" validate:"required"` +} + + +// UnmarshalDeleteZoneAccessRuleResp unmarshals an instance of DeleteZoneAccessRuleResp from the specified map of raw messages. +func UnmarshalDeleteZoneAccessRuleResp(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(DeleteZoneAccessRuleResp) + err = core.UnmarshalPrimitive(m, "success", &obj.Success) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "errors", &obj.Errors) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "messages", &obj.Messages) + if err != nil { + return + } + err = core.UnmarshalModel(m, "result", &obj.Result, UnmarshalDeleteZoneAccessRuleRespResult) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// ListZoneAccessRulesResp : list access rules response. +type ListZoneAccessRulesResp struct { + // Operation success flag. + Success *bool `json:"success" validate:"required"` + + // Array of errors encountered. + Errors [][]string `json:"errors" validate:"required"` + + // Array of messages returned. + Messages [][]string `json:"messages" validate:"required"` + + // Container for response information. + Result []ZoneAccessRuleObject `json:"result" validate:"required"` + + // Statistics of results. + ResultInfo *ListZoneAccessRulesRespResultInfo `json:"result_info" validate:"required"` +} + + +// UnmarshalListZoneAccessRulesResp unmarshals an instance of ListZoneAccessRulesResp from the specified map of raw messages. +func UnmarshalListZoneAccessRulesResp(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ListZoneAccessRulesResp) + err = core.UnmarshalPrimitive(m, "success", &obj.Success) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "errors", &obj.Errors) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "messages", &obj.Messages) + if err != nil { + return + } + err = core.UnmarshalModel(m, "result", &obj.Result, UnmarshalZoneAccessRuleObject) + if err != nil { + return + } + err = core.UnmarshalModel(m, "result_info", &obj.ResultInfo, UnmarshalListZoneAccessRulesRespResultInfo) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// ZoneAccessRuleObject : access rule object. +type ZoneAccessRuleObject struct { + // Identifier of the firewall access rule. + ID *string `json:"id" validate:"required"` + + // A personal note about the rule. Typically used as a reminder or explanation for the rule. + Notes *string `json:"notes" validate:"required"` + + // List of modes that are allowed. + AllowedModes []string `json:"allowed_modes" validate:"required"` + + // The action to be applied to a request matching the access rule. + Mode *string `json:"mode" validate:"required"` + + // The scope definition of the access rule. + Scope *ZoneAccessRuleObjectScope `json:"scope,omitempty"` + + // The creation date-time of the firewall access rule. + CreatedOn *string `json:"created_on" validate:"required"` + + // The modification date-time of the firewall access rule. + ModifiedOn *string `json:"modified_on" validate:"required"` + + // configuration. + Configuration *ZoneAccessRuleObjectConfiguration `json:"configuration" validate:"required"` +} + +// Constants associated with the ZoneAccessRuleObject.AllowedModes property. +const ( + ZoneAccessRuleObject_AllowedModes_Block = "block" + ZoneAccessRuleObject_AllowedModes_Challenge = "challenge" + ZoneAccessRuleObject_AllowedModes_JsChallenge = "js_challenge" + ZoneAccessRuleObject_AllowedModes_Whitelist = "whitelist" +) + +// Constants associated with the ZoneAccessRuleObject.Mode property. +// The action to be applied to a request matching the access rule. +const ( + ZoneAccessRuleObject_Mode_Block = "block" + ZoneAccessRuleObject_Mode_Challenge = "challenge" + ZoneAccessRuleObject_Mode_JsChallenge = "js_challenge" + ZoneAccessRuleObject_Mode_Whitelist = "whitelist" +) + + +// UnmarshalZoneAccessRuleObject unmarshals an instance of ZoneAccessRuleObject from the specified map of raw messages. +func UnmarshalZoneAccessRuleObject(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ZoneAccessRuleObject) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "notes", &obj.Notes) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "allowed_modes", &obj.AllowedModes) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "mode", &obj.Mode) + if err != nil { + return + } + err = core.UnmarshalModel(m, "scope", &obj.Scope, UnmarshalZoneAccessRuleObjectScope) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "created_on", &obj.CreatedOn) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "modified_on", &obj.ModifiedOn) + if err != nil { + return + } + err = core.UnmarshalModel(m, "configuration", &obj.Configuration, UnmarshalZoneAccessRuleObjectConfiguration) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// ZoneAccessRuleResp : access rule response. +type ZoneAccessRuleResp struct { + // Operation success flag. + Success *bool `json:"success" validate:"required"` + + // Array of errors encountered. + Errors [][]string `json:"errors" validate:"required"` + + // Array of messages returned. + Messages [][]string `json:"messages" validate:"required"` + + // access rule object. + Result *ZoneAccessRuleObject `json:"result" validate:"required"` +} + + +// UnmarshalZoneAccessRuleResp unmarshals an instance of ZoneAccessRuleResp from the specified map of raw messages. +func UnmarshalZoneAccessRuleResp(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ZoneAccessRuleResp) + err = core.UnmarshalPrimitive(m, "success", &obj.Success) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "errors", &obj.Errors) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "messages", &obj.Messages) + if err != nil { + return + } + err = core.UnmarshalModel(m, "result", &obj.Result, UnmarshalZoneAccessRuleObject) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} diff --git a/vendor/github.com/IBM/networking-go-sdk/zonelockdownv1/zone_lockdown_v1.go b/vendor/github.com/IBM/networking-go-sdk/zonelockdownv1/zone_lockdown_v1.go new file mode 100644 index 0000000000..0d813707f1 --- /dev/null +++ b/vendor/github.com/IBM/networking-go-sdk/zonelockdownv1/zone_lockdown_v1.go @@ -0,0 +1,982 @@ +/** + * (C) Copyright IBM Corp. 2020. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Package zonelockdownv1 : Operations and models for the ZoneLockdownV1 service +package zonelockdownv1 + +import ( + "encoding/json" + "fmt" + "github.com/IBM/go-sdk-core/v4/core" + common "github.com/IBM/networking-go-sdk/common" + "reflect" +) + +// ZoneLockdownV1 : Zone Lockdown +// +// Version: 1.0.1 +type ZoneLockdownV1 struct { + Service *core.BaseService + + // Full crn of the service instance. + Crn *string + + // Zone identifier (zone id). + ZoneIdentifier *string +} + +// DefaultServiceURL is the default URL to make service requests to. +const DefaultServiceURL = "https://api.cis.cloud.ibm.com" + +// DefaultServiceName is the default key used to find external configuration information. +const DefaultServiceName = "zone_lockdown" + +// ZoneLockdownV1Options : Service options +type ZoneLockdownV1Options struct { + ServiceName string + URL string + Authenticator core.Authenticator + + // Full crn of the service instance. + Crn *string `validate:"required"` + + // Zone identifier (zone id). + ZoneIdentifier *string `validate:"required"` +} + +// NewZoneLockdownV1UsingExternalConfig : constructs an instance of ZoneLockdownV1 with passed in options and external configuration. +func NewZoneLockdownV1UsingExternalConfig(options *ZoneLockdownV1Options) (zoneLockdown *ZoneLockdownV1, err error) { + if options.ServiceName == "" { + options.ServiceName = DefaultServiceName + } + + if options.Authenticator == nil { + options.Authenticator, err = core.GetAuthenticatorFromEnvironment(options.ServiceName) + if err != nil { + return + } + } + + zoneLockdown, err = NewZoneLockdownV1(options) + if err != nil { + return + } + + err = zoneLockdown.Service.ConfigureService(options.ServiceName) + if err != nil { + return + } + + if options.URL != "" { + err = zoneLockdown.Service.SetServiceURL(options.URL) + } + return +} + +// NewZoneLockdownV1 : constructs an instance of ZoneLockdownV1 with passed in options. +func NewZoneLockdownV1(options *ZoneLockdownV1Options) (service *ZoneLockdownV1, err error) { + serviceOptions := &core.ServiceOptions{ + URL: DefaultServiceURL, + Authenticator: options.Authenticator, + } + + err = core.ValidateStruct(options, "options") + if err != nil { + return + } + + baseService, err := core.NewBaseService(serviceOptions) + if err != nil { + return + } + + if options.URL != "" { + err = baseService.SetServiceURL(options.URL) + if err != nil { + return + } + } + + service = &ZoneLockdownV1{ + Service: baseService, + Crn: options.Crn, + ZoneIdentifier: options.ZoneIdentifier, + } + + return +} + +// SetServiceURL sets the service URL +func (zoneLockdown *ZoneLockdownV1) SetServiceURL(url string) error { + return zoneLockdown.Service.SetServiceURL(url) +} + +// ListAllZoneLockownRules : List all lockdown rules +// List all lockdown rules for a zone. +func (zoneLockdown *ZoneLockdownV1) ListAllZoneLockownRules(listAllZoneLockownRulesOptions *ListAllZoneLockownRulesOptions) (result *ListLockdownResp, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(listAllZoneLockownRulesOptions, "listAllZoneLockownRulesOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/lockdowns"} + pathParameters := []string{*zoneLockdown.Crn, *zoneLockdown.ZoneIdentifier} + + builder := core.NewRequestBuilder(core.GET) + _, err = builder.ConstructHTTPURL(zoneLockdown.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range listAllZoneLockownRulesOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("zone_lockdown", "V1", "ListAllZoneLockownRules") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + if listAllZoneLockownRulesOptions.Page != nil { + builder.AddQuery("page", fmt.Sprint(*listAllZoneLockownRulesOptions.Page)) + } + if listAllZoneLockownRulesOptions.PerPage != nil { + builder.AddQuery("per_page", fmt.Sprint(*listAllZoneLockownRulesOptions.PerPage)) + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = zoneLockdown.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalListLockdownResp) + if err != nil { + return + } + response.Result = result + + return +} + +// CreateZoneLockdownRule : Create lockdown rule +// Create a new lockdown rule for a given zone under a service instance. +func (zoneLockdown *ZoneLockdownV1) CreateZoneLockdownRule(createZoneLockdownRuleOptions *CreateZoneLockdownRuleOptions) (result *LockdownResp, response *core.DetailedResponse, err error) { + err = core.ValidateStruct(createZoneLockdownRuleOptions, "createZoneLockdownRuleOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/lockdowns"} + pathParameters := []string{*zoneLockdown.Crn, *zoneLockdown.ZoneIdentifier} + + builder := core.NewRequestBuilder(core.POST) + _, err = builder.ConstructHTTPURL(zoneLockdown.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range createZoneLockdownRuleOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("zone_lockdown", "V1", "CreateZoneLockdownRule") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if createZoneLockdownRuleOptions.ID != nil { + body["id"] = createZoneLockdownRuleOptions.ID + } + if createZoneLockdownRuleOptions.Paused != nil { + body["paused"] = createZoneLockdownRuleOptions.Paused + } + if createZoneLockdownRuleOptions.Description != nil { + body["description"] = createZoneLockdownRuleOptions.Description + } + if createZoneLockdownRuleOptions.Urls != nil { + body["urls"] = createZoneLockdownRuleOptions.Urls + } + if createZoneLockdownRuleOptions.Configurations != nil { + body["configurations"] = createZoneLockdownRuleOptions.Configurations + } + if createZoneLockdownRuleOptions.Priority != nil { + body["priority"] = createZoneLockdownRuleOptions.Priority + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + return + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = zoneLockdown.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLockdownResp) + if err != nil { + return + } + response.Result = result + + return +} + +// DeleteZoneLockdownRule : Delete lockdown rule +// Delete a lockdown rule for a particular zone, given its id. +func (zoneLockdown *ZoneLockdownV1) DeleteZoneLockdownRule(deleteZoneLockdownRuleOptions *DeleteZoneLockdownRuleOptions) (result *DeleteLockdownResp, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(deleteZoneLockdownRuleOptions, "deleteZoneLockdownRuleOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(deleteZoneLockdownRuleOptions, "deleteZoneLockdownRuleOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/lockdowns"} + pathParameters := []string{*zoneLockdown.Crn, *zoneLockdown.ZoneIdentifier, *deleteZoneLockdownRuleOptions.LockdownRuleIdentifier} + + builder := core.NewRequestBuilder(core.DELETE) + _, err = builder.ConstructHTTPURL(zoneLockdown.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range deleteZoneLockdownRuleOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("zone_lockdown", "V1", "DeleteZoneLockdownRule") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = zoneLockdown.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDeleteLockdownResp) + if err != nil { + return + } + response.Result = result + + return +} + +// GetLockdown : Get lockdown rule +// For a given service instance, zone id and lockdown rule id, get the lockdown rule details. +func (zoneLockdown *ZoneLockdownV1) GetLockdown(getLockdownOptions *GetLockdownOptions) (result *LockdownResp, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(getLockdownOptions, "getLockdownOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(getLockdownOptions, "getLockdownOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/lockdowns"} + pathParameters := []string{*zoneLockdown.Crn, *zoneLockdown.ZoneIdentifier, *getLockdownOptions.LockdownRuleIdentifier} + + builder := core.NewRequestBuilder(core.GET) + _, err = builder.ConstructHTTPURL(zoneLockdown.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range getLockdownOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("zone_lockdown", "V1", "GetLockdown") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = zoneLockdown.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLockdownResp) + if err != nil { + return + } + response.Result = result + + return +} + +// UpdateLockdownRule : Update lockdown rule +// Update an existing lockdown rule for a given zone under a given service instance. +func (zoneLockdown *ZoneLockdownV1) UpdateLockdownRule(updateLockdownRuleOptions *UpdateLockdownRuleOptions) (result *LockdownResp, response *core.DetailedResponse, err error) { + err = core.ValidateNotNil(updateLockdownRuleOptions, "updateLockdownRuleOptions cannot be nil") + if err != nil { + return + } + err = core.ValidateStruct(updateLockdownRuleOptions, "updateLockdownRuleOptions") + if err != nil { + return + } + + pathSegments := []string{"v1", "zones", "firewall/lockdowns"} + pathParameters := []string{*zoneLockdown.Crn, *zoneLockdown.ZoneIdentifier, *updateLockdownRuleOptions.LockdownRuleIdentifier} + + builder := core.NewRequestBuilder(core.PUT) + _, err = builder.ConstructHTTPURL(zoneLockdown.Service.Options.URL, pathSegments, pathParameters) + if err != nil { + return + } + + for headerName, headerValue := range updateLockdownRuleOptions.Headers { + builder.AddHeader(headerName, headerValue) + } + + sdkHeaders := common.GetSdkHeaders("zone_lockdown", "V1", "UpdateLockdownRule") + for headerName, headerValue := range sdkHeaders { + builder.AddHeader(headerName, headerValue) + } + builder.AddHeader("Accept", "application/json") + builder.AddHeader("Content-Type", "application/json") + + body := make(map[string]interface{}) + if updateLockdownRuleOptions.ID != nil { + body["id"] = updateLockdownRuleOptions.ID + } + if updateLockdownRuleOptions.Paused != nil { + body["paused"] = updateLockdownRuleOptions.Paused + } + if updateLockdownRuleOptions.Description != nil { + body["description"] = updateLockdownRuleOptions.Description + } + if updateLockdownRuleOptions.Urls != nil { + body["urls"] = updateLockdownRuleOptions.Urls + } + if updateLockdownRuleOptions.Configurations != nil { + body["configurations"] = updateLockdownRuleOptions.Configurations + } + if updateLockdownRuleOptions.Priority != nil { + body["priority"] = updateLockdownRuleOptions.Priority + } + _, err = builder.SetBodyContentJSON(body) + if err != nil { + return + } + + request, err := builder.Build() + if err != nil { + return + } + + var rawResponse map[string]json.RawMessage + response, err = zoneLockdown.Service.Request(request, &rawResponse) + if err != nil { + return + } + err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalLockdownResp) + if err != nil { + return + } + response.Result = result + + return +} + +// CreateZoneLockdownRuleOptions : The CreateZoneLockdownRule options. +type CreateZoneLockdownRuleOptions struct { + // Lockdown rule identifier. + ID *string `json:"id,omitempty"` + + // Whether this zone lockdown is currently paused. + Paused *bool `json:"paused,omitempty"` + + // A note that you can use to describe the reason for a Lockdown rule. + Description *string `json:"description,omitempty"` + + // URLs to be included in this rule definition. Wildcards are permitted. The URL pattern entered here will be escaped + // before use. This limits the URL to just simple wildcard patterns. + Urls []string `json:"urls,omitempty"` + + // List of IP addresses or CIDR ranges to use for this rule. This can include any number of ip or ip_range + // configurations that can access the provided URLs. + Configurations []LockdownInputConfigurationsItem `json:"configurations,omitempty"` + + // firewall priority. + Priority *int64 `json:"priority,omitempty"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewCreateZoneLockdownRuleOptions : Instantiate CreateZoneLockdownRuleOptions +func (*ZoneLockdownV1) NewCreateZoneLockdownRuleOptions() *CreateZoneLockdownRuleOptions { + return &CreateZoneLockdownRuleOptions{} +} + +// SetID : Allow user to set ID +func (options *CreateZoneLockdownRuleOptions) SetID(id string) *CreateZoneLockdownRuleOptions { + options.ID = core.StringPtr(id) + return options +} + +// SetPaused : Allow user to set Paused +func (options *CreateZoneLockdownRuleOptions) SetPaused(paused bool) *CreateZoneLockdownRuleOptions { + options.Paused = core.BoolPtr(paused) + return options +} + +// SetDescription : Allow user to set Description +func (options *CreateZoneLockdownRuleOptions) SetDescription(description string) *CreateZoneLockdownRuleOptions { + options.Description = core.StringPtr(description) + return options +} + +// SetUrls : Allow user to set Urls +func (options *CreateZoneLockdownRuleOptions) SetUrls(urls []string) *CreateZoneLockdownRuleOptions { + options.Urls = urls + return options +} + +// SetConfigurations : Allow user to set Configurations +func (options *CreateZoneLockdownRuleOptions) SetConfigurations(configurations []LockdownInputConfigurationsItem) *CreateZoneLockdownRuleOptions { + options.Configurations = configurations + return options +} + +// SetPriority : Allow user to set Priority +func (options *CreateZoneLockdownRuleOptions) SetPriority(priority int64) *CreateZoneLockdownRuleOptions { + options.Priority = core.Int64Ptr(priority) + return options +} + +// SetHeaders : Allow user to set Headers +func (options *CreateZoneLockdownRuleOptions) SetHeaders(param map[string]string) *CreateZoneLockdownRuleOptions { + options.Headers = param + return options +} + +// DeleteLockdownRespResult : Container for response information. +type DeleteLockdownRespResult struct { + // ID. + ID *string `json:"id" validate:"required"` +} + + +// UnmarshalDeleteLockdownRespResult unmarshals an instance of DeleteLockdownRespResult from the specified map of raw messages. +func UnmarshalDeleteLockdownRespResult(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(DeleteLockdownRespResult) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// DeleteZoneLockdownRuleOptions : The DeleteZoneLockdownRule options. +type DeleteZoneLockdownRuleOptions struct { + // Identifier of the lockdown rule to be deleted. + LockdownRuleIdentifier *string `json:"lockdown_rule_identifier" validate:"required"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewDeleteZoneLockdownRuleOptions : Instantiate DeleteZoneLockdownRuleOptions +func (*ZoneLockdownV1) NewDeleteZoneLockdownRuleOptions(lockdownRuleIdentifier string) *DeleteZoneLockdownRuleOptions { + return &DeleteZoneLockdownRuleOptions{ + LockdownRuleIdentifier: core.StringPtr(lockdownRuleIdentifier), + } +} + +// SetLockdownRuleIdentifier : Allow user to set LockdownRuleIdentifier +func (options *DeleteZoneLockdownRuleOptions) SetLockdownRuleIdentifier(lockdownRuleIdentifier string) *DeleteZoneLockdownRuleOptions { + options.LockdownRuleIdentifier = core.StringPtr(lockdownRuleIdentifier) + return options +} + +// SetHeaders : Allow user to set Headers +func (options *DeleteZoneLockdownRuleOptions) SetHeaders(param map[string]string) *DeleteZoneLockdownRuleOptions { + options.Headers = param + return options +} + +// GetLockdownOptions : The GetLockdown options. +type GetLockdownOptions struct { + // Identifier of lockdown rule for the given zone. + LockdownRuleIdentifier *string `json:"lockdown_rule_identifier" validate:"required"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewGetLockdownOptions : Instantiate GetLockdownOptions +func (*ZoneLockdownV1) NewGetLockdownOptions(lockdownRuleIdentifier string) *GetLockdownOptions { + return &GetLockdownOptions{ + LockdownRuleIdentifier: core.StringPtr(lockdownRuleIdentifier), + } +} + +// SetLockdownRuleIdentifier : Allow user to set LockdownRuleIdentifier +func (options *GetLockdownOptions) SetLockdownRuleIdentifier(lockdownRuleIdentifier string) *GetLockdownOptions { + options.LockdownRuleIdentifier = core.StringPtr(lockdownRuleIdentifier) + return options +} + +// SetHeaders : Allow user to set Headers +func (options *GetLockdownOptions) SetHeaders(param map[string]string) *GetLockdownOptions { + options.Headers = param + return options +} + +// ListAllZoneLockownRulesOptions : The ListAllZoneLockownRules options. +type ListAllZoneLockownRulesOptions struct { + // Page number of paginated results. + Page *int64 `json:"page,omitempty"` + + // Maximum number of lockdown rules per page. + PerPage *int64 `json:"per_page,omitempty"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewListAllZoneLockownRulesOptions : Instantiate ListAllZoneLockownRulesOptions +func (*ZoneLockdownV1) NewListAllZoneLockownRulesOptions() *ListAllZoneLockownRulesOptions { + return &ListAllZoneLockownRulesOptions{} +} + +// SetPage : Allow user to set Page +func (options *ListAllZoneLockownRulesOptions) SetPage(page int64) *ListAllZoneLockownRulesOptions { + options.Page = core.Int64Ptr(page) + return options +} + +// SetPerPage : Allow user to set PerPage +func (options *ListAllZoneLockownRulesOptions) SetPerPage(perPage int64) *ListAllZoneLockownRulesOptions { + options.PerPage = core.Int64Ptr(perPage) + return options +} + +// SetHeaders : Allow user to set Headers +func (options *ListAllZoneLockownRulesOptions) SetHeaders(param map[string]string) *ListAllZoneLockownRulesOptions { + options.Headers = param + return options +} + +// ListLockdownRespResultInfo : Statistics of results. +type ListLockdownRespResultInfo struct { + // Page number. + Page *int64 `json:"page" validate:"required"` + + // Number of results per page. + PerPage *int64 `json:"per_page" validate:"required"` + + // Number of results. + Count *int64 `json:"count" validate:"required"` + + // Total number of results. + TotalCount *int64 `json:"total_count" validate:"required"` +} + + +// UnmarshalListLockdownRespResultInfo unmarshals an instance of ListLockdownRespResultInfo from the specified map of raw messages. +func UnmarshalListLockdownRespResultInfo(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ListLockdownRespResultInfo) + err = core.UnmarshalPrimitive(m, "page", &obj.Page) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "per_page", &obj.PerPage) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "count", &obj.Count) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "total_count", &obj.TotalCount) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// LockdownInputConfigurationsItem : LockdownInputConfigurationsItem struct +type LockdownInputConfigurationsItem struct { + // properties. + Target *string `json:"target" validate:"required"` + + // IP addresses or CIDR, if target is "ip", then value should be an IP addresses, otherwise CIDR. + Value *string `json:"value" validate:"required"` +} + +// Constants associated with the LockdownInputConfigurationsItem.Target property. +// properties. +const ( + LockdownInputConfigurationsItem_Target_Ip = "ip" + LockdownInputConfigurationsItem_Target_IpRange = "ip_range" +) + + +// NewLockdownInputConfigurationsItem : Instantiate LockdownInputConfigurationsItem (Generic Model Constructor) +func (*ZoneLockdownV1) NewLockdownInputConfigurationsItem(target string, value string) (model *LockdownInputConfigurationsItem, err error) { + model = &LockdownInputConfigurationsItem{ + Target: core.StringPtr(target), + Value: core.StringPtr(value), + } + err = core.ValidateStruct(model, "required parameters") + return +} + +// UnmarshalLockdownInputConfigurationsItem unmarshals an instance of LockdownInputConfigurationsItem from the specified map of raw messages. +func UnmarshalLockdownInputConfigurationsItem(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(LockdownInputConfigurationsItem) + err = core.UnmarshalPrimitive(m, "target", &obj.Target) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "value", &obj.Value) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// LockdownObjectConfigurationsItem : LockdownObjectConfigurationsItem struct +type LockdownObjectConfigurationsItem struct { + // target. + Target *string `json:"target" validate:"required"` + + // IP addresses or CIDR, if target is "ip", then value should be an IP addresses, otherwise CIDR. + Value *string `json:"value" validate:"required"` +} + +// Constants associated with the LockdownObjectConfigurationsItem.Target property. +// target. +const ( + LockdownObjectConfigurationsItem_Target_Ip = "ip" + LockdownObjectConfigurationsItem_Target_IpRange = "ip_range" +) + + +// UnmarshalLockdownObjectConfigurationsItem unmarshals an instance of LockdownObjectConfigurationsItem from the specified map of raw messages. +func UnmarshalLockdownObjectConfigurationsItem(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(LockdownObjectConfigurationsItem) + err = core.UnmarshalPrimitive(m, "target", &obj.Target) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "value", &obj.Value) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// UpdateLockdownRuleOptions : The UpdateLockdownRule options. +type UpdateLockdownRuleOptions struct { + // Identifier of lockdown rule. + LockdownRuleIdentifier *string `json:"lockdown_rule_identifier" validate:"required"` + + // Lockdown rule identifier. + ID *string `json:"id,omitempty"` + + // Whether this zone lockdown is currently paused. + Paused *bool `json:"paused,omitempty"` + + // A note that you can use to describe the reason for a Lockdown rule. + Description *string `json:"description,omitempty"` + + // URLs to be included in this rule definition. Wildcards are permitted. The URL pattern entered here will be escaped + // before use. This limits the URL to just simple wildcard patterns. + Urls []string `json:"urls,omitempty"` + + // List of IP addresses or CIDR ranges to use for this rule. This can include any number of ip or ip_range + // configurations that can access the provided URLs. + Configurations []LockdownInputConfigurationsItem `json:"configurations,omitempty"` + + // firewall priority. + Priority *int64 `json:"priority,omitempty"` + + // Allows users to set headers on API requests + Headers map[string]string +} + +// NewUpdateLockdownRuleOptions : Instantiate UpdateLockdownRuleOptions +func (*ZoneLockdownV1) NewUpdateLockdownRuleOptions(lockdownRuleIdentifier string) *UpdateLockdownRuleOptions { + return &UpdateLockdownRuleOptions{ + LockdownRuleIdentifier: core.StringPtr(lockdownRuleIdentifier), + } +} + +// SetLockdownRuleIdentifier : Allow user to set LockdownRuleIdentifier +func (options *UpdateLockdownRuleOptions) SetLockdownRuleIdentifier(lockdownRuleIdentifier string) *UpdateLockdownRuleOptions { + options.LockdownRuleIdentifier = core.StringPtr(lockdownRuleIdentifier) + return options +} + +// SetID : Allow user to set ID +func (options *UpdateLockdownRuleOptions) SetID(id string) *UpdateLockdownRuleOptions { + options.ID = core.StringPtr(id) + return options +} + +// SetPaused : Allow user to set Paused +func (options *UpdateLockdownRuleOptions) SetPaused(paused bool) *UpdateLockdownRuleOptions { + options.Paused = core.BoolPtr(paused) + return options +} + +// SetDescription : Allow user to set Description +func (options *UpdateLockdownRuleOptions) SetDescription(description string) *UpdateLockdownRuleOptions { + options.Description = core.StringPtr(description) + return options +} + +// SetUrls : Allow user to set Urls +func (options *UpdateLockdownRuleOptions) SetUrls(urls []string) *UpdateLockdownRuleOptions { + options.Urls = urls + return options +} + +// SetConfigurations : Allow user to set Configurations +func (options *UpdateLockdownRuleOptions) SetConfigurations(configurations []LockdownInputConfigurationsItem) *UpdateLockdownRuleOptions { + options.Configurations = configurations + return options +} + +// SetPriority : Allow user to set Priority +func (options *UpdateLockdownRuleOptions) SetPriority(priority int64) *UpdateLockdownRuleOptions { + options.Priority = core.Int64Ptr(priority) + return options +} + +// SetHeaders : Allow user to set Headers +func (options *UpdateLockdownRuleOptions) SetHeaders(param map[string]string) *UpdateLockdownRuleOptions { + options.Headers = param + return options +} + +// DeleteLockdownResp : delete lockdown response. +type DeleteLockdownResp struct { + // Operation success flag. + Success *bool `json:"success" validate:"required"` + + // Array of errors encountered. + Errors [][]string `json:"errors" validate:"required"` + + // Array of messages returned. + Messages [][]string `json:"messages" validate:"required"` + + // Container for response information. + Result *DeleteLockdownRespResult `json:"result" validate:"required"` +} + + +// UnmarshalDeleteLockdownResp unmarshals an instance of DeleteLockdownResp from the specified map of raw messages. +func UnmarshalDeleteLockdownResp(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(DeleteLockdownResp) + err = core.UnmarshalPrimitive(m, "success", &obj.Success) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "errors", &obj.Errors) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "messages", &obj.Messages) + if err != nil { + return + } + err = core.UnmarshalModel(m, "result", &obj.Result, UnmarshalDeleteLockdownRespResult) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// ListLockdownResp : list lockdown response. +type ListLockdownResp struct { + // Was operation successful. + Success *bool `json:"success" validate:"required"` + + // Array of errors encountered. + Errors [][]string `json:"errors" validate:"required"` + + // Array of messages returned. + Messages [][]string `json:"messages" validate:"required"` + + // Container for response information. + Result []LockdownObject `json:"result" validate:"required"` + + // Statistics of results. + ResultInfo *ListLockdownRespResultInfo `json:"result_info" validate:"required"` +} + + +// UnmarshalListLockdownResp unmarshals an instance of ListLockdownResp from the specified map of raw messages. +func UnmarshalListLockdownResp(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(ListLockdownResp) + err = core.UnmarshalPrimitive(m, "success", &obj.Success) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "errors", &obj.Errors) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "messages", &obj.Messages) + if err != nil { + return + } + err = core.UnmarshalModel(m, "result", &obj.Result, UnmarshalLockdownObject) + if err != nil { + return + } + err = core.UnmarshalModel(m, "result_info", &obj.ResultInfo, UnmarshalListLockdownRespResultInfo) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// LockdownObject : lockdown object. +type LockdownObject struct { + // Lockdown rule identifier. + ID *string `json:"id" validate:"required"` + + // firewall priority. + Priority *int64 `json:"priority,omitempty"` + + // Whether this zone lockdown is currently paused. + Paused *bool `json:"paused" validate:"required"` + + // A note that you can use to describe the reason for a Lockdown rule. + Description *string `json:"description" validate:"required"` + + // URLs to be included in this rule definition. Wildcards are permitted. The URL pattern entered here will be escaped + // before use. This limits the URL to just simple wildcard patterns. + Urls []string `json:"urls" validate:"required"` + + // List of IP addresses or CIDR ranges to use for this rule. This can include any number of ip or ip_range + // configurations that can access the provided URLs. + Configurations []LockdownObjectConfigurationsItem `json:"configurations" validate:"required"` +} + + +// UnmarshalLockdownObject unmarshals an instance of LockdownObject from the specified map of raw messages. +func UnmarshalLockdownObject(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(LockdownObject) + err = core.UnmarshalPrimitive(m, "id", &obj.ID) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "priority", &obj.Priority) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "paused", &obj.Paused) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "description", &obj.Description) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "urls", &obj.Urls) + if err != nil { + return + } + err = core.UnmarshalModel(m, "configurations", &obj.Configurations, UnmarshalLockdownObjectConfigurationsItem) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} + +// LockdownResp : lockdown response. +type LockdownResp struct { + // Was operation successful. + Success *bool `json:"success" validate:"required"` + + // Array of errors encountered. + Errors [][]string `json:"errors" validate:"required"` + + // Array of messages returned. + Messages [][]string `json:"messages" validate:"required"` + + // lockdown object. + Result *LockdownObject `json:"result" validate:"required"` +} + + +// UnmarshalLockdownResp unmarshals an instance of LockdownResp from the specified map of raw messages. +func UnmarshalLockdownResp(m map[string]json.RawMessage, result interface{}) (err error) { + obj := new(LockdownResp) + err = core.UnmarshalPrimitive(m, "success", &obj.Success) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "errors", &obj.Errors) + if err != nil { + return + } + err = core.UnmarshalPrimitive(m, "messages", &obj.Messages) + if err != nil { + return + } + err = core.UnmarshalModel(m, "result", &obj.Result, UnmarshalLockdownObject) + if err != nil { + return + } + reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) + return +} diff --git a/vendor/modules.txt b/vendor/modules.txt index e37e8ecbc6..4d57edfa7e 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -139,6 +139,9 @@ github.com/IBM/networking-go-sdk/globalloadbalancerv1 github.com/IBM/networking-go-sdk/routingv1 github.com/IBM/networking-go-sdk/sslcertificateapiv1 github.com/IBM/networking-go-sdk/transitgatewayapisv1 +github.com/IBM/networking-go-sdk/useragentblockingrulesv1 +github.com/IBM/networking-go-sdk/zonefirewallaccessrulesv1 +github.com/IBM/networking-go-sdk/zonelockdownv1 github.com/IBM/networking-go-sdk/zoneratelimitsv1 github.com/IBM/networking-go-sdk/zonessettingsv1 github.com/IBM/networking-go-sdk/zonesv1 From 2eaf1da7564ebf0b495ec7fdcb3ce9487c090039 Mon Sep 17 00:00:00 2001 From: Kumar Ganesan Date: Tue, 10 Nov 2020 20:44:25 +0530 Subject: [PATCH 2/2] CIS Firewall resource changes --- examples/ibm-cis/README.md | 18 +- examples/ibm-cis/main.tf | 9 +- examples/ibm-cis/outputs.tf | 4 + ibm/config.go | 82 ++ ibm/data_source_ibm_cis_firewall.go | 285 +++++-- ibm/data_source_ibm_cis_firewall_test.go | 58 +- ibm/provider.go | 3 +- ibm/resource_ibm_cis_firewall.go | 925 +++++++++++++++++----- ibm/resource_ibm_cis_firewall_test.go | 359 +++++++-- website/docs/d/cis_firewall.html.markdown | 61 +- website/docs/r/cis_firewall.html.markdown | 101 ++- 11 files changed, 1524 insertions(+), 381 deletions(-) diff --git a/examples/ibm-cis/README.md b/examples/ibm-cis/README.md index 8f55956c25..eebc25d7ba 100644 --- a/examples/ibm-cis/README.md +++ b/examples/ibm-cis/README.md @@ -367,8 +367,19 @@ Customise the variables in `variables.tf` to your local environment and chosen D | record\_content | DNS Record Content | `string` | yes | | firewall\_type | Firewall Type | `string` | yes | | lockdown\_url | Lockdown URL | `string` | yes | -| lockdown\_target | Lockdown Configuration target | `string` | yes | -| lockdown\_value | Lockdown Configuration Value | `string` | yes | +| lockdown\_paused | Locdown rule paused or not | `boolean` | no +| lockdown\_description | Lockdown description | `string` | no +| lockdown\_priority | Lockdown priority | `integer` | no +| lockdown\_configurations\_target | Lockdown Configuration target | `string` | yes | +| lockdown\_configurations\_value | Lockdown Configuration Value | `string` | yes | +| access_rule\_notes | Access rule notes | `string` | no +| access_rule\_mode | Access rule mode | `string` | yes +| access_rule\_configuration\_target | Access rule configuration target | `string` | yes | +| access_rule\_configuration\_value | Access rule configuration Value | `string` | yes | +| ua_rule\_description | User Agent rule description | `string` | no +| ua_rule\_mode | User Agent rule mode | `string` | yes +| ua_rule\_configuration\_target | User Agent rule configuration target | `string` | yes | +| ua_rule\_configuration\_value | User Agent rule configuration Value | `string` | yes | | threshold | Rate Limiting Threshold | `number` | yes | | period | Rate Limiting Period | `number` | yes | | match\_request\_url | URL pattern of matching request | `string` | no | @@ -413,6 +424,9 @@ Customise the variables in `variables.tf` to your local environment and chosen D | edge_functions_action_id | Resource ID. It is combination of `action_name`:`domain_id`:`cis_id`| | edge_functions_trigger_id | Resource ID. It is combination of `trigger_id`:`domain_id`:`cis_id`| | page_id | Custom Page ID | +| lockdown\_lockdown_id | Firewall Lockdown ID +| access_rule\_access_rule_id | Firewall Access rule ID +| ua_rule\_ua_rule_id | Firewall User Agent rule ID diff --git a/examples/ibm-cis/main.tf b/examples/ibm-cis/main.tf index e70e22c3cf..4a80f34eae 100644 --- a/examples/ibm-cis/main.tf +++ b/examples/ibm-cis/main.tf @@ -104,7 +104,7 @@ resource "ibm_cis_dns_record" "example" { } -# CIS Firewall - Present resource supports only lockdown +# CIS Firewall resource "ibm_cis_firewall" "lockdown" { cis_id = ibm_cis.web_domain.id domain_id = ibm_cis_domain.web_domain.id @@ -121,6 +121,13 @@ resource "ibm_cis_firewall" "lockdown" { } } +# CIS Firewall data source +data "ibm_cis_firewall" "ua_rules" { + cis_id = ibm_cis.web_domain.id + domain_id = ibm_cis_domain.web_domain.id + firewall_type = "ua_rules" +} + #CIS Rate Limit resource "ibm_cis_rate_limit" "ratelimit" { cis_id = data.ibm_cis.web_domain.id diff --git a/examples/ibm-cis/outputs.tf b/examples/ibm-cis/outputs.tf index 2c8c471f52..a5e0fec79c 100644 --- a/examples/ibm-cis/outputs.tf +++ b/examples/ibm-cis/outputs.tf @@ -40,3 +40,7 @@ output "cache_settings" { output "ibm_cis_custom_page_output" { value = ibm_cis_custom_page.custom_page } + +output "ibm_cis_firewall_ouput" { + value = ibm_cis_firewall.lockdown +} diff --git a/ibm/config.go b/ibm/config.go index a65f0347bd..8cfbbb99b1 100644 --- a/ibm/config.go +++ b/ibm/config.go @@ -28,6 +28,9 @@ import ( cisroutingv1 "github.com/IBM/networking-go-sdk/routingv1" cissslv1 "github.com/IBM/networking-go-sdk/sslcertificateapiv1" tg "github.com/IBM/networking-go-sdk/transitgatewayapisv1" + cisuarulev1 "github.com/IBM/networking-go-sdk/useragentblockingrulesv1" + cisaccessrulev1 "github.com/IBM/networking-go-sdk/zonefirewallaccessrulesv1" + cislockdownv1 "github.com/IBM/networking-go-sdk/zonelockdownv1" cisratelimitv1 "github.com/IBM/networking-go-sdk/zoneratelimitsv1" cisdomainsettingsv1 "github.com/IBM/networking-go-sdk/zonessettingsv1" ciszonesv1 "github.com/IBM/networking-go-sdk/zonesv1" @@ -205,6 +208,9 @@ type ClientSession interface { CisRoutingClientSession() (*cisroutingv1.RoutingV1, error) CisCacheClientSession() (*ciscachev1.CachingApiV1, error) CisCustomPageClientSession() (*ciscustompagev1.CustomPagesV1, error) + CisAccessRuleClientSession() (*cisaccessrulev1.ZoneFirewallAccessRulesV1, error) + CisUARuleClientSession() (*cisuarulev1.UserAgentBlockingRulesV1, error) + CisLockdownClientSession() (*cislockdownv1.ZoneLockdownV1, error) } type clientSession struct { @@ -368,6 +374,18 @@ type clientSession struct { // CIS Custom Pages service options cisCustomPageErr error cisCustomPageClient *ciscustompagev1.CustomPagesV1 + + // CIS Firewall Access rule service option + cisAccessRuleErr error + cisAccessRuleClient *cisaccessrulev1.ZoneFirewallAccessRulesV1 + + // CIS User Agent Blocking Rule service option + cisUARuleErr error + cisUARuleClient *cisuarulev1.UserAgentBlockingRulesV1 + + // CIS Firewall Lockdwon Rule service option + cisLockdownErr error + cisLockdownClient *cislockdownv1.ZoneLockdownV1 } // BluemixAcccountAPI ... @@ -616,6 +634,21 @@ func (sess clientSession) CisCustomPageClientSession() (*ciscustompagev1.CustomP return sess.cisCustomPageClient, sess.cisCustomPageErr } +// CIS Firewall access rule +func (sess clientSession) CisAccessRuleClientSession() (*cisaccessrulev1.ZoneFirewallAccessRulesV1, error) { + return sess.cisAccessRuleClient, sess.cisAccessRuleErr +} + +// CIS User Agent Blocking rule +func (sess clientSession) CisUARuleClientSession() (*cisuarulev1.UserAgentBlockingRulesV1, error) { + return sess.cisUARuleClient, sess.cisUARuleErr +} + +// CIS Firewall Lockdown rule +func (sess clientSession) CisLockdownClientSession() (*cislockdownv1.ZoneLockdownV1, error) { + return sess.cisLockdownClient, sess.cisLockdownErr +} + // ClientSession configures and returns a fully initialized ClientSession func (c *Config) ClientSession() (interface{}, error) { sess, err := newSession(c) @@ -680,6 +713,9 @@ func (c *Config) ClientSession() (interface{}, error) { session.cisRoutingErr = errEmptyBluemixCredentials session.cisCacheErr = errEmptyBluemixCredentials session.cisCustomPageErr = errEmptyBluemixCredentials + session.cisAccessRuleErr = errEmptyBluemixCredentials + session.cisUARuleErr = errEmptyBluemixCredentials + session.cisLockdownErr = errEmptyBluemixCredentials return session, nil } @@ -1172,6 +1208,7 @@ func (c *Config) ClientSession() (interface{}, error) { ZoneIdentifier: core.StringPtr(""), Authenticator: authenticator, } + session.cisCustomPageClient, session.cisCustomPageErr = ciscustompagev1.NewCustomPagesV1(cisCustomPageOpt) if session.cisCustomPageErr != nil { @@ -1179,6 +1216,51 @@ func (c *Config) ClientSession() (interface{}, error) { fmt.Errorf("Error occured while configuring CIS Custom Pages service: %s", session.cisCustomPageErr) } + + // IBM Network CIS Firewall Access rule + cisAccessRuleOpt := &cisaccessrulev1.ZoneFirewallAccessRulesV1Options{ + URL: cisEndPoint, + Crn: core.StringPtr(""), + ZoneIdentifier: core.StringPtr(""), + Authenticator: authenticator, + } + session.cisAccessRuleClient, session.cisAccessRuleErr = + cisaccessrulev1.NewZoneFirewallAccessRulesV1(cisAccessRuleOpt) + if session.cisAccessRuleErr != nil { + session.cisAccessRuleErr = + fmt.Errorf("Error occured while configuring CIS Firewall Access Rule service: %s", + session.cisAccessRuleErr) + } + + // IBM Network CIS Firewall User Agent Blocking rule + cisUARuleOpt := &cisuarulev1.UserAgentBlockingRulesV1Options{ + URL: cisEndPoint, + Crn: core.StringPtr(""), + ZoneIdentifier: core.StringPtr(""), + Authenticator: authenticator, + } + session.cisUARuleClient, session.cisUARuleErr = + cisuarulev1.NewUserAgentBlockingRulesV1(cisUARuleOpt) + if session.cisUARuleErr != nil { + session.cisUARuleErr = + fmt.Errorf("Error occured while configuring CIS Firewall User Agent Blocking Rule service: %s", + session.cisUARuleErr) + } + + // IBM Network CIS Firewall Lockdown rule + cisLockdownOpt := &cislockdownv1.ZoneLockdownV1Options{ + URL: cisEndPoint, + Crn: core.StringPtr(""), + ZoneIdentifier: core.StringPtr(""), + Authenticator: authenticator, + } + session.cisLockdownClient, session.cisLockdownErr = + cislockdownv1.NewZoneLockdownV1(cisLockdownOpt) + if session.cisLockdownErr != nil { + session.cisLockdownErr = + fmt.Errorf("Error occured while configuring CIS Firewall Lockdown Rule service: %s", + session.cisLockdownErr) + } return session, nil } diff --git a/ibm/data_source_ibm_cis_firewall.go b/ibm/data_source_ibm_cis_firewall.go index 1817433af5..04f8540375 100644 --- a/ibm/data_source_ibm_cis_firewall.go +++ b/ibm/data_source_ibm_cis_firewall.go @@ -3,67 +3,165 @@ package ibm import ( "log" + "github.com/IBM/go-sdk-core/v3/core" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) -func dataIBMCISFirewallRecord() *schema.Resource { +func dataIBMCISFirewallsRecord() *schema.Resource { return &schema.Resource{ Read: dataIBMCISFirewallRecordRead, Schema: map[string]*schema.Schema{ - "cis_id": { + cisID: { Type: schema.TypeString, Description: "CIS object id", Required: true, }, - "domain_id": { - Type: schema.TypeString, - Description: "Associated CIS domain", - Required: true, + cisDomainID: { + Type: schema.TypeString, + Description: "Associated CIS domain", + Required: true, + DiffSuppressFunc: suppressDomainIDDiff, }, - "firewall_type": { + cisFirewallType: { Type: schema.TypeString, Required: true, Description: "Type of firewall.Allowable values are access-rules,ua-rules,lockdowns", }, - "lockdown": { + cisFirewallLockdown: { Type: schema.TypeList, Computed: true, - Description: "Lockdown json Data", + Description: "Lockdown Data", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "lockdown_id": { - Type: schema.TypeString, - Computed: true, + cisFirewallLockdownID: { + Type: schema.TypeString, + Computed: true, + Description: "firewall identifier", }, - "paused": { - Type: schema.TypeBool, - Computed: true, + cisFirewallLockdownPaused: { + Type: schema.TypeBool, + Computed: true, + Description: "Firewall rule paused or enabled", }, - "description": { - Type: schema.TypeString, - Computed: true, + cisFirewallLockdownDesc: { + Type: schema.TypeString, + Computed: true, + Description: "description", + }, + cisFirewallLockdownPriority: { + Type: schema.TypeInt, + Computed: true, + Description: "Firewall priority", + }, + cisFirewallLockdownURLs: { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Description: "URL in which firewall rule is applied", }, - "priority": { - Type: schema.TypeInt, + cisFirewallLockdownConfigurations: { + Type: schema.TypeList, Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + cisFirewallLockdownConfigurationsTarget: { + Type: schema.TypeString, + Computed: true, + Description: "Target type", + }, + cisFirewallLockdownConfigurationsValue: { + Type: schema.TypeString, + Computed: true, + Description: "Target value", + }, + }, + }, }, - "urls": { + }, + }, + }, + cisFirewallAccessRule: { + Type: schema.TypeList, + Computed: true, + Description: "Access Rule Data", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + cisFirewallAccessRuleID: { + Type: schema.TypeString, + Computed: true, + Description: "firewall identifier", + }, + cisFirewallAccessRuleNotes: { + Type: schema.TypeString, + Computed: true, + Description: "description", + }, + cisFirewallAccessRuleMode: { + Type: schema.TypeString, + Computed: true, + Description: "Access rule mode", + }, + cisFirewallAccessRuleConfiguration: { Type: schema.TypeList, Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + cisFirewallUARuleConfigurationTarget: { + Type: schema.TypeString, + Computed: true, + Description: "Target type", + }, + cisFirewallUARuleConfigurationValue: { + Type: schema.TypeString, + Computed: true, + Description: "Target value", + }, + }, + }, + }, + }, + }, + }, + cisFirewallUARule: { + Type: schema.TypeList, + Computed: true, + Description: "User Agent Rule Data", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + cisFirewallUARuleID: { + Type: schema.TypeString, + Computed: true, + Description: "firewall identifier", + }, + cisFirewallUARulePaused: { + Type: schema.TypeBool, + Computed: true, + Description: "Rule whether paused or not", }, - "configurations": { + cisFirewallUARuleDesc: { + Type: schema.TypeString, + Computed: true, + Description: "description", + }, + cisFirewallUARuleMode: { + Type: schema.TypeString, + Computed: true, + Description: "user agent rule mode", + }, + cisFirewallUARuleConfiguration: { Type: schema.TypeList, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "target": { - Type: schema.TypeString, - Computed: true, + cisFirewallUARuleConfigurationTarget: { + Type: schema.TypeString, + Computed: true, + Description: "Target type", }, - "value": { - Type: schema.TypeString, - Computed: true, + cisFirewallUARuleConfigurationValue: { + Type: schema.TypeString, + Computed: true, + Description: "Target value", }, }, }, @@ -75,44 +173,111 @@ func dataIBMCISFirewallRecord() *schema.Resource { } } func dataIBMCISFirewallRecordRead(d *schema.ResourceData, meta interface{}) error { - cisClient, err := meta.(ClientSession).CisAPI() - if err != nil { - return err - } - cisID := d.Get("cis_id").(string) - zoneID := d.Get("domain_id").(string) - firewallType := d.Get("firewall_type").(string) + crn := d.Get(cisID).(string) + zoneID, _, _ := convertTftoCisTwoVar(d.Get(cisDomainID).(string)) + firewallType := d.Get(cisFirewallType).(string) - recordList, err := cisClient.Firewall().ListFirewall(cisID, zoneID, firewallType) - if err != nil { - log.Printf("[WARN] Error getting zone during Firewall Record List %v\n", err) - return err - } - - record := make([]map[string]interface{}, 0, len(recordList)) - if firewallType == "lockdowns" { - for _, l := range recordList { - configurationList := make([]map[string]interface{}, 0, len(l.Configurations)) - for _, c := range l.Configurations { - configuration := make(map[string]interface{}) - configuration["target"] = c.Target - configuration["value"] = c.Value + if firewallType == cisFirewallTypeLockdowns { + cisClient, err := meta.(ClientSession).CisLockdownClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + opt := cisClient.NewListAllZoneLockownRulesOptions() + result, response, err := cisClient.ListAllZoneLockownRules(opt) + if err != nil { + log.Printf("List all zone lockdown rules failed: %v", response) + return err + } + lockdownList := make([]map[string]interface{}, 0) + for _, instance := range result.Result { + configurationList := []interface{}{} + for _, c := range instance.Configurations { + configuration := make(map[string]interface{}, 0) + configuration[cisFirewallLockdownConfigurationsTarget] = c.Target + configuration[cisFirewallLockdownConfigurationsValue] = c.Value configurationList = append(configurationList, configuration) } lockdown := make(map[string]interface{}) - lockdown["lockdown_id"] = l.ID - lockdown["paused"] = l.Paused - lockdown["priority"] = l.Priority - lockdown["configurations"] = configurationList - lockdown["urls"] = l.Urls - record = append(record, lockdown) + lockdown[cisFirewallLockdownID] = *instance.ID + lockdown[cisFirewallLockdownPaused] = *instance.Paused + if instance.Priority != nil { + lockdown[cisFirewallLockdownPriority] = *instance.Priority + } + lockdown[cisFirewallLockdownURLs] = instance.Urls + lockdown[cisFirewallLockdownConfigurations] = configurationList + if instance.Description != nil { + lockdown[cisFirewallLockdownDesc] = *instance.Description + } + lockdownList = append(lockdownList, lockdown) + } + d.Set(cisFirewallLockdown, lockdownList) + } else if firewallType == cisFirewallTypeAccessRules { + cisClient, err := meta.(ClientSession).CisAccessRuleClientSession() + if err != nil { + return err } - d.Set("lockdown", record) + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + opt := cisClient.NewListAllZoneAccessRulesOptions() + result, response, err := cisClient.ListAllZoneAccessRules(opt) + if err != nil { + log.Printf("List all zone access rules failed: %v", response) + return err + } + accessRuleList := make([]interface{}, 0) + for _, instance := range result.Result { + configurations := []interface{}{} + configuration := map[string]interface{}{} + configuration[cisFirewallAccessRuleConfigurationTarget] = *instance.Configuration.Target + configuration[cisFirewallAccessRuleConfigurationValue] = *instance.Configuration.Value + configurations = append(configurations, configuration) + accessRule := make(map[string]interface{}, 0) + accessRule[cisFirewallAccessRuleID] = *instance.ID + accessRule[cisFirewallAccessRuleMode] = *instance.Mode + accessRule[cisFirewallAccessRuleNotes] = *instance.Notes + accessRule[cisFirewallAccessRuleConfiguration] = configurations + accessRuleList = append(accessRuleList, accessRule) + } + d.Set(cisFirewallAccessRule, accessRuleList) + } else if firewallType == cisFirewallTypeUARules { + cisClient, err := meta.(ClientSession).CisUARuleClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + opt := cisClient.NewListAllZoneUserAgentRulesOptions() + result, response, err := cisClient.ListAllZoneUserAgentRules(opt) + if err != nil { + log.Printf("List all zone ua rules failed: %v", response) + return err + } + uaRuleList := make([]interface{}, 0) + for _, instance := range result.Result { + configurations := []interface{}{} + configuration := map[string]interface{}{} + configuration[cisFirewallUARuleConfigurationTarget] = *instance.Configuration.Target + configuration[cisFirewallUARuleConfigurationValue] = *instance.Configuration.Value + configurations = append(configurations, configuration) + uaRule := make(map[string]interface{}, 0) + uaRule[cisFirewallUARuleID] = *instance.ID + uaRule[cisFirewallUARuleMode] = *instance.Mode + uaRule[cisFirewallUARulePaused] = *instance.Paused + if instance.Description != nil { + uaRule[cisFirewallUARuleDesc] = *instance.Description + } + uaRule[cisFirewallUARuleConfiguration] = configurations + uaRuleList = append(uaRuleList, uaRule) + } + d.Set(cisFirewallUARule, uaRuleList) } + d.SetId(firewallType + ":" + cisID) - d.Set("cis_id", cisID) - d.Set("domain_id", zoneID) - d.Set("firewall_type", firewallType) + d.Set(cisID, crn) + d.Set(cisDomainID, zoneID) + d.Set(cisFirewallType, firewallType) return nil } diff --git a/ibm/data_source_ibm_cis_firewall_test.go b/ibm/data_source_ibm_cis_firewall_test.go index e009a71457..61cb3629c8 100644 --- a/ibm/data_source_ibm_cis_firewall_test.go +++ b/ibm/data_source_ibm_cis_firewall_test.go @@ -7,12 +7,12 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/resource" ) -func TestAccIBMCisFirewallDataSource_Basic(t *testing.T) { +func TestAccIBMCisFirewallLockdownDataSource_Basic(t *testing.T) { resource.Test(t, resource.TestCase{ Providers: testAccProviders, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckIBMCisFirewallDataSourceConfig_basic1(), + { + Config: testAccCheckIBMCisFirewallLockdownDataSourceConfigBasic(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.ibm_cis_firewall.lockdown", "firewall_type", "lockdowns"), ), @@ -21,14 +21,60 @@ func TestAccIBMCisFirewallDataSource_Basic(t *testing.T) { }) } -func testAccCheckIBMCisFirewallDataSourceConfig_basic1() string { - return testAccCheckIBMCisDomainDataSourceConfigBasic1() + fmt.Sprintf(` +func TestAccIBMCisFirewallAccessRuleDataSource_Basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCisFirewallAccessRuleDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("data.ibm_cis_firewall.access_rule", "firewall_type", "access_rules"), + ), + }, + }, + }) +} +func TestAccIBMCisFirewallUARuleDataSource_Basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCisFirewallUARuleDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("data.ibm_cis_firewall.ua_rule", "firewall_type", "ua_rules"), + ), + }, + }, + }) +} + +func testAccCheckIBMCisFirewallLockdownDataSourceConfigBasic() string { + return testAccCheckIBMCisFirewallLockdownBasic() + fmt.Sprintf(` data "ibm_cis_firewall" "lockdown"{ cis_id = data.ibm_cis.cis.id domain_id = data.ibm_cis_domain.cis_domain.domain_id firewall_type = "lockdowns" } - + `) +} + +func testAccCheckIBMCisFirewallAccessRuleDataSourceConfigBasic() string { + return testAccCheckIBMCisFirewallAccessRuleBasic() + fmt.Sprintf(` + data "ibm_cis_firewall" "access_rule"{ + cis_id = data.ibm_cis.cis.id + domain_id = data.ibm_cis_domain.cis_domain.domain_id + firewall_type = "access_rules" + } + `) +} + +func testAccCheckIBMCisFirewallUARuleDataSourceConfigBasic() string { + return testAccCheckIBMCisFirewallUARuleBasic() + fmt.Sprintf(` + data "ibm_cis_firewall" "ua_rule"{ + cis_id = data.ibm_cis.cis.id + domain_id = data.ibm_cis_domain.cis_domain.domain_id + firewall_type = "ua_rules" + } `) } diff --git a/ibm/provider.go b/ibm/provider.go index 7ae2da5e51..dcdd52a94c 100644 --- a/ibm/provider.go +++ b/ibm/provider.go @@ -173,7 +173,7 @@ func Provider() terraform.ResourceProvider { "ibm_cis_origin_pools": dataSourceIBMCISOriginPools(), "ibm_cis_healthchecks": dataSourceIBMCISHealthChecks(), "ibm_cis_domain": dataSourceIBMCISDomain(), - "ibm_cis_firewall": dataIBMCISFirewallRecord(), + "ibm_cis_firewall": dataIBMCISFirewallsRecord(), "ibm_cis_rate_limit": dataSourceIBMCISRateLimit(), "ibm_cis_ip_addresses": dataSourceIBMCISIP(), "ibm_cis_edge_functions_actions": dataSourceIBMCISEdgeFunctionsActions(), @@ -490,6 +490,7 @@ func Validator() ValidatorDict { "ibm_cis_routing": resourceIBMCISRoutingValidator(), "ibm_cis_cache_settings": resourceIBMCISCacheSettingsValidator(), "ibm_cis_custom_page": resourceIBMCISCustomPageValidator(), + "ibm_cis_firewall": resourceIBMCISFirewallValidator(), "ibm_tg_gateway": resourceIBMTGValidator(), "ibm_tg_connection": resourceIBMTransitGatewayConnectionValidator(), "ibm_dl_virtual_connection": resourceIBMdlGatewayVCValidator(), diff --git a/ibm/resource_ibm_cis_firewall.go b/ibm/resource_ibm_cis_firewall.go index ec5e380063..b7caf115c3 100644 --- a/ibm/resource_ibm_cis_firewall.go +++ b/ibm/resource_ibm_cis_firewall.go @@ -3,11 +3,53 @@ package ibm import ( "fmt" "log" - "strings" + "github.com/IBM/go-sdk-core/v3/core" + cislockdownv1 "github.com/IBM/networking-go-sdk/zonelockdownv1" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) - v1 "github.com/IBM-Cloud/bluemix-go/api/cis/cisv1" +const ( + ibmCISFirewall = "ibm_cis_firewall" + cisFirewallType = "firewall_type" + cisFirewallTypeLockdowns = "lockdowns" + cisFirewallTypeAccessRules = "access_rules" + cisFirewallTypeUARules = "ua_rules" + cisFirewallLockdown = "lockdown" + cisFirewallLockdownID = "lockdown_id" + cisFirewallLockdownName = "name" + cisFirewallLockdownPaused = "paused" + cisFirewallLockdownDesc = "description" + cisFirewallLockdownPriority = "priority" + cisFirewallLockdownURLs = "urls" + cisFirewallLockdownConfigurations = "configurations" + cisFirewallLockdownConfigurationsTarget = "target" + cisFirewallLockdownConfigurationsTargetIP = "ip" + cisFirewallLockdownConfigurationsTargetIPRange = "ip_range" + cisFirewallLockdownConfigurationsValue = "value" + cisFirewallAccessRule = "access_rule" + cisFirewallAccessRuleID = "access_rule_id" + cisFirewallAccessRuleMode = "mode" + cisFirewallAccessRuleModeBlock = "block" + cisFirewallAccessRuleModeChallenge = "challenge" + cisFirewallAccessRuleModeWhitelist = "whitelist" + cisFirewallAccessRuleModeJSChallenge = "js_challenge" + cisFirewallAccessRuleNotes = "notes" + cisFirewallAccessRuleConfiguration = "configuration" + cisFirewallAccessRuleConfigurationTarget = "target" + cisFirewallAccessRuleConfigurationValue = "value" + cisFirewallUARule = "ua_rule" + cisFirewallUARuleID = "ua_rule_id" + cisFirewallUARulePaused = "paused" + cisFirewallUARuleDesc = "description" + cisFirewallUARuleMode = "mode" + cisFirewallUARuleModeBlock = "block" + cisFirewallUARuleModeChallenge = "challenge" + cisFirewallUARuleModeJSChallenge = "js_challenge" + cisFirewallUARuleConfiguration = "configuration" + cisFirewallUARuleConfigurationTarget = "target" + cisFirewallUARuleConfigurationTargetUA = "ua" + cisFirewallUARuleConfigurationValue = "value" ) func resourceIBMCISFirewallRecord() *schema.Resource { @@ -20,63 +62,193 @@ func resourceIBMCISFirewallRecord() *schema.Resource { Importer: &schema.ResourceImporter{}, Schema: map[string]*schema.Schema{ - "cis_id": { + cisID: { Type: schema.TypeString, Description: "CIS object id", Required: true, + ForceNew: true, }, - "domain_id": { - Type: schema.TypeString, - Description: "Associated CIS domain", - Required: true, + cisDomainID: { + Type: schema.TypeString, + Description: "Associated CIS domain", + Required: true, + ForceNew: true, + DiffSuppressFunc: suppressDomainIDDiff, }, - "firewall_type": { + cisFirewallType: { Type: schema.TypeString, Required: true, + ForceNew: true, Description: "Type of firewall.Allowable values are access-rules,ua-rules,lockdowns", - ValidateFunc: validateAllowedStringValue([]string{"lockdowns", "access_rules", "ua_rules"}), + ValidateFunc: InvokeValidator(ibmCISFirewall, cisFirewallType), }, - "lockdown": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Description: "Lockdown json Data", + cisFirewallLockdown: { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + ExactlyOneOf: []string{ + cisFirewallLockdown, + cisFirewallAccessRule, + cisFirewallUARule}, + Description: "Lockdown Data", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "lockdown_id": { - Type: schema.TypeString, - Computed: true, + cisFirewallLockdownID: { + Type: schema.TypeString, + Computed: true, + Description: "firewall identifier", }, - "paused": { - Type: schema.TypeBool, - Optional: true, + cisFirewallLockdownPaused: { + Type: schema.TypeBool, + Optional: true, + Description: "Firewall rule paused or enabled", }, - "description": { - Type: schema.TypeString, - Optional: true, + cisFirewallLockdownDesc: { + Type: schema.TypeString, + Optional: true, + Description: "description", }, - "priority": { - Type: schema.TypeInt, - Optional: true, + cisFirewallLockdownPriority: { + Type: schema.TypeInt, + Optional: true, + Description: "Firewall priority", }, - "urls": { + cisFirewallLockdownURLs: { + Type: schema.TypeList, + Required: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Description: "URL in which firewall rule is applied", + }, + cisFirewallLockdownConfigurations: { Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, + Required: true, + MinItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + cisFirewallLockdownConfigurationsTarget: { + Type: schema.TypeString, + Required: true, + Description: "Target type", + ValidateFunc: InvokeValidator( + ibmCISFirewall, + cisFirewallLockdownConfigurationsTarget), + }, + cisFirewallLockdownConfigurationsValue: { + Type: schema.TypeString, + Required: true, + Description: "Target value", + }, + }, + }, + }, + }, + }, + }, + cisFirewallAccessRule: { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + ExactlyOneOf: []string{ + cisFirewallLockdown, + cisFirewallAccessRule, + cisFirewallUARule}, + Description: "Access Rule Data", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + cisFirewallAccessRuleID: { + Type: schema.TypeString, + Computed: true, + Description: "access rule firewall identifier", + }, + cisFirewallAccessRuleNotes: { + Type: schema.TypeString, + Optional: true, + Description: "description", }, - "configurations": { + cisFirewallAccessRuleMode: { + Type: schema.TypeString, + Required: true, + Description: "Access rule mode", + ValidateFunc: InvokeValidator(ibmCISFirewall, cisFirewallAccessRuleMode), + }, + cisFirewallAccessRuleConfiguration: { Type: schema.TypeList, - Optional: true, + Required: true, + MinItems: 1, + MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "target": { - Type: schema.TypeString, - Optional: true, + cisFirewallUARuleConfigurationTarget: { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "Target type", + ValidateFunc: InvokeValidator(ibmCISFirewall, + cisFirewallAccessRuleConfigurationTarget), }, - "value": { - Type: schema.TypeString, - Optional: true, + cisFirewallUARuleConfigurationValue: { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "Target value", + }, + }, + }, + }, + }, + }, + }, + cisFirewallUARule: { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + ExactlyOneOf: []string{ + cisFirewallLockdown, + cisFirewallAccessRule, + cisFirewallUARule}, + Description: "User Agent Rule Data", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + cisFirewallUARuleID: { + Type: schema.TypeString, + Computed: true, + Description: "User Agent firewall identifier", + }, + cisFirewallUARulePaused: { + Type: schema.TypeBool, + Optional: true, + Description: "Rule whether paused or not", + }, + cisFirewallUARuleDesc: { + Type: schema.TypeString, + Optional: true, + Description: "description", + }, + cisFirewallUARuleMode: { + Type: schema.TypeString, + Required: true, + Description: "user agent rule mode", + ValidateFunc: InvokeValidator(ibmCISFirewall, cisFirewallUARuleMode), + }, + cisFirewallUARuleConfiguration: { + Type: schema.TypeList, + Required: true, + MinItems: 1, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + cisFirewallUARuleConfigurationTarget: { + Type: schema.TypeString, + Required: true, + Description: "Target type", + ValidateFunc: InvokeValidator(ibmCISFirewall, + cisFirewallUARuleConfigurationTarget), + }, + cisFirewallUARuleConfigurationValue: { + Type: schema.TypeString, + Required: true, + Description: "Target value", }, }, }, @@ -88,220 +260,555 @@ func resourceIBMCISFirewallRecord() *schema.Resource { } } +func resourceIBMCISFirewallValidator() *ResourceValidator { + firewallTypes := "access_rules, ua_rules, lockdowns" + validateSchema := make([]ValidateSchema, 1) + validateSchema = append(validateSchema, + ValidateSchema{ + Identifier: cisFirewallType, + ValidateFunctionIdentifier: ValidateAllowedStringValue, + Type: TypeString, + Required: true, + AllowedValues: firewallTypes}) + validateSchema = append(validateSchema, + ValidateSchema{ + Identifier: cisFirewallLockdownConfigurationsTarget, + ValidateFunctionIdentifier: ValidateAllowedStringValue, + Type: TypeString, + Required: true, + AllowedValues: "ip, ip_range"}) + validateSchema = append(validateSchema, + ValidateSchema{ + Identifier: cisFirewallAccessRuleConfigurationTarget, + ValidateFunctionIdentifier: ValidateAllowedStringValue, + Type: TypeString, + Required: true, + AllowedValues: "ip, ip_range, asn, country"}) + validateSchema = append(validateSchema, + ValidateSchema{ + Identifier: cisFirewallUARuleConfigurationTarget, + ValidateFunctionIdentifier: ValidateAllowedStringValue, + Type: TypeString, + Required: true, + AllowedValues: "ua"}) + validateSchema = append(validateSchema, + ValidateSchema{ + Identifier: cisFirewallAccessRuleMode, + ValidateFunctionIdentifier: ValidateAllowedStringValue, + Type: TypeString, + Required: true, + AllowedValues: "block, challenge, whitelist, js_challenge"}) + validateSchema = append(validateSchema, + ValidateSchema{ + Identifier: cisFirewallUARuleMode, + ValidateFunctionIdentifier: ValidateAllowedStringValue, + Type: TypeString, + Required: true, + AllowedValues: "block, challenge, js_challenge"}) + cisFirewallValidator := ResourceValidator{ResourceName: ibmCISHealthCheck, Schema: validateSchema} + return &cisFirewallValidator +} + func resourceIBMCISFirewallRecordCreate(d *schema.ResourceData, meta interface{}) error { - cisClient, err := meta.(ClientSession).CisAPI() - if err != nil { - return err - } - cisID := d.Get("cis_id").(string) - zoneID, _, err := convertTftoCisTwoVar(d.Get("domain_id").(string)) - if err != nil { - return err - } - firewallType := d.Get("firewall_type").(string) + crn := d.Get(cisID).(string) + zoneID, _, _ := convertTftoCisTwoVar(d.Get(cisDomainID).(string)) + firewallType := d.Get(cisFirewallType).(string) - newRecord := v1.FirewallBody{} + if firewallType == cisFirewallTypeLockdowns { + // Firewall Type : Lockdowns - if lockdown, ok := d.GetOk("lockdown"); ok { - lockdownlist := lockdown.([]interface{}) - for _, l := range lockdownlist { - lockdownMap, _ := l.(map[string]interface{}) + cisClient, err := meta.(ClientSession).CisLockdownClientSession() + if err != nil { + return err + } + lockdown := d.Get(cisFirewallLockdown).([]interface{})[0].(map[string]interface{}) - if paused := lockdownMap["paused"]; paused != nil { - newRecord.Paused = paused.(bool) - } - if description := lockdownMap["description"]; description != nil { - newRecord.Description = description.(string) - } - if priority := lockdownMap["priority"]; priority != nil { - newRecord.Priority = priority.(int) - } - var urls = make([]string, 0) - if u, ok := lockdownMap["urls"]; ok && u != nil { - for _, url := range u.([]interface{}) { - urls = append(urls, fmt.Sprintf("%v", url)) - } - newRecord.Urls = urls - } - var configurationList = make([]v1.Configuration, 0) - if res, ok := lockdownMap["configurations"]; ok { - configurations := res.([]interface{}) - for _, c := range configurations { - r, _ := c.(map[string]interface{}) - if target, value := r["target"], r["value"]; target != nil && value != nil { - configurationRecord := v1.Configuration{} - configurationRecord.Target, configurationRecord.Value = target.(string), value.(string) - configurationList = append(configurationList, configurationRecord) - } - } - newRecord.Configurations = configurationList - } + opt := cisClient.NewCreateZoneLockdownRuleOptions() + // not able to check bool variable availability + v, _ := lockdown[cisFirewallLockdownPaused] + opt.SetPaused(v.(bool)) + if v, ok := lockdown[cisFirewallLockdownDesc]; ok && v.(string) != "" { + opt.SetDescription(v.(string)) } - } + if v, ok := lockdown[cisFirewallLockdownPriority]; ok && v.(int) > 0 { + opt.SetPriority(int64(v.(int))) + } + urls := expandStringList(lockdown[cisFirewallLockdownURLs].([]interface{})) + configurations, err := expandLockdownsTypeConfiguration( + lockdown[cisFirewallLockdownConfigurations].([]interface{})) + if err != nil { + return err + } + opt.SetUrls(urls) + opt.SetConfigurations(configurations) - var recordPtr *v1.FirewallRecord - recordPtr, err = cisClient.Firewall().CreateFirewall(cisID, zoneID, firewallType, newRecord) - if err != nil { - return fmt.Errorf("Failed to create Firewall: %s", err) - } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + result, response, err := cisClient.CreateZoneLockdownRule(opt) + if err != nil { + log.Printf("Create zone firewall lockdown failed: %v", response) + return err + } + d.SetId(convertCisToTfFourVar(firewallType, *result.Result.ID, zoneID, crn)) - // In the Event that the API returns an empty Firewall, we verify that the - // ID returned is not the default "" + } else if firewallType == cisFirewallTypeAccessRules { - record := *recordPtr + cisClient, err := meta.(ClientSession).CisAccessRuleClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + accessRule := d.Get(cisFirewallAccessRule).([]interface{})[0].(map[string]interface{}) - if record.ID == "" { - return fmt.Errorf("Failed to find record in Create response; Record was empty") - } + mode := accessRule[cisFirewallAccessRuleMode].(string) + + configList := accessRule[cisFirewallAccessRuleConfiguration].([]interface{}) + + config := configList[0].(map[string]interface{}) + target := config[cisFirewallAccessRuleConfigurationTarget].(string) + value := config[cisFirewallAccessRuleConfigurationValue].(string) - d.SetId(convertCisToTfFourVar(firewallType, record.ID, zoneID, cisID)) + configOpt, err := cisClient.NewZoneAccessRuleInputConfiguration(target, value) + if err != nil { + log.Printf("Error in firewall type %s input: %s", firewallType, err) + return err + } + + opt := cisClient.NewCreateZoneAccessRuleOptions() + opt.SetMode(mode) + opt.SetConfiguration(configOpt) + if v, ok := accessRule[cisFirewallAccessRuleNotes]; ok && v.(string) != "" { + opt.SetNotes(v.(string)) + } + + result, response, err := cisClient.CreateZoneAccessRule(opt) + if err != nil { + log.Printf("Create zone firewall access rule failed: %v", response) + return err + } + d.SetId(convertCisToTfFourVar(firewallType, *result.Result.ID, zoneID, crn)) + + } else if firewallType == cisFirewallTypeUARules { + cisClient, err := meta.(ClientSession).CisUARuleClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + uaRule := d.Get(cisFirewallUARule).([]interface{})[0].(map[string]interface{}) + + mode := uaRule[cisFirewallUARuleMode].(string) + configList := uaRule[cisFirewallUARuleConfiguration].([]interface{}) + if len(configList) > 1 { + return fmt.Errorf("Only one configuration is allowed for %s type", firewallType) + } + config := configList[0].(map[string]interface{}) + target := config[cisFirewallLockdownConfigurationsTarget].(string) + value := config[cisFirewallLockdownConfigurationsValue].(string) + + configOpt, err := cisClient.NewUseragentRuleInputConfiguration(target, value) + if err != nil { + log.Printf("Error in firewall type %s input: %s", firewallType, err) + return err + } + + opt := cisClient.NewCreateZoneUserAgentRuleOptions() + opt.SetMode(mode) + opt.SetConfiguration(configOpt) + + if v, ok := uaRule[cisFirewallUARuleDesc]; ok && v.(string) != "" { + opt.SetDescription(v.(string)) + } + // not able to check bool attribute availablity + v, _ := uaRule[cisFirewallUARulePaused] + opt.SetPaused(v.(bool)) + + result, response, err := cisClient.CreateZoneUserAgentRule(opt) + if err != nil { + log.Printf("Create zone user agent rule failed: %v", response) + return err + } + d.SetId(convertCisToTfFourVar(firewallType, *result.Result.ID, zoneID, crn)) + } return resourceIBMCISFirewallRecordRead(d, meta) } func resourceIBMCISFirewallRecordRead(d *schema.ResourceData, meta interface{}) error { - cisClient, err := meta.(ClientSession).CisAPI() - if err != nil { - return err - } - firewallType, recordID, zoneID, cisID, _ := convertTfToCisFourVar(d.Id()) - if err != nil { - return err - } + firewallType, lockdownID, zoneID, crn, _ := convertTfToCisFourVar(d.Id()) - var recordPtr *v1.FirewallRecord - recordPtr, err = cisClient.Firewall().GetFirewall(cisID, zoneID, firewallType, recordID) - if err != nil { - if strings.Contains(err.Error(), "Request failed with status code: 404") { - d.SetId("") - return nil + if firewallType == cisFirewallTypeLockdowns { + // Firewall Type : Lockdowns + cisClient, err := meta.(ClientSession).CisLockdownClientSession() + if err != nil { + return err } - log.Printf("[WARN] Error getting zone during Firewall Read %v\n", err) - return err - } - record := *recordPtr - d.Set("cis_id", cisID) - d.Set("firewall_type", firewallType) - d.Set("domain_id", convertCisToTfTwoVar(zoneID, cisID)) - - if &record.Paused != nil || record.Urls != nil || record.Configurations != nil { - configuration := make([]map[string]interface{}, 0, len(record.Configurations)) - for _, c := range record.Configurations { - r := map[string]interface{}{ - "target": c.Target, - "value": c.Value, - } - configuration = append(configuration, r) + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewGetLockdownOptions(lockdownID) + + result, response, err := cisClient.GetLockdown(opt) + if err != nil { + log.Printf("Get zone firewall lockdown failed: %v", response) + return err } - lockdown := map[string]interface{}{ - "lockdown_id": recordID, - "paused": record.Paused, - "urls": record.Urls, - "configurations": configuration, + lockdownList := []interface{}{} + lockdown := map[string]interface{}{} + lockdown[cisFirewallLockdownID] = *result.Result.ID + lockdown[cisFirewallLockdownPaused] = *result.Result.Paused + lockdown[cisFirewallLockdownURLs] = flattenStringList(result.Result.Urls) + lockdown[cisFirewallLockdownConfigurations] = + flattenLockdownsTypeConfiguration(result.Result.Configurations) + if result.Result.Description != nil { + lockdown[cisFirewallLockdownDesc] = *result.Result.Description } - if &record.Description != nil { - lockdown["description"] = record.Description + if result.Result.Priority != nil { + lockdown[cisFirewallLockdownPriority] = *result.Result.Priority } - if &record.Priority != nil { - lockdown["priority"] = record.Priority + lockdownList = append(lockdownList, lockdown) + d.Set(cisFirewallLockdown, lockdownList) + + } else if firewallType == cisFirewallTypeAccessRules { + + // Firewall Type : Zone Access firewall rules + cisClient, err := meta.(ClientSession).CisAccessRuleClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewGetZoneAccessRuleOptions(lockdownID) + + result, response, err := cisClient.GetZoneAccessRule(opt) + if err != nil { + log.Printf("Get zone firewall lockdown failed: %v", response) + return err } - lockdowns := make([]map[string]interface{}, 0, 1) - lockdowns = append(lockdowns, lockdown) - d.Set("lockdown", lockdowns) + config := map[string]interface{}{} + configList := []interface{}{} + config[cisFirewallUARuleConfigurationTarget] = *result.Result.Configuration.Target + config[cisFirewallUARuleConfigurationValue] = *result.Result.Configuration.Value + configList = append(configList, config) + + accessRuleList := []interface{}{} + accessRule := map[string]interface{}{} + accessRule[cisFirewallAccessRuleID] = *result.Result.ID + accessRule[cisFirewallAccessRuleNotes] = *result.Result.Notes + accessRule[cisFirewallAccessRuleMode] = *result.Result.Mode + accessRule[cisFirewallAccessRuleConfiguration] = configList + accessRuleList = append(accessRuleList, accessRule) + d.Set(cisFirewallAccessRule, accessRuleList) + } else if firewallType == cisFirewallTypeUARules { + // Firewall Type: User Agent access rules + cisClient, err := meta.(ClientSession).CisUARuleClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewGetUserAgentRuleOptions(lockdownID) + result, response, err := cisClient.GetUserAgentRule(opt) + if err != nil { + log.Printf("Get zone user agent rule failed: %v", response) + return err + } + + config := map[string]interface{}{} + configList := []interface{}{} + config[cisFirewallUARuleConfigurationTarget] = *result.Result.Configuration.Target + config[cisFirewallUARuleConfigurationValue] = *result.Result.Configuration.Value + configList = append(configList, config) + + uaRuleList := []interface{}{} + uaRule := map[string]interface{}{} + uaRule[cisFirewallUARuleID] = *result.Result.ID + uaRule[cisFirewallUARulePaused] = *result.Result.Paused + uaRule[cisFirewallUARuleMode] = *result.Result.Mode + uaRule[cisFirewallUARuleConfiguration] = configList + if result.Result.Description != nil { + uaRule[cisFirewallUARuleDesc] = *result.Result.Description + } + uaRuleList = append(uaRuleList, uaRule) + d.Set(cisFirewallUARule, uaRuleList) } + d.Set(cisID, crn) + d.Set(cisDomainID, zoneID) + d.Set(cisFirewallType, firewallType) return nil } func resourceIBMCISFirewallRecordUpdate(d *schema.ResourceData, meta interface{}) error { - cisClient, err := meta.(ClientSession).CisAPI() - if err != nil { - return err - } - firewallType, recordID, zoneID, cisID, _ := convertTfToCisFourVar(d.Id()) - if err != nil { - return err - } - updateRecord := v1.FirewallBody{} - if d.HasChange("lockdown") { - if lockdown, ok := d.GetOk("lockdown"); ok { - lockdownlist := lockdown.([]interface{}) - for _, l := range lockdownlist { - lockdownMap, _ := l.(map[string]interface{}) - if paused := lockdownMap["paused"]; paused != nil { - updateRecord.Paused = paused.(bool) - } - if description := lockdownMap["description"]; description != nil { - updateRecord.Description = description.(string) - } - if priority := lockdownMap["priority"]; priority != nil { - updateRecord.Priority = priority.(int) - } - var urls = make([]string, 0) - if u, ok := lockdownMap["urls"]; ok && u != nil { - for _, url := range u.([]interface{}) { - urls = append(urls, fmt.Sprintf("%v", url)) - } - updateRecord.Urls = urls - } - var configurationList = make([]v1.Configuration, 0) - if res, ok := lockdownMap["configurations"]; ok { - configurations := res.([]interface{}) - for _, c := range configurations { - r, _ := c.(map[string]interface{}) - if target, value := r["target"], r["value"]; target != nil && value != nil { - configurationRecord := v1.Configuration{} - configurationRecord.Target, configurationRecord.Value = target.(string), value.(string) - configurationList = append(configurationList, configurationRecord) - } - } - updateRecord.Configurations = configurationList - } + + firewallType, lockdownID, zoneID, crn, _ := convertTfToCisFourVar(d.Id()) + + if d.HasChange(cisFirewallLockdown) || + d.HasChange(cisFirewallAccessRule) || + d.HasChange(cisFirewallUARule) { + + if firewallType == cisFirewallTypeLockdowns { + // Firewall Type : Lockdowns + lockdown := d.Get(cisFirewallLockdown).([]interface{})[0].(map[string]interface{}) + + cisClient, err := meta.(ClientSession).CisLockdownClientSession() + if err != nil { + return err + } + + opt := cisClient.NewUpdateLockdownRuleOptions(lockdownID) + // not able to check bool variable availability + v, _ := lockdown[cisFirewallLockdownPaused] + opt.SetPaused(v.(bool)) + if v, ok := lockdown[cisFirewallLockdownDesc]; ok && v.(string) != "" { + opt.SetDescription(v.(string)) + } + if v, ok := lockdown[cisFirewallLockdownPriority]; ok && v.(int) > 0 { + opt.SetPriority(int64(v.(int))) + } + urls := expandStringList(lockdown[cisFirewallLockdownURLs].([]interface{})) + configurations, err := expandLockdownsTypeConfiguration(lockdown[cisFirewallLockdownConfigurations].([]interface{})) + if err != nil { + return err + } + opt.SetUrls(urls) + opt.SetConfigurations(configurations) + + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + _, response, err := cisClient.UpdateLockdownRule(opt) + if err != nil { + log.Printf("Update zone firewall lockdown failed: %v", response) + return err + } + + } else if firewallType == cisFirewallTypeAccessRules { + + accessRule := d.Get(cisFirewallAccessRule).([]interface{})[0].(map[string]interface{}) + + // Firewall Type : Zone Access firewall rules + cisClient, err := meta.(ClientSession).CisAccessRuleClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + mode := accessRule[cisFirewallAccessRuleMode].(string) + opt := cisClient.NewUpdateZoneAccessRuleOptions(lockdownID) + if v, ok := accessRule[cisFirewallAccessRuleNotes]; ok && v.(string) != "" { + opt.SetNotes(v.(string)) + } + opt.SetMode(mode) + + _, response, err := cisClient.UpdateZoneAccessRule(opt) + if err != nil { + log.Printf("Update zone firewall access rule failed: %v", response) + return err + } + + } else if firewallType == cisFirewallTypeUARules { + // Firewall Type: User Agent access rules + uaRule := d.Get(cisFirewallUARule).([]interface{})[0].(map[string]interface{}) + cisClient, err := meta.(ClientSession).CisUARuleClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + mode := uaRule[cisFirewallUARuleMode].(string) + config := uaRule[cisFirewallUARuleConfiguration].([]interface{})[0].(map[string]interface{}) + target := config[cisFirewallUARuleConfigurationTarget].(string) + value := config[cisFirewallUARuleConfigurationValue].(string) + + configOpt, err := cisClient.NewUseragentRuleInputConfiguration(target, value) + if err != nil { + log.Printf("Error in firewall type %s input: %s", firewallType, err) + return err + } + + opt := cisClient.NewUpdateUserAgentRuleOptions(lockdownID) + opt.SetMode(mode) + opt.SetConfiguration(configOpt) + + if v, ok := uaRule[cisFirewallUARuleDesc]; ok && v.(string) != "" { + opt.SetDescription(v.(string)) + } + // not able to check bool attribute availablity + v, _ := uaRule[cisFirewallUARulePaused] + opt.SetPaused(v.(bool)) + + _, response, err := cisClient.UpdateUserAgentRule(opt) + if err != nil { + log.Printf("Update zone user agent rule failed: %v", response) + return err } } - } - _, err = cisClient.Firewall().UpdateFirewall(cisID, zoneID, firewallType, recordID, updateRecord) - if err != nil { - log.Printf("[WARN] Error getting zone during Firewall Update %v\n", err) - return err - } + } return resourceIBMCISFirewallRecordRead(d, meta) } func resourceIBMCISFirewallRecordDelete(d *schema.ResourceData, meta interface{}) error { - cisClient, err := meta.(ClientSession).CisAPI() - if err != nil { - return err - } - firewallType, recordID, zoneID, cisID, _ := convertTfToCisFourVar(d.Id()) - if err != nil { - return err - } - err = cisClient.Firewall().DeleteFirewall(cisID, zoneID, firewallType, recordID) - if err != nil && !strings.Contains(err.Error(), "Request failed with status code: 404") { - return fmt.Errorf("Error deleting IBMCISFirewall: %s", err) + firewallType, lockdownID, zoneID, crn, _ := convertTfToCisFourVar(d.Id()) + + if firewallType == cisFirewallTypeLockdowns { + // Firewall Type : Lockdowns + cisClient, err := meta.(ClientSession).CisLockdownClientSession() + if err != nil { + return err + } + + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewDeleteZoneLockdownRuleOptions(lockdownID) + + _, response, err := cisClient.DeleteZoneLockdownRule(opt) + if err != nil { + log.Printf("Delete zone firewall lockdown failed: %v", response) + return err + } + + } else if firewallType == cisFirewallTypeAccessRules { + + // Firewall Type : Zone Access firewall rules + cisClient, err := meta.(ClientSession).CisAccessRuleClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewDeleteZoneAccessRuleOptions(lockdownID) + + _, response, err := cisClient.DeleteZoneAccessRule(opt) + if err != nil { + log.Printf("Delete zone firewall access rule failed: %v", response) + return err + } + + } else if firewallType == cisFirewallTypeUARules { + // Firewall Type: User Agent access rules + cisClient, err := meta.(ClientSession).CisUARuleClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewDeleteZoneUserAgentRuleOptions(lockdownID) + _, response, err := cisClient.DeleteZoneUserAgentRule(opt) + if err != nil { + log.Printf("Delete zone user agent rule failed: %v", response) + return err + } } + return nil } func resourceIBMCISFirewallRecordExists(d *schema.ResourceData, meta interface{}) (bool, error) { - cisClient, err := meta.(ClientSession).CisAPI() - if err != nil { - return false, err - } - firewallType, recordID, zoneID, cisID, _ := convertTfToCisFourVar(d.Id()) - if err != nil { - return false, err - } - _, err = cisClient.Firewall().GetFirewall(cisID, zoneID, firewallType, recordID) - if err != nil { - if strings.Contains(err.Error(), "Request failed with status code: 404") { - return false, nil + firewallType, lockdownID, zoneID, crn, _ := convertTfToCisFourVar(d.Id()) + + if firewallType == cisFirewallTypeLockdowns { + // Firewall Type : Lockdowns + cisClient, err := meta.(ClientSession).CisLockdownClientSession() + if err != nil { + return false, err + } + + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewGetLockdownOptions(lockdownID) + + _, response, err := cisClient.GetLockdown(opt) + if err != nil { + if response != nil && response.StatusCode == 404 { + log.Printf("Zone Firewall Lockdown is not found") + return false, nil + } + log.Printf("Get zone firewall lockdown failed: %v", response) + return false, err + } + + } else if firewallType == cisFirewallTypeAccessRules { + + // Firewall Type : Zone Access firewall rules + cisClient, err := meta.(ClientSession).CisAccessRuleClientSession() + if err != nil { + return false, err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewGetZoneAccessRuleOptions(lockdownID) + + _, response, err := cisClient.GetZoneAccessRule(opt) + if err != nil { + if response != nil && response.StatusCode == 404 { + log.Printf("Zone Firewall Access Rule is not found") + return false, nil + } + log.Printf("Get zone firewall lockdown failed: %v", response) + return false, err + } + + } else if firewallType == cisFirewallTypeUARules { + // Firewall Type: User Agent access rules + cisClient, err := meta.(ClientSession).CisUARuleClientSession() + if err != nil { + return false, err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewGetUserAgentRuleOptions(lockdownID) + _, response, err := cisClient.GetUserAgentRule(opt) + if err != nil { + if response != nil && response.StatusCode == 404 { + log.Printf("Zone Firewall User Agent Rule does not found") + return false, nil + } + log.Printf("Get zone user agent rule failed: %v", response) + return false, err } - return false, fmt.Errorf("Error getting IBMCISFirewall: %s", err) + } return true, nil } + +func expandLockdownsTypeConfiguration(lockdownConfigs []interface{}) ([]cislockdownv1.LockdownInputConfigurationsItem, error) { + var configListOutput = make([]cislockdownv1.LockdownInputConfigurationsItem, 0) + + for _, lockdownConfig := range lockdownConfigs { + configMap, _ := lockdownConfig.(map[string]interface{}) + target := configMap[cisFirewallLockdownConfigurationsTarget].(string) + value := configMap[cisFirewallLockdownConfigurationsValue].(string) + configOutput := cislockdownv1.LockdownInputConfigurationsItem{ + Target: core.StringPtr(target), + Value: core.StringPtr(value), + } + configListOutput = append(configListOutput, configOutput) + } + return configListOutput, nil +} + +func flattenLockdownsTypeConfiguration(lockdownConfigs []cislockdownv1.LockdownObjectConfigurationsItem) interface{} { + configListOutput := []interface{}{} + + for _, lockdownConfig := range lockdownConfigs { + configOutput := map[string]string{} + configOutput[cisFirewallLockdownConfigurationsTarget] = *lockdownConfig.Target + configOutput[cisFirewallLockdownConfigurationsValue] = *lockdownConfig.Value + configListOutput = append(configListOutput, configOutput) + } + return configListOutput +} diff --git a/ibm/resource_ibm_cis_firewall_test.go b/ibm/resource_ibm_cis_firewall_test.go index 0f1ed045cf..ea5185595c 100644 --- a/ibm/resource_ibm_cis_firewall_test.go +++ b/ibm/resource_ibm_cis_firewall_test.go @@ -2,8 +2,10 @@ package ibm import ( "fmt" + "log" "testing" + "github.com/IBM/go-sdk-core/v4/core" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/terraform" ) @@ -11,86 +13,231 @@ import ( func TestAccIBMCisFirewall_Basic(t *testing.T) { var record string - name := "lockdowns" + name := "ibm_cis_firewall.lockdowns" resource.Test(t, resource.TestCase{ Providers: testAccProviders, CheckDestroy: testAccCheckIBMCisFirewallDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckIBMCisFirewallConfigCisDS_Basic(name), + Config: testAccCheckIBMCisFirewallLockdownBasic(), Check: resource.ComposeTestCheckFunc( - testAccCheckIBMCisFirewallExists("ibm_cis_firewall.lockdown", &record), + testAccCheckIBMCisFirewallExists(name, &record), resource.TestCheckResourceAttr( - "ibm_cis_firewall.lockdown", "firewall_type", "lockdowns"), + name, "firewall_type", "lockdowns"), resource.TestCheckResourceAttr( - "ibm_cis_firewall.lockdown", "lockdown.0.configurations.0.value", "127.0.0.1"), + name, "lockdown.0.configurations.0.value", "127.0.0.1"), ), }, { - Config: testAccCheckIBMCisFirewallConfigCisDS_Update(name), + Config: testAccCheckIBMCisFirewallLockdownUpdate(), Check: resource.ComposeTestCheckFunc( - testAccCheckIBMCisFirewallExists("ibm_cis_firewall.lockdown", &record), + testAccCheckIBMCisFirewallExists(name, &record), resource.TestCheckResourceAttr( - "ibm_cis_firewall.lockdown", "firewall_type", "lockdowns"), + name, "firewall_type", "lockdowns"), resource.TestCheckResourceAttr( - "ibm_cis_firewall.lockdown", "lockdown.0.configurations.0.value", "127.0.0.3"), + name, "lockdown.0.configurations.0.value", "127.0.0.3"), ), }, }, }) } -func TestAccIBMCisFirewall_Import(t *testing.T) { + +func TestAccIBMCisFirewallAccessRuleBasic(t *testing.T) { var record string - name := "lockdowns" + name := "ibm_cis_firewall.access_rules" resource.Test(t, resource.TestCase{ Providers: testAccProviders, CheckDestroy: testAccCheckIBMCisFirewallDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckIBMCisFirewallConfigCisDS_Basic(name), + { + Config: testAccCheckIBMCisFirewallAccessRuleBasic(), Check: resource.ComposeTestCheckFunc( - testAccCheckIBMCisFirewallExists("ibm_cis_firewall.lockdown", &record), + testAccCheckIBMCisFirewallExists(name, &record), resource.TestCheckResourceAttr( - "ibm_cis_firewall.lockdown", "firewall_type", "lockdowns"), + name, "firewall_type", "access_rules"), resource.TestCheckResourceAttr( - "ibm_cis_firewall.lockdown", "lockdown.0.configurations.0.value", "127.0.0.1"), + name, "access_rule.0.configuration.0.value", "192.168.1.3"), ), }, { - Config: testAccCheckIBMCisFirewallConfigCisDS_Update(name), + Config: testAccCheckIBMCisFirewallAccessRuleUpdate(), + Check: resource.ComposeTestCheckFunc( + testAccCheckIBMCisFirewallExists(name, &record), + resource.TestCheckResourceAttr( + name, "firewall_type", "access_rules"), + resource.TestCheckResourceAttr( + name, "access_rule.0.configuration.0.value", "192.168.1.3"), + ), + }, + }, + }) +} + +func TestAccIBMCisFirewallUARuleBasic(t *testing.T) { + + var record string + name := "ibm_cis_firewall.ua_rules" + + resource.Test(t, resource.TestCase{ + Providers: testAccProviders, + CheckDestroy: testAccCheckIBMCisFirewallDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCisFirewallUARuleBasic(), + Check: resource.ComposeTestCheckFunc( + testAccCheckIBMCisFirewallExists(name, &record), + resource.TestCheckResourceAttr( + name, "firewall_type", "ua_rules"), + resource.TestCheckResourceAttr( + name, "ua_rule.0.mode", "block"), + ), + }, + { + Config: testAccCheckIBMCisFirewallUARuleUpdate(), + Check: resource.ComposeTestCheckFunc( + testAccCheckIBMCisFirewallExists(name, &record), + resource.TestCheckResourceAttr( + name, "firewall_type", "ua_rules"), + resource.TestCheckResourceAttr( + name, "ua_rule.0.mode", "challenge"), + ), + }, + }, + }) +} + +func TestAccIBMCisFirewallLockdown_Import(t *testing.T) { + name := "ibm_cis_firewall.lockdowns" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCisFirewallLockdownBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + name, "firewall_type", "lockdowns"), + resource.TestCheckResourceAttr( + name, "lockdown.0.configurations.0.value", "127.0.0.1"), + ), + }, + { + ResourceName: name, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccIBMCisFirewallAccessRule_Import(t *testing.T) { + name := "ibm_cis_firewall.access_rules" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCisFirewallAccessRuleBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + name, "firewall_type", "access_rules"), + resource.TestCheckResourceAttr( + name, "access_rule.0.configuration.0.value", "192.168.1.3"), + ), + }, + { + ResourceName: name, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccIBMCisFirewallUARule_Import(t *testing.T) { + name := "ibm_cis_firewall.ua_rules" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCisFirewallUARuleBasic(), Check: resource.ComposeTestCheckFunc( - testAccCheckIBMCisFirewallExists("ibm_cis_firewall.lockdown", &record), resource.TestCheckResourceAttr( - "ibm_cis_firewall.lockdown", "firewall_type", "lockdowns"), + name, "firewall_type", "ua_rules"), resource.TestCheckResourceAttr( - "ibm_cis_firewall.lockdown", "lockdown.0.configurations.0.value", "127.0.0.3"), + name, "ua_rule.0.mode", "block"), ), }, - resource.TestStep{ - ResourceName: "ibm_cis_firewall.lockdown", + { + ResourceName: name, ImportState: true, ImportStateVerify: true, }, }, }) } + func testAccCheckIBMCisFirewallDestroy(s *terraform.State) error { - cisClient, err := testAccProvider.Meta().(ClientSession).CisAPI() - if err != nil { - return err - } for _, rs := range s.RootModule().Resources { if rs.Type != "ibm_cis_firewall" { continue } - firewallType, recordID, zoneID, cisID, _ := convertTfToCisFourVar(rs.Primary.ID) - _, err = cisClient.Firewall().GetFirewall(cisID, zoneID, firewallType, recordID) - if err == nil { - return fmt.Errorf("Record still exists") + firewallType, lockdownID, zoneID, crn, _ := convertTfToCisFourVar(rs.Primary.ID) + if firewallType == cisFirewallTypeLockdowns { + // Firewall Type : Lockdowns + cisClient, err := testAccProvider.Meta().(ClientSession).CisLockdownClientSession() + if err != nil { + return err + } + + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewGetLockdownOptions(lockdownID) + _, _, err = cisClient.GetLockdown(opt) + if err == nil { + return fmt.Errorf("%s type rule still exists", firewallType) + } + + } else if firewallType == cisFirewallTypeAccessRules { + + // Firewall Type : Zone Access firewall rules + cisClient, err := testAccProvider.Meta().(ClientSession).CisAccessRuleClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewGetZoneAccessRuleOptions(lockdownID) + _, _, err = cisClient.GetZoneAccessRule(opt) + if err == nil { + return fmt.Errorf("%s type rule still exists", firewallType) + } + + } else if firewallType == cisFirewallTypeUARules { + // Firewall Type: User Agent access rules + cisClient, err := testAccProvider.Meta().(ClientSession).CisUARuleClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewGetUserAgentRuleOptions(lockdownID) + _, _, err = cisClient.GetUserAgentRule(opt) + if err == nil { + return fmt.Errorf("%s type rule still exists", firewallType) + } } + } return nil @@ -108,31 +255,77 @@ func testAccCheckIBMCisFirewallExists(n string, tfRecordID *string) resource.Tes } tfRecord := *tfRecordID - cisClient, err := testAccProvider.Meta().(ClientSession).CisAPI() - firewallType, recordID, zoneID, cisID, _ := convertTfToCisFourVar(rs.Primary.ID) - foundRecordPtr, err := cisClient.Firewall().GetFirewall(cisID, zoneID, firewallType, recordID) - if err != nil { - return err + firewallType, lockdownID, zoneID, crn, _ := convertTfToCisFourVar(rs.Primary.ID) + if firewallType == cisFirewallTypeLockdowns { + // Firewall Type : Lockdowns + cisClient, err := testAccProvider.Meta().(ClientSession).CisLockdownClientSession() + if err != nil { + return err + } + + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewGetLockdownOptions(lockdownID) + + result, response, err := cisClient.GetLockdown(opt) + if err != nil { + log.Printf("Get zone firewall lockdown failed: %v", response) + return err + } + tfRecord = convertCisToTfFourVar(firewallType, *result.Result.ID, zoneID, crn) + } else if firewallType == cisFirewallTypeAccessRules { + + // Firewall Type : Zone Access firewall rules + cisClient, err := testAccProvider.Meta().(ClientSession).CisAccessRuleClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewGetZoneAccessRuleOptions(lockdownID) + + result, response, err := cisClient.GetZoneAccessRule(opt) + if err != nil { + log.Printf("Get zone firewall lockdown failed: %v", response) + return err + } + tfRecord = convertCisToTfFourVar(firewallType, *result.Result.ID, zoneID, crn) + } else if firewallType == cisFirewallTypeUARules { + // Firewall Type: User Agent access rules + cisClient, err := testAccProvider.Meta().(ClientSession).CisUARuleClientSession() + if err != nil { + return err + } + cisClient.Crn = core.StringPtr(crn) + cisClient.ZoneIdentifier = core.StringPtr(zoneID) + + opt := cisClient.NewGetUserAgentRuleOptions(lockdownID) + result, response, err := cisClient.GetUserAgentRule(opt) + if err != nil { + log.Printf("Get zone user agent rule failed: %v", response) + return err + } + tfRecord = convertCisToTfFourVar(firewallType, *result.Result.ID, zoneID, crn) } - foundRecord := *foundRecordPtr - if foundRecord.ID != recordID { - return fmt.Errorf("Record not found") + if rs.Primary.ID != tfRecord { + return fmt.Errorf("Firewall lockdown not found") } - tfRecord = convertCisToTfFourVar(firewallType, foundRecord.ID, zoneID, cisID) + // tfRecord = convertCisToTfFourVar(firewallType, foundRecord.ID, zoneID, cisID) *tfRecordID = tfRecord return nil } } -func testAccCheckIBMCisFirewallConfigCisDS_Basic(name string) string { +func testAccCheckIBMCisFirewallLockdownBasic() string { return testAccCheckIBMCisDomainDataSourceConfigBasic1() + fmt.Sprintf(` - resource "ibm_cis_firewall" "lockdown" { + resource "ibm_cis_firewall" "lockdowns" { cis_id = data.ibm_cis.cis.id domain_id = data.ibm_cis_domain.cis_domain.id - firewall_type = "%s" - + firewall_type = "lockdowns" lockdown { paused = "false" urls = ["www.cis-terraform.com"] @@ -141,18 +334,15 @@ func testAccCheckIBMCisFirewallConfigCisDS_Basic(name string) string { value = "127.0.0.1" } } - } - - `, name) + }`) } -func testAccCheckIBMCisFirewallConfigCisDS_Update(name string) string { +func testAccCheckIBMCisFirewallLockdownUpdate() string { return testAccCheckIBMCisDomainDataSourceConfigBasic1() + fmt.Sprintf(` - resource "ibm_cis_firewall" "lockdown" { + resource "ibm_cis_firewall" "lockdowns" { cis_id = data.ibm_cis.cis.id domain_id = data.ibm_cis_domain.cis_domain.id - firewall_type = "%s" - + firewall_type = "lockdowns" lockdown { paused = "false" urls = ["www.cis-terraform.com"] @@ -161,6 +351,71 @@ func testAccCheckIBMCisFirewallConfigCisDS_Update(name string) string { value = "127.0.0.3" } } - } - `, name) + }`) +} + +func testAccCheckIBMCisFirewallAccessRuleBasic() string { + return testAccCheckIBMCisDomainDataSourceConfigBasic1() + fmt.Sprintf(` + resource "ibm_cis_firewall" "access_rules" { + cis_id = data.ibm_cis.cis.id + domain_id = data.ibm_cis_domain.cis_domain.id + firewall_type = "access_rules" + access_rule { + mode = "block" + notes = "access rule notes" + configuration { + target = "ip" + value = "192.168.1.3" + } + } + }`) +} + +func testAccCheckIBMCisFirewallAccessRuleUpdate() string { + return testAccCheckIBMCisDomainDataSourceConfigBasic1() + fmt.Sprintf(` + resource "ibm_cis_firewall" "access_rules" { + cis_id = data.ibm_cis.cis.id + domain_id = data.ibm_cis_domain.cis_domain.id + firewall_type = "access_rules" + access_rule { + mode = "block" + notes = "access rule notes update" + configuration { + target = "ip" + value = "192.168.1.3" + } + } + }`) +} + +func testAccCheckIBMCisFirewallUARuleBasic() string { + return testAccCheckIBMCisDomainDataSourceConfigBasic1() + fmt.Sprintf(` + resource "ibm_cis_firewall" "ua_rules" { + cis_id = data.ibm_cis.cis.id + domain_id = data.ibm_cis_domain.cis_domain.id + firewall_type = "ua_rules" + ua_rule { + mode = "block" + configuration { + target = "ua" + value = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4" + } + } + }`) +} + +func testAccCheckIBMCisFirewallUARuleUpdate() string { + return testAccCheckIBMCisDomainDataSourceConfigBasic1() + fmt.Sprintf(` + resource "ibm_cis_firewall" "ua_rules" { + cis_id = data.ibm_cis.cis.id + domain_id = data.ibm_cis_domain.cis_domain.id + firewall_type = "ua_rules" + ua_rule { + mode = "challenge" + configuration { + target = "ua" + value = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4" + } + } + }`) } diff --git a/website/docs/d/cis_firewall.html.markdown b/website/docs/d/cis_firewall.html.markdown index 5c5a07907b..7a39730975 100644 --- a/website/docs/d/cis_firewall.html.markdown +++ b/website/docs/d/cis_firewall.html.markdown @@ -1,54 +1,71 @@ --- layout: "ibm" page_title: "IBM: ibm_cis_firewall" -sidebar_current: "docs-ibm-cis-firewall" +sidebar_current: "docs-ibm-datasource-cis-firewall" description: |- - Get information on an IBM Cloud Internet Services Firewall. + Get information on an IBM Cloud Internet Services Firewall. --- -# ibm\_cis_firewall +# ibm_cis_firewall Imports a read only copy of an existing Internet Services Firewall resource. + ## Example Usage ```hcl -# Add a firewall to the domain - data "ibm_cis_firewall" "lockdown" { cis_id = ibm_cis.instance.id domain_id = ibm_cis_domain.example.id firewall_type = "lockdowns" } ``` + **NOTE:** IBM terraform provider supports only lockdowns rules ## Argument Reference The following arguments are supported: -* `cis_id` - (Required,string) The ID of the CIS service instance -* `domain_id` - (Required,string) The ID of the domain to add the Lockdown. -* `firewall_type` - (Required,string) The type of firewall. Allowable values are [`lockdowns`],[`access_rules`],[`ua_rules`]. +- `cis_id` - (Required,string) The ID of the CIS service instance +- `domain_id` - (Required,string) The ID of the domain to add the Lockdown. +- `firewall_type` - (Required,string) The type of firewall. Allowable values are [`lockdowns`],[`access_rules`],[`ua_rules`]. + +**NOTE:** -**NOTE:** 1. [`access_rules`]: Access Rules are a way to allow, challenge, or block requests to your website. You can apply access rules to one domain only or all domains in the same service instance. 2. [`ua_rules`]: Perform access control when matching the exact UserAgent reported by the client. The access control mechanisms can be defined within a rule to help manage traffic from particular clients. This will enable you to customize the access to your site. 3. [`lockdowns`]: Lock access to URLs in this domain to only permitted addresses or address ranges. - ## Attributes Reference The following attributes are exported: -* `id` - The record ID. It is a combination of <`firewall_type`>,<`lockdown_id`>,<`domain_id`>,<`cis_id`> attributes concatenated with ":". -* `lockdown` - List of lockdowns that are present in domain of CIS instance. It is the data describing a lockdowns rule. - * `lockdown_id` - The lockdown ID. - * `paused` - Whether this rule is currently disabled. - * `description` - Some useful information about this rule to help identify the purpose of it. - * `priority` - The priority of the record - * `urls` - URLs included in this rule definition. Wildcards are permitted. The URL pattern entered here is escaped before use. This limits the URL to just simple wildcard patterns. - * `configurations` - List of IP addresses or CIDR ranges to use for this rule. This can include any number of [`ip`] or [`ip_range`] configurations that can access the provided URLs. - * `target` -The request property to target. Valid values: [`ip`], [`ip_range`]. - * `value` - IP addresses or CIDR. If target is [`ip`], then value is an IP addresses, otherwise CIDR. - -**NOTE:** `lockdowns` is computed only if `firewall_type` argument is set to [`lockdowns`]. For `firewall_type` other than [`lockdowns`], `lockdowns` attribute is nil. +- `id` - The record ID. It is a combination of <`firewall_type`>,<`lockdown_id`>,<`domain_id`>,<`cis_id`> attributes concatenated with ":". +- `lockdown` - List of lockdown to be created. It is the data describing a lockdowns rule. + - `lockdown_id` - The lockdown ID. + - `paused` - Whether this rule is currently disabled. + - `description` - Some useful information about this rule to help identify the purpose of it. + - `priority` - The priority of the record. + - `urls` - URLs included in this rule definition. Wildcards are permitted. The URL pattern entered here is escaped before use. This limits the URL to just simple wildcard patterns. + - `configurations` - List of IP addresses or CIDR ranges to use for this rule. This can include any number of [`ip`] or [`ip_range`] configurations that can access the provided URLs. + - `target` - The request property to target. Valid values: [`ip`], [`ip_range`]. + - `value` - IP addresses or CIDR. +- `access_rule` - Access rule to be created. It is the data describing access rule. + - `access_rule_id` - The access rule ID. + - `notes` - Free text for notes. + - `mode` - The mode of access rule. The valid modes are [`block`], [`challenge`], [`whitelist`], [`js_challenge`]. + - `configuration` - The Configuration of firewall. + - `target` - The request property to target. Valid values: [`ip`], [`ip_range`], [`asn`], [`country`]. + - `value` - IP address or CIDR or Autonomous or Country code. +- `ua_rule` - User Agent rule to be created. It is the data describing user agent rule. + - `ua_rule_id` - The User Agent rule ID. + - `description` - Free text. + - `mode` - The mode of access rule. The valid modes are [`block`], [`challenge`], [`js_challenge`]. + - `paused` - Whether this rule is currently disabled. + - `configuration` - The Configuration of firewall. + - `target` - The request property to target. Valid value: [`ua`]. + - `value` - The exact User Agent string to match with this rule. + +**NOTE:** + +- Exactly one of [`lockdown`], [`access_rule`] and [`ua_rule`] will be set for respective firewall types [`lockdowns`], [`access_rules`], [`ua_rules`]. diff --git a/website/docs/r/cis_firewall.html.markdown b/website/docs/r/cis_firewall.html.markdown index a28761a59d..4f74b7ff13 100644 --- a/website/docs/r/cis_firewall.html.markdown +++ b/website/docs/r/cis_firewall.html.markdown @@ -1,7 +1,7 @@ --- layout: "ibm" page_title: "IBM: ibm_cis_firewall" -sidebar_current: "docs-ibm-cis-firewall" +sidebar_current: "docs-ibm-resource-cis-firewall" description: |- Provides a IBM CIS Firewall resource. --- @@ -30,58 +30,103 @@ resource "ibm_cis_firewall" "lockdown" { priority=1 } } + +resource "ibm_cis_firewall" "access_rules" { + cis_id = ibm_cis.instance.id + domain_id = ibm_cis_domain.example.id + firewall_type = "access_rules" + access_rule { + mode = "block" + notes = "access rule notes" + configuration { + target = "asn" + value = "AS12346" + } + } +} + +resource "ibm_cis_firewall" "ua_rules" { + cis_id = ibm_cis.instance.id + domain_id = ibm_cis_domain.example.id + firewall_type = "ua_rules" + ua_rule { + mode = "challenge" + configuration { + target = "ua" + value = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4" + } + } +} ``` -**NOTE:** IBM terraform provider supports only lockdowns rules ## Argument Reference The following arguments are supported: -* `cis_id` - (Required,string) The ID of the CIS service instance -* `domain_id` - (Required,string) The ID of the domain to add the Lockdown. -* `firewall_type` - (Required,string) The type of firewall. Allowable values are [`lockdowns`],[`access_rules`],[`ua_rules`]. +- `cis_id` - (Required,string) The ID of the CIS service instance +- `domain_id` - (Required,string) The ID of the domain to add the Lockdown. +- `firewall_type` - (Required,string) The type of firewall. Allowable values are [`lockdowns`],[`access_rules`],[`ua_rules`]. + +**NOTE:** -**NOTE:** 1. [`access_rules`]: Access Rules are a way to allow, challenge, or block requests to your website. You can apply access rules to one domain only or all domains in the same service instance. 2. [`ua_rules`]: Perform access control when matching the exact UserAgent reported by the client. The access control mechanisms can be defined within a rule to help manage traffic from particular clients. This will enable you to customize the access to your site. 3. [`lockdowns`]: Lock access to URLs in this domain to only permitted addresses or address ranges. -* `lockdown` - (Optional,list) (Maxitems: 1) List of lockdown to be created. It is the data describing a lockdowns rule. - * `paused` - (Optional,bool). Whether this rule is currently disabled. - * `description` - (Optional,string). Some useful information about this rule to help identify the purpose of it. - * `priority` - (Optional,int) The priority of the record - * `urls` - (Optional,list). URLs included in this rule definition. Wildcards are permitted. The URL pattern entered here is escaped before use. This limits the URL to just simple wildcard patterns. - * `configurations` - (Optional,list). List of IP addresses or CIDR ranges to use for this rule. This can include any number of [`ip`] or [`ip_range`] configurations that can access the provided URLs. - * `target` - (Optional,string). The request property to target. Valid values: [`ip`], [`ip_range`]. - * `value` - (Optional,string). IP addresses or CIDR. If target is [`ip`], then value is an IP addresses, otherwise CIDR. - -**NOTE:** `lockdowns` argument is a required parameter if `firewall_type` is [`lockdowns`]. To create a firewall-lockdown `paused`,`urls`,`configurations` are required arguments. For `firewall_type` other than [`lockdowns`], `lockdowns` argument shouldn't be passed in a payload +- `lockdown` - (Optional,list) (MinItems: 1) List of lockdown to be created. It is the data describing a lockdowns rule. + - `paused` - (Optional,boolean). Whether this rule is currently disabled. + - `description` - (Optional,string). Some useful information about this rule to help identify the purpose of it. + - `priority` - (Optional,int) The priority of the record. + - `urls` - (Optional,list). URLs included in this rule definition. Wildcards are permitted. The URL pattern entered here is escaped before use. This limits the URL to just simple wildcard patterns. + - `configurations` - (Optional,list). List of IP addresses or CIDR ranges to use for this rule. This can include any number of [`ip`] or [`ip_range`].configurations that can access the provided URLs. This can not be modified once it is created. + - `target` - (Optional,string). The request property to target. Valid values: [`ip`], [`ip_range`]. + - `value` - (Optional,string). IP addresses or CIDR. +- `access_rule` - (Optional) (MaxItem: 1) Access rule to be created. It is the data describing access rule. + - `notes` - (Optional, string) Free text for notes. + - `mode` - (Required, string) The mode of access rule. The valid modes are [`block`], [`challenge`], [`whitelist`], [`js_challenge`]. + - `configuration` - (Required, List) (MaxItems: 1) The Configuration of firewall. + - `target` - (Required, string) The request property to target. Valid values: [`ip`], [`ip_range`], [`asn`], [`country`]. + - `value` - (Required, string) IP address or CIDR or Autonomous or Country code. +- `ua_rule` - (Optional) (MaxItem: 1) User Agent rule to be created. It is the data describing user agent rule. + - `description` - (Optional, string) Free text. + - `mode` - (Required, string) The mode of access rule. The valid modes are [`block`], [`challenge`], [`js_challenge`]. + - `paused` - (Optional, boolean) Whether this rule is currently disabled. + - `configuration` - (Required, List) (MaxItems: 1) The Configuration of firewall. + - `target` - (Required, string) The request property to target. Valid values: [`ua`]. + - `value` - (Required, string) The exact User Agent string to match with this rule. + +**NOTE:** + +- Exactly one of [`lockdown`], [`access_rule`] and [`ua_rule`] is allowed to be given for input for respective firewall types [`lockdowns`], [`access_rules`], [`ua_rules`]. ## Attributes Reference The following attributes are exported: -* `id` - The record ID. It is a combination of <`firewall_type`>,<`lockdown_id`>,<`domain_id`>,<`cis_id`> attributes concatenated with ":". -* `lockdown_id` - The lockdown ID. - +- `id` - The firewall ID. It is a combination of <`firewall_type`>,<`lockdown_id/access_rul_id/ua_rule_id`>,<`domain_id`>,<`cis_id`> attributes concatenated with ":". +- `lockdown` + - `lockdown_id` - The lockdown ID. +- `access_rule` + - `access_rule_id` - The access rule ID. +- `ua_rule` + - `ua_rule_id` - The User Agent rule ID. ## Import -The `ibm_cis_firewall` resource can be imported using the `id`. The ID is formed from the `Firewall Type`,the `Firewall ID`, the `Domain ID` of the domain and the `CRN` (Cloud Resource Name) concatentated using a `:` character. - -The Domain ID and CRN will be located on the **Overview** page of the Internet Services instance under the **Domain** heading of the UI, or via using the `bx cis` CLI commands. +The `ibm_cis_firewall` resource can be imported using the `id`. The ID is formed from the `Firewall Type`,the `Firewall ID`, the `Domain ID` of the domain and the `CRN` (Cloud Resource Name) concatentated using a `:` character. -* **Domain ID** is a 32 digit character string of the form: `9caf68812ae9b3f0377fdf986751a78f` +The Domain ID and CRN will be located on the **Overview** page of the Internet Services instance under the **Domain** heading of the UI, or via using the `ibm cis` CLI commands. -* **CRN** is a 120 digit character string of the form: `crn:v1:bluemix:public:internet-svcs:global:a/4ea1882a2d3401ed1e459979941966ea:31fa970d-51d0-4b05-893e-251cba75a7b3::` +- **Domain ID** is a 32 digit character string of the form: `9caf68812ae9b3f0377fdf986751a78f` -* **Firewall ID** is a 32 digit character string of the form: `489d96f0da6ed76251b475971b097205c`. - -* **Firewall Type** is a string. It can be either of [`lockdowns`],[`access_rules`],[`ua_rules`]. +- **CRN** is a 120 digit character string of the form: `crn:v1:bluemix:public:internet-svcs:global:a/4ea1882a2d3401ed1e459979941966ea:31fa970d-51d0-4b05-893e-251cba75a7b3::` +- **Firewall ID** is a 32 digit character string of the form: `489d96f0da6ed76251b475971b097205c`. +- **Firewall Type** is a string. It can be either of [`lockdowns`],[`access_rules`],[`ua_rules`]. ``` $ terraform import ibm_cis_firewall.myorg ::: -$ terraform import ibm_cis_firewall.myorg lockdowns 48996f0da6ed76251b475971b097205c:9caf68812ae9b3f0377fdf986751a78f:crn:v1:bluemix:public:internet-svcs:global:a/4ea1882a2d3401ed1e459979941966ea:31fa970d-51d0-4b05-893e-251cba75a7b3:: \ No newline at end of file +$ terraform import ibm_cis_firewall.myorg lockdowns lockdowns:48996f0da6ed76251b475971b097205c:9caf68812ae9b3f0377fdf986751a78f:crn:v1:bluemix:public:internet-svcs:global:a/4ea1882a2d3401ed1e459979941966ea:31fa970d-51d0-4b05-893e-251cba75a7b3:: +```