From 149dc4e584c6a68c272eae01456fb03b0a18c376 Mon Sep 17 00:00:00 2001 From: graysonwu Date: Wed, 6 Dec 2023 09:33:44 -0800 Subject: [PATCH] Separate security policy and rule Signed-off-by: graysonwu --- api/api_list.yaml | 21 ++ api/infra/domains/security_policies/rule.go | 192 ++++++++++++++++ nsxt/policy_common.go | 50 ++-- nsxt/policy_utils.go | 15 ++ nsxt/provider.go | 2 + ...ce_nsxt_policy_intrusion_service_policy.go | 2 +- nsxt/resource_nsxt_policy_security_policy.go | 58 +---- ...rce_nsxt_policy_security_policy_no_rule.go | 149 ++++++++++++ ...source_nsxt_policy_security_policy_rule.go | 216 ++++++++++++++++++ 9 files changed, 634 insertions(+), 71 deletions(-) create mode 100644 api/infra/domains/security_policies/rule.go create mode 100644 nsxt/resource_nsxt_policy_security_policy_no_rule.go create mode 100644 nsxt/resource_nsxt_policy_security_policy_rule.go diff --git a/api/api_list.yaml b/api/api_list.yaml index ddfb2404c..5d6c6cdea 100644 --- a/api/api_list.yaml +++ b/api/api_list.yaml @@ -877,3 +877,24 @@ supported_method: - New - List +- api_packages: + - client: github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/domains/security_policies + model: github.com/vmware/vsphere-automation-sdk-go/services/nsxt/model + type: Local + - client: github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/domains/security_policies + model: github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/model + type: Global + - client: github.com/vmware/vsphere-automation-sdk-go/services/nsxt/orgs/projects/infra/domains/security_policies + model: github.com/vmware/vsphere-automation-sdk-go/services/nsxt/model + type: Multitenancy + model_name: Rule + obj_name: Rule + client_name: RulesClient + list_result_name: RuleListResult + supported_method: + - New + - Get + - Delete + - Patch + - Update + - List \ No newline at end of file diff --git a/api/infra/domains/security_policies/rule.go b/api/infra/domains/security_policies/rule.go new file mode 100644 index 000000000..214820ab1 --- /dev/null +++ b/api/infra/domains/security_policies/rule.go @@ -0,0 +1,192 @@ +//nolint:revive +package securitypolicies + +// The following file has been autogenerated. Please avoid any changes! +import ( + "errors" + + vapiProtocolClient_ "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" + client1 "github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/domains/security_policies" + model1 "github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/model" + client0 "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/domains/security_policies" + model0 "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/model" + client2 "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/orgs/projects/infra/domains/security_policies" + + utl "github.com/vmware/terraform-provider-nsxt/api/utl" +) + +type RuleClientContext utl.ClientContext + +func NewRulesClient(sessionContext utl.SessionContext, connector vapiProtocolClient_.Connector) *RuleClientContext { + var client interface{} + + switch sessionContext.ClientType { + + case utl.Local: + client = client0.NewRulesClient(connector) + + case utl.Global: + client = client1.NewRulesClient(connector) + + case utl.Multitenancy: + client = client2.NewRulesClient(connector) + + default: + return nil + } + return &RuleClientContext{Client: client, ClientType: sessionContext.ClientType, ProjectID: sessionContext.ProjectID} +} + +func (c RuleClientContext) Get(domainIdParam string, securityPolicyIdParam string, ruleIdParam string) (model0.Rule, error) { + var obj model0.Rule + var err error + + switch c.ClientType { + + case utl.Local: + client := c.Client.(client0.RulesClient) + obj, err = client.Get(domainIdParam, securityPolicyIdParam, ruleIdParam) + if err != nil { + return obj, err + } + + case utl.Global: + client := c.Client.(client1.RulesClient) + gmObj, err1 := client.Get(domainIdParam, securityPolicyIdParam, ruleIdParam) + if err1 != nil { + return obj, err1 + } + var rawObj interface{} + rawObj, err = utl.ConvertModelBindingType(gmObj, model1.RuleBindingType(), model0.RuleBindingType()) + obj = rawObj.(model0.Rule) + + case utl.Multitenancy: + client := c.Client.(client2.RulesClient) + obj, err = client.Get(utl.DefaultOrgID, c.ProjectID, domainIdParam, securityPolicyIdParam, ruleIdParam) + if err != nil { + return obj, err + } + + default: + return obj, errors.New("invalid infrastructure for model") + } + return obj, err +} + +func (c RuleClientContext) Delete(domainIdParam string, securityPolicyIdParam string, ruleIdParam string) error { + var err error + + switch c.ClientType { + + case utl.Local: + client := c.Client.(client0.RulesClient) + err = client.Delete(domainIdParam, securityPolicyIdParam, ruleIdParam) + + case utl.Global: + client := c.Client.(client1.RulesClient) + err = client.Delete(domainIdParam, securityPolicyIdParam, ruleIdParam) + + case utl.Multitenancy: + client := c.Client.(client2.RulesClient) + err = client.Delete(utl.DefaultOrgID, c.ProjectID, domainIdParam, securityPolicyIdParam, ruleIdParam) + + default: + err = errors.New("invalid infrastructure for model") + } + return err +} + +func (c RuleClientContext) Patch(domainIdParam string, securityPolicyIdParam string, ruleIdParam string, ruleParam model0.Rule) error { + var err error + + switch c.ClientType { + + case utl.Local: + client := c.Client.(client0.RulesClient) + err = client.Patch(domainIdParam, securityPolicyIdParam, ruleIdParam, ruleParam) + + case utl.Global: + client := c.Client.(client1.RulesClient) + gmObj, err1 := utl.ConvertModelBindingType(ruleParam, model0.RuleBindingType(), model1.RuleBindingType()) + if err1 != nil { + return err1 + } + err = client.Patch(domainIdParam, securityPolicyIdParam, ruleIdParam, gmObj.(model1.Rule)) + + case utl.Multitenancy: + client := c.Client.(client2.RulesClient) + err = client.Patch(utl.DefaultOrgID, c.ProjectID, domainIdParam, securityPolicyIdParam, ruleIdParam, ruleParam) + + default: + err = errors.New("invalid infrastructure for model") + } + return err +} + +func (c RuleClientContext) Update(domainIdParam string, securityPolicyIdParam string, ruleIdParam string, ruleParam model0.Rule) (model0.Rule, error) { + var err error + var obj model0.Rule + + switch c.ClientType { + + case utl.Local: + client := c.Client.(client0.RulesClient) + obj, err = client.Update(domainIdParam, securityPolicyIdParam, ruleIdParam, ruleParam) + + case utl.Global: + client := c.Client.(client1.RulesClient) + gmObj, err := utl.ConvertModelBindingType(ruleParam, model0.RuleBindingType(), model1.RuleBindingType()) + if err != nil { + return obj, err + } + gmObj, err = client.Update(domainIdParam, securityPolicyIdParam, ruleIdParam, gmObj.(model1.Rule)) + if err != nil { + return obj, err + } + obj1, err1 := utl.ConvertModelBindingType(gmObj, model1.RuleBindingType(), model0.RuleBindingType()) + if err1 != nil { + return obj, err1 + } + obj = obj1.(model0.Rule) + + case utl.Multitenancy: + client := c.Client.(client2.RulesClient) + obj, err = client.Update(utl.DefaultOrgID, c.ProjectID, domainIdParam, securityPolicyIdParam, ruleIdParam, ruleParam) + + default: + err = errors.New("invalid infrastructure for model") + } + return obj, err +} + +func (c RuleClientContext) List(domainIdParam string, securityPolicyIdParam string, cursorParam *string, includeMarkForDeleteObjectsParam *bool, includedFieldsParam *string, pageSizeParam *int64, sortAscendingParam *bool, sortByParam *string) (model0.RuleListResult, error) { + var err error + var obj model0.RuleListResult + + switch c.ClientType { + + case utl.Local: + client := c.Client.(client0.RulesClient) + obj, err = client.List(domainIdParam, securityPolicyIdParam, cursorParam, includeMarkForDeleteObjectsParam, includedFieldsParam, pageSizeParam, sortAscendingParam, sortByParam) + + case utl.Global: + client := c.Client.(client1.RulesClient) + gmObj, err := client.List(domainIdParam, securityPolicyIdParam, cursorParam, includeMarkForDeleteObjectsParam, includedFieldsParam, pageSizeParam, sortAscendingParam, sortByParam) + if err != nil { + return obj, err + } + obj1, err1 := utl.ConvertModelBindingType(gmObj, model1.RuleListResultBindingType(), model0.RuleListResultBindingType()) + if err1 != nil { + return obj, err1 + } + obj = obj1.(model0.RuleListResult) + + case utl.Multitenancy: + client := c.Client.(client2.RulesClient) + obj, err = client.List(utl.DefaultOrgID, c.ProjectID, domainIdParam, securityPolicyIdParam, cursorParam, includeMarkForDeleteObjectsParam, includedFieldsParam, pageSizeParam, sortAscendingParam, sortByParam) + + default: + err = errors.New("invalid infrastructure for model") + } + return obj, err +} diff --git a/nsxt/policy_common.go b/nsxt/policy_common.go index 169a2f506..22402f752 100644 --- a/nsxt/policy_common.go +++ b/nsxt/policy_common.go @@ -166,17 +166,23 @@ func getPolicyRuleActionSchema(isIds bool) *schema.Schema { } func getSecurityPolicyAndGatewayRulesSchema(scopeRequired bool, isIds bool, nsxIDReadOnly bool) *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Description: "List of rules in the section", + Optional: true, + MaxItems: 1000, + Elem: &schema.Resource{ + Schema: getSecurityPolicyAndGatewayRuleSchema(scopeRequired, isIds, nsxIDReadOnly, false), + }, + } +} + +func getSecurityPolicyAndGatewayRuleSchema(scopeRequired bool, isIds bool, nsxIDReadOnly bool, separated bool) map[string]*schema.Schema { ruleSchema := map[string]*schema.Schema{ "nsx_id": getFlexNsxIDSchema(nsxIDReadOnly), "display_name": getDisplayNameSchema(), "description": getDescriptionSchema(), "revision": getRevisionSchema(), - "sequence_number": { - Type: schema.TypeInt, - Description: "Sequence number of the this rule", - Optional: true, - Computed: true, - }, "destination_groups": { Type: schema.TypeSet, Description: "List of destination groups", @@ -282,19 +288,27 @@ func getSecurityPolicyAndGatewayRulesSchema(scopeRequired bool, isIds bool, nsxI if isIds { ruleSchema["ids_profiles"] = getIdsProfilesSchema() } - return &schema.Schema{ - Type: schema.TypeList, - Description: "List of rules in the section", - Optional: true, - MaxItems: 1000, - Elem: &schema.Resource{ - Schema: ruleSchema, - }, + if separated { + ruleSchema["policy_path"] = getPolicyPathSchema(true, false, "Security Policy path") + ruleSchema["sequence_number"] = &schema.Schema{ + Type: schema.TypeInt, + Description: "Sequence number of the this rule", + Required: true, + } + ruleSchema["context"] = getContextSchema() + } else { + ruleSchema["sequence_number"] = &schema.Schema{ + Type: schema.TypeInt, + Description: "Sequence number of the this rule", + Optional: true, + Computed: true, + } } + return ruleSchema } func getPolicyGatewayPolicySchema() map[string]*schema.Schema { - secPolicy := getPolicySecurityPolicySchema(false, true) + secPolicy := getPolicySecurityPolicySchema(false, true, true) // GW Policies don't support scope delete(secPolicy, "scope") secPolicy["category"].ValidateFunc = validation.StringInSlice(gatewayPolicyCategoryWritableValues, false) @@ -303,7 +317,7 @@ func getPolicyGatewayPolicySchema() map[string]*schema.Schema { return secPolicy } -func getPolicySecurityPolicySchema(isIds bool, withContext bool) map[string]*schema.Schema { +func getPolicySecurityPolicySchema(isIds, withContext, withRule bool) map[string]*schema.Schema { result := map[string]*schema.Schema{ "nsx_id": getNsxIDSchema(), "path": getPathSchema(), @@ -371,6 +385,10 @@ func getPolicySecurityPolicySchema(isIds bool, withContext bool) map[string]*sch if !withContext { delete(result, "context") } + + if !withRule { + delete(result, "rule") + } return result } diff --git a/nsxt/policy_utils.go b/nsxt/policy_utils.go index 59561cd95..9a729ef70 100644 --- a/nsxt/policy_utils.go +++ b/nsxt/policy_utils.go @@ -155,6 +155,21 @@ func setPathListInMap(data map[string]interface{}, attrName string, pathList []s } } +func getPathListFromSchema(d *schema.ResourceData, schemaAttrName string) []string { + pathList := interface2StringList(d.Get(schemaAttrName).(*schema.Set).List()) + if len(pathList) == 0 { + // Convert empty value to "ANY" + pathList = append(pathList, "ANY") + } + return pathList +} + +func setPathListInSchema(d *schema.ResourceData, attrName string, pathList []string) { + if !(len(pathList) == 1 && pathList[0] == "ANY") { + d.Set(attrName, pathList) + } +} + func getDomainFromResourcePath(rPath string) string { return getResourceIDFromResourcePath(rPath, "domains") } diff --git a/nsxt/provider.go b/nsxt/provider.go index 2200d860f..544ca28d1 100644 --- a/nsxt/provider.go +++ b/nsxt/provider.go @@ -437,6 +437,8 @@ func Provider() *schema.Provider { "nsxt_edge_high_availability_profile": resourceNsxtEdgeHighAvailabilityProfile(), "nsxt_policy_host_transport_node_collection": resourceNsxtPolicyHostTransportNodeCollection(), "nsxt_policy_lb_client_ssl_profile": resourceNsxtPolicyLBClientSslProfile(), + "nsxt_policy_security_policy_rule": resourceNsxtPolicySecurityPolicyRule(), + "nsxt_policy_security_policy_no_rule": resourceNsxtPolicySecurityPolicyNoRule(), }, ConfigureFunc: providerConfigure, diff --git a/nsxt/resource_nsxt_policy_intrusion_service_policy.go b/nsxt/resource_nsxt_policy_intrusion_service_policy.go index e37593620..e3b7ff895 100644 --- a/nsxt/resource_nsxt_policy_intrusion_service_policy.go +++ b/nsxt/resource_nsxt_policy_intrusion_service_policy.go @@ -29,7 +29,7 @@ func resourceNsxtPolicyIntrusionServicePolicy() *schema.Resource { Importer: &schema.ResourceImporter{ State: nsxtDomainResourceImporter, }, - Schema: getPolicySecurityPolicySchema(true, false), + Schema: getPolicySecurityPolicySchema(true, false, true), } } diff --git a/nsxt/resource_nsxt_policy_security_policy.go b/nsxt/resource_nsxt_policy_security_policy.go index 1ca398f6b..fc9df539f 100644 --- a/nsxt/resource_nsxt_policy_security_policy.go +++ b/nsxt/resource_nsxt_policy_security_policy.go @@ -24,7 +24,7 @@ func resourceNsxtPolicySecurityPolicy() *schema.Resource { Importer: &schema.ResourceImporter{ State: nsxtDomainResourceImporter, }, - Schema: getPolicySecurityPolicySchema(false, true), + Schema: getPolicySecurityPolicySchema(false, true, true), } } @@ -57,34 +57,9 @@ func resourceNsxtPolicySecurityPolicyExistsPartial(domainName string) func(sessi func policySecurityPolicyBuildAndPatch(d *schema.ResourceData, m interface{}, connector client.Connector, isGlobalManager bool, id string, createFlow bool) error { + obj := securityPolicySchemaToModelNoRule(d, id) domain := d.Get("domain").(string) - displayName := d.Get("display_name").(string) - description := d.Get("description").(string) - tags := getPolicyTagsFromSchema(d) - category := d.Get("category").(string) - comments := d.Get("comments").(string) - locked := d.Get("locked").(bool) - scope := getStringListFromSchemaSet(d, "scope") - sequenceNumber := int64(d.Get("sequence_number").(int)) - stateful := d.Get("stateful").(bool) - tcpStrict := d.Get("tcp_strict").(bool) revision := int64(d.Get("revision").(int)) - objType := "SecurityPolicy" - - obj := model.SecurityPolicy{ - Id: &id, - DisplayName: &displayName, - Description: &description, - Tags: tags, - Category: &category, - Comments: &comments, - Locked: &locked, - Scope: scope, - SequenceNumber: &sequenceNumber, - Stateful: &stateful, - TcpStrict: &tcpStrict, - ResourceType: &objType, - } log.Printf("[INFO] Creating Security Policy with ID %s", id) if createFlow { @@ -130,35 +105,10 @@ func resourceNsxtPolicySecurityPolicyCreate(d *schema.ResourceData, m interface{ } func resourceNsxtPolicySecurityPolicyRead(d *schema.ResourceData, m interface{}) error { - connector := getPolicyConnector(m) - id := d.Id() - domainName := d.Get("domain").(string) - if id == "" { - return fmt.Errorf("Error obtaining Security Policy id") - } - client := domains.NewSecurityPoliciesClient(getSessionContext(d, m), connector) - obj, err := client.Get(domainName, id) + obj, err := securityPolicyModelToSchemaNoRule(d, m) if err != nil { - return handleReadError(d, "SecurityPolicy", id, err) - } - d.Set("display_name", obj.DisplayName) - d.Set("description", obj.Description) - setPolicyTagsInSchema(d, obj.Tags) - d.Set("nsx_id", id) - d.Set("path", obj.Path) - d.Set("domain", getDomainFromResourcePath(*obj.Path)) - d.Set("category", obj.Category) - d.Set("comments", obj.Comments) - d.Set("locked", obj.Locked) - if len(obj.Scope) == 1 && obj.Scope[0] == "ANY" { - d.Set("scope", nil) - } else { - d.Set("scope", obj.Scope) + return err } - d.Set("sequence_number", obj.SequenceNumber) - d.Set("stateful", obj.Stateful) - d.Set("tcp_strict", obj.TcpStrict) - d.Set("revision", obj.Revision) return setPolicyRulesInSchema(d, obj.Rules) } diff --git a/nsxt/resource_nsxt_policy_security_policy_no_rule.go b/nsxt/resource_nsxt_policy_security_policy_no_rule.go new file mode 100644 index 000000000..f38e4636d --- /dev/null +++ b/nsxt/resource_nsxt_policy_security_policy_no_rule.go @@ -0,0 +1,149 @@ +/* Copyright © 2019 VMware, Inc. All Rights Reserved. + SPDX-License-Identifier: MPL-2.0 */ + +package nsxt + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/model" + + "github.com/vmware/terraform-provider-nsxt/api/infra/domains" +) + +func resourceNsxtPolicySecurityPolicyNoRule() *schema.Resource { + return &schema.Resource{ + Create: resourceNsxtPolicySecurityPolicyNoRuleCreate, + Read: resourceNsxtPolicySecurityPolicyNoRuleRead, + Update: resourceNsxtPolicySecurityPolicyNoRuleUpdate, + Delete: resourceNsxtPolicySecurityPolicyNoRuleDelete, + Importer: &schema.ResourceImporter{ + State: nsxtDomainResourceImporter, + }, + Schema: getPolicySecurityPolicySchema(false, true, false), + } +} + +func resourceNsxtPolicySecurityPolicyNoRuleCreate(d *schema.ResourceData, m interface{}) error { + connector := getPolicyConnector(m) + + // Initialize resource Id and verify this ID is not yet used + id, err := getOrGenerateID2(d, m, resourceNsxtPolicySecurityPolicyExistsPartial(d.Get("domain").(string))) + if err != nil { + return err + } + + log.Printf("[INFO] Creating Security Policy with ID %s", id) + domain := d.Get("domain").(string) + client := domains.NewSecurityPoliciesClient(getSessionContext(d, m), connector) + + obj := securityPolicySchemaToModelNoRule(d, id) + err = client.Patch(domain, id, obj) + if err != nil { + return handleCreateError("Security Policy", id, err) + } + + d.SetId(id) + d.Set("nsx_id", id) + + return resourceNsxtPolicySecurityPolicyNoRuleRead(d, m) +} + +func securityPolicySchemaToModelNoRule(d *schema.ResourceData, id string) model.SecurityPolicy { + displayName := d.Get("display_name").(string) + description := d.Get("description").(string) + tags := getPolicyTagsFromSchema(d) + category := d.Get("category").(string) + comments := d.Get("comments").(string) + locked := d.Get("locked").(bool) + scope := getStringListFromSchemaSet(d, "scope") + sequenceNumber := int64(d.Get("sequence_number").(int)) + stateful := d.Get("stateful").(bool) + tcpStrict := d.Get("tcp_strict").(bool) + objType := "SecurityPolicy" + + return model.SecurityPolicy{ + Id: &id, + DisplayName: &displayName, + Description: &description, + Tags: tags, + Category: &category, + Comments: &comments, + Locked: &locked, + Scope: scope, + SequenceNumber: &sequenceNumber, + Stateful: &stateful, + TcpStrict: &tcpStrict, + ResourceType: &objType, + } +} + +func resourceNsxtPolicySecurityPolicyNoRuleRead(d *schema.ResourceData, m interface{}) error { + _, err := securityPolicyModelToSchemaNoRule(d, m) + return err +} + +func securityPolicyModelToSchemaNoRule(d *schema.ResourceData, m interface{}) (*model.SecurityPolicy, error) { + connector := getPolicyConnector(m) + id := d.Id() + domainName := d.Get("domain").(string) + if id == "" { + return nil, fmt.Errorf("Error obtaining Security Policy id") + } + client := domains.NewSecurityPoliciesClient(getSessionContext(d, m), connector) + obj, err := client.Get(domainName, id) + if err != nil { + return nil, handleReadError(d, "SecurityPolicy", id, err) + } + d.Set("display_name", obj.DisplayName) + d.Set("description", obj.Description) + setPolicyTagsInSchema(d, obj.Tags) + d.Set("nsx_id", id) + d.Set("path", obj.Path) + d.Set("domain", getDomainFromResourcePath(*obj.Path)) + d.Set("category", obj.Category) + d.Set("comments", obj.Comments) + d.Set("locked", obj.Locked) + if len(obj.Scope) == 1 && obj.Scope[0] == "ANY" { + d.Set("scope", nil) + } else { + d.Set("scope", obj.Scope) + } + d.Set("sequence_number", obj.SequenceNumber) + d.Set("stateful", obj.Stateful) + d.Set("tcp_strict", obj.TcpStrict) + d.Set("revision", obj.Revision) + return &obj, nil +} + +func resourceNsxtPolicySecurityPolicyNoRuleUpdate(d *schema.ResourceData, m interface{}) error { + connector := getPolicyConnector(m) + + id := d.Id() + if id == "" { + return fmt.Errorf("Error obtaining Security Policy id") + } + + log.Printf("[INFO] Updating Security Policy with ID %s", id) + domain := d.Get("domain").(string) + client := domains.NewSecurityPoliciesClient(getSessionContext(d, m), connector) + remoteObj, err := client.Get(domain, id) + if err != nil { + return handleUpdateError("Security Policy", id, err) + } + + obj := securityPolicySchemaToModelNoRule(d, id) + obj.Rules = remoteObj.Rules + err = client.Patch(domain, id, obj) + if err != nil { + return handleUpdateError("Security Policy", id, err) + } + + return resourceNsxtPolicySecurityPolicyNoRuleRead(d, m) +} + +func resourceNsxtPolicySecurityPolicyNoRuleDelete(d *schema.ResourceData, m interface{}) error { + return resourceNsxtPolicySecurityPolicyDelete(d, m) +} diff --git a/nsxt/resource_nsxt_policy_security_policy_rule.go b/nsxt/resource_nsxt_policy_security_policy_rule.go new file mode 100644 index 000000000..09c81f839 --- /dev/null +++ b/nsxt/resource_nsxt_policy_security_policy_rule.go @@ -0,0 +1,216 @@ +/* Copyright © 2023 VMware, Inc. All Rights Reserved. +SPDX-License-Identifier: MPL-2.0 */ + +package nsxt + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" + "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/model" + + "github.com/vmware/terraform-provider-nsxt/api/infra/domains/security_policies" + utl "github.com/vmware/terraform-provider-nsxt/api/utl" +) + +func resourceNsxtPolicySecurityPolicyRule() *schema.Resource { + return &schema.Resource{ + Create: resourceNsxtPolicySecurityPolicyRuleCreate, + Read: resourceNsxtPolicySecurityPolicyRuleRead, + Update: resourceNsxtPolicySecurityPolicyRuleUpdate, + Delete: resourceNsxtPolicySecurityPolicyRuleDelete, + Importer: &schema.ResourceImporter{ + State: nsxtDomainResourceImporter, + }, + Schema: getSecurityPolicyAndGatewayRuleSchema(false, false, true, true), + } +} + +func resourceNsxtPolicySecurityPolicyRuleCreate(d *schema.ResourceData, m interface{}) error { + connector := getPolicyConnector(m) + + // Initialize resource Id and verify this ID is not yet used + id, err := getOrGenerateID2(d, m, resourceNsxtPolicySecurityPolicyRuleExistsPartial(d.Get("policy_path").(string))) + if err != nil { + return err + } + + policyPath := d.Get("policy_path").(string) + log.Printf("[INFO] Creating Security Policy Rule with ID %s under policy %s", id, policyPath) + domain := getDomainFromResourcePath(policyPath) + policyID := getPolicyIDFromPath(policyPath) + + client := securitypolicies.NewRulesClient(getSessionContext(d, m), connector) + rule := securityPolicyRuleSchemaToModel(d, id) + err = client.Patch(domain, policyID, id, rule) + if err != nil { + return handleCreateError("Security Policy Rule", id, err) + } + + d.SetId(id) + d.Set("nsx_id", id) + + return resourceNsxtPolicySecurityPolicyRuleRead(d, m) +} + +func securityPolicyRuleSchemaToModel(d *schema.ResourceData, id string) model.Rule { + displayName := d.Get("display_name").(string) + description := d.Get("description").(string) + action := d.Get("action").(string) + logged := d.Get("logged").(bool) + tag := d.Get("log_label").(string) + disabled := d.Get("disabled").(bool) + sourcesExcluded := d.Get("sources_excluded").(bool) + destinationsExcluded := d.Get("destinations_excluded").(bool) + + var ipProtocol *string + ipp := d.Get("ip_version").(string) + if ipp != "NONE" { + ipProtocol = &ipp + } + direction := d.Get("direction").(string) + notes := d.Get("notes").(string) + seq := d.Get("sequence_number").(int) + sequenceNumber := int64(seq) + tagStructs := getPolicyTagsFromSet(d.Get("tag").(*schema.Set)) + + resourceType := "Rule" + return model.Rule{ + ResourceType: &resourceType, + Id: &id, + DisplayName: &displayName, + Notes: ¬es, + Description: &description, + Action: &action, + Logged: &logged, + Tag: &tag, + Tags: tagStructs, + Disabled: &disabled, + SourcesExcluded: &sourcesExcluded, + DestinationsExcluded: &destinationsExcluded, + IpProtocol: ipProtocol, + Direction: &direction, + SourceGroups: getPathListFromSchema(d, "source_groups"), + DestinationGroups: getPathListFromSchema(d, "destination_groups"), + Services: getPathListFromSchema(d, "services"), + Scope: getPathListFromSchema(d, "scope"), + Profiles: getPathListFromSchema(d, "profiles"), + SequenceNumber: &sequenceNumber, + } +} + +func resourceNsxtPolicySecurityPolicyRuleExistsPartial(policyPath string) func(sessionContext utl.SessionContext, id string, connector client.Connector) (bool, error) { + return func(sessionContext utl.SessionContext, id string, connector client.Connector) (bool, error) { + return resourceNsxtPolicySecurityPolicyRuleExistsInDomain(sessionContext, id, policyPath, connector) + } +} + +func resourceNsxtPolicySecurityPolicyRuleExistsInDomain(sessionContext utl.SessionContext, id string, policyPath string, connector client.Connector) (bool, error) { + client := securitypolicies.NewRulesClient(sessionContext, connector) + + domain := getDomainFromResourcePath(policyPath) + policyID := getPolicyIDFromPath(policyPath) + _, err := client.Get(domain, policyID, id) + + if err == nil { + return true, nil + } + + if isNotFoundError(err) { + return false, nil + } + + return false, logAPIError("Error retrieving Security Policy Rule", err) +} + +func resourceNsxtPolicySecurityPolicyRuleRead(d *schema.ResourceData, m interface{}) error { + connector := getPolicyConnector(m) + id := d.Id() + if id == "" { + return fmt.Errorf("Error obtaining Security Policy Rule ID") + } + + policyPath := d.Get("policy_path").(string) + domain := getDomainFromResourcePath(policyPath) + policyID := getPolicyIDFromPath(policyPath) + + client := securitypolicies.NewRulesClient(getSessionContext(d, m), connector) + rule, err := client.Get(domain, policyID, id) + if err != nil { + return handleReadError(d, "SecurityPolicyRule", fmt.Sprintf("%s/%s", policyPath, id), err) + } + + securityPolicyRuleModelToSchema(d, rule) + return nil +} + +func securityPolicyRuleModelToSchema(d *schema.ResourceData, rule model.Rule) { + d.Set("display_name", rule.DisplayName) + d.Set("description", rule.Description) + d.Set("notes", rule.Notes) + d.Set("logged", rule.Logged) + d.Set("log_label", rule.Tag) + d.Set("action", rule.Action) + d.Set("destinations_excluded", rule.DestinationsExcluded) + d.Set("sources_excluded", rule.SourcesExcluded) + if rule.IpProtocol == nil { + d.Set("ip_version", "NONE") + } else { + d.Set("ip_version", rule.IpProtocol) + } + d.Set("direction", rule.Direction) + d.Set("disabled", rule.Disabled) + d.Set("revision", rule.Revision) + setPathListInSchema(d, "source_groups", rule.SourceGroups) + setPathListInSchema(d, "destination_groups", rule.DestinationGroups) + setPathListInSchema(d, "profiles", rule.Profiles) + setPathListInSchema(d, "services", rule.Services) + setPathListInSchema(d, "scope", rule.Scope) + d.Set("sequence_number", rule.SequenceNumber) + d.Set("nsx_id", rule.Id) + d.Set("rule_id", rule.RuleId) + + setPolicyTagsInSchema(d, rule.Tags) +} + +func resourceNsxtPolicySecurityPolicyRuleUpdate(d *schema.ResourceData, m interface{}) error { + connector := getPolicyConnector(m) + + id := d.Id() + if id == "" { + return fmt.Errorf("Error obtaining Security Policy Rule ID") + } + + policyPath := d.Get("policy_path").(string) + log.Printf("[INFO] Updating Security Policy Rule with ID %s under policy %s", id, policyPath) + domain := getDomainFromResourcePath(policyPath) + policyID := getPolicyIDFromPath(policyPath) + + client := securitypolicies.NewRulesClient(getSessionContext(d, m), connector) + rule := securityPolicyRuleSchemaToModel(d, id) + err := client.Patch(domain, policyID, id, rule) + if err != nil { + return handleUpdateError("Security Policy Rule", id, err) + } + + return resourceNsxtPolicySecurityPolicyRuleRead(d, m) +} + +func resourceNsxtPolicySecurityPolicyRuleDelete(d *schema.ResourceData, m interface{}) error { + id := d.Get("nsx_id").(string) + if id == "" { + return fmt.Errorf("Error obtaining Security Policy Rule ID") + } + + connector := getPolicyConnector(m) + + policyPath := d.Get("policy_path").(string) + log.Printf("[INFO] Deleting Security Policy Rule with ID %s under policy %s", id, policyPath) + domain := getDomainFromResourcePath(policyPath) + policyID := getPolicyIDFromPath(policyPath) + + client := securitypolicies.NewRulesClient(getSessionContext(d, m), connector) + return client.Delete(domain, policyID, id) +}