0
# IAM Policy Management
1
2
Identity and Access Management (IAM) operations for BigQuery Connection resources. These operations allow you to manage access control policies, check permissions, and secure connection resources using Google Cloud IAM.
3
4
## Capabilities
5
6
### Getting IAM Policies
7
8
Retrieves the current IAM policy for a connection resource.
9
10
```python { .api }
11
def get_iam_policy(
12
request: GetIamPolicyRequest = None,
13
*,
14
resource: str = None,
15
retry: OptionalRetry = DEFAULT,
16
timeout: Union[float, object] = DEFAULT,
17
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
18
) -> Policy:
19
"""
20
Gets the access control policy for a connection resource.
21
22
Parameters:
23
- request: The request object containing resource and options
24
- resource: Required. Resource name of the connection in format 'projects/{project_id}/locations/{location_id}/connections/{connection_id}'
25
- retry: Retry configuration for the request
26
- timeout: Timeout for the request in seconds
27
- metadata: Additional metadata to send with the request
28
29
Returns:
30
Policy: The IAM policy for the resource
31
32
Raises:
33
google.api_core.exceptions.NotFound: If the connection does not exist
34
google.api_core.exceptions.PermissionDenied: If caller lacks permission to get the policy
35
google.api_core.exceptions.GoogleAPICallError: If the request fails
36
"""
37
```
38
39
**Usage Example:**
40
41
```python
42
from google.cloud.bigquery_connection import ConnectionServiceClient
43
44
client = ConnectionServiceClient()
45
46
# Get IAM policy for a connection
47
resource = "projects/my-project/locations/us-central1/connections/my-connection"
48
policy = client.get_iam_policy(resource=resource)
49
50
print(f"Policy version: {policy.version}")
51
print(f"ETag: {policy.etag}")
52
print("Bindings:")
53
for binding in policy.bindings:
54
print(f" Role: {binding.role}")
55
print(f" Members: {', '.join(binding.members)}")
56
if binding.condition:
57
print(f" Condition: {binding.condition.expression}")
58
```
59
60
### Setting IAM Policies
61
62
Sets the IAM policy for a connection resource, replacing any existing policy.
63
64
```python { .api }
65
def set_iam_policy(
66
request: SetIamPolicyRequest = None,
67
*,
68
resource: str = None,
69
policy: Policy = None,
70
retry: OptionalRetry = DEFAULT,
71
timeout: Union[float, object] = DEFAULT,
72
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
73
) -> Policy:
74
"""
75
Sets the access control policy for a connection resource.
76
77
Parameters:
78
- request: The request object containing resource and policy
79
- resource: Required. Resource name of the connection
80
- policy: Required. The policy to be applied to the resource
81
- retry: Retry configuration for the request
82
- timeout: Timeout for the request in seconds
83
- metadata: Additional metadata to send with the request
84
85
Returns:
86
Policy: The updated IAM policy
87
88
Raises:
89
google.api_core.exceptions.NotFound: If the connection does not exist
90
google.api_core.exceptions.PermissionDenied: If caller lacks permission to set the policy
91
google.api_core.exceptions.InvalidArgument: If the policy is invalid
92
google.api_core.exceptions.GoogleAPICallError: If the request fails
93
"""
94
```
95
96
**Usage Example:**
97
98
```python
99
from google.cloud.bigquery_connection import ConnectionServiceClient
100
from google.iam.v1 import policy_pb2
101
102
client = ConnectionServiceClient()
103
resource = "projects/my-project/locations/us-central1/connections/my-connection"
104
105
# Get current policy
106
current_policy = client.get_iam_policy(resource=resource)
107
108
# Create new policy with additional binding
109
new_policy = policy_pb2.Policy()
110
new_policy.version = current_policy.version
111
new_policy.etag = current_policy.etag
112
113
# Copy existing bindings
114
for binding in current_policy.bindings:
115
new_binding = new_policy.bindings.add()
116
new_binding.role = binding.role
117
new_binding.members[:] = binding.members
118
if binding.condition:
119
new_binding.condition.CopyFrom(binding.condition)
120
121
# Add new binding for BigQuery Connection User role
122
new_binding = new_policy.bindings.add()
123
new_binding.role = "roles/bigquery.connectionUser"
124
new_binding.members.append("user:analyst@example.com")
125
new_binding.members.append("group:data-team@example.com")
126
127
# Set the updated policy
128
updated_policy = client.set_iam_policy(
129
resource=resource,
130
policy=new_policy
131
)
132
133
print(f"Updated policy version: {updated_policy.version}")
134
```
135
136
### Advanced Policy Management
137
138
**Using SetIamPolicyRequest for Full Control:**
139
140
```python
141
from google.iam.v1 import iam_policy_pb2, policy_pb2
142
143
# Create SetIamPolicyRequest for more control
144
request = iam_policy_pb2.SetIamPolicyRequest()
145
request.resource = resource
146
147
# Build policy with conditional binding
148
policy = policy_pb2.Policy()
149
policy.version = 3 # Required for conditions
150
151
# Add conditional binding
152
binding = policy.bindings.add()
153
binding.role = "roles/bigquery.connectionUser"
154
binding.members.append("user:temp-analyst@example.com")
155
156
# Add condition (access only during business hours)
157
condition = binding.condition
158
condition.title = "Business hours only"
159
condition.description = "Access restricted to business hours (9 AM - 5 PM UTC)"
160
condition.expression = '''
161
request.time.getHours() >= 9 && request.time.getHours() < 17
162
'''
163
164
request.policy.CopyFrom(policy)
165
166
# Set policy with condition
167
updated_policy = client.set_iam_policy(request=request)
168
```
169
170
### Testing IAM Permissions
171
172
Tests whether the caller has the specified permissions on a connection resource.
173
174
```python { .api }
175
def test_iam_permissions(
176
request: TestIamPermissionsRequest = None,
177
*,
178
resource: str = None,
179
permissions: Optional[MutableSequence[str]] = None,
180
retry: OptionalRetry = DEFAULT,
181
timeout: Union[float, object] = DEFAULT,
182
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
183
) -> TestIamPermissionsResponse:
184
"""
185
Tests whether the caller has the specified permissions on a connection resource.
186
187
Parameters:
188
- request: The request object containing resource and permissions to test
189
- resource: Required. Resource name of the connection
190
- permissions: Required. List of permissions to test
191
- retry: Retry configuration for the request
192
- timeout: Timeout for the request in seconds
193
- metadata: Additional metadata to send with the request
194
195
Returns:
196
TestIamPermissionsResponse: The permissions that the caller has
197
198
Raises:
199
google.api_core.exceptions.NotFound: If the connection does not exist
200
google.api_core.exceptions.GoogleAPICallError: If the request fails
201
"""
202
```
203
204
**Usage Example:**
205
206
```python
207
from google.cloud.bigquery_connection import ConnectionServiceClient
208
209
client = ConnectionServiceClient()
210
resource = "projects/my-project/locations/us-central1/connections/my-connection"
211
212
# Test specific permissions
213
permissions_to_test = [
214
"bigquery.connections.get",
215
"bigquery.connections.update",
216
"bigquery.connections.delete",
217
"bigquery.connections.use"
218
]
219
220
response = client.test_iam_permissions(
221
resource=resource,
222
permissions=permissions_to_test
223
)
224
225
print("Permissions granted:")
226
for permission in response.permissions:
227
print(f" - {permission}")
228
229
# Check if specific permission is granted
230
if "bigquery.connections.use" in response.permissions:
231
print("✓ Can use this connection")
232
else:
233
print("✗ Cannot use this connection")
234
```
235
236
### Batch Permission Testing
237
238
```python
239
# Test permissions on multiple connections
240
connections = [
241
"projects/my-project/locations/us-central1/connections/conn-1",
242
"projects/my-project/locations/us-central1/connections/conn-2",
243
"projects/my-project/locations/us-central1/connections/conn-3"
244
]
245
246
permissions_to_test = ["bigquery.connections.use", "bigquery.connections.get"]
247
248
for resource in connections:
249
try:
250
response = client.test_iam_permissions(
251
resource=resource,
252
permissions=permissions_to_test
253
)
254
print(f"{resource}: {len(response.permissions)}/{len(permissions_to_test)} permissions")
255
except Exception as e:
256
print(f"{resource}: Error - {e}")
257
```
258
259
## Common IAM Roles for BigQuery Connections
260
261
### Predefined Roles
262
263
**BigQuery Connection Admin (`roles/bigquery.connectionAdmin`)**
264
- Full control over connections including create, read, update, delete
265
- Can manage IAM policies for connections
266
- Can use connections in BigQuery queries
267
268
**BigQuery Connection User (`roles/bigquery.connectionUser`)**
269
- Can use existing connections in BigQuery queries
270
- Cannot create, modify, or delete connections
271
- Cannot view connection credentials
272
273
**BigQuery Data Editor (`roles/bigquery.dataEditor`)**
274
- Can use connections for data manipulation
275
- Can create and manage datasets that use connections
276
277
**BigQuery Data Viewer (`roles/bigquery.dataViewer`)**
278
- Can use connections for read-only queries
279
- Cannot modify data through connections
280
281
### Connection-Specific Permissions
282
283
```python
284
# Core connection permissions
285
CONNECTION_PERMISSIONS = [
286
"bigquery.connections.create", # Create new connections
287
"bigquery.connections.delete", # Delete connections
288
"bigquery.connections.get", # Read connection metadata
289
"bigquery.connections.list", # List connections in a location
290
"bigquery.connections.update", # Modify connection configuration
291
"bigquery.connections.use", # Use connection in BigQuery queries
292
]
293
294
# IAM management permissions
295
IAM_PERMISSIONS = [
296
"bigquery.connections.getIamPolicy", # Read IAM policy
297
"bigquery.connections.setIamPolicy", # Modify IAM policy
298
]
299
```
300
301
## Security Best Practices
302
303
### Principle of Least Privilege
304
305
```python
306
# Grant minimal permissions needed
307
# For analysts who only need to query data:
308
analyst_policy = {
309
"role": "roles/bigquery.connectionUser",
310
"members": ["group:analysts@example.com"]
311
}
312
313
# For data engineers who manage connections:
314
admin_policy = {
315
"role": "roles/bigquery.connectionAdmin",
316
"members": ["group:data-engineers@example.com"]
317
}
318
```
319
320
### Conditional Access
321
322
```python
323
# Time-based access restrictions
324
time_condition = {
325
"title": "Business hours only",
326
"description": "Access restricted to 9 AM - 5 PM UTC weekdays",
327
"expression": '''
328
request.time.getHours() >= 9 &&
329
request.time.getHours() < 17 &&
330
request.time.getDayOfWeek() >= 1 &&
331
request.time.getDayOfWeek() <= 5
332
'''
333
}
334
335
# IP-based access restrictions
336
ip_condition = {
337
"title": "Corporate network only",
338
"description": "Access restricted to corporate IP ranges",
339
"expression": '''
340
inIpRange(origin.ip, '10.0.0.0/16') ||
341
inIpRange(origin.ip, '192.168.1.0/24')
342
'''
343
}
344
```
345
346
### Regular Policy Auditing
347
348
```python
349
def audit_connection_policies(project_id: str, location: str):
350
"""Audit IAM policies for all connections."""
351
client = ConnectionServiceClient()
352
parent = f"projects/{project_id}/locations/{location}"
353
354
connections = client.list_connections(parent=parent)
355
356
for connection in connections:
357
policy = client.get_iam_policy(resource=connection.name)
358
359
print(f"Connection: {connection.friendly_name}")
360
print(f" Policy version: {policy.version}")
361
print(f" Bindings: {len(policy.bindings)}")
362
363
for binding in policy.bindings:
364
print(f" Role: {binding.role}")
365
print(f" Members: {len(binding.members)}")
366
if binding.condition:
367
print(f" Condition: {binding.condition.title}")
368
```
369
370
## Types
371
372
### Request Types
373
374
```python { .api }
375
from google.iam.v1 import iam_policy_pb2
376
377
class GetIamPolicyRequest:
378
"""Request message for GetIamPolicy method."""
379
resource: str # Required. Resource name of the connection
380
options: GetPolicyOptions # Optional. Policy format options
381
382
class SetIamPolicyRequest:
383
"""Request message for SetIamPolicy method."""
384
resource: str # Required. Resource name of the connection
385
policy: Policy # Required. The policy to be applied
386
update_mask: FieldMask # Optional. Update mask for partial updates
387
388
class TestIamPermissionsRequest:
389
"""Request message for TestIamPermissions method."""
390
resource: str # Required. Resource name of the connection
391
permissions: MutableSequence[str] # Required. Permissions to test
392
```
393
394
### Response Types
395
396
```python { .api }
397
from google.iam.v1 import policy_pb2, iam_policy_pb2
398
399
class Policy:
400
"""IAM policy for a resource."""
401
version: int # Policy format version
402
bindings: MutableSequence[Binding] # Access control bindings
403
audit_configs: MutableSequence[AuditConfig] # Audit configuration
404
etag: bytes # Version identifier for optimistic concurrency
405
406
class Binding:
407
"""Associates members with a role."""
408
role: str # IAM role (e.g., "roles/bigquery.connectionUser")
409
members: MutableSequence[str] # List of identities
410
condition: Expr # Optional condition for conditional binding
411
412
class TestIamPermissionsResponse:
413
"""Response message for TestIamPermissions method."""
414
permissions: MutableSequence[str] # Permissions that the caller has
415
```
416
417
### Member Identity Formats
418
419
```python
420
# User accounts
421
"user:analyst@example.com"
422
423
# Service accounts
424
"serviceAccount:bigquery-sa@my-project.iam.gserviceaccount.com"
425
426
# Google Groups
427
"group:data-team@example.com"
428
429
# Google Workspace domains
430
"domain:example.com"
431
432
# All authenticated users
433
"allAuthenticatedUsers"
434
435
# Public access (not recommended for connections)
436
"allUsers"
437
```