-
Notifications
You must be signed in to change notification settings - Fork 264
/
Copy pathresource_compute_security_policy.go
875 lines (742 loc) · 30 KB
/
resource_compute_security_policy.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
package google
import (
"context"
"fmt"
"log"
"time"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
compute "google.golang.org/api/compute/v0.beta"
)
func resourceComputeSecurityPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceComputeSecurityPolicyCreate,
Read: resourceComputeSecurityPolicyRead,
Update: resourceComputeSecurityPolicyUpdate,
Delete: resourceComputeSecurityPolicyDelete,
Importer: &schema.ResourceImporter{
State: resourceSecurityPolicyStateImporter,
},
CustomizeDiff: rulesCustomizeDiff,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(4 * time.Minute),
Update: schema.DefaultTimeout(4 * time.Minute),
Delete: schema.DefaultTimeout(4 * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateGCPName,
Description: `The name of the security policy.`,
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: `An optional description of this security policy. Max size is 2048.`,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `The project in which the resource belongs. If it is not provided, the provider project is used.`,
},
"type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: `The type indicates the intended use of the security policy. CLOUD_ARMOR - Cloud Armor backend security policies can be configured to filter incoming HTTP requests targeting backend services. They filter requests before they hit the origin servers. CLOUD_ARMOR_EDGE - Cloud Armor edge security policies can be configured to filter incoming HTTP requests targeting backend services (including Cloud CDN-enabled) as well as backend buckets (Cloud Storage). They filter requests before the request is served from Google's cache.`,
},
"rule": {
Type: schema.TypeSet,
Optional: true,
Computed: true, // If no rules are set, a default rule is added
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"action": {
Type: schema.TypeString,
Required: true,
Description: `Action to take when match matches the request.`,
},
"priority": {
Type: schema.TypeInt,
Required: true,
Description: `An unique positive integer indicating the priority of evaluation for a rule. Rules are evaluated from highest priority (lowest numerically) to lowest priority (highest numerically) in order.`,
},
"match": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"src_ip_ranges": {
Type: schema.TypeSet,
Required: true,
MinItems: 1,
MaxItems: 10,
Elem: &schema.Schema{Type: schema.TypeString},
Description: `Set of IP addresses or ranges (IPV4 or IPV6) in CIDR notation to match against inbound traffic. There is a limit of 10 IP ranges per rule. A value of '*' matches all IPs (can be used to override the default behavior).`,
},
},
},
Description: `The configuration options available when specifying versioned_expr. This field must be specified if versioned_expr is specified and cannot be specified if versioned_expr is not specified.`,
},
"versioned_expr": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"SRC_IPS_V1"}, false),
Description: `Predefined rule expression. If this field is specified, config must also be specified. Available options: SRC_IPS_V1: Must specify the corresponding src_ip_ranges field in config.`,
},
"expr": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"expression": {
Type: schema.TypeString,
Required: true,
Description: `Textual representation of an expression in Common Expression Language syntax. The application context of the containing message determines which well-known feature set of CEL is supported.`,
},
// These fields are not yet supported (Issue hashicorp/terraform-provider-google#4497: mbang)
// "title": {
// Type: schema.TypeString,
// Optional: true,
// },
// "description": {
// Type: schema.TypeString,
// Optional: true,
// },
// "location": {
// Type: schema.TypeString,
// Optional: true,
// },
},
},
Description: `User defined CEVAL expression. A CEVAL expression is used to specify match criteria such as origin.ip, source.region_code and contents in the request header.`,
},
},
},
Description: `A match condition that incoming traffic is evaluated against. If it evaluates to true, the corresponding action is enforced.`,
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: `An optional description of this rule. Max size is 64.`,
},
"preview": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
Description: `When set to true, the action specified above is not enforced. Stackdriver logs for requests that trigger a preview action are annotated as such.`,
},
"rate_limit_options": {
Type: schema.TypeList,
Optional: true,
Description: `Rate limit threshold for this security policy. Must be specified if the action is "rate_based_ban" or "throttle". Cannot be specified for any other actions.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"rate_limit_threshold": {
Type: schema.TypeList,
Required: true,
Description: `Threshold at which to begin ratelimiting.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"count": {
Type: schema.TypeInt,
Required: true,
Description: `Number of HTTP(S) requests for calculating the threshold.`,
},
"interval_sec": {
Type: schema.TypeInt,
Required: true,
Description: `Interval over which the threshold is computed.`,
},
},
},
},
"conform_action": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"allow"}, false),
Description: `Action to take for requests that are under the configured rate limit threshold. Valid option is "allow" only.`,
},
"exceed_action": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"redirect", "deny(403)", "deny(404)", "deny(429)", "deny(502)"}, false),
Description: `Action to take for requests that are above the configured rate limit threshold, to either deny with a specified HTTP response code, or redirect to a different endpoint. Valid options are "deny()" where valid values for status are 403, 404, 429, and 502, and "redirect" where the redirect parameters come from exceedRedirectOptions below.`,
},
"enforce_on_key": {
Type: schema.TypeString,
Optional: true,
Default: "ALL",
Description: `Determines the key to enforce the rateLimitThreshold on`,
},
"enforce_on_key_name": {
Type: schema.TypeString,
Optional: true,
Description: `Rate limit key name applicable only for the following key types: HTTP_HEADER -- Name of the HTTP header whose value is taken as the key value. HTTP_COOKIE -- Name of the HTTP cookie whose value is taken as the key value.`,
},
"ban_threshold": {
Type: schema.TypeList,
Optional: true,
Description: `Can only be specified if the action for the rule is "rate_based_ban". If specified, the key will be banned for the configured 'banDurationSec' when the number of requests that exceed the 'rateLimitThreshold' also exceed this 'banThreshold'.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"count": {
Type: schema.TypeInt,
Required: true,
Description: `Number of HTTP(S) requests for calculating the threshold.`,
},
"interval_sec": {
Type: schema.TypeInt,
Required: true,
Description: `Interval over which the threshold is computed.`,
},
},
},
},
"ban_duration_sec": {
Type: schema.TypeInt,
Optional: true,
Description: `Can only be specified if the action for the rule is "rate_based_ban". If specified, determines the time (in seconds) the traffic will continue to be banned by the rate limit after the rate falls below the threshold.`,
},
"exceed_redirect_options": {
Type: schema.TypeList,
Optional: true,
Description: `Parameters defining the redirect action that is used as the exceed action. Cannot be specified if the exceed action is not redirect.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
Description: `Type of the redirect action.`,
ValidateFunc: validation.StringInSlice([]string{"EXTERNAL_302", "GOOGLE_RECAPTCHA"}, false),
},
"target": {
Type: schema.TypeString,
Optional: true,
Description: `Target for the redirect action. This is required if the type is EXTERNAL_302 and cannot be specified for GOOGLE_RECAPTCHA.`,
},
},
},
},
},
},
},
"redirect_options": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"EXTERNAL_302", "GOOGLE_RECAPTCHA"}, false),
Description: `Type of the redirect action. Available options: EXTERNAL_302: Must specify the corresponding target field in config. GOOGLE_RECAPTCHA: Cannot specify target field in config.`,
},
"target": {
Type: schema.TypeString,
Optional: true,
Description: `Target for the redirect action. This is required if the type is EXTERNAL_302 and cannot be specified for GOOGLE_RECAPTCHA.`,
},
},
},
Description: `Parameters defining the redirect action. Cannot be specified for any other actions.`,
},
},
},
Description: `The set of rules that belong to this policy. There must always be a default rule (rule with priority 2147483647 and match "*"). If no rules are provided when creating a security policy, a default rule with action "allow" will be added.`,
},
"fingerprint": {
Type: schema.TypeString,
Computed: true,
Description: `Fingerprint of this resource.`,
},
"self_link": {
Type: schema.TypeString,
Computed: true,
Description: `The URI of the created resource.`,
},
"adaptive_protection_config": {
Type: schema.TypeList,
Optional: true,
Description: `Adaptive Protection Config of this security policy.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"layer_7_ddos_defense_config": {
Type: schema.TypeList,
Description: `Layer 7 DDoS Defense Config of this security policy`,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enable": {
Type: schema.TypeBool,
Optional: true,
Description: `If set to true, enables CAAP for L7 DDoS detection.`,
},
"rule_visibility": {
Type: schema.TypeString,
Optional: true,
Default: "STANDARD",
ValidateFunc: validation.StringInSlice([]string{"STANDARD", "PREMIUM"}, false),
Description: `Rule visibility. Supported values include: "STANDARD", "PREMIUM".`,
},
},
},
},
},
},
},
},
UseJSONNumber: true,
}
}
func rulesCustomizeDiff(_ context.Context, diff *schema.ResourceDiff, _ interface{}) error {
_, n := diff.GetChange("rule")
nSet := n.(*schema.Set)
nPriorities := map[int64]bool{}
for _, rule := range nSet.List() {
priority := int64(rule.(map[string]interface{})["priority"].(int))
if nPriorities[priority] {
return fmt.Errorf("Two rules have the same priority, please update one of the priorities to be different.")
}
nPriorities[priority] = true
}
return nil
}
func resourceComputeSecurityPolicyCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
project, err := getProject(d, config)
if err != nil {
return err
}
sp := d.Get("name").(string)
securityPolicy := &compute.SecurityPolicy{
Name: sp,
Description: d.Get("description").(string),
}
if v, ok := d.GetOk("type"); ok {
securityPolicy.Type = v.(string)
}
if v, ok := d.GetOk("rule"); ok {
securityPolicy.Rules = expandSecurityPolicyRules(v.(*schema.Set).List())
}
if v, ok := d.GetOk("adaptive_protection_config"); ok {
securityPolicy.AdaptiveProtectionConfig = expandSecurityPolicyAdaptiveProtectionConfig(v.([]interface{}))
}
log.Printf("[DEBUG] SecurityPolicy insert request: %#v", securityPolicy)
client := config.NewComputeClient(userAgent)
op, err := client.SecurityPolicies.Insert(project, securityPolicy).Do()
if err != nil {
return errwrap.Wrapf("Error creating SecurityPolicy: {{err}}", err)
}
id, err := replaceVars(d, config, "projects/{{project}}/global/securityPolicies/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
err = computeOperationWaitTime(config, op, project, fmt.Sprintf("Creating SecurityPolicy %q", sp), userAgent, d.Timeout(schema.TimeoutCreate))
if err != nil {
return err
}
return resourceComputeSecurityPolicyRead(d, meta)
}
func resourceComputeSecurityPolicyRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
project, err := getProject(d, config)
if err != nil {
return err
}
sp := d.Get("name").(string)
client := config.NewComputeClient(userAgent)
securityPolicy, err := client.SecurityPolicies.Get(project, sp).Do()
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("SecurityPolicy %q", d.Id()))
}
if err := d.Set("name", securityPolicy.Name); err != nil {
return fmt.Errorf("Error setting name: %s", err)
}
if err := d.Set("description", securityPolicy.Description); err != nil {
return fmt.Errorf("Error setting description: %s", err)
}
if err := d.Set("type", securityPolicy.Type); err != nil {
return fmt.Errorf("Error setting type: %s", err)
}
if err := d.Set("rule", flattenSecurityPolicyRules(securityPolicy.Rules)); err != nil {
return err
}
if err := d.Set("fingerprint", securityPolicy.Fingerprint); err != nil {
return fmt.Errorf("Error setting fingerprint: %s", err)
}
if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error setting project: %s", err)
}
if err := d.Set("self_link", ConvertSelfLinkToV1(securityPolicy.SelfLink)); err != nil {
return fmt.Errorf("Error setting self_link: %s", err)
}
if err := d.Set("adaptive_protection_config", flattenSecurityPolicyAdaptiveProtectionConfig(securityPolicy.AdaptiveProtectionConfig)); err != nil {
return fmt.Errorf("Error setting adaptive_protection_config: %s", err)
}
return nil
}
func resourceComputeSecurityPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
project, err := getProject(d, config)
if err != nil {
return err
}
sp := d.Get("name").(string)
securityPolicy := &compute.SecurityPolicy{
Fingerprint: d.Get("fingerprint").(string),
}
if d.HasChange("type") {
securityPolicy.Type = d.Get("type").(string)
securityPolicy.ForceSendFields = append(securityPolicy.ForceSendFields, "Type")
}
if d.HasChange("description") {
securityPolicy.Description = d.Get("description").(string)
securityPolicy.ForceSendFields = append(securityPolicy.ForceSendFields, "Description")
}
if len(securityPolicy.ForceSendFields) > 0 {
client := config.NewComputeClient(userAgent)
op, err := client.SecurityPolicies.Patch(project, sp, securityPolicy).Do()
if err != nil {
return errwrap.Wrapf(fmt.Sprintf("Error updating SecurityPolicy %q: {{err}}", sp), err)
}
err = computeOperationWaitTime(config, op, project, fmt.Sprintf("Updating SecurityPolicy %q", sp), userAgent, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
}
if d.HasChange("rule") {
o, n := d.GetChange("rule")
oSet := o.(*schema.Set)
nSet := n.(*schema.Set)
oPriorities := map[int64]bool{}
nPriorities := map[int64]bool{}
for _, rule := range oSet.List() {
oPriorities[int64(rule.(map[string]interface{})["priority"].(int))] = true
}
for _, rule := range nSet.List() {
priority := int64(rule.(map[string]interface{})["priority"].(int))
nPriorities[priority] = true
if !oPriorities[priority] {
client := config.NewComputeClient(userAgent)
// If the rule is in new and its priority does not exist in old, then add it.
op, err := client.SecurityPolicies.AddRule(project, sp, expandSecurityPolicyRule(rule)).Do()
if err != nil {
return errwrap.Wrapf(fmt.Sprintf("Error updating SecurityPolicy %q: {{err}}", sp), err)
}
err = computeOperationWaitTime(config, op, project, fmt.Sprintf("Updating SecurityPolicy %q", sp), userAgent, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
} else if !oSet.Contains(rule) {
client := config.NewComputeClient(userAgent)
// If the rule is in new, and its priority is in old, but its hash is different than the one in old, update it.
op, err := client.SecurityPolicies.PatchRule(project, sp, expandSecurityPolicyRule(rule)).Priority(priority).Do()
if err != nil {
return errwrap.Wrapf(fmt.Sprintf("Error updating SecurityPolicy %q: {{err}}", sp), err)
}
err = computeOperationWaitTime(config, op, project, fmt.Sprintf("Updating SecurityPolicy %q", sp), userAgent, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
}
}
for _, rule := range oSet.List() {
priority := int64(rule.(map[string]interface{})["priority"].(int))
if !nPriorities[priority] {
client := config.NewComputeClient(userAgent)
// If the rule's priority is in old but not new, remove it.
op, err := client.SecurityPolicies.RemoveRule(project, sp).Priority(priority).Do()
if err != nil {
return errwrap.Wrapf(fmt.Sprintf("Error updating SecurityPolicy %q: {{err}}", sp), err)
}
err = computeOperationWaitTime(config, op, project, fmt.Sprintf("Updating SecurityPolicy %q", sp), userAgent, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
}
}
}
return resourceComputeSecurityPolicyRead(d, meta)
}
func resourceComputeSecurityPolicyDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
project, err := getProject(d, config)
if err != nil {
return err
}
client := config.NewComputeClient(userAgent)
// Delete the SecurityPolicy
op, err := client.SecurityPolicies.Delete(project, d.Get("name").(string)).Do()
if err != nil {
return errwrap.Wrapf("Error deleting SecurityPolicy: {{err}}", err)
}
err = computeOperationWaitTime(config, op, project, "Deleting SecurityPolicy", userAgent, d.Timeout(schema.TimeoutDelete))
if err != nil {
return err
}
d.SetId("")
return nil
}
func expandSecurityPolicyRules(configured []interface{}) []*compute.SecurityPolicyRule {
rules := make([]*compute.SecurityPolicyRule, 0, len(configured))
for _, raw := range configured {
rules = append(rules, expandSecurityPolicyRule(raw))
}
return rules
}
func expandSecurityPolicyRule(raw interface{}) *compute.SecurityPolicyRule {
data := raw.(map[string]interface{})
return &compute.SecurityPolicyRule{
Description: data["description"].(string),
Priority: int64(data["priority"].(int)),
Action: data["action"].(string),
Preview: data["preview"].(bool),
Match: expandSecurityPolicyMatch(data["match"].([]interface{})),
RateLimitOptions: expandSecurityPolicyRuleRateLimitOptions(data["rate_limit_options"].([]interface{})),
RedirectOptions: expandSecurityPolicyRuleRedirectOptions(data["redirect_options"].([]interface{})),
ForceSendFields: []string{"Description", "Preview"},
}
}
func expandSecurityPolicyMatch(configured []interface{}) *compute.SecurityPolicyRuleMatcher {
if len(configured) == 0 || configured[0] == nil {
return nil
}
data := configured[0].(map[string]interface{})
return &compute.SecurityPolicyRuleMatcher{
VersionedExpr: data["versioned_expr"].(string),
Config: expandSecurityPolicyMatchConfig(data["config"].([]interface{})),
Expr: expandSecurityPolicyMatchExpr(data["expr"].([]interface{})),
}
}
func expandSecurityPolicyMatchConfig(configured []interface{}) *compute.SecurityPolicyRuleMatcherConfig {
if len(configured) == 0 || configured[0] == nil {
return nil
}
data := configured[0].(map[string]interface{})
return &compute.SecurityPolicyRuleMatcherConfig{
SrcIpRanges: convertStringArr(data["src_ip_ranges"].(*schema.Set).List()),
}
}
func expandSecurityPolicyMatchExpr(expr []interface{}) *compute.Expr {
if len(expr) == 0 || expr[0] == nil {
return nil
}
data := expr[0].(map[string]interface{})
return &compute.Expr{
Expression: data["expression"].(string),
// These fields are not yet supported (Issue hashicorp/terraform-provider-google#4497: mbang)
// Title: data["title"].(string),
// Description: data["description"].(string),
// Location: data["location"].(string),
}
}
func flattenSecurityPolicyRules(rules []*compute.SecurityPolicyRule) []map[string]interface{} {
rulesSchema := make([]map[string]interface{}, 0, len(rules))
for _, rule := range rules {
data := map[string]interface{}{
"description": rule.Description,
"priority": rule.Priority,
"action": rule.Action,
"preview": rule.Preview,
"match": flattenMatch(rule.Match),
"rate_limit_options": flattenSecurityPolicyRuleRateLimitOptions(rule.RateLimitOptions),
"redirect_options": flattenSecurityPolicyRedirectOptions(rule.RedirectOptions),
}
rulesSchema = append(rulesSchema, data)
}
return rulesSchema
}
func flattenMatch(match *compute.SecurityPolicyRuleMatcher) []map[string]interface{} {
if match == nil {
return nil
}
data := map[string]interface{}{
"versioned_expr": match.VersionedExpr,
"config": flattenMatchConfig(match.Config),
"expr": flattenMatchExpr(match),
}
return []map[string]interface{}{data}
}
func flattenMatchConfig(conf *compute.SecurityPolicyRuleMatcherConfig) []map[string]interface{} {
if conf == nil {
return nil
}
data := map[string]interface{}{
"src_ip_ranges": schema.NewSet(schema.HashString, convertStringArrToInterface(conf.SrcIpRanges)),
}
return []map[string]interface{}{data}
}
func flattenMatchExpr(match *compute.SecurityPolicyRuleMatcher) []map[string]interface{} {
if match.Expr == nil {
return nil
}
data := map[string]interface{}{
"expression": match.Expr.Expression,
// These fields are not yet supported (Issue hashicorp/terraform-provider-google#4497: mbang)
// "title": match.Expr.Title,
// "description": match.Expr.Description,
// "location": match.Expr.Location,
}
return []map[string]interface{}{data}
}
func expandSecurityPolicyAdaptiveProtectionConfig(configured []interface{}) *compute.SecurityPolicyAdaptiveProtectionConfig {
if len(configured) == 0 || configured[0] == nil {
return nil
}
data := configured[0].(map[string]interface{})
return &compute.SecurityPolicyAdaptiveProtectionConfig{
Layer7DdosDefenseConfig: expandLayer7DdosDefenseConfig(data["layer_7_ddos_defense_config"].([]interface{})),
}
}
func expandLayer7DdosDefenseConfig(configured []interface{}) *compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig {
if len(configured) == 0 || configured[0] == nil {
return nil
}
data := configured[0].(map[string]interface{})
return &compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig{
Enable: data["enable"].(bool),
RuleVisibility: data["rule_visibility"].(string),
}
}
func flattenSecurityPolicyAdaptiveProtectionConfig(conf *compute.SecurityPolicyAdaptiveProtectionConfig) []map[string]interface{} {
if conf == nil {
return nil
}
data := map[string]interface{}{
"layer_7_ddos_defense_config": flattenLayer7DdosDefenseConfig(conf.Layer7DdosDefenseConfig),
}
return []map[string]interface{}{data}
}
func flattenLayer7DdosDefenseConfig(conf *compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig) []map[string]interface{} {
if conf == nil {
return nil
}
data := map[string]interface{}{
"enable": conf.Enable,
"rule_visibility": conf.RuleVisibility,
}
return []map[string]interface{}{data}
}
func expandSecurityPolicyRuleRateLimitOptions(configured []interface{}) *compute.SecurityPolicyRuleRateLimitOptions {
if len(configured) == 0 || configured[0] == nil {
return nil
}
data := configured[0].(map[string]interface{})
return &compute.SecurityPolicyRuleRateLimitOptions{
BanThreshold: expandThreshold(data["ban_threshold"].([]interface{})),
RateLimitThreshold: expandThreshold(data["rate_limit_threshold"].([]interface{})),
ExceedAction: data["exceed_action"].(string),
ConformAction: data["conform_action"].(string),
EnforceOnKey: data["enforce_on_key"].(string),
EnforceOnKeyName: data["enforce_on_key_name"].(string),
BanDurationSec: int64(data["ban_duration_sec"].(int)),
ExceedRedirectOptions: expandSecurityPolicyRuleRedirectOptions(data["exceed_redirect_options"].([]interface{})),
}
}
func expandThreshold(configured []interface{}) *compute.SecurityPolicyRuleRateLimitOptionsThreshold {
if len(configured) == 0 || configured[0] == nil {
return nil
}
data := configured[0].(map[string]interface{})
return &compute.SecurityPolicyRuleRateLimitOptionsThreshold{
Count: int64(data["count"].(int)),
IntervalSec: int64(data["interval_sec"].(int)),
}
}
func flattenSecurityPolicyRuleRateLimitOptions(conf *compute.SecurityPolicyRuleRateLimitOptions) []map[string]interface{} {
if conf == nil {
return nil
}
data := map[string]interface{}{
"ban_threshold": flattenThreshold(conf.BanThreshold),
"rate_limit_threshold": flattenThreshold(conf.RateLimitThreshold),
"exceed_action": conf.ExceedAction,
"conform_action": conf.ConformAction,
"enforce_on_key": conf.EnforceOnKey,
"enforce_on_key_name": conf.EnforceOnKeyName,
"ban_duration_sec": conf.BanDurationSec,
"exceed_redirect_options": flattenSecurityPolicyRedirectOptions(conf.ExceedRedirectOptions),
}
return []map[string]interface{}{data}
}
func flattenThreshold(conf *compute.SecurityPolicyRuleRateLimitOptionsThreshold) []map[string]interface{} {
if conf == nil {
return nil
}
data := map[string]interface{}{
"count": conf.Count,
"interval_sec": conf.IntervalSec,
}
return []map[string]interface{}{data}
}
func expandSecurityPolicyRuleRedirectOptions(configured []interface{}) *compute.SecurityPolicyRuleRedirectOptions {
if len(configured) == 0 || configured[0] == nil {
return nil
}
data := configured[0].(map[string]interface{})
return &compute.SecurityPolicyRuleRedirectOptions{
Type: data["type"].(string),
Target: data["target"].(string),
}
}
func flattenSecurityPolicyRedirectOptions(conf *compute.SecurityPolicyRuleRedirectOptions) []map[string]interface{} {
if conf == nil {
return nil
}
data := map[string]interface{}{
"type": conf.Type,
"target": conf.Target,
}
return []map[string]interface{}{data}
}
func resourceSecurityPolicyStateImporter(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
if err := parseImportId([]string{"projects/(?P<project>[^/]+)/global/securityPolicies/(?P<name>[^/]+)", "(?P<project>[^/]+)/(?P<name>[^/]+)", "(?P<name>[^/]+)"}, d, config); err != nil {
return nil, err
}
// Replace import id for the resource id
id, err := replaceVars(d, config, "projects/{{project}}/global/securityPolicies/{{name}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
}