Skip to content

API reference

This page is generated directly from the docstrings in spanguard's source, so it never drifts out of sync with the code. All nine names below are importable straight from the top-level package:

from spanguard import (
    Redactor,
    Policy,
    RedactionResult,
    Span,
    AuditRecord,
    Recognizer,
    Keyring,
    StreamRedactor,
    StreamBufferFullError,
)

Core

The three types you touch on nearly every call: configure a Policy, run it through a Redactor, and get back a RedactionResult.

Redactor

Redactor

Redactor(policy: Policy, recognizers: list[Recognizer] | None = None, *, hmac_key: bytes | None = None, tokenize_key: bytes | None = None)

Detect and redact PII/PHI in text according to a Policy.

reveal

reveal(text: str, keyring: Keyring | None = None) -> str

Restore tokenized values using keyring (defaults to this Redactor's).

Policy

Policy

Bases: BaseModel

Immutable, serializable redaction policy.

policy_hash

policy_hash() -> str

Stable content-addressed hash of the policy for the audit record.

RedactionResult

RedactionResult dataclass

RedactionResult(text: str, audit: AuditRecord, spans: list[Span] = list())

Result of a redaction: transformed text, its audit, and the spans.

Types

Value objects returned as part of a RedactionResult.

Span

Span dataclass

Span(type: str, start: int, end: int)

A detected sensitive region: entity type over half-open [start, end).

type is a fixed entity label (e.g. "EMAIL"), never the matched value — it appears verbatim in the audit record's counts and in placeholder output.

AuditRecord

AuditRecord dataclass

AuditRecord(counts: dict[str, int], policy_hash: str, ts: str)

Per-operation audit trail. Contains counts only — never raw values.

Extensibility

Implement this protocol to plug a custom detector into a Redactor — see Recognizers for a full worked example.

Recognizer

Recognizer

Bases: Protocol

A detector for one entity type. Users implement this to add detectors.

Contract: entity_type (and the type field of every Span returned) MUST be a fixed, non-sensitive entity label (e.g. "EMAIL", "PHONE"), never a value derived from the matched text. The label appears verbatim in placeholder output ([EMAIL]) and as a key in the audit record's counts; putting matched content in it would leak raw data into redacted output and audit records.

entity_type instance-attribute

entity_type: str

Fixed entity label for this recognizer. See class contract above: never derive this from matched text.

recognize

recognize(text: str) -> list[Span]

Return non-overlapping spans of entity_type found in text.

Reversible redaction

Backs tokenize mode's Redactor.reveal().

Keyring

Keyring

Keyring(tokenize_key: bytes)

Holds the tokenize key and an in-memory token->raw map for reveal().

The key and the map are never exposed via repr/str, so a Keyring can be logged without leaking secrets or raw values.

reveal

reveal(text: str) -> str

Replace every token this keyring issued with its original value.

Substitution is a single left-to-right pass (one re.sub over an alternation of all issued tokens), so a raw value that happens to contain another issued token's string is never re-expanded.

Streaming

Redacts text that arrives in chunks — see Streaming for the split-equals-one-shot guarantee.

StreamRedactor

StreamRedactor

StreamRedactor(redactor: Redactor, tail: int = _DEFAULT_TAIL, max_buffer: int | None = None)

Redact a text arriving in chunks, holding back a tail so an entity split across a boundary is still redacted as one.

Guarantee: for any chunking, the concatenation of all feed() outputs plus flush() equals redactor.redact(full_text).text -- for every mode (mask, placeholder, hash, tokenize) with the same keys.

Memory: text is emitted only up to a whitespace character that no entity straddles, so while the stream keeps supplying such separators the buffer stays near tail plus one chunk. A stream without one (a long base64 blob, or whitespace only inside a phone number) is held until one arrives or flush() is called. Pass max_buffer to cap that: a feed() that leaves more than max_buffer characters held and can emit nothing raises StreamBufferFullError. (A feed that does emit may still leave the buffer over the cap; the next feed that cannot emit raises.)

tail must be >= _MIN_TAIL (64), which is enforced. An entity longer than tail with no internal separators (e.g. an email or an API key) degrades gracefully to a word-boundary split. The floor exists specifically to prevent a sub-threshold leak of entities that DO contain internal separators (e.g. a spaced credit card number): below the floor, the buffer never holds enough of the entity for detection to fire, so every whitespace cut looks safe and the raw value streams out unmasked in pieces.

StreamBufferFullError

StreamBufferFullError

Bases: Exception

Raised by StreamRedactor.feed when the held-back buffer exceeds max_buffer and no point to emit up to is safe yet.

The chunk passed to that feed() has already been accepted, so do not feed it again. The buffer is kept intact: call flush() to redact and emit everything held so far (an entity still arriving may then be split), or discard the redactor.