"""Find and replace personal data and secrets in text, on the CPU. The tagger is egemma-pii-secrets' int8 ONNX model, read with onnxruntime and tokenizers. The rules are the model's vendored trace_rules plus albedo's overlay. Offsets are code points (Unicode scalars) in Python strings. """ from __future__ import annotations from collections import OrderedDict from collections.abc import Callable, Sequence from dataclasses import dataclass import hashlib import hmac import json import os from pathlib import Path import re import secrets from . import overlay, trace_rules LABELS = ( "PERSON", "ADDRESS", "GOV_ID", "EMAIL", "FINANCIAL", "PHONE", "SENSITIVE", "DATE_OF_BIRTH", "IP_ADDRESS", "SECRET_TOKEN", "SECRET_PASSWORD", "SECRET_CONNECTION", "SECRET_PRIVATE_KEY", ) TAGS = ("O", *(f"{p}-{label}" for label in LABELS for p in "BI")) CATEGORIES = tuple(label.lower() for label in (*LABELS, "OPAQUE_BLOB")) WINDOW, STRIDE = 512, 128 MODEL_FILE, TOKENIZER_FILE = "tagger.int8.onnx", "tokenizer.json" MANIFEST = Path(__file__).resolve().parents[2] / "export" / "tagger.json" CATEGORY = re.compile(r"[a-z0-9_]{1,64}") _STOP_L = set(" \t\n\r'\"`=:(<[{,") _STOP_R = set(" \t\n\r'\"`&,;)]}>") Progress = Callable[[int], None] class EngineError(Exception): """A failure named by its code alone; it never carries input text.""" def __init__(self, code: str): super().__init__(code) self.code = code @dataclass(frozen=True) class Keep: """A range of the input to copy unchanged, such as an exact-match marker.""" start: int end: int category: str @dataclass(frozen=True) class Span: """A range of the output: a marker the engine wrote, or a copied keep.""" start: int end: int category: str source: str # "model", "rule" or "keep" def manifest(path: Path = MANIFEST) -> dict: """The pinned model manifest; `pins` maps each file name to its entry.""" data = json.loads(path.read_text()) data["pins"] = {f["name"]: f for f in data["files"]} return data def spans_from(tags: Sequence[int], offsets: Sequence[tuple[int, int]], text: str): """Character spans of one window's tags, as redact.py at the pinned revision joins them: B/I runs, trimmed, secrets widened to the whole token.""" found: list[dict] = [] current: dict | None = None for tag, (a, b) in zip(tags, offsets): if a == b: continue name = TAGS[tag] if name == "O": current = None continue prefix, label = name.split("-", 1) if ( current and current["label"] == label and (prefix == "I" or a <= current["end"] + 1) ): current["end"] = b else: current = {"start": a, "end": b, "label": label} found.append(current) trimmed = [] for s in found: a, b = s["start"], s["end"] while a < b and text[a] in " \t\n\r'\"": a += 1 while b > a and text[b - 1] in " \t\n\r'\",;": b -= 1 if a < b: trimmed.append({"start": a, "end": b, "label": s["label"]}) out: list[dict] = [] for s in sorted(trimmed, key=lambda s: s["start"]): if s["label"].startswith("SECRET_") and s["label"] != "SECRET_PRIVATE_KEY": a, b = s["start"], s["end"] while a > 0 and text[a - 1] not in _STOP_L: a -= 1 while b < len(text) and text[b] not in _STOP_R: b += 1 if b > a and text[b - 1] == "." and (b == len(text) or text[b].isspace()): b -= 1 s = {**s, "start": a, "end": b} if ( out and s["label"].startswith("SECRET_") and out[-1]["label"].startswith("SECRET_") and s["start"] < out[-1]["end"] ): out[-1]["end"] = max(out[-1]["end"], s["end"]) continue out.append(s) return out def merge(spans: list[dict]) -> list[dict]: """Union of overlapping spans; a secret label wins over a PII label, and the sources of every span merged in are kept.""" out: list[dict] = [] for s in sorted(spans, key=lambda s: (s["start"], -s["end"])): if out and s["start"] < out[-1]["end"]: top = out[-1] top["end"] = max(top["end"], s["end"]) if s["label"].startswith("SECRET_") and not top["label"].startswith( "SECRET_" ): top["label"] = s["label"] top["sources"] |= s["sources"] continue out.append({**s, "sources": set(s["sources"])}) return out class Tagger: """The ONNX tagger on the CPU, over 512-token windows that overlap by 128.""" def __init__(self, model_dir: Path, threads: int, pins: dict[str, dict]): model_dir = Path(model_dir) for name in (MODEL_FILE, TOKENIZER_FILE): _verify(model_dir / name, pins.get(name)) try: import numpy import onnxruntime from tokenizers import Tokenizer except ImportError: raise EngineError("runtime_missing") from None self._numpy = numpy try: onnxruntime.set_default_logger_severity(3) options = onnxruntime.SessionOptions() options.intra_op_num_threads = max(1, threads) options.inter_op_num_threads = 1 options.execution_mode = onnxruntime.ExecutionMode.ORT_SEQUENTIAL options.log_severity_level = 3 self._session = onnxruntime.InferenceSession( str(model_dir / MODEL_FILE), options, providers=["CPUExecutionProvider"], ) tokenizer = Tokenizer.from_file(str(model_dir / TOKENIZER_FILE)) tokenizer.no_padding() tokenizer.enable_truncation(max_length=WINDOW, stride=STRIDE) self._tokenizer = tokenizer except Exception: raise EngineError("model_invalid") from None if self._session.get_providers() != ["CPUExecutionProvider"]: raise EngineError("internal") self.windows("hello") def windows(self, text: str, progress: Progress | None = None) -> list[dict]: """Model spans of `text`, from every window through the tail.""" try: first = self._tokenizer.encode(text) except Exception: raise EngineError("inference_failed") from None found: list[dict] = [] for window in (first, *first.overflowing): ids = self._numpy.asarray([window.ids], dtype=self._numpy.int64) try: logits = self._session.run( None, {"input_ids": ids, "attention_mask": self._numpy.ones_like(ids)}, )[0] except Exception: raise EngineError("inference_failed") from None if logits.shape != (1, len(window.ids), len(TAGS)): raise EngineError("inference_failed") tags = logits[0].argmax(-1).tolist() found += spans_from(tags, window.offsets, text) if progress: progress(max((b for _, b in window.offsets), default=0)) return found class Engine: """Redacts strings for one export: its markers are numbered across every string it sees, so one value keeps one marker for the whole export.""" def __init__(self, tagger, cache_chars: int = 16 * 1024 * 1024): self._tagger = tagger self._key = secrets.token_bytes(32) self._numbers: dict[bytes, int] = {} self._counts: dict[str, int] = {} # Repeated strings (a file read twice, a tool result quoted back) are # tagged once. Bounded by the characters of the cleaned strings held. self._cache: OrderedDict[bytes, tuple[str, tuple[Span, ...]]] = OrderedDict() self._cache_chars = cache_chars self._cached = 0 def _digest(self, *parts: str) -> bytes: message = b"".join( len(data).to_bytes(8, "big") + data for data in (part.encode("utf-8", "surrogatepass") for part in parts) ) return hmac.digest(self._key, message, hashlib.sha256) def marker(self, category: str, value: str) -> str: key = self._digest(category, value) number = self._numbers.get(key) if number is None: number = self._counts.get(category, 0) + 1 self._counts[category] = number self._numbers[key] = number return f"[REDACTED:{category}#{number}]" def found(self, text: str, progress: Progress | None = None) -> list[dict]: """Merged rule and model spans in `text`, after the vendored veto.""" model = self._tagger.windows if self._tagger else None found = [] if model: found += [{**s, "sources": {"model"}} for s in model(text, progress)] inner = (lambda inside: model(inside)) if model else None ruled = trace_rules.rule_spans(text, inner=inner) + overlay.spans(text) found += [{**s, "sources": {"rule"}} for s in ruled] kept = trace_rules.apply_veto(found, text) # Unreadable base64 is redacted rather than only listed for review, # unless the veto knows it as a public shape, such as an ssh key. public = trace_rules.veto_ranges(text) for s in trace_rules.opaque_blobs(text): covered = sum( max(0, min(e, s["end"]) - max(b, s["start"])) for b, e in public ) if covered < 0.8 * (s["end"] - s["start"]): kept.append({**s, "sources": {"rule"}}) return merge(kept) def redact( self, text: str, keep: Sequence[Keep] = (), progress: Progress | None = None ) -> tuple[str, tuple[Span, ...]]: """`text` with every finding replaced by its marker and every keep range copied, and the spans of both in the output.""" keep = sorted(keep, key=lambda k: k.start) _check(text, keep) cache_key = self._digest( text, *(f"{k.start}:{k.end}:{k.category}" for k in keep) ) cached = self._cache.get(cache_key) if cached is not None: self._cache.move_to_end(cache_key) return cached pieces = [] for s in self.found(text, progress): for a, b in _outside(s["start"], s["end"], keep): source = "rule" if "rule" in s["sources"] else "model" pieces.append((a, b, s["label"].lower(), source)) pieces += [(k.start, k.end, k.category, "keep") for k in keep] out, spans, position = [], [], 0 length = 0 for a, b, category, source in sorted(pieces): out.append(text[position:a]) length += a - position value = text[a:b] if source == "keep" else self.marker(category, text[a:b]) out.append(value) spans.append(Span(length, length + len(value), category, source)) length += len(value) position = b out.append(text[position:]) result = ("".join(out), tuple(spans)) if len(result[0]) <= self._cache_chars // 8: self._cache[cache_key] = result self._cached += len(result[0]) while self._cached > self._cache_chars: _, (evicted, _) = self._cache.popitem(last=False) self._cached -= len(evicted) return result def _verify(path: Path, pin: dict | None) -> None: """Refuses a model file that is missing or differs from its pin.""" if pin is None: raise EngineError("model_invalid") try: size = path.stat().st_size except OSError: raise EngineError("model_missing") from None if size != pin["bytes"]: raise EngineError("model_invalid") digest = hashlib.sha256() try: with path.open("rb") as file: while chunk := file.read(1 << 20): digest.update(chunk) except OSError: raise EngineError("model_missing") from None if not hmac.compare_digest(digest.hexdigest(), pin["sha256"]): raise EngineError("model_invalid") def _check(text: str, keep: Sequence[Keep]) -> None: try: text.encode("utf-8") except UnicodeEncodeError: raise EngineError("invalid_request") from None end = 0 for k in keep: if not (end <= k.start < k.end <= len(text)) or not CATEGORY.fullmatch( k.category ): raise EngineError("invalid_request") end = k.end def _outside(start: int, end: int, keep: Sequence[Keep]): """The parts of [start, end) that no keep range covers.""" for k in keep: if k.end <= start or k.start >= end: continue if k.start > start: yield start, k.start start = max(start, k.end) if start < end: yield start, end def threads(default: int = 2) -> int: """The ONNX thread count from ALBEDO_REDACT_THREADS, at most the CPU count.""" try: wanted = int(os.environ.get("ALBEDO_REDACT_THREADS", default)) except ValueError: wanted = default return max(1, min(wanted, os.cpu_count() or 1))