Intercept and validate __setstate__ protocol before state restoration. This hook is called when deserializing an object that implements __setstate__, right before the state is restored to the object. It allows inspection and modification of the state dictionary. Whe
(self, obj, state, **kwargs)
| 470 | return self.inspect_reduced_object(obj, **kwargs) |
| 471 | |
| 472 | def intercept_setstate(self, obj, state, **kwargs): |
| 473 | """Intercept and validate __setstate__ protocol before state restoration. |
| 474 | |
| 475 | This hook is called when deserializing an object that implements __setstate__, |
| 476 | right before the state is restored to the object. It allows inspection and |
| 477 | modification of the state dictionary. |
| 478 | |
| 479 | When Called |
| 480 | ----------- |
| 481 | - Before obj.__setstate__(state) is called |
| 482 | - After the object has been instantiated (via __new__) |
| 483 | - After the state dict has been deserialized |
| 484 | |
| 485 | Security Use Cases |
| 486 | ------------------ |
| 487 | - Inspect state for malicious values |
| 488 | - Sanitize or filter dangerous state attributes |
| 489 | - Validate state against expected schema |
| 490 | - Modify state to enforce security policies |
| 491 | - Audit state restoration for logging |
| 492 | |
| 493 | Args: |
| 494 | obj (object): The object whose state is about to be restored. |
| 495 | state (dict or other): The state to be restored (typically a dict, but can |
| 496 | be any object depending on __setstate__ implementation). |
| 497 | **kwargs: Reserved for future extensions. |
| 498 | |
| 499 | Returns: |
| 500 | None: Always return None. Modify the state dict in-place if needed. |
| 501 | |
| 502 | Raises: |
| 503 | Exception: Raise any exception to reject the state and abort deserialization. |
| 504 | |
| 505 | Example: |
| 506 | >>> class SetStateChecker(DeserializationPolicy): |
| 507 | ... def intercept_setstate(self, obj, state, **kwargs): |
| 508 | ... # Block if state contains dangerous attributes |
| 509 | ... if isinstance(state, dict): |
| 510 | ... dangerous_attrs = {'__code__', '__globals__', '_eval'} |
| 511 | ... if any(attr in state for attr in dangerous_attrs): |
| 512 | ... raise ValueError("State contains dangerous attributes") |
| 513 | ... |
| 514 | ... # Sanitize: remove private attributes |
| 515 | ... state.clear() |
| 516 | ... state.update({k: v for k, v in state.items() |
| 517 | ... if not k.startswith('_')}) |
| 518 | |
| 519 | Note: |
| 520 | This hook can modify the state dict in-place. Changes will be reflected |
| 521 | when __setstate__ is called. |
| 522 | |
| 523 | `check_setstate` is an alias for this hook. |
| 524 | """ |
| 525 | pass |
| 526 | |
| 527 | # Hook alias |
| 528 | def check_setstate(self, obj, state, **kwargs): |
no outgoing calls
no test coverage detected