pydantic_encryption 0.3.1__tar.gz → 0.4.0__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.
Files changed (20) hide show
  1. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/PKG-INFO +35 -2
  2. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/README.md +33 -0
  3. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/__init__.py +11 -1
  4. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/integrations/sqlalchemy.py +53 -1
  5. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/models/base.py +35 -53
  6. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pyproject.toml +3 -3
  7. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/LICENSE +0 -0
  8. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/_lazy.py +0 -0
  9. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/adapters/__init__.py +0 -0
  10. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/adapters/base.py +0 -0
  11. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/adapters/encryption/__init__.py +0 -0
  12. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/adapters/encryption/aws.py +0 -0
  13. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/adapters/encryption/evervault.py +0 -0
  14. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/adapters/encryption/fernet.py +0 -0
  15. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/adapters/hashing/__init__.py +0 -0
  16. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/adapters/hashing/argon2.py +0 -0
  17. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/config.py +0 -0
  18. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/integrations/__init__.py +0 -0
  19. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/models/__init__.py +0 -0
  20. {pydantic_encryption-0.3.1 → pydantic_encryption-0.4.0}/pydantic_encryption/types.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pydantic_encryption
3
- Version: 0.3.1
3
+ Version: 0.4.0
4
4
  Summary: Encryption and Hashing Models for Pydantic
5
5
  License-File: LICENSE
6
6
  Author: Julien Kmec
@@ -29,7 +29,7 @@ Requires-Dist: polyfactory (>=2.0.0) ; extra == "dev"
29
29
  Requires-Dist: psycopg2-binary (>=2.9.10) ; extra == "dev"
30
30
  Requires-Dist: pydantic (>=2.10.6)
31
31
  Requires-Dist: pydantic-settings (>=2.9.1)
32
- Requires-Dist: pydantic-super-model (>=1.1.2)
32
+ Requires-Dist: pydantic-super-model (>=1.2.0)
33
33
  Requires-Dist: pytest (>=8.3.5) ; extra == "dev"
34
34
  Requires-Dist: pytest-asyncio (>=0.26.0) ; extra == "dev"
35
35
  Requires-Dist: pytest-cov (>=6.1.1) ; extra == "dev"
@@ -187,6 +187,39 @@ class User(Base, table=True):
187
187
  session_duration: timedelta = Field(sa_type=SQLAlchemyEncrypted())
188
188
  ```
189
189
 
190
+ ### Array Support (PostgreSQL)
191
+
192
+ You can encrypt arrays of values using `SQLAlchemyPGEncryptedArray`. Each element in the array is individually encrypted and stored in a PostgreSQL `ARRAY(bytea)` column.
193
+
194
+ ```python
195
+ from pydantic_encryption.integrations.sqlalchemy import SQLAlchemyPGEncryptedArray
196
+ from sqlmodel import SQLModel, Field
197
+
198
+ class User(Base, table=True):
199
+ __tablename__ = "users"
200
+
201
+ username: str = Field(default=None)
202
+ tags: list[str] | None = Field(
203
+ default=None,
204
+ sa_type=SQLAlchemyPGEncryptedArray(),
205
+ )
206
+ ```
207
+
208
+ All [supported types](#supported-types) can be used as array elements. Arrays can even contain mixed types, as each element is self-describing:
209
+
210
+ ```python
211
+ # String arrays
212
+ user.tags = ["admin", "moderator"]
213
+
214
+ # Integer arrays
215
+ user.scores = [100, 95, 87]
216
+
217
+ # Mixed types also work
218
+ user.metadata = [42, "hello", 3.14]
219
+ ```
220
+
221
+ **Note:** `SQLAlchemyPGEncryptedArray` requires a PostgreSQL backend since it uses PostgreSQL's native `ARRAY` type.
222
+
190
223
  ## Choose an Encryption Method
191
224
 
192
225
  You can choose which encryption algorithm to use by setting the `ENCRYPTION_METHOD` environment variable.
@@ -141,6 +141,39 @@ class User(Base, table=True):
141
141
  session_duration: timedelta = Field(sa_type=SQLAlchemyEncrypted())
142
142
  ```
143
143
 
144
+ ### Array Support (PostgreSQL)
145
+
146
+ You can encrypt arrays of values using `SQLAlchemyPGEncryptedArray`. Each element in the array is individually encrypted and stored in a PostgreSQL `ARRAY(bytea)` column.
147
+
148
+ ```python
149
+ from pydantic_encryption.integrations.sqlalchemy import SQLAlchemyPGEncryptedArray
150
+ from sqlmodel import SQLModel, Field
151
+
152
+ class User(Base, table=True):
153
+ __tablename__ = "users"
154
+
155
+ username: str = Field(default=None)
156
+ tags: list[str] | None = Field(
157
+ default=None,
158
+ sa_type=SQLAlchemyPGEncryptedArray(),
159
+ )
160
+ ```
161
+
162
+ All [supported types](#supported-types) can be used as array elements. Arrays can even contain mixed types, as each element is self-describing:
163
+
164
+ ```python
165
+ # String arrays
166
+ user.tags = ["admin", "moderator"]
167
+
168
+ # Integer arrays
169
+ user.scores = [100, 95, 87]
170
+
171
+ # Mixed types also work
172
+ user.metadata = [42, "hello", 3.14]
173
+ ```
174
+
175
+ **Note:** `SQLAlchemyPGEncryptedArray` requires a PostgreSQL backend since it uses PostgreSQL's native `ARRAY` type.
176
+
144
177
  ## Choose an Encryption Method
145
178
 
146
179
  You can choose which encryption algorithm to use by setting the `ENCRYPTION_METHOD` environment variable.
@@ -18,7 +18,11 @@ from pydantic_encryption.types import (
18
18
  if TYPE_CHECKING:
19
19
  from pydantic_encryption.adapters.encryption.aws import AWSAdapter
20
20
  from pydantic_encryption.adapters.encryption.evervault import EvervaultAdapter
21
- from pydantic_encryption.integrations.sqlalchemy import SQLAlchemyEncrypted, SQLAlchemyHashed
21
+ from pydantic_encryption.integrations.sqlalchemy import (
22
+ SQLAlchemyEncrypted,
23
+ SQLAlchemyPGEncryptedArray,
24
+ SQLAlchemyHashed,
25
+ )
22
26
 
23
27
 
24
28
  def __getattr__(name: str):
@@ -27,6 +31,11 @@ def __getattr__(name: str):
27
31
 
28
32
  return SQLAlchemyEncrypted
29
33
 
34
+ if name == "SQLAlchemyPGEncryptedArray":
35
+ from pydantic_encryption.integrations.sqlalchemy import SQLAlchemyPGEncryptedArray
36
+
37
+ return SQLAlchemyPGEncryptedArray
38
+
30
39
  if name == "SQLAlchemyHashed":
31
40
  from pydantic_encryption.integrations.sqlalchemy import SQLAlchemyHashed
32
41
 
@@ -68,5 +77,6 @@ __all__ = [
68
77
  "EvervaultAdapter",
69
78
  # SQLAlchemy (optional - lazy loaded)
70
79
  "SQLAlchemyEncrypted",
80
+ "SQLAlchemyPGEncryptedArray",
71
81
  "SQLAlchemyHashed",
72
82
  ]
@@ -9,7 +9,7 @@ from pydantic_encryption._lazy import require_optional_dependency
9
9
 
10
10
  require_optional_dependency("sqlalchemy", "sqlalchemy")
11
11
 
12
- from sqlalchemy.types import LargeBinary, TypeDecorator
12
+ from sqlalchemy.types import ARRAY, LargeBinary, TypeDecorator
13
13
 
14
14
  from pydantic_encryption.adapters import encryption, hashing
15
15
  from pydantic_encryption.config import settings
@@ -174,6 +174,58 @@ class SQLAlchemyEncrypted(TypeDecorator):
174
174
  return self.impl.python_type
175
175
 
176
176
 
177
+ class SQLAlchemyPGEncryptedArray(TypeDecorator):
178
+ """Type adapter for SQLAlchemy to encrypt and decrypt arrays using the specified encryption method.
179
+
180
+ Each element in the array is individually encrypted/decrypted. This type uses PostgreSQL's
181
+ native ARRAY(LargeBinary) column type, so it requires a PostgreSQL backend.
182
+ """
183
+
184
+ impl = ARRAY(LargeBinary)
185
+ cache_ok = True
186
+
187
+ def __init__(self, *args, **kwargs):
188
+ super().__init__(*args, **kwargs)
189
+ self._element_type = SQLAlchemyEncrypted()
190
+
191
+ def process_bind_param(self, value: list[EncryptableValue] | None, dialect) -> list[bytes] | None:
192
+ """Encrypts each element in the array before binding to the database."""
193
+
194
+ if value is None:
195
+ return None
196
+
197
+ return [self._element_type._process_encrypt_value(element) for element in value]
198
+
199
+ def process_literal_param(self, value: list[EncryptableValue] | None, dialect) -> list[bytes] | None:
200
+ """Encrypts each element in the array for literal SQL expressions."""
201
+
202
+ if value is None:
203
+ return None
204
+
205
+ return [self._element_type._process_encrypt_value(element) for element in value]
206
+
207
+ def process_result_value(self, value: list[bytes] | None, dialect) -> list[EncryptableValue] | None:
208
+ """Decrypts each element in the array after retrieving from the database."""
209
+
210
+ if value is None:
211
+ return None
212
+
213
+ result = []
214
+ for element in value:
215
+ if element is None:
216
+ result.append(None)
217
+ else:
218
+ decrypted = self._element_type._process_decrypt_value(element)
219
+ result.append(self._element_type._deserialize_value(decrypted))
220
+ return result
221
+
222
+ @property
223
+ def python_type(self):
224
+ """Return the Python type this is bound to."""
225
+
226
+ return list
227
+
228
+
177
229
  class SQLAlchemyHashed(TypeDecorator):
178
230
  """Type adapter for SQLAlchemy to hash strings using Argon2."""
179
231
 
@@ -1,6 +1,6 @@
1
- from typing import Annotated, Any, Optional, Union, get_args, get_origin, get_type_hints
1
+ from typing import Any
2
2
 
3
- from pydantic_super_model import SuperModel
3
+ from pydantic_super_model import AnnotatedFieldInfo, SuperModel
4
4
 
5
5
  from pydantic_encryption.adapters import encryption, hashing
6
6
  from pydantic_encryption.config import settings
@@ -12,12 +12,22 @@ __all__ = ["BaseModel", "SecureModel"]
12
12
  class SecureModel:
13
13
  """Base class for encryptable and hashable models."""
14
14
 
15
- _disable: Optional[bool] = None
15
+ _disable: bool | None = None
16
16
 
17
17
  def __init_subclass__(cls, *, disable: bool = False, **kwargs) -> None:
18
18
  cls._disable = disable
19
19
  super().__init_subclass__(**kwargs)
20
20
 
21
+ @staticmethod
22
+ def _get_field_values(fields: dict[str, AnnotatedFieldInfo]) -> dict[str, str]:
23
+ """Extract raw values from annotated field info objects."""
24
+
25
+ return {
26
+ field_name: annotated_field.value
27
+ for field_name, annotated_field in fields.items()
28
+ if annotated_field.value is not None
29
+ }
30
+
21
31
  def encrypt_data(self) -> None:
22
32
  """Encrypt data using the specified encryption method."""
23
33
 
@@ -28,19 +38,20 @@ class SecureModel:
28
38
  return
29
39
 
30
40
  encrypted_data: dict[str, str] = {}
41
+ encryption_fields = self._get_field_values(self.pending_encryption_fields)
31
42
 
32
43
  match settings.ENCRYPTION_METHOD:
33
44
  case EncryptionMethod.EVERVAULT:
34
- encrypted_data = encryption.evervault.EvervaultAdapter.encrypt(self.pending_encryption_fields)
45
+ encrypted_data = encryption.evervault.EvervaultAdapter.encrypt(encryption_fields)
35
46
  case EncryptionMethod.FERNET:
36
47
  encrypted_data = {
37
48
  field_name: encryption.fernet.FernetAdapter.encrypt(value)
38
- for field_name, value in self.pending_encryption_fields.items()
49
+ for field_name, value in encryption_fields.items()
39
50
  }
40
51
  case EncryptionMethod.AWS:
41
52
  encrypted_data = {
42
53
  field_name: encryption.aws.AWSAdapter.encrypt(value)
43
- for field_name, value in self.pending_encryption_fields.items()
54
+ for field_name, value in encryption_fields.items()
44
55
  }
45
56
  case _:
46
57
  raise ValueError(f"Unknown encryption method: {settings.ENCRYPTION_METHOD}")
@@ -58,19 +69,20 @@ class SecureModel:
58
69
  return
59
70
 
60
71
  decrypted_data: dict[str, str] = {}
72
+ decryption_fields = self._get_field_values(self.pending_decryption_fields)
61
73
 
62
74
  match settings.ENCRYPTION_METHOD:
63
75
  case EncryptionMethod.EVERVAULT:
64
- decrypted_data = encryption.evervault.EvervaultAdapter.decrypt(self.pending_decryption_fields)
76
+ decrypted_data = encryption.evervault.EvervaultAdapter.decrypt(decryption_fields)
65
77
  case EncryptionMethod.FERNET:
66
78
  decrypted_data = {
67
79
  field_name: encryption.fernet.FernetAdapter.decrypt(value)
68
- for field_name, value in self.pending_decryption_fields.items()
80
+ for field_name, value in decryption_fields.items()
69
81
  }
70
82
  case EncryptionMethod.AWS:
71
83
  decrypted_data = {
72
84
  field_name: encryption.aws.AWSAdapter.decrypt(value)
73
- for field_name, value in self.pending_decryption_fields.items()
85
+ for field_name, value in decryption_fields.items()
74
86
  }
75
87
  case _:
76
88
  raise ValueError(f"Unknown encryption method: {settings.ENCRYPTION_METHOD}")
@@ -87,7 +99,9 @@ class SecureModel:
87
99
  if not self.pending_hash_fields:
88
100
  return
89
101
 
90
- for field_name, value in self.pending_hash_fields.items():
102
+ hash_fields = self._get_field_values(self.pending_hash_fields)
103
+
104
+ for field_name, value in hash_fields.items():
91
105
  hashed = hashing.argon2.Argon2Adapter.hash(value)
92
106
  setattr(self, field_name, hashed)
93
107
 
@@ -104,43 +118,6 @@ class SecureModel:
104
118
  if self.pending_decryption_fields:
105
119
  self.decrypt_data()
106
120
 
107
- def get_annotated_fields(self, *annotations: type) -> dict[str, str]:
108
- """Get fields that have the specified annotations, handling union types."""
109
-
110
- def has_annotation(target_type, target_annotations):
111
- """Check if a type has any of the target annotations."""
112
-
113
- if any(target_type is ann or target_type == ann for ann in target_annotations):
114
- return True
115
-
116
- if get_origin(target_type) is Annotated:
117
- for arg in get_args(target_type)[1:]:
118
- if any(arg is ann or arg == ann for ann in target_annotations):
119
- return True
120
-
121
- return False
122
-
123
- type_hints = get_type_hints(type(self), include_extras=True)
124
- annotated_fields: dict[str, str] = {}
125
-
126
- for field_name, field_annotation in type_hints.items():
127
- found_annotation = False
128
-
129
- if has_annotation(field_annotation, annotations):
130
- found_annotation = True
131
- elif get_origin(field_annotation) is Union:
132
- for arg in get_args(field_annotation):
133
- if has_annotation(arg, annotations):
134
- found_annotation = True
135
- break
136
-
137
- if found_annotation:
138
- field_value = getattr(self, field_name, None)
139
- if field_value is not None:
140
- annotated_fields[field_name] = field_value
141
-
142
- return annotated_fields
143
-
144
121
  @classmethod
145
122
  def _get_class_parameter(cls, parameter_name: str) -> Any:
146
123
  """Get a class parameter from the class or its parent classes."""
@@ -152,20 +129,20 @@ class SecureModel:
152
129
  return None
153
130
 
154
131
  @property
155
- def pending_encryption_fields(self) -> dict[str, str]:
156
- """Get all encrypted fields from the model."""
132
+ def pending_encryption_fields(self) -> dict[str, AnnotatedFieldInfo]:
133
+ """Get encrypted fields from the model."""
157
134
 
158
135
  return self.get_annotated_fields(Encrypt)
159
136
 
160
137
  @property
161
- def pending_decryption_fields(self) -> dict[str, str]:
162
- """Get all decrypted fields from the model."""
138
+ def pending_decryption_fields(self) -> dict[str, AnnotatedFieldInfo]:
139
+ """Get decrypted fields from the model."""
163
140
 
164
141
  return self.get_annotated_fields(Decrypt)
165
142
 
166
143
  @property
167
- def pending_hash_fields(self) -> dict[str, str]:
168
- """Get all hashable fields from the model."""
144
+ def pending_hash_fields(self) -> dict[str, AnnotatedFieldInfo]:
145
+ """Get hashable fields from the model."""
169
146
 
170
147
  return self.get_annotated_fields(Hash)
171
148
 
@@ -173,6 +150,11 @@ class SecureModel:
173
150
  class BaseModel(SuperModel, SecureModel):
174
151
  """Base model for encryptable models."""
175
152
 
153
+ def get_annotated_fields(self, *annotations: type) -> dict[str, AnnotatedFieldInfo]:
154
+ """Return annotated field info objects keyed by field name."""
155
+
156
+ return super().get_annotated_fields(*annotations)
157
+
176
158
  def model_post_init(self, context: Any, /) -> None:
177
159
  self.default_post_init()
178
160
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pydantic_encryption"
3
- version = "0.3.1"
3
+ version = "0.4.0"
4
4
  description = "Encryption and Hashing Models for Pydantic"
5
5
  authors = [
6
6
  { name = "Julien Kmec", email = "me@julien.dev" },
@@ -14,7 +14,7 @@ requires-python = ">=3.11,<3.15"
14
14
  dependencies = [
15
15
  "pydantic>=2.10.6",
16
16
  "pydantic-settings>=2.9.1",
17
- "pydantic-super-model>=1.1.2",
17
+ "pydantic-super-model>=1.2.0",
18
18
  "cryptography>=44.0.0",
19
19
  "argon2-cffi>=23.1.0",
20
20
  ]
@@ -56,7 +56,7 @@ dev = [
56
56
 
57
57
  [tool.black]
58
58
  line-length = 110
59
- target-version = ["py312"]
59
+ target-version = ["py312", "py313", "py314"]
60
60
 
61
61
  [tool.isort]
62
62
  profile = "black"