diff --git a/monkey/common/credentials/credentials.py b/monkey/common/credentials/credentials.py index e04be27a5..291d488ca 100644 --- a/monkey/common/credentials/credentials.py +++ b/monkey/common/credentials/credentials.py @@ -1,5 +1,6 @@ from __future__ import annotations +import json from dataclasses import dataclass from typing import Any, Mapping, MutableMapping, Sequence, Tuple @@ -142,3 +143,8 @@ class Credentials: @staticmethod def to_json(credentials: Credentials) -> str: return CredentialsSchema().dumps(credentials) + + @staticmethod + def from_json_array(credentials_array_json: str) -> Sequence[Credentials]: + credentials_list = json.loads(credentials_array_json) + return [Credentials.from_mapping(c) for c in credentials_list] diff --git a/monkey/tests/unit_tests/common/credentials/test_credentials.py b/monkey/tests/unit_tests/common/credentials/test_credentials.py index c68e1c813..07a6a5ad6 100644 --- a/monkey/tests/unit_tests/common/credentials/test_credentials.py +++ b/monkey/tests/unit_tests/common/credentials/test_credentials.py @@ -87,3 +87,22 @@ def test_credentials_deserialization__invalid_component(): } with pytest.raises(InvalidCredentialComponentError): Credentials.from_mapping(invalid_data) + + +def test_from_json_array(): + deserialized_credentials_0 = Credentials.from_mapping(CREDENTIALS_DICT) + deserialized_credentials_1 = Credentials( + secrets=(Password(PASSWORD),), identities=(Username("STUPID"),) + ) + deserialized_credentials_2 = Credentials(secrets=(LMHash(LM_HASH),), identities=tuple()) + credentials_array_json = ( + f"[{Credentials.to_json(deserialized_credentials_0)}," + f"{Credentials.to_json(deserialized_credentials_1)}," + f"{Credentials.to_json(deserialized_credentials_2)}]" + ) + + credentials_sequence = Credentials.from_json_array(credentials_array_json) + assert len(credentials_sequence) == 3 + assert credentials_sequence[0] == deserialized_credentials_0 + assert credentials_sequence[1] == deserialized_credentials_1 + assert credentials_sequence[2] == deserialized_credentials_2