0
# Audit and Logging
1
2
Support for audit trails and policy change tracking through specialized message types designed for logging IAM operations and policy modifications. These types enable comprehensive audit logging of IAM policy changes and access control events.
3
4
## Capabilities
5
6
### Audit Data Structure
7
8
Main audit data message containing policy changes for logging purposes.
9
10
```python { .api }
11
class AuditData:
12
"""
13
Audit data containing IAM policy changes for logging.
14
15
Attributes:
16
policy_delta (PolicyDelta): The policy changes being audited
17
"""
18
policy_delta: PolicyDelta
19
```
20
21
### Policy Change Tracking
22
23
Comprehensive tracking of changes made to IAM policies including binding modifications and audit configuration updates.
24
25
```python { .api }
26
class PolicyDelta:
27
"""
28
Represents a complete set of changes to an IAM policy.
29
30
Attributes:
31
binding_deltas (List[BindingDelta]): Changes to role bindings
32
audit_config_deltas (List[AuditConfigDelta]): Changes to audit configurations
33
"""
34
binding_deltas: List[BindingDelta]
35
audit_config_deltas: List[AuditConfigDelta]
36
```
37
38
### Binding Change Tracking
39
40
Tracks additions and removals of members from role bindings, including conditional access changes.
41
42
```python { .api }
43
class BindingDelta:
44
"""
45
Represents a change to a role binding in an IAM policy.
46
47
Attributes:
48
action (Action): Whether this is an ADD or REMOVE operation
49
role (str): The role being modified (e.g., "roles/viewer")
50
member (str): The member being added or removed (e.g., "user:alice@example.com")
51
condition (google.type.Expr): Optional conditional logic for the binding
52
"""
53
action: Action
54
role: str
55
member: str
56
condition: google.type.Expr
57
```
58
59
### Audit Configuration Change Tracking
60
61
Tracks changes to audit logging configurations for services.
62
63
```python { .api }
64
class AuditConfigDelta:
65
"""
66
Represents a change to audit configuration in an IAM policy.
67
68
Attributes:
69
action (Action): Whether this is an ADD or REMOVE operation
70
service (str): Service name (e.g., "storage.googleapis.com")
71
exempted_member (str): Member being added/removed from exemption list
72
log_type (str): Type of audit log being modified
73
"""
74
action: Action
75
service: str
76
exempted_member: str
77
log_type: str
78
```
79
80
### Action Types
81
82
Enumeration of actions that can be performed on policy elements.
83
84
```python { .api }
85
class Action:
86
"""
87
Types of actions that can be performed on policy elements.
88
"""
89
ACTION_UNSPECIFIED = 0 # Unspecified action
90
ADD = 1 # Add the element
91
REMOVE = 2 # Remove the element
92
```
93
94
### Resource Policy Members
95
96
Information about IAM policy principals for resource-specific policies.
97
98
```python { .api }
99
class ResourcePolicyMember:
100
"""
101
Contains information about IAM policy members for resource-specific policies.
102
103
Attributes:
104
iam_policy_name_principal (str): Principal name (output only)
105
iam_policy_uid_principal (str): Principal unique identifier (output only)
106
"""
107
iam_policy_name_principal: str # output only
108
iam_policy_uid_principal: str # output only
109
```
110
111
## Usage Examples
112
113
### Creating Audit Data for Policy Changes
114
115
```python
116
from google.iam.v1.logging import audit_data_pb2
117
from google.iam.v1 import policy_pb2
118
119
# Create audit data for a binding change
120
audit_data = audit_data_pb2.AuditData()
121
122
# Create policy delta
123
policy_delta = policy_pb2.PolicyDelta()
124
125
# Add binding delta for adding a new member
126
binding_delta = policy_pb2.BindingDelta()
127
binding_delta.action = policy_pb2.BindingDelta.Action.ADD
128
binding_delta.role = "roles/viewer"
129
binding_delta.member = "user:newuser@example.com"
130
policy_delta.binding_deltas.append(binding_delta)
131
132
# Add binding delta for removing a member
133
remove_delta = policy_pb2.BindingDelta()
134
remove_delta.action = policy_pb2.BindingDelta.Action.REMOVE
135
remove_delta.role = "roles/editor"
136
remove_delta.member = "user:olduser@example.com"
137
policy_delta.binding_deltas.append(remove_delta)
138
139
# Add audit config delta
140
audit_config_delta = policy_pb2.AuditConfigDelta()
141
audit_config_delta.action = policy_pb2.AuditConfigDelta.Action.ADD
142
audit_config_delta.service = "pubsub.googleapis.com"
143
audit_config_delta.log_type = "DATA_READ"
144
audit_config_delta.exempted_member = "serviceAccount:backup@project.iam.gserviceaccount.com"
145
policy_delta.audit_config_deltas.append(audit_config_delta)
146
147
# Set the policy delta in audit data
148
audit_data.policy_delta.CopyFrom(policy_delta)
149
150
print(f"Audit data created with {len(audit_data.policy_delta.binding_deltas)} binding changes")
151
print(f"and {len(audit_data.policy_delta.audit_config_deltas)} audit config changes")
152
```
153
154
### Logging Policy Changes with Conditions
155
156
```python
157
from google.iam.v1.logging import audit_data_pb2
158
from google.iam.v1 import policy_pb2
159
from google.type import expr_pb2
160
161
# Create audit data for conditional binding change
162
audit_data = audit_data_pb2.AuditData()
163
policy_delta = policy_pb2.PolicyDelta()
164
165
# Add conditional binding delta
166
binding_delta = policy_pb2.BindingDelta()
167
binding_delta.action = policy_pb2.BindingDelta.Action.ADD
168
binding_delta.role = "roles/storage.objectViewer"
169
binding_delta.member = "user:contractor@example.com"
170
171
# Add condition for temporary access
172
condition = expr_pb2.Expr()
173
condition.title = "Temporary access"
174
condition.description = "Access expires at end of month"
175
condition.expression = '''
176
request.time < timestamp("2024-01-01T00:00:00Z")
177
'''
178
binding_delta.condition.CopyFrom(condition)
179
180
policy_delta.binding_deltas.append(binding_delta)
181
audit_data.policy_delta.CopyFrom(policy_delta)
182
183
print("Conditional binding change logged for audit")
184
```
185
186
### Tracking Multiple Policy Changes
187
188
```python
189
from google.iam.v1.logging import audit_data_pb2
190
from google.iam.v1 import policy_pb2
191
192
def create_comprehensive_audit_log(changes):
193
"""Create audit data for multiple policy changes."""
194
195
audit_data = audit_data_pb2.AuditData()
196
policy_delta = policy_pb2.PolicyDelta()
197
198
# Process binding changes
199
for change in changes.get('bindings', []):
200
binding_delta = policy_pb2.BindingDelta()
201
binding_delta.action = (
202
policy_pb2.BindingDelta.Action.ADD if change['action'] == 'add'
203
else policy_pb2.BindingDelta.Action.REMOVE
204
)
205
binding_delta.role = change['role']
206
binding_delta.member = change['member']
207
policy_delta.binding_deltas.append(binding_delta)
208
209
# Process audit config changes
210
for change in changes.get('audit_configs', []):
211
audit_delta = policy_pb2.AuditConfigDelta()
212
audit_delta.action = (
213
policy_pb2.AuditConfigDelta.Action.ADD if change['action'] == 'add'
214
else policy_pb2.AuditConfigDelta.Action.REMOVE
215
)
216
audit_delta.service = change['service']
217
audit_delta.log_type = change['log_type']
218
if 'exempted_member' in change:
219
audit_delta.exempted_member = change['exempted_member']
220
policy_delta.audit_config_deltas.append(audit_delta)
221
222
audit_data.policy_delta.CopyFrom(policy_delta)
223
return audit_data
224
225
# Example usage
226
changes = {
227
'bindings': [
228
{
229
'action': 'add',
230
'role': 'roles/viewer',
231
'member': 'user:alice@example.com'
232
},
233
{
234
'action': 'remove',
235
'role': 'roles/editor',
236
'member': 'user:bob@example.com'
237
}
238
],
239
'audit_configs': [
240
{
241
'action': 'add',
242
'service': 'storage.googleapis.com',
243
'log_type': 'DATA_READ',
244
'exempted_member': 'serviceAccount:reader@project.iam.gserviceaccount.com'
245
}
246
]
247
}
248
249
audit_data = create_comprehensive_audit_log(changes)
250
print(f"Created audit log with {len(audit_data.policy_delta.binding_deltas)} binding changes")
251
```
252
253
### Integrating with Logging Systems
254
255
```python
256
import json
257
import logging
258
from google.iam.v1.logging import audit_data_pb2
259
from google.iam.v1 import policy_pb2
260
from google.protobuf.json_format import MessageToDict
261
262
# Set up logging
263
logging.basicConfig(level=logging.INFO)
264
audit_logger = logging.getLogger('iam_audit')
265
266
def log_policy_change(resource_name, audit_data):
267
"""Log policy changes in structured format."""
268
269
# Convert protobuf to dictionary for JSON logging
270
audit_dict = MessageToDict(audit_data)
271
272
log_entry = {
273
'timestamp': '2024-01-15T10:30:00Z',
274
'resource': resource_name,
275
'event_type': 'iam_policy_change',
276
'audit_data': audit_dict,
277
'change_count': {
278
'binding_changes': len(audit_data.policy_delta.binding_deltas),
279
'audit_config_changes': len(audit_data.policy_delta.audit_config_deltas)
280
}
281
}
282
283
# Log as structured JSON
284
audit_logger.info(json.dumps(log_entry, indent=2))
285
286
# Example usage
287
audit_data = audit_data_pb2.AuditData()
288
policy_delta = policy_pb2.PolicyDelta()
289
290
binding_delta = policy_pb2.BindingDelta()
291
binding_delta.action = policy_pb2.BindingDelta.Action.ADD
292
binding_delta.role = "roles/viewer"
293
binding_delta.member = "user:alice@example.com"
294
policy_delta.binding_deltas.append(binding_delta)
295
296
audit_data.policy_delta.CopyFrom(policy_delta)
297
298
log_policy_change("projects/my-project/topics/my-topic", audit_data)
299
```
300
301
### Resource Policy Member Tracking
302
303
```python
304
from google.iam.v1 import resource_policy_member_pb2
305
306
# Track resource policy members (typically used in responses)
307
def display_policy_members(members):
308
"""Display resource policy member information."""
309
310
for member in members:
311
member_info = resource_policy_member_pb2.ResourcePolicyMember()
312
member_info.iam_policy_name_principal = member.get('name', '')
313
member_info.iam_policy_uid_principal = member.get('uid', '')
314
315
print(f"Principal: {member_info.iam_policy_name_principal}")
316
print(f"UID: {member_info.iam_policy_uid_principal}")
317
318
# Example member data (would come from service response)
319
member_data = [
320
{'name': 'user:alice@example.com', 'uid': '123456789'},
321
{'name': 'serviceAccount:app@project.iam.gserviceaccount.com', 'uid': '987654321'}
322
]
323
324
display_policy_members(member_data)
325
```