pydantic_encryption 0.0.2a0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Julien Kmec
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,199 @@
1
+ Metadata-Version: 2.1
2
+ Name: pydantic_encryption
3
+ Version: 0.0.2a0
4
+ Summary: Encryption models for Pydantic
5
+ Author: Julien Kmec
6
+ Author-email: me@julien.dev
7
+ Requires-Python: >=3.12,<3.13
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Requires-Dist: pydantic (>=2.10.6,<3.0.0)
11
+ Requires-Dist: pydantic-settings (>=2.9.1,<3.0.0)
12
+ Description-Content-Type: text/markdown
13
+
14
+ # Encryption models for Pydantic
15
+
16
+ This package provides Pydantic field types that encrypt and decrypt the field values.
17
+
18
+ ## Installation
19
+
20
+ Install [Poetry](https://python-poetry.org/) if you haven't already.
21
+
22
+ Install this package with the `evervault` and `generics` extras:
23
+ ```bash
24
+ poetry add pydantic_encryption --with evervault,generics
25
+ ```
26
+
27
+ Install this package without extras:
28
+ ```bash
29
+ poetry add pydantic_encryption
30
+ ```
31
+
32
+ ## Features
33
+
34
+ - Encrypt and decrypt fields
35
+ - Support for BaseModel inheritance
36
+ - Support for generics
37
+
38
+ ## Example
39
+
40
+ ```py
41
+ from pydantic_encryption import BaseModel, EncryptField
42
+
43
+ class User(BaseModel):
44
+ name: str
45
+ password: EncryptField # This field will be encrypted
46
+
47
+ user = User(name="John Doe", password="123456")
48
+ print(user.password) # encrypted
49
+ ```
50
+
51
+
52
+
53
+ ## Choose an Encryption Method
54
+
55
+ ### Evervault
56
+
57
+ If you install this package with the `evervault` extra, you can use [Evervault](https://evervault.com/) to encrypt and decrypt fields.
58
+
59
+ You need to set the following environment variables or add them to your `.env` file:
60
+
61
+ ```bash
62
+ EVERVAULT_APP_ID=your_app_id
63
+ EVERVAULT_API_KEY=your_api_key
64
+ EVERVAULT_ENCRYPTION_ROLE=your_encryption_role
65
+ ```
66
+
67
+ ### Custom Encryption
68
+
69
+ You can define your own encryption and decryption methods by subclassing `EncryptableObject`.
70
+
71
+ `EncryptableObject` provides you with the utilities to handle encryption and decryption.
72
+
73
+ `self.pending_encryption_fields` and `self.pending_decryption_fields` are dictionaries of field names to field values that need to be encrypted or decrypted, i.e., fields annotated with `EncryptField` or `DecryptField`.
74
+
75
+ You can override the `encrypt_data` and `decrypt_data` methods to implement your own encryption and decryption logic.
76
+
77
+ You then need to override `model_post_init` to call `self.encrypt_data()` and/or `self.decrypt_data()`.
78
+
79
+ First, define a custom encryptable object:
80
+
81
+ ```py
82
+ from typing import override
83
+ from pydantic_encryption import EncryptableObject
84
+
85
+ class MyEncryptableObject(EncryptableObject):
86
+ @override
87
+ def encrypt_data(self) -> None:
88
+ # Your encryption logic here
89
+ pass
90
+
91
+ @override
92
+ def decrypt_data(self) -> None:
93
+ # Your decryption logic here
94
+ pass
95
+
96
+ @override
97
+ def model_post_init(self, context: Any, /) -> None:
98
+ if not self._disable:
99
+ if self.pending_decryption_fields:
100
+ self.decrypt_data()
101
+
102
+ if self.pending_encryption_fields:
103
+ self.encrypt_data()
104
+
105
+ super().model_post_init(context)
106
+ ```
107
+
108
+ Then use it:
109
+
110
+ ```py
111
+ from pydantic import BaseModel # Here, we don't use the BaseModel provided by the library, but the native one from Pydantic
112
+ from pydantic_encryption import EncryptField
113
+
114
+ class MyModel(BaseModel, MyEncryptableObject):
115
+ username: str
116
+ password: EncryptField
117
+
118
+ model = MyModel(username="john_doe", password="123456")
119
+ print(model.password) # encrypted
120
+ ```
121
+
122
+ ## Encryption
123
+
124
+ You can encrypt any field by annotating with `EncryptField` and inheriting from `EncryptableObject`.
125
+
126
+ ```py
127
+ from pydantic_encryption import EncryptableObject, EncryptField, BaseModel
128
+
129
+ class User(BaseModel):
130
+ name: str
131
+ password: EncryptField # This field will be encrypted
132
+
133
+ user = User(name="John Doe", password="123456")
134
+ print(user.password) # encrypted
135
+ print(user.name) # plaintext (untouched)
136
+ ```
137
+
138
+ ## Decryption
139
+
140
+ Similar to encryption, you can decrypt any field by annotating with `DecryptField` and inheriting from `EncryptableObject`.
141
+
142
+ ```py
143
+ from pydantic_encryption import EncryptableObject, DecryptField, BaseModel
144
+
145
+ class User(BaseModel, EncryptableObject):
146
+ name: str
147
+ password: DecryptField # This field will be decrypted
148
+
149
+ user = User(name="John Doe", password="123456")
150
+ print(user.password) # encrypted
151
+ print(user.name) # plaintext (untouched)
152
+
153
+ ```
154
+
155
+
156
+ ## Disable Auto-Encryption/Decryption
157
+
158
+ You can disable auto-encryption/decryption by setting `disable` to `True` in the class definition.
159
+
160
+ ```py
161
+ from pydantic_encryption import EncryptableObject, EncryptField, BaseModel
162
+
163
+ class UserResponse(BaseModel, EncryptableObject, disable=True):
164
+ name: str
165
+ password: EncryptField
166
+
167
+ # To encrypt/decrypt, call `encrypt_data()` or `decrypt_data()`:
168
+ user = UserResponse(name="John Doe", password="ENCRYPTED_PASSWORD")
169
+
170
+ user.decrypt_data()
171
+ print(user.password) # decrypted
172
+
173
+ user.encrypt_data()
174
+ print(user.password) # encrypted
175
+ ```
176
+
177
+ ## Generics
178
+
179
+ Each BaseModel has an additional helpful method that will tell you its generic type.
180
+
181
+ To use generics, you must install this package with the `generics` extra: `poetry add pydantic_encryption --with generics`.
182
+
183
+ ```py
184
+ from pydantic_encryption import BaseModel
185
+
186
+ class MyModel[T](BaseModel):
187
+ value: T
188
+
189
+ model = MyModel[str](value="Hello")
190
+ print(model.get_type()) # <class 'str'>
191
+ ```
192
+
193
+ ## Run Tests
194
+
195
+ ```bash
196
+ poetry install --with test
197
+ poetry run coverage run -m pytest -v -s
198
+ ```
199
+
@@ -0,0 +1,185 @@
1
+ # Encryption models for Pydantic
2
+
3
+ This package provides Pydantic field types that encrypt and decrypt the field values.
4
+
5
+ ## Installation
6
+
7
+ Install [Poetry](https://python-poetry.org/) if you haven't already.
8
+
9
+ Install this package with the `evervault` and `generics` extras:
10
+ ```bash
11
+ poetry add pydantic_encryption --with evervault,generics
12
+ ```
13
+
14
+ Install this package without extras:
15
+ ```bash
16
+ poetry add pydantic_encryption
17
+ ```
18
+
19
+ ## Features
20
+
21
+ - Encrypt and decrypt fields
22
+ - Support for BaseModel inheritance
23
+ - Support for generics
24
+
25
+ ## Example
26
+
27
+ ```py
28
+ from pydantic_encryption import BaseModel, EncryptField
29
+
30
+ class User(BaseModel):
31
+ name: str
32
+ password: EncryptField # This field will be encrypted
33
+
34
+ user = User(name="John Doe", password="123456")
35
+ print(user.password) # encrypted
36
+ ```
37
+
38
+
39
+
40
+ ## Choose an Encryption Method
41
+
42
+ ### Evervault
43
+
44
+ If you install this package with the `evervault` extra, you can use [Evervault](https://evervault.com/) to encrypt and decrypt fields.
45
+
46
+ You need to set the following environment variables or add them to your `.env` file:
47
+
48
+ ```bash
49
+ EVERVAULT_APP_ID=your_app_id
50
+ EVERVAULT_API_KEY=your_api_key
51
+ EVERVAULT_ENCRYPTION_ROLE=your_encryption_role
52
+ ```
53
+
54
+ ### Custom Encryption
55
+
56
+ You can define your own encryption and decryption methods by subclassing `EncryptableObject`.
57
+
58
+ `EncryptableObject` provides you with the utilities to handle encryption and decryption.
59
+
60
+ `self.pending_encryption_fields` and `self.pending_decryption_fields` are dictionaries of field names to field values that need to be encrypted or decrypted, i.e., fields annotated with `EncryptField` or `DecryptField`.
61
+
62
+ You can override the `encrypt_data` and `decrypt_data` methods to implement your own encryption and decryption logic.
63
+
64
+ You then need to override `model_post_init` to call `self.encrypt_data()` and/or `self.decrypt_data()`.
65
+
66
+ First, define a custom encryptable object:
67
+
68
+ ```py
69
+ from typing import override
70
+ from pydantic_encryption import EncryptableObject
71
+
72
+ class MyEncryptableObject(EncryptableObject):
73
+ @override
74
+ def encrypt_data(self) -> None:
75
+ # Your encryption logic here
76
+ pass
77
+
78
+ @override
79
+ def decrypt_data(self) -> None:
80
+ # Your decryption logic here
81
+ pass
82
+
83
+ @override
84
+ def model_post_init(self, context: Any, /) -> None:
85
+ if not self._disable:
86
+ if self.pending_decryption_fields:
87
+ self.decrypt_data()
88
+
89
+ if self.pending_encryption_fields:
90
+ self.encrypt_data()
91
+
92
+ super().model_post_init(context)
93
+ ```
94
+
95
+ Then use it:
96
+
97
+ ```py
98
+ from pydantic import BaseModel # Here, we don't use the BaseModel provided by the library, but the native one from Pydantic
99
+ from pydantic_encryption import EncryptField
100
+
101
+ class MyModel(BaseModel, MyEncryptableObject):
102
+ username: str
103
+ password: EncryptField
104
+
105
+ model = MyModel(username="john_doe", password="123456")
106
+ print(model.password) # encrypted
107
+ ```
108
+
109
+ ## Encryption
110
+
111
+ You can encrypt any field by annotating with `EncryptField` and inheriting from `EncryptableObject`.
112
+
113
+ ```py
114
+ from pydantic_encryption import EncryptableObject, EncryptField, BaseModel
115
+
116
+ class User(BaseModel):
117
+ name: str
118
+ password: EncryptField # This field will be encrypted
119
+
120
+ user = User(name="John Doe", password="123456")
121
+ print(user.password) # encrypted
122
+ print(user.name) # plaintext (untouched)
123
+ ```
124
+
125
+ ## Decryption
126
+
127
+ Similar to encryption, you can decrypt any field by annotating with `DecryptField` and inheriting from `EncryptableObject`.
128
+
129
+ ```py
130
+ from pydantic_encryption import EncryptableObject, DecryptField, BaseModel
131
+
132
+ class User(BaseModel, EncryptableObject):
133
+ name: str
134
+ password: DecryptField # This field will be decrypted
135
+
136
+ user = User(name="John Doe", password="123456")
137
+ print(user.password) # encrypted
138
+ print(user.name) # plaintext (untouched)
139
+
140
+ ```
141
+
142
+
143
+ ## Disable Auto-Encryption/Decryption
144
+
145
+ You can disable auto-encryption/decryption by setting `disable` to `True` in the class definition.
146
+
147
+ ```py
148
+ from pydantic_encryption import EncryptableObject, EncryptField, BaseModel
149
+
150
+ class UserResponse(BaseModel, EncryptableObject, disable=True):
151
+ name: str
152
+ password: EncryptField
153
+
154
+ # To encrypt/decrypt, call `encrypt_data()` or `decrypt_data()`:
155
+ user = UserResponse(name="John Doe", password="ENCRYPTED_PASSWORD")
156
+
157
+ user.decrypt_data()
158
+ print(user.password) # decrypted
159
+
160
+ user.encrypt_data()
161
+ print(user.password) # encrypted
162
+ ```
163
+
164
+ ## Generics
165
+
166
+ Each BaseModel has an additional helpful method that will tell you its generic type.
167
+
168
+ To use generics, you must install this package with the `generics` extra: `poetry add pydantic_encryption --with generics`.
169
+
170
+ ```py
171
+ from pydantic_encryption import BaseModel
172
+
173
+ class MyModel[T](BaseModel):
174
+ value: T
175
+
176
+ model = MyModel[str](value="Hello")
177
+ print(model.get_type()) # <class 'str'>
178
+ ```
179
+
180
+ ## Run Tests
181
+
182
+ ```bash
183
+ poetry install --with test
184
+ poetry run coverage run -m pytest -v -s
185
+ ```
@@ -0,0 +1 @@
1
+ from .models import *
@@ -0,0 +1,35 @@
1
+ from typing import override, Any
2
+ from pydantic_settings import BaseSettings
3
+
4
+
5
+ class Settings(BaseSettings):
6
+ """Settings for the package."""
7
+
8
+ # Evervault settings
9
+ EVERVAULT_API_KEY: str | None = None
10
+ EVERVAULT_APP_ID: str | None = None
11
+ EVERVAULT_ENCRYPTION_ROLE: str | None = None
12
+
13
+ class Config:
14
+ env_file = [".env.local", ".env"]
15
+ case_sensitive = True
16
+ extra = "ignore"
17
+
18
+ @override
19
+ def model_post_init(self, context: Any, /) -> None:
20
+ try:
21
+ import evervault # pylint: disable=unused-import
22
+ except ImportError:
23
+ pass
24
+ else:
25
+ if not (
26
+ self.EVERVAULT_APP_ID
27
+ and self.EVERVAULT_API_KEY
28
+ and self.EVERVAULT_ENCRYPTION_ROLE
29
+ ):
30
+ raise ValueError("Evervault settings are not configured")
31
+
32
+ return super().model_post_init(context)
33
+
34
+
35
+ settings = Settings()
@@ -0,0 +1,2 @@
1
+ from .encryption import *
2
+ from .base import *
@@ -0,0 +1,42 @@
1
+ from typing import Any, override
2
+ from pydantic import BaseModel as PydanticBaseModel
3
+ from .encryption import EncryptableObject
4
+
5
+ try:
6
+ from generics import get_filled_type
7
+ except ImportError:
8
+ get_filled_type = None
9
+
10
+ __all__ = ["BaseModel"]
11
+
12
+
13
+ class BaseModel(PydanticBaseModel, EncryptableObject):
14
+ """Base model for encryptable models."""
15
+
16
+ _generic_type_value: Any = None
17
+
18
+ @override
19
+ def model_post_init(self, context: Any, /) -> None:
20
+ if not self._disable:
21
+ if self.pending_decryption_fields:
22
+ self.decrypt_data()
23
+
24
+ if self.pending_encryption_fields:
25
+ self.encrypt_data()
26
+
27
+ super().model_post_init(context)
28
+
29
+ def get_type(self) -> type | None:
30
+ """Get the type of the model."""
31
+
32
+ if not get_filled_type:
33
+ raise NotImplementedError(
34
+ "Generics are not available. Please install this package with the `generics` extra."
35
+ )
36
+
37
+ if self._generic_type_value:
38
+ return self._generic_type_value
39
+
40
+ self._generic_type_value = get_filled_type(self, BaseModel, 0)
41
+
42
+ return self._generic_type_value
@@ -0,0 +1,172 @@
1
+ from typing import (
2
+ Any,
3
+ Annotated,
4
+ get_type_hints,
5
+ Union,
6
+ get_args,
7
+ get_origin,
8
+ )
9
+ from pydantic_encryption.config import settings
10
+
11
+ try:
12
+ import evervault
13
+ except ImportError:
14
+ evervault_client = None
15
+ else:
16
+ evervault_client = evervault.Client(
17
+ app_uuid=settings.EVERVAULT_APP_ID, api_key=settings.EVERVAULT_API_KEY
18
+ )
19
+
20
+ __all__ = [
21
+ "EncryptField",
22
+ "DecryptField",
23
+ "EncryptableObject",
24
+ ]
25
+
26
+
27
+ class _EncryptedFieldValue:
28
+ pass
29
+
30
+
31
+ class _DecryptedFieldValue:
32
+ pass
33
+
34
+
35
+ EncryptField = Annotated[
36
+ str, _EncryptedFieldValue
37
+ ] # Fields with this annotation will be encrypted
38
+ DecryptField = Annotated[
39
+ str, _DecryptedFieldValue
40
+ ] # Fields with this annotation will be decrypted
41
+
42
+
43
+ class EncryptableObject:
44
+ """Base class for encryptable models."""
45
+
46
+ _disable: bool | None = None
47
+
48
+ def __init_subclass__(cls, disable: bool | None = None, **kwargs):
49
+ super().__init_subclass__(**kwargs)
50
+
51
+ cls._disable = disable
52
+
53
+ def encrypt_data(self) -> None:
54
+ """Encrypt data using Evervault."""
55
+
56
+ if self._disable:
57
+ return
58
+
59
+ if not evervault_client:
60
+ raise ValueError(
61
+ "Evervault is not available. Please install this package with the `evervault` extra."
62
+ )
63
+
64
+ if not self.pending_encryption_fields:
65
+ return
66
+
67
+ encrypted_data_dict = evervault_client.encrypt(
68
+ self.pending_encryption_fields, role=settings.EVERVAULT_ENCRYPTION_ROLE
69
+ )
70
+
71
+ for field_name, value in encrypted_data_dict.items():
72
+ setattr(self, field_name, value)
73
+
74
+ def decrypt_data(self) -> None:
75
+ """Decrypt data using Evervault. After this call, all decrypted fields are type str."""
76
+
77
+ if self._disable:
78
+ return
79
+
80
+ if not evervault_client:
81
+ raise ValueError(
82
+ "Evervault is not available. Please install this package with the `evervault` extra."
83
+ )
84
+
85
+ if not self.pending_decryption_fields:
86
+ return
87
+
88
+ decrypted_data: dict[str, str] = evervault_client.decrypt(
89
+ self.pending_decryption_fields
90
+ )
91
+
92
+ for field_name, value in decrypted_data.items():
93
+ setattr(self, field_name, value)
94
+
95
+ @staticmethod
96
+ def get_annotated_fields(
97
+ instance: "BaseModel", obj: dict[str, Any] | None = None, *annotations: type
98
+ ) -> dict[str, str]:
99
+ """Get fields that have the specified annotations, handling union types.
100
+
101
+ Args:
102
+ instance: The instance to get annotated fields from
103
+ obj: The object to get annotated fields from
104
+ annotations: The annotations to look for
105
+
106
+ Returns:
107
+ A dictionary of field names to field values
108
+ """
109
+
110
+ def has_annotation(target_type, target_annotations):
111
+ """Check if a type has any of the target annotations."""
112
+
113
+ # Direct match
114
+ if any(
115
+ target_type is ann or target_type == ann for ann in target_annotations
116
+ ):
117
+ return True
118
+
119
+ # Annotated type
120
+ if get_origin(target_type) is Annotated:
121
+ for arg in get_args(target_type)[1:]: # Skip first arg (the type)
122
+ if any(arg is ann or arg == ann for ann in target_annotations):
123
+ return True
124
+
125
+ return False
126
+
127
+ obj = obj or {}
128
+ type_hints = get_type_hints(instance, include_extras=True)
129
+ annotated_fields: dict[str, str] = {}
130
+
131
+ for field_name, field_annotation in type_hints.items():
132
+ found_annotation = False
133
+
134
+ # Direct check
135
+ if has_annotation(field_annotation, annotations):
136
+ found_annotation = True
137
+
138
+ # Check union types
139
+ elif get_origin(field_annotation) is Union:
140
+ for arg in get_args(field_annotation):
141
+
142
+ if has_annotation(arg, annotations):
143
+ found_annotation = True
144
+
145
+ break
146
+
147
+ # If annotation found, add field value to result
148
+ if found_annotation:
149
+ field_value = None
150
+
151
+ if field_name in obj:
152
+ field_value = obj[field_name]
153
+
154
+ elif hasattr(instance, field_name):
155
+ field_value = getattr(instance, field_name)
156
+
157
+ if field_value is not None:
158
+ annotated_fields[field_name] = field_value
159
+
160
+ return annotated_fields
161
+
162
+ @property
163
+ def pending_encryption_fields(self) -> dict[str, str]:
164
+ """Get all encrypted fields from the model."""
165
+
166
+ return self.get_annotated_fields(self, None, _EncryptedFieldValue)
167
+
168
+ @property
169
+ def pending_decryption_fields(self) -> dict[str, str]:
170
+ """Get all decrypted fields from the model."""
171
+
172
+ return self.get_annotated_fields(self, None, _DecryptedFieldValue)
@@ -0,0 +1,32 @@
1
+ [tool.poetry]
2
+ name = "pydantic_encryption"
3
+ version = "0.0.2a0"
4
+ description = "Encryption models for Pydantic"
5
+ authors = ["Julien Kmec <me@julien.dev>"]
6
+ readme = "README.md"
7
+ packages = [{include = "pydantic_encryption"}]
8
+
9
+ [tool.poetry.dependencies]
10
+ python = "<3.13, >=3.12"
11
+ pydantic = "^2.10.6"
12
+ pydantic-settings = "^2.9.1"
13
+
14
+ [tool.poetry.group.evervault]
15
+ optional = true
16
+
17
+ [tool.poetry.group.evervault.dependencies]
18
+ evervault = "^4.4.1"
19
+
20
+ [tool.poetry.group.generics]
21
+ optional = true
22
+
23
+ [tool.poetry.group.generics.dependencies]
24
+ python-generics = "^0.2.3"
25
+
26
+ [tool.poetry.group.test.dependencies]
27
+ pytest = "^8.3.5"
28
+ coverage = "^7.8.0"
29
+
30
+ [build-system]
31
+ requires = ["poetry-core", "setuptools"]
32
+ build-backend = "poetry.core.masonry.api"