forked from hashicorp/terraform-provider-google-beta
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresource_compute_region_security_policy_rule.go
2129 lines (1897 loc) · 91.5 KB
/
resource_compute_region_security_policy_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
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
// ----------------------------------------------------------------------------
//
// *** AUTO GENERATED CODE *** Type: MMv1 ***
//
// ----------------------------------------------------------------------------
//
// This file is automatically generated by Magic Modules and manual
// changes will be clobbered when the file is regenerated.
//
// Please read more about how to change this file in
// .github/CONTRIBUTING.md.
//
// ----------------------------------------------------------------------------
package compute
import (
"fmt"
"log"
"net/http"
"reflect"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource"
transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport"
"github.com/hashicorp/terraform-provider-google-beta/google-beta/verify"
)
func ResourceComputeRegionSecurityPolicyRule() *schema.Resource {
return &schema.Resource{
Create: resourceComputeRegionSecurityPolicyRuleCreate,
Read: resourceComputeRegionSecurityPolicyRuleRead,
Update: resourceComputeRegionSecurityPolicyRuleUpdate,
Delete: resourceComputeRegionSecurityPolicyRuleDelete,
Importer: &schema.ResourceImporter{
State: resourceComputeRegionSecurityPolicyRuleImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Update: schema.DefaultTimeout(20 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
CustomizeDiff: customdiff.All(
tpgresource.DefaultProviderProject,
),
Schema: map[string]*schema.Schema{
"action": {
Type: schema.TypeString,
Required: true,
Description: `The Action to perform when the rule is matched. The following are the valid actions:
* allow: allow access to target.
* deny(STATUS): deny access to target, returns the HTTP response code specified. Valid values for STATUS are 403, 404, and 502.
* rate_based_ban: limit client traffic to the configured threshold and ban the client if the traffic exceeds the threshold. Configure parameters for this action in RateLimitOptions. Requires rateLimitOptions to be set.
* redirect: redirect to a different target. This can either be an internal reCAPTCHA redirect, or an external URL-based redirect via a 302 response. Parameters for this action can be configured via redirectOptions. This action is only supported in Global Security Policies of type CLOUD_ARMOR.
* throttle: limit client traffic to the configured threshold. Configure parameters for this action in rateLimitOptions. Requires rateLimitOptions to be set for this.`,
},
"priority": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
Description: `An integer indicating the priority of a rule in the list.
The priority must be a positive value between 0 and 2147483647.
Rules are evaluated from highest to lowest priority where 0 is the highest priority and 2147483647 is the lowest priority.`,
},
"region": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The Region in which the created Region Security Policy rule should reside.`,
},
"security_policy": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The name of the security policy this rule belongs to.`,
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: `An optional description of this resource. Provide this property when you create the resource.`,
},
"match": {
Type: schema.TypeList,
Optional: true,
Description: `A match condition that incoming traffic is evaluated against.
If it evaluates to true, the corresponding 'action' is enforced.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"config": {
Type: schema.TypeList,
Optional: true,
Description: `The configuration options available when specifying versionedExpr.
This field must be specified if versionedExpr is specified and cannot be specified if versionedExpr is not specified.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"src_ip_ranges": {
Type: schema.TypeList,
Optional: true,
Description: `CIDR IP address range. Maximum number of srcIpRanges allowed is 10.`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
"expr": {
Type: schema.TypeList,
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.`,
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.`,
},
},
},
},
"versioned_expr": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: verify.ValidateEnum([]string{"SRC_IPS_V1", ""}),
Description: `Preconfigured versioned expression. If this field is specified, config must also be specified.
Available preconfigured expressions along with their requirements are: SRC_IPS_V1 - must specify the corresponding srcIpRange field in config. Possible values: ["SRC_IPS_V1"]`,
},
},
},
},
"network_match": {
Type: schema.TypeList,
Optional: true,
Description: `A match condition that incoming packets are evaluated against for CLOUD_ARMOR_NETWORK security policies. If it matches, the corresponding 'action' is enforced.
The match criteria for a rule consists of built-in match fields (like 'srcIpRanges') and potentially multiple user-defined match fields ('userDefinedFields').
Field values may be extracted directly from the packet or derived from it (e.g. 'srcRegionCodes'). Some fields may not be present in every packet (e.g. 'srcPorts'). A user-defined field is only present if the base header is found in the packet and the entire field is in bounds.
Each match field may specify which values can match it, listing one or more ranges, prefixes, or exact values that are considered a match for the field. A field value must be present in order to match a specified match field. If no match values are specified for a match field, then any field value is considered to match it, and it's not required to be present. For strings specifying '*' is also equivalent to match all.
For a packet to match a rule, all specified match fields must match the corresponding field values derived from the packet.
Example:
networkMatch: srcIpRanges: - "192.0.2.0/24" - "198.51.100.0/24" userDefinedFields: - name: "ipv4_fragment_offset" values: - "1-0x1fff"
The above match condition matches packets with a source IP in 192.0.2.0/24 or 198.51.100.0/24 and a user-defined field named "ipv4_fragment_offset" with a value between 1 and 0x1fff inclusive`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"dest_ip_ranges": {
Type: schema.TypeList,
Optional: true,
Description: `Destination IPv4/IPv6 addresses or CIDR prefixes, in standard text format.`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"dest_ports": {
Type: schema.TypeList,
Optional: true,
Description: `Destination port numbers for TCP/UDP/SCTP. Each element can be a 16-bit unsigned decimal number (e.g. "80") or range (e.g. "0-1023").`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"ip_protocols": {
Type: schema.TypeList,
Optional: true,
Description: `IPv4 protocol / IPv6 next header (after extension headers). Each element can be an 8-bit unsigned decimal number (e.g. "6"), range (e.g. "253-254"), or one of the following protocol names: "tcp", "udp", "icmp", "esp", "ah", "ipip", or "sctp".`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"src_asns": {
Type: schema.TypeList,
Optional: true,
Description: `BGP Autonomous System Number associated with the source IP address.`,
Elem: &schema.Schema{
Type: schema.TypeInt,
},
},
"src_ip_ranges": {
Type: schema.TypeList,
Optional: true,
Description: `Source IPv4/IPv6 addresses or CIDR prefixes, in standard text format.`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"src_ports": {
Type: schema.TypeList,
Optional: true,
Description: `Source port numbers for TCP/UDP/SCTP. Each element can be a 16-bit unsigned decimal number (e.g. "80") or range (e.g. "0-1023").`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"src_region_codes": {
Type: schema.TypeList,
Optional: true,
Description: `Two-letter ISO 3166-1 alpha-2 country code associated with the source IP address.`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"user_defined_fields": {
Type: schema.TypeList,
Optional: true,
Description: `User-defined fields. Each element names a defined field and lists the matching values for that field.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Description: `Name of the user-defined field, as given in the definition.`,
},
"values": {
Type: schema.TypeList,
Optional: true,
Description: `Matching values of the field. Each element can be a 32-bit unsigned decimal or hexadecimal (starting with "0x") number (e.g. "64") or range (e.g. "0x400-0x7ff").`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
},
},
},
"preconfigured_waf_config": {
Type: schema.TypeList,
Optional: true,
Description: `Preconfigured WAF configuration to be applied for the rule.
If the rule does not evaluate preconfigured WAF rules, i.e., if evaluatePreconfiguredWaf() is not used, this field will have no effect.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"exclusion": {
Type: schema.TypeList,
Optional: true,
Description: `An exclusion to apply during preconfigured WAF evaluation.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"target_rule_set": {
Type: schema.TypeString,
Required: true,
Description: `Target WAF rule set to apply the preconfigured WAF exclusion.`,
},
"request_cookie": {
Type: schema.TypeList,
Optional: true,
Description: `Request cookie whose value will be excluded from inspection during preconfigured WAF evaluation.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"operator": {
Type: schema.TypeString,
Required: true,
ValidateFunc: verify.ValidateEnum([]string{"CONTAINS", "ENDS_WITH", "EQUALS", "EQUALS_ANY", "STARTS_WITH"}),
Description: `You can specify an exact match or a partial match by using a field operator and a field value.
Available options:
EQUALS: The operator matches if the field value equals the specified value.
STARTS_WITH: The operator matches if the field value starts with the specified value.
ENDS_WITH: The operator matches if the field value ends with the specified value.
CONTAINS: The operator matches if the field value contains the specified value.
EQUALS_ANY: The operator matches if the field value is any value. Possible values: ["CONTAINS", "ENDS_WITH", "EQUALS", "EQUALS_ANY", "STARTS_WITH"]`,
},
"value": {
Type: schema.TypeString,
Optional: true,
Description: `A request field matching the specified value will be excluded from inspection during preconfigured WAF evaluation.
The field value must be given if the field operator is not EQUALS_ANY, and cannot be given if the field operator is EQUALS_ANY.`,
},
},
},
},
"request_header": {
Type: schema.TypeList,
Optional: true,
Description: `Request header whose value will be excluded from inspection during preconfigured WAF evaluation.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"operator": {
Type: schema.TypeString,
Required: true,
ValidateFunc: verify.ValidateEnum([]string{"CONTAINS", "ENDS_WITH", "EQUALS", "EQUALS_ANY", "STARTS_WITH"}),
Description: `You can specify an exact match or a partial match by using a field operator and a field value.
Available options:
EQUALS: The operator matches if the field value equals the specified value.
STARTS_WITH: The operator matches if the field value starts with the specified value.
ENDS_WITH: The operator matches if the field value ends with the specified value.
CONTAINS: The operator matches if the field value contains the specified value.
EQUALS_ANY: The operator matches if the field value is any value. Possible values: ["CONTAINS", "ENDS_WITH", "EQUALS", "EQUALS_ANY", "STARTS_WITH"]`,
},
"value": {
Type: schema.TypeString,
Optional: true,
Description: `A request field matching the specified value will be excluded from inspection during preconfigured WAF evaluation.
The field value must be given if the field operator is not EQUALS_ANY, and cannot be given if the field operator is EQUALS_ANY.`,
},
},
},
},
"request_query_param": {
Type: schema.TypeList,
Optional: true,
Description: `Request query parameter whose value will be excluded from inspection during preconfigured WAF evaluation.
Note that the parameter can be in the query string or in the POST body.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"operator": {
Type: schema.TypeString,
Required: true,
ValidateFunc: verify.ValidateEnum([]string{"CONTAINS", "ENDS_WITH", "EQUALS", "EQUALS_ANY", "STARTS_WITH"}),
Description: `You can specify an exact match or a partial match by using a field operator and a field value.
Available options:
EQUALS: The operator matches if the field value equals the specified value.
STARTS_WITH: The operator matches if the field value starts with the specified value.
ENDS_WITH: The operator matches if the field value ends with the specified value.
CONTAINS: The operator matches if the field value contains the specified value.
EQUALS_ANY: The operator matches if the field value is any value. Possible values: ["CONTAINS", "ENDS_WITH", "EQUALS", "EQUALS_ANY", "STARTS_WITH"]`,
},
"value": {
Type: schema.TypeString,
Optional: true,
Description: `A request field matching the specified value will be excluded from inspection during preconfigured WAF evaluation.
The field value must be given if the field operator is not EQUALS_ANY, and cannot be given if the field operator is EQUALS_ANY.`,
},
},
},
},
"request_uri": {
Type: schema.TypeList,
Optional: true,
Description: `Request URI from the request line to be excluded from inspection during preconfigured WAF evaluation.
When specifying this field, the query or fragment part should be excluded.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"operator": {
Type: schema.TypeString,
Required: true,
ValidateFunc: verify.ValidateEnum([]string{"CONTAINS", "ENDS_WITH", "EQUALS", "EQUALS_ANY", "STARTS_WITH"}),
Description: `You can specify an exact match or a partial match by using a field operator and a field value.
Available options:
EQUALS: The operator matches if the field value equals the specified value.
STARTS_WITH: The operator matches if the field value starts with the specified value.
ENDS_WITH: The operator matches if the field value ends with the specified value.
CONTAINS: The operator matches if the field value contains the specified value.
EQUALS_ANY: The operator matches if the field value is any value. Possible values: ["CONTAINS", "ENDS_WITH", "EQUALS", "EQUALS_ANY", "STARTS_WITH"]`,
},
"value": {
Type: schema.TypeString,
Optional: true,
Description: `A request field matching the specified value will be excluded from inspection during preconfigured WAF evaluation.
The field value must be given if the field operator is not EQUALS_ANY, and cannot be given if the field operator is EQUALS_ANY.`,
},
},
},
},
"target_rule_ids": {
Type: schema.TypeList,
Optional: true,
Description: `A list of target rule IDs under the WAF rule set to apply the preconfigured WAF exclusion.
If omitted, it refers to all the rule IDs under the WAF rule set.`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
},
},
},
},
},
},
"preview": {
Type: schema.TypeBool,
Optional: true,
Description: `If set to true, the specified action is not enforced.`,
},
"rate_limit_options": {
Type: schema.TypeList,
Optional: true,
Description: `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{
"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.`,
},
"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,
Optional: true,
Description: `Number of HTTP(S) requests for calculating the threshold.`,
},
"interval_sec": {
Type: schema.TypeInt,
Optional: true,
Description: `Interval over which the threshold is computed.`,
},
},
},
},
"conform_action": {
Type: schema.TypeString,
Optional: true,
Description: `Action to take for requests that are under the configured rate limit threshold.
Valid option is "allow" only.`,
},
"enforce_on_key": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: verify.ValidateEnum([]string{"ALL", "IP", "HTTP_HEADER", "XFF_IP", "HTTP_COOKIE", "HTTP_PATH", "SNI", "REGION_CODE", "TLS_JA3_FINGERPRINT", "USER_IP", ""}),
Description: `Determines the key to enforce the rateLimitThreshold on. Possible values are:
* ALL: A single rate limit threshold is applied to all the requests matching this rule. This is the default value if "enforceOnKey" is not configured.
* IP: The source IP address of the request is the key. Each IP has this limit enforced separately.
* HTTP_HEADER: The value of the HTTP header whose name is configured under "enforceOnKeyName". The key value is truncated to the first 128 bytes of the header value. If no such header is present in the request, the key type defaults to ALL.
* XFF_IP: The first IP address (i.e. the originating client IP address) specified in the list of IPs under X-Forwarded-For HTTP header. If no such header is present or the value is not a valid IP, the key defaults to the source IP address of the request i.e. key type IP.
* HTTP_COOKIE: The value of the HTTP cookie whose name is configured under "enforceOnKeyName". The key value is truncated to the first 128 bytes of the cookie value. If no such cookie is present in the request, the key type defaults to ALL.
* HTTP_PATH: The URL path of the HTTP request. The key value is truncated to the first 128 bytes.
* SNI: Server name indication in the TLS session of the HTTPS request. The key value is truncated to the first 128 bytes. The key type defaults to ALL on a HTTP session.
* REGION_CODE: The country/region from which the request originates.
* TLS_JA3_FINGERPRINT: JA3 TLS/SSL fingerprint if the client connects using HTTPS, HTTP/2 or HTTP/3. If not available, the key type defaults to ALL.
* USER_IP: The IP address of the originating client, which is resolved based on "userIpRequestHeaders" configured with the security policy. If there is no "userIpRequestHeaders" configuration or an IP address cannot be resolved from it, the key type defaults to IP. Possible values: ["ALL", "IP", "HTTP_HEADER", "XFF_IP", "HTTP_COOKIE", "HTTP_PATH", "SNI", "REGION_CODE", "TLS_JA3_FINGERPRINT", "USER_IP"]`,
},
"enforce_on_key_configs": {
Type: schema.TypeList,
Optional: true,
Description: `If specified, any combination of values of enforceOnKeyType/enforceOnKeyName is treated as the key on which ratelimit threshold/action is enforced.
You can specify up to 3 enforceOnKeyConfigs.
If enforceOnKeyConfigs is specified, enforceOnKey must not be specified.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"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.`,
},
"enforce_on_key_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: verify.ValidateEnum([]string{"ALL", "IP", "HTTP_HEADER", "XFF_IP", "HTTP_COOKIE", "HTTP_PATH", "SNI", "REGION_CODE", "TLS_JA3_FINGERPRINT", "USER_IP", ""}),
Description: `Determines the key to enforce the rateLimitThreshold on. Possible values are:
* ALL: A single rate limit threshold is applied to all the requests matching this rule. This is the default value if "enforceOnKeyConfigs" is not configured.
* IP: The source IP address of the request is the key. Each IP has this limit enforced separately.
* HTTP_HEADER: The value of the HTTP header whose name is configured under "enforceOnKeyName". The key value is truncated to the first 128 bytes of the header value. If no such header is present in the request, the key type defaults to ALL.
* XFF_IP: The first IP address (i.e. the originating client IP address) specified in the list of IPs under X-Forwarded-For HTTP header. If no such header is present or the value is not a valid IP, the key defaults to the source IP address of the request i.e. key type IP.
* HTTP_COOKIE: The value of the HTTP cookie whose name is configured under "enforceOnKeyName". The key value is truncated to the first 128 bytes of the cookie value. If no such cookie is present in the request, the key type defaults to ALL.
* HTTP_PATH: The URL path of the HTTP request. The key value is truncated to the first 128 bytes.
* SNI: Server name indication in the TLS session of the HTTPS request. The key value is truncated to the first 128 bytes. The key type defaults to ALL on a HTTP session.
* REGION_CODE: The country/region from which the request originates.
* TLS_JA3_FINGERPRINT: JA3 TLS/SSL fingerprint if the client connects using HTTPS, HTTP/2 or HTTP/3. If not available, the key type defaults to ALL.
* USER_IP: The IP address of the originating client, which is resolved based on "userIpRequestHeaders" configured with the security policy. If there is no "userIpRequestHeaders" configuration or an IP address cannot be resolved from it, the key type defaults to IP. Possible values: ["ALL", "IP", "HTTP_HEADER", "XFF_IP", "HTTP_COOKIE", "HTTP_PATH", "SNI", "REGION_CODE", "TLS_JA3_FINGERPRINT", "USER_IP"]`,
},
},
},
},
"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.`,
},
"exceed_action": {
Type: schema.TypeString,
Optional: true,
Description: `Action to take for requests that are above the configured rate limit threshold, to deny with a specified HTTP response code.
Valid options are deny(STATUS), where valid values for STATUS are 403, 404, 429, and 502.`,
},
"rate_limit_threshold": {
Type: schema.TypeList,
Optional: true,
Description: `Threshold at which to begin ratelimiting.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"count": {
Type: schema.TypeInt,
Optional: true,
Description: `Number of HTTP(S) requests for calculating the threshold.`,
},
"interval_sec": {
Type: schema.TypeInt,
Optional: true,
Description: `Interval over which the threshold is computed.`,
},
},
},
},
},
},
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
UseJSONNumber: true,
}
}
func resourceComputeRegionSecurityPolicyRuleCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}
obj := make(map[string]interface{})
descriptionProp, err := expandComputeRegionSecurityPolicyRuleDescription(d.Get("description"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("description"); !tpgresource.IsEmptyValue(reflect.ValueOf(descriptionProp)) && (ok || !reflect.DeepEqual(v, descriptionProp)) {
obj["description"] = descriptionProp
}
priorityProp, err := expandComputeRegionSecurityPolicyRulePriority(d.Get("priority"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("priority"); !tpgresource.IsEmptyValue(reflect.ValueOf(priorityProp)) && (ok || !reflect.DeepEqual(v, priorityProp)) {
obj["priority"] = priorityProp
}
matchProp, err := expandComputeRegionSecurityPolicyRuleMatch(d.Get("match"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("match"); !tpgresource.IsEmptyValue(reflect.ValueOf(matchProp)) && (ok || !reflect.DeepEqual(v, matchProp)) {
obj["match"] = matchProp
}
preconfiguredWafConfigProp, err := expandComputeRegionSecurityPolicyRulePreconfiguredWafConfig(d.Get("preconfigured_waf_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("preconfigured_waf_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(preconfiguredWafConfigProp)) && (ok || !reflect.DeepEqual(v, preconfiguredWafConfigProp)) {
obj["preconfiguredWafConfig"] = preconfiguredWafConfigProp
}
actionProp, err := expandComputeRegionSecurityPolicyRuleAction(d.Get("action"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("action"); !tpgresource.IsEmptyValue(reflect.ValueOf(actionProp)) && (ok || !reflect.DeepEqual(v, actionProp)) {
obj["action"] = actionProp
}
rateLimitOptionsProp, err := expandComputeRegionSecurityPolicyRuleRateLimitOptions(d.Get("rate_limit_options"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("rate_limit_options"); !tpgresource.IsEmptyValue(reflect.ValueOf(rateLimitOptionsProp)) && (ok || !reflect.DeepEqual(v, rateLimitOptionsProp)) {
obj["rateLimitOptions"] = rateLimitOptionsProp
}
previewProp, err := expandComputeRegionSecurityPolicyRulePreview(d.Get("preview"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("preview"); !tpgresource.IsEmptyValue(reflect.ValueOf(previewProp)) && (ok || !reflect.DeepEqual(v, previewProp)) {
obj["preview"] = previewProp
}
networkMatchProp, err := expandComputeRegionSecurityPolicyRuleNetworkMatch(d.Get("network_match"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("network_match"); !tpgresource.IsEmptyValue(reflect.ValueOf(networkMatchProp)) && (ok || !reflect.DeepEqual(v, networkMatchProp)) {
obj["networkMatch"] = networkMatchProp
}
url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/securityPolicies/{{security_policy}}/addRule?priority={{priority}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Creating new RegionSecurityPolicyRule: %#v", obj)
billingProject := ""
project, err := tpgresource.GetProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for RegionSecurityPolicyRule: %s", err)
}
billingProject = project
// err == nil indicates that the billing_project value was found
if bp, err := tpgresource.GetBillingProject(d, config); err == nil {
billingProject = bp
}
headers := make(http.Header)
// We can't Create a default rule since one is automatically created with the policy
rulePriority, ok := d.GetOk("priority")
if ok && rulePriority.(int) == 2147483647 {
log.Printf("[WARN] RegionSecurityPolicyRule represents a default rule, will attempt an Update instead")
newUrl, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/securityPolicies/{{security_policy}}/patchRule?priority={{priority}}")
if err != nil {
return err
}
url = newUrl
}
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutCreate),
Headers: headers,
})
if err != nil {
return fmt.Errorf("Error creating RegionSecurityPolicyRule: %s", err)
}
// Store the ID now
id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/regions/{{region}}/securityPolicies/{{security_policy}}/priority/{{priority}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
err = ComputeOperationWaitTime(
config, res, project, "Creating RegionSecurityPolicyRule", userAgent,
d.Timeout(schema.TimeoutCreate))
if err != nil {
// The resource didn't actually create
d.SetId("")
return fmt.Errorf("Error waiting to create RegionSecurityPolicyRule: %s", err)
}
log.Printf("[DEBUG] Finished creating RegionSecurityPolicyRule %q: %#v", d.Id(), res)
return resourceComputeRegionSecurityPolicyRuleRead(d, meta)
}
func resourceComputeRegionSecurityPolicyRuleRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}
url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/securityPolicies/{{security_policy}}/getRule?priority={{priority}}")
if err != nil {
return err
}
billingProject := ""
project, err := tpgresource.GetProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for RegionSecurityPolicyRule: %s", err)
}
billingProject = project
// err == nil indicates that the billing_project value was found
if bp, err := tpgresource.GetBillingProject(d, config); err == nil {
billingProject = bp
}
headers := make(http.Header)
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "GET",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Headers: headers,
})
if err != nil {
return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("ComputeRegionSecurityPolicyRule %q", d.Id()))
}
if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error reading RegionSecurityPolicyRule: %s", err)
}
if err := d.Set("description", flattenComputeRegionSecurityPolicyRuleDescription(res["description"], d, config)); err != nil {
return fmt.Errorf("Error reading RegionSecurityPolicyRule: %s", err)
}
if err := d.Set("priority", flattenComputeRegionSecurityPolicyRulePriority(res["priority"], d, config)); err != nil {
return fmt.Errorf("Error reading RegionSecurityPolicyRule: %s", err)
}
if err := d.Set("match", flattenComputeRegionSecurityPolicyRuleMatch(res["match"], d, config)); err != nil {
return fmt.Errorf("Error reading RegionSecurityPolicyRule: %s", err)
}
if err := d.Set("preconfigured_waf_config", flattenComputeRegionSecurityPolicyRulePreconfiguredWafConfig(res["preconfiguredWafConfig"], d, config)); err != nil {
return fmt.Errorf("Error reading RegionSecurityPolicyRule: %s", err)
}
if err := d.Set("action", flattenComputeRegionSecurityPolicyRuleAction(res["action"], d, config)); err != nil {
return fmt.Errorf("Error reading RegionSecurityPolicyRule: %s", err)
}
if err := d.Set("rate_limit_options", flattenComputeRegionSecurityPolicyRuleRateLimitOptions(res["rateLimitOptions"], d, config)); err != nil {
return fmt.Errorf("Error reading RegionSecurityPolicyRule: %s", err)
}
if err := d.Set("preview", flattenComputeRegionSecurityPolicyRulePreview(res["preview"], d, config)); err != nil {
return fmt.Errorf("Error reading RegionSecurityPolicyRule: %s", err)
}
if err := d.Set("network_match", flattenComputeRegionSecurityPolicyRuleNetworkMatch(res["networkMatch"], d, config)); err != nil {
return fmt.Errorf("Error reading RegionSecurityPolicyRule: %s", err)
}
return nil
}
func resourceComputeRegionSecurityPolicyRuleUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}
billingProject := ""
project, err := tpgresource.GetProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for RegionSecurityPolicyRule: %s", err)
}
billingProject = project
obj := make(map[string]interface{})
descriptionProp, err := expandComputeRegionSecurityPolicyRuleDescription(d.Get("description"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("description"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, descriptionProp)) {
obj["description"] = descriptionProp
}
priorityProp, err := expandComputeRegionSecurityPolicyRulePriority(d.Get("priority"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("priority"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, priorityProp)) {
obj["priority"] = priorityProp
}
matchProp, err := expandComputeRegionSecurityPolicyRuleMatch(d.Get("match"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("match"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, matchProp)) {
obj["match"] = matchProp
}
preconfiguredWafConfigProp, err := expandComputeRegionSecurityPolicyRulePreconfiguredWafConfig(d.Get("preconfigured_waf_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("preconfigured_waf_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, preconfiguredWafConfigProp)) {
obj["preconfiguredWafConfig"] = preconfiguredWafConfigProp
}
actionProp, err := expandComputeRegionSecurityPolicyRuleAction(d.Get("action"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("action"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, actionProp)) {
obj["action"] = actionProp
}
rateLimitOptionsProp, err := expandComputeRegionSecurityPolicyRuleRateLimitOptions(d.Get("rate_limit_options"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("rate_limit_options"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, rateLimitOptionsProp)) {
obj["rateLimitOptions"] = rateLimitOptionsProp
}
previewProp, err := expandComputeRegionSecurityPolicyRulePreview(d.Get("preview"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("preview"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, previewProp)) {
obj["preview"] = previewProp
}
networkMatchProp, err := expandComputeRegionSecurityPolicyRuleNetworkMatch(d.Get("network_match"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("network_match"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, networkMatchProp)) {
obj["networkMatch"] = networkMatchProp
}
url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/securityPolicies/{{security_policy}}/patchRule?priority={{priority}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Updating RegionSecurityPolicyRule %q: %#v", d.Id(), obj)
headers := make(http.Header)
updateMask := []string{}
if d.HasChange("description") {
updateMask = append(updateMask, "description")
}
if d.HasChange("priority") {
updateMask = append(updateMask, "priority")
}
if d.HasChange("match") {
updateMask = append(updateMask, "match")
}
if d.HasChange("preconfigured_waf_config") {
updateMask = append(updateMask, "preconfiguredWafConfig")
}
if d.HasChange("action") {
updateMask = append(updateMask, "action")
}
if d.HasChange("rate_limit_options") {
updateMask = append(updateMask, "rateLimitOptions.rateLimitThreshold",
"rateLimitOptions.conformAction",
"rateLimitOptions.exceedAction",
"rateLimitOptions.enforceOnKey",
"rateLimitOptions.enforceOnKeyName",
"rateLimitOptions.enforceOnKeyConfigs",
"rateLimitOptions.banThreshold",
"rateLimitOptions.banDurationSec")
}
if d.HasChange("preview") {
updateMask = append(updateMask, "preview")
}
if d.HasChange("network_match") {
updateMask = append(updateMask, "network_match.userDefinedFields",
"network_match.srcIpRanges",
"network_match.destIpRanges",
"network_match.ipProtocols",
"network_match.srcPorts",
"network_match.destPorts",
"network_match.srcRegionCodes",
"network_match.srcAsns")
}
// updateMask is a URL parameter but not present in the schema, so ReplaceVars
// won't set it
url, err = transport_tpg.AddQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")})
if err != nil {
return err
}
// err == nil indicates that the billing_project value was found
if bp, err := tpgresource.GetBillingProject(d, config); err == nil {
billingProject = bp
}
// if updateMask is empty we are not updating anything so skip the post
if len(updateMask) > 0 {
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutUpdate),
Headers: headers,
})
if err != nil {
return fmt.Errorf("Error updating RegionSecurityPolicyRule %q: %s", d.Id(), err)
} else {
log.Printf("[DEBUG] Finished updating RegionSecurityPolicyRule %q: %#v", d.Id(), res)
}
err = ComputeOperationWaitTime(
config, res, project, "Updating RegionSecurityPolicyRule", userAgent,
d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
}
return resourceComputeRegionSecurityPolicyRuleRead(d, meta)
}
func resourceComputeRegionSecurityPolicyRuleDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}
billingProject := ""
project, err := tpgresource.GetProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for RegionSecurityPolicyRule: %s", err)
}
billingProject = project
url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/securityPolicies/{{security_policy}}/removeRule?priority={{priority}}")
if err != nil {
return err
}
var obj map[string]interface{}
// err == nil indicates that the billing_project value was found
if bp, err := tpgresource.GetBillingProject(d, config); err == nil {
billingProject = bp
}
headers := make(http.Header)
// The default rule of a Security Policy cannot be removed
rulePriority, ok := d.GetOk("priority")
if ok && rulePriority.(int) == 2147483647 {
log.Printf("[WARN] RegionSecurityPolicyRule represents a default rule, skipping Delete request")
return nil
}
log.Printf("[DEBUG] Deleting RegionSecurityPolicyRule %q", d.Id())
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutDelete),
Headers: headers,
})
if err != nil {
return transport_tpg.HandleNotFoundError(err, d, "RegionSecurityPolicyRule")
}
err = ComputeOperationWaitTime(
config, res, project, "Deleting RegionSecurityPolicyRule", userAgent,
d.Timeout(schema.TimeoutDelete))
if err != nil {
return err
}
log.Printf("[DEBUG] Finished deleting RegionSecurityPolicyRule %q: %#v", d.Id(), res)
return nil
}
func resourceComputeRegionSecurityPolicyRuleImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*transport_tpg.Config)
if err := tpgresource.ParseImportId([]string{
"^projects/(?P<project>[^/]+)/regions/(?P<region>[^/]+)/securityPolicies/(?P<security_policy>[^/]+)/priority/(?P<priority>[^/]+)$",
"^(?P<project>[^/]+)/(?P<region>[^/]+)/(?P<security_policy>[^/]+)/(?P<priority>[^/]+)$",
"^(?P<region>[^/]+)/(?P<security_policy>[^/]+)/(?P<priority>[^/]+)$",
"^(?P<security_policy>[^/]+)/(?P<priority>[^/]+)$",
}, d, config); err != nil {
return nil, err
}
// Replace import id for the resource id
id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/regions/{{region}}/securityPolicies/{{security_policy}}/priority/{{priority}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
}
func flattenComputeRegionSecurityPolicyRuleDescription(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenComputeRegionSecurityPolicyRulePriority(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
// Handles the string fixed64 format
if strVal, ok := v.(string); ok {
if intVal, err := tpgresource.StringToFixed64(strVal); err == nil {
return intVal
}
}
// number values are represented as float64
if floatVal, ok := v.(float64); ok {
intVal := int(floatVal)
return intVal
}
return v // let terraform core handle it otherwise
}
func flattenComputeRegionSecurityPolicyRuleMatch(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {
return nil
}
transformed := make(map[string]interface{})