Skip to content

Secret Mapping

ImmutableSecretMapping

Bases: UserDict, Mapping[Any, Secret]

A dictionary-like object that stores secret values and prevents changes to the dictionary.

Source code in src/sosecrets/secretdicts.py
  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
class ImmutableSecretMapping(UserDict, Mapping[Any, Secret]):
    """
    A dictionary-like object that stores secret values and prevents changes to the dictionary.
    """
    _frozen = False

    def __init__(self, dict=None, /, **kwargs):
        """
        Initialize a new `ImmutableSecretMapping` object.

        Args:
            mapping (Dict[Any, Any]): A dictionary with `Any` keys and `Any` values.
        """
        if dict is None or dict == {}:
            raise ValueError("Cannot initialize `ImmutableSecretMapping` with an empty dictionary")
        super().__init__(dict, **kwargs)
        for k, v in self.data.items():
            if not isinstance(v, Secret):
                self.data[k] = Secret(v)
            else:
                self.data[k] = v
        self._frozen = True

    def __setitem__(self, key: Any, value: Any) -> None:
        """
        Raise an exception when attempting to set a new key-value pair in the `ImmutableSecretMapping` object.

        Parameters:
            key (Any): The key to set.
            value (Any): The value to set.

        Raises:
            TypeError: When attempting to set a new key-value pair.
        """
        if self._frozen:
            raise TypeError(
                "ImmutableSecretMapping object does not support item assignment.")
        super().__setitem__(key, value)

    @classmethod
    def from_func(
            cls,
            func: Callable[[Any], Dict[Any, Any]],
            *func_args: Tuple[Any],
            **func_kwargs: Dict[Any, Any]) -> 'ImmutableSecretMapping':
        """Create a new ImmutableSecretMapping object from the result of a function.

        Args:
            func (callable): A function that returns a dictionary with `Any` keys and secret values.
            *func_args (Any): Positional arguments to pass to the function.
            **func_kwargs (Any): Keyword arguments to pass to the function.

        Returns:
            ImmutableSecretMapping: A new ImmutableSecretMapping object.

        Raises:
            ValueError: If the result of the function is empty.
        """
        mapping = func(*func_args, **func_kwargs)
        if not mapping:
            raise ValueError("Result of the function is empty.")
        new_mapping = {}
        for k, v in mapping.items():
            if not isinstance(v, Secret):
                new_mapping[k] = Secret(v)
            else:
                new_mapping[k] = v
        return cls(new_mapping)

    def get_exposed(self, key: Any, default: Optional[Any] = None) -> Any:
        """Get the exposed value of a key in the ImmutableSecretMapping object.

        Args:
            key (Any): The key to get.
            default (Optional[Any]): The default value to return if the key is not found.

        Returns:
            Any: The exposed value of the key, or the default value if the key is not found."""
        value: Secret = self.data.get(key, default)
        if value == default:
            return value
        return value.expose_secret()

    def expose_dict(self) -> Dict[Any, Any]:
        """
        Return a new dictionary that exposes exposed information.

        This method returns a new dictionary with the same keys as the original dictionary,
        but with values that have been converted to exposed information using their `expose_secret()` method.
        The `expose_secret()` method is expected to return a exposed version of the value.

        Returns:
            Dict[Any, Any]: A new dictionary with exposed values.
        """
        return {k: v.expose_secret() for k, v in self.data.items()}

__init__(dict=None, /, **kwargs)

Initialize a new ImmutableSecretMapping object.

Parameters:

Name Type Description Default
mapping Dict[Any, Any]

A dictionary with Any keys and Any values.

required
Source code in src/sosecrets/secretdicts.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def __init__(self, dict=None, /, **kwargs):
    """
    Initialize a new `ImmutableSecretMapping` object.

    Args:
        mapping (Dict[Any, Any]): A dictionary with `Any` keys and `Any` values.
    """
    if dict is None or dict == {}:
        raise ValueError("Cannot initialize `ImmutableSecretMapping` with an empty dictionary")
    super().__init__(dict, **kwargs)
    for k, v in self.data.items():
        if not isinstance(v, Secret):
            self.data[k] = Secret(v)
        else:
            self.data[k] = v
    self._frozen = True

__setitem__(key, value)

Raise an exception when attempting to set a new key-value pair in the ImmutableSecretMapping object.

Parameters:

Name Type Description Default
key Any

The key to set.

required
value Any

The value to set.

required

Raises:

Type Description
TypeError

When attempting to set a new key-value pair.

Source code in src/sosecrets/secretdicts.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def __setitem__(self, key: Any, value: Any) -> None:
    """
    Raise an exception when attempting to set a new key-value pair in the `ImmutableSecretMapping` object.

    Parameters:
        key (Any): The key to set.
        value (Any): The value to set.

    Raises:
        TypeError: When attempting to set a new key-value pair.
    """
    if self._frozen:
        raise TypeError(
            "ImmutableSecretMapping object does not support item assignment.")
    super().__setitem__(key, value)

expose_dict()

Return a new dictionary that exposes exposed information.

This method returns a new dictionary with the same keys as the original dictionary, but with values that have been converted to exposed information using their expose_secret() method. The expose_secret() method is expected to return a exposed version of the value.

Returns:

Type Description
Dict[Any, Any]

Dict[Any, Any]: A new dictionary with exposed values.

Source code in src/sosecrets/secretdicts.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def expose_dict(self) -> Dict[Any, Any]:
    """
    Return a new dictionary that exposes exposed information.

    This method returns a new dictionary with the same keys as the original dictionary,
    but with values that have been converted to exposed information using their `expose_secret()` method.
    The `expose_secret()` method is expected to return a exposed version of the value.

    Returns:
        Dict[Any, Any]: A new dictionary with exposed values.
    """
    return {k: v.expose_secret() for k, v in self.data.items()}

from_func(func, *func_args, **func_kwargs) classmethod

Create a new ImmutableSecretMapping object from the result of a function.

Parameters:

Name Type Description Default
func callable

A function that returns a dictionary with Any keys and secret values.

required
*func_args Any

Positional arguments to pass to the function.

()
**func_kwargs Any

Keyword arguments to pass to the function.

{}

Returns:

Name Type Description
ImmutableSecretMapping ImmutableSecretMapping

A new ImmutableSecretMapping object.

Raises:

Type Description
ValueError

If the result of the function is empty.

Source code in src/sosecrets/secretdicts.py
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
@classmethod
def from_func(
        cls,
        func: Callable[[Any], Dict[Any, Any]],
        *func_args: Tuple[Any],
        **func_kwargs: Dict[Any, Any]) -> 'ImmutableSecretMapping':
    """Create a new ImmutableSecretMapping object from the result of a function.

    Args:
        func (callable): A function that returns a dictionary with `Any` keys and secret values.
        *func_args (Any): Positional arguments to pass to the function.
        **func_kwargs (Any): Keyword arguments to pass to the function.

    Returns:
        ImmutableSecretMapping: A new ImmutableSecretMapping object.

    Raises:
        ValueError: If the result of the function is empty.
    """
    mapping = func(*func_args, **func_kwargs)
    if not mapping:
        raise ValueError("Result of the function is empty.")
    new_mapping = {}
    for k, v in mapping.items():
        if not isinstance(v, Secret):
            new_mapping[k] = Secret(v)
        else:
            new_mapping[k] = v
    return cls(new_mapping)

get_exposed(key, default=None)

Get the exposed value of a key in the ImmutableSecretMapping object.

Parameters:

Name Type Description Default
key Any

The key to get.

required
default Optional[Any]

The default value to return if the key is not found.

None

Returns:

Name Type Description
Any Any

The exposed value of the key, or the default value if the key is not found.

Source code in src/sosecrets/secretdicts.py
75
76
77
78
79
80
81
82
83
84
85
86
87
def get_exposed(self, key: Any, default: Optional[Any] = None) -> Any:
    """Get the exposed value of a key in the ImmutableSecretMapping object.

    Args:
        key (Any): The key to get.
        default (Optional[Any]): The default value to return if the key is not found.

    Returns:
        Any: The exposed value of the key, or the default value if the key is not found."""
    value: Secret = self.data.get(key, default)
    if value == default:
        return value
    return value.expose_secret()

MutableSecretMapping

Bases: UserDict, Mapping[Any, Secret]

A dictionary-like object that stores secret values and allows changes to the dictionary.

Source code in src/sosecrets/secretdicts.py
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
class MutableSecretMapping(UserDict, Mapping[Any, Secret]):
    """
    A dictionary-like object that stores secret values and allows changes to the dictionary.
    """
    _unset = True

    def __init__(self, dict=None, /, **kwargs):
        """
        Initialize a new `MutableSecretMapping` object.

        Args:
            mapping (Dict[Any, Any]): A dictionary with `Any` keys and `Any` values.
        """
        super().__init__(dict, **kwargs)
        for k, v in self.data.items():
            if not isinstance(v, Secret):
                self.data[k] = Secret(v)
            else:
                self.data[k] = v
        self._unset = False

    def __setitem__(self, key: Any, value: Any) -> None:
        """
        Set a new key-value pair in the `MutableSecretMapping` object.

        Parameters:
            key (Any): The key to set.
            value (Any): The value to set.

        Raises:
            ValueError: If the value is not of type `Secret`.
        """
        if self._unset:
            if not isinstance(value, Secret):
                value = Secret(value)
            super().__setitem__(key, value)
        if not isinstance(value, Secret):
            raise ValueError("Value must be of type `Secret`.")
        super().__setitem__(key, value)


    @classmethod
    def from_func(
            cls,
            func: Callable[..., Dict[Any, Any]],
            *func_args: Tuple[Any, ...],
            **func_kwargs: Dict[Any, Any]) -> 'MutableSecretMapping':
        """Create a new `MutableSecretMapping` object from the result of a function.

        Args:
            func (callable): A function that returns a dictionary with `Any` keys and secret values.
            *func_args (Any): Positional arguments to pass to the function.
            **func_kwargs (Any): Keyword arguments to pass to the function.

        Returns:
            MutableSecretMapping: A new `MutableSecretMapping` object.

        Raises:
            ValueError: If the result of the function is empty.
        """
        mapping = func(*func_args, **func_kwargs)
        if not mapping:
            raise ValueError("Result of the function is empty.")
        new_mapping = {}
        for k, v in mapping.items():
            if not isinstance(v, Secret):
                new_mapping[k] = Secret(v)
            else:
                new_mapping[k] = v
        return cls(new_mapping)

    def get_exposed(self, key: Any, default: Optional[Any] = None) -> Any:
        """
        Get the exposed value of a key in the `MutableSecretMapping` object.

        Args:
            key (Any): The key to get.
            default (Optional[Any]): The default value to return if the key is not found.

        Returns:
            Any: The exposed value of the key, or the default value if the key is not found.
        """
        value: Secret = super().get(key, default)
        if value == default:
            return value
        return value.expose_secret()

    def expose_dict(self) -> Dict[Any, Any]:
        """
        Return a new dictionary that exposes exposed information.

        This method returns a new dictionary with the same keys as the original dictionary,
        but with values that have been converted to exposed information using their `expose_secret()` method.
        The `expose_secret()` method is expected to return a exposed version of the value.

        Returns:
            Dict[Any, Any]: A new dictionary with exposed values.
        """
        return {k: v.expose_secret() for k, v in super().items()}

__init__(dict=None, /, **kwargs)

Initialize a new MutableSecretMapping object.

Parameters:

Name Type Description Default
mapping Dict[Any, Any]

A dictionary with Any keys and Any values.

required
Source code in src/sosecrets/secretdicts.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def __init__(self, dict=None, /, **kwargs):
    """
    Initialize a new `MutableSecretMapping` object.

    Args:
        mapping (Dict[Any, Any]): A dictionary with `Any` keys and `Any` values.
    """
    super().__init__(dict, **kwargs)
    for k, v in self.data.items():
        if not isinstance(v, Secret):
            self.data[k] = Secret(v)
        else:
            self.data[k] = v
    self._unset = False

__setitem__(key, value)

Set a new key-value pair in the MutableSecretMapping object.

Parameters:

Name Type Description Default
key Any

The key to set.

required
value Any

The value to set.

required

Raises:

Type Description
ValueError

If the value is not of type Secret.

Source code in src/sosecrets/secretdicts.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def __setitem__(self, key: Any, value: Any) -> None:
    """
    Set a new key-value pair in the `MutableSecretMapping` object.

    Parameters:
        key (Any): The key to set.
        value (Any): The value to set.

    Raises:
        ValueError: If the value is not of type `Secret`.
    """
    if self._unset:
        if not isinstance(value, Secret):
            value = Secret(value)
        super().__setitem__(key, value)
    if not isinstance(value, Secret):
        raise ValueError("Value must be of type `Secret`.")
    super().__setitem__(key, value)

expose_dict()

Return a new dictionary that exposes exposed information.

This method returns a new dictionary with the same keys as the original dictionary, but with values that have been converted to exposed information using their expose_secret() method. The expose_secret() method is expected to return a exposed version of the value.

Returns:

Type Description
Dict[Any, Any]

Dict[Any, Any]: A new dictionary with exposed values.

Source code in src/sosecrets/secretdicts.py
190
191
192
193
194
195
196
197
198
199
200
201
def expose_dict(self) -> Dict[Any, Any]:
    """
    Return a new dictionary that exposes exposed information.

    This method returns a new dictionary with the same keys as the original dictionary,
    but with values that have been converted to exposed information using their `expose_secret()` method.
    The `expose_secret()` method is expected to return a exposed version of the value.

    Returns:
        Dict[Any, Any]: A new dictionary with exposed values.
    """
    return {k: v.expose_secret() for k, v in super().items()}

from_func(func, *func_args, **func_kwargs) classmethod

Create a new MutableSecretMapping object from the result of a function.

Parameters:

Name Type Description Default
func callable

A function that returns a dictionary with Any keys and secret values.

required
*func_args Any

Positional arguments to pass to the function.

()
**func_kwargs Any

Keyword arguments to pass to the function.

{}

Returns:

Name Type Description
MutableSecretMapping MutableSecretMapping

A new MutableSecretMapping object.

Raises:

Type Description
ValueError

If the result of the function is empty.

Source code in src/sosecrets/secretdicts.py
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
@classmethod
def from_func(
        cls,
        func: Callable[..., Dict[Any, Any]],
        *func_args: Tuple[Any, ...],
        **func_kwargs: Dict[Any, Any]) -> 'MutableSecretMapping':
    """Create a new `MutableSecretMapping` object from the result of a function.

    Args:
        func (callable): A function that returns a dictionary with `Any` keys and secret values.
        *func_args (Any): Positional arguments to pass to the function.
        **func_kwargs (Any): Keyword arguments to pass to the function.

    Returns:
        MutableSecretMapping: A new `MutableSecretMapping` object.

    Raises:
        ValueError: If the result of the function is empty.
    """
    mapping = func(*func_args, **func_kwargs)
    if not mapping:
        raise ValueError("Result of the function is empty.")
    new_mapping = {}
    for k, v in mapping.items():
        if not isinstance(v, Secret):
            new_mapping[k] = Secret(v)
        else:
            new_mapping[k] = v
    return cls(new_mapping)

get_exposed(key, default=None)

Get the exposed value of a key in the MutableSecretMapping object.

Parameters:

Name Type Description Default
key Any

The key to get.

required
default Optional[Any]

The default value to return if the key is not found.

None

Returns:

Name Type Description
Any Any

The exposed value of the key, or the default value if the key is not found.

Source code in src/sosecrets/secretdicts.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def get_exposed(self, key: Any, default: Optional[Any] = None) -> Any:
    """
    Get the exposed value of a key in the `MutableSecretMapping` object.

    Args:
        key (Any): The key to get.
        default (Optional[Any]): The default value to return if the key is not found.

    Returns:
        Any: The exposed value of the key, or the default value if the key is not found.
    """
    value: Secret = super().get(key, default)
    if value == default:
        return value
    return value.expose_secret()