0
# IAM Policy Management
1
2
Non-API-specific IAM (Identity and Access Management) policy definitions for Google Cloud Platform services. This module provides a high-level abstraction for managing IAM policies, including role bindings, member management, and conditional access controls across Google Cloud resources.
3
4
## Capabilities
5
6
### Policy Management
7
8
Core IAM policy representation and manipulation with support for role bindings, member management, and policy versioning.
9
10
```python { .api }
11
class Policy:
12
def __init__(self, etag=None, version=None): ...
13
14
@property
15
def bindings(self): ...
16
17
@bindings.setter
18
def bindings(self, value): ...
19
20
# Dictionary interface (version 1 only)
21
def __getitem__(self, key): ...
22
def __setitem__(self, key, value): ...
23
def __delitem__(self, key): ...
24
def __iter__(self): ...
25
def __len__(self): ...
26
```
27
28
### Policy Serialization
29
30
Methods for converting between Policy objects and Google Cloud IAM API representations.
31
32
```python { .api }
33
@classmethod
34
def from_api_repr(cls, resource): ...
35
36
def to_api_repr(self): ...
37
```
38
39
### Member Factory Methods
40
41
Static methods for creating properly formatted member identifiers for different identity types.
42
43
```python { .api }
44
@staticmethod
45
def user(email): ...
46
47
@staticmethod
48
def service_account(email): ...
49
50
@staticmethod
51
def group(email): ...
52
53
@staticmethod
54
def domain(domain): ...
55
56
@staticmethod
57
def all_users(): ...
58
59
@staticmethod
60
def authenticated_users(): ...
61
```
62
63
### Usage Examples
64
65
#### Basic Policy Creation and Management
66
67
```python
68
from google.api_core import iam
69
70
# Create a new policy
71
policy = iam.Policy()
72
73
# Add role bindings using the bindings property
74
policy.bindings = [
75
{
76
"role": "roles/viewer",
77
"members": {
78
iam.Policy.user("user@example.com"),
79
iam.Policy.group("admins@example.com"),
80
iam.Policy.all_users()
81
}
82
},
83
{
84
"role": "roles/editor",
85
"members": {
86
iam.Policy.service_account("service@project.iam.gserviceaccount.com")
87
}
88
}
89
]
90
```
91
92
#### Conditional Access Control
93
94
```python
95
# Create policy with conditional bindings (requires version 3+)
96
policy = iam.Policy(version=3)
97
policy.bindings = [
98
{
99
"role": "roles/viewer",
100
"members": {iam.Policy.user("temp-user@example.com")},
101
"condition": {
102
"title": "time_limited_access",
103
"description": "Access expires on 2024-12-31",
104
"expression": "request.time < timestamp(\"2024-12-31T23:59:59Z\")"
105
}
106
}
107
]
108
```
109
110
#### Working with API Resources
111
112
```python
113
# Convert from API response
114
api_response = {
115
"version": 1,
116
"etag": "ABC123",
117
"bindings": [
118
{
119
"role": "roles/owner",
120
"members": ["user:owner@example.com"]
121
}
122
]
123
}
124
125
policy = iam.Policy.from_api_repr(api_response)
126
127
# Modify policy
128
policy.bindings.append({
129
"role": "roles/viewer",
130
"members": {iam.Policy.user("viewer@example.com")}
131
})
132
133
# Convert back to API format
134
api_resource = policy.to_api_repr()
135
```
136
137
#### Legacy Dictionary Interface (Version 1 Only)
138
139
```python
140
# Version 1 policies support dictionary-like access
141
policy = iam.Policy(version=1)
142
143
# Set members for a role
144
policy["roles/viewer"] = {
145
iam.Policy.user("user@example.com"),
146
iam.Policy.group("viewers@example.com")
147
}
148
149
# Get members for a role
150
viewers = policy["roles/viewer"]
151
152
# Remove a role
153
del policy["roles/editor"]
154
155
# Iterate over roles
156
for role in policy:
157
print(f"Role: {role}, Members: {policy[role]}")
158
```
159
160
### Policy Versioning
161
162
IAM policy versions control available features and API compatibility.
163
164
```python { .api }
165
# Version 1 (default)
166
# - Supports dictionary-style access
167
# - No conditional bindings
168
# - Legacy properties available
169
170
# Version 3+
171
# - Required for conditional bindings
172
# - Dictionary access raises InvalidOperationException
173
# - Must use bindings property
174
```
175
176
### Exception Handling
177
178
Comprehensive error handling for policy operations and version compatibility.
179
180
```python { .api }
181
class InvalidOperationException(Exception): ...
182
```
183
184
### Version Compatibility Examples
185
186
```python
187
# Version 1 - Basic functionality
188
policy_v1 = iam.Policy(version=1)
189
policy_v1["roles/viewer"] = {iam.Policy.user("user@example.com")} # Works
190
191
# Version 3 - Conditional bindings
192
policy_v3 = iam.Policy(version=3)
193
try:
194
policy_v3["roles/viewer"] = {"user@example.com"} # Raises InvalidOperationException
195
except iam.InvalidOperationException:
196
# Must use bindings property instead
197
policy_v3.bindings = [{
198
"role": "roles/viewer",
199
"members": {iam.Policy.user("user@example.com")}
200
}]
201
```
202
203
### Member Types and Formats
204
205
Standard member identifier formats for different identity types:
206
207
```python
208
# Users
209
iam.Policy.user("user@example.com")
210
# Returns: "user:user@example.com"
211
212
# Service Accounts
213
iam.Policy.service_account("service@project.iam.gserviceaccount.com")
214
# Returns: "serviceAccount:service@project.iam.gserviceaccount.com"
215
216
# Groups
217
iam.Policy.group("admins@example.com")
218
# Returns: "group:admins@example.com"
219
220
# Domains
221
iam.Policy.domain("example.com")
222
# Returns: "domain:example.com"
223
224
# Special members
225
iam.Policy.all_users()
226
# Returns: "allUsers"
227
228
iam.Policy.authenticated_users()
229
# Returns: "allAuthenticatedUsers"
230
```
231
232
### Predefined Roles
233
234
Common IAM role constants for convenience.
235
236
```python { .api }
237
OWNER_ROLE = "roles/owner" # All rights to an object
238
EDITOR_ROLE = "roles/editor" # Rights to modify an object
239
VIEWER_ROLE = "roles/viewer" # Rights to access an object
240
```
241
242
## Import Patterns
243
244
```python
245
from google.api_core import iam
246
247
# Create policies
248
policy = iam.Policy()
249
250
# Use member factory methods
251
member = iam.Policy.user("user@example.com")
252
253
# Use predefined roles
254
policy.bindings = [{
255
"role": iam.VIEWER_ROLE,
256
"members": {member}
257
}]
258
259
# Handle exceptions
260
try:
261
policy["role"] = members # May raise InvalidOperationException
262
except iam.InvalidOperationException:
263
# Handle version compatibility issue
264
pass
265
```
266
267
## Types
268
269
```python { .api }
270
from typing import Dict, List, Optional, Set, Union
271
272
# Policy binding structure
273
PolicyBinding = Dict[str, Union[str, Set[str], Dict[str, str]]]
274
275
# Condition structure for conditional bindings
276
Condition = Dict[str, str] # Contains title, description, expression
277
278
# Member identifier types
279
MemberIdentifier = str # Formatted as "type:identifier"
280
281
# Policy resource structure for API serialization
282
PolicyResource = Dict[str, Union[int, str, List[PolicyBinding]]]
283
```
284
285
## Policy Binding Structure
286
287
### Basic Binding Format
288
```python
289
{
290
"role": "roles/viewer",
291
"members": {"user:user@example.com", "group:admins@example.com"}
292
}
293
```
294
295
### Conditional Binding Format
296
```python
297
{
298
"role": "roles/viewer",
299
"members": {"user:user@example.com"},
300
"condition": {
301
"title": "time_limited_access",
302
"description": "Access valid until year end",
303
"expression": "request.time < timestamp(\"2024-12-31T23:59:59Z\")"
304
}
305
}
306
```
307
308
## Architecture and Design Patterns
309
310
### Policy Versioning Strategy
311
- **Version 1**: Basic role-member bindings with dictionary interface
312
- **Version 3+**: Conditional bindings with restricted access patterns
313
- **Automatic Migration**: Policies automatically upgrade when conditions are added
314
315
### Member Normalization
316
- **List to Set Conversion**: Automatic conversion for de-duplication
317
- **Format Validation**: Consistent member identifier formatting
318
- **Type Safety**: Static factory methods prevent format errors
319
320
### API Integration
321
- **Seamless Serialization**: Direct conversion to/from Google Cloud IAM API formats
322
- **Resource Optimization**: Empty bindings are excluded from API calls
323
- **Sorting and Consistency**: Deterministic output for reliable API operations
324
325
### Error Handling Strategy
326
- **Version Compatibility**: Clear exceptions when using incompatible operations
327
- **Graceful Degradation**: Fallback behaviors for legacy code patterns
328
- **Validation**: Early detection of invalid policy configurations
329
330
This module provides the foundation for IAM policy management across all Google Cloud services, supporting both simple role assignments and complex conditional access scenarios.