sendproof-core 0.1.0a1__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.
Files changed (209) hide show
  1. sendproof_core/__init__.py +56 -0
  2. sendproof_core/assets.py +71 -0
  3. sendproof_core/capture.py +416 -0
  4. sendproof_core/effects.py +79 -0
  5. sendproof_core/identity.py +22 -0
  6. sendproof_core/jsonsafe.py +103 -0
  7. sendproof_core/limits.py +24 -0
  8. sendproof_core/marker.py +131 -0
  9. sendproof_core/options.py +129 -0
  10. sendproof_core/protocol.py +132 -0
  11. sendproof_core/provider.py +121 -0
  12. sendproof_core/py.typed +0 -0
  13. sendproof_core/redaction.py +88 -0
  14. sendproof_core/scope.py +146 -0
  15. sendproof_core/stores/__init__.py +119 -0
  16. sendproof_core/stores/base.py +99 -0
  17. sendproof_core/stores/cassandra_hook.py +173 -0
  18. sendproof_core/stores/classify.py +153 -0
  19. sendproof_core/stores/classify_batch_two.py +397 -0
  20. sendproof_core/stores/cosmos_hook.py +214 -0
  21. sendproof_core/stores/dynamodb_hook.py +214 -0
  22. sendproof_core/stores/elasticsearch_hook.py +248 -0
  23. sendproof_core/stores/firestore_hook.py +459 -0
  24. sendproof_core/stores/guard.py +205 -0
  25. sendproof_core/stores/mongo_hook.py +1406 -0
  26. sendproof_core/stores/redis_hook.py +536 -0
  27. sendproof_core/stores/tables.py +1486 -0
  28. sendproof_core/stores/versions.py +46 -0
  29. sendproof_core/sync_engine.py +308 -0
  30. sendproof_core/trace_store.py +92 -0
  31. sendproof_core/txguard.py +237 -0
  32. sendproof_core/ui/action-bar.js +91 -0
  33. sendproof_core/ui/api.js +239 -0
  34. sendproof_core/ui/app.css +848 -0
  35. sendproof_core/ui/app.js +742 -0
  36. sendproof_core/ui/autofill.js +137 -0
  37. sendproof_core/ui/code-copy.js +71 -0
  38. sendproof_core/ui/code-picker.js +149 -0
  39. sendproof_core/ui/commands.js +197 -0
  40. sendproof_core/ui/components.js +77 -0
  41. sendproof_core/ui/context-bar.js +82 -0
  42. sendproof_core/ui/copy.js +92 -0
  43. sendproof_core/ui/coverage-popover.js +35 -0
  44. sendproof_core/ui/crumb-fit.js +80 -0
  45. sendproof_core/ui/deprecation.js +164 -0
  46. sendproof_core/ui/display-settings.js +175 -0
  47. sendproof_core/ui/doc-diff.js +209 -0
  48. sendproof_core/ui/docs-view.js +347 -0
  49. sendproof_core/ui/favicon.png +0 -0
  50. sendproof_core/ui/favicon.svg +1 -0
  51. sendproof_core/ui/field-help.js +52 -0
  52. sendproof_core/ui/field-modules.js +23 -0
  53. sendproof_core/ui/fields/controls.js +179 -0
  54. sendproof_core/ui/fields/dom.js +36 -0
  55. sendproof_core/ui/fields/infer.js +71 -0
  56. sendproof_core/ui/fields/lookup-source.js +63 -0
  57. sendproof_core/ui/fields/lookup.js +285 -0
  58. sendproof_core/ui/fields/render.js +496 -0
  59. sendproof_core/ui/fields/select.js +175 -0
  60. sendproof_core/ui/fields/validate.js +363 -0
  61. sendproof_core/ui/fields/validation-formats.js +164 -0
  62. sendproof_core/ui/fields/validation-references.js +68 -0
  63. sendproof_core/ui/fields/validation-values.js +137 -0
  64. sendproof_core/ui/generate-menu.js +44 -0
  65. sendproof_core/ui/generate.js +184 -0
  66. sendproof_core/ui/header-editor.js +777 -0
  67. sendproof_core/ui/headers.js +188 -0
  68. sendproof_core/ui/highlight.js +257 -0
  69. sendproof_core/ui/history-popover.js +24 -0
  70. sendproof_core/ui/i18n.js +253 -0
  71. sendproof_core/ui/icons.js +87 -0
  72. sendproof_core/ui/index.html +70 -0
  73. sendproof_core/ui/issues.js +187 -0
  74. sendproof_core/ui/json-view.js +166 -0
  75. sendproof_core/ui/lang-icons.js +62 -0
  76. sendproof_core/ui/layout.js +262 -0
  77. sendproof_core/ui/listbox.js +334 -0
  78. sendproof_core/ui/locales/ar-capture.js +366 -0
  79. sendproof_core/ui/locales/ar-stores.js +116 -0
  80. sendproof_core/ui/locales/ar.js +561 -0
  81. sendproof_core/ui/locales/cs-capture.js +442 -0
  82. sendproof_core/ui/locales/cs-stores.js +116 -0
  83. sendproof_core/ui/locales/cs.js +689 -0
  84. sendproof_core/ui/locales/da-capture.js +347 -0
  85. sendproof_core/ui/locales/da-stores.js +116 -0
  86. sendproof_core/ui/locales/da.js +522 -0
  87. sendproof_core/ui/locales/de-capture.js +347 -0
  88. sendproof_core/ui/locales/de-stores.js +116 -0
  89. sendproof_core/ui/locales/de.js +519 -0
  90. sendproof_core/ui/locales/el-capture.js +347 -0
  91. sendproof_core/ui/locales/el-stores.js +116 -0
  92. sendproof_core/ui/locales/el.js +520 -0
  93. sendproof_core/ui/locales/en-capture.js +349 -0
  94. sendproof_core/ui/locales/en-stores.js +95 -0
  95. sendproof_core/ui/locales/en.js +522 -0
  96. sendproof_core/ui/locales/es-capture.js +353 -0
  97. sendproof_core/ui/locales/es-stores.js +116 -0
  98. sendproof_core/ui/locales/es.js +525 -0
  99. sendproof_core/ui/locales/fa-capture.js +348 -0
  100. sendproof_core/ui/locales/fa-stores.js +116 -0
  101. sendproof_core/ui/locales/fa.js +521 -0
  102. sendproof_core/ui/locales/fi-capture.js +347 -0
  103. sendproof_core/ui/locales/fi-stores.js +116 -0
  104. sendproof_core/ui/locales/fi.js +523 -0
  105. sendproof_core/ui/locales/fr-capture.js +353 -0
  106. sendproof_core/ui/locales/fr-stores.js +116 -0
  107. sendproof_core/ui/locales/fr.js +525 -0
  108. sendproof_core/ui/locales/he-capture.js +358 -0
  109. sendproof_core/ui/locales/he-stores.js +116 -0
  110. sendproof_core/ui/locales/he.js +529 -0
  111. sendproof_core/ui/locales/hi-capture.js +348 -0
  112. sendproof_core/ui/locales/hi-stores.js +116 -0
  113. sendproof_core/ui/locales/hi.js +523 -0
  114. sendproof_core/ui/locales/id-capture.js +347 -0
  115. sendproof_core/ui/locales/id-stores.js +116 -0
  116. sendproof_core/ui/locales/id.js +521 -0
  117. sendproof_core/ui/locales/it-capture.js +361 -0
  118. sendproof_core/ui/locales/it-stores.js +116 -0
  119. sendproof_core/ui/locales/it.js +523 -0
  120. sendproof_core/ui/locales/ja-capture.js +346 -0
  121. sendproof_core/ui/locales/ja-stores.js +116 -0
  122. sendproof_core/ui/locales/ja.js +521 -0
  123. sendproof_core/ui/locales/ko-capture.js +346 -0
  124. sendproof_core/ui/locales/ko-stores.js +116 -0
  125. sendproof_core/ui/locales/ko.js +522 -0
  126. sendproof_core/ui/locales/nb-capture.js +349 -0
  127. sendproof_core/ui/locales/nb-stores.js +116 -0
  128. sendproof_core/ui/locales/nb.js +521 -0
  129. sendproof_core/ui/locales/nl-capture.js +355 -0
  130. sendproof_core/ui/locales/nl-stores.js +116 -0
  131. sendproof_core/ui/locales/nl.js +520 -0
  132. sendproof_core/ui/locales/pl-capture.js +432 -0
  133. sendproof_core/ui/locales/pl-stores.js +116 -0
  134. sendproof_core/ui/locales/pl.js +528 -0
  135. sendproof_core/ui/locales/pt-BR-capture.js +350 -0
  136. sendproof_core/ui/locales/pt-BR-stores.js +116 -0
  137. sendproof_core/ui/locales/pt-BR.js +523 -0
  138. sendproof_core/ui/locales/pt-PT-capture.js +350 -0
  139. sendproof_core/ui/locales/pt-PT-stores.js +116 -0
  140. sendproof_core/ui/locales/pt-PT.js +523 -0
  141. sendproof_core/ui/locales/ru-capture.js +437 -0
  142. sendproof_core/ui/locales/ru-stores.js +116 -0
  143. sendproof_core/ui/locales/ru.js +624 -0
  144. sendproof_core/ui/locales/sv-capture.js +349 -0
  145. sendproof_core/ui/locales/sv-stores.js +116 -0
  146. sendproof_core/ui/locales/sv.js +518 -0
  147. sendproof_core/ui/locales/th-capture.js +347 -0
  148. sendproof_core/ui/locales/th-stores.js +116 -0
  149. sendproof_core/ui/locales/th.js +521 -0
  150. sendproof_core/ui/locales/tr-capture.js +348 -0
  151. sendproof_core/ui/locales/tr-stores.js +116 -0
  152. sendproof_core/ui/locales/tr.js +521 -0
  153. sendproof_core/ui/locales/uk-capture.js +442 -0
  154. sendproof_core/ui/locales/uk-stores.js +116 -0
  155. sendproof_core/ui/locales/uk.js +630 -0
  156. sendproof_core/ui/locales/vi-capture.js +346 -0
  157. sendproof_core/ui/locales/vi-stores.js +116 -0
  158. sendproof_core/ui/locales/vi.js +523 -0
  159. sendproof_core/ui/locales/zh-Hans-capture.js +347 -0
  160. sendproof_core/ui/locales/zh-Hans-stores.js +116 -0
  161. sendproof_core/ui/locales/zh-Hans.js +523 -0
  162. sendproof_core/ui/locales/zh-Hant-capture.js +346 -0
  163. sendproof_core/ui/locales/zh-Hant-stores.js +116 -0
  164. sendproof_core/ui/locales/zh-Hant.js +522 -0
  165. sendproof_core/ui/manifest.json +866 -0
  166. sendproof_core/ui/markdown.js +39 -0
  167. sendproof_core/ui/model-view.js +182 -0
  168. sendproof_core/ui/navigation.js +233 -0
  169. sendproof_core/ui/operation-header.js +76 -0
  170. sendproof_core/ui/operations.js +7 -0
  171. sendproof_core/ui/overview-view.js +63 -0
  172. sendproof_core/ui/personas.js +59 -0
  173. sendproof_core/ui/popover.js +71 -0
  174. sendproof_core/ui/preview-false.js +108 -0
  175. sendproof_core/ui/request-editor.js +496 -0
  176. sendproof_core/ui/response-metadata.js +354 -0
  177. sendproof_core/ui/response-viewer.js +618 -0
  178. sendproof_core/ui/result-blocked.js +155 -0
  179. sendproof_core/ui/result-capture.js +25 -0
  180. sendproof_core/ui/result-database.js +185 -0
  181. sendproof_core/ui/result-effects.js +176 -0
  182. sendproof_core/ui/result-headers.js +106 -0
  183. sendproof_core/ui/result-logs.js +408 -0
  184. sendproof_core/ui/result-states.js +213 -0
  185. sendproof_core/ui/results.js +371 -0
  186. sendproof_core/ui/router.js +118 -0
  187. sendproof_core/ui/schema-model.js +336 -0
  188. sendproof_core/ui/schema-tree.js +344 -0
  189. sendproof_core/ui/schema.js +397 -0
  190. sendproof_core/ui/security.js +31 -0
  191. sendproof_core/ui/seeded-menu.js +69 -0
  192. sendproof_core/ui/settings.js +93 -0
  193. sendproof_core/ui/shortcuts-sheet.js +73 -0
  194. sendproof_core/ui/shortcuts.js +190 -0
  195. sendproof_core/ui/sidebar.js +289 -0
  196. sendproof_core/ui/signin.js +259 -0
  197. sendproof_core/ui/snippets.js +530 -0
  198. sendproof_core/ui/store-marks.js +47 -0
  199. sendproof_core/ui/stores.js +131 -0
  200. sendproof_core/ui/styles.css +971 -0
  201. sendproof_core/ui/toggletip.js +53 -0
  202. sendproof_core/ui/uuid.js +10 -0
  203. sendproof_core/ui/view.js +122 -0
  204. sendproof_core/ui/views.css +653 -0
  205. sendproof_core/workbench.py +310 -0
  206. sendproof_core-0.1.0a1.dist-info/METADATA +116 -0
  207. sendproof_core-0.1.0a1.dist-info/RECORD +209 -0
  208. sendproof_core-0.1.0a1.dist-info/WHEEL +4 -0
  209. sendproof_core-0.1.0a1.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,214 @@
1
+ """Sendproof write guard for Azure Cosmos DB for NoSQL (``spec/data-stores.md``, ``guard`` mode).
2
+
3
+ ``cosmosdb_store(client)`` guards an ``azure-cosmos`` 4 ``CosmosClient`` (synchronous or
4
+ ``azure.cosmos.aio``) in place through its azure-core **transport**.
5
+
6
+ Why the transport: ``CosmosClient`` builds its azure-core pipeline from a fixed policy list, so
7
+ ``per_call_policies=`` is **not** honoured (it falls through to the HTTP session and fails). The
8
+ one extension point the client does honour is ``transport=``, and every request the SDK sends,
9
+ retries and metadata reads included, passes through ``transport.send`` after the pipeline signed it
10
+ and before it is written. The hook swaps the client's transport for a guarded subclass, so
11
+ ``database_client()``, ``get_container_client()``, ``scripts`` and every other derived proxy, which
12
+ all share the client's one pipeline, stay guarded.
13
+
14
+ * Each ``HttpRequest`` is classified with ``fromRequest`` in ``cosmosdb.json``: the method, the
15
+ resource path and the ``x-ms-documentdb-isquery``, ``x-ms-cosmos-is-query-plan-request``,
16
+ ``x-ms-cosmos-is-batch-request`` and ``x-ms-documentdb-is-upsert`` headers name the operation.
17
+ A request that names a pre-trigger or post-trigger is a write. So are stored-procedure
18
+ executions, batches and patches.
19
+ * Reads run and become a ``Db`` entry: the query text with every literal replaced by ``?`` (names
20
+ of parameters, never their values). In a Preview the first write raises
21
+ :class:`~sendproof_core.stores.guard.PreviewWriteBlocked` and the Preview answers 409.
22
+
23
+ Coverage: the hooked client, and anything built from it. A second ``CosmosClient`` is not covered
24
+ unless you hook it too or build it with ``transport=store.guard_transport(RequestsTransport())``.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import inspect
30
+ import json
31
+ import re
32
+ import time
33
+ from http import HTTPStatus
34
+ from typing import Any, Iterable, Optional
35
+ from urllib.parse import urlsplit
36
+
37
+ from .base import DataStore
38
+ from .classify_batch_two import classify_cosmos, path_segments
39
+ from .guard import check_command, read_set, store_label
40
+ from .versions import require_supported
41
+
42
+ _COSMOS_STRING = re.compile(r"""'(?:[^'\\]|\\.)*'?|"(?:[^"\\]|\\.)*"?""", re.DOTALL)
43
+ _COSMOS_NUMBER = re.compile(r"(?<![\w@.])-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(?![\w])")
44
+
45
+
46
+ def sanitize_cosmos_sql(text: str) -> str:
47
+ """Replace every literal in a Cosmos DB SQL query with ``?``: single- and double-quoted strings
48
+ (both are strings in this dialect) and numbers. ``@parameter`` names and identifiers are kept."""
49
+ return _COSMOS_NUMBER.sub("?", _COSMOS_STRING.sub("?", text))
50
+
51
+
52
+ def _query_text(body: Any) -> Optional[str]:
53
+ """The sanitized text of a query request's JSON body (``{"query": ..., "parameters": [...]}``)."""
54
+ if isinstance(body, (bytes, bytearray)):
55
+ body = bytes(body).decode("utf-8", "replace")
56
+ try:
57
+ parsed = json.loads(body) if isinstance(body, str) else None
58
+ except ValueError:
59
+ return "?"
60
+ query = parsed.get("query") if isinstance(parsed, dict) else None
61
+ return sanitize_cosmos_sql(query) if isinstance(query, str) else None
62
+
63
+
64
+ def _status_name(status: Any) -> Optional[str]:
65
+ """``NotFound``, ``Conflict``, ``TooManyRequests``...: the HTTP phrase of an error status, else ``None``."""
66
+ try:
67
+ code = int(status)
68
+ return HTTPStatus(code).phrase.replace(" ", "") if code >= 400 else None
69
+ except (TypeError, ValueError):
70
+ return f"HTTP{status}"
71
+
72
+
73
+ class _Guard:
74
+ """The methods a guarded transport class gets.
75
+
76
+ They are copied into a subclass with the transport's own class as its only base, and call
77
+ ``base.send(self, ...)`` rather than ``super()``: swapping a transport's ``__class__`` needs the
78
+ same instance layout, and a mixin in front of azure-core's ``Generic`` and ``ABC`` bases changes it.
79
+ """
80
+
81
+ _sendproof_store: "CosmosDBStore"
82
+
83
+ def _sendproof_before(self, request: Any) -> Optional[tuple]:
84
+ store = self._sendproof_store
85
+ path = urlsplit(str(request.url)).path
86
+ headers = dict(request.headers or {})
87
+ verdict = classify_cosmos(request={"method": str(request.method), "path": path, "headers": headers},
88
+ treat_as_read=store._reads)
89
+ scope = check_command("cosmosdb", verdict.operation, verdict.kind)
90
+ if scope is None:
91
+ return None
92
+ segments = path_segments(path)
93
+ names = {kind: segments[index + 1] for index, kind in enumerate(segments[:-1]) if kind in ("dbs", "colls")}
94
+ statement = _query_text(getattr(request, "body", None)) if verdict.operation in ("Query", "SqlQuery") else None
95
+ return scope, verdict, names.get("colls"), names.get("dbs"), statement, time.perf_counter()
96
+
97
+ def _sendproof_after(self, pending: Optional[tuple], response: Any, error: Optional[BaseException]) -> None:
98
+ if pending is None:
99
+ return
100
+ scope, verdict, target, namespace, statement, began = pending
101
+ rows: Optional[int] = None
102
+ failure: Optional[str] = type(error).__name__ if error is not None else None
103
+ if response is not None:
104
+ failure = _status_name(getattr(response, "status_code", None))
105
+ try:
106
+ count = response.headers.get("x-ms-item-count")
107
+ rows = int(count) if count is not None else None
108
+ except (AttributeError, TypeError, ValueError):
109
+ rows = None
110
+ scope.capture.record_db(
111
+ "cosmosdb", verdict.operation, target=target, namespace=namespace, statement=statement,
112
+ rows_affected=rows, error=failure, elapsed_ms=(time.perf_counter() - began) * 1000,
113
+ )
114
+
115
+
116
+ def _guarded_class(base: type, store: "CosmosDBStore") -> type:
117
+ """A subclass of the transport class ``base`` whose ``send`` classifies and guards before sending."""
118
+ if inspect.iscoroutinefunction(base.send):
119
+ async def send(self: Any, request: Any, *args: Any, **kwargs: Any) -> Any:
120
+ pending = self._sendproof_before(request)
121
+ try:
122
+ response = await base.send(self, request, *args, **kwargs)
123
+ except Exception as error:
124
+ self._sendproof_after(pending, None, error)
125
+ raise
126
+ self._sendproof_after(pending, response, None)
127
+ return response
128
+ else:
129
+ def send(self: Any, request: Any, *args: Any, **kwargs: Any) -> Any: # type: ignore[misc]
130
+ pending = self._sendproof_before(request)
131
+ try:
132
+ response = base.send(self, request, *args, **kwargs)
133
+ except Exception as error:
134
+ self._sendproof_after(pending, None, error)
135
+ raise
136
+ self._sendproof_after(pending, response, None)
137
+ return response
138
+ return type(f"Guarded{base.__name__}", (base,), {
139
+ "send": send, "_sendproof_before": _Guard._sendproof_before, "_sendproof_after": _Guard._sendproof_after,
140
+ "_sendproof_store": store, "__module__": __name__,
141
+ })
142
+
143
+
144
+ _classes: dict[tuple[type, int], type] = {}
145
+
146
+
147
+ def _client_transport(client: Any) -> Any:
148
+ """The azure-core transport a ``CosmosClient`` sends through.
149
+
150
+ ``client_connection.pipeline_client._pipeline._transport`` is not public API, so a client whose
151
+ layout differs is refused at registration rather than left unguarded.
152
+ """
153
+ pipeline = getattr(getattr(getattr(client, "client_connection", None), "pipeline_client", None), "_pipeline", None)
154
+ transport = getattr(pipeline, "_transport", None)
155
+ policies = getattr(pipeline, "_impl_policies", None)
156
+ # The object found must be the one the pipeline's last step sends through, or guarding it guards nothing.
157
+ runner = getattr(policies[-1], "next", None) if isinstance(policies, list) and policies else None
158
+ if transport is None or not hasattr(transport, "send") or getattr(runner, "_sender", None) is not transport:
159
+ raise TypeError(
160
+ "cosmosdb_store could not find the azure-core transport of this client (azure-cosmos 4 expected). "
161
+ "Build the client with transport=store.guard_transport(...) instead.")
162
+ return transport
163
+
164
+
165
+ class CosmosDBStore(DataStore):
166
+ """A hooked Cosmos DB client, ready for ``data_stores``."""
167
+
168
+ system = "cosmosdb"
169
+
170
+ def __init__(self, name: Optional[str], reads: Optional[frozenset[str]]) -> None:
171
+ self.name = name
172
+ self._reads = reads
173
+
174
+ def describe(self) -> dict[str, Any]:
175
+ return {"system": "cosmosdb", **({"name": self.name} if self.name else {}), "mode": "guard"}
176
+
177
+ def guard_transport(self, transport: Any) -> Any:
178
+ """Guard an azure-core transport object in place and return it, for ``CosmosClient(transport=...)``.
179
+
180
+ Hooking a transport twice is refused, so a request is never logged twice.
181
+ """
182
+ if getattr(type(transport), "_sendproof_store", None) is not None:
183
+ raise TypeError("This Cosmos DB client or transport is already hooked by cosmosdb_store.")
184
+ base = type(transport)
185
+ key = (base, id(self))
186
+ guarded = _classes.get(key)
187
+ if guarded is None:
188
+ guarded = _classes[key] = _guarded_class(base, self)
189
+ try:
190
+ transport.__class__ = guarded
191
+ except TypeError as error: # an unusual instance layout: refuse rather than leave the client unguarded
192
+ raise TypeError(f"cosmosdb_store can't hook a {base.__name__}; build the client with a plain subclass of it.") from error
193
+ return transport
194
+
195
+
196
+ def cosmosdb_store(client: Any = None, *, name: Optional[str] = None,
197
+ treat_as_read: Optional[Iterable[str]] = None) -> CosmosDBStore:
198
+ """Hook an ``azure-cosmos`` 4 ``CosmosClient`` (sync or aio) in place and return the store for ``data_stores``.
199
+
200
+ Pass nothing to get just the store, and build the client with
201
+ ``transport=store.guard_transport(RequestsTransport())``. Hooking the same client twice is refused.
202
+
203
+ Args:
204
+ name: A display label for discovery, such as ``orders``. Never an account endpoint or key.
205
+ treat_as_read: Operation types you state never write, such as ``Execute`` for a stored
206
+ procedure you know only reads: exact names, no wildcards. A request that names a
207
+ trigger is still a write. **The guard trusts this list**: a listed operation that does
208
+ write is not blocked.
209
+ """
210
+ require_supported("azure-cosmos", "cosmosdb_store")
211
+ store = CosmosDBStore(store_label(name), read_set(treat_as_read))
212
+ if client is not None:
213
+ store.guard_transport(_client_transport(client))
214
+ return store
@@ -0,0 +1,214 @@
1
+ """Sendproof write guard for DynamoDB (``spec/data-stores.md``, ``guard`` mode).
2
+
3
+ ``dynamodb_store(target)`` registers botocore event handlers on a boto3 or aioboto3 session, a
4
+ botocore session, a client or a resource:
5
+
6
+ * ``before-parameter-build.dynamodb`` classifies the operation and its parameters and, in a
7
+ Preview, refuses a write by raising :class:`~sendproof_core.stores.guard.PreviewWriteBlocked`.
8
+ It runs before the request is serialized, signed or sent, so a refused operation never becomes
9
+ an HTTP request, and credentials, the ``Authorization`` header and signatures never reach the hook.
10
+ * ``after-call.dynamodb`` and ``after-call-error.dynamodb`` log the operation as a ``Db`` entry.
11
+
12
+ The operation is the botocore operation model's name (``UpdateItem``). boto3 resources and tables,
13
+ PynamoDB and aioboto3 clients all call ``client._make_api_call``, so they all pass through the
14
+ handlers.
15
+
16
+ Registering on a **session** covers every client made from it *afterwards*; registering on a
17
+ **client** (or a resource, through its client) covers that client only. A client created from an
18
+ unhooked session, or inside a handler, is not covered.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import re
24
+ import time
25
+ from typing import Any, Iterable, Mapping, Optional
26
+
27
+ from ..scope import current_scope
28
+ from .base import DataStore
29
+ from .classify import WRITE, classify_dynamo
30
+ from .guard import guard, read_set, refuse_unattributed, store_label
31
+
32
+ _UNIQUE_ID = "sendproof-dynamodb-guard"
33
+ _STARTED = "sendproof_started"
34
+ _EVENTS = ("before-parameter-build.dynamodb", "after-call.dynamodb", "after-call-error.dynamodb")
35
+
36
+
37
+ def sanitize_partiql(text: str) -> str:
38
+ """Replace every literal in PartiQL text with ``?``.
39
+
40
+ Single-quoted strings (with ``''`` escapes) and numbers are replaced; double-quoted
41
+ identifiers (table and attribute names) are kept as written. A statement may inline values
42
+ instead of using ``?`` parameters, and a value never appears in a ``Db`` entry.
43
+ """
44
+ out: list[str] = []
45
+ index, length = 0, len(text)
46
+ while index < length:
47
+ char = text[index]
48
+ if char == '"':
49
+ end = text.find('"', index + 1)
50
+ stop = length if end < 0 else end + 1
51
+ out.append(text[index:stop])
52
+ index = stop
53
+ elif char == "'":
54
+ end = index + 1
55
+ while end < length and not (text[end] == "'" and text[end + 1:end + 2] != "'"):
56
+ end += 2 if text[end] == "'" else 1
57
+ out.append("?")
58
+ index = end + 1
59
+ elif char.isdigit() and not re.match(r"[\w.]", text[index - 1] if index else ""):
60
+ number = re.match(r"[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?", text[index:])
61
+ out.append("?")
62
+ index += number.end() if number else 1
63
+ else:
64
+ out.append(char)
65
+ index += 1
66
+ return "".join(out)
67
+
68
+
69
+ def _statement(params: Mapping[str, Any]) -> Optional[str]:
70
+ """The PartiQL text of a request, with literals replaced by ``?``; other actions have no statement."""
71
+ if isinstance(params.get("Statement"), str):
72
+ return sanitize_partiql(params["Statement"])
73
+ listed = params.get("Statements") or params.get("TransactStatements")
74
+ if isinstance(listed, (list, tuple)):
75
+ return "; ".join(sanitize_partiql(str(item.get("Statement", "")) if isinstance(item, Mapping) else "") for item in listed)
76
+ return None
77
+
78
+
79
+ def _target(params: Mapping[str, Any], statement: Optional[str]) -> Optional[str]:
80
+ """The table a command targets: ``TableName``, the first ``RequestItems`` table, a transaction item's table or the quoted PartiQL table."""
81
+ if isinstance(params.get("TableName"), str):
82
+ return params["TableName"]
83
+ items = params.get("RequestItems")
84
+ if isinstance(items, Mapping) and items:
85
+ return str(next(iter(items)))
86
+ transact = params.get("TransactItems")
87
+ if isinstance(transact, (list, tuple)) and transact and isinstance(transact[0], Mapping):
88
+ for body in transact[0].values():
89
+ if isinstance(body, Mapping) and isinstance(body.get("TableName"), str):
90
+ return body["TableName"]
91
+ found = re.search(r'"([^"]+)"', statement) if statement else None
92
+ return found.group(1) if found else None
93
+
94
+
95
+ def _rows(parsed: Any) -> Optional[int]:
96
+ """Items matched, returned or written, when the reply says so."""
97
+ if not isinstance(parsed, Mapping):
98
+ return None
99
+ if isinstance(parsed.get("Items"), list):
100
+ return len(parsed["Items"])
101
+ if isinstance(parsed.get("Count"), int):
102
+ return parsed["Count"]
103
+ return 1 if parsed.get("Item") or parsed.get("Attributes") else None
104
+
105
+
106
+ class DynamoDBStore(DataStore):
107
+ """A hooked DynamoDB client or session, ready for ``data_stores``."""
108
+
109
+ system = "dynamodb"
110
+
111
+ def __init__(self, name: Optional[str], reads: Optional[frozenset[str]]) -> None:
112
+ self.name = name
113
+ self._reads = reads
114
+
115
+ def describe(self) -> dict[str, Any]:
116
+ return {"system": "dynamodb", **({"name": self.name} if self.name else {}), "mode": "guard"}
117
+
118
+ # ------------------------------------------------------------- event handlers
119
+ def before_parameter_build(self, params: Any = None, model: Any = None, context: Any = None, **_: Any) -> None:
120
+ """Classify the operation before anything is built, signed or sent; refuse a write in a Preview."""
121
+ operation = str(getattr(model, "name", "") or "")
122
+ params = params if isinstance(params, Mapping) else {}
123
+ kind = classify_dynamo(operation, params, self._reads)
124
+ guard("dynamodb", operation, kind)
125
+ if kind == WRITE and current_scope() is None:
126
+ refuse_unattributed("dynamodb", operation)
127
+ if context is not None:
128
+ statement = _statement(params)
129
+ context[_STARTED] = (time.perf_counter(), operation, _target(params, statement), statement)
130
+
131
+ def after_call(self, parsed: Any = None, context: Any = None, **_: Any) -> None:
132
+ """Log the finished operation, with its error code when DynamoDB refused it."""
133
+ error = parsed.get("Error", {}).get("Code") if isinstance(parsed, Mapping) and isinstance(parsed.get("Error"), Mapping) else None
134
+ self._log(context, rows=None if error else _rows(parsed), error=error)
135
+
136
+ def after_call_error(self, exception: Any = None, context: Any = None, **_: Any) -> None:
137
+ """Log an operation that failed before DynamoDB answered (a connection error, for example)."""
138
+ self._log(context, rows=None, error=type(exception).__name__ if exception is not None else "Error")
139
+
140
+ @staticmethod
141
+ def _log(context: Any, rows: Optional[int], error: Optional[str]) -> None:
142
+ scope = current_scope()
143
+ started = context.pop(_STARTED, None) if isinstance(context, dict) else None
144
+ if scope is None or started is None:
145
+ return
146
+ began, operation, target, statement = started
147
+ scope.capture.record_db(
148
+ "dynamodb", operation, target=target, statement=statement, rows_affected=rows, error=error,
149
+ elapsed_ms=(time.perf_counter() - began) * 1000,
150
+ )
151
+
152
+ def register(self, emitter: Any) -> None:
153
+ """Add the handlers to a botocore event emitter or session. Hooking one twice is refused."""
154
+ if _already_hooked(emitter):
155
+ raise TypeError("This DynamoDB client or session is already hooked by dynamodb_store.")
156
+ register = emitter.register
157
+ register("before-parameter-build.dynamodb", self.before_parameter_build, unique_id=_UNIQUE_ID + "-guard")
158
+ register("after-call.dynamodb", self.after_call, unique_id=_UNIQUE_ID + "-after")
159
+ register("after-call-error.dynamodb", self.after_call_error, unique_id=_UNIQUE_ID + "-error")
160
+ try:
161
+ emitter._sendproof_dynamodb = True
162
+ except AttributeError: # an emitter without a __dict__ cannot be marked; the unique ids still prevent duplicates
163
+ pass
164
+
165
+
166
+ def _already_hooked(emitter: Any) -> bool:
167
+ """Whether the guard handlers are already registered on ``emitter``.
168
+
169
+ botocore keeps registered ``unique_id`` values on the emitter, behind the event aliaser that
170
+ clients wrap it in, and copies them into each client made from a hooked session, so this sees a
171
+ session's hook from its clients. The flag set at registration is the fallback.
172
+ """
173
+ for candidate in (emitter, getattr(emitter, "_emitter", None)):
174
+ registered = getattr(candidate, "_unique_id_handlers", None)
175
+ if isinstance(registered, dict) and (_UNIQUE_ID + "-guard") in registered:
176
+ return True
177
+ return bool(getattr(emitter, "_sendproof_dynamodb", False))
178
+
179
+
180
+ def _emitter(target: Any) -> Any:
181
+ """The object whose ``register`` adds botocore event handlers for ``target``."""
182
+ meta = getattr(target, "meta", None)
183
+ if meta is not None and hasattr(meta, "events"): # a client
184
+ return meta.events
185
+ client = getattr(meta, "client", None)
186
+ if client is not None and hasattr(client.meta, "events"): # a boto3 resource or Table
187
+ return client.meta.events
188
+ for name in ("events", "_session"): # a boto3 / aioboto3 session
189
+ inner = getattr(target, name, None)
190
+ if inner is not None and hasattr(inner, "register"):
191
+ return inner
192
+ if hasattr(target, "register"): # a botocore or aiobotocore session, or an emitter
193
+ return target
194
+ raise TypeError("dynamodb_store takes a boto3 or aioboto3 session, a botocore session, a client or a resource.")
195
+
196
+
197
+ def dynamodb_store(
198
+ target: Any, *, name: Optional[str] = None, treat_as_read: Optional[Iterable[str]] = None,
199
+ ) -> DynamoDBStore:
200
+ """Hook a boto3 or aioboto3 session, a botocore session, a client or a resource, and return the store.
201
+
202
+ Hooking the same target twice is refused, so its operations are never logged twice.
203
+
204
+ Args:
205
+ target: ``boto3.Session()``, ``aioboto3.Session()``, ``botocore.session.Session()``, a
206
+ DynamoDB client, or a resource or table. A session covers clients made from it
207
+ afterwards; a client covers itself.
208
+ name: A display label for discovery, such as ``orders``. Never an endpoint or ARN.
209
+ treat_as_read: Action names you state never write, matched exactly.
210
+ **The guard trusts this list**: a listed action that does write is not blocked.
211
+ """
212
+ store = DynamoDBStore(store_label(name), read_set(treat_as_read))
213
+ store.register(_emitter(target))
214
+ return store
@@ -0,0 +1,248 @@
1
+ """Sendproof write guard for Elasticsearch and OpenSearch (``spec/data-stores.md``, ``guard`` mode).
2
+
3
+ ``elasticsearch_store(client)`` hooks an ``elasticsearch`` 8 client (``Elasticsearch`` or
4
+ ``AsyncElasticsearch``) and ``opensearch_store(client)`` an ``opensearch-py`` 2 client
5
+ (``OpenSearch`` or ``AsyncOpenSearch``) in place. The hook is a ``Transport`` subclass whose
6
+ ``perform_request(method, target, body=...)`` is the one place every typed API call, helper
7
+ (``helpers.bulk``, ``helpers.scan``) and raw ``client.perform_request`` goes through, below the
8
+ serializer and the HTTP node, so a refused write never becomes an HTTP request:
9
+
10
+ * The request is classified by method and path (and, for the SQL endpoints, the body) with the
11
+ shared ``elasticsearch.json`` table. A ``POST`` to ``_search`` reads; ``_bulk``,
12
+ ``_update_by_query``, ``_delete_by_query``, ``_reindex``, document ``PUT``/``POST``/``DELETE`` and
13
+ every index, alias, template and mapping change write.
14
+ * Reads run and become a ``Db`` entry whose statement is the request body with every value replaced
15
+ by ``?``. In a Preview the first write raises
16
+ :class:`~sendproof_core.stores.guard.PreviewWriteBlocked` and the Preview answers 409.
17
+ * Point-in-time, scroll, async-search and SQL-cursor handles are session state: allowed, not logged.
18
+
19
+ Derived clients stay guarded: ``client.options(...)`` (and ``child``-style copies) share the
20
+ hooked transport. Hooking a client covers that client and its copies; a second client built
21
+ elsewhere is not covered unless it is built with ``store.guard_transport_class(...)``::
22
+
23
+ store = elasticsearch_store(name="search") # no client yet
24
+ client = Elasticsearch(url, transport_class=store.guard_transport_class(Transport))
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import inspect
30
+ import json
31
+ import time
32
+ from typing import Any, Iterable, Mapping, Optional
33
+
34
+ from .base import DataStore
35
+ from .classify import SESSION
36
+ from .classify_batch_two import classify_elasticsearch, elasticsearch_target
37
+ from .guard import check_command, read_set, sanitize_document, store_label
38
+
39
+
40
+ def sanitize_body(body: Any) -> Optional[str]:
41
+ """A request body as ``Db`` statement text: field names and operators kept, every value ``?``.
42
+
43
+ NDJSON (``_bulk``, ``_msearch``) is sanitized line by line. A body the hook can't read becomes ``?``.
44
+ """
45
+ if body is None or body == "" or body == b"":
46
+ return None
47
+ if isinstance(body, (bytes, bytearray)):
48
+ body = bytes(body).decode("utf-8", "replace")
49
+ if isinstance(body, str):
50
+ lines = [line for line in body.split("\n") if line.strip()]
51
+ try:
52
+ return "\n".join(json.dumps(sanitize_document(json.loads(line)), separators=(",", ":")) for line in lines)
53
+ except ValueError:
54
+ return "?"
55
+ try:
56
+ return json.dumps(sanitize_document(body), separators=(",", ":"))
57
+ except (TypeError, ValueError):
58
+ return "?"
59
+
60
+
61
+ def _rows(body: Any) -> Optional[int]:
62
+ """Documents returned, matched or written, when the reply says so."""
63
+ if isinstance(body, (bytes, bytearray, str)) or not isinstance(body, Mapping):
64
+ return None
65
+ hits = body.get("hits")
66
+ if isinstance(hits, Mapping) and isinstance(hits.get("hits"), list):
67
+ return len(hits["hits"])
68
+ for key in ("docs", "items"):
69
+ if isinstance(body.get(key), list):
70
+ return len(body[key])
71
+ for key in ("updated", "deleted"):
72
+ if isinstance(body.get(key), int) and not isinstance(body.get(key), bool):
73
+ return body[key]
74
+ if body.get("found") is True or body.get("result") in ("created", "updated", "deleted"):
75
+ return 1
76
+ return None
77
+
78
+
79
+ def _error_name(error: BaseException) -> str:
80
+ """The store's error type (``version_conflict_engine_exception``) when the client exposes it, else the class name."""
81
+ found = getattr(error, "error", None)
82
+ return found if isinstance(found, str) and found and len(found) <= 64 else type(error).__name__
83
+
84
+
85
+ class _GuardBase:
86
+ """What the four guarded transports share: classify, guard, then log when the reply arrives."""
87
+
88
+ _sendproof_store: "ElasticsearchStore"
89
+
90
+ def _sendproof_before(self, method: Any, path: Any, body: Any) -> Optional[tuple]:
91
+ store = self._sendproof_store
92
+ verdict = classify_elasticsearch(method, path, body, store._reads)
93
+ scope = check_command(store.system, verdict.operation, verdict.kind)
94
+ if scope is None or verdict.kind == SESSION:
95
+ return None # outside a request, or a handle that is never logged
96
+ return scope, verdict, elasticsearch_target(path), sanitize_body(body), time.perf_counter()
97
+
98
+ def _sendproof_after(self, pending: Optional[tuple], response: Any, error: Optional[BaseException]) -> None:
99
+ if pending is None:
100
+ return
101
+ scope, verdict, target, statement, began = pending
102
+ body = getattr(response, "body", response)
103
+ scope.capture.record_db(
104
+ self._sendproof_store.system, verdict.operation, target=target, statement=statement,
105
+ rows_affected=None if error is not None else _rows(body),
106
+ error=None if error is None else _error_name(error), elapsed_ms=(time.perf_counter() - began) * 1000,
107
+ )
108
+
109
+
110
+ class _ElasticSync(_GuardBase):
111
+ """Mixin for ``elastic_transport.Transport``."""
112
+
113
+ def perform_request(self, method: Any, target: Any, *args: Any, **kwargs: Any) -> Any:
114
+ pending = self._sendproof_before(method, target, kwargs.get("body"))
115
+ try:
116
+ response = super().perform_request(method, target, *args, **kwargs) # type: ignore[misc]
117
+ except Exception as error:
118
+ self._sendproof_after(pending, None, error)
119
+ raise
120
+ self._sendproof_after(pending, response, None)
121
+ return response
122
+
123
+
124
+ class _ElasticAsync(_GuardBase):
125
+ """Mixin for ``elastic_transport.AsyncTransport``."""
126
+
127
+ async def perform_request(self, method: Any, target: Any, *args: Any, **kwargs: Any) -> Any:
128
+ pending = self._sendproof_before(method, target, kwargs.get("body"))
129
+ try:
130
+ response = await super().perform_request(method, target, *args, **kwargs) # type: ignore[misc]
131
+ except Exception as error:
132
+ self._sendproof_after(pending, None, error)
133
+ raise
134
+ self._sendproof_after(pending, response, None)
135
+ return response
136
+
137
+
138
+ class _OpenSync(_GuardBase):
139
+ """Mixin for ``opensearchpy.Transport``, whose ``perform_request(method, url, params, body, ...)`` takes the body positionally."""
140
+
141
+ def perform_request(self, method: Any, url: Any, params: Any = None, body: Any = None, *args: Any, **kwargs: Any) -> Any:
142
+ pending = self._sendproof_before(method, url, body)
143
+ try:
144
+ response = super().perform_request(method, url, params, body, *args, **kwargs) # type: ignore[misc]
145
+ except Exception as error:
146
+ self._sendproof_after(pending, None, error)
147
+ raise
148
+ self._sendproof_after(pending, response, None)
149
+ return response
150
+
151
+
152
+ class _OpenAsync(_GuardBase):
153
+ """Mixin for ``opensearchpy.AsyncTransport``."""
154
+
155
+ async def perform_request(self, method: Any, url: Any, params: Any = None, body: Any = None, *args: Any, **kwargs: Any) -> Any:
156
+ pending = self._sendproof_before(method, url, body)
157
+ try:
158
+ response = await super().perform_request(method, url, params, body, *args, **kwargs) # type: ignore[misc]
159
+ except Exception as error:
160
+ self._sendproof_after(pending, None, error)
161
+ raise
162
+ self._sendproof_after(pending, response, None)
163
+ return response
164
+
165
+
166
+ _GUARDS = (_ElasticSync, _ElasticAsync, _OpenSync, _OpenAsync)
167
+ _classes: dict[tuple[type, int], type] = {}
168
+
169
+
170
+ def _flavor(base: type) -> str:
171
+ """``opensearch`` for an ``opensearch-py`` transport class, ``elasticsearch`` for an ``elastic-transport`` one."""
172
+ return "opensearch" if base.__module__.split(".")[0] == "opensearchpy" else "elasticsearch"
173
+
174
+
175
+ class ElasticsearchStore(DataStore):
176
+ """A hooked Elasticsearch or OpenSearch client, ready for ``data_stores``.
177
+
178
+ ``system`` is ``elasticsearch`` or ``opensearch``: the id the ``Db`` entries, discovery and the 409 report.
179
+ """
180
+
181
+ def __init__(self, system: str, name: Optional[str], reads: Optional[frozenset[str]]) -> None:
182
+ self.system = system
183
+ self.name = name
184
+ self._reads = reads
185
+
186
+ def describe(self) -> dict[str, Any]:
187
+ return {"system": self.system, **({"name": self.name} if self.name else {}), "mode": "guard"}
188
+
189
+ def guard_transport_class(self, base: type) -> type:
190
+ """A guarded subclass of a transport class, for ``transport_class=`` when you build the client yourself."""
191
+ if issubclass(base, _GUARDS):
192
+ return base
193
+ flavor = _flavor(base)
194
+ if flavor != self.system:
195
+ raise TypeError(f"{base.__name__} belongs to the {flavor} client; use {flavor}_store.")
196
+ asynchronous = inspect.iscoroutinefunction(base.perform_request)
197
+ mixin = {("elasticsearch", False): _ElasticSync, ("elasticsearch", True): _ElasticAsync,
198
+ ("opensearch", False): _OpenSync, ("opensearch", True): _OpenAsync}[(flavor, asynchronous)]
199
+ key = (base, id(self))
200
+ found = _classes.get(key)
201
+ if found is None:
202
+ found = _classes[key] = type(f"Guarded{base.__name__}", (mixin, base), {
203
+ "_sendproof_store": self, "__module__": __name__,
204
+ })
205
+ return found
206
+
207
+ def guard_transport(self, transport: Any) -> None:
208
+ """Guard one transport object in place. Hooking a transport twice is refused."""
209
+ if isinstance(transport, _GUARDS):
210
+ raise TypeError(f"This {self.system} client is already hooked by {self.system}_store.")
211
+ transport.__class__ = self.guard_transport_class(type(transport))
212
+
213
+
214
+ def _hook(system: str, client: Any, name: Optional[str], treat_as_read: Optional[Iterable[str]]) -> ElasticsearchStore:
215
+ store = ElasticsearchStore(system, store_label(name), read_set(treat_as_read, allow_spaces=True))
216
+ if client is not None:
217
+ transport = getattr(client, "transport", None) or getattr(client, "_transport", None) or client
218
+ if not hasattr(transport, "perform_request"):
219
+ raise TypeError(f"{system}_store takes a {system} client or its transport.")
220
+ store.guard_transport(transport)
221
+ return store
222
+
223
+
224
+ def elasticsearch_store(client: Any = None, *, name: Optional[str] = None,
225
+ treat_as_read: Optional[Iterable[str]] = None) -> ElasticsearchStore:
226
+ """Hook an ``elasticsearch`` 8 client in place and return the store for ``data_stores``.
227
+
228
+ ``client`` is an ``Elasticsearch`` or ``AsyncElasticsearch`` (or its ``Transport``). Pass
229
+ nothing to get just the store and build your client with
230
+ ``transport_class=store.guard_transport_class(Transport)``. Hooking the same client twice is
231
+ refused, so a request is never logged twice.
232
+
233
+ Args:
234
+ name: A display label for discovery, such as ``search``. Never a URL or host name.
235
+ treat_as_read: Operation names you state never write: the table's endpoint name, or
236
+ ``METHOD /path`` for an unlisted endpoint, such as ``POST /{}/_refresh``. Exact names,
237
+ no wildcards. **The guard trusts this list**: a listed request that does write is not blocked.
238
+ """
239
+ return _hook("elasticsearch", client, name, treat_as_read)
240
+
241
+
242
+ def opensearch_store(client: Any = None, *, name: Optional[str] = None,
243
+ treat_as_read: Optional[Iterable[str]] = None) -> ElasticsearchStore:
244
+ """Hook an ``opensearch-py`` 2 client (``OpenSearch`` or ``AsyncOpenSearch``) in place; see :func:`elasticsearch_store`.
245
+
246
+ The store reports ``opensearch`` as its system.
247
+ """
248
+ return _hook("opensearch", client, name, treat_as_read)