From b6e04074a42debc4c324670cc417d1e584949611 Mon Sep 17 00:00:00 2001 From: Mike Salvatore Date: Thu, 18 Aug 2022 09:32:34 -0400 Subject: [PATCH] Island: Make Machine.network_interfaces immutable --- monkey/monkey_island/cc/models/machine.py | 11 +++++++++-- .../monkey_island/cc/models/test_machine.py | 7 +++++++ vulture_allowlist.py | 1 + 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/monkey/monkey_island/cc/models/machine.py b/monkey/monkey_island/cc/models/machine.py index c06c6b086..82d7bcfba 100644 --- a/monkey/monkey_island/cc/models/machine.py +++ b/monkey/monkey_island/cc/models/machine.py @@ -1,7 +1,7 @@ from ipaddress import IPv4Interface -from typing import Optional, Sequence +from typing import MutableSequence, Optional, Sequence -from pydantic import Field, PositiveInt +from pydantic import Field, PositiveInt, validator from common import OperatingSystems @@ -15,3 +15,10 @@ class Machine(MutableBaseModel): operating_system: OperatingSystems operating_system_version: str hostname: str + + @validator("network_interfaces", pre=True) + def _make_sequence_immutable(cls, sequence: Sequence): + if isinstance(sequence, MutableSequence): + return tuple(sequence) + + return sequence diff --git a/monkey/tests/unit_tests/monkey_island/cc/models/test_machine.py b/monkey/tests/unit_tests/monkey_island/cc/models/test_machine.py index dc0ccd45d..2945d7744 100644 --- a/monkey/tests/unit_tests/monkey_island/cc/models/test_machine.py +++ b/monkey/tests/unit_tests/monkey_island/cc/models/test_machine.py @@ -1,6 +1,7 @@ import uuid from ipaddress import IPv4Interface from types import MappingProxyType +from typing import MutableSequence import pytest @@ -125,6 +126,12 @@ def test_network_interfaces_set_invalid_value(): m.network_interfaces = [IPv4Interface("172.1.2.3/24"), None] +def test_network_interfaces_sequence_is_immutable(): + m = Machine(**MACHINE_OBJECT_DICT) + + assert not isinstance(m.network_interfaces, MutableSequence) + + def test_operating_system_set_valid_value(): m = Machine(**MACHINE_OBJECT_DICT) diff --git a/vulture_allowlist.py b/vulture_allowlist.py index 312022dd3..29cedf4c0 100644 --- a/vulture_allowlist.py +++ b/vulture_allowlist.py @@ -210,6 +210,7 @@ _serialize_credentials # unused method (monkey/common/credentials/credentials:6 # Models _make_simulation # unused method (monkey/monkey_island/cc/models/simulation.py:19 operating_system_version +_make_sequence_immutable # TODO DELETE AFTER RESOURCE REFACTORING