grootveil 2.0.0__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.
- grootveil/__init__.py +42 -0
- grootveil/actions/__init__.py +0 -0
- grootveil/actions/base.py +33 -0
- grootveil/actions/encrypt.py +32 -0
- grootveil/actions/hash.py +12 -0
- grootveil/actions/keep.py +6 -0
- grootveil/actions/mask.py +24 -0
- grootveil/actions/pseudonymize.py +23 -0
- grootveil/actions/redact.py +6 -0
- grootveil/actions/registry.py +27 -0
- grootveil/actions/replace.py +8 -0
- grootveil/core/__init__.py +0 -0
- grootveil/core/errors.py +2 -0
- grootveil/core/labels.py +40 -0
- grootveil/detectors/__init__.py +0 -0
- grootveil/detectors/base.py +11 -0
- grootveil/detectors/deny_list.py +27 -0
- grootveil/detectors/model.py +129 -0
- grootveil/detectors/rules/__init__.py +14 -0
- grootveil/detectors/rules/address.py +50 -0
- grootveil/detectors/rules/checks.py +18 -0
- grootveil/detectors/rules/contact.py +114 -0
- grootveil/detectors/rules/dates.py +127 -0
- grootveil/detectors/rules/detector.py +77 -0
- grootveil/detectors/rules/financial.py +96 -0
- grootveil/detectors/rules/ids/__init__.py +20 -0
- grootveil/detectors/rules/ids/americas.py +50 -0
- grootveil/detectors/rules/ids/asia_pacific.py +148 -0
- grootveil/detectors/rules/ids/documents.py +48 -0
- grootveil/detectors/rules/ids/europe.py +219 -0
- grootveil/detectors/rules/ids/germany.py +84 -0
- grootveil/detectors/rules/ids/middle_east_africa.py +85 -0
- grootveil/detectors/rules/rule.py +37 -0
- grootveil/detectors/rules/secrets.py +74 -0
- grootveil/models/__init__.py +0 -0
- grootveil/models/action_config.py +24 -0
- grootveil/models/finding.py +14 -0
- grootveil/models/item.py +14 -0
- grootveil/models/protected.py +21 -0
- grootveil/py.typed +0 -0
- grootveil/resolvers/__init__.py +0 -0
- grootveil/resolvers/address_prefix.py +64 -0
- grootveil/resolvers/join.py +30 -0
- grootveil/resolvers/overlaps.py +42 -0
- grootveil/resolvers/register.py +33 -0
- grootveil/resolvers/words.py +14 -0
- grootveil/services/__init__.py +0 -0
- grootveil/services/applier.py +26 -0
- grootveil/services/resolver.py +35 -0
- grootveil/services/vault.py +40 -0
- grootveil/shield.py +257 -0
- grootveil-2.0.0.dist-info/METADATA +198 -0
- grootveil-2.0.0.dist-info/RECORD +54 -0
- grootveil-2.0.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from dataclasses import replace
|
|
3
|
+
|
|
4
|
+
from grootveil.models.finding import Finding
|
|
5
|
+
|
|
6
|
+
# One thing = one span (the same rule as our training data): address parts with only spaces, commas or new lines
|
|
7
|
+
# between them are one ADDRESS; names with only spaces between them are one PERSON_NAME.
|
|
8
|
+
JOIN = {"ADDRESS": re.compile(r"[\s,]*"), "PERSON_NAME": re.compile(r" +")}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def join(text: str, findings: list[Finding]) -> list[Finding]:
|
|
12
|
+
out: list[Finding] = []
|
|
13
|
+
for f in sorted(findings, key=lambda f: (f.start, f.end)):
|
|
14
|
+
prev = out[-1] if out else None
|
|
15
|
+
if (
|
|
16
|
+
prev
|
|
17
|
+
and prev.label == f.label
|
|
18
|
+
and f.label in JOIN
|
|
19
|
+
and prev.end <= f.start
|
|
20
|
+
and JOIN[f.label].fullmatch(text[prev.end : f.start])
|
|
21
|
+
):
|
|
22
|
+
out[-1] = replace(
|
|
23
|
+
prev,
|
|
24
|
+
end=f.end,
|
|
25
|
+
score=max(prev.score, f.score),
|
|
26
|
+
why=f"{prev.why}; joined with the next part" if prev.why else "",
|
|
27
|
+
)
|
|
28
|
+
else:
|
|
29
|
+
out.append(f)
|
|
30
|
+
return out
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from bisect import bisect_left
|
|
2
|
+
from dataclasses import replace
|
|
3
|
+
|
|
4
|
+
from grootveil.models.finding import Finding
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def take_in_pieces(findings: list[Finding]) -> list[Finding]:
|
|
8
|
+
"""A rule's match that holds model findings of its own label (the model cut one value into pieces:
|
|
9
|
+
"2025-09-08T21" and "39Z" in "2025-09-08T21:34:39Z") takes their place, with their best score. The whole value is
|
|
10
|
+
masked, not only the pieces."""
|
|
11
|
+
model = sorted((f for f in findings if f.source == "model"), key=lambda f: f.start)
|
|
12
|
+
starts = [f.start for f in model]
|
|
13
|
+
taken: set[int] = set()
|
|
14
|
+
grown: dict[int, Finding] = {}
|
|
15
|
+
for r in findings:
|
|
16
|
+
if not r.source.startswith("rule:"):
|
|
17
|
+
continue
|
|
18
|
+
inside = [
|
|
19
|
+
m
|
|
20
|
+
for m in model[bisect_left(starts, r.start) : bisect_left(starts, r.end)]
|
|
21
|
+
if m.label == r.label and m.end <= r.end and (m.start, m.end) != (r.start, r.end)
|
|
22
|
+
]
|
|
23
|
+
if inside:
|
|
24
|
+
taken.update(id(m) for m in inside)
|
|
25
|
+
score = max(r.score, *(m.score for m in inside))
|
|
26
|
+
grown[id(r)] = replace(r, score=score, why=f"{r.why}; holds the model's pieces")
|
|
27
|
+
if not grown:
|
|
28
|
+
return findings
|
|
29
|
+
return [grown.get(id(f), f) for f in findings if id(f) not in taken]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def remove_overlaps(findings: list[Finding]) -> list[Finding]:
|
|
33
|
+
"""Higher score wins, then the longer span, then the model over a rule. A finding that overlaps a kept one is
|
|
34
|
+
dropped. First a rule's match takes in the model's pieces of the same value (take_in_pieces)."""
|
|
35
|
+
findings = take_in_pieces(findings)
|
|
36
|
+
kept: list[Finding] = []
|
|
37
|
+
taken = bytearray(max((f.end for f in findings), default=0)) # 1 where a kept finding is
|
|
38
|
+
for f in sorted(findings, key=lambda f: (-f.score, f.start - f.end, f.source != "model")):
|
|
39
|
+
if not any(taken[f.start : f.end]):
|
|
40
|
+
taken[f.start : f.end] = b"\x01" * (f.end - f.start)
|
|
41
|
+
kept.append(f)
|
|
42
|
+
return sorted(kept, key=lambda f: f.start)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
from grootveil.core.labels import DIRECT
|
|
4
|
+
from grootveil.models.finding import Finding
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def register(text: str, findings: list[Finding], min_len: int = 3) -> list[Finding]:
|
|
8
|
+
"""A direct identifier found once is masked everywhere: every other exact mention of the same value (as a whole
|
|
9
|
+
word) is added with the same label and score, source "register". A person is protected only when every mention
|
|
10
|
+
is masked.
|
|
11
|
+
ponytail: exact value only; "Priya" alone after "Priya Sharma" relies on the model. Add name parts if leaks show."""
|
|
12
|
+
out = list(findings)
|
|
13
|
+
values = {text[f.start : f.end]: f for f in findings if f.label in DIRECT and f.end - f.start >= min_len}
|
|
14
|
+
# a place name alone ("USA") is often part of other words ("Athletica USA"): only street addresses (with a digit)
|
|
15
|
+
values = {v: f for v, f in values.items() if f.label != "ADDRESS" or any(c.isdigit() for c in v)}
|
|
16
|
+
taken = bytearray(len(text)) # 1 where a finding already is
|
|
17
|
+
for o in out:
|
|
18
|
+
taken[o.start : o.end] = b"\x01" * (o.end - o.start)
|
|
19
|
+
for value, f in values.items():
|
|
20
|
+
for m in re.finditer(rf"(?<!\w){re.escape(value)}(?!\w)", text):
|
|
21
|
+
if not any(taken[m.start() : m.end()]):
|
|
22
|
+
taken[m.start() : m.end()] = b"\x01" * (m.end() - m.start())
|
|
23
|
+
out.append(
|
|
24
|
+
Finding(
|
|
25
|
+
f.label,
|
|
26
|
+
m.start(),
|
|
27
|
+
m.end(),
|
|
28
|
+
f.score,
|
|
29
|
+
"register",
|
|
30
|
+
f"same value as the {f.label} found at {f.start}",
|
|
31
|
+
)
|
|
32
|
+
)
|
|
33
|
+
return sorted(out, key=lambda f: f.start)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from dataclasses import replace
|
|
2
|
+
|
|
3
|
+
from grootveil.models.finding import Finding
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def whole_words(text: str, f: Finding) -> Finding:
|
|
7
|
+
"""A finding never cuts a word: an edge inside a word moves out to the word's edge ("IB" of "IBAN" becomes
|
|
8
|
+
"IBAN"). Widening, not dropping: a dropped piece could be PII that leaks."""
|
|
9
|
+
start, end = f.start, f.end
|
|
10
|
+
while start > 0 and text[start - 1].isalnum() and text[start].isalnum():
|
|
11
|
+
start -= 1
|
|
12
|
+
while end < len(text) and text[end - 1].isalnum() and text[end].isalnum():
|
|
13
|
+
end += 1
|
|
14
|
+
return f if (start, end) == (f.start, f.end) else replace(f, start=start, end=end)
|
|
File without changes
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
|
|
3
|
+
from grootveil.actions.base import Context
|
|
4
|
+
from grootveil.actions.registry import get
|
|
5
|
+
from grootveil.models.action_config import ActionConfig
|
|
6
|
+
from grootveil.models.finding import Finding
|
|
7
|
+
from grootveil.models.item import Item
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def apply(
|
|
11
|
+
text: str, findings: list[Finding], action_for: Callable[[str], ActionConfig], ctx: Context
|
|
12
|
+
) -> tuple[str, list[Item]]:
|
|
13
|
+
"""The text with each finding changed by its label's action; items point into the new text."""
|
|
14
|
+
parts, items, pos, length = [], [], 0, 0
|
|
15
|
+
for f in sorted(findings, key=lambda f: f.start):
|
|
16
|
+
if not 0 <= pos <= f.start < f.end <= len(text):
|
|
17
|
+
raise ValueError(f"finding outside the text or overlapping the one before: {f}")
|
|
18
|
+
config = action_for(f.label)
|
|
19
|
+
new = get(config.name)(text[f.start : f.end], f.label, ctx, **config.params)
|
|
20
|
+
parts += [text[pos : f.start], new]
|
|
21
|
+
length += f.start - pos
|
|
22
|
+
items.append(Item(f.label, length, length + len(new), new, config.name, f.score, f.source))
|
|
23
|
+
length += len(new)
|
|
24
|
+
pos = f.end
|
|
25
|
+
parts.append(text[pos:])
|
|
26
|
+
return "".join(parts), items
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Raw findings from every detector -> the final list: at most one label per character.
|
|
2
|
+
|
|
3
|
+
Order: whole words -> labels asked for -> threshold per label -> allow list -> an address's unit part in front
|
|
4
|
+
("1st Floor, ") -> join parts of one thing -> overlaps ->
|
|
5
|
+
entity register (every other mention of a direct identifier that was found).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from grootveil.models.finding import Finding
|
|
9
|
+
from grootveil.resolvers.address_prefix import address_prefix
|
|
10
|
+
from grootveil.resolvers.join import join
|
|
11
|
+
from grootveil.resolvers.overlaps import remove_overlaps
|
|
12
|
+
from grootveil.resolvers.register import register
|
|
13
|
+
from grootveil.resolvers.words import whole_words
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def resolve(
|
|
17
|
+
text: str,
|
|
18
|
+
findings: list[Finding],
|
|
19
|
+
labels: set[str] | None = None,
|
|
20
|
+
thresholds: dict[str, float] | None = None,
|
|
21
|
+
allow_list: set[str] | None = None,
|
|
22
|
+
) -> list[Finding]:
|
|
23
|
+
"""thresholds: {"default": 0.5, "PASSWORD": 0.3}; allow_list: exact values that are never PII."""
|
|
24
|
+
thresholds = thresholds or {}
|
|
25
|
+
kept = [
|
|
26
|
+
f
|
|
27
|
+
for f in (whole_words(text, f) for f in findings)
|
|
28
|
+
if (labels is None or f.label in labels)
|
|
29
|
+
and f.score >= thresholds.get(f.label, thresholds.get("default", 0.0))
|
|
30
|
+
and not (allow_list and text[f.start : f.end] in allow_list)
|
|
31
|
+
]
|
|
32
|
+
return register(text, remove_overlaps(join(text, address_prefix(text, kept))))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
__all__ = ["resolve"]
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""The values restore() needs, kept inside the ref itself: sealed (AES-256-GCM with the secret) with an expiry time.
|
|
2
|
+
Nothing is stored on the server, so any replica can restore, and the values never travel in plain text.
|
|
3
|
+
A ref: v1.<url-safe base64 of nonce + ciphertext>
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import base64
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
from cryptography.exceptions import InvalidTag
|
|
13
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
14
|
+
|
|
15
|
+
from grootveil.core.errors import RefError
|
|
16
|
+
|
|
17
|
+
PREFIX = "v1."
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _aes(secret: bytes) -> AESGCM:
|
|
21
|
+
return AESGCM(hashlib.sha256(b"grootveil vault v1:" + secret).digest())
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def seal(tokens: dict[str, str], secret: bytes, ttl_seconds: int, now: float | None = None) -> str:
|
|
25
|
+
body = json.dumps({"exp": int((now or time.time()) + ttl_seconds), "tokens": tokens}).encode()
|
|
26
|
+
nonce = os.urandom(12)
|
|
27
|
+
return PREFIX + base64.urlsafe_b64encode(nonce + _aes(secret).encrypt(nonce, body, None)).decode()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def open_ref(ref: str, secret: bytes, now: float | None = None) -> dict[str, str]:
|
|
31
|
+
if not ref.startswith(PREFIX):
|
|
32
|
+
raise RefError("not a grootveil ref")
|
|
33
|
+
try:
|
|
34
|
+
raw = base64.urlsafe_b64decode(ref[len(PREFIX) :])
|
|
35
|
+
body = json.loads(_aes(secret).decrypt(raw[:12], raw[12:], None))
|
|
36
|
+
except (InvalidTag, ValueError) as e:
|
|
37
|
+
raise RefError("the ref was changed or sealed with another secret") from e
|
|
38
|
+
if body["exp"] < (now or time.time()):
|
|
39
|
+
raise RefError("the ref has expired")
|
|
40
|
+
return body["tokens"]
|
grootveil/shield.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Shield: the one entry point. scan finds, protect finds and changes, restore puts values back.
|
|
2
|
+
|
|
3
|
+
shield = Shield(secret="...") # our model + the rules; Shield(model=None): rules only
|
|
4
|
+
shield.scan(text) # [Finding(label, start, end, score, source, why)]
|
|
5
|
+
safe = shield.protect(text, action="pseudonymize") # Protected(text, items, ref)
|
|
6
|
+
shield.restore(llm_answer, safe.ref) # the placeholders in the answer become the values again
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import inspect
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from grootveil.actions.base import Context
|
|
13
|
+
from grootveil.actions.registry import ACTIONS
|
|
14
|
+
from grootveil.core.labels import LABELS
|
|
15
|
+
from grootveil.detectors.base import Detector
|
|
16
|
+
from grootveil.detectors.deny_list import DenyListDetector
|
|
17
|
+
from grootveil.detectors.rules import DEFAULT_RULES, Rule, RuleDetector
|
|
18
|
+
from grootveil.detectors.rules.detector import EXTRA_RULE_TIMEOUT
|
|
19
|
+
from grootveil.models.action_config import ActionConfig
|
|
20
|
+
from grootveil.models.finding import Finding
|
|
21
|
+
from grootveil.models.protected import Protected
|
|
22
|
+
from grootveil.services import vault
|
|
23
|
+
from grootveil.services.applier import apply
|
|
24
|
+
from grootveil.services.resolver import resolve
|
|
25
|
+
|
|
26
|
+
MODEL = "default" # Shield(model=MODEL): our fine-tuned model at its pinned revision
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Shield:
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
model: str | None = MODEL,
|
|
33
|
+
revision: str | None = None,
|
|
34
|
+
rules: list[Rule] | None = DEFAULT_RULES,
|
|
35
|
+
secret: str | bytes | None = None,
|
|
36
|
+
detectors: list[Detector] | None = None,
|
|
37
|
+
threshold: float = 0.5,
|
|
38
|
+
ttl_seconds: int = 86400,
|
|
39
|
+
**model_args,
|
|
40
|
+
):
|
|
41
|
+
"""model: an HF repo or a local folder, MODEL for ours, None for rules only (no torch needed).
|
|
42
|
+
rules: the rule list, None for the model alone. secret: for hash, encrypt and refs.
|
|
43
|
+
detectors: instead of model and rules (tests, or your own detector). threshold: the lowest score kept, when a
|
|
44
|
+
call gives none. ttl_seconds: how long a ref from protect() can be restored. model_args: max_len, stride,
|
|
45
|
+
device, fp16, batch_size."""
|
|
46
|
+
self.threshold = _threshold(threshold)
|
|
47
|
+
if isinstance(ttl_seconds, bool) or not isinstance(ttl_seconds, int) or ttl_seconds < 1:
|
|
48
|
+
raise ValueError("ttl_seconds must be a whole number of seconds, 1 or more")
|
|
49
|
+
self.ttl_seconds = ttl_seconds
|
|
50
|
+
if secret is not None and not isinstance(secret, str | bytes):
|
|
51
|
+
raise TypeError(f"secret must be a str or bytes, not {type(secret).__name__}")
|
|
52
|
+
self.secret = secret.encode() if isinstance(secret, str) else secret
|
|
53
|
+
if detectors is None:
|
|
54
|
+
detectors = [RuleDetector(rules)] if rules else []
|
|
55
|
+
if model is not None:
|
|
56
|
+
detectors.append(_model(model, revision, **model_args))
|
|
57
|
+
if not detectors:
|
|
58
|
+
raise ValueError("a Shield needs the model, the rules or both")
|
|
59
|
+
self.detectors = detectors
|
|
60
|
+
|
|
61
|
+
def scan(
|
|
62
|
+
self,
|
|
63
|
+
text: str | list[str],
|
|
64
|
+
labels: list[str] | None = None,
|
|
65
|
+
threshold: float | None = None,
|
|
66
|
+
allow_list: list[str] | None = None,
|
|
67
|
+
deny_list: dict[str, str] | None = None,
|
|
68
|
+
extra_rules: list[Rule] | None = None,
|
|
69
|
+
) -> list[Finding] | list[list[Finding]]:
|
|
70
|
+
"""What is PII, where, how sure and why. labels: only these (all when None). threshold: the lowest score kept.
|
|
71
|
+
allow_list: exact values that are never PII. deny_list: values that are always PII, with their label
|
|
72
|
+
({"Project Falcon": "CUSTOMER_ID"}; whole words, any case, score 1.0). extra_rules: more rules, for this call
|
|
73
|
+
only (next to the Shield's own)."""
|
|
74
|
+
texts = _texts(text)
|
|
75
|
+
found = self._scan(texts, labels, threshold, allow_list, deny_list, extra_rules)
|
|
76
|
+
return found[0] if isinstance(text, str) else found
|
|
77
|
+
|
|
78
|
+
def protect(
|
|
79
|
+
self,
|
|
80
|
+
text: str | list[str],
|
|
81
|
+
action: ActionConfig | dict | str = "replace",
|
|
82
|
+
label_actions: dict[str, ActionConfig | dict | str] | None = None,
|
|
83
|
+
labels: list[str] | None = None,
|
|
84
|
+
threshold: float | None = None,
|
|
85
|
+
allow_list: list[str] | None = None,
|
|
86
|
+
deny_list: dict[str, str] | None = None,
|
|
87
|
+
extra_rules: list[Rule] | None = None,
|
|
88
|
+
) -> Protected | list[Protected]:
|
|
89
|
+
"""scan, then each finding changed by its label's action. A batch shares one set of placeholders (one person,
|
|
90
|
+
one placeholder) and one ref. action: for every label ("mask" or {"type": "mask", "keep_last": 4}).
|
|
91
|
+
label_actions: other actions for some labels ({"CARD_NUMBER": "redact"}). The other options: as scan."""
|
|
92
|
+
texts = _texts(text)
|
|
93
|
+
actions = self._actions(action, label_actions) # checked before the model runs
|
|
94
|
+
found = self._scan(texts, labels, threshold, allow_list, deny_list, extra_rules)
|
|
95
|
+
out = self._change(texts, found, *actions)
|
|
96
|
+
return out[0] if isinstance(text, str) else out
|
|
97
|
+
|
|
98
|
+
def apply(
|
|
99
|
+
self,
|
|
100
|
+
text: str,
|
|
101
|
+
findings: list[Finding],
|
|
102
|
+
action: ActionConfig | dict | str = "replace",
|
|
103
|
+
label_actions: dict[str, ActionConfig | dict | str] | None = None,
|
|
104
|
+
) -> Protected:
|
|
105
|
+
"""protect() on findings you already have (from scan, or from another tool), without finding anything: each
|
|
106
|
+
finding is changed by its label's action. The findings must be inside the text and must not overlap."""
|
|
107
|
+
texts = _texts(text)
|
|
108
|
+
if not isinstance(findings, list | tuple) or not all(isinstance(f, Finding) for f in findings):
|
|
109
|
+
raise TypeError("findings must be a list of Finding")
|
|
110
|
+
if unknown := sorted({f.label for f in findings} - set(LABELS)):
|
|
111
|
+
raise ValueError(f"unknown labels {unknown}; known: {LABELS}")
|
|
112
|
+
return self._change(texts, [list(findings)], *self._actions(action, label_actions))[0]
|
|
113
|
+
|
|
114
|
+
def _actions(
|
|
115
|
+
self, action: ActionConfig | dict | str, label_actions: dict[str, ActionConfig | dict | str] | None
|
|
116
|
+
) -> tuple[ActionConfig, dict[str, ActionConfig]]:
|
|
117
|
+
"""(the action for every label, the other actions by label), every one checked."""
|
|
118
|
+
default = _action(action)
|
|
119
|
+
chosen = {label: _action(a) for label, a in (label_actions or {}).items()}
|
|
120
|
+
if unknown_labels := sorted(set(chosen) - set(LABELS)):
|
|
121
|
+
raise ValueError(f"unknown labels {unknown_labels}; known: {LABELS}")
|
|
122
|
+
if unknown := sorted({a.name for a in [default, *chosen.values()]} - set(ACTIONS)):
|
|
123
|
+
raise ValueError(f"unknown actions {unknown}; known: {sorted(ACTIONS)}")
|
|
124
|
+
for a in [default, *chosen.values()]:
|
|
125
|
+
self._try(a)
|
|
126
|
+
return default, chosen
|
|
127
|
+
|
|
128
|
+
def _change(
|
|
129
|
+
self,
|
|
130
|
+
texts: list[str],
|
|
131
|
+
found: list[list[Finding]],
|
|
132
|
+
default: ActionConfig,
|
|
133
|
+
chosen: dict[str, ActionConfig],
|
|
134
|
+
) -> list[Protected]:
|
|
135
|
+
"""Each text with its findings changed; one ref for all of them when an action can be undone."""
|
|
136
|
+
ctx = Context(secret=self.secret, texts=texts)
|
|
137
|
+
changed = [
|
|
138
|
+
apply(t, f, lambda label: chosen.get(label, default), ctx) for t, f in zip(texts, found, strict=True)
|
|
139
|
+
]
|
|
140
|
+
ref = None
|
|
141
|
+
if ctx.tokens:
|
|
142
|
+
if not self.secret:
|
|
143
|
+
raise ValueError("pseudonymize and encrypt need a secret (Shield(secret=...)) to make a ref")
|
|
144
|
+
ref = vault.seal(ctx.tokens, self.secret, self.ttl_seconds)
|
|
145
|
+
return [Protected(new, items, ref) for new, items in changed]
|
|
146
|
+
|
|
147
|
+
def restore(self, text: str, ref: str) -> str:
|
|
148
|
+
"""Every placeholder (and encrypted value) of the ref that appears in text becomes its value again: the text
|
|
149
|
+
can be new (an LLM's answer), only the tokens must be in it. Longest token first."""
|
|
150
|
+
if not isinstance(text, str) or not isinstance(ref, str):
|
|
151
|
+
raise TypeError("restore needs a text and a ref (Protected.ref), both str")
|
|
152
|
+
if not self.secret:
|
|
153
|
+
raise ValueError("restore needs the secret the ref was sealed with")
|
|
154
|
+
tokens = vault.open_ref(ref, self.secret)
|
|
155
|
+
for token in sorted(tokens, key=len, reverse=True):
|
|
156
|
+
text = text.replace(token, tokens[token])
|
|
157
|
+
return text
|
|
158
|
+
|
|
159
|
+
def _try(self, a: ActionConfig) -> None:
|
|
160
|
+
"""Run the action once on a sample value, so a wrong setting fails now, whatever the text (Presidio checks
|
|
161
|
+
only when a value is found)."""
|
|
162
|
+
action = ACTIONS[a.name]
|
|
163
|
+
try:
|
|
164
|
+
action("sample-value-1234", "EMAIL", Context(secret=self.secret), **a.params)
|
|
165
|
+
except TypeError: # an unknown setting, or one of the wrong type
|
|
166
|
+
takes = [p for p in inspect.signature(action).parameters if p not in ("value", "label", "ctx")]
|
|
167
|
+
raise ValueError(
|
|
168
|
+
f"action {a.name}: bad settings {sorted(a.params)}; it takes {takes or 'no settings'}"
|
|
169
|
+
) from None
|
|
170
|
+
|
|
171
|
+
def _scan(
|
|
172
|
+
self,
|
|
173
|
+
texts: list[str],
|
|
174
|
+
labels: list[str] | None,
|
|
175
|
+
threshold: float | None,
|
|
176
|
+
allow_list: list[str] | None,
|
|
177
|
+
deny_list: dict[str, str] | None = None,
|
|
178
|
+
extra_rules: list[Rule] | None = None,
|
|
179
|
+
) -> list[list[Finding]]:
|
|
180
|
+
_strings("labels", labels)
|
|
181
|
+
_strings("allow_list", allow_list)
|
|
182
|
+
if deny_list is not None and not (
|
|
183
|
+
isinstance(deny_list, dict) and all(isinstance(x, str) for kv in deny_list.items() for x in kv)
|
|
184
|
+
):
|
|
185
|
+
raise TypeError('deny_list must be a dict of value: label, both str ({"Project Falcon": "CUSTOMER_ID"})')
|
|
186
|
+
if extra_rules is not None and not (
|
|
187
|
+
isinstance(extra_rules, list | tuple) and all(isinstance(r, Rule) for r in extra_rules)
|
|
188
|
+
):
|
|
189
|
+
raise TypeError("extra_rules must be a list of Rule")
|
|
190
|
+
asked = [*(labels or []), *(deny_list or {}).values(), *(r.label for r in extra_rules or [])]
|
|
191
|
+
if unknown := sorted(set(asked) - set(LABELS)):
|
|
192
|
+
raise ValueError(f"unknown labels {unknown}; known: {LABELS}")
|
|
193
|
+
limit = {"default": self.threshold if threshold is None else _threshold(threshold)}
|
|
194
|
+
if not texts: # an empty batch: nothing for a detector to read
|
|
195
|
+
return []
|
|
196
|
+
raw: list[list[Finding]] = [[] for _ in texts]
|
|
197
|
+
detectors = list(self.detectors)
|
|
198
|
+
if deny_list:
|
|
199
|
+
detectors.append(DenyListDetector(deny_list))
|
|
200
|
+
if extra_rules:
|
|
201
|
+
detectors.append(RuleDetector(extra_rules, timeout=EXTRA_RULE_TIMEOUT))
|
|
202
|
+
for d in detectors:
|
|
203
|
+
for i, found in enumerate(d.detect(texts)):
|
|
204
|
+
raw[i] += found
|
|
205
|
+
enabled = set(labels) if labels is not None else None
|
|
206
|
+
return [
|
|
207
|
+
resolve(t, found, enabled, limit, set(allow_list or ()) or None)
|
|
208
|
+
for t, found in zip(texts, raw, strict=True)
|
|
209
|
+
]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _action(a: ActionConfig | dict | str) -> ActionConfig:
|
|
213
|
+
return a if isinstance(a, ActionConfig) else ActionConfig.from_dict(a)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _texts(text: str | list[str]) -> list[str]:
|
|
217
|
+
"""The call's texts as a list. Anything that is not a str, or a list of str, stops here with a clear error."""
|
|
218
|
+
texts = [text] if isinstance(text, str) else text
|
|
219
|
+
if not isinstance(texts, list | tuple) or not all(isinstance(t, str) for t in texts):
|
|
220
|
+
raise TypeError("text must be a str or a list of str")
|
|
221
|
+
return list(texts)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _strings(name: str, values: object) -> None:
|
|
225
|
+
"""labels and allow_list: a list of str. One str is refused: it would be read letter by letter."""
|
|
226
|
+
if values is not None and not (
|
|
227
|
+
isinstance(values, list | tuple | set | frozenset) and all(isinstance(v, str) for v in values)
|
|
228
|
+
):
|
|
229
|
+
raise TypeError(f"{name} must be a list of str")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _threshold(value: float) -> float:
|
|
233
|
+
if isinstance(value, bool) or not isinstance(value, int | float) or not 0 <= value <= 1:
|
|
234
|
+
raise ValueError("threshold must be a number between 0 and 1")
|
|
235
|
+
return value
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _model(model: str, revision: str | None, **model_args) -> Detector:
|
|
239
|
+
try:
|
|
240
|
+
from grootveil.detectors.model import DEFAULT_MODEL, DEFAULT_REVISION, ModelDetector
|
|
241
|
+
except ImportError as e: # torch or transformers missing
|
|
242
|
+
raise ImportError(
|
|
243
|
+
"the model needs torch and transformers: pip install 'grootveil[transformers]'"
|
|
244
|
+
" (or Shield(model=None) for rules only)"
|
|
245
|
+
) from e
|
|
246
|
+
if model == MODEL:
|
|
247
|
+
model, revision = DEFAULT_MODEL, revision or DEFAULT_REVISION
|
|
248
|
+
elif Path(model).is_dir():
|
|
249
|
+
revision = None
|
|
250
|
+
try:
|
|
251
|
+
return ModelDetector(model, revision=revision, **model_args)
|
|
252
|
+
except OSError as e: # transformers only says "not a valid model identifier"
|
|
253
|
+
raise OSError(
|
|
254
|
+
f"cannot load the model {model!r}. Ours is private: set HF_TOKEN to a Hugging Face token with read access"
|
|
255
|
+
" to it, and check the network (the first run downloads about 2.4 GB). Or use Shield(model=None) for rules"
|
|
256
|
+
" only."
|
|
257
|
+
) from e
|