0
# Firewall Policies
1
2
Advanced security rules that automatically respond to detected threats with configurable actions. Firewall policies provide automated threat response capabilities including allow, block, substitute, and redirect actions based on risk analysis and custom conditions.
3
4
## Capabilities
5
6
### Create Firewall Policy
7
8
Creates a new firewall policy with conditions and actions that automatically respond to assessment results.
9
10
```python { .api }
11
def create_firewall_policy(
12
request: CreateFirewallPolicyRequest = None,
13
*,
14
parent: str = None,
15
firewall_policy: FirewallPolicy = None,
16
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
17
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
18
metadata: Sequence[Tuple[str, str]] = ()
19
) -> FirewallPolicy:
20
"""
21
Creates a firewall policy.
22
23
Args:
24
request: The request object for creating a firewall policy
25
parent: Required. The name of the project in format 'projects/{project}'
26
firewall_policy: Required. Firewall policy configuration
27
retry: Retry configuration for the request
28
timeout: Timeout for the request in seconds
29
metadata: Additional metadata for the request
30
31
Returns:
32
FirewallPolicy: The created firewall policy
33
34
Raises:
35
google.api_core.exceptions.InvalidArgument: If policy configuration is invalid
36
google.api_core.exceptions.AlreadyExists: If policy path already exists
37
google.api_core.exceptions.PermissionDenied: If insufficient permissions
38
"""
39
```
40
41
#### Usage Example
42
43
```python
44
from google.cloud import recaptchaenterprise
45
from google.cloud.recaptchaenterprise_v1.types import FirewallPolicy, FirewallAction
46
47
client = recaptchaenterprise.RecaptchaEnterpriseServiceClient()
48
49
# Create block action for low scores
50
block_action = FirewallAction(
51
block=FirewallAction.BlockAction()
52
)
53
54
# Create firewall policy
55
policy = FirewallPolicy(
56
description="Block suspicious login attempts",
57
path="/login/*",
58
condition="assessment.risk_analysis.score < 0.3",
59
actions=[block_action]
60
)
61
62
request = recaptchaenterprise.CreateFirewallPolicyRequest(
63
parent="projects/your-project-id",
64
firewall_policy=policy
65
)
66
67
created_policy = client.create_firewall_policy(request=request)
68
print(f"Created policy: {created_policy.name}")
69
```
70
71
### List Firewall Policies
72
73
Retrieves all firewall policies for a project with support for pagination.
74
75
```python { .api }
76
def list_firewall_policies(
77
request: ListFirewallPoliciesRequest = None,
78
*,
79
parent: str = None,
80
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
81
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
82
metadata: Sequence[Tuple[str, str]] = ()
83
) -> ListFirewallPoliciesResponse:
84
"""
85
Returns the list of firewall policies in the project.
86
87
Args:
88
request: The request object for listing firewall policies
89
parent: Required. The name of the project in format 'projects/{project}'
90
retry: Retry configuration for the request
91
timeout: Timeout for the request in seconds
92
metadata: Additional metadata for the request
93
94
Returns:
95
ListFirewallPoliciesResponse: List of firewall policies
96
97
Raises:
98
google.api_core.exceptions.PermissionDenied: If insufficient permissions
99
google.api_core.exceptions.InvalidArgument: If parent format is invalid
100
"""
101
```
102
103
### Get Firewall Policy
104
105
Retrieves detailed information about a specific firewall policy.
106
107
```python { .api }
108
def get_firewall_policy(
109
request: GetFirewallPolicyRequest = None,
110
*,
111
name: str = None,
112
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
113
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
114
metadata: Sequence[Tuple[str, str]] = ()
115
) -> FirewallPolicy:
116
"""
117
Returns the specified firewall policy.
118
119
Args:
120
request: The request object for getting a firewall policy
121
name: Required. Policy name in format 'projects/{project}/firewallpolicies/{policy}'
122
retry: Retry configuration for the request
123
timeout: Timeout for the request in seconds
124
metadata: Additional metadata for the request
125
126
Returns:
127
FirewallPolicy: The firewall policy configuration
128
129
Raises:
130
google.api_core.exceptions.NotFound: If the policy doesn't exist
131
google.api_core.exceptions.PermissionDenied: If insufficient permissions
132
"""
133
```
134
135
### Update Firewall Policy
136
137
Updates the configuration of an existing firewall policy.
138
139
```python { .api }
140
def update_firewall_policy(
141
request: UpdateFirewallPolicyRequest = None,
142
*,
143
firewall_policy: FirewallPolicy = None,
144
update_mask: FieldMask = None,
145
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
146
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
147
metadata: Sequence[Tuple[str, str]] = ()
148
) -> FirewallPolicy:
149
"""
150
Updates the specified firewall policy.
151
152
Args:
153
request: The request object for updating a firewall policy
154
firewall_policy: Required. The policy to update
155
update_mask: Optional. Field mask specifying which fields to update
156
retry: Retry configuration for the request
157
timeout: Timeout for the request in seconds
158
metadata: Additional metadata for the request
159
160
Returns:
161
FirewallPolicy: The updated firewall policy
162
163
Raises:
164
google.api_core.exceptions.NotFound: If the policy doesn't exist
165
google.api_core.exceptions.InvalidArgument: If update parameters are invalid
166
google.api_core.exceptions.PermissionDenied: If insufficient permissions
167
"""
168
```
169
170
### Delete Firewall Policy
171
172
Permanently deletes a firewall policy.
173
174
```python { .api }
175
def delete_firewall_policy(
176
request: DeleteFirewallPolicyRequest = None,
177
*,
178
name: str = None,
179
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
180
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
181
metadata: Sequence[Tuple[str, str]] = ()
182
) -> None:
183
"""
184
Deletes the specified firewall policy.
185
186
Args:
187
request: The request object for deleting a firewall policy
188
name: Required. Policy name in format 'projects/{project}/firewallpolicies/{policy}'
189
retry: Retry configuration for the request
190
timeout: Timeout for the request in seconds
191
metadata: Additional metadata for the request
192
193
Raises:
194
google.api_core.exceptions.NotFound: If the policy doesn't exist
195
google.api_core.exceptions.PermissionDenied: If insufficient permissions
196
"""
197
```
198
199
### Reorder Firewall Policies
200
201
Changes the order of firewall policies, which affects their evaluation priority.
202
203
```python { .api }
204
def reorder_firewall_policies(
205
request: ReorderFirewallPoliciesRequest = None,
206
*,
207
parent: str = None,
208
names: List[str] = None,
209
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
210
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
211
metadata: Sequence[Tuple[str, str]] = ()
212
) -> ReorderFirewallPoliciesResponse:
213
"""
214
Reorders all firewall policies.
215
216
Args:
217
request: The request object for reordering policies
218
parent: Required. The name of the project in format 'projects/{project}'
219
names: Required. Ordered list of policy names
220
retry: Retry configuration for the request
221
timeout: Timeout for the request in seconds
222
metadata: Additional metadata for the request
223
224
Returns:
225
ReorderFirewallPoliciesResponse: Confirmation of reordering
226
227
Raises:
228
google.api_core.exceptions.InvalidArgument: If policy names are invalid
229
google.api_core.exceptions.PermissionDenied: If insufficient permissions
230
"""
231
```
232
233
## Request and Response Types
234
235
### FirewallPolicy
236
237
```python { .api }
238
class FirewallPolicy:
239
"""Firewall policy configuration."""
240
name: str # Output only. Resource name
241
description: str # Human-readable description
242
path: str # Path pattern to match requests
243
condition: str # CEL expression for triggering policy
244
actions: List[FirewallAction] # Actions to take when policy matches
245
```
246
247
### FirewallAction
248
249
```python { .api }
250
class FirewallAction:
251
"""Action to take when firewall conditions match."""
252
allow: AllowAction # Allow the request
253
block: BlockAction # Block the request
254
substitute: SubstituteAction # Substitute token or response
255
redirect: RedirectAction # Redirect to different URL
256
set_header: SetHeaderAction # Set HTTP headers
257
258
class AllowAction:
259
"""Allow action - lets the request proceed."""
260
pass # Empty class, just allows request
261
262
class BlockAction:
263
"""Block action - stops the request."""
264
pass # Empty class, blocks request
265
266
class SubstituteAction:
267
"""Substitute action - replaces token or response."""
268
path: str # Path to substitute
269
270
class RedirectAction:
271
"""Redirect action - redirects to different URL."""
272
pass # Empty class, uses default redirect
273
274
class SetHeaderAction:
275
"""Set header action - adds HTTP headers."""
276
key: str # Header name
277
value: str # Header value
278
```
279
280
### Request Types
281
282
```python { .api }
283
class CreateFirewallPolicyRequest:
284
"""Request message for creating a firewall policy."""
285
parent: str # Required. Project name
286
firewall_policy: FirewallPolicy # Required. Policy configuration
287
288
class ListFirewallPoliciesRequest:
289
"""Request message for listing firewall policies."""
290
parent: str # Required. Project name
291
page_size: int # Optional. Maximum results per page
292
page_token: str # Optional. Pagination token
293
294
class ListFirewallPoliciesResponse:
295
"""Response message for listing firewall policies."""
296
firewall_policies: List[FirewallPolicy] # The list of policies
297
next_page_token: str # Token for next page
298
299
class GetFirewallPolicyRequest:
300
"""Request message for getting a firewall policy."""
301
name: str # Required. Policy name
302
303
class UpdateFirewallPolicyRequest:
304
"""Request message for updating a firewall policy."""
305
firewall_policy: FirewallPolicy # Required. Updated policy
306
update_mask: FieldMask # Optional. Fields to update
307
308
class DeleteFirewallPolicyRequest:
309
"""Request message for deleting a firewall policy."""
310
name: str # Required. Policy name
311
312
class ReorderFirewallPoliciesRequest:
313
"""Request message for reordering firewall policies."""
314
parent: str # Required. Project name
315
names: List[str] # Required. Ordered policy names
316
317
class ReorderFirewallPoliciesResponse:
318
"""Response message for reordering firewall policies."""
319
pass # Empty response confirming reorder
320
```
321
322
## Usage Examples
323
324
### Creating Different Types of Policies
325
326
#### Block Low-Score Assessments
327
328
```python
329
# Block requests with risk scores below 0.3
330
block_policy = FirewallPolicy(
331
description="Block suspicious login attempts",
332
path="/api/login",
333
condition="assessment.risk_analysis.score < 0.3",
334
actions=[FirewallAction(block=FirewallAction.BlockAction())]
335
)
336
```
337
338
#### Redirect Suspicious Registration Attempts
339
340
```python
341
# Redirect suspicious registration attempts to verification page
342
redirect_policy = FirewallPolicy(
343
description="Redirect suspicious registrations",
344
path="/register",
345
condition="assessment.risk_analysis.score < 0.5 && assessment.token_properties.action == 'register'",
346
actions=[FirewallAction(redirect=FirewallAction.RedirectAction())]
347
)
348
```
349
350
#### Set Headers for Monitoring
351
352
```python
353
# Add monitoring headers for medium-risk requests
354
header_policy = FirewallPolicy(
355
description="Tag medium-risk requests",
356
path="/api/*",
357
condition="assessment.risk_analysis.score >= 0.3 && assessment.risk_analysis.score < 0.7",
358
actions=[
359
FirewallAction(
360
set_header=FirewallAction.SetHeaderAction(
361
key="X-Risk-Level",
362
value="medium"
363
)
364
),
365
FirewallAction(allow=FirewallAction.AllowAction())
366
]
367
)
368
```
369
370
#### Multiple Actions Policy
371
372
```python
373
# Complex policy with multiple actions
374
multi_action_policy = FirewallPolicy(
375
description="Multi-tier response for payment endpoints",
376
path="/payment/*",
377
condition="assessment.risk_analysis.score < 0.6",
378
actions=[
379
# Set warning header
380
FirewallAction(
381
set_header=FirewallAction.SetHeaderAction(
382
key="X-Fraud-Warning",
383
value="high-risk-detected"
384
)
385
),
386
# Allow with monitoring
387
FirewallAction(allow=FirewallAction.AllowAction())
388
]
389
)
390
```
391
392
### Advanced Condition Examples
393
394
#### Account Defender Integration
395
396
```python
397
# Block based on Account Defender signals
398
account_defender_policy = FirewallPolicy(
399
description="Block suspicious account behavior",
400
path="/account/*",
401
condition="""
402
assessment.account_defender_assessment.labels.contains('SUSPICIOUS_ACCOUNT_CREATION') ||
403
assessment.account_defender_assessment.labels.contains('SUSPICIOUS_LOGIN_ACTIVITY')
404
""",
405
actions=[FirewallAction(block=FirewallAction.BlockAction())]
406
)
407
```
408
409
#### Fraud Prevention Integration
410
411
```python
412
# Block high-risk transactions
413
fraud_prevention_policy = FirewallPolicy(
414
description="Block high-risk transactions",
415
path="/checkout",
416
condition="""
417
assessment.fraud_prevention_assessment.transaction_risk > 0.8 ||
418
assessment.fraud_prevention_assessment.stolen_instrument_verdict.risk > 0.7
419
""",
420
actions=[FirewallAction(block=FirewallAction.BlockAction())]
421
)
422
```
423
424
#### Time and Geography Conditions
425
426
```python
427
# Different rules based on request context
428
geo_time_policy = FirewallPolicy(
429
description="Geographic and time-based filtering",
430
path="/sensitive/*",
431
condition="""
432
assessment.risk_analysis.score < 0.4 ||
433
(assessment.event.user_ip_address.startsWith('192.168.') &&
434
assessment.risk_analysis.score < 0.6)
435
""",
436
actions=[FirewallAction(block=FirewallAction.BlockAction())]
437
)
438
```
439
440
### Policy Management Workflow
441
442
#### Complete Policy Lifecycle
443
444
```python
445
# Create policy
446
policy = FirewallPolicy(
447
description="Production login protection",
448
path="/login",
449
condition="assessment.risk_analysis.score < 0.4",
450
actions=[FirewallAction(block=FirewallAction.BlockAction())]
451
)
452
453
created_policy = client.create_firewall_policy(
454
parent="projects/your-project",
455
firewall_policy=policy
456
)
457
458
# Update policy condition
459
from google.protobuf import field_mask_pb2
460
461
updated_policy = FirewallPolicy(
462
name=created_policy.name,
463
description="Updated login protection",
464
condition="assessment.risk_analysis.score < 0.3" # Stricter threshold
465
)
466
467
update_mask = field_mask_pb2.FieldMask(paths=["description", "condition"])
468
469
client.update_firewall_policy(
470
firewall_policy=updated_policy,
471
update_mask=update_mask
472
)
473
474
# Reorder policies (most specific first)
475
policy_names = [
476
"projects/your-project/firewallpolicies/login-policy",
477
"projects/your-project/firewallpolicies/api-policy",
478
"projects/your-project/firewallpolicies/general-policy"
479
]
480
481
client.reorder_firewall_policies(
482
parent="projects/your-project",
483
names=policy_names
484
)
485
```
486
487
## Condition Language (CEL)
488
489
Firewall policies use Common Expression Language (CEL) for conditions. Available fields:
490
491
### Assessment Fields
492
493
```python
494
# Risk analysis
495
assessment.risk_analysis.score # Risk score (0.0-1.0)
496
assessment.risk_analysis.reasons # List of risk reasons
497
498
# Token properties
499
assessment.token_properties.valid # Token validity
500
assessment.token_properties.action # Expected action
501
assessment.token_properties.hostname # Token hostname
502
503
# Event details
504
assessment.event.user_ip_address # Client IP address
505
assessment.event.user_agent # User agent string
506
assessment.event.expected_action # Expected action name
507
508
# Account Defender
509
assessment.account_defender_assessment.labels # Account defender labels
510
511
# Fraud Prevention
512
assessment.fraud_prevention_assessment.transaction_risk # Transaction risk score
513
```
514
515
### CEL Operators and Functions
516
517
```python
518
# Comparison operators
519
assessment.risk_analysis.score < 0.5
520
assessment.risk_analysis.score >= 0.3
521
522
# Logical operators
523
condition1 && condition2
524
condition1 || condition2
525
!condition
526
527
# String operations
528
assessment.event.user_agent.contains('bot')
529
assessment.event.user_ip_address.startsWith('192.168.')
530
assessment.token_properties.hostname.endsWith('.example.com')
531
532
# List operations
533
assessment.risk_analysis.reasons.contains('SUSPICIOUS_ACTIVITY')
534
assessment.account_defender_assessment.labels.size() > 0
535
```
536
537
## Error Handling
538
539
```python
540
from google.api_core import exceptions
541
542
try:
543
policy = client.create_firewall_policy(request=request)
544
except exceptions.InvalidArgument as e:
545
print(f"Invalid policy configuration: {e}")
546
# Check CEL condition syntax, path patterns, action configuration
547
except exceptions.AlreadyExists as e:
548
print(f"Policy with this path already exists: {e}")
549
except exceptions.PermissionDenied as e:
550
print(f"Insufficient permissions: {e}")
551
552
try:
553
client.reorder_firewall_policies(parent=parent, names=policy_names)
554
except exceptions.InvalidArgument as e:
555
print(f"Invalid policy names or order: {e}")
556
# Ensure all policies exist and names are correct
557
```
558
559
## Best Practices
560
561
### Policy Design
562
- Use specific path patterns to avoid unintended matches
563
- Test conditions thoroughly before deploying to production
564
- Implement gradual rollout for new policies
565
- Monitor policy performance and effectiveness
566
567
### Condition Writing
568
- Keep conditions simple and readable
569
- Use meaningful variable names in complex expressions
570
- Test edge cases and boundary conditions
571
- Document complex condition logic
572
573
### Action Configuration
574
- Use allow actions explicitly for transparency
575
- Combine multiple actions when needed (headers + allow/block)
576
- Consider user experience impact of block/redirect actions
577
- Implement proper error handling for blocked requests
578
579
### Policy Management
580
- Use descriptive names and documentation
581
- Implement proper ordering based on specificity
582
- Regular review and cleanup of unused policies
583
- Monitor logs for policy effectiveness and false positives