-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_model_serialization.py
More file actions
322 lines (270 loc) · 12.3 KB
/
test_model_serialization.py
File metadata and controls
322 lines (270 loc) · 12.3 KB
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
"""Tests for model serialization, particularly handling frozensets with nested Pydantic models."""
from datetime import timedelta
import entities
import sso
from access_control import AccessRequestDecision, ApproveRequestDecision, DecisionReason
from events import (
Event,
GroupRevokeEvent,
RevokeEvent,
ScheduledGroupRevokeEvent,
ScheduledRevokeEvent,
)
from statement import Statement, GroupStatement
class TestModelSerialization:
"""Test that Pydantic models can be serialized to dict without errors."""
def test_access_request_decision_with_statements_dict_serialization(self):
"""Test that AccessRequestDecision.dict() works with frozenset of Statement objects."""
statement = Statement.model_validate(
{
"resource_type": "Account",
"resource": ["123456789012"],
"permission_set": ["AdminAccess"],
"approvers": ["approver@example.com"],
"allow_self_approval": True,
}
)
decision = AccessRequestDecision(
grant=True,
reason=DecisionReason.SelfApproval,
based_on_statements=frozenset([statement]),
approvers=frozenset(["approver@example.com"]),
)
# This should not raise TypeError: unhashable type: 'dict'
result = decision.dict()
assert isinstance(result, dict)
assert result["grant"] is True
assert result["reason"] == DecisionReason.SelfApproval.value
assert "based_on_statements" in result
# Frozensets are converted to lists for JSON serialization
assert isinstance(result["based_on_statements"], list)
assert len(result["based_on_statements"]) == 1
def test_approve_request_decision_with_statements_dict_serialization(self):
"""Test that ApproveRequestDecision.dict() works with frozenset of Statement objects."""
statement = Statement.model_validate(
{
"resource_type": "Account",
"resource": ["123456789012"],
"permission_set": ["AdminAccess"],
"approvers": ["approver@example.com"],
"allow_self_approval": False,
}
)
decision = ApproveRequestDecision(
grant=True,
permit=True,
based_on_statements=frozenset([statement]),
)
# This should not raise TypeError: unhashable type: 'dict'
result = decision.dict()
assert isinstance(result, dict)
assert result["grant"] is True
assert result["permit"] is True
assert "based_on_statements" in result
assert isinstance(result["based_on_statements"], list)
assert len(result["based_on_statements"]) == 1
def test_access_request_decision_with_group_statements_dict_serialization(self):
"""Test that AccessRequestDecision.dict() works with frozenset of GroupStatement objects."""
group_statement = GroupStatement.model_validate(
{
"resource": ["11111111-2222-3333-4444-555555555555"],
"approvers": ["approver@example.com"],
"allow_self_approval": True,
}
)
decision = AccessRequestDecision(
grant=False,
reason=DecisionReason.RequiresApproval,
based_on_statements=frozenset([group_statement]),
approvers=frozenset(["approver@example.com"]),
)
# This should not raise TypeError: unhashable type: 'dict'
result = decision.dict()
assert isinstance(result, dict)
assert result["grant"] is False
assert result["reason"] == DecisionReason.RequiresApproval.value
assert "based_on_statements" in result
assert isinstance(result["based_on_statements"], list)
assert len(result["based_on_statements"]) == 1
def test_access_request_decision_with_multiple_statements(self):
"""Test serialization with multiple statements in the frozenset."""
statements = frozenset(
[
Statement.model_validate(
{
"resource_type": "Account",
"resource": ["123456789012"],
"permission_set": ["AdminAccess"],
"approvers": ["approver1@example.com"],
"allow_self_approval": True,
}
),
Statement.model_validate(
{
"resource_type": "Account",
"resource": ["987654321098"],
"permission_set": ["ReadOnlyAccess"],
"approvers": ["approver2@example.com"],
"allow_self_approval": False,
}
),
]
)
decision = AccessRequestDecision(
grant=False,
reason=DecisionReason.RequiresApproval,
based_on_statements=statements,
approvers=frozenset(["approver1@example.com", "approver2@example.com"]),
)
# This should not raise TypeError: unhashable type: 'dict'
result = decision.dict()
assert isinstance(result, dict)
assert isinstance(result["based_on_statements"], list)
assert len(result["based_on_statements"]) == 2
assert isinstance(result["approvers"], list)
assert len(result["approvers"]) == 2
def test_statement_dict_serialization(self):
"""Test that Statement.dict() works correctly."""
statement = Statement.model_validate(
{
"resource_type": "Account",
"resource": ["123456789012", "*"],
"permission_set": ["AdminAccess", "PowerUserAccess"],
"approvers": ["approver@example.com", "admin@example.com"],
"allow_self_approval": True,
"approval_is_not_required": False,
}
)
result = statement.dict()
assert isinstance(result, dict)
assert result["resource_type"] == "Account"
assert isinstance(result["resource"], list)
assert isinstance(result["permission_set"], list)
assert isinstance(result["approvers"], list)
assert result["allow_self_approval"] is True
assert result["approval_is_not_required"] is False
def test_group_statement_dict_serialization(self):
"""Test that GroupStatement.dict() works correctly."""
group_statement = GroupStatement.model_validate(
{
"resource": ["11111111-2222-3333-4444-555555555555"],
"approvers": ["approver@example.com"],
"allow_self_approval": False,
"approval_is_not_required": True,
}
)
result = group_statement.dict()
assert isinstance(result, dict)
assert isinstance(result["resource"], list)
assert isinstance(result["approvers"], list)
assert result["allow_self_approval"] is False
assert result["approval_is_not_required"] is True
class TestRevokeEventSerialization:
"""Test that RevokeEvent and GroupRevokeEvent serialize thread_ts correctly through EventBridge payload."""
def _sample_user(self):
return entities.slack.User(email="user@example.com", id="U123", real_name="Test User")
def _sample_user_account_assignment(self):
return sso.UserAccountAssignment(
instance_arn="arn:aws:sso:::instance/ssoins-123",
account_id="123456789012",
permission_set_arn="arn:aws:sso:::permissionSet/ssoins-123/ps-123",
user_principal_id="user-principal-123",
)
def _sample_group_assignment(self):
return sso.GroupAssignment(
identity_store_id="d-123456789",
group_name="TestGroup",
group_id="group-123",
user_principal_id="user-principal-123",
membership_id="membership-123",
)
def test_revoke_event_with_thread_ts_json_roundtrip(self):
"""Test RevokeEvent preserves thread_ts through JSON serialization (EventBridge payload)."""
event = RevokeEvent(
schedule_name="test-schedule",
approver=self._sample_user(),
requester=self._sample_user(),
user_account_assignment=self._sample_user_account_assignment(),
permission_duration=timedelta(hours=1),
thread_ts="1234567890.123456",
)
# Serialize to JSON (mimics EventBridge payload)
json_str = event.json()
# Deserialize back
restored = RevokeEvent.model_validate_json(json_str)
assert restored.thread_ts == "1234567890.123456"
def test_revoke_event_without_thread_ts_backward_compat(self):
"""Test RevokeEvent works without thread_ts (older scheduled jobs)."""
# JSON without thread_ts field (simulates older scheduled jobs)
event = RevokeEvent(
schedule_name="test-schedule",
approver=self._sample_user(),
requester=self._sample_user(),
user_account_assignment=self._sample_user_account_assignment(),
permission_duration=timedelta(hours=1),
)
json_str = event.json()
restored = RevokeEvent.model_validate_json(json_str)
assert restored.thread_ts is None
def test_group_revoke_event_with_thread_ts_json_roundtrip(self):
"""Test GroupRevokeEvent preserves thread_ts through JSON serialization."""
event = GroupRevokeEvent(
schedule_name="test-schedule",
approver=self._sample_user(),
requester=self._sample_user(),
group_assignment=self._sample_group_assignment(),
permission_duration=timedelta(hours=1),
thread_ts="1234567890.654321",
)
json_str = event.json()
restored = GroupRevokeEvent.model_validate_json(json_str)
assert restored.thread_ts == "1234567890.654321"
def test_group_revoke_event_without_thread_ts_backward_compat(self):
"""Test GroupRevokeEvent works without thread_ts (older scheduled jobs)."""
event = GroupRevokeEvent(
schedule_name="test-schedule",
approver=self._sample_user(),
requester=self._sample_user(),
group_assignment=self._sample_group_assignment(),
permission_duration=timedelta(hours=1),
)
json_str = event.json()
restored = GroupRevokeEvent.model_validate_json(json_str)
assert restored.thread_ts is None
def test_scheduled_revoke_event_parses_thread_ts_from_nested_json(self):
"""Test ScheduledRevokeEvent model_validator preserves thread_ts from JSON string."""
revoke_event = RevokeEvent(
schedule_name="test-schedule",
approver=self._sample_user(),
requester=self._sample_user(),
user_account_assignment=self._sample_user_account_assignment(),
permission_duration=timedelta(hours=1),
thread_ts="1234567890.999999",
)
# This mimics the EventBridge payload structure where revoke_event is a JSON string
payload = {
"action": "event_bridge_revoke",
"revoke_event": revoke_event.json(),
}
# Parse using Event (the root model used in revoker.py)
parsed = Event.model_validate(payload)
assert isinstance(parsed.root, ScheduledRevokeEvent)
assert parsed.root.revoke_event.thread_ts == "1234567890.999999"
def test_scheduled_group_revoke_event_parses_thread_ts_from_nested_json(self):
"""Test ScheduledGroupRevokeEvent model_validator preserves thread_ts from JSON string."""
group_revoke_event = GroupRevokeEvent(
schedule_name="test-schedule",
approver=self._sample_user(),
requester=self._sample_user(),
group_assignment=self._sample_group_assignment(),
permission_duration=timedelta(hours=1),
thread_ts="1234567890.111111",
)
# This mimics the EventBridge payload structure
payload = {
"action": "event_bridge_group_revoke",
"revoke_event": group_revoke_event.json(),
}
parsed = Event.model_validate(payload)
assert isinstance(parsed.root, ScheduledGroupRevokeEvent)
assert parsed.root.revoke_event.thread_ts == "1234567890.111111"