pydantic_encryption 0.0.2__py3-none-any.whl

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,3 @@
1
+ from .models import *
2
+ from .annotations import *
3
+ from .lib import *
@@ -0,0 +1,29 @@
1
+ from enum import Enum
2
+ from typing import Any, Callable, Optional, Type, get_origin, get_args, Annotated
3
+ from pydantic import BeforeValidator
4
+
5
+
6
+ class Encrypt:
7
+ """Annotation to mark fields for encryption."""
8
+
9
+
10
+ def decrypt_bytes_to_str(v: bytes | str) -> str:
11
+ if isinstance(v, bytes):
12
+ return v.decode("utf-8")
13
+
14
+ return v
15
+
16
+
17
+ Decrypt = Annotated[str, BeforeValidator(decrypt_bytes_to_str)]
18
+
19
+
20
+ class Hash:
21
+ """Annotation to mark fields for hashing."""
22
+
23
+
24
+ class EncryptionMethod(Enum):
25
+ """Enum for encryption methods."""
26
+
27
+ FERNET = "fernet"
28
+ EVERVAULT = "evervault"
29
+ AWS = "aws"
@@ -0,0 +1,33 @@
1
+ from typing import Optional
2
+ from pydantic_settings import BaseSettings, SettingsConfigDict
3
+ from pydantic_encryption.annotations import EncryptionMethod
4
+
5
+
6
+ class Settings(BaseSettings):
7
+ """Settings for the package."""
8
+
9
+ # Fernet settings
10
+ ENCRYPTION_KEY: Optional[str] = None
11
+
12
+ # AWS KMS settings
13
+ AWS_KMS_KEY_ARN: Optional[str] = None
14
+ AWS_KMS_REGION: Optional[str] = None
15
+ AWS_ACCESS_KEY_ID: Optional[str] = None
16
+ AWS_SECRET_ACCESS_KEY: Optional[str] = None
17
+
18
+ # Evervault settings
19
+ EVERVAULT_API_KEY: Optional[str] = None
20
+ EVERVAULT_APP_ID: Optional[str] = None
21
+ EVERVAULT_ENCRYPTION_ROLE: Optional[str] = None
22
+
23
+ # Encryption settings
24
+ ENCRYPTION_METHOD: EncryptionMethod = EncryptionMethod.FERNET
25
+
26
+ model_config = SettingsConfigDict(
27
+ env_file=[".env.local", ".env"],
28
+ case_sensitive=False,
29
+ extra="ignore",
30
+ )
31
+
32
+
33
+ settings = Settings()
@@ -0,0 +1,2 @@
1
+ from .adapters.encryption import fernet, evervault, aws
2
+ from .adapters.hashing import argon2
@@ -0,0 +1,3 @@
1
+ from .fernet import fernet_encrypt, fernet_decrypt
2
+ from .evervault import evervault_encrypt, evervault_decrypt
3
+ from .aws import aws_encrypt, aws_decrypt
@@ -0,0 +1,91 @@
1
+ try:
2
+ import boto3
3
+ import aws_encryption_sdk
4
+ from aws_encryption_sdk import CommitmentPolicy
5
+ from aws_cryptographic_material_providers.mpl import (
6
+ AwsCryptographicMaterialProviders,
7
+ )
8
+ from aws_cryptographic_material_providers.mpl.config import MaterialProvidersConfig
9
+ from aws_cryptographic_material_providers.mpl.models import CreateAwsKmsKeyringInput
10
+ except ImportError:
11
+ pass
12
+ else:
13
+ KMS_CLIENT = None
14
+ CLIENT = None
15
+ MAT_PROV = None
16
+ KMS_KEYRING = None
17
+
18
+ from pydantic_encryption.models.encryptable import EncryptedValue, DecryptedValue
19
+ from pydantic_encryption.annotations import EncryptionMethod
20
+ from pydantic_encryption.config import settings
21
+
22
+ if settings.ENCRYPTION_METHOD == EncryptionMethod.AWS:
23
+ KMS_CLIENT = boto3.client(
24
+ "kms",
25
+ region_name=settings.AWS_KMS_REGION,
26
+ aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
27
+ aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
28
+ )
29
+
30
+ CLIENT = aws_encryption_sdk.EncryptionSDKClient(
31
+ commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT
32
+ )
33
+
34
+ MAT_PROV = AwsCryptographicMaterialProviders(config=MaterialProvidersConfig())
35
+
36
+ keyring_input = CreateAwsKmsKeyringInput(
37
+ kms_key_id=settings.AWS_KMS_KEY_ARN,
38
+ kms_client=KMS_CLIENT,
39
+ )
40
+
41
+ KMS_KEYRING = MAT_PROV.create_aws_kms_keyring(input=keyring_input)
42
+
43
+
44
+ def _check_aws_encryption():
45
+ if not (KMS_CLIENT and CLIENT and MAT_PROV and KMS_KEYRING):
46
+ raise ValueError(
47
+ "AWS encryption is not available. Please install this package with the `aws` extra."
48
+ )
49
+
50
+
51
+ def aws_encrypt(plaintext: bytes | str | EncryptedValue) -> EncryptedValue:
52
+ """Encrypt data using AWS KMS."""
53
+
54
+ _check_aws_encryption()
55
+
56
+ if isinstance(plaintext, EncryptedValue):
57
+ return plaintext
58
+
59
+ if isinstance(plaintext, str):
60
+ plaintext = plaintext.encode("utf-8")
61
+
62
+ ciphertext, _ = CLIENT.encrypt(
63
+ source=plaintext,
64
+ keyring=KMS_KEYRING,
65
+ )
66
+
67
+ return EncryptedValue(ciphertext)
68
+
69
+
70
+ def aws_decrypt(ciphertext: bytes | str | EncryptedValue) -> DecryptedValue:
71
+ """Decrypt data using AWS KMS."""
72
+
73
+ _check_aws_encryption()
74
+
75
+ if isinstance(ciphertext, DecryptedValue):
76
+ return ciphertext
77
+
78
+ if isinstance(ciphertext, str):
79
+ try:
80
+ ciphertext_bytes = ciphertext.encode("utf-8")
81
+ except UnicodeDecodeError:
82
+ ciphertext_bytes = str(ciphertext)
83
+ else:
84
+ ciphertext_bytes = ciphertext
85
+
86
+ plaintext, _ = CLIENT.decrypt(
87
+ source=ciphertext_bytes,
88
+ keyring=KMS_KEYRING,
89
+ )
90
+
91
+ return DecryptedValue(plaintext)
@@ -0,0 +1,47 @@
1
+ from pydantic_encryption.config import settings
2
+ from pydantic_encryption.annotations import EncryptionMethod
3
+
4
+ try:
5
+ import evervault
6
+ except ImportError:
7
+ evervault = None
8
+ else:
9
+ EVERVAULT_CLIENT = None
10
+
11
+ EvervaultData = dict[str, (bytes | list | dict | set | str)]
12
+
13
+
14
+ if settings.ENCRYPTION_METHOD == EncryptionMethod.EVERVAULT:
15
+ if not (
16
+ settings.EVERVAULT_APP_ID
17
+ and settings.EVERVAULT_API_KEY
18
+ and settings.EVERVAULT_ENCRYPTION_ROLE
19
+ ):
20
+ raise ValueError(
21
+ "Evervault settings are not configured. Please set the following environment variables: EVERVAULT_APP_ID, EVERVAULT_API_KEY, EVERVAULT_ENCRYPTION_ROLE."
22
+ )
23
+
24
+ if not evervault:
25
+ raise ValueError(
26
+ "Evervault is not available. Please install this package with the `evervault` extra."
27
+ )
28
+
29
+ EVERVAULT_CLIENT = evervault.Client(
30
+ app_uuid=settings.EVERVAULT_APP_ID, api_key=settings.EVERVAULT_API_KEY
31
+ )
32
+
33
+
34
+ def evervault_encrypt(
35
+ fields: dict[str, str],
36
+ ) -> EvervaultData:
37
+ """Encrypt data using Evervault."""
38
+
39
+ return EVERVAULT_CLIENT.encrypt(fields, role=settings.EVERVAULT_ENCRYPTION_ROLE)
40
+
41
+
42
+ def evervault_decrypt(
43
+ fields: EvervaultData,
44
+ ) -> EvervaultData:
45
+ """Decrypt data using Evervault."""
46
+
47
+ return EVERVAULT_CLIENT.decrypt(fields)
@@ -0,0 +1,56 @@
1
+ try:
2
+ from cryptography.fernet import Fernet
3
+ except ImportError:
4
+ pass
5
+ else:
6
+ FERNET_CLIENT = None
7
+
8
+ from pydantic_encryption.config import settings
9
+ from pydantic_encryption.annotations import EncryptionMethod
10
+ from pydantic_encryption.models.encryptable import EncryptedValue, DecryptedValue
11
+
12
+ if settings.ENCRYPTION_METHOD == EncryptionMethod.FERNET:
13
+ if not settings.ENCRYPTION_KEY:
14
+ raise ValueError(
15
+ "Fernet is not available. Please set the ENCRYPTION_KEY environment variable."
16
+ )
17
+
18
+ FERNET_CLIENT = FERNET_CLIENT or Fernet(settings.ENCRYPTION_KEY)
19
+
20
+
21
+ def fernet_encrypt(
22
+ plaintext: bytes | str | EncryptedValue,
23
+ ) -> EncryptedValue:
24
+ """Encrypt data using Fernet."""
25
+
26
+ if isinstance(plaintext, EncryptedValue):
27
+ return plaintext
28
+
29
+ if isinstance(plaintext, str):
30
+ plaintext = plaintext.encode("utf-8")
31
+
32
+ encrypted_value = EncryptedValue(FERNET_CLIENT.encrypt(plaintext))
33
+
34
+ return encrypted_value
35
+
36
+
37
+ def fernet_decrypt(
38
+ ciphertext: str | bytes | EncryptedValue,
39
+ ) -> DecryptedValue:
40
+ """Decrypt data using Fernet."""
41
+
42
+ if isinstance(ciphertext, DecryptedValue):
43
+ return ciphertext
44
+
45
+ if isinstance(ciphertext, str):
46
+ try:
47
+ ciphertext_bytes = ciphertext.encode("utf-8")
48
+ except UnicodeDecodeError:
49
+ ciphertext_bytes = str(ciphertext)
50
+ else:
51
+ ciphertext_bytes = ciphertext
52
+
53
+ decrypted_bytes = FERNET_CLIENT.decrypt(ciphertext_bytes)
54
+ decrypted_value = decrypted_bytes.decode("utf-8")
55
+
56
+ return DecryptedValue(decrypted_value)
@@ -0,0 +1 @@
1
+ from .argon2 import argon2_hash_data
@@ -0,0 +1,20 @@
1
+ from argon2 import PasswordHasher
2
+ from pydantic_encryption.models.encryptable import HashedValue
3
+
4
+
5
+ argon2_hasher = PasswordHasher()
6
+
7
+
8
+ def argon2_hash_data(value: str | bytes | HashedValue) -> HashedValue:
9
+ """Hash data using Argon2.
10
+
11
+ This function will not re-hash values that already have the 'hashed' flag set to True
12
+ Otherwise, it will hash the value using Argon2 and return a HashableString.
13
+ """
14
+
15
+ if isinstance(value, HashedValue):
16
+ return value
17
+
18
+ hashed_value = HashedValue(argon2_hasher.hash(value))
19
+
20
+ return hashed_value
@@ -0,0 +1,3 @@
1
+ from .secure_model import *
2
+ from .base import *
3
+ from .adapters import *
@@ -0,0 +1,4 @@
1
+ from .sqlalchemy import (
2
+ SQLAlchemyEncrypted,
3
+ SQLAlchemyHashed,
4
+ )
@@ -0,0 +1,143 @@
1
+ try:
2
+ from sqlalchemy.types import TypeDecorator, LargeBinary
3
+ except ImportError:
4
+ sqlalchemy_available = False
5
+ else:
6
+ sqlalchemy_available = True
7
+
8
+ from pydantic_encryption.lib.adapters import encryption, hashing
9
+ from pydantic_encryption.annotations import EncryptionMethod
10
+ from pydantic_encryption.models.encryptable import (
11
+ EncryptedValue,
12
+ DecryptedValue,
13
+ HashedValue,
14
+ )
15
+ from pydantic_encryption.config import settings
16
+
17
+
18
+ class SQLAlchemyEncrypted(TypeDecorator):
19
+ """Type adapter for SQLAlchemy to encrypt and decrypt strings using the specified encryption method."""
20
+
21
+ impl = LargeBinary
22
+ cache_ok = True
23
+
24
+ def __init__(
25
+ self,
26
+ *args,
27
+ **kwargs,
28
+ ):
29
+ if not sqlalchemy_available:
30
+ raise ImportError(
31
+ "SQLAlchemy is not available. Please install this package with the `sqlalchemy` extra."
32
+ )
33
+
34
+ super().__init__(*args, **kwargs)
35
+
36
+ def _process_encrypt_value(
37
+ self, value: str | bytes | None
38
+ ) -> EncryptedValue | None:
39
+ if value is None:
40
+ return None
41
+
42
+ match settings.ENCRYPTION_METHOD:
43
+ case EncryptionMethod.FERNET:
44
+ return encryption.fernet_encrypt(value)
45
+ case EncryptionMethod.EVERVAULT:
46
+ return encryption.evervault_encrypt(value)
47
+ case EncryptionMethod.AWS:
48
+ return encryption.aws_encrypt(value)
49
+
50
+ def _process_decrypt_value(self, value: str | bytes | None) -> str | bytes | None:
51
+ if value is None:
52
+ return None
53
+
54
+ match settings.ENCRYPTION_METHOD:
55
+ case EncryptionMethod.FERNET:
56
+ return encryption.fernet_decrypt(value)
57
+ case EncryptionMethod.EVERVAULT:
58
+ return encryption.evervault_decrypt(value)
59
+ case EncryptionMethod.AWS:
60
+ value = encryption.aws_decrypt(value)
61
+ return value
62
+
63
+ def process_bind_param(
64
+ self, value: str | bytes | None, dialect
65
+ ) -> str | bytes | None:
66
+ """Encrypts a string before binding it to the database."""
67
+
68
+ return self._process_encrypt_value(value)
69
+
70
+ def process_literal_param(
71
+ self, value: str | bytes | None, dialect
72
+ ) -> str | bytes | None:
73
+ """Encrypts a string for literal SQL expressions."""
74
+
75
+ return self._process_encrypt_value(value)
76
+
77
+ def process_result_value(
78
+ self, value: str | bytes | None, dialect
79
+ ) -> DecryptedValue | None:
80
+ """Decrypts a string after retrieving it from the database."""
81
+
82
+ if value is None:
83
+ return None
84
+
85
+ decrypted_value = self._process_decrypt_value(value)
86
+
87
+ return DecryptedValue(decrypted_value)
88
+
89
+ @property
90
+ def python_type(self):
91
+ """Return the Python type this is bound to (str)."""
92
+
93
+ return self.impl.python_type
94
+
95
+
96
+ class SQLAlchemyHashed(TypeDecorator):
97
+ """Type adapter for SQLAlchemy to hash strings using Argon2."""
98
+
99
+ impl = LargeBinary
100
+ cache_ok = True
101
+
102
+ def __init__(self, *args, **kwargs):
103
+ if not sqlalchemy_available:
104
+ raise ImportError(
105
+ "SQLAlchemy is not available. Please install this package with the `sqlalchemy` extra."
106
+ )
107
+
108
+ super().__init__(*args, **kwargs)
109
+
110
+ def process_bind_param(self, value: str | bytes | None, dialect) -> bytes | None:
111
+ """Hashes a string before binding it to the database."""
112
+
113
+ if value is None:
114
+ return None
115
+
116
+ return hashing.argon2_hash_data(value)
117
+
118
+ def process_literal_param(
119
+ self, value: str | bytes | None, dialect
120
+ ) -> HashedValue | None:
121
+ """Hashes a string for literal SQL expressions."""
122
+
123
+ if value is None:
124
+ return None
125
+
126
+ processed = hashing.argon2_hash_data(value)
127
+
128
+ return dialect.literal_processor(self.impl)(processed)
129
+
130
+ def process_result_value(
131
+ self, value: str | bytes | None, dialect
132
+ ) -> HashedValue | None:
133
+ """Returns the hash value as-is from the database, wrapped as a HashableBinary."""
134
+
135
+ if value is None:
136
+ return None
137
+
138
+ return HashedValue(value)
139
+
140
+ @property
141
+ def python_type(self):
142
+ """Return the Python type this is bound to (str)."""
143
+ return self.impl.python_type
@@ -0,0 +1,16 @@
1
+ from typing import Any
2
+
3
+ from super_model import SuperModel
4
+
5
+ from . import SecureModel
6
+
7
+ __all__ = ["BaseModel"]
8
+
9
+
10
+ class BaseModel(SuperModel, SecureModel):
11
+ """Base model for encryptable models."""
12
+
13
+ def model_post_init(self, context: Any, /) -> None:
14
+ self.default_post_init()
15
+
16
+ super().model_post_init(context)
@@ -0,0 +1,30 @@
1
+ class NormalizeToBytes(bytes):
2
+ """Normalize a value to bytes."""
3
+
4
+ def __new__(cls, value: str | bytes):
5
+ if isinstance(value, str):
6
+ value = value.encode("utf-8")
7
+
8
+ return super().__new__(cls, value)
9
+
10
+
11
+ class NormalizeToString(str):
12
+ """Normalize a value to string."""
13
+
14
+ def __new__(cls, value: str | bytes):
15
+ if isinstance(value, bytes):
16
+ value = value.decode("utf-8")
17
+
18
+ return super().__new__(cls, value)
19
+
20
+
21
+ class EncryptedValue(NormalizeToBytes):
22
+ encrypted: bool = True
23
+
24
+
25
+ class DecryptedValue(NormalizeToString):
26
+ encrypted: bool = False
27
+
28
+
29
+ class HashedValue(NormalizeToBytes):
30
+ hashed: bool = True
@@ -0,0 +1,202 @@
1
+ from typing import (
2
+ Annotated,
3
+ Optional,
4
+ Union,
5
+ get_args,
6
+ get_origin,
7
+ get_type_hints,
8
+ Any,
9
+ )
10
+
11
+ from pydantic_encryption.lib import argon2, fernet, evervault, aws
12
+ from pydantic_encryption.annotations import Encrypt, Decrypt, Hash, EncryptionMethod
13
+ from pydantic_encryption.config import settings
14
+
15
+
16
+ __all__ = ["SecureModel"]
17
+
18
+
19
+ class SecureModel:
20
+ """Base class for encryptable and hashable models."""
21
+
22
+ _disable: Optional[bool] = None
23
+
24
+ def __init_subclass__(
25
+ cls,
26
+ *,
27
+ disable: bool = False,
28
+ **kwargs,
29
+ ) -> None:
30
+ cls._disable = disable
31
+ super().__init_subclass__(**kwargs)
32
+
33
+ def encrypt_data(self) -> None:
34
+ """Encrypt data using the specified encryption method."""
35
+
36
+ if self._disable:
37
+ return
38
+
39
+ if not self.pending_encryption_fields:
40
+ return
41
+
42
+ encrypted_data: dict[str, str] = {}
43
+
44
+ match settings.ENCRYPTION_METHOD:
45
+ case EncryptionMethod.EVERVAULT:
46
+ encrypted_data = evervault.evervault_encrypt(
47
+ self.pending_encryption_fields
48
+ )
49
+
50
+ case EncryptionMethod.FERNET:
51
+ encrypted_data = {
52
+ field_name: fernet.fernet_encrypt(value)
53
+ for field_name, value in self.pending_encryption_fields.items()
54
+ }
55
+ case EncryptionMethod.AWS:
56
+ encrypted_data = {
57
+ field_name: aws.aws_encrypt(value)
58
+ for field_name, value in self.pending_encryption_fields.items()
59
+ }
60
+
61
+ for field_name, value in encrypted_data.items():
62
+ setattr(self, field_name, value)
63
+
64
+ def decrypt_data(self) -> None:
65
+ """Decrypt data using the specified encryption method. After this call, all decrypted fields are type str."""
66
+
67
+ if self._disable:
68
+ return
69
+
70
+ if not self.pending_decryption_fields:
71
+ return
72
+
73
+ decrypted_data: dict[str, str] = {}
74
+
75
+ match settings.ENCRYPTION_METHOD:
76
+ case EncryptionMethod.EVERVAULT:
77
+ decrypted_data = evervault.evervault_decrypt(
78
+ self.pending_decryption_fields
79
+ )
80
+
81
+ case EncryptionMethod.FERNET:
82
+ decrypted_data = {
83
+ field_name: fernet.fernet_decrypt(value)
84
+ for field_name, value in self.pending_decryption_fields.items()
85
+ }
86
+ case EncryptionMethod.AWS:
87
+ decrypted_data = {
88
+ field_name: aws.aws_decrypt(value)
89
+ for field_name, value in self.pending_decryption_fields.items()
90
+ }
91
+
92
+ for field_name, value in decrypted_data.items():
93
+ setattr(self, field_name, value)
94
+
95
+ def hash_data(self) -> None:
96
+ """Hash fields marked with `Hash` annotation."""
97
+
98
+ if self._disable:
99
+ return
100
+
101
+ if not self.pending_hash_fields:
102
+ return
103
+
104
+ for field_name, value in self.pending_hash_fields.items():
105
+ hashed = argon2.argon2_hash_data(value)
106
+
107
+ setattr(self, field_name, hashed)
108
+
109
+ def default_post_init(self) -> None:
110
+ """Post initialization hook. If you make your own BaseModel, you must call this in model_post_init()."""
111
+
112
+ if not self._disable:
113
+ if self.pending_encryption_fields:
114
+ self.encrypt_data()
115
+
116
+ if self.pending_hash_fields:
117
+ self.hash_data()
118
+
119
+ if self.pending_decryption_fields:
120
+ self.decrypt_data()
121
+
122
+ def get_annotated_fields(self, *annotations: type) -> dict[str, str]:
123
+ """Get fields that have the specified annotations, handling union types.
124
+
125
+ Args:
126
+ annotations: The annotations to look for
127
+
128
+ Returns:
129
+ A dictionary of field names to field values
130
+ """
131
+
132
+ def has_annotation(target_type, target_annotations):
133
+ """Check if a type has any of the target annotations."""
134
+
135
+ # Direct match
136
+ if any(
137
+ target_type is ann or target_type == ann for ann in target_annotations
138
+ ):
139
+ return True
140
+
141
+ # Annotated type
142
+ if get_origin(target_type) is Annotated:
143
+ for arg in get_args(target_type)[1:]: # Skip first arg (the type)
144
+ if any(arg is ann or arg == ann for ann in target_annotations):
145
+ return True
146
+
147
+ return False
148
+
149
+ type_hints = get_type_hints(type(self), include_extras=True)
150
+ annotated_fields: dict[str, str] = {}
151
+
152
+ for field_name, field_annotation in type_hints.items():
153
+ found_annotation = False
154
+
155
+ # Direct check
156
+ if has_annotation(field_annotation, annotations):
157
+ found_annotation = True
158
+
159
+ # Check union types
160
+ elif get_origin(field_annotation) is Union:
161
+ for arg in get_args(field_annotation):
162
+
163
+ if has_annotation(arg, annotations):
164
+ found_annotation = True
165
+
166
+ break
167
+
168
+ if found_annotation:
169
+ field_value = getattr(self, field_name, None)
170
+
171
+ if field_value is not None:
172
+ annotated_fields[field_name] = field_value
173
+
174
+ return annotated_fields
175
+
176
+ @classmethod
177
+ def _get_class_parameter(cls, parameter_name: str) -> Any:
178
+ """Get a class parameter from the class or its parent classes."""
179
+
180
+ for base in cls.__mro__[1:]:
181
+ if hasattr(base, parameter_name):
182
+ return getattr(base, parameter_name)
183
+
184
+ return None
185
+
186
+ @property
187
+ def pending_encryption_fields(self) -> dict[str, str]:
188
+ """Get all encrypted fields from the model."""
189
+
190
+ return self.get_annotated_fields(Encrypt)
191
+
192
+ @property
193
+ def pending_decryption_fields(self) -> dict[str, str]:
194
+ """Get all decrypted fields from the model."""
195
+
196
+ return self.get_annotated_fields(Decrypt)
197
+
198
+ @property
199
+ def pending_hash_fields(self) -> dict[str, str]:
200
+ """Get all hashable fields from the model."""
201
+
202
+ return self.get_annotated_fields(Hash)
@@ -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,361 @@
1
+ Metadata-Version: 2.3
2
+ Name: pydantic_encryption
3
+ Version: 0.0.2
4
+ Summary: Encryption and Hashing Models for Pydantic
5
+ Author: Julien Kmec
6
+ Author-email: me@julien.dev
7
+ Requires-Python: >=3.11.0,<3.14
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Provides-Extra: dev
13
+ Provides-Extra: sqlalchemy
14
+ Requires-Dist: argon2-cffi (>=23.1.0,<24.0.0)
15
+ Requires-Dist: aws-encryption-sdk[mpl] (>=4.0.1,<5.0.0)
16
+ Requires-Dist: boto3 (>=1.38.8,<2.0.0)
17
+ Requires-Dist: coverage (>=7.8.0) ; extra == "dev"
18
+ Requires-Dist: evervault (>=4.4.1)
19
+ Requires-Dist: psycopg2-binary (>=2.9.10,<3.0.0) ; extra == "dev"
20
+ Requires-Dist: pydantic (>=2.10.6)
21
+ Requires-Dist: pydantic-settings (>=2.9.1)
22
+ Requires-Dist: pydantic-super-model (>=1.0.2,<2.0.0)
23
+ Requires-Dist: pytest (>=8.3.5) ; extra == "dev"
24
+ Requires-Dist: pytest-asyncio (>=0.26.0,<0.27.0) ; extra == "dev"
25
+ Requires-Dist: pytest-cov (>=6.1.1,<7.0.0) ; extra == "dev"
26
+ Requires-Dist: pytest-docker (>=3.2.1,<4.0.0) ; extra == "dev"
27
+ Requires-Dist: pytest-env (>=1.1.5,<2.0.0) ; extra == "dev"
28
+ Requires-Dist: pytest-sqlalchemy (>=0.3.0,<0.4.0) ; extra == "dev"
29
+ Requires-Dist: sqlalchemy (>=2.0.40,<3.0.0) ; extra == "sqlalchemy"
30
+ Requires-Dist: sqlalchemy-utils (>=0.41.2,<0.42.0) ; extra == "dev"
31
+ Requires-Dist: sqlmodel (>=0.0.24,<0.0.25) ; extra == "sqlalchemy"
32
+ Description-Content-Type: text/markdown
33
+
34
+ # Encryption and Hashing Models for Pydantic
35
+
36
+ This package provides Pydantic field annotations that encrypt, decrypt, and hash field values.
37
+
38
+ ## Installation
39
+
40
+ Install with [pip](https://pip.pypa.io/en/stable/):
41
+ ```bash
42
+ pip install "pydantic_encryption[sqlalchemy]"
43
+ ```
44
+
45
+ Install with [Poetry](https://python-poetry.org/docs/):
46
+ ```bash
47
+ poetry add pydantic_encryption --E sqlalchemy
48
+ ```
49
+
50
+ ### Optional extras
51
+
52
+ - `sqlalchemy`: Built-in SQLAlchemy integration
53
+ - `dev`: Development and test dependencies
54
+
55
+ ## Features
56
+
57
+ - Encrypt and decrypt specific fields
58
+ - Hash specific fields
59
+ - Built-in SQLAlchemy integration
60
+ - Support for AWS KMS (Key Management Service) single-region
61
+ - Support for Fernet symmetric encryption and Evervault
62
+ - Support for generics
63
+
64
+ ## Example
65
+
66
+ ```python
67
+ from typing import Annotated
68
+ from pydantic_encryption import BaseModel, Encrypt, Hash
69
+
70
+ class User(BaseModel):
71
+ name: str
72
+ address: Annotated[bytes, Encrypt] # This field will be encrypted
73
+ password: Annotated[bytes, Hash] # This field will be hashed
74
+
75
+ user = User(name="John Doe", address="123456", password="secret123")
76
+
77
+ print(user.name) # plaintext (untouched)
78
+ print(user.address) # encrypted
79
+ print(user.password) # hashed
80
+ ```
81
+
82
+ ## SQLAlchemy Integration
83
+
84
+ If you install this package with the `sqlalchemy` extra, you can use the built-in SQLAlchemy integration for the columns.
85
+
86
+ SQLAlchemy will automatically handle the encryption/decryption of fields with the `SQLAlchemyEncrypted` type and the hashing of fields with the `SQLAlchemyHashed` type.
87
+
88
+ When you create a new instance of the model, the fields will be encrypted and when you query the database, the fields will be decrypted.
89
+
90
+ ### Example:
91
+
92
+ ```python
93
+ import uuid
94
+ from pydantic_encryption import SQLAlchemyEncrypted, SQLAlchemyHashed
95
+ from sqlmodel import SQLModel, Field
96
+ from sqlalchemy import create_engine
97
+ from sqlalchemy.orm import sessionmaker
98
+
99
+ # Define our schema
100
+ class User(Base, table=True):
101
+ __tablename__ = "users"
102
+
103
+ username: str = Field(default=None)
104
+ email: bytes = Field(
105
+ default=None,
106
+ sa_type=SQLAlchemyEncrypted(),
107
+ )
108
+ password: bytes = Field(
109
+ sa_type=SQLAlchemyHashed(),
110
+ nullable=False,
111
+ )
112
+
113
+ # Create the database
114
+ engine = create_engine("sqlite:///:memory:")
115
+ SQLModel.metadata.create_all(engine)
116
+ Session = sessionmaker(bind=engine)
117
+ session = Session()
118
+
119
+ # Create a user
120
+ user = User(username="john_doe", email="john@example.com", password="secret123") # The email and password will be encrypted/hashed automatically
121
+
122
+ session.add(user)
123
+ session.commit()
124
+
125
+ # Query the user
126
+ user = session.query(User).filter_by(username="john_doe").first()
127
+
128
+ print(user.email) # decrypted
129
+ print(user.password) # hashed
130
+ ```
131
+
132
+ ## Choose an Encryption Method
133
+
134
+ You can choose which encryption algorithm to use by setting the `ENCRYPTION_METHOD` environment variable.
135
+
136
+ Valid values are:
137
+ - `fernet`: Fernet symmetric encryption
138
+ - `aws`: AWS KMS
139
+ - `evervault`: [Evervault](https://evervault.com/)
140
+
141
+ See [config.py](https://github.com/julien777z/pydantic-encryption/blob/main/pydantic_encryption/config.py) for the possible environment variables.
142
+
143
+ ### Example:
144
+
145
+ `.env`
146
+ ```env
147
+ ENCRYPTION_METHOD=aws
148
+ AWS_KMS_KEY_ARN=123
149
+ AWS_KMS_REGION=us-east-1
150
+ AWS_ACCESS_KEY_ID=123
151
+ AWS_SECRET_ACCESS_KEY=123
152
+ ```
153
+
154
+ ```python
155
+ from typing import Annotated
156
+ from pydantic_encryption import BaseModel, Encrypt
157
+
158
+ class User(BaseModel):
159
+ name: str
160
+ address: Annotated[bytes, Encrypt] # This field will be encrypted by AWS KMS
161
+ ```
162
+
163
+ ### Default Encryption (Fernet Symmetric Encryption)
164
+
165
+ By default, Fernet will be used for encryption and decryption.
166
+
167
+ First you need to generate an encryption key. You can use the following command:
168
+
169
+ ```bash
170
+ openssl rand -base64 32
171
+ ```
172
+
173
+ Then set the following environment variable or add it to your `.env` file:
174
+
175
+ ```bash
176
+ ENCRYPTION_KEY=your_encryption_key
177
+ ```
178
+
179
+ ### Custom Encryption or Hashing
180
+
181
+ You can define your own encryption or hashing methods by subclassing `SecureModel`. `SecureModel` provides you with the utilities to handle encryption, decryption, and hashing.
182
+
183
+ `self.pending_encryption_fields`, `self.pending_decryption_fields`, and `self.pending_hash_fields` are dictionaries of field names to field values that need to be encrypted, decrypted, or hashed, i.e., fields annotated with `Encrypt`, `Decrypt`, or `Hash`.
184
+
185
+ You can override the `encrypt_data`, `decrypt_data`, and `hash_data` methods to implement your own encryption, decryption, and hashing logic. You then need to override `model_post_init` to call these methods or use the default implementation accessible via `self.default_post_init()`.
186
+
187
+ First, define a custom secure model:
188
+
189
+ ```python
190
+ from typing import Any, override
191
+ from pydantic import BaseModel as PydanticBaseModel
192
+ from pydantic_encryption import SecureModel
193
+
194
+ class MySecureModel(PydanticBaseModel, SecureModel):
195
+ @override
196
+ def encrypt_data(self) -> None:
197
+ # Your encryption logic here
198
+ pass
199
+
200
+ @override
201
+ def decrypt_data(self) -> None:
202
+ # Your decryption logic here
203
+ pass
204
+
205
+ @override
206
+ def hash_data(self) -> None:
207
+ # Your hashing logic here
208
+ pass
209
+
210
+ @override
211
+ def model_post_init(self, context: Any, /) -> None:
212
+ # Either define your own logic, for example:
213
+
214
+ # if not self._disable:
215
+ # if self.pending_decryption_fields:
216
+ # self.decrypt_data()
217
+
218
+ # if self.pending_encryption_fields:
219
+ # self.encrypt_data()
220
+
221
+ # if self.pending_hash_fields:
222
+ # self.hash_data()
223
+
224
+ # Or use the default logic:
225
+ self.default_post_init()
226
+
227
+ super().model_post_init(context)
228
+ ```
229
+
230
+ Then use it:
231
+
232
+ ```python
233
+ from typing import Annotated
234
+ from pydantic import BaseModel # Here, we don't use the BaseModel provided by the library, but the native one from Pydantic
235
+ from pydantic_encryption import Encrypt
236
+
237
+ class MyModel(BaseModel, MySecureModel):
238
+ username: str
239
+ address: Annotated[bytes, Encrypt]
240
+
241
+ model = MyModel(username="john_doe", address="123456")
242
+ print(model.address) # encrypted
243
+ ```
244
+
245
+ ## Encryption
246
+
247
+ You can encrypt any field by using the `Encrypt` annotation with `Annotated` and inheriting from `BaseModel`.
248
+
249
+ ```python
250
+ from typing import Annotated
251
+ from pydantic_encryption import Encrypt, BaseModel
252
+
253
+ class User(BaseModel):
254
+ name: str
255
+ address: Annotated[bytes, Encrypt] # This field will be encrypted
256
+
257
+ user = User(name="John Doe", address="123456")
258
+ print(user.address) # encrypted
259
+ print(user.name) # plaintext (untouched)
260
+ ```
261
+
262
+ The fields marked with `Encrypt` are automatically encrypted during model initialization.
263
+
264
+ ## Decryption
265
+
266
+ Similar to encryption, you can decrypt any field by using the `Decrypt` annotation with `Annotated` and inheriting from `BaseModel`.
267
+
268
+ ```python
269
+ from typing import Annotated
270
+ from pydantic_encryption import Decrypt, BaseModel
271
+
272
+ class UserResponse(BaseModel):
273
+ name: str
274
+ address: Annotated[bytes, Decrypt] # This field will be decrypted
275
+
276
+ user = UserResponse(**user_data) # encrypted value
277
+ print(user.address) # decrypted
278
+ print(user.name) # plaintext (untouched)
279
+ ```
280
+
281
+ Fields marked with `Decrypt` are automatically decrypted during model initialization.
282
+
283
+ Note: if you use `SQLAlchemyEncrypted`, then the value will be decrypted automatically when you query the database.
284
+
285
+
286
+ ## Hashing
287
+
288
+ You can hash sensitive data like passwords by using the `Hash` annotation.
289
+
290
+ ```python
291
+ from typing import Annotated
292
+ from pydantic_encryption import Hash, BaseModel
293
+
294
+ class User(BaseModel):
295
+ username: str
296
+ password: Annotated[bytes, Hash] # This field will be hashed
297
+
298
+ user = User(username="john_doe", password="secret123")
299
+ print(user.password) # hashed value
300
+ ```
301
+
302
+ Fields marked with `Hash` are automatically hashed using bcrypt during model initialization.
303
+
304
+ ## Disable Auto Processing
305
+
306
+ You can disable automatic encryption/decryption/hashing by setting `disable` to `True` in the class definition.
307
+
308
+ ```python
309
+ from typing import Annotated
310
+ from pydantic_encryption import Encrypt, BaseModel
311
+
312
+ class UserResponse(BaseModel, disable=True):
313
+ name: str
314
+ address: Annotated[bytes, Encrypt]
315
+
316
+ # To encrypt/decrypt/hash, call the respective methods manually:
317
+ user = UserResponse(name="John Doe", address="123 Main St")
318
+
319
+ # Manual encryption
320
+ user.encrypt_data()
321
+ print(user.address) # encrypted
322
+
323
+ # Or user.decrypt_data() to decrypt and user.hash_data() to hash
324
+ ```
325
+
326
+ ## Generics
327
+
328
+ Each BaseModel has an additional helpful method that will tell you its generic type.
329
+
330
+ ```py
331
+ from pydantic_encryption import BaseModel
332
+
333
+ class MyModel[T](BaseModel):
334
+ value: T
335
+
336
+ model = MyModel[str](value="Hello")
337
+ print(model.get_type()) # <class 'str'>
338
+ ```
339
+
340
+ ## Run Tests
341
+
342
+ Install [Poetry](https://python-poetry.org/docs/) and run:
343
+
344
+ ```bash
345
+ poetry install --with test
346
+ poetry run coverage run -m pytest -v -s
347
+ ```
348
+
349
+ ## Roadmap
350
+
351
+ This is an early development version. I am considering the following features:
352
+
353
+ - [ ] Add optional support for other encryption providers beyond Evervault
354
+ - [x] Add support for AWS KMS and other key management services
355
+ - [ ] Native encryption via PostgreSQL and other databases
356
+ - [ ] Specifying encryption key per table or row instead of globally
357
+
358
+ ## Feature Requests
359
+
360
+ If you have any feature requests, please open an issue.
361
+
@@ -0,0 +1,21 @@
1
+ pydantic_encryption/__init__.py,sha256=T7oLh0VmSDQQsm1RJEIYfqQad4OLjZVEjFmrttUgf-U,68
2
+ pydantic_encryption/annotations.py,sha256=nqYD430qroj_elWXhrW53cQkbudrhiq9EyRHWxd4DwQ,604
3
+ pydantic_encryption/config.py,sha256=GwkPfJ5tTiLjWRkSnnc2F4hM5zbB-N5Bq9aGxXGBVHQ,906
4
+ pydantic_encryption/lib/__init__.py,sha256=ur0laXOsXqbcQWrx11bJ2BQLlnofNK6ftH3OjR8Mt4E,93
5
+ pydantic_encryption/lib/adapters/encryption/__init__.py,sha256=slNvvpbCCY9D0OQerxnC-HRsSenbsHUemr-ww-gbRc4,153
6
+ pydantic_encryption/lib/adapters/encryption/aws.py,sha256=Zi8LSSlH4oIHdMCLH22czDduHjci07hcY6Xk6L05soE,2651
7
+ pydantic_encryption/lib/adapters/encryption/evervault.py,sha256=AFnCgqwAInmhOsnrKXS_AcI6BoucAYhnnnaCfMeV6nA,1321
8
+ pydantic_encryption/lib/adapters/encryption/fernet.py,sha256=hzehv51HKrbcBnuiQBuTnukf6d7kK-3b79C7oyAB4E4,1570
9
+ pydantic_encryption/lib/adapters/hashing/__init__.py,sha256=UFLrgoQYEWaq9lLk-Wq_nkQaJ5VuG0rMn4uwQKUIfPc,37
10
+ pydantic_encryption/lib/adapters/hashing/argon2.py,sha256=cl6cefTi0c5wlnAic1SsFiwF0YKl68KcyLpm_Reypb4,560
11
+ pydantic_encryption/models/__init__.py,sha256=ndC3tQ3rUt5PzHRuLuQDAFah3D9VunkOBbubXVz_H5I,72
12
+ pydantic_encryption/models/adapters/__init__.py,sha256=v1ZAuqGoP_svmVCa8wGx9XWUVkrQx3lWFmnA4BkdI-o,75
13
+ pydantic_encryption/models/adapters/sqlalchemy.py,sha256=Ku90wyv_KMo0Ef6TTh_BMSq6udJOXTZTS84xlcqCFOA,4308
14
+ pydantic_encryption/models/base.py,sha256=1shweK1IhrUDP2iU0YFxUKaX86C5keu1n2BVDraPZyE,332
15
+ pydantic_encryption/models/encryptable.py,sha256=716AKoWIGdIza35YSJPxIfEJjjXvoi7Q4xruwbu6Le8,673
16
+ pydantic_encryption/models/secure_model.py,sha256=kVecrKKmT6tpXz8VtnlQ17ZJjiNysar0uCJNH2GbEhs,6253
17
+ pydantic_encryption-0.0.2.dist-info/LICENSE,sha256=dFNs5hXEzJ71UQDYyZIiVfY-N_Q8DOP4TD7LNoktmHo,1068
18
+ pydantic_encryption-0.0.2.dist-info/METADATA,sha256=66S0entVKQEe72UgzWfjOheTbWoZxneDPacNyNYVZRs,10704
19
+ pydantic_encryption-0.0.2.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
20
+ pydantic_encryption-0.0.2.dist-info/entry_points.txt,sha256=AT3gClO05RdAWPgP3acTdbY8B4v3nC45XaU1ODcvaag,48
21
+ pydantic_encryption-0.0.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.1.3
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ tests=scripts.run_tests:main
3
+