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,88 @@
1
+ """Decides which SQL text and parameter names look like secrets.
2
+
3
+ Words are split at punctuation, underscores and camel-case boundaries. ``key`` alone is ordinary
4
+ (primary key, idempotency key) and counts only after qualifiers such as ``api`` or ``private``.
5
+ Session identifiers and payloads (``session_key``, ``session_data``, ``session_id``) are bearer
6
+ credentials, so they count as secrets too: a statement on Django's ``django_session`` table or a
7
+ Flask-Session table names them and has all of its values redacted.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+
14
+ REDACTED = "[REDACTED]"
15
+
16
+ _SECRET_WORDS = frozenset(
17
+ {"password", "passwd", "pwd", "secret", "token", "hash", "salt", "credential", "credentials", "apikey"}
18
+ )
19
+ _KEY_QUALIFIERS = frozenset({"api", "private", "secret", "access", "signing", "encryption", "client"})
20
+ _SESSION_PARTS = frozenset({"key", "data", "id", "token"})
21
+ _WORD = re.compile(r"[A-Z]+(?![a-z])|[A-Z]?[a-z]+|[0-9]+")
22
+
23
+
24
+ def looks_secret(text: str) -> bool:
25
+ """Whether an identifier or statement names a secret, judged by whole words."""
26
+ previous: str | None = None
27
+ for match in _WORD.finditer(text):
28
+ word = match.group(0).lower()
29
+ if word in _SECRET_WORDS or (word == "key" and previous in _KEY_QUALIFIERS):
30
+ return True
31
+ if previous == "session" and word in _SESSION_PARTS:
32
+ return True
33
+ previous = word
34
+ return False
35
+
36
+
37
+ def redact_deep(value: object) -> object:
38
+ """Replace the value of every secret-named field, at any depth of a nested document.
39
+
40
+ A secret-named field (``password_hash``, ``apiKey``) keeps its place but shows
41
+ :data:`REDACTED`, even when its value is itself a document or a list. ``None`` is left as it
42
+ is, so an absent secret stays distinguishable.
43
+ """
44
+ if isinstance(value, dict):
45
+ return {
46
+ name: (REDACTED if looks_secret(str(name)) and inner is not None else redact_deep(inner))
47
+ for name, inner in value.items()
48
+ }
49
+ if isinstance(value, (list, tuple)):
50
+ return [redact_deep(item) for item in value]
51
+ return value
52
+
53
+
54
+ def python_type_name(value: object) -> str:
55
+ """A database-neutral type label for a bound Python value."""
56
+ return {str: "String", int: "Int64", float: "Double", bool: "Boolean", bytes: "Binary"}.get(
57
+ type(value), type(value).__name__
58
+ )
59
+
60
+
61
+ def describe_parameters(
62
+ statement: str, named: "list[tuple[str, object, str]]", show_values: bool
63
+ ) -> "tuple[list[tuple[str, str | None, str]], bool]":
64
+ """Stringify and redact bound parameters for the log.
65
+
66
+ ``named`` holds ``(name, value, type label)``. Values show only when ``show_values`` is true,
67
+ a parameter named like a secret always shows :data:`REDACTED`, and a statement that mentions
68
+ a secret word hides every value in it. Returns the entries and whether anything was clipped.
69
+ """
70
+ from . import limits
71
+
72
+ redact_all = show_values and looks_secret(statement)
73
+ result: list[tuple[str, str | None, str]] = []
74
+ truncated = len(named) > limits.PARAMETERS
75
+ for name, value, kind in named[: limits.PARAMETERS]:
76
+ if not show_values or redact_all or looks_secret(name):
77
+ result.append((name, REDACTED, kind))
78
+ elif value is None:
79
+ result.append((name, None, kind))
80
+ elif isinstance(value, (bytes, bytearray, memoryview)):
81
+ raw = bytes(value)
82
+ result.append((name, raw[: limits.TEXT // 2].hex(), kind))
83
+ truncated |= len(raw) > limits.TEXT // 2
84
+ else:
85
+ text = str(value)
86
+ result.append((name, limits.clip(text), kind))
87
+ truncated |= len(text) > limits.TEXT
88
+ return result, truncated
@@ -0,0 +1,146 @@
1
+ """Request scope shared between adapters, providers and application code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import threading
7
+ from contextlib import contextmanager
8
+ from contextvars import ContextVar, Token
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Iterator
11
+
12
+ from .capture import Capture, CaptureLogHandler
13
+
14
+
15
+ @dataclass
16
+ class RequestScope:
17
+ """State of one preview or observed request.
18
+
19
+ Providers keep their own state in :attr:`extensions` under a unique key.
20
+ """
21
+
22
+ capture: Capture
23
+ environment: str
24
+ include_sql_parameter_values: bool
25
+ extensions: dict[str, Any] = field(default_factory=dict)
26
+ #: Set when the application handler is entered, i.e. after routing and authorization.
27
+ entered: bool = False
28
+ #: Document, item and key changes captured by ``preview``-mode data stores (MongoDB), in addition
29
+ #: to the SQL provider's own.
30
+ store_changes: list[Any] = field(default_factory=list)
31
+ store_changes_truncated: bool = False
32
+
33
+ @property
34
+ def rollback(self) -> bool:
35
+ """Whether this scope is a rollback-only preview."""
36
+ return self.capture.rollback
37
+
38
+
39
+ _current: ContextVar[RequestScope | None] = ContextVar("sendproof_scope", default=None)
40
+ _handler: CaptureLogHandler | None = None
41
+
42
+ #: How code without a scope is attributed: ``"request"`` inside any request the adapter saw,
43
+ #: ``"detached"`` inside work the host marked with :func:`detached`, ``None`` otherwise.
44
+ _attribution: ContextVar[str | None] = ContextVar("sendproof_attribution", default=None)
45
+ #: Previews currently open in this process, by scope identity, with how often each is active.
46
+ _open: dict[int, list[Any]] = {}
47
+ _open_lock = threading.Lock()
48
+
49
+
50
+ def current_scope() -> RequestScope | None:
51
+ """Return the preview or observed scope of the running request, if any."""
52
+ return _current.get()
53
+
54
+
55
+ def activate(scope: RequestScope) -> Token[RequestScope | None]:
56
+ """Make ``scope`` current for this context. Pass the token to :func:`deactivate`.
57
+
58
+ A Preview scope counts as open from here until the matching :func:`deactivate`.
59
+ """
60
+ token = _current.set(scope)
61
+ if scope.rollback:
62
+ with _open_lock:
63
+ _open.setdefault(id(scope), [scope, 0])[1] += 1
64
+ return token
65
+
66
+
67
+ def deactivate(token: Token[RequestScope | None]) -> None:
68
+ """Restore the previous scope."""
69
+ scope = _current.get()
70
+ _current.reset(token)
71
+ if scope is not None and scope.rollback:
72
+ with _open_lock:
73
+ entry = _open.get(id(scope))
74
+ if entry is not None and entry[0] is scope:
75
+ entry[1] -= 1
76
+ if entry[1] <= 0:
77
+ del _open[id(scope)]
78
+
79
+
80
+ def open_previews() -> list[RequestScope]:
81
+ """Every Preview currently open in this process."""
82
+ with _open_lock:
83
+ return [entry[0] for entry in _open.values()]
84
+
85
+
86
+ def attributed() -> bool:
87
+ """Whether the running code belongs to a request the adapter saw, or to host-marked background work.
88
+
89
+ Store hooks use it to tell a write that some request made from one that nothing can attribute,
90
+ such as a thread a handler started without copying its context.
91
+ """
92
+ return _current.get() is not None or _attribution.get() is not None
93
+
94
+
95
+ @contextmanager
96
+ def request_context() -> Iterator[None]:
97
+ """Mark the ``with`` body as part of an ordinary request. The framework adapters wrap every request in it."""
98
+ token = _attribution.set("request")
99
+ try:
100
+ yield
101
+ finally:
102
+ _attribution.reset(token)
103
+
104
+
105
+ def enter_request() -> Token[str | None]:
106
+ """Mark the current context as part of an ordinary request until :func:`leave_request`."""
107
+ return _attribution.set("request")
108
+
109
+
110
+ def leave_request(token: Token[str | None]) -> None:
111
+ """End :func:`enter_request`. Tolerates a token from another context (a server that never closed the body)."""
112
+ try:
113
+ _attribution.reset(token)
114
+ except ValueError:
115
+ pass
116
+
117
+
118
+ @contextmanager
119
+ def detached() -> Iterator[None]:
120
+ """Mark background work that belongs to no request, such as a worker thread or a scheduled job.
121
+
122
+ While a Preview is open, a store write that no request and no ``detached()`` block accounts
123
+ for fails every open Preview with 500: it may come from a handler's own thread, which a
124
+ Preview cannot roll back. Wrap genuine background work in this so it never does::
125
+
126
+ def refresh_cache():
127
+ with detached():
128
+ cache.set("rates", fetch_rates())
129
+ """
130
+ token = _attribution.set("detached")
131
+ try:
132
+ yield
133
+ finally:
134
+ _attribution.reset(token)
135
+
136
+
137
+ def install_logging_capture() -> None:
138
+ """Attach the capture handler to the root logger once.
139
+
140
+ Records reach it only when their logger propagates to the root logger and its effective
141
+ level allows them, as with any other root handler.
142
+ """
143
+ global _handler
144
+ if _handler is None:
145
+ _handler = CaptureLogHandler(current_scope)
146
+ logging.getLogger().addHandler(_handler)
@@ -0,0 +1,119 @@
1
+ """Data-store support: the write guard and the Redis, DynamoDB, MongoDB, Cassandra, Elasticsearch,
2
+ OpenSearch, Cosmos DB and Firestore hooks (``spec/data-stores.md``).
3
+
4
+ Each hook is imported on first use, so installing the core never requires a store client library::
5
+
6
+ from sendproof_core.stores import dynamodb_store, mongo_store, redis_store
7
+
8
+ bench = Sendproof(
9
+ app,
10
+ provider=SQLAlchemyPreview(engine),
11
+ data_stores=[
12
+ mongo_store(mongo_client, name="catalog"), # handlers use the returned store's .client
13
+ redis_store(redis_client, name="cache"), # hooks the client in place
14
+ dynamodb_store(boto3_session, name="orders"),
15
+ # Batch two, guard-only: each hooks its client in place.
16
+ cassandra_store(cluster, name="tickets"),
17
+ elasticsearch_store(es_client, name="search"), # opensearch_store(...) for opensearch-py
18
+ cosmosdb_store(cosmos_client, name="orders"),
19
+ firestore_store(firestore_client, name="profiles"),
20
+ ],
21
+ )
22
+
23
+ Only hooked clients are covered. A client created inside a handler, a second client for the same
24
+ store, or a raw socket is not: its writes are neither blocked nor rolled back.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from typing import Any
30
+
31
+ from .base import DataStore, StoresOnlyProvider
32
+ from .classify import classify_dynamo, classify_mongo, classify_redis, partiql_verb
33
+ from .classify_batch_two import (
34
+ Verdict,
35
+ classify_cassandra,
36
+ classify_cassandra_message,
37
+ classify_cosmos,
38
+ classify_elasticsearch,
39
+ classify_firestore,
40
+ cosmos_operation,
41
+ firestore_rpc,
42
+ )
43
+ from .guard import (
44
+ PreviewTransactionControl,
45
+ PreviewWriteBlocked,
46
+ guard,
47
+ refuse_in_preview,
48
+ sanitize_document,
49
+ write_reason,
50
+ )
51
+
52
+ # Each hook lives in a module named ``*_hook`` so that its factory function can carry the public name.
53
+ _LAZY = {
54
+ "redis_store": "redis_hook",
55
+ "RedisStore": "redis_hook",
56
+ "dynamodb_store": "dynamodb_hook",
57
+ "DynamoDBStore": "dynamodb_hook",
58
+ "mongo_store": "mongo_hook",
59
+ "MongoStore": "mongo_hook",
60
+ "mongo_monitor": "mongo_hook",
61
+ "cassandra_store": "cassandra_hook",
62
+ "CassandraStore": "cassandra_hook",
63
+ "elasticsearch_store": "elasticsearch_hook",
64
+ "opensearch_store": "elasticsearch_hook",
65
+ "ElasticsearchStore": "elasticsearch_hook",
66
+ "cosmosdb_store": "cosmos_hook",
67
+ "CosmosDBStore": "cosmos_hook",
68
+ "firestore_store": "firestore_hook",
69
+ "FirestoreStore": "firestore_hook",
70
+ }
71
+
72
+
73
+ def __getattr__(name: str) -> Any:
74
+ module = _LAZY.get(name)
75
+ if module is None:
76
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
77
+ from importlib import import_module
78
+
79
+ return getattr(import_module(f".{module}", __name__), name)
80
+
81
+
82
+ __all__ = [
83
+ "CassandraStore",
84
+ "CosmosDBStore",
85
+ "DataStore",
86
+ "DynamoDBStore",
87
+ "ElasticsearchStore",
88
+ "FirestoreStore",
89
+ "MongoStore",
90
+ "PreviewTransactionControl",
91
+ "PreviewWriteBlocked",
92
+ "RedisStore",
93
+ "StoresOnlyProvider",
94
+ "Verdict",
95
+ "cassandra_store",
96
+ "classify_cassandra",
97
+ "classify_cassandra_message",
98
+ "classify_cosmos",
99
+ "classify_dynamo",
100
+ "classify_elasticsearch",
101
+ "classify_firestore",
102
+ "classify_mongo",
103
+ "classify_redis",
104
+ "cosmos_operation",
105
+ "cosmosdb_store",
106
+ "dynamodb_store",
107
+ "elasticsearch_store",
108
+ "firestore_rpc",
109
+ "firestore_store",
110
+ "guard",
111
+ "mongo_monitor",
112
+ "mongo_store",
113
+ "opensearch_store",
114
+ "partiql_verb",
115
+ "redis_store",
116
+ "refuse_in_preview",
117
+ "sanitize_document",
118
+ "write_reason",
119
+ ]
@@ -0,0 +1,99 @@
1
+ """The contract every data-store hook implements, and the stand-in provider for apps without SQL.
2
+
3
+ A :class:`DataStore` is what ``redis_store(...)``, ``dynamodb_store(...)``, ``mongo_store(...)`` and the
4
+ batch-two factories (``cassandra_store``, ``elasticsearch_store``, ``opensearch_store``,
5
+ ``cosmosdb_store``, ``firestore_store``) return. The framework adapters pass the list they were given (``data_stores=[...]``) to the
6
+ Preview pipeline:
7
+
8
+ 1. ``begin(scope)`` runs before the handler. A ``preview``-mode store (MongoDB on a replica set)
9
+ starts its transaction here.
10
+ 2. The handler runs. Hooks call :func:`~sendproof_core.stores.guard.guard` before sending.
11
+ 3. ``finish(scope)`` runs after the handler and before the SQL rollback. A ``preview``-mode store
12
+ captures its changes and aborts its transaction; a failure here answers 500.
13
+
14
+ Every method has a synchronous and an ``a``-prefixed asynchronous form, so the ASGI adapter never
15
+ blocks its event loop on a synchronous client and the WSGI adapters never need an event loop.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from typing import Any, Optional
21
+
22
+ from ..provider import PreviewChange, PreviewObservation, PreviewProvider, PreviewSession, run_in_thread
23
+ from ..scope import RequestScope
24
+
25
+
26
+ class DataStore:
27
+ """A hooked data store. Subclasses override what they need; the defaults do nothing."""
28
+
29
+ #: Short store id: ``mongodb``, ``redis``, ``dynamodb``, ``cassandra``, ``elasticsearch``, ``opensearch``,
30
+ #: ``cosmosdb`` or ``firestore``.
31
+ system: str = ""
32
+
33
+ def describe(self) -> dict[str, Any]:
34
+ """The capabilities ``dataStores`` entry: ``system``, optional ``name``, ``mode``, optional ``reason``."""
35
+ raise NotImplementedError
36
+
37
+ async def adescribe(self) -> dict[str, Any]:
38
+ """Async form of :meth:`describe`; the default runs it in a worker thread."""
39
+ return await run_in_thread(self.describe)
40
+
41
+ def begin(self, scope: RequestScope) -> None:
42
+ """Prepare a Preview, for example start a transaction. Called before the handler."""
43
+
44
+ async def abegin(self, scope: RequestScope) -> None:
45
+ """Async form of :meth:`begin`; the default runs it in a worker thread."""
46
+ await run_in_thread(self.begin, scope)
47
+
48
+ def finish(self, scope: RequestScope) -> None:
49
+ """Capture changes and abort the store's transaction. Called after the handler, even if it failed."""
50
+
51
+ async def afinish(self, scope: RequestScope) -> None:
52
+ """Async form of :meth:`finish`; the default runs it in a worker thread."""
53
+ await run_in_thread(self.finish, scope)
54
+
55
+
56
+ class _NoChanges(PreviewSession, PreviewObservation):
57
+ """A session and an observation that capture no SQL changes and roll back nothing."""
58
+
59
+ @property
60
+ def changes(self) -> list[PreviewChange]:
61
+ return []
62
+
63
+ def rollback(self) -> None:
64
+ """Nothing to roll back."""
65
+
66
+ def close(self) -> None:
67
+ """Nothing to release."""
68
+
69
+ async def arollback(self) -> None:
70
+ """Nothing to roll back."""
71
+
72
+ async def aclose(self) -> None:
73
+ """Nothing to release."""
74
+
75
+
76
+ class StoresOnlyProvider(PreviewProvider):
77
+ """Lets an app Preview with data stores alone, when it registered no SQL provider.
78
+
79
+ The stores do their own rolling back and guarding, so the dispatch needs no SQL transaction.
80
+ A SQL database the host gave no provider for is then not covered, like any unhooked client.
81
+ """
82
+
83
+ database: Optional[str] = None
84
+ system: Optional[str] = None
85
+
86
+ def begin(self, scope: RequestScope) -> PreviewSession:
87
+ return _NoChanges()
88
+
89
+ def begin_observation(self, scope: RequestScope) -> PreviewObservation | None:
90
+ return _NoChanges()
91
+
92
+
93
+ def validate_stores(stores: Any) -> list[DataStore]:
94
+ """Check a ``data_stores`` argument and return it as a list."""
95
+ items = list(stores or ())
96
+ if any(not isinstance(item, DataStore) for item in items):
97
+ raise TypeError("data_stores takes stores made by redis_store, dynamodb_store, mongo_store, cassandra_store, "
98
+ "elasticsearch_store, opensearch_store, cosmosdb_store or firestore_store.")
99
+ return items
@@ -0,0 +1,173 @@
1
+ """Sendproof write guard for Cassandra (``spec/data-stores.md``, ``guard`` mode).
2
+
3
+ ``cassandra_store(target)`` guards a DataStax ``cassandra-driver`` (or ScyllaDB's fork) ``Session``
4
+ or ``Cluster`` in place. The hook overrides ``Session.execute_async``, which every other entry point
5
+ reaches: ``Session.execute``, ``execute_concurrent`` and the ``cqlengine`` object mapper all call
6
+ it. It sees the statement before the driver builds a message, so nothing is sent for a refused write:
7
+
8
+ * A statement is classified by the text it carries: a string, a ``SimpleStatement``, or a
9
+ ``BoundStatement`` / ``PreparedStatement``, whose ``prepared_statement.query_string`` is the text
10
+ the driver prepared, so an ``EXECUTE`` is classified exactly like its ``PREPARE``.
11
+ * Every ``BatchStatement`` is a write, even one holding only reads. ``execute_graph_async`` (DSE
12
+ Graph) is a write too: the guard can't read Gremlin.
13
+ * Reads run. In a Preview the first write raises
14
+ :class:`~sendproof_core.stores.guard.PreviewWriteBlocked` and the Preview answers 409. A read
15
+ becomes a ``Db`` entry whose statement has every literal replaced by ``?``.
16
+
17
+ Registering on a **cluster** covers its sessions: the ones that exist and every session
18
+ ``Cluster.connect`` creates afterwards (the hook wraps that cluster's ``connect``). Registering on a **session** covers that session only. A
19
+ session of another cluster, or a raw connection, is not covered.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import functools
25
+ import time
26
+ from typing import Any, Iterable, Optional
27
+
28
+ from ..scope import RequestScope
29
+ from .base import DataStore
30
+ from .classify import SESSION, WRITE
31
+ from .classify_batch_two import Verdict, classify_cassandra, cql_target, sanitize_cql
32
+ from .guard import check_command, read_set, store_label
33
+
34
+ _HOOKED = "_sendproof_cassandra_store"
35
+
36
+
37
+ def _query_text(query: Any) -> tuple[Optional[str], Optional[str]]:
38
+ """``(text, kind)`` of what ``Session.execute`` was given: the CQL text, or ``(None, "BATCH")``
39
+ for a batch and ``(None, "UNKNOWN")`` for a statement type the hook can't read."""
40
+ from cassandra.query import BatchStatement, BoundStatement, PreparedStatement, SimpleStatement
41
+
42
+ if isinstance(query, str):
43
+ return query, None
44
+ if isinstance(query, BatchStatement):
45
+ return None, "BATCH"
46
+ if isinstance(query, BoundStatement):
47
+ return query.prepared_statement.query_string, None
48
+ if isinstance(query, (PreparedStatement, SimpleStatement)):
49
+ return query.query_string, None
50
+ return None, "UNKNOWN"
51
+
52
+
53
+ class _Guarded:
54
+ """Mixin for ``cassandra.cluster.Session``: classify and guard before sending, log when done."""
55
+
56
+ _sendproof_store: "CassandraStore"
57
+
58
+ def execute_async(self, query: Any, *args: Any, **kwargs: Any) -> Any:
59
+ store = self._sendproof_store
60
+ text, special = _query_text(query)
61
+ verdict = Verdict(WRITE, special) if special else classify_cassandra(text, store._reads)
62
+ scope = check_command("cassandra", verdict.operation, verdict.kind)
63
+ began = time.perf_counter()
64
+ future = super().execute_async(query, *args, **kwargs) # type: ignore[misc]
65
+ if scope is not None and verdict.kind != SESSION:
66
+ store._log_when_done(future, scope, verdict, text, getattr(self, "keyspace", None), began)
67
+ return future
68
+
69
+ def execute_graph_async(self, *args: Any, **kwargs: Any) -> Any:
70
+ check_command("cassandra", "GRAPH", WRITE) # Gremlin can write and the guard can't read it
71
+ return super().execute_graph_async(*args, **kwargs) # type: ignore[misc]
72
+
73
+
74
+ _classes: dict[tuple[type, int], type] = {}
75
+
76
+
77
+ class CassandraStore(DataStore):
78
+ """A hooked Cassandra session or cluster, ready for ``data_stores``."""
79
+
80
+ system = "cassandra"
81
+
82
+ def __init__(self, name: Optional[str], reads: Optional[frozenset[str]]) -> None:
83
+ self.name = name
84
+ self._reads = reads
85
+
86
+ def describe(self) -> dict[str, Any]:
87
+ return {"system": "cassandra", **({"name": self.name} if self.name else {}), "mode": "guard"}
88
+
89
+ # ------------------------------------------------------------------ logging
90
+ def _log_when_done(self, future: Any, scope: RequestScope, verdict: Verdict, text: Optional[str],
91
+ keyspace: Optional[str], began: float) -> None:
92
+ """Log the command when its reply arrives. The driver runs callbacks on its own threads, so the
93
+ capture is bound here; one that already ended ignores the entry."""
94
+ statement = sanitize_cql(text) if text is not None else None
95
+ namespace, target = cql_target(statement) if statement else (None, None)
96
+ namespace = namespace or keyspace
97
+
98
+ def log(rows: Optional[int], error: Optional[str]) -> None:
99
+ scope.capture.record_db(
100
+ "cassandra", verdict.operation, target=target, namespace=namespace, statement=statement,
101
+ rows_affected=rows, error=error, elapsed_ms=(time.perf_counter() - began) * 1000,
102
+ )
103
+
104
+ def done(result: Any) -> None:
105
+ try:
106
+ rows = len(result) if result is not None and not isinstance(result, (str, bytes)) else None
107
+ except TypeError:
108
+ rows = None
109
+ log(rows, None)
110
+
111
+ future.add_callbacks(done, lambda error: log(None, type(error).__name__))
112
+
113
+ # ------------------------------------------------------------------ hooking
114
+ def guard_session(self, session: Any) -> None:
115
+ """Guard one session in place. Hooking a session twice is refused, so a command is never logged twice."""
116
+ if isinstance(session, _Guarded):
117
+ raise TypeError("This Cassandra session is already hooked by cassandra_store.")
118
+ base = type(session)
119
+ key = (base, id(self))
120
+ guarded = _classes.get(key)
121
+ if guarded is None:
122
+ guarded = _classes[key] = type(f"Guarded{base.__name__}", (_Guarded, base), {
123
+ "_sendproof_store": self, "__module__": __name__,
124
+ })
125
+ session.__class__ = guarded
126
+
127
+ def guard_cluster(self, cluster: Any) -> None:
128
+ """Guard a cluster's sessions: the existing ones, and every session ``connect()`` creates later."""
129
+ if getattr(cluster, _HOOKED, None) is not None:
130
+ raise TypeError("This Cassandra cluster is already hooked by cassandra_store.")
131
+ # ``connect()`` is the public, only way a cluster makes a session; wrapping it relies on no
132
+ # private method, so a driver that reorganizes its internals can't make sessions unguarded.
133
+ original = cluster.connect
134
+ sessions = getattr(cluster, "sessions", None)
135
+ if not callable(original) or sessions is None:
136
+ raise TypeError("This cassandra-driver Cluster has no connect() or sessions; cassandra_store can't guard it.")
137
+ store = self
138
+
139
+ @functools.wraps(original)
140
+ def connect(*args: Any, **kwargs: Any) -> Any:
141
+ session = original(*args, **kwargs)
142
+ if not isinstance(session, _Guarded):
143
+ store.guard_session(session)
144
+ return session
145
+
146
+ cluster.connect = connect
147
+ setattr(cluster, _HOOKED, self)
148
+ for session in list(sessions):
149
+ if not isinstance(session, _Guarded):
150
+ self.guard_session(session)
151
+
152
+
153
+ def cassandra_store(target: Any, *, name: Optional[str] = None, treat_as_read: Optional[Iterable[str]] = None) -> CassandraStore:
154
+ """Hook a ``cassandra-driver`` ``Cluster`` or ``Session`` in place and return the store for ``data_stores``.
155
+
156
+ Args:
157
+ target: A ``Cluster`` (covers its sessions, before and after the call) or a ``Session``
158
+ (covers that session). Hook the cluster whenever the host owns it.
159
+ name: A display label for discovery, such as ``tickets``. Never a contact point or host name.
160
+ treat_as_read: Statement keys you state never write, such as a custom statement
161
+ ``DESCRIBE``-like keyword: exact upper-case names (``LIST ROLES``), no wildcards.
162
+ **The guard trusts this list**: a listed statement that does write is not blocked.
163
+ """
164
+ from cassandra.cluster import Cluster, Session
165
+
166
+ store = CassandraStore(store_label(name), read_set(treat_as_read, lambda item: item.upper(), allow_spaces=True))
167
+ if isinstance(target, Session):
168
+ store.guard_session(target)
169
+ elif isinstance(target, Cluster):
170
+ store.guard_cluster(target)
171
+ else:
172
+ raise TypeError("cassandra_store takes a cassandra-driver Cluster or Session.")
173
+ return store