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,153 @@
1
+ """Write classification for the batch-one data stores, driven by the shared tables.
2
+
3
+ Each table of ``spec/data-stores/`` (embedded in :mod:`.tables`) lists reads and connection-level
4
+ commands. **Everything else, including a command the table has never heard of, is a write**, so
5
+ the guard fails closed when a store adds a command.
6
+
7
+ Every function here is pure. The shared vectors in
8
+ ``spec/data-stores/classification-cases.json`` run through them in ``core/tests/test_stores.py``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any, Iterable, Mapping, Optional
14
+
15
+ from .tables import DYNAMODB_TABLE, MONGODB_TABLE, REDIS_TABLE
16
+
17
+ #: How the guard treats one store command. Only ``"write"`` can block a Preview.
18
+ READ, WRITE, SESSION, TRANSACTION = "read", "write", "session", "transaction"
19
+
20
+ _REDIS_READ = frozenset(REDIS_TABLE["read"]) | frozenset(REDIS_TABLE["moduleRead"])
21
+ _REDIS_SESSION = frozenset(REDIS_TABLE["session"])
22
+ _REDIS_TRANSACTION = frozenset(REDIS_TABLE["transaction"])
23
+
24
+ _MONGO_READ = frozenset(name.lower() for name in MONGODB_TABLE["read"])
25
+ _MONGO_SESSION = frozenset(name.lower() for name in MONGODB_TABLE["session"])
26
+ _MONGO_NOT_IN_TRANSACTION = frozenset(name.lower() for name in MONGODB_TABLE["notInTransaction"]["commands"])
27
+ _MONGO_STAGES: tuple[str, ...] = tuple(MONGODB_TABLE["notInTransaction"]["stages"])
28
+ _WRITING_STAGES = frozenset({"$out", "$merge"})
29
+
30
+ _DYNAMO_READ = frozenset(DYNAMODB_TABLE["read"])
31
+ _DYNAMO_PARTIQL = frozenset(DYNAMODB_TABLE["partiql"]["operations"])
32
+
33
+
34
+ def _text(value: Any) -> str:
35
+ """An argument as text: bytes are decoded, everything else is stringified."""
36
+ if isinstance(value, (bytes, bytearray, memoryview)):
37
+ return bytes(value).decode("utf-8", errors="replace")
38
+ return str(value)
39
+
40
+
41
+ def classify_redis(name: Any, args: Iterable[Any] = (), treat_as_read: Optional[frozenset[str]] = None) -> str:
42
+ """Classify a Redis command as ``read``, ``write``, ``session`` or ``transaction``.
43
+
44
+ ``name`` is the command name in any case and ``args`` its arguments, of which only the first
45
+ is read, to form ``CONTAINER|SUBCOMMAND`` keys such as ``OBJECT|ENCODING``. ``treat_as_read``
46
+ holds host-declared reads, compared exactly against the upper-case key.
47
+
48
+ redis-py accepts a container command either as two arguments (``"OBJECT", "ENCODING"``) or as
49
+ one space-separated name (``"CONFIG GET"``); both forms classify the same.
50
+ """
51
+ command = _text(name).strip().upper()
52
+ arguments = list(args)
53
+ if " " in command: # "CONFIG GET" -> CONFIG with GET as its first argument
54
+ command, _, rest = command.partition(" ")
55
+ arguments.insert(0, rest.strip())
56
+ with_sub = f"{command}|{_text(arguments[0]).upper()}" if arguments else command
57
+ for key in (with_sub, command):
58
+ if key in _REDIS_SESSION:
59
+ return SESSION
60
+ if key in _REDIS_TRANSACTION:
61
+ return TRANSACTION
62
+ if key in _REDIS_READ or (treat_as_read is not None and key in treat_as_read):
63
+ return READ
64
+ return WRITE
65
+
66
+
67
+ def _is_plain(value: Any) -> bool:
68
+ """A plain mapping literal, as opposed to BSON values and class instances."""
69
+ return isinstance(value, Mapping)
70
+
71
+
72
+ def pipeline_uses(value: Any, stages: frozenset[str]) -> bool:
73
+ """Whether any key of an aggregation pipeline, at any depth (sub-pipelines included), is in ``stages``."""
74
+ if isinstance(value, (list, tuple)):
75
+ return any(pipeline_uses(item, stages) for item in value)
76
+ if _is_plain(value):
77
+ return any(key in stages or pipeline_uses(inner, stages) for key, inner in value.items())
78
+ return False
79
+
80
+
81
+ def classify_mongo(command: Mapping[str, Any], treat_as_read: Optional[frozenset[str]] = None) -> tuple[str, Optional[str]]:
82
+ """Classify a MongoDB command document by its first key, case-insensitively.
83
+
84
+ Returns ``(kind, refused_in_transaction)``. ``aggregate`` is a write when any stage at any
85
+ depth is ``$out`` or ``$merge``; ``explain`` takes the classification of the command inside
86
+ it. ``refused_in_transaction`` names the command or stage MongoDB refuses inside a
87
+ transaction (``$out``, ``count``...), which a ``preview``-mode Preview must block before
88
+ sending. ``treat_as_read`` holds host-declared reads in lower case.
89
+ """
90
+ name = next(iter(command), "")
91
+ lower = str(name).lower()
92
+ if lower == "explain" and _is_plain(command[name]):
93
+ return classify_mongo(command[name], treat_as_read)
94
+ refused: Optional[str] = None
95
+ if lower in _MONGO_NOT_IN_TRANSACTION:
96
+ refused = str(name)
97
+ if lower == "aggregate":
98
+ pipeline = command.get("pipeline")
99
+ refused = next((stage for stage in _MONGO_STAGES if pipeline_uses(pipeline, frozenset({stage}))), refused)
100
+ if lower in _MONGO_SESSION:
101
+ return SESSION, None
102
+ if lower == "aggregate" and pipeline_uses(command.get("pipeline"), _WRITING_STAGES):
103
+ return WRITE, refused
104
+ if lower in _MONGO_READ or (treat_as_read is not None and lower in treat_as_read):
105
+ return READ, refused
106
+ return WRITE, refused
107
+
108
+
109
+ def partiql_verb(statement: Any) -> str:
110
+ """Skip whitespace and SQL-style comments, then return the first word of a PartiQL statement in upper case."""
111
+ text = "" if statement is None else str(statement)
112
+ while True:
113
+ trimmed = text.lstrip()
114
+ if trimmed.startswith("--"):
115
+ end = trimmed.find("\n")
116
+ text = "" if end < 0 else trimmed[end + 1:]
117
+ continue
118
+ if trimmed.startswith("/*"):
119
+ end = trimmed.find("*/")
120
+ if end < 0:
121
+ return ""
122
+ text = trimmed[end + 2:]
123
+ continue
124
+ word = []
125
+ for char in trimmed:
126
+ if char.isascii() and char.isalpha():
127
+ word.append(char)
128
+ else:
129
+ break
130
+ return "".join(word).upper()
131
+
132
+
133
+ def classify_dynamo(operation: str, params: Optional[Mapping[str, Any]] = None,
134
+ treat_as_read: Optional[frozenset[str]] = None) -> str:
135
+ """Classify a DynamoDB action and its input as ``read`` or ``write``.
136
+
137
+ A PartiQL request is a read only when every statement in it is a ``SELECT``. ``treat_as_read``
138
+ holds host-declared action names.
139
+ """
140
+ params = params or {}
141
+ if operation in _DYNAMO_READ or (treat_as_read is not None and operation in treat_as_read):
142
+ return READ
143
+ if operation in _DYNAMO_PARTIQL:
144
+ if operation == "ExecuteStatement":
145
+ statements = [params.get("Statement")]
146
+ else:
147
+ listed = params.get("Statements") or params.get("TransactStatements")
148
+ statements = [item.get("Statement") if isinstance(item, Mapping) else None for item in listed] \
149
+ if isinstance(listed, (list, tuple)) else []
150
+ if statements and all(partiql_verb(statement) == "SELECT" for statement in statements):
151
+ return READ
152
+ return WRITE
153
+ return WRITE
@@ -0,0 +1,397 @@
1
+ """Write classification for the batch-two stores: Cassandra, Elasticsearch and OpenSearch, Cosmos DB and Firestore.
2
+
3
+ Like :mod:`.classify`, every function is pure and driven by the shared tables of
4
+ ``spec/data-stores/`` (embedded in :mod:`.tables`). **Everything the table does not list as a read
5
+ is a write**, so the guard fails closed when a store adds a statement, endpoint or RPC. The shared
6
+ vectors in ``spec/data-stores/classification-cases.json`` run through these functions in
7
+ ``core/tests/test_batch_two.py``.
8
+
9
+ Each classifier returns a :class:`Verdict`: the kind (``read``, ``write`` or ``session``) and the
10
+ ``db.operation.name`` the ``Db`` entry and the 409 body use.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import re
17
+ from typing import Any, Mapping, NamedTuple, Optional
18
+ from urllib.parse import unquote
19
+
20
+ from .classify import READ, SESSION, WRITE
21
+ from .tables import CASSANDRA_TABLE, COSMOSDB_TABLE, ELASTICSEARCH_TABLE, FIRESTORE_TABLE
22
+
23
+
24
+ class Verdict(NamedTuple):
25
+ """How the guard treats one command, and the operation name it is logged and refused under."""
26
+
27
+ kind: str
28
+ operation: str
29
+
30
+
31
+ # ---------------------------------------------------------------------------------------- statements
32
+ class _Shape(NamedTuple):
33
+ first: str
34
+ second: str
35
+ multiple: bool
36
+ broken: bool
37
+
38
+
39
+ def statement_shape(text: Any, *, dollar: bool = False, slash_comments: bool = False, backticks: bool = False) -> _Shape:
40
+ """Read the shape of one statement the way the server would.
41
+
42
+ Returns its first two words (upper case, after whitespace and comments), whether anything but
43
+ whitespace and comments follows a semicolon outside quotes (``multiple``), and ``broken`` for
44
+ an unterminated quote or comment. Quotes are ``'...'`` and ``"..."`` with doubled-quote
45
+ escapes; ``backticks`` adds ``...``, ``dollar`` adds CQL's ``$$...$$`` strings and
46
+ ``slash_comments`` adds ``//`` line comments.
47
+ """
48
+ source = "" if text is None else (bytes(text).decode("utf-8", "replace") if isinstance(text, (bytes, bytearray)) else str(text))
49
+ length = len(source)
50
+ index = 0
51
+
52
+ class Unterminated(Exception):
53
+ pass
54
+
55
+ def comment() -> bool:
56
+ nonlocal index
57
+ if source.startswith("--", index) or (slash_comments and source.startswith("//", index)):
58
+ end = source.find("\n", index)
59
+ index = length if end < 0 else end + 1
60
+ return True
61
+ if source.startswith("/*", index):
62
+ end = source.find("*/", index + 2)
63
+ if end < 0:
64
+ raise Unterminated
65
+ index = end + 2
66
+ return True
67
+ return False
68
+
69
+ def skip() -> None:
70
+ nonlocal index
71
+ while True:
72
+ while index < length and source[index].isspace():
73
+ index += 1
74
+ if not comment():
75
+ return
76
+
77
+ def word() -> str:
78
+ nonlocal index
79
+ skip()
80
+ match = re.match(r"[A-Za-z_]+", source[index:])
81
+ if not match:
82
+ return ""
83
+ index += match.end()
84
+ return match.group(0).upper()
85
+
86
+ try:
87
+ first = word()
88
+ second = word()
89
+ multiple = False
90
+ while index < length:
91
+ if comment():
92
+ continue
93
+ char = source[index]
94
+ quote = char if char in "'\"" or (backticks and char == "`") else ("$$" if dollar and source.startswith("$$", index) else None)
95
+ if quote:
96
+ end = index + len(quote)
97
+ while True:
98
+ end = source.find(quote, end)
99
+ if end < 0:
100
+ raise Unterminated
101
+ if quote != "$$" and source[end + 1:end + 2] == quote:
102
+ end += 2
103
+ continue
104
+ break
105
+ index = end + len(quote)
106
+ continue
107
+ index += 1
108
+ if char == ";":
109
+ skip()
110
+ if index < length:
111
+ multiple = True
112
+ break
113
+ return _Shape(first, second, multiple, False)
114
+ except Unterminated:
115
+ return _Shape("", "", False, True)
116
+
117
+
118
+ # ------------------------------------------------------------------------------------------ Cassandra
119
+ _CASSANDRA_READ = frozenset(CASSANDRA_TABLE["read"])
120
+ _CASSANDRA_SESSION = frozenset(CASSANDRA_TABLE["protocol"]["session"])
121
+
122
+
123
+ def classify_cassandra(statement: Any, treat_as_read: Optional[frozenset[str]] = None) -> Verdict:
124
+ """Classify one CQL statement: ``read`` only for a single statement whose key the table lists.
125
+
126
+ The key is the first keyword, or ``LIST <word>``. Text the hook can't read (an unterminated
127
+ quote or comment, nothing at all) and a second statement after a semicolon are writes.
128
+ ``treat_as_read`` holds host-declared reads, compared exactly against the upper-case key.
129
+ """
130
+ shape = statement_shape(statement, dollar=True, slash_comments=True)
131
+ key = f"LIST {shape.second}" if shape.first == "LIST" else shape.first
132
+ operation = "BATCH" if shape.first == "BEGIN" else (key if shape.first == "LIST" else (shape.first or "UNKNOWN"))
133
+ listed = key in _CASSANDRA_READ or (treat_as_read is not None and key in treat_as_read)
134
+ return Verdict(READ if listed and not shape.broken and not shape.multiple else WRITE, operation)
135
+
136
+
137
+ def classify_cassandra_message(message: str, statement: Any = None, prepared: Any = None,
138
+ treat_as_read: Optional[frozenset[str]] = None) -> Verdict:
139
+ """Classify a native-protocol message: ``PREPARE`` and the connection messages are ``session``,
140
+ ``QUERY`` classifies its text, ``EXECUTE`` classifies the text that was prepared (an id the hook
141
+ never saw prepared is a write) and every ``BATCH`` is a write."""
142
+ if message in _CASSANDRA_SESSION:
143
+ return Verdict(SESSION, message)
144
+ if message == "QUERY":
145
+ return classify_cassandra(statement, treat_as_read)
146
+ if message == "EXECUTE":
147
+ return Verdict(WRITE, "EXECUTE") if prepared is None else classify_cassandra(prepared, treat_as_read)
148
+ return Verdict(WRITE, message)
149
+
150
+
151
+ _CQL_TOKEN = re.compile(
152
+ r"""
153
+ (?P<comment>--[^\n]*|//[^\n]*|/\*.*?(?:\*/|\Z))
154
+ | (?P<ident>"(?:[^"]|"")*")
155
+ | (?P<string>'(?:[^']|'')*'?|\$\$.*?(?:\$\$|\Z))
156
+ | (?P<uuid>\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b)
157
+ | (?P<number>(?<![\w.])(?:0[xX][0-9a-fA-F]+|[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)(?![\w]))
158
+ """,
159
+ re.VERBOSE | re.DOTALL,
160
+ )
161
+
162
+
163
+ def sanitize_cql(text: str) -> str:
164
+ """Replace every literal in CQL text with ``?`` and drop comments.
165
+
166
+ Quoted strings, ``$$`` strings, numbers, hex blobs and UUIDs are replaced; double-quoted
167
+ identifiers are kept as written. A statement may inline values instead of binding them, and a
168
+ value never appears in a ``Db`` entry.
169
+ """
170
+ def replace(match: "re.Match[str]") -> str:
171
+ kind = match.lastgroup
172
+ return " " if kind == "comment" else (match.group(0) if kind == "ident" else "?")
173
+ return _CQL_TOKEN.sub(replace, text)
174
+
175
+
176
+ _CQL_TARGET = re.compile(
177
+ r"""^\s*(?:SELECT\b.*?\bFROM|DELETE\b.*?\bFROM|INSERT\s+INTO|UPDATE|TRUNCATE(?:\s+TABLE)?)\s+
178
+ (?P<name>(?:"(?:[^"]|"")+"|\w+)(?:\.(?:"(?:[^"]|"")+"|\w+))?)""",
179
+ re.IGNORECASE | re.VERBOSE | re.DOTALL,
180
+ )
181
+
182
+
183
+ def cql_target(statement: str) -> tuple[Optional[str], Optional[str]]:
184
+ """The ``(keyspace, table)`` a sanitized statement names; either is ``None`` when it doesn't."""
185
+ found = _CQL_TARGET.match(statement)
186
+ if not found:
187
+ return None, None
188
+ parts = re.findall(r'"(?:[^"]|"")+"|\w+', found.group("name"))
189
+ unquote_name = lambda part: part[1:-1].replace('""', '"') if part.startswith('"') else part # noqa: E731
190
+ if len(parts) == 2:
191
+ return unquote_name(parts[0]), unquote_name(parts[1])
192
+ return None, unquote_name(parts[0])
193
+
194
+
195
+ # ------------------------------------------------------------------------- Elasticsearch / OpenSearch
196
+ _ES_ENDPOINTS = tuple(
197
+ (entry["kind"], entry["name"], frozenset(entry["methods"]), tuple(tuple(path.split("/")[1:]) for path in entry["paths"]))
198
+ for entry in ELASTICSEARCH_TABLE["endpoints"]
199
+ )
200
+ _ES_METHOD_DEFAULT = ELASTICSEARCH_TABLE["methodDefault"]
201
+ _ES_SQL_WORDS = frozenset(ELASTICSEARCH_TABLE["sql"]["readWords"])
202
+
203
+
204
+ def path_segments(path: Any) -> list[str]:
205
+ """Split a request path into percent-decoded segments, without its query string and with repeated
206
+ and trailing slashes dropped, as the server does."""
207
+ text = path.decode("utf-8", "replace") if isinstance(path, (bytes, bytearray)) else str(path)
208
+ return [unquote(segment) for segment in text.split("?", 1)[0].split("/") if segment]
209
+
210
+
211
+ def _es_segment(pattern: str, segment: str) -> bool:
212
+ if pattern == "{index}":
213
+ return bool(segment) and not segment.startswith("_")
214
+ return bool(segment) if pattern == "{id}" else pattern == segment
215
+
216
+
217
+ def _sql_request_reads(body: Any) -> bool:
218
+ """Whether a SQL endpoint's body is one ``SELECT``, ``SHOW`` or ``DESCRIBE`` statement or a cursor page."""
219
+ parsed = body
220
+ if isinstance(body, (bytes, bytearray)):
221
+ body = bytes(body).decode("utf-8", "replace")
222
+ if isinstance(body, str):
223
+ try:
224
+ parsed = json.loads(body)
225
+ except ValueError:
226
+ return False
227
+ if not isinstance(parsed, Mapping):
228
+ return False
229
+ query = parsed.get("query")
230
+ if isinstance(query, str):
231
+ shape = statement_shape(query, backticks=True)
232
+ return not shape.broken and not shape.multiple and shape.first in _ES_SQL_WORDS
233
+ return query is None and isinstance(parsed.get("cursor"), str)
234
+
235
+
236
+ def classify_elasticsearch(method: Any, path: Any, body: Any = None,
237
+ treat_as_read: Optional[frozenset[str]] = None) -> Verdict:
238
+ """Classify an Elasticsearch or OpenSearch request by HTTP method and path (and, for the SQL
239
+ endpoints, the body). The first table entry that matches decides; the operation is its name.
240
+
241
+ Without an entry, ``GET`` and ``HEAD`` read and anything else is a write, and the operation is
242
+ the method and the path with every segment that doesn't start with an underscore replaced by
243
+ ``{}`` (``PUT /{}``). ``treat_as_read`` holds host-declared operation names.
244
+ """
245
+ verb = (method.decode() if isinstance(method, (bytes, bytearray)) else str(method)).upper()
246
+ segments = path_segments(path)
247
+ for kind, name, methods, patterns in _ES_ENDPOINTS:
248
+ if verb not in methods:
249
+ continue
250
+ if any(len(pattern) == len(segments) and all(_es_segment(p, s) for p, s in zip(pattern, segments)) for pattern in patterns):
251
+ if kind == "sql":
252
+ kind = READ if _sql_request_reads(body) else WRITE
253
+ return Verdict(kind, name)
254
+ operation = f"{verb} /" + "/".join(s if s.startswith("_") else "{}" for s in segments)
255
+ if treat_as_read is not None and operation in treat_as_read:
256
+ return Verdict(READ, operation)
257
+ return Verdict(_ES_METHOD_DEFAULT.get(verb, ELASTICSEARCH_TABLE["default"]), operation)
258
+
259
+
260
+ def elasticsearch_target(path: Any) -> Optional[str]:
261
+ """The index a request names (its first segment, when that isn't an endpoint), for ``db.collection.name``."""
262
+ segments = path_segments(path)
263
+ return segments[0] if segments and not segments[0].startswith("_") else None
264
+
265
+
266
+ # ---------------------------------------------------------------------------------------------- Cosmos DB
267
+ _COSMOS_CANONICAL = {name.lower(): name for name in [*COSMOSDB_TABLE["read"], *COSMOSDB_TABLE["write"]]}
268
+ _COSMOS_READ = frozenset(COSMOSDB_TABLE["read"])
269
+ _COSMOS_TRIGGER_HEADERS = frozenset({"x-ms-documentdb-pre-trigger-include", "x-ms-documentdb-post-trigger-include"})
270
+
271
+
272
+ def _header(headers: Mapping[str, Any], name: str) -> Optional[str]:
273
+ for key, value in headers.items():
274
+ if str(key).lower() == name:
275
+ return None if value is None else str(value)
276
+ return None
277
+
278
+
279
+ def _truthy(value: Optional[str]) -> bool:
280
+ return str(value or "").lower() == "true"
281
+
282
+
283
+ def cosmos_operation(method: Any, path: Any, headers: Optional[Mapping[str, Any]] = None) -> str:
284
+ """Derive a Cosmos DB operation type from an HTTP request, as ``fromRequest`` in the table describes."""
285
+ headers = headers or {}
286
+ segments = path_segments(path)
287
+ one = len(segments) > 0 and len(segments) % 2 == 0
288
+ verb = str(method).upper()
289
+ if verb == "GET":
290
+ return "Read" if one else "ReadFeed"
291
+ if verb == "HEAD":
292
+ return "Head" if one else "HeadFeed"
293
+ if verb == "POST":
294
+ if _truthy(_header(headers, "x-ms-cosmos-is-query-plan-request")):
295
+ return "QueryPlan"
296
+ if _truthy(_header(headers, "x-ms-documentdb-isquery")) or re.match(
297
+ r"application/query\+json\b", _header(headers, "content-type") or "", re.IGNORECASE
298
+ ):
299
+ return "Query"
300
+ if _truthy(_header(headers, "x-ms-cosmos-is-batch-request")):
301
+ return "Batch"
302
+ if one and segments[-2] == "sprocs":
303
+ return "ExecuteJavaScript"
304
+ return "Upsert" if _truthy(_header(headers, "x-ms-documentdb-is-upsert")) else "Create"
305
+ return {"PUT": "Replace", "PATCH": "Patch", "DELETE": "Delete"}.get(verb, verb)
306
+
307
+
308
+ def classify_cosmos(operation_type: Optional[str] = None, triggers: bool = False,
309
+ request: Optional[Mapping[str, Any]] = None,
310
+ treat_as_read: Optional[frozenset[str]] = None) -> Verdict:
311
+ """Classify a Cosmos DB operation.
312
+
313
+ Pass ``operation_type`` (an SDK-level hook) or ``request`` (``{method, path, headers}``, a hook
314
+ on the HTTP pipeline). ``triggers=True``, or a trigger header on the request, makes any
315
+ operation a write. Operation types compare case-insensitively.
316
+ """
317
+ if operation_type is None:
318
+ request = request or {}
319
+ operation_type = cosmos_operation(request.get("method", ""), request.get("path", ""), request.get("headers"))
320
+ operation = _COSMOS_CANONICAL.get(str(operation_type).lower(), str(operation_type))
321
+ headers = (request or {}).get("headers") or {}
322
+ triggered = triggers or any(str(name).lower() in _COSMOS_TRIGGER_HEADERS for name in headers)
323
+ listed = operation in _COSMOS_READ or (treat_as_read is not None and operation in treat_as_read)
324
+ return Verdict(READ if listed and not triggered else WRITE, operation)
325
+
326
+
327
+ # ----------------------------------------------------------------------------------------------- Firestore
328
+ _FIRESTORE_SERVICES = FIRESTORE_TABLE["services"]
329
+ _FIRESTORE_VERBS = FIRESTORE_TABLE["fromRest"]["verbs"]
330
+
331
+
332
+ def firestore_rpc(method: Any, path: Any) -> str:
333
+ """Derive a Firestore RPC name from a REST request, as ``fromRest`` in the table describes."""
334
+ segments = path_segments(path)
335
+ last = segments[-1] if segments else ""
336
+ colon = last.rfind(":")
337
+ if colon >= 0:
338
+ verb = last[colon + 1:]
339
+ return _FIRESTORE_VERBS.get(verb, verb)
340
+ after = len(segments) - (segments.index("documents") + 1) if "documents" in segments else 0
341
+ document = "documents" in segments and after > 0 and after % 2 == 0
342
+ verb = str(method).upper()
343
+ if verb == "GET":
344
+ return "GetDocument" if document else "ListDocuments"
345
+ if verb == "PATCH":
346
+ return "UpdateDocument"
347
+ if verb == "DELETE":
348
+ return "DeleteDocument"
349
+ if verb == "POST":
350
+ return "POST" if document else "CreateDocument"
351
+ return verb
352
+
353
+
354
+ def _writes(message: Any) -> Optional[int]:
355
+ """How many writes a ``Commit`` message carries, or ``None`` when the hook can't read the message."""
356
+ if message is None:
357
+ return None
358
+ if isinstance(message, Mapping):
359
+ listed = message.get("writes", [])
360
+ else:
361
+ try:
362
+ listed = getattr(message, "writes")
363
+ except AttributeError:
364
+ return None
365
+ try:
366
+ return len(listed) if listed is not None else 0
367
+ except TypeError:
368
+ return None
369
+
370
+
371
+ def classify_firestore(rpc: Any, message: Any = None, treat_as_read: Optional[frozenset[str]] = None) -> Verdict:
372
+ """Classify a Firestore RPC.
373
+
374
+ ``rpc`` is the gRPC path (``/google.firestore.v1.Firestore/Commit``) or a bare v1 method name;
375
+ ``message`` is the request (a mapping or a message object), when the hook can read it. A
376
+ ``Commit`` is a write when it carries a write or can't be read, and ``session`` when it holds
377
+ none. Methods of any other service or API version are writes, except admin methods that start
378
+ with ``Get`` or ``List``.
379
+ """
380
+ text = rpc.decode() if isinstance(rpc, (bytes, bytearray)) else str(rpc)
381
+ if "/" in text:
382
+ parts = [part for part in text.split("/") if part]
383
+ service, operation = (parts + ["", ""])[:2]
384
+ else:
385
+ service, operation = "google.firestore.v1.Firestore", text
386
+ known = _FIRESTORE_SERVICES.get(service)
387
+ if known is None:
388
+ return Verdict(WRITE, operation)
389
+ if "readPrefixes" in known:
390
+ return Verdict(READ if operation.startswith(tuple(known["readPrefixes"])) else WRITE, operation)
391
+ if operation == "Commit":
392
+ return Verdict(SESSION if _writes(message) == 0 else WRITE, operation)
393
+ if operation in known["read"] or (treat_as_read is not None and operation in treat_as_read):
394
+ return Verdict(READ, operation)
395
+ if operation in known["session"]:
396
+ return Verdict(SESSION, operation)
397
+ return Verdict(WRITE, operation)