classifyre-cli 0.9.2__py3-none-any.whl → 0.9.4__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.
- {classifyre_cli-0.9.2.dist-info → classifyre_cli-0.9.4.dist-info}/METADATA +1 -1
- {classifyre_cli-0.9.2.dist-info → classifyre_cli-0.9.4.dist-info}/RECORD +15 -15
- src/detectors/pii/detector.py +60 -25
- src/query/bindings.py +9 -0
- src/query/connectors/arrow.py +8 -0
- src/query/connectors/base.py +8 -0
- src/query/connectors/object_storage.py +8 -1
- src/query/connectors/odbc.py +4 -0
- src/query/masks.py +42 -2
- src/query/runner.py +5 -3
- src/query/session.py +249 -48
- src/query/warm.py +9 -0
- src/query/worker.py +348 -16
- {classifyre_cli-0.9.2.dist-info → classifyre_cli-0.9.4.dist-info}/WHEEL +0 -0
- {classifyre_cli-0.9.2.dist-info → classifyre_cli-0.9.4.dist-info}/entry_points.txt +0 -0
|
@@ -44,7 +44,7 @@ src/detectors/custom_detector/runner.py,sha256=NMK8sfQUOVwoSrbUF7fx2iBIYvPO_BngN
|
|
|
44
44
|
src/detectors/custom_detector/sdk.py,sha256=QepinCIP2l-sBrKY0wSRdVawReEOFbuoCQ5AkcR91c4,12729
|
|
45
45
|
src/detectors/custom_detector/session.py,sha256=AwJEZccpQObu2bNHpooBqDKGWzU7zh6nnyKpj06-SiQ,17578
|
|
46
46
|
src/detectors/pii/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
47
|
-
src/detectors/pii/detector.py,sha256=
|
|
47
|
+
src/detectors/pii/detector.py,sha256=kceyL-NK1-TTDTqTekeZVJfm2NLcVqPRGMoA6lY8NQU,47364
|
|
48
48
|
src/detectors/secrets/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
49
49
|
src/detectors/secrets/detector.py,sha256=i9bTcN19f-Hh29JoLsfKa7y2JsmLyCFo1eHJc7Ruq50,14616
|
|
50
50
|
src/detectors/threat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
@@ -93,27 +93,27 @@ src/pipeline/scan_cache.py,sha256=cje5Fcbf2vJDOd3DOoTT__gn28fxQp_HojZESnhr2_s,30
|
|
|
93
93
|
src/pipeline/text_artifact.py,sha256=7gpu1r6Ipc0nAt4S8bdzcy8KV9JKaTRgHPgrMw7J1I8,2433
|
|
94
94
|
src/pipeline/worker_pool.py,sha256=Yjr_2LXxV2nYNcXNN4gFRPK9KN15GP_IkkAzaplKaTc,10543
|
|
95
95
|
src/query/__init__.py,sha256=RhfyfKL7loabux082s5CMWFlBTq3rDl3q23LwpurAO0,989
|
|
96
|
-
src/query/bindings.py,sha256=
|
|
96
|
+
src/query/bindings.py,sha256=KMqATSAJHGD9y3HrWhbE1w8ixJgGV5dDsqHq2FgkL-A,6258
|
|
97
97
|
src/query/describe.py,sha256=oJBA2WruLYWXROHHlg2Y_P9T6KtWyATUiYbx2T8KoSw,3245
|
|
98
98
|
src/query/gate.py,sha256=cNvdANq3cvcc9AGE-wk2Ad_1HpsZKphUNBscCTga-eM,13040
|
|
99
|
-
src/query/masks.py,sha256=
|
|
99
|
+
src/query/masks.py,sha256=E-B1kt_99BIcaKpTEYGXYLGKnr3R5b-piLqaZci84Aw,10982
|
|
100
100
|
src/query/predicate.py,sha256=VH4U3UyfAL5aWKdcrSSgADy5T3s7WVWJowmNywo6EaE,1644
|
|
101
101
|
src/query/rows.py,sha256=JcUgThkVIKJsQIlhemT_xQ0aiQNItCQ-x8NsLx0KLhc,4588
|
|
102
|
-
src/query/runner.py,sha256=
|
|
103
|
-
src/query/session.py,sha256=
|
|
104
|
-
src/query/warm.py,sha256=
|
|
105
|
-
src/query/worker.py,sha256=
|
|
102
|
+
src/query/runner.py,sha256=EBwcaMHwSgBgdGNr9k_DMhEB2yc0qcDWGUm8C0AzPjw,7888
|
|
103
|
+
src/query/session.py,sha256=ELrjIZ3etEQUkLwl4gAqQJ5Rgz9dHABZ4kLGQ1fApYU,43538
|
|
104
|
+
src/query/warm.py,sha256=E1QQKm2FqJ5M8hOPeLBYn24bjetFeE8GPYaf8PoR1T8,7719
|
|
105
|
+
src/query/worker.py,sha256=nxW6sqkVFOiCtJh5Tbek8esoY07pxnWrhCwvC8D9e88,52962
|
|
106
106
|
src/query/connectors/__init__.py,sha256=e8rZ-xjwo4qewUMzdwAl5yifTY0sPpUGFaWyYeB48R4,4669
|
|
107
|
-
src/query/connectors/arrow.py,sha256=
|
|
107
|
+
src/query/connectors/arrow.py,sha256=HZtCVhIGa4GUibFOejUYkKGHvlurLoa3zZx5MFRTr8g,23012
|
|
108
108
|
src/query/connectors/attached_catalog.py,sha256=KrxLIAGvHsLFjEoGg4KI28wuealjHYDjld4a1UM2vYg,1516
|
|
109
|
-
src/query/connectors/base.py,sha256=
|
|
109
|
+
src/query/connectors/base.py,sha256=Y-5AyRl-gQm8B1CFHDgKf6Z-O9poJq6ICWRiEN-BnIw,7887
|
|
110
110
|
src/query/connectors/custom.py,sha256=BLAWAsjXjRMKN58nYhxABdSCCviAUid1hFSkx1xgKYM,4313
|
|
111
111
|
src/query/connectors/databricks.py,sha256=Cvlke_yM72iUO6RB8H-i6duRxiOiTpwbQJsFIJia90c,2757
|
|
112
112
|
src/query/connectors/meilisearch.py,sha256=_mpeFJ_Nn1eIaz6BHm6viOY1ioQahYNxNkV5eKIrPow,8909
|
|
113
113
|
src/query/connectors/mysql.py,sha256=7QyYY35yt_-oRsaWrhLz-7O7zCiSrZqyw-EW2veu1cw,5598
|
|
114
114
|
src/query/connectors/neo4j.py,sha256=leGRZ-uH4Ba2G3yp2mYx8Jouao7nmu5E3B9jUjO8MXk,8533
|
|
115
|
-
src/query/connectors/object_storage.py,sha256=
|
|
116
|
-
src/query/connectors/odbc.py,sha256=
|
|
115
|
+
src/query/connectors/object_storage.py,sha256=hN_-_q5XAQwnWgR2Ogdysj_PDghuqi1dcpTB1Wtf5kU,5354
|
|
116
|
+
src/query/connectors/odbc.py,sha256=23URmiz3pDTDrGO08zC7BAQa6ugztAE_JM7dK8iPLnQ,2936
|
|
117
117
|
src/query/connectors/postgres.py,sha256=pOvVxToZCTs2oE3KW1f0lvjo2Br0_NTl9Nj3VX7TYkQ,2916
|
|
118
118
|
src/sources/__init__.py,sha256=wYksO_0IcvlGXLouWapKyqzL0jG0El4rDDGRfwa4Zqk,3350
|
|
119
119
|
src/sources/asset_metadata.py,sha256=OnHwnUSlT1Ow_6Rz2SnJvZyJvaz00TsuQgAnXjTXsdA,6143
|
|
@@ -254,7 +254,7 @@ src/utils/urn.py,sha256=gqSl0H0FBZZ3cJbpDWX1ewGcyZz2MrNVTIQdoFrQMM0,12622
|
|
|
254
254
|
src/utils/uv_sync.py,sha256=L4ETHuidlgFLbz4e3Vv0Ornh7w8xrkYeFQQGw0hJe8E,10214
|
|
255
255
|
src/utils/validation.py,sha256=5NHsgyZwyEONRu9_ADxUAQNPvbMnpMhKL-hpgFEVMm8,3837
|
|
256
256
|
src/utils/video_processing.py,sha256=B6Br9ybFEa_ioglJGo0P9Fmp1e2B95C24joAktwrjww,11293
|
|
257
|
-
classifyre_cli-0.9.
|
|
258
|
-
classifyre_cli-0.9.
|
|
259
|
-
classifyre_cli-0.9.
|
|
260
|
-
classifyre_cli-0.9.
|
|
257
|
+
classifyre_cli-0.9.4.dist-info/METADATA,sha256=5Pgq6D2zNUjcESHhgr_waCGlp-NhYQukC68cItfpN1s,5841
|
|
258
|
+
classifyre_cli-0.9.4.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
259
|
+
classifyre_cli-0.9.4.dist-info/entry_points.txt,sha256=edxllyMiIFfajgCZ3dTRACXYGC34ZX1AYTezMSR5E_8,45
|
|
260
|
+
classifyre_cli-0.9.4.dist-info/RECORD,,
|
src/detectors/pii/detector.py
CHANGED
|
@@ -240,10 +240,6 @@ class PIIDetector(BaseDetector):
|
|
|
240
240
|
_TABULAR_CELL_RE: ClassVar[re.Pattern[str]] = re.compile(r"^ ([^:]+):(?: ?(.*))?$")
|
|
241
241
|
_TABULAR_CONTINUATION_RE: ClassVar[re.Pattern[str]] = re.compile(r"^ (.*)$")
|
|
242
242
|
|
|
243
|
-
# Fall back to full-text analysis when a page has more than this many cells.
|
|
244
|
-
# Per-cell analysis at scale causes O(rowsxcolumns) Presidio calls per page.
|
|
245
|
-
_TABULAR_CELL_LIMIT: ClassVar[int] = 200
|
|
246
|
-
|
|
247
243
|
# spaCy's own ceiling when nlp.max_length is not overridden.
|
|
248
244
|
_SPACY_DEFAULT_MAX_LENGTH: ClassVar[int] = 1_000_000
|
|
249
245
|
|
|
@@ -616,7 +612,10 @@ class PIIDetector(BaseDetector):
|
|
|
616
612
|
# ------------------------------------------------------------------
|
|
617
613
|
|
|
618
614
|
def _normalize_column_name(self, column_name: str) -> str:
|
|
619
|
-
|
|
615
|
+
# camelCase and PascalCase are words too (FirstName, MobilePhone,
|
|
616
|
+
# HTTPReferrerURL): CRM exports name their columns that way.
|
|
617
|
+
split = re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", " ", column_name)
|
|
618
|
+
return re.sub(r"[^a-z0-9]+", " ", split.lower()).strip()
|
|
620
619
|
|
|
621
620
|
def _column_tokens(self, column_name: str) -> set[str]:
|
|
622
621
|
normalized = self._normalize_column_name(column_name)
|
|
@@ -760,7 +759,8 @@ class PIIDetector(BaseDetector):
|
|
|
760
759
|
# ------------------------------------------------------------------
|
|
761
760
|
|
|
762
761
|
def _extract_tabular_cells(self, content: str) -> list[_TabularCell]:
|
|
763
|
-
|
|
762
|
+
# Any row header: a page of a sweep starts at its own row (row_101:).
|
|
763
|
+
if not any(self._TABULAR_ROW_RE.match(line) for line in content.splitlines()):
|
|
764
764
|
return []
|
|
765
765
|
|
|
766
766
|
cells: list[_TabularCell] = []
|
|
@@ -845,35 +845,52 @@ class PIIDetector(BaseDetector):
|
|
|
845
845
|
return [deduped[k] for k in ordered_keys]
|
|
846
846
|
|
|
847
847
|
def _detect_tabular_content(self, content: str) -> list[DetectionResult] | None:
|
|
848
|
+
"""Findings of a tabular page, each tagged with its row and column.
|
|
849
|
+
|
|
850
|
+
The page is analysed one column at a time: the column's cells become
|
|
851
|
+
one text of ``<column>: <value>`` blocks, and each result is mapped
|
|
852
|
+
back to the cell it falls in. That is one Presidio call per column
|
|
853
|
+
rather than per cell, so pages of any size keep their columns (they
|
|
854
|
+
used to fall back to full text past 200 cells, losing every column,
|
|
855
|
+
so nothing was classified or masked), and every value is read beside
|
|
856
|
+
its column's name — the context that lifts a phone number or a
|
|
857
|
+
national id over the threshold, which a bare cell lacked.
|
|
858
|
+
"""
|
|
848
859
|
cells = self._extract_tabular_cells(content)
|
|
849
860
|
if not cells:
|
|
850
861
|
return None
|
|
851
862
|
|
|
852
|
-
# For very wide/long pages fall back to full-text analysis to avoid O(N) Presidio calls.
|
|
853
|
-
if len(cells) > self._TABULAR_CELL_LIMIT:
|
|
854
|
-
logger.debug(
|
|
855
|
-
"Page has %d cells (> %d limit); using full-text analysis instead of per-cell",
|
|
856
|
-
len(cells),
|
|
857
|
-
self._TABULAR_CELL_LIMIT,
|
|
858
|
-
)
|
|
859
|
-
return None
|
|
860
|
-
|
|
861
863
|
threshold = self._cfg.confidence_threshold or 0.7
|
|
862
864
|
results: list[DetectionResult] = []
|
|
863
|
-
|
|
865
|
+
by_column: dict[str, list[_TabularCell]] = {}
|
|
864
866
|
for cell in cells:
|
|
865
|
-
|
|
867
|
+
by_column.setdefault(cell.column_name, []).append(cell)
|
|
868
|
+
|
|
869
|
+
for column_name, column_cells in by_column.items():
|
|
870
|
+
allowed = self._allowed_entities_for_column(column_name)
|
|
866
871
|
if not allowed:
|
|
867
872
|
continue
|
|
868
|
-
|
|
869
|
-
for
|
|
873
|
+
text, spans = self._column_text(column_name, column_cells)
|
|
874
|
+
value_starts = [start for start, _end in spans]
|
|
875
|
+
for result in self._analyze_structured_cell(text, allowed_entity_types=allowed):
|
|
870
876
|
if not self._is_entity_enabled(result.entity_type):
|
|
871
877
|
continue
|
|
872
|
-
if not self._is_entity_allowed_for_column(result.entity_type,
|
|
878
|
+
if not self._is_entity_allowed_for_column(result.entity_type, column_name):
|
|
873
879
|
continue
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
880
|
+
# The cell whose value starts at or before the match; a match
|
|
881
|
+
# starting in the label before a value belongs to that value.
|
|
882
|
+
index = bisect.bisect_right(value_starts, result.start) - 1
|
|
883
|
+
if index < 0 or result.start >= spans[index][1]:
|
|
884
|
+
index += 1
|
|
885
|
+
if index >= len(spans):
|
|
886
|
+
continue
|
|
887
|
+
value_start, value_end = spans[index]
|
|
888
|
+
start, end = max(result.start, value_start), min(result.end, value_end)
|
|
889
|
+
if end <= start:
|
|
890
|
+
continue
|
|
891
|
+
cell = column_cells[index]
|
|
892
|
+
matched_content = text[start:end]
|
|
893
|
+
if not matched_content.strip() or not self._should_keep_tabular_result(
|
|
877
894
|
cell=cell,
|
|
878
895
|
entity_type=result.entity_type,
|
|
879
896
|
matched_content=matched_content,
|
|
@@ -886,8 +903,8 @@ class PIIDetector(BaseDetector):
|
|
|
886
903
|
confidence=result.score,
|
|
887
904
|
recognition_metadata=result.recognition_metadata,
|
|
888
905
|
line_number=cell.row_index,
|
|
889
|
-
start=
|
|
890
|
-
end=
|
|
906
|
+
start=start - value_start,
|
|
907
|
+
end=end - value_start,
|
|
891
908
|
metadata={
|
|
892
909
|
"tabular_row_index": cell.row_index,
|
|
893
910
|
"tabular_column_name": cell.column_name,
|
|
@@ -898,6 +915,24 @@ class PIIDetector(BaseDetector):
|
|
|
898
915
|
|
|
899
916
|
return self._dedupe_tabular_findings(results)
|
|
900
917
|
|
|
918
|
+
@staticmethod
|
|
919
|
+
def _column_text(
|
|
920
|
+
column_name: str, cells: list[_TabularCell]
|
|
921
|
+
) -> tuple[str, list[tuple[int, int]]]:
|
|
922
|
+
"""One column's cells as ``<column>: <value>`` blocks, a blank line
|
|
923
|
+
apart, and where each value starts and ends in that text."""
|
|
924
|
+
parts: list[str] = []
|
|
925
|
+
spans: list[tuple[int, int]] = []
|
|
926
|
+
position = 0
|
|
927
|
+
label = f"{column_name}: "
|
|
928
|
+
for cell in cells:
|
|
929
|
+
start = position + len(label)
|
|
930
|
+
spans.append((start, start + len(cell.value)))
|
|
931
|
+
block = f"{label}{cell.value}\n\n"
|
|
932
|
+
parts.append(block)
|
|
933
|
+
position += len(block)
|
|
934
|
+
return "".join(parts), spans
|
|
935
|
+
|
|
901
936
|
# ------------------------------------------------------------------
|
|
902
937
|
# Result construction
|
|
903
938
|
# ------------------------------------------------------------------
|
src/query/bindings.py
CHANGED
|
@@ -120,6 +120,10 @@ class SourceBinding:
|
|
|
120
120
|
binding = self._known_binding()
|
|
121
121
|
return binding.explain(exc) if binding else None
|
|
122
122
|
|
|
123
|
+
def needs_external_access(self) -> bool:
|
|
124
|
+
"""The opened reader needs DuckDB's external access left on (ODBC)."""
|
|
125
|
+
return self._reader is not None and self._reader.needs_external_access
|
|
126
|
+
|
|
123
127
|
def local_paths(self) -> list[str]:
|
|
124
128
|
"""Local paths DuckDB reads for this source (none until it is opened)."""
|
|
125
129
|
return self._reader.local_paths() if self._reader is not None else []
|
|
@@ -132,6 +136,11 @@ class SourceBinding:
|
|
|
132
136
|
"""Why a connector's scan of that table failed, as it said it."""
|
|
133
137
|
return self._reader.failure(relation) if self._reader else None
|
|
134
138
|
|
|
139
|
+
def reset_query(self, conn: Any) -> None:
|
|
140
|
+
"""Release per-query state registered on ``conn`` between sticky queries."""
|
|
141
|
+
if self._reader is not None:
|
|
142
|
+
self._reader.reset_query(conn)
|
|
143
|
+
|
|
135
144
|
def close(self) -> None:
|
|
136
145
|
if self._reader is not None:
|
|
137
146
|
self._reader.close()
|
src/query/connectors/arrow.py
CHANGED
|
@@ -171,6 +171,14 @@ class ArrowConnector(QueryBinding):
|
|
|
171
171
|
live = self._live.get(relation.strip('"'))
|
|
172
172
|
return live.error if live is not None else None
|
|
173
173
|
|
|
174
|
+
def reset_query(self, conn: Any) -> None:
|
|
175
|
+
for name in list(self._live):
|
|
176
|
+
try:
|
|
177
|
+
conn.unregister(name)
|
|
178
|
+
except Exception: # pragma: no cover - best effort
|
|
179
|
+
pass
|
|
180
|
+
self._live.clear()
|
|
181
|
+
|
|
174
182
|
def close(self) -> None:
|
|
175
183
|
self._live.clear()
|
|
176
184
|
|
src/query/connectors/base.py
CHANGED
|
@@ -118,6 +118,11 @@ class QueryBinding(ABC):
|
|
|
118
118
|
#: (``uv sync --group``); the query worker installs them before it forks
|
|
119
119
|
#: a query, so no query syncs the environment under another.
|
|
120
120
|
dependency_groups: ClassVar[tuple[str, ...]] = ()
|
|
121
|
+
#: The reader cannot work with DuckDB's ``enable_external_access`` off
|
|
122
|
+
#: (``odbc_scanner`` refuses every connection then). The session leaves it
|
|
123
|
+
#: on for such a query and locks everything else; it runs only in a Job,
|
|
124
|
+
#: never in the shared query worker (``DEFAULT_JOB_ONLY_SOURCES``).
|
|
125
|
+
needs_external_access: ClassVar[bool] = False
|
|
121
126
|
|
|
122
127
|
def __init__(self, source: SourceContext) -> None:
|
|
123
128
|
self.source = source
|
|
@@ -156,6 +161,9 @@ class QueryBinding(ABC):
|
|
|
156
161
|
(``ConnectorError``); None for tables DuckDB reads itself."""
|
|
157
162
|
return None
|
|
158
163
|
|
|
164
|
+
def reset_query(self, conn: Any) -> None:
|
|
165
|
+
"""Release per-query state registered on ``conn`` between sticky queries."""
|
|
166
|
+
|
|
159
167
|
def close(self) -> None:
|
|
160
168
|
"""Release what the binding made (temporary files); the session closes DuckDB."""
|
|
161
169
|
|
|
@@ -30,6 +30,7 @@ class ObjectStorageBinding(QueryBinding):
|
|
|
30
30
|
def __init__(self, source: SourceContext) -> None:
|
|
31
31
|
super().__init__(source)
|
|
32
32
|
self._storage: Any = None
|
|
33
|
+
self._iceberg_version_guessing = False
|
|
33
34
|
|
|
34
35
|
def relation(self, conn: Any, location: TableLocation) -> str:
|
|
35
36
|
(key,) = self.require(location, "object_key")
|
|
@@ -59,7 +60,13 @@ class ObjectStorageBinding(QueryBinding):
|
|
|
59
60
|
# Without a version-hint file DuckDB finds the newest metadata by
|
|
60
61
|
# listing the root, which it calls "unsafe" because a writer could
|
|
61
62
|
# be mid-commit; for a read-only query that is the right trade.
|
|
62
|
-
|
|
63
|
+
if not self._iceberg_version_guessing:
|
|
64
|
+
row = conn.execute(
|
|
65
|
+
"SELECT current_setting('unsafe_enable_version_guessing')"
|
|
66
|
+
).fetchone()
|
|
67
|
+
if not (row and bool(row[0])):
|
|
68
|
+
conn.execute("SET unsafe_enable_version_guessing = true")
|
|
69
|
+
self._iceberg_version_guessing = True
|
|
63
70
|
return f"iceberg_scan({uri}, allow_moved_paths = true)"
|
|
64
71
|
if location.kind == "file":
|
|
65
72
|
if fmt == "parquet":
|
src/query/connectors/odbc.py
CHANGED
|
@@ -17,6 +17,10 @@ from .base import QueryBinding, SourceContext, TableLocation
|
|
|
17
17
|
|
|
18
18
|
class OdbcBinding(QueryBinding):
|
|
19
19
|
tier = "extension"
|
|
20
|
+
# odbc_scanner opens no connection with external access off, not even
|
|
21
|
+
# through a handle made before: "ODBC connections cannot be opened when
|
|
22
|
+
# external access is disabled".
|
|
23
|
+
needs_external_access = True
|
|
20
24
|
|
|
21
25
|
def __init__(self, source: SourceContext) -> None:
|
|
22
26
|
super().__init__(source)
|
src/query/masks.py
CHANGED
|
@@ -14,7 +14,33 @@ from typing import Any
|
|
|
14
14
|
|
|
15
15
|
from ..utils.duckdb_engine import quote_identifier
|
|
16
16
|
|
|
17
|
-
MASK_KINDS = ("redact", "partial", "hash", "null")
|
|
17
|
+
MASK_KINDS = ("redact", "partial", "hash", "null", "scrub")
|
|
18
|
+
|
|
19
|
+
#: What ``scrub`` removes from free text, in order (RE2, as DuckDB reads it):
|
|
20
|
+
#: the identifiers and credentials a pattern can tell apart. Names and other
|
|
21
|
+
#: words stay — scrub keeps a text readable, it does not anonymise it. Every
|
|
22
|
+
#: row is scrubbed, not only the rows a scan sampled.
|
|
23
|
+
SCRUB_PATTERNS: tuple[tuple[str, str], ...] = (
|
|
24
|
+
(r"(?s)-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", "[private key]"),
|
|
25
|
+
(r"eyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}", "[token]"),
|
|
26
|
+
(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b", "[key]"),
|
|
27
|
+
(r"\b[sr]k_(?:live|test)_[0-9A-Za-z]{10,}\b", "[key]"),
|
|
28
|
+
(r"\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b", "[key]"),
|
|
29
|
+
(r"\bxox[abprs]-[A-Za-z0-9-]{10,}\b", "[key]"),
|
|
30
|
+
(
|
|
31
|
+
r"(?i)\b(password|passwort|passwd|pwd|passcode|pin)(\s*(?:is|ist|:|=)\s*)\S+",
|
|
32
|
+
"\\1\\2[secret]",
|
|
33
|
+
),
|
|
34
|
+
# A long run of key characters: an AWS secret access key (40) and its
|
|
35
|
+
# like. Words and URLs break such runs (spaces, dots, colons).
|
|
36
|
+
(r"[A-Za-z0-9/+]{30,}={0,2}", "[secret]"),
|
|
37
|
+
(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", "[email]"),
|
|
38
|
+
(r"\b[A-Z]{2}[0-9]{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,4})?\b", "[iban]"),
|
|
39
|
+
(r"\b(?:[0-9][ -]?){12,18}[0-9]\b", "[card number]"),
|
|
40
|
+
(r"\+[0-9][0-9 ()/-]{6,}[0-9]", "[phone]"),
|
|
41
|
+
(r"\b[0-9]{4} ?[0-9]{6}\b", "[number]"),
|
|
42
|
+
(r"\b[A-Z]{1,2}[0-9]{6,8}[A-Z]?\b", "[document number]"),
|
|
43
|
+
)
|
|
18
44
|
|
|
19
45
|
#: Shorter values are redacted whole by a ``partial`` mask: their last four
|
|
20
46
|
#: characters would be most of them.
|
|
@@ -141,10 +167,24 @@ def _struct_fields(type_name: str) -> list[tuple[str, str]] | None:
|
|
|
141
167
|
|
|
142
168
|
def _masked_leaf(expr: str, type_name: str, mask: str, salt: str) -> str:
|
|
143
169
|
if mask == "hash":
|
|
170
|
+
# Text is hashed lower-cased and trimmed: the same address spelt
|
|
171
|
+
# differently in two systems must join (a hash is for joining).
|
|
172
|
+
value = (
|
|
173
|
+
f"lower(trim(CAST({expr} AS VARCHAR)))"
|
|
174
|
+
if _is_text(type_name)
|
|
175
|
+
else f"CAST({expr} AS VARCHAR)"
|
|
176
|
+
)
|
|
144
177
|
return (
|
|
145
178
|
f"CASE WHEN {expr} IS NULL THEN NULL "
|
|
146
|
-
f"ELSE left(sha256({_literal(salt)} ||
|
|
179
|
+
f"ELSE left(sha256({_literal(salt)} || {value}), 16) END"
|
|
147
180
|
)
|
|
181
|
+
if mask == "scrub" and _is_text(type_name):
|
|
182
|
+
scrubbed = expr
|
|
183
|
+
for pattern, replacement in SCRUB_PATTERNS:
|
|
184
|
+
scrubbed = (
|
|
185
|
+
f"regexp_replace({scrubbed}, {_literal(pattern)}, {_literal(replacement)}, 'g')"
|
|
186
|
+
)
|
|
187
|
+
return scrubbed
|
|
148
188
|
if mask == "null" or not _is_text(type_name):
|
|
149
189
|
# A number, a date or a map has no "partly hidden" form.
|
|
150
190
|
return f"CAST(NULL AS {type_name})" if type_name else "NULL"
|
src/query/runner.py
CHANGED
|
@@ -20,7 +20,7 @@ from typing import TYPE_CHECKING, Any
|
|
|
20
20
|
from ..utils.redaction import ENCRYPTED_CONFIG_PATHS, Redactor, _leaves_at_path
|
|
21
21
|
|
|
22
22
|
if TYPE_CHECKING:
|
|
23
|
-
from .session import QueryRequest, QueryResult
|
|
23
|
+
from .session import QueryRequest, QueryResult, StickyDuckDbState
|
|
24
24
|
|
|
25
25
|
logger = logging.getLogger(__name__)
|
|
26
26
|
|
|
@@ -123,7 +123,9 @@ def ensure_dependencies() -> None:
|
|
|
123
123
|
require_module("sqlglot", "SQL query", ["lineage"])
|
|
124
124
|
|
|
125
125
|
|
|
126
|
-
def run_query(
|
|
126
|
+
def run_query(
|
|
127
|
+
request_data: dict[str, Any], *, sticky: StickyDuckDbState | None = None
|
|
128
|
+
) -> tuple[dict[str, Any], QueryResult | None]:
|
|
127
129
|
"""Run a request; return the status payload and, on success, the result."""
|
|
128
130
|
redact = _redactor(request_data)
|
|
129
131
|
try:
|
|
@@ -136,7 +138,7 @@ def run_query(request_data: dict[str, Any]) -> tuple[dict[str, Any], QueryResult
|
|
|
136
138
|
|
|
137
139
|
request = QueryRequest.from_dict(request_data)
|
|
138
140
|
try:
|
|
139
|
-
with QuerySession(request) as session:
|
|
141
|
+
with QuerySession(request, sticky=sticky) as session:
|
|
140
142
|
result = session.run()
|
|
141
143
|
except QueryRefusedError as exc:
|
|
142
144
|
return error_payload(exc.code, redact(str(exc))), None
|