altcodepro-polydb-python 2.3.31__tar.gz → 2.5.2__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 (101) hide show
  1. {altcodepro_polydb_python-2.3.31/src/altcodepro_polydb_python.egg-info → altcodepro_polydb_python-2.5.2}/PKG-INFO +4 -1
  2. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/pyproject.toml +4 -1
  3. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2/src/altcodepro_polydb_python.egg-info}/PKG-INFO +4 -1
  4. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/altcodepro_polydb_python.egg-info/SOURCES.txt +8 -0
  5. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/altcodepro_polydb_python.egg-info/requires.txt +4 -0
  6. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/MongoDBAdapter.py +106 -18
  7. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/advanced_query.py +63 -1
  8. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/audit/AuditStorage.py +110 -12
  9. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/audit/models.py +95 -3
  10. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/errors.py +6 -0
  11. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/multitenancy.py +44 -4
  12. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/query.py +46 -7
  13. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/schema.py +36 -9
  14. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/security.py +108 -29
  15. altcodepro_polydb_python-2.5.2/tests/test_advanced_query_injection.py +139 -0
  16. altcodepro_polydb_python-2.5.2/tests/test_audit_chain_cutover.py +252 -0
  17. altcodepro_polydb_python-2.5.2/tests/test_audit_hmac.py +190 -0
  18. altcodepro_polydb_python-2.5.2/tests/test_field_encryption.py +172 -0
  19. altcodepro_polydb_python-2.5.2/tests/test_like_pattern_escaping.py +71 -0
  20. altcodepro_polydb_python-2.5.2/tests/test_multitenancy_ddl_injection.py +147 -0
  21. altcodepro_polydb_python-2.5.2/tests/test_nosql_operator_injection.py +165 -0
  22. altcodepro_polydb_python-2.5.2/tests/test_schema_ddl_injection.py +145 -0
  23. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/LICENSE +0 -0
  24. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/MANIFEST.in +0 -0
  25. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/README.md +0 -0
  26. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/requirements-aws.txt +0 -0
  27. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/requirements-azure.txt +0 -0
  28. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/requirements-dev.txt +0 -0
  29. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/requirements-gcp.txt +0 -0
  30. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/requirements-generic.txt +0 -0
  31. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/requirements.txt +0 -0
  32. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/setup.cfg +0 -0
  33. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/setup.py +0 -0
  34. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/altcodepro_polydb_python.egg-info/dependency_links.txt +0 -0
  35. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/altcodepro_polydb_python.egg-info/top_level.txt +0 -0
  36. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/PolyDB.py +0 -0
  37. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/__init__.py +0 -0
  38. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/AzureBlobStorageAdapter.py +0 -0
  39. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/AzureFileStorageAdapter.py +0 -0
  40. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/AzureQueueAdapter.py +0 -0
  41. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/AzureTableStorageAdapter.py +0 -0
  42. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/BlockchainBlobAdapter.py +0 -0
  43. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/BlockchainFileAdapter.py +0 -0
  44. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/BlockchainKVAdapter.py +0 -0
  45. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/BlockchainQueueAdapter.py +0 -0
  46. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/DynamoDBAdapter.py +0 -0
  47. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/EFSAdapter.py +0 -0
  48. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/FirestoreAdapter.py +0 -0
  49. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/GCPFilestoreAdapter.py +0 -0
  50. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/GCPPubSubAdapter.py +0 -0
  51. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/GCPStorageAdapter.py +0 -0
  52. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/PostgreSQLAdapter.py +0 -0
  53. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/S3Adapter.py +0 -0
  54. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/S3CompatibleAdapter.py +0 -0
  55. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/SQSAdapter.py +0 -0
  56. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/VercelBlobAdapter.py +0 -0
  57. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/VercelFileAdapter.py +0 -0
  58. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/VercelKVAdapter.py +0 -0
  59. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/VercelQueueAdapter.py +0 -0
  60. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/adapters/__init__.py +0 -0
  61. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/audit/__init__.py +0 -0
  62. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/audit/context.py +0 -0
  63. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/audit/manager.py +0 -0
  64. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/base/NoSQLKVAdapter.py +0 -0
  65. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/base/ObjectStorageAdapter.py +0 -0
  66. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/base/QueueAdapter.py +0 -0
  67. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/base/SharedFilesAdapter.py +0 -0
  68. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/base/__init__.py +0 -0
  69. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/batch.py +0 -0
  70. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/cache.py +0 -0
  71. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/cloudDatabaseFactory.py +0 -0
  72. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/databaseFactory.py +0 -0
  73. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/decorators.py +0 -0
  74. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/json_safe.py +0 -0
  75. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/models.py +0 -0
  76. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/monitoring.py +0 -0
  77. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/observability/__init__.py +0 -0
  78. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/observability/logging.py +0 -0
  79. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/py.typed +0 -0
  80. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/registry.py +0 -0
  81. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/retry.py +0 -0
  82. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/services/__init__.py +0 -0
  83. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/services/compliance_service.py +0 -0
  84. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/services/security_service.py +0 -0
  85. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/types.py +0 -0
  86. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/utils.py +0 -0
  87. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/src/polydb/validation.py +0 -0
  88. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_atomic_decrement.py +0 -0
  89. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_aws.py +0 -0
  90. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_azure.py +0 -0
  91. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_azure_queue_receipt_handle.py +0 -0
  92. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_azure_table_empty_filter.py +0 -0
  93. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_azure_table_unpack_entity.py +0 -0
  94. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_blockchain.py +0 -0
  95. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_cloud_factory.py +0 -0
  96. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_gcp.py +0 -0
  97. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_mongodb.py +0 -0
  98. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_multi_engine.py +0 -0
  99. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_observability.py +0 -0
  100. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_postgresql.py +0 -0
  101. {altcodepro_polydb_python-2.3.31 → altcodepro_polydb_python-2.5.2}/tests/test_vercel.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: altcodepro-polydb-python
3
- Version: 2.3.31
3
+ Version: 2.5.2
4
4
  Summary: Production-ready multi-cloud database abstraction layer with connection pooling, retry logic, and thread safety
5
5
  Author: AltCodePro
6
6
  Project-URL: Homepage, https://github.com/altcodepro/polydb-python
@@ -69,6 +69,8 @@ Provides-Extra: generic
69
69
  Requires-Dist: pymongo>=4.16.0; extra == "generic"
70
70
  Requires-Dist: pika>=1.3.2; extra == "generic"
71
71
  Requires-Dist: boto3>=1.42.47; extra == "generic"
72
+ Provides-Extra: security
73
+ Requires-Dist: cryptography>=42.0.0; extra == "security"
72
74
  Provides-Extra: all
73
75
  Requires-Dist: boto3>=1.42.47; extra == "all"
74
76
  Requires-Dist: botocore>=1.42.47; extra == "all"
@@ -83,6 +85,7 @@ Requires-Dist: google-cloud-storage>=3.9.0; extra == "all"
83
85
  Requires-Dist: pymongo>=4.16.0; extra == "all"
84
86
  Requires-Dist: pika>=1.3.2; extra == "all"
85
87
  Requires-Dist: requests>=2.32.5; extra == "all"
88
+ Requires-Dist: cryptography>=42.0.0; extra == "all"
86
89
  Provides-Extra: dev
87
90
  Requires-Dist: black>=26.1.0; extra == "dev"
88
91
  Requires-Dist: flake8>=7.3.0; extra == "dev"
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "altcodepro-polydb-python"
7
- version = "2.3.31"
7
+ version = "2.5.2"
8
8
  description = "Production-ready multi-cloud database abstraction layer with connection pooling, retry logic, and thread safety"
9
9
  readme = { file = "README.md", content-type = "text/markdown" }
10
10
  requires-python = ">=3.11"
@@ -92,6 +92,8 @@ bolckchain = ["ipfshttpclient>=0.7.0", "web3>=7.14.1"]
92
92
 
93
93
  generic = ["pymongo>=4.16.0", "pika>=1.3.2", "boto3>=1.42.47"]
94
94
 
95
+ security = ["cryptography>=42.0.0"]
96
+
95
97
  all = [
96
98
  "boto3>=1.42.47",
97
99
  "botocore>=1.42.47",
@@ -106,6 +108,7 @@ all = [
106
108
  "pymongo>=4.16.0",
107
109
  "pika>=1.3.2",
108
110
  "requests>=2.32.5",
111
+ "cryptography>=42.0.0",
109
112
  ]
110
113
 
111
114
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: altcodepro-polydb-python
3
- Version: 2.3.31
3
+ Version: 2.5.2
4
4
  Summary: Production-ready multi-cloud database abstraction layer with connection pooling, retry logic, and thread safety
5
5
  Author: AltCodePro
6
6
  Project-URL: Homepage, https://github.com/altcodepro/polydb-python
@@ -69,6 +69,8 @@ Provides-Extra: generic
69
69
  Requires-Dist: pymongo>=4.16.0; extra == "generic"
70
70
  Requires-Dist: pika>=1.3.2; extra == "generic"
71
71
  Requires-Dist: boto3>=1.42.47; extra == "generic"
72
+ Provides-Extra: security
73
+ Requires-Dist: cryptography>=42.0.0; extra == "security"
72
74
  Provides-Extra: all
73
75
  Requires-Dist: boto3>=1.42.47; extra == "all"
74
76
  Requires-Dist: botocore>=1.42.47; extra == "all"
@@ -83,6 +85,7 @@ Requires-Dist: google-cloud-storage>=3.9.0; extra == "all"
83
85
  Requires-Dist: pymongo>=4.16.0; extra == "all"
84
86
  Requires-Dist: pika>=1.3.2; extra == "all"
85
87
  Requires-Dist: requests>=2.32.5; extra == "all"
88
+ Requires-Dist: cryptography>=42.0.0; extra == "all"
86
89
  Provides-Extra: dev
87
90
  Requires-Dist: black>=26.1.0; extra == "dev"
88
91
  Requires-Dist: flake8>=7.3.0; extra == "dev"
@@ -75,7 +75,10 @@ src/polydb/observability/logging.py
75
75
  src/polydb/services/__init__.py
76
76
  src/polydb/services/compliance_service.py
77
77
  src/polydb/services/security_service.py
78
+ tests/test_advanced_query_injection.py
78
79
  tests/test_atomic_decrement.py
80
+ tests/test_audit_chain_cutover.py
81
+ tests/test_audit_hmac.py
79
82
  tests/test_aws.py
80
83
  tests/test_azure.py
81
84
  tests/test_azure_queue_receipt_handle.py
@@ -83,9 +86,14 @@ tests/test_azure_table_empty_filter.py
83
86
  tests/test_azure_table_unpack_entity.py
84
87
  tests/test_blockchain.py
85
88
  tests/test_cloud_factory.py
89
+ tests/test_field_encryption.py
86
90
  tests/test_gcp.py
91
+ tests/test_like_pattern_escaping.py
87
92
  tests/test_mongodb.py
88
93
  tests/test_multi_engine.py
94
+ tests/test_multitenancy_ddl_injection.py
95
+ tests/test_nosql_operator_injection.py
89
96
  tests/test_observability.py
90
97
  tests/test_postgresql.py
98
+ tests/test_schema_ddl_injection.py
91
99
  tests/test_vercel.py
@@ -30,6 +30,7 @@ google-cloud-storage>=3.9.0
30
30
  pymongo>=4.16.0
31
31
  pika>=1.3.2
32
32
  requests>=2.32.5
33
+ cryptography>=42.0.0
33
34
 
34
35
  [aws]
35
36
  boto3>=1.42.47
@@ -71,6 +72,9 @@ pymongo>=4.16.0
71
72
  [rabbitmq]
72
73
  pika>=1.3.2
73
74
 
75
+ [security]
76
+ cryptography>=42.0.0
77
+
74
78
  [test]
75
79
  pytest>=9.0.2
76
80
  pytest-asyncio>=1.2.0
@@ -14,6 +14,25 @@ from ..types import JsonDict
14
14
  from ..models import PartitionConfig
15
15
 
16
16
 
17
+ def _as_literal(value: Any) -> Any:
18
+ """Wrap a dict value so Mongo compares it instead of executing it.
19
+
20
+ A bare dict on the right-hand side of a field is an *operator expression*
21
+ to Mongo, so a filter value that came from request input can turn
22
+ ``{"password": <value>}`` into ``{"password": {"$gt": ""}}`` - a match on
23
+ every document, i.e. filter/auth bypass and full-collection extraction.
24
+ ``{"$eq": {...}}`` is exactly the same comparison Mongo performs for a
25
+ literal subdocument, so legitimate exact-match-on-subdocument queries keep
26
+ working while ``$``-operators can no longer be smuggled in through a value.
27
+ """
28
+ return {"$eq": value} if isinstance(value, dict) else value
29
+
30
+
31
+ def _sanitize_query(query: Dict[str, Any]) -> Dict[str, Any]:
32
+ """Apply _as_literal to every value of a caller-supplied Mongo query."""
33
+ return {k: _as_literal(v) for k, v in (query or {}).items()}
34
+
35
+
17
36
  class MongoDBAdapter(NoSQLKVAdapter):
18
37
  """MongoDB adapter compatible with PolyDB contract"""
19
38
 
@@ -31,6 +50,7 @@ class MongoDBAdapter(NoSQLKVAdapter):
31
50
 
32
51
  self._client = None
33
52
  self._lock = threading.Lock()
53
+ self._indexed_collections: set = set()
34
54
 
35
55
  self._initialize_client()
36
56
 
@@ -74,7 +94,73 @@ class MongoDBAdapter(NoSQLKVAdapter):
74
94
 
75
95
  collection_name = meta.get("collection") or meta.get("table") or model.__name__.lower()
76
96
 
77
- return self._client[self.db_name][collection_name] # type: ignore
97
+ collection = self._client[self.db_name][collection_name] # type: ignore
98
+
99
+ self._ensure_pk_rk_index(collection, collection_name)
100
+
101
+ return collection
102
+
103
+ def _ensure_pk_rk_index(self, collection, collection_name: str) -> None:
104
+ """
105
+ Create the compound (_pk, _rk) index once per collection.
106
+
107
+ Without it, every _get_raw/_put_raw lookup and query_page's
108
+ `.sort("_pk")` scan the whole collection -- on Cosmos DB's Mongo
109
+ API that's a cross-partition fan-out, billed and latent
110
+ accordingly. Best-effort: a provider that rejects index creation
111
+ (e.g. restricted tier) shouldn't take the adapter down, so a
112
+ failure here is logged once and not retried on every call.
113
+ Note: this is a logical uniqueness/query index only -- it does
114
+ NOT retroactively set Cosmos's physical shard key, which can only
115
+ be chosen at container-creation time.
116
+ """
117
+ if collection_name in self._indexed_collections:
118
+ return
119
+
120
+ with self._lock:
121
+ if collection_name in self._indexed_collections:
122
+ return
123
+
124
+ try:
125
+ collection.create_index(
126
+ [("_pk", 1), ("_rk", 1)], unique=True, name="pk_rk_unique"
127
+ )
128
+ except Exception:
129
+ self.logger.warning(
130
+ "Could not ensure (_pk, _rk) index on %s",
131
+ collection_name,
132
+ exc_info=True,
133
+ )
134
+ finally:
135
+ self._indexed_collections.add(collection_name)
136
+
137
+ # -----------------------------------------------------
138
+ # Internal <-> domain field mapping
139
+ # -----------------------------------------------------
140
+
141
+ def _finalize_doc(self, model: type, doc: JsonDict) -> JsonDict:
142
+ """
143
+ Strip PolyDB's internal _pk/_rk storage keys before returning a
144
+ record, mapping each back to the domain field it was derived from
145
+ (the model's declared partition_key/sort_key) -- mirrors
146
+ AzureTableStorageAdapter._unpack_entity, which already does this
147
+ for PartitionKey/RowKey. Without it, callers see raw storage-
148
+ internal column names instead of their own schema's field names.
149
+ Guarded with setdefault so a real stored property never gets
150
+ clobbered by the derived value.
151
+ """
152
+ pk_field, rk_field = self._pk_rk_field_names(model)
153
+ pk_val = doc.pop("_pk", None)
154
+ rk_val = doc.pop("_rk", None)
155
+
156
+ if pk_val is not None:
157
+ doc.setdefault(pk_field, pk_val)
158
+ if rk_val is not None:
159
+ doc.setdefault(rk_field, rk_val)
160
+
161
+ doc.setdefault("id", rk_val)
162
+
163
+ return doc
78
164
 
79
165
  # -----------------------------------------------------
80
166
  # PUT
@@ -87,7 +173,11 @@ class MongoDBAdapter(NoSQLKVAdapter):
87
173
  payload = dict(data or {})
88
174
  payload["_pk"] = pk
89
175
  payload["_rk"] = rk
90
- payload["id"] = pk
176
+ # _rk is the record's natural identifier (the base class
177
+ # already falls back to `id` when a model has no explicit
178
+ # sort_key); _pk is just the tenant/partition grouping, so it
179
+ # must never overwrite a caller-supplied `id`.
180
+ payload.setdefault("id", rk)
91
181
 
92
182
  collection.update_one(
93
183
  {"_pk": pk, "_rk": rk},
@@ -96,11 +186,7 @@ class MongoDBAdapter(NoSQLKVAdapter):
96
186
  )
97
187
 
98
188
  # return full stored row (tests expect this)
99
- result = dict(payload)
100
- result.pop("_pk", None)
101
- result.pop("_rk", None)
102
-
103
- return result
189
+ return self._finalize_doc(model, dict(payload))
104
190
 
105
191
  except Exception as e:
106
192
  raise NoSQLError(f"MongoDB put failed: {e}")
@@ -120,9 +206,8 @@ class MongoDBAdapter(NoSQLKVAdapter):
120
206
  return None
121
207
 
122
208
  doc.pop("_id", None)
123
- doc.setdefault("id", pk)
124
209
 
125
- return doc
210
+ return self._finalize_doc(model, doc)
126
211
 
127
212
  except Exception as e:
128
213
  raise NoSQLError(f"MongoDB get failed: {e}")
@@ -140,7 +225,9 @@ class MongoDBAdapter(NoSQLKVAdapter):
140
225
  try:
141
226
  collection = self._get_collection(model)
142
227
 
143
- query = query or {}
228
+ # Sanitize before adding our own operator clause below, so the
229
+ # pagination cursor isn't stripped along with injected operators.
230
+ query = _sanitize_query(query)
144
231
 
145
232
  if continuation_token:
146
233
  query["_pk"] = {"$gt": continuation_token}
@@ -151,8 +238,7 @@ class MongoDBAdapter(NoSQLKVAdapter):
151
238
 
152
239
  for doc in cursor:
153
240
  doc.pop("_id", None)
154
- doc.setdefault("id", doc.get("_pk"))
155
- rows.append(doc)
241
+ rows.append(self._finalize_doc(model, doc))
156
242
 
157
243
  if not rows:
158
244
  return [], None
@@ -179,7 +265,7 @@ class MongoDBAdapter(NoSQLKVAdapter):
179
265
  for k, v in (filters or {}).items():
180
266
 
181
267
  if k == "id":
182
- query["_pk"] = v
268
+ query["_rk"] = _as_literal(v)
183
269
  continue
184
270
 
185
271
  if k.endswith("__gt"):
@@ -195,7 +281,10 @@ class MongoDBAdapter(NoSQLKVAdapter):
195
281
  query[k[:-5]] = {"$lte": v}
196
282
 
197
283
  elif k.endswith("__in"):
198
- query[k[:-4]] = {"$in": v}
284
+ # $in operands are matched literally by Mongo, but the list
285
+ # itself has to be a list - a dict here would be read as an
286
+ # operator document.
287
+ query[k[:-4]] = {"$in": list(v) if isinstance(v, (list, tuple, set)) else [v]}
199
288
 
200
289
  elif k.endswith("__contains"):
201
290
  safe_pattern = re.escape(str(v))
@@ -205,7 +294,7 @@ class MongoDBAdapter(NoSQLKVAdapter):
205
294
  }
206
295
 
207
296
  else:
208
- query[k] = v
297
+ query[k] = _as_literal(v)
209
298
 
210
299
  cursor = collection.find(query)
211
300
 
@@ -216,8 +305,7 @@ class MongoDBAdapter(NoSQLKVAdapter):
216
305
 
217
306
  for doc in cursor:
218
307
  doc.pop("_id", None)
219
- doc.setdefault("id", doc.get("_pk"))
220
- results.append(doc)
308
+ results.append(self._finalize_doc(model, doc))
221
309
 
222
310
  return results
223
311
 
@@ -238,7 +326,7 @@ class MongoDBAdapter(NoSQLKVAdapter):
238
326
  if result.deleted_count == 0:
239
327
  raise DatabaseError(f"Item {pk}/{rk} does not exist")
240
328
 
241
- return {"id": pk}
329
+ return {"id": rk}
242
330
 
243
331
  except DatabaseError:
244
332
  raise
@@ -5,6 +5,45 @@ Advanced query capabilities: JOIN, subqueries, aggregates
5
5
  from typing import List, Optional, Any, Dict
6
6
  from dataclasses import dataclass, field
7
7
  from enum import Enum
8
+ import re
9
+
10
+ from .errors import ValidationError
11
+ from .utils import validate_table_name, validate_column_name
12
+
13
+ # table.column / alias.column - each half validated with the same allowlists
14
+ # used elsewhere for identifiers, joined by a single literal dot.
15
+ _QUALIFIED_COLUMN_RE = re.compile(r"^[a-zA-Z0-9_-]+\.[a-zA-Z0-9_]+$")
16
+
17
+
18
+ def _validate_qualified_column(value: str) -> str:
19
+ """Validate a column reference that may be table/alias-qualified (a.b) or bare (b)."""
20
+ if not isinstance(value, str) or not value:
21
+ raise ValidationError(f"Invalid column reference: {value!r}")
22
+ if _QUALIFIED_COLUMN_RE.match(value):
23
+ return value
24
+ return validate_column_name(value)
25
+
26
+
27
+ # Safe HAVING grammar: one or more `FUNC(col) OP operand` comparisons joined by
28
+ # AND/OR. No string literals, no semicolons/comments, no subqueries - this is
29
+ # an allowlist, not a sanitizer, so anything outside this shape is rejected.
30
+ _IDENT = r"[A-Za-z_][A-Za-z0-9_]*"
31
+ _QUALIFIED = rf"{_IDENT}(?:\.{_IDENT})?"
32
+ _FUNC_CALL = rf"{_IDENT}\(\s*(?:\*|{_QUALIFIED})\s*\)"
33
+ _OPERAND = rf"(?:{_FUNC_CALL}|{_QUALIFIED}|-?\d+(?:\.\d+)?)"
34
+ _COMPARISON_OP = r"(?:!=|<>|>=|<=|=|<|>)"
35
+ _CONDITION = rf"{_OPERAND}\s*{_COMPARISON_OP}\s*{_OPERAND}"
36
+ _HAVING_RE = re.compile(rf"^{_CONDITION}(?:\s+(?:AND|OR)\s+{_CONDITION})*$", re.IGNORECASE)
37
+
38
+
39
+ def _validate_having_condition(condition: str) -> str:
40
+ if not isinstance(condition, str) or not _HAVING_RE.match(condition.strip()):
41
+ raise ValidationError(
42
+ f"Invalid HAVING condition: {condition!r}. Only simple aggregate "
43
+ 'comparisons such as "COUNT(id) > 5" (optionally chained with AND/OR) '
44
+ "are allowed - no string literals, subqueries, or statement separators."
45
+ )
46
+ return condition
8
47
 
9
48
 
10
49
  class JoinType(Enum):
@@ -49,6 +88,13 @@ class AdvancedQueryBuilder:
49
88
  having_conditions: List[str] = field(default_factory=list)
50
89
  subqueries: Dict[str, "AdvancedQueryBuilder"] = field(default_factory=dict)
51
90
 
91
+ def __post_init__(self) -> None:
92
+ validate_table_name(self.table)
93
+ for gf in self.group_by_fields:
94
+ _validate_qualified_column(gf)
95
+ for cond in self.having_conditions:
96
+ _validate_having_condition(cond)
97
+
52
98
  def join(
53
99
  self,
54
100
  table: str,
@@ -58,6 +104,11 @@ class AdvancedQueryBuilder:
58
104
  alias: Optional[str] = None,
59
105
  ) -> "AdvancedQueryBuilder":
60
106
  """Add JOIN clause"""
107
+ validate_table_name(table)
108
+ _validate_qualified_column(on_left)
109
+ _validate_qualified_column(on_right)
110
+ if alias is not None:
111
+ validate_column_name(alias)
61
112
  self.joins.append(
62
113
  Join(table=table, join_type=join_type, on_left=on_left, on_right=on_right, alias=alias)
63
114
  )
@@ -67,16 +118,27 @@ class AdvancedQueryBuilder:
67
118
  self, function: AggregateFunction, field: str, alias: str
68
119
  ) -> "AdvancedQueryBuilder":
69
120
  """Add aggregate function"""
121
+ if field != "*":
122
+ _validate_qualified_column(field)
123
+ validate_column_name(alias)
70
124
  self.aggregates.append(Aggregate(function=function, field=field, alias=alias))
71
125
  return self
72
126
 
73
127
  def group_by(self, *fields: str) -> "AdvancedQueryBuilder":
74
128
  """Add GROUP BY"""
129
+ for f in fields:
130
+ _validate_qualified_column(f)
75
131
  self.group_by_fields.extend(fields)
76
132
  return self
77
133
 
78
134
  def having(self, condition: str) -> "AdvancedQueryBuilder":
79
- """Add HAVING clause"""
135
+ """Add HAVING clause.
136
+
137
+ `condition` must match the safe aggregate-comparison grammar enforced
138
+ by `_validate_having_condition` (e.g. "COUNT(id) > 5") - free-form SQL
139
+ text is rejected to prevent HAVING-clause injection.
140
+ """
141
+ _validate_having_condition(condition)
80
142
  self.having_conditions.append(condition)
81
143
  return self
82
144
 
@@ -1,7 +1,9 @@
1
1
  # src/polydb/audit/AuditStorage.py
2
2
  from __future__ import annotations
3
3
 
4
+ import hmac
4
5
  import threading
6
+ from dataclasses import dataclass
5
7
  from typing import Optional, Dict, Any
6
8
 
7
9
  from .models import AuditRecord
@@ -97,7 +99,20 @@ class AuditStorage:
97
99
  and re-chains instead of forking. (threading.Lock alone was only
98
100
  process-local — the old "distributed-safe" claim was false.)"""
99
101
  from dataclasses import asdict
100
- from .models import compute_audit_hash
102
+ from .models import (
103
+ AuditKeyMissingError,
104
+ AUDIT_HMAC_KEY_ENV,
105
+ audit_hmac_key,
106
+ compute_audit_hash,
107
+ require_hmac,
108
+ )
109
+
110
+ if require_hmac() and audit_hmac_key() is None:
111
+ raise AuditKeyMissingError(
112
+ f"{AUDIT_HMAC_KEY_ENV} is unset. An unkeyed audit hash can be "
113
+ "recomputed by anyone who can write the log, so this "
114
+ "deployment has asked to refuse writing one."
115
+ )
101
116
 
102
117
  last_err: Optional[Exception] = None
103
118
  for _ in range(8):
@@ -139,11 +154,38 @@ class AuditStorage:
139
154
  raise last_err or RuntimeError("audit persist failed after retries")
140
155
 
141
156
  def verify_chain(self, tenant_id: Optional[str] = None) -> bool:
142
- """Verify BOTH chain linkage AND per-record content integrity.
143
- The old version only checked previous_hash linkage, so editing
144
- before/after/action while leaving `hash` intact passed silently."""
157
+ """Verify BOTH chain linkage AND per-record content integrity."""
158
+ return self.verify_chain_detailed(tenant_id).ok
159
+
160
+ def verify_chain_detailed(
161
+ self, tenant_id: Optional[str] = None
162
+ ) -> "ChainVerification":
163
+ """Verify the chain, reporting *why* rather than only whether.
164
+
165
+ Two things are checked per record: that it links to its predecessor,
166
+ and that its own digest still matches its content. The second is what
167
+ catches an editor who changed ``before``/``after``/``action`` and left
168
+ ``hash`` alone.
169
+
170
+ Records written before ``POLYDB_AUDIT_HMAC_KEY`` was configured carry
171
+ an unkeyed SHA-256 and cannot be re-verified with the key. They are
172
+ accepted, but only *before* the first keyed record in the chain -- and
173
+ that restriction is what keeps it from being a loophole rather than a
174
+ migration path:
175
+
176
+ * An attacker cannot append unkeyed records after the cutover, because
177
+ once a keyed record has been seen every later record must be keyed.
178
+ * An attacker cannot rewrite the legacy prefix either. Rewriting record
179
+ N means recomputing ``hash(N)``, which is ``previous_hash`` inside
180
+ record N+1's payload -- and if N+1 is keyed, its digest cannot be
181
+ recomputed without the key.
182
+
183
+ So configuring a key seals everything written up to that moment as well
184
+ as everything after it. ``legacy_records`` reports how much of the
185
+ chain is still resting on that seal.
186
+ """
145
187
  from ..query import QueryBuilder, Operator
146
- from .models import compute_audit_hash
188
+ from .models import audit_hmac_key, compute_audit_hash
147
189
 
148
190
  builder = QueryBuilder()
149
191
  if tenant_id is not None:
@@ -152,13 +194,69 @@ class AuditStorage:
152
194
 
153
195
  records = self.sql.query_linq("polydb_audit_log", builder)
154
196
  if not records:
155
- return True
197
+ return ChainVerification(ok=True)
156
198
 
199
+ key = audit_hmac_key()
157
200
  prev = ""
158
- for r in records:
201
+ legacy = 0
202
+ seen_keyed = False
203
+
204
+ for index, r in enumerate(records):
205
+ audit_id = r.get("audit_id")
206
+
159
207
  if (r.get("previous_hash") or "") != prev:
160
- return False
161
- if r.get("hash") != compute_audit_hash(r): # content tamper check
162
- return False
163
- prev = r.get("hash")
164
- return True
208
+ return ChainVerification(
209
+ ok=False,
210
+ broken_at=index,
211
+ audit_id=audit_id,
212
+ reason="link",
213
+ legacy_records=legacy,
214
+ )
215
+
216
+ stored = r.get("hash") or ""
217
+
218
+ if key is not None and hmac.compare_digest(
219
+ stored, compute_audit_hash(r, key=key)
220
+ ):
221
+ seen_keyed = True
222
+ elif not seen_keyed and hmac.compare_digest(
223
+ stored, compute_audit_hash(r, key=None)
224
+ ):
225
+ # Predates the key. Sealed by the first keyed record that
226
+ # follows it, so it is only trusted while none has appeared.
227
+ legacy += 1
228
+ else:
229
+ # Distinguish the two ways this arrives. If the *unkeyed*
230
+ # digest matches the record as stored, the content is intact
231
+ # and the record simply was not keyed - which after the
232
+ # cutover is what stripping the key looks like. Otherwise the
233
+ # record itself was edited.
234
+ downgraded = seen_keyed and hmac.compare_digest(
235
+ stored, compute_audit_hash(r, key=None)
236
+ )
237
+ return ChainVerification(
238
+ ok=False,
239
+ broken_at=index,
240
+ audit_id=audit_id,
241
+ reason="unkeyed_after_cutover" if downgraded else "content",
242
+ legacy_records=legacy,
243
+ )
244
+
245
+ prev = stored
246
+
247
+ return ChainVerification(ok=True, legacy_records=legacy)
248
+
249
+
250
+ @dataclass(frozen=True)
251
+ class ChainVerification:
252
+ """The outcome of :meth:`AuditStorage.verify_chain_detailed`."""
253
+
254
+ ok: bool
255
+ broken_at: Optional[int] = None
256
+ audit_id: Optional[str] = None
257
+ #: "link" (previous_hash mismatch), "content" (record edited), or
258
+ #: "unkeyed_after_cutover" (an unkeyed record appended after keying began,
259
+ #: which is what stripping the key would look like).
260
+ reason: Optional[str] = None
261
+ #: How many leading records still carry a pre-key unkeyed digest.
262
+ legacy_records: int = 0