-
Notifications
You must be signed in to change notification settings - Fork 16
/
resource_zpa_policy_access_rule.go
331 lines (303 loc) · 10.1 KB
/
resource_zpa_policy_access_rule.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package zpa
import (
"fmt"
"log"
"strconv"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
client "github.com/zscaler/zscaler-sdk-go/zpa"
"github.com/zscaler/zscaler-sdk-go/zpa/services/policysetcontroller"
)
func validateAccessPolicyRuleOrder(order string, zClient *Client) error {
policy, _, err := zClient.policysetcontroller.GetByNameAndType("ACCESS_POLICY", "Zscaler Deception")
if err != nil || policy == nil {
return nil
}
if order == "" {
return nil
}
o, err := strconv.Atoi(order)
if err != nil {
return nil
}
if o == 1 {
return fmt.Errorf("policy Zscaler Deception exists, order must start from 2")
}
return nil
}
func resourcePolicyAccessRule() *schema.Resource {
return &schema.Resource{
Create: resourcePolicyAccessCreate,
Read: resourcePolicyAccessRead,
Update: resourcePolicyAccessUpdate,
Delete: resourcePolicyAccessDelete,
Importer: &schema.ResourceImporter{
StateContext: importPolicyStateContextFunc([]string{"ACCESS_POLICY", "GLOBAL_POLICY"}),
},
Schema: MergeSchema(
CommonPolicySchema(), map[string]*schema.Schema{
"action": {
Type: schema.TypeString,
Optional: true,
Description: " This is for providing the rule action.",
ValidateFunc: validation.StringInSlice([]string{
"ALLOW",
"DENY",
}, false),
},
"app_server_groups": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Description: "List of the server group IDs.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
"app_connector_groups": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Description: "List of app-connector IDs.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
"conditions": GetPolicyConditionsSchema([]string{
"USER",
"USER_GROUP",
"APP",
"APP_GROUP",
"LOCATION",
"IDP",
"SAML",
"SCIM",
"SCIM_GROUP",
"CLIENT_TYPE",
"POSTURE",
"TRUSTED_NETWORK",
"BRANCH_CONNECTOR_GROUP",
"EDGE_CONNECTOR_GROUP",
"MACHINE_GRP",
"COUNTRY_CODE",
"PLATFORM",
}),
},
),
}
}
func resourcePolicyAccessCreate(d *schema.ResourceData, m interface{}) error {
zClient := m.(*Client)
req, err := expandCreatePolicyRule(d)
if err != nil {
return err
}
log.Printf("[INFO] Creating zpa policy rule with request\n%+v\n", req)
if err := validateAccessPolicyRuleOrder(req.RuleOrder, zClient); err != nil {
return err
}
if !ValidateConditions(req.Conditions, zClient) {
return fmt.Errorf("couldn't validate the zpa policy rule (%s) operands, please make sure you are using valid inputs for APP type, LHS & RHS", req.Name)
}
policysetcontroller, _, err := zClient.policysetcontroller.Create(req)
if err != nil {
return err
}
d.SetId(policysetcontroller.ID)
order, ok := d.GetOk("rule_order")
if ok {
reorder(order, policysetcontroller.PolicySetID, "ACCESS_POLICY", policysetcontroller.ID, zClient)
}
return resourcePolicyAccessRead(d, m)
}
func resourcePolicyAccessRead(d *schema.ResourceData, m interface{}) error {
zClient := m.(*Client)
globalPolicySet, _, err := zClient.policysetcontroller.GetByPolicyType("ACCESS_POLICY")
if err != nil {
return err
}
log.Printf("[INFO] Getting Policy Set Rule: globalPolicySet:%s id: %s\n", globalPolicySet.ID, d.Id())
resp, _, err := zClient.policysetcontroller.GetPolicyRule(globalPolicySet.ID, d.Id())
if err != nil {
if obj, ok := err.(*client.ErrorResponse); ok && obj.IsObjectNotFound() {
log.Printf("[WARN] Removing policy rule %s from state because it no longer exists in ZPA", d.Id())
d.SetId("")
return nil
}
return err
}
log.Printf("[INFO] Got Policy Set Rule:\n%+v\n", resp)
d.SetId(resp.ID)
_ = d.Set("description", resp.Description)
_ = d.Set("name", resp.Name)
_ = d.Set("action", resp.Action)
_ = d.Set("action_id", resp.ActionID)
_ = d.Set("custom_msg", resp.CustomMsg)
_ = d.Set("default_rule", resp.DefaultRule)
_ = d.Set("operator", resp.Operator)
_ = d.Set("policy_set_id", resp.PolicySetID)
_ = d.Set("policy_type", resp.PolicyType)
_ = d.Set("priority", resp.Priority)
_ = d.Set("rule_order", resp.RuleOrder)
_ = d.Set("lss_default_rule", resp.LSSDefaultRule)
_ = d.Set("conditions", flattenPolicyConditions(resp.Conditions))
_ = d.Set("app_server_groups", flattenPolicyRuleServerGroups(resp.AppServerGroups))
_ = d.Set("app_connector_groups", flattenPolicyRuleAppConnectorGroups(resp.AppConnectorGroups))
return nil
}
func resourcePolicyAccessUpdate(d *schema.ResourceData, m interface{}) error {
zClient := m.(*Client)
globalPolicySet, _, err := zClient.policysetcontroller.GetByPolicyType("ACCESS_POLICY")
if err != nil {
return err
}
ruleID := d.Id()
log.Printf("[INFO] Updating policy rule ID: %v\n", ruleID)
req, err := expandCreatePolicyRule(d)
if err != nil {
return err
}
if err := validateAccessPolicyRuleOrder(req.RuleOrder, zClient); err != nil {
return err
}
if !ValidateConditions(req.Conditions, zClient) {
return fmt.Errorf("couldn't validate the zpa policy rule (%s) operands, please make sure you are using valid inputs for APP type, LHS & RHS", req.Name)
}
if _, _, err := zClient.policysetcontroller.GetPolicyRule(globalPolicySet.ID, ruleID); err != nil {
if respErr, ok := err.(*client.ErrorResponse); ok && respErr.IsObjectNotFound() {
d.SetId("")
return nil
}
}
if _, err := zClient.policysetcontroller.Update(globalPolicySet.ID, ruleID, req); err != nil {
return err
}
if d.HasChange("rule_order") {
order, ok := d.GetOk("rule_order")
if ok {
reorder(order, globalPolicySet.ID, "ACCESS_POLICY", ruleID, zClient)
}
}
return resourcePolicyAccessRead(d, m)
}
func resourcePolicyAccessDelete(d *schema.ResourceData, m interface{}) error {
zClient := m.(*Client)
globalPolicySet, _, err := zClient.policysetcontroller.GetByPolicyType("ACCESS_POLICY")
if err != nil {
return err
}
log.Printf("[INFO] Deleting policy set rule with id %v\n", d.Id())
if _, err := zClient.policysetcontroller.Delete(globalPolicySet.ID, d.Id()); err != nil {
return err
}
return nil
}
func expandCreatePolicyRule(d *schema.ResourceData) (*policysetcontroller.PolicyRule, error) {
policySetID, ok := d.Get("policy_set_id").(string)
if !ok {
log.Printf("[ERROR] policy_set_id is not set\n")
return nil, fmt.Errorf("policy_set_id is not set")
}
log.Printf("[INFO] action_id:%v\n", d.Get("action_id"))
conditions, err := ExpandPolicyConditions(d)
if err != nil {
return nil, err
}
return &policysetcontroller.PolicyRule{
ID: d.Get("id").(string),
Name: d.Get("name").(string),
Description: d.Get("description").(string),
Action: d.Get("action").(string),
ActionID: d.Get("action_id").(string),
BypassDefaultRule: d.Get("bypass_default_rule").(bool),
CustomMsg: d.Get("custom_msg").(string),
DefaultRule: d.Get("default_rule").(bool),
Operator: d.Get("operator").(string),
PolicySetID: policySetID,
PolicyType: d.Get("policy_type").(string),
Priority: d.Get("priority").(string),
RuleOrder: d.Get("rule_order").(string),
LSSDefaultRule: d.Get("lss_default_rule").(bool),
Conditions: conditions,
AppServerGroups: expandPolicySetControllerAppServerGroups(d),
AppConnectorGroups: expandPolicysetControllerAppConnectorGroups(d),
}, nil
}
func expandPolicySetControllerAppServerGroups(d *schema.ResourceData) []policysetcontroller.AppServerGroups {
appServerGroupsInterface, ok := d.GetOk("app_server_groups")
if ok {
appServer := appServerGroupsInterface.(*schema.Set)
log.Printf("[INFO] app server groups data: %+v\n", appServer)
var appServerGroups []policysetcontroller.AppServerGroups
for _, appServerGroup := range appServer.List() {
appServerGroup, _ := appServerGroup.(map[string]interface{})
if appServerGroup != nil {
for _, id := range appServerGroup["id"].(*schema.Set).List() {
appServerGroups = append(appServerGroups, policysetcontroller.AppServerGroups{
ID: id.(string),
})
}
}
}
return appServerGroups
}
return []policysetcontroller.AppServerGroups{}
}
func expandPolicysetControllerAppConnectorGroups(d *schema.ResourceData) []policysetcontroller.AppConnectorGroups {
appConnectorGroupsInterface, ok := d.GetOk("app_connector_groups")
if ok {
appConnector := appConnectorGroupsInterface.(*schema.Set)
log.Printf("[INFO] app connector groups data: %+v\n", appConnector)
var appConnectorGroups []policysetcontroller.AppConnectorGroups
for _, appConnectorGroup := range appConnector.List() {
appConnectorGroup, _ := appConnectorGroup.(map[string]interface{})
if appConnectorGroup != nil {
for _, id := range appConnectorGroup["id"].(*schema.Set).List() {
appConnectorGroups = append(appConnectorGroups, policysetcontroller.AppConnectorGroups{
ID: id.(string),
})
}
}
}
return appConnectorGroups
}
return []policysetcontroller.AppConnectorGroups{}
}
func flattenPolicyRuleServerGroups(appServerGroup []policysetcontroller.AppServerGroups) []interface{} {
result := make([]interface{}, 1)
mapIds := make(map[string]interface{})
ids := make([]string, len(appServerGroup))
for i, serverGroup := range appServerGroup {
ids[i] = serverGroup.ID
}
mapIds["id"] = ids
result[0] = mapIds
return result
}
func flattenPolicyRuleAppConnectorGroups(appConnectorGroups []policysetcontroller.AppConnectorGroups) []interface{} {
result := make([]interface{}, 1)
mapIds := make(map[string]interface{})
ids := make([]string, len(appConnectorGroups))
for i, group := range appConnectorGroups {
ids[i] = group.ID
}
mapIds["id"] = ids
result[0] = mapIds
return result
}