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,459 @@
1
+ """Sendproof write guard for Google Cloud Firestore (``spec/data-stores.md``, ``guard`` mode).
2
+
3
+ ``firestore_store(client)`` guards a ``google-cloud-firestore`` 2 ``Client`` or ``AsyncClient`` in
4
+ place with a **gRPC channel interceptor**, the hook that sees every call type:
5
+
6
+ * The interceptor covers unary calls (``Commit``, ``GetDocument``, ``BeginTransaction``...),
7
+ server-streaming calls (``RunQuery``, ``BatchGetDocuments``) **and** bidirectional streams
8
+ (``Listen``, ``Write``). A ``Write`` stream is refused when it is opened, before its first message,
9
+ so a unary-only interceptor could not have let it through.
10
+ * A call is classified by its RPC method with ``firestore.json``. ``Commit`` is a write when its
11
+ request carries at least one write; one with none only ends a transaction that read and wrote
12
+ nothing, so it is allowed. ``BatchWrite`` and the document RPCs are writes. A method the table
13
+ doesn't list is a write.
14
+ * Reads run and become a ``Db`` entry that names the RPC, the collection and the database, with the
15
+ request as JSON whose every literal, document paths included, is ``?``. In a Preview the first write
16
+ raises :class:`~sendproof_core.stores.guard.PreviewWriteBlocked` and the Preview answers 409.
17
+ * ``bulk_writer()`` returns a writer whose ``create``, ``set``, ``update`` and ``delete`` are refused in
18
+ a Preview where the handler queues them, on its thread: refusing the batch on the writer's own
19
+ threads would be retried until ``flush()`` hangs. Its batches run in the flushing code's context.
20
+
21
+ The hook overrides private methods, so registration refuses a ``google-cloud-firestore`` outside
22
+ the verified minor versions (:mod:`sendproof_core.stores.versions`) or a client whose layout differs.
23
+
24
+ How it is installed: ``Client`` takes no transport, and the GAPIC transport builds all its stubs
25
+ from the channel it is given, so the hook swaps the client's class for a subclass whose
26
+ ``_firestore_api_helper`` builds the transport over an intercepted channel
27
+ (``grpc.intercept_channel`` for ``Client``, a channel created with ``interceptors=`` for
28
+ ``AsyncClient``). ``_firestore_api_internal`` is cleared so a client already used is rebuilt guarded
29
+ at its next call. Every collection, document, query, batch, transaction and ``bulk_writer`` made
30
+ from the client reaches Firestore through ``client._firestore_api``, so they stay guarded; an
31
+ ``AsyncClient``'s synchronous copy (used by ``bulk_writer``) is guarded too. A second ``Client`` is
32
+ not covered unless it is hooked as well.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import concurrent.futures
38
+ import contextvars
39
+ import inspect
40
+ import json
41
+ import re
42
+ import time
43
+ from typing import Any, Iterable, Optional
44
+
45
+ from .base import DataStore
46
+ from .classify import SESSION, WRITE
47
+ from .classify_batch_two import classify_firestore
48
+ from .guard import check_command, read_set, sanitize_document, store_label
49
+ from .versions import require_supported
50
+
51
+ _DATABASE = re.compile(r"(?:^|/)databases/([^/]+)")
52
+
53
+
54
+ def _field(message: Any, name: str) -> Any:
55
+ """A request field by name, from a proto-plus or protobuf message or a mapping; ``None`` when absent."""
56
+ try:
57
+ if isinstance(message, dict):
58
+ return message.get(name)
59
+ return getattr(message, name, None)
60
+ except Exception: # a field the message class doesn't have
61
+ return None
62
+
63
+
64
+ def _collection_of(document_name: Any) -> Optional[str]:
65
+ """The collection id in a document name (``projects/p/databases/d/documents/orders/o-1`` is ``orders``)."""
66
+ if not isinstance(document_name, str) or "/documents/" not in document_name:
67
+ return None
68
+ parts = [part for part in document_name.split("/documents/", 1)[1].split("/") if part]
69
+ return parts[-2] if len(parts) >= 2 else (parts[0] if parts else None)
70
+
71
+
72
+ def describe_request(message: Any) -> tuple[Optional[str], Optional[str]]:
73
+ """``(collection, database)`` a request names, for the ``Db`` entry. Names only, never a value."""
74
+ if message is None:
75
+ return None, None
76
+ database = None
77
+ for name in ("database", "parent", "name"):
78
+ found = _DATABASE.search(str(_field(message, name) or ""))
79
+ if found:
80
+ database = found.group(1)
81
+ break
82
+ collection = None
83
+ writes = _field(message, "writes")
84
+ try:
85
+ first = writes[0] if writes else None
86
+ except (TypeError, IndexError, KeyError):
87
+ first = None
88
+ if first is not None:
89
+ for name in ("update", "transform"):
90
+ part = _field(first, name)
91
+ collection = _collection_of(_field(part, "name") or _field(part, "document")) if part is not None else None
92
+ if collection:
93
+ break
94
+ collection = collection or _collection_of(_field(first, "delete"))
95
+ if collection is None:
96
+ collection = _collection_of(_field(message, "name"))
97
+ if collection is None:
98
+ documents = _field(message, "documents")
99
+ try:
100
+ collection = _collection_of(documents[0]) if documents else None
101
+ except (TypeError, IndexError, KeyError):
102
+ collection = None
103
+ if collection is None:
104
+ query = _field(message, "structured_query")
105
+ if query is None:
106
+ query = _field(_field(message, "structured_aggregation_query"), "structured_query")
107
+ sources = _field(query, "from_") or _field(query, "from") if query is not None else None
108
+ try:
109
+ collection = _field(sources[0], "collection_id") if sources else None
110
+ except (TypeError, IndexError, KeyError):
111
+ collection = None
112
+ return collection or _field(message, "collection_id") or None, database
113
+
114
+
115
+ def describe_statement(message: Any) -> Optional[str]:
116
+ """The ``Db`` statement of a request: the message as JSON with every literal, document paths
117
+ included, replaced by ``"?"``. Field names are kept; ``None`` when the message can't be read."""
118
+ if message is None:
119
+ return None
120
+ try:
121
+ to_dict = getattr(type(message), "to_dict", None) # a proto-plus message
122
+ if callable(to_dict):
123
+ data = to_dict(message, use_integers_for_enums=False)
124
+ else:
125
+ from google.protobuf.json_format import MessageToDict
126
+
127
+ data = MessageToDict(message)
128
+ return json.dumps(sanitize_document(data), separators=(",", ":")) if data else None
129
+ except Exception: # an unknown message shape: log the call without a statement rather than fail it
130
+ return None
131
+
132
+
133
+ class _Guard:
134
+ """Classifies one call and writes its ``Db`` entry. Shared by the synchronous and asynchronous interceptors."""
135
+
136
+ def __init__(self, store: "FirestoreStore") -> None:
137
+ self.store = store
138
+
139
+ def before(self, method: Any, message: Any) -> Optional[tuple]:
140
+ """Classify the call, refuse a write in a Preview, and return what the ``Db`` entry needs."""
141
+ text = method.decode() if isinstance(method, (bytes, bytearray)) else str(method)
142
+ verdict = classify_firestore(text, message, self.store._reads)
143
+ scope = check_command("firestore", verdict.operation, verdict.kind)
144
+ if scope is None or verdict.kind == SESSION:
145
+ return None # outside a request, or a call that changes no data and isn't logged
146
+ collection, database = describe_request(message)
147
+ return scope, verdict, collection, database, describe_statement(message), time.perf_counter()
148
+
149
+ @staticmethod
150
+ def after(pending: Optional[tuple], outcome: Any) -> None:
151
+ """Log the call. A streaming call is logged when it is opened, so its entry has no error or timing."""
152
+ if pending is None:
153
+ return
154
+ scope, verdict, collection, database, statement, began = pending
155
+ error = None
156
+ try:
157
+ import grpc
158
+
159
+ if isinstance(outcome, grpc.RpcError) and callable(getattr(outcome, "code", None)):
160
+ code = outcome.code()
161
+ error = None if code is None or code == grpc.StatusCode.OK else code.name
162
+ except Exception:
163
+ error = None
164
+ scope.capture.record_db("firestore", verdict.operation, target=collection, namespace=database, statement=statement,
165
+ error=error, elapsed_ms=(time.perf_counter() - began) * 1000)
166
+
167
+
168
+ def _sync_interceptor(guard: _Guard) -> Any:
169
+ """A ``grpc`` client interceptor for all four call shapes."""
170
+ import grpc
171
+
172
+ class Interceptor(grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor,
173
+ grpc.StreamUnaryClientInterceptor, grpc.StreamStreamClientInterceptor):
174
+ _sendproof_guard = guard
175
+
176
+ def intercept_unary_unary(self, continuation: Any, client_call_details: Any, request: Any) -> Any:
177
+ pending = guard.before(client_call_details.method, request)
178
+ outcome = continuation(client_call_details, request)
179
+ guard.after(pending, outcome)
180
+ return outcome
181
+
182
+ def intercept_unary_stream(self, continuation: Any, client_call_details: Any, request: Any) -> Any:
183
+ pending = guard.before(client_call_details.method, request)
184
+ outcome = continuation(client_call_details, request)
185
+ guard.after(pending, None)
186
+ return outcome
187
+
188
+ def intercept_stream_unary(self, continuation: Any, client_call_details: Any, request_iterator: Any) -> Any:
189
+ pending = guard.before(client_call_details.method, None) # refused before the first message is read
190
+ outcome = continuation(client_call_details, request_iterator)
191
+ guard.after(pending, None)
192
+ return outcome
193
+
194
+ def intercept_stream_stream(self, continuation: Any, client_call_details: Any, request_iterator: Any) -> Any:
195
+ pending = guard.before(client_call_details.method, None) # Write is refused before its first message
196
+ outcome = continuation(client_call_details, request_iterator)
197
+ guard.after(pending, None)
198
+ return outcome
199
+
200
+ return Interceptor()
201
+
202
+
203
+ def _async_interceptors(guard: _Guard) -> list:
204
+ """The four ``grpc.aio`` client interceptors, one per call shape.
205
+
206
+ ``grpc.aio`` registers an interceptor for **one** shape, the first it is an instance of, so a
207
+ single object inheriting all four would guard unary calls only and let a ``Write`` stream through.
208
+ """
209
+ from grpc import aio
210
+
211
+ class UnaryUnary(aio.UnaryUnaryClientInterceptor):
212
+ async def intercept_unary_unary(self, continuation: Any, client_call_details: Any, request: Any) -> Any:
213
+ pending = guard.before(client_call_details.method, request)
214
+ outcome = await continuation(client_call_details, request)
215
+ guard.after(pending, None)
216
+ return outcome
217
+
218
+ class UnaryStream(aio.UnaryStreamClientInterceptor):
219
+ async def intercept_unary_stream(self, continuation: Any, client_call_details: Any, request: Any) -> Any:
220
+ pending = guard.before(client_call_details.method, request)
221
+ outcome = await continuation(client_call_details, request)
222
+ guard.after(pending, None)
223
+ return outcome
224
+
225
+ class StreamUnary(aio.StreamUnaryClientInterceptor):
226
+ async def intercept_stream_unary(self, continuation: Any, client_call_details: Any, request_iterator: Any) -> Any:
227
+ pending = guard.before(client_call_details.method, None)
228
+ outcome = await continuation(client_call_details, request_iterator)
229
+ guard.after(pending, None)
230
+ return outcome
231
+
232
+ class StreamStream(aio.StreamStreamClientInterceptor):
233
+ async def intercept_stream_stream(self, continuation: Any, client_call_details: Any, request_iterator: Any) -> Any:
234
+ pending = guard.before(client_call_details.method, None)
235
+ outcome = await continuation(client_call_details, request_iterator)
236
+ guard.after(pending, None)
237
+ return outcome
238
+
239
+ return [UnaryUnary(), UnaryStream(), StreamUnary(), StreamStream()]
240
+
241
+
242
+ _HOOKED = "_sendproof_firestore_store"
243
+ _bulk_writer_classes: dict[tuple[type, int], type] = {}
244
+
245
+
246
+ class _ContextExecutor(concurrent.futures.ThreadPoolExecutor):
247
+ """A thread pool that runs each task in the context of the code that submitted it.
248
+
249
+ ``BulkWriter`` submits its batches from the thread that queued or flushed them, so its sends
250
+ keep that request's attribution instead of arriving with none.
251
+ """
252
+
253
+ def submit(self, fn: Any, /, *args: Any, **kwargs: Any) -> Any: # type: ignore[override]
254
+ return super().submit(contextvars.copy_context().run, fn, *args, **kwargs)
255
+
256
+
257
+ def _guarded_bulk_writer_class(base: type, store: "FirestoreStore") -> type:
258
+ """A ``BulkWriter`` subclass whose writes are refused in a Preview before they are queued."""
259
+
260
+ def guarded(name: str) -> Any:
261
+ original = getattr(base, name)
262
+
263
+ def method(self: Any, *args: Any, **kwargs: Any) -> Any:
264
+ check_command("firestore", "BatchWrite", WRITE)
265
+ return original(self, *args, **kwargs)
266
+
267
+ method.__name__ = name
268
+ return method
269
+
270
+ namespace: dict[str, Any] = {name: guarded(name) for name in ("create", "set", "update", "delete")}
271
+ namespace.update({"_instantiate_executor": lambda self: _ContextExecutor(), _HOOKED: store, "__module__": __name__})
272
+ return type(f"Guarded{base.__name__}", (base,), namespace)
273
+
274
+
275
+ def _check_layout(base: type, asynchronous: bool) -> None:
276
+ """Refuse a client class whose private layout isn't the one the hook overrides."""
277
+ from google.cloud.firestore_v1 import base_client
278
+
279
+ problems = []
280
+ helper = getattr(base, "_firestore_api_helper", None)
281
+ try:
282
+ parameters = list(inspect.signature(helper).parameters) if callable(helper) else []
283
+ except (TypeError, ValueError):
284
+ parameters = []
285
+ if parameters != ["self", "transport", "client_class", "client_module"]:
286
+ problems.append("_firestore_api_helper(transport, client_class, client_module)")
287
+ if not hasattr(base, "_firestore_api_internal"):
288
+ problems.append("_firestore_api_internal")
289
+ if not callable(getattr(base, "bulk_writer", None)):
290
+ problems.append("bulk_writer")
291
+ if asynchronous:
292
+ problems += [name for name in ("_emulator_channel", "_to_sync_copy") if not callable(getattr(base, name, None))]
293
+ if not hasattr(base_client, "_GRPC_MSG_SIZE_OPTIONS"):
294
+ problems.append("base_client._GRPC_MSG_SIZE_OPTIONS")
295
+ if problems:
296
+ raise TypeError(f"This google-cloud-firestore client has no {', '.join(problems)}; firestore_store can't guard it.")
297
+
298
+
299
+ class FirestoreStore(DataStore):
300
+ """A hooked Firestore client, ready for ``data_stores``."""
301
+
302
+ system = "firestore"
303
+
304
+ def __init__(self, name: Optional[str], reads: Optional[frozenset[str]]) -> None:
305
+ self.name = name
306
+ self._reads = reads
307
+ self._guard = _Guard(self)
308
+ self._sync = None
309
+ self._async: Optional[list] = None
310
+
311
+ def describe(self) -> dict[str, Any]:
312
+ return {"system": "firestore", **({"name": self.name} if self.name else {}), "mode": "guard"}
313
+
314
+ def _interceptor(self, asynchronous: bool) -> Any:
315
+ """The synchronous interceptor, or the list of the four asynchronous ones."""
316
+ if asynchronous:
317
+ if self._async is None:
318
+ self._async = _async_interceptors(self._guard)
319
+ return self._async
320
+ if self._sync is None:
321
+ self._sync = _sync_interceptor(self._guard)
322
+ return self._sync
323
+
324
+ # ------------------------------------------------------------------ transports
325
+ def _guarded_transport(self, transport: type, asynchronous: bool) -> type:
326
+ """A subclass of the GAPIC gRPC transport that builds all its stubs over an intercepted channel."""
327
+ import grpc
328
+
329
+ store = self
330
+ if not asynchronous:
331
+ class SyncTransport(transport): # type: ignore[valid-type, misc]
332
+ def __init__(self, *args: Any, channel: Any = None, **kwargs: Any) -> None:
333
+ if not isinstance(channel, grpc.Channel):
334
+ raise TypeError("firestore_store needs the client's own gRPC channel to guard it.")
335
+ super().__init__(*args, channel=grpc.intercept_channel(channel, store._interceptor(False)), **kwargs)
336
+
337
+ SyncTransport.__name__ = SyncTransport.__qualname__ = f"Guarded{transport.__name__}"
338
+ return SyncTransport
339
+
340
+ class AsyncTransport(transport): # type: ignore[valid-type, misc]
341
+ @classmethod
342
+ def create_channel(cls, *args: Any, **kwargs: Any) -> Any:
343
+ kwargs["interceptors"] = [*(kwargs.get("interceptors") or ()), *store._interceptor(True)]
344
+ return super().create_channel(*args, **kwargs)
345
+
346
+ def __init__(self, *args: Any, channel: Any = None, **kwargs: Any) -> None:
347
+ # Every call shape must carry its interceptor. A channel whose layout differs, or one
348
+ # built without them, is refused rather than used unguarded.
349
+ ours = store._interceptor(True)
350
+ for shape, interceptor in zip(("unary_unary", "unary_stream", "stream_unary", "stream_stream"), ours):
351
+ found = getattr(channel, f"_{shape}_interceptors", None)
352
+ if not isinstance(found, list) or interceptor not in found:
353
+ raise TypeError("firestore_store needs the client's channel to carry its interceptors.")
354
+ super().__init__(*args, channel=channel, **kwargs)
355
+
356
+ AsyncTransport.__name__ = AsyncTransport.__qualname__ = f"Guarded{transport.__name__}"
357
+ return AsyncTransport
358
+
359
+ def _guarded_client_class(self, base: type, asynchronous: bool) -> type:
360
+ store = self
361
+
362
+ def _firestore_api_helper(self: Any, transport: type, client_class: Any, client_module: Any) -> Any:
363
+ return base._firestore_api_helper(self, store._guarded_transport(transport, asynchronous), client_class, client_module)
364
+
365
+ def bulk_writer(self: Any, *args: Any, **kwargs: Any) -> Any:
366
+ return store._guard_bulk_writer(base.bulk_writer(self, *args, **kwargs))
367
+
368
+ namespace: dict[str, Any] = {"_firestore_api_helper": _firestore_api_helper, "bulk_writer": bulk_writer,
369
+ "__module__": __name__, _HOOKED: self}
370
+
371
+ if asynchronous:
372
+ def _emulator_channel(self: Any, transport: type) -> Any:
373
+ # An asynchronous channel takes its interceptors when it is created.
374
+ import grpc
375
+ from google.cloud.firestore_v1.base_client import _GRPC_MSG_SIZE_OPTIONS
376
+
377
+ token = getattr(self._credentials, "id_token", None) if self._credentials is not None else None
378
+ options = [("Authorization", f"Bearer {token or 'owner'}"), *_GRPC_MSG_SIZE_OPTIONS]
379
+ return grpc.aio.insecure_channel(self._emulator_host, options=options, interceptors=store._interceptor(True))
380
+
381
+ def _to_sync_copy(self: Any) -> Any:
382
+ copy = base._to_sync_copy(self)
383
+ if getattr(type(copy), _HOOKED, None) is None:
384
+ store.guard_client(copy)
385
+ return copy
386
+
387
+ namespace["_emulator_channel"] = _emulator_channel
388
+ namespace["_to_sync_copy"] = _to_sync_copy
389
+ return type(f"Guarded{base.__name__}", (base,), namespace)
390
+
391
+ def _guard_bulk_writer(self, writer: Any) -> Any:
392
+ """Guard a ``BulkWriter``: refuse its writes where the handler queues them, and send its batches
393
+ in the context of the code that flushed them.
394
+
395
+ A ``BulkWriter`` sends ``BatchWrite`` from its own executor threads. Refusing there would leave
396
+ the refused batch counted in flight, and enough of those stall ``flush()`` for good, so in a
397
+ Preview ``create``, ``set``, ``update`` and ``delete`` are refused before anything is queued.
398
+ Outside a Preview its batches run in the flushing code's context, so an observed Send logs them.
399
+ """
400
+ base = type(writer)
401
+ if getattr(base, _HOOKED, None) is not None:
402
+ return writer
403
+ missing = [name for name in ("create", "set", "update", "delete", "_executor") if not hasattr(writer, name)]
404
+ if missing:
405
+ raise TypeError(f"This google-cloud-firestore BulkWriter has no {', '.join(missing)}; firestore_store can't guard it.")
406
+ guarded = _bulk_writer_classes.get((base, id(self)))
407
+ if guarded is None:
408
+ guarded = _bulk_writer_classes[(base, id(self))] = _guarded_bulk_writer_class(base, self)
409
+ previous = writer._executor
410
+ writer.__class__ = guarded
411
+ writer._executor = _ContextExecutor()
412
+ previous.shutdown(wait=False)
413
+ return writer
414
+
415
+ # ------------------------------------------------------------------ hooking
416
+ def guard_client(self, client: Any) -> None:
417
+ """Guard a Firestore client in place. Hooking a client twice is refused.
418
+
419
+ The hook overrides private methods of the client, so a version outside the verified range
420
+ (:data:`~sendproof_core.stores.versions.SUPPORTED`) or a client whose layout differs is refused here.
421
+ """
422
+ from google.cloud.firestore_v1.async_client import AsyncClient
423
+ from google.cloud.firestore_v1.client import Client
424
+
425
+ if getattr(type(client), _HOOKED, None) is not None:
426
+ raise TypeError("This Firestore client is already hooked by firestore_store.")
427
+ if isinstance(client, AsyncClient):
428
+ asynchronous = True
429
+ elif isinstance(client, Client):
430
+ asynchronous = False
431
+ else:
432
+ raise TypeError("firestore_store takes a google-cloud-firestore Client or AsyncClient.")
433
+ require_supported("google-cloud-firestore", "firestore_store")
434
+ _check_layout(type(client), asynchronous)
435
+ client.__class__ = self._guarded_client_class(type(client), asynchronous)
436
+ previous = getattr(client, "_firestore_api_internal", None)
437
+ if previous is not None: # already used: rebuild it over a guarded channel at the next call
438
+ client._firestore_api_internal = None
439
+ if not asynchronous:
440
+ try:
441
+ previous.transport.close()
442
+ except Exception:
443
+ pass
444
+
445
+
446
+ def firestore_store(client: Any, *, name: Optional[str] = None, treat_as_read: Optional[Iterable[str]] = None) -> FirestoreStore:
447
+ """Hook a ``google-cloud-firestore`` 2 ``Client`` or ``AsyncClient`` in place and return the store for ``data_stores``.
448
+
449
+ Hooking the same client twice is refused. Hook the client before you hand it to code that
450
+ keeps a reference to ``client._firestore_api``.
451
+
452
+ Args:
453
+ name: A display label for discovery, such as ``profiles``. Never a project id or host name.
454
+ treat_as_read: RPC method names you state never write, such as ``ExecutePipeline``: exact
455
+ names, no wildcards. **The guard trusts this list**: a listed method that does write is not blocked.
456
+ """
457
+ store = FirestoreStore(store_label(name), read_set(treat_as_read))
458
+ store.guard_client(client)
459
+ return store
@@ -0,0 +1,205 @@
1
+ """The write guard of ``spec/data-stores.md``: the single decision point every store hook calls
2
+ before it sends a command, plus the helpers hooks share for logging and redaction.
3
+
4
+ Outside a Preview the guard does nothing, so Send and observed Send are never blocked. In a
5
+ Preview it records the first refused write on the request's :class:`~sendproof_core.capture.Capture`
6
+ and raises :class:`PreviewWriteBlocked`. **The capture's mark, not the handler's response, decides
7
+ the outcome**: a handler that catches the error and returns 200 still produces a 409.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from typing import Any, Callable, Iterable, Mapping, Optional
14
+
15
+ from ..scope import RequestScope, attributed, current_scope, open_previews
16
+ from .classify import WRITE
17
+
18
+ #: Display names used in ``Preview unavailable: this operation writes to <Store>``.
19
+ STORE_NAMES = {
20
+ "mongodb": "MongoDB", "redis": "Redis", "dynamodb": "DynamoDB",
21
+ "cassandra": "Cassandra", "elasticsearch": "Elasticsearch", "opensearch": "OpenSearch",
22
+ "cosmosdb": "Cosmos DB", "firestore": "Firestore",
23
+ }
24
+
25
+
26
+ def store_name(store: str) -> str:
27
+ """The display name of a store id; unknown ids are shown as given."""
28
+ return STORE_NAMES.get(store, store)
29
+
30
+
31
+ def write_reason(store: str) -> str:
32
+ """The reason shown for a write to a guarded store."""
33
+ return f"Preview unavailable: this operation writes to {store_name(store)}"
34
+
35
+
36
+ class PreviewWriteBlocked(Exception):
37
+ """Raised to the handler when the guard refuses a write. No byte of the command reached the store."""
38
+
39
+ def __init__(self, store: str, operation: str, detail: str) -> None:
40
+ super().__init__(detail)
41
+ #: Store id, such as ``redis``.
42
+ self.store = store
43
+ #: The refused command or action name.
44
+ self.operation = operation
45
+ self.detail = detail
46
+
47
+
48
+ class PreviewTransactionControl(Exception):
49
+ """Raised when a handler tries to end or escape the Preview transaction.
50
+
51
+ A raw SQL ``COMMIT``, a MongoDB ``commitTransaction`` or a command sent with a session other
52
+ than the Preview's. The Preview answers 500 without confirmation even if the handler catches it.
53
+ """
54
+
55
+
56
+ def current_preview() -> Optional[RequestScope]:
57
+ """The scope of the Preview this code runs inside, even after the Preview finished.
58
+
59
+ Store hooks use it so a write that a handler sends after its response settled is still
60
+ refused, never sent unguarded. Returns ``None`` outside a Preview, including observed sends.
61
+ """
62
+ scope = current_scope()
63
+ return scope if scope is not None and scope.rollback else None
64
+
65
+
66
+ def guard(store: str, operation: str, kind: str, detail: Optional[str] = None) -> None:
67
+ """Call before sending a store command. Does nothing outside a Preview or for anything but a write.
68
+
69
+ In a Preview it marks the capture blocked (the first block wins), logs a blocked ``Db`` entry
70
+ and raises :class:`PreviewWriteBlocked`. ``detail`` replaces the default "writes to <Store>"
71
+ reason, for example for a MongoDB command that cannot run inside a transaction.
72
+ """
73
+ if kind != WRITE:
74
+ return
75
+ scope = current_preview()
76
+ if scope is None:
77
+ return
78
+ reason = detail or write_reason(store)
79
+ scope.capture.block(store, operation, reason)
80
+ scope.capture.record_db(store, operation, blocked=True)
81
+ raise PreviewWriteBlocked(store, operation, reason)
82
+
83
+
84
+ def refuse_unattributed(store: str, operation: str,
85
+ must_fail: Optional[Callable[[RequestScope], bool]] = None) -> None:
86
+ """Refuse, before it is sent, a write that no request and no :func:`~sendproof_core.detached` block accounts for.
87
+
88
+ Call it before sending a write seen with no current scope (``spec/data-stores.md``, "Writes the
89
+ binding can't attribute to a request"). While any Preview is open, such a write may come from a
90
+ Preview handler's own thread, a client's background writer or a task started without the
91
+ request's context, and a guarded store can't roll it back. So every open Preview is blocked
92
+ (or, when ``must_fail(scope)`` says the store joins that Preview's transaction, fails with 500)
93
+ and :class:`PreviewWriteBlocked` is raised: no byte of the write is sent. With no Preview open,
94
+ or inside an ordinary request or a ``detached()`` block, it does nothing.
95
+ """
96
+ if attributed():
97
+ return
98
+ previews = open_previews()
99
+ if not previews:
100
+ return
101
+ reason = (f"{write_reason(store)}, from code that no request accounts for while this Preview was open. "
102
+ "Wrap background work in sendproof_core.detached().")
103
+ for scope in previews:
104
+ if must_fail is not None and must_fail(scope):
105
+ scope.capture.refuse(PreviewTransactionControl(reason))
106
+ else:
107
+ scope.capture.block(store, operation, reason)
108
+ scope.capture.record_db(store, operation, blocked=True)
109
+ raise PreviewWriteBlocked(store, operation, reason)
110
+
111
+
112
+ def unattributed_write(store: str, operation: str) -> None:
113
+ """A write that no request accounts for, seen only **after** it was sent (a monitoring tripwire).
114
+
115
+ Hooks that see a write before sending it call :func:`refuse_unattributed` instead. This one is
116
+ for the cases that can't refuse, such as MongoDB command monitoring seeing a raw client's
117
+ write: it was neither blocked nor rolled back, so every open Preview fails with 500 rather than
118
+ claim a rollback. With no Preview open, or inside an ordinary request or a ``detached()`` block,
119
+ it does nothing.
120
+ """
121
+ if attributed():
122
+ return
123
+ previews = open_previews()
124
+ if not previews:
125
+ return
126
+ for scope in previews:
127
+ scope.capture.refuse(PreviewTransactionControl(
128
+ f"A {store_name(store)} {operation} ran outside any request while this Preview was open, so it may "
129
+ "have come from the Preview's own thread; the Preview can't be confirmed. Wrap background work "
130
+ "in sendproof_core.detached()."))
131
+
132
+
133
+ def check_command(store: str, operation: str, kind: str) -> Optional[RequestScope]:
134
+ """The one call a guard-only hook makes before it sends a command.
135
+
136
+ Refuses a write in a Preview (:func:`guard`), refuses a write with no request attribution while
137
+ any Preview is open (:func:`refuse_unattributed`), and returns the scope the command's ``Db``
138
+ entry belongs to (``None`` outside any request).
139
+ """
140
+ guard(store, operation, kind)
141
+ scope = current_scope()
142
+ if kind == WRITE and scope is None:
143
+ refuse_unattributed(store, operation)
144
+ return scope
145
+
146
+
147
+ def refuse_in_preview(message: str) -> Optional[PreviewTransactionControl]:
148
+ """Refuse something that would end or escape the Preview transaction.
149
+
150
+ Records the fault on the current Preview, so the Preview fails with 500 even if the handler
151
+ catches the error, and returns the error for the caller to raise. Outside a Preview it
152
+ returns ``None``.
153
+ """
154
+ scope = current_preview()
155
+ if scope is None:
156
+ return None
157
+ error = PreviewTransactionControl(message)
158
+ scope.capture.refuse(error)
159
+ return error
160
+
161
+
162
+ def sanitize_document(value: Any) -> Any:
163
+ """Replace every literal in a command document with ``"?"``, keeping field names and operators.
164
+
165
+ Used for the ``statement`` of a MongoDB ``Db`` entry (OpenTelemetry ``db.query.text``). BSON
166
+ values, dates and bytes are literals too.
167
+ """
168
+ if isinstance(value, (list, tuple)):
169
+ return [sanitize_document(item) for item in value]
170
+ if isinstance(value, Mapping):
171
+ return {str(name): sanitize_document(inner) for name, inner in value.items()}
172
+ return "?"
173
+
174
+
175
+ _BAD_LABEL = re.compile(r"[\x00-\x1f\x7f/\\@=;:?#%]")
176
+
177
+
178
+ def store_label(name: Optional[str]) -> Optional[str]:
179
+ """Validate the optional label a host gives a store for capabilities ``dataStores``.
180
+
181
+ Discovery is shown to anyone who can open the workbench, so the label must be a display name
182
+ such as ``catalog``: never a connection string, URL, host:port, user or password.
183
+ """
184
+ if name is None:
185
+ return None
186
+ if not isinstance(name, str) or not name.strip() or len(name) > 64 or _BAD_LABEL.search(name):
187
+ raise ValueError('A data store name must be a display label such as "catalog", not a connection string, URL or host.')
188
+ return name
189
+
190
+
191
+ def read_set(names: Optional[Iterable[str]], transform=lambda name: name, allow_spaces: bool = False) -> Optional[frozenset[str]]:
192
+ """Normalize host-declared reads (``treat_as_read``) into an exact-match set, after ``transform``.
193
+
194
+ ``allow_spaces`` admits names that hold single spaces, such as the CQL key ``LIST ROLES`` or the
195
+ Elasticsearch operation ``POST /{}/_refresh``. Wildcards are never allowed.
196
+ """
197
+ if names is None:
198
+ return None
199
+ if isinstance(names, str):
200
+ raise TypeError("treat_as_read takes a list of exact command names.")
201
+ items = list(names)
202
+ pattern = r"[*?]|\s{2,}|^\s|\s$|[^\S ]" if allow_spaces else r"[*?\s]"
203
+ if any(not isinstance(item, str) or not item or re.search(pattern, item) for item in items):
204
+ raise ValueError("treat_as_read takes exact command names, without wildcards.")
205
+ return frozenset(transform(item) for item in items)