"""Detection, deterministic tokens, the vault's crypto, restore policies, streaming."""
from __future__ import annotations
import os
import random
import sqlite3
import pytest
from cryptography.exceptions import InvalidTag
from pii_proxy.detect import card_brand, find_pii, luhn_ok
from pii_proxy.masking import Context, StreamRestorer, mask_payload, mask_text, restore_payload, restore_text
from pii_proxy.samples import corpus
from pii_proxy.vault import Vault
FULL = {"SSN": "full", "CARD": "full"}
@pytest.fixture
def vault(tmp_path):
return Vault(tmp_path / "vault.db", os.urandom(32))
def ctx(vault, policy=FULL, tenant="acme", scope="s1", **kw):
return Context(vault, tenant, scope, policy, **kw)
# ── detection ──
@pytest.mark.parametrize("text,expected", [
("SSN 123-45-6789", [("SSN", "123456789")]),
("ssn: 123456789", [("SSN", "123456789")]),
("Visa 4111 1111 1111 1111 exp 08/29", [("CARD", "4111111111111111")]),
("Amex 3782 822463 10005", [("CARD", "378282246310005")]),
("card 4111-1111-1111-1111 then zip 1234", [("CARD", "4111111111111111")]),
("card 4111 1111 1111 1111 1234 Hamburg", [("CARD", "4111111111111111")]),
])
def test_finds_pii(text, expected):
assert [(f.kind, f.normalized) for f in find_pii(text)] == expected
@pytest.mark.parametrize("text", [
"Call 555-123-4567", "ZIP 94105-1234", "000-12-3456", "666-12-3456", "ITIN 912-78-1234",
"account 123456789", "order 1234 5678 9012 3452", "ref 4111 1111 1111 1112", "123-45 6789",
"IBAN DE89 3704 0044 0532 0130 00", "ISBN 978-3-16-148410-0",
])
def test_ignores_lookalikes(text):
assert find_pii(text) == []
def test_luhn_and_brands():
assert luhn_ok("4111111111111111") and not luhn_ok("4111111111111112")
assert card_brand("378282246310005") == "AMEX"
assert card_brand("2221000000000009") == "MASTERCARD"
assert card_brand("1234567812345670") == ""
def test_corpus_recall_is_total_and_precision_is_high():
tp = fp = fn = 0
for text, labels, _ in corpus(1000):
got = {(f.kind, f.normalized) for f in find_pii(text)}
want = set(labels)
tp, fp, fn = tp + len(got & want), fp + len(got - want), fn + len(want - got)
assert fn == 0, "a missed SSN or card is a compliance incident"
assert tp / (tp + fp) > 0.9
# ── deterministic tokens + vault ──
def test_same_value_same_token_any_format(vault):
c = ctx(vault)
a = mask_text("4111 1111 1111 1111", c)
b = mask_text("4111-1111-1111-1111", c)
assert a == b and a.startswith("[[CARD_VISA:")
def test_scopes_and_tenants_get_different_tokens(vault):
t = mask_text("123-45-6789", ctx(vault))
assert t != mask_text("123-45-6789", ctx(vault, scope="s2"))
assert t != mask_text("123-45-6789", ctx(vault, tenant="globex"))
def test_tokens_survive_a_restart_with_the_same_master_key(tmp_path):
key = os.urandom(32)
t1 = mask_text("123-45-6789", ctx(Vault(tmp_path / "v.db", key)))
v2 = Vault(tmp_path / "v.db", key)
assert mask_text("123-45-6789", ctx(v2)) == t1
assert restore_text(t1, ctx(v2)) == "123-45-6789"
def test_tokens_are_uuid_v8(vault):
token = mask_text("123-45-6789", ctx(vault)).split(":")[1].rstrip("]")
assert token[14] == "8" and token[19] in "89ab"
def test_ciphertext_is_bound_to_its_row(vault, tmp_path):
c = ctx(vault)
t1 = mask_text("123-45-6789", c).split(":")[1].rstrip("]")
t2 = mask_text("234-56-7891", c).split(":")[1].rstrip("]")
db = sqlite3.connect(tmp_path / "vault.db")
ct, nonce = db.execute("SELECT ciphertext, nonce FROM tokens WHERE token = ?", (t2,)).fetchone()
db.execute("UPDATE tokens SET ciphertext = ?, nonce = ? WHERE token = ?", (ct, nonce, t1))
db.commit()
with pytest.raises(InvalidTag): # swapping ciphertexts between rows is detected
vault.lookup("acme", "s1", t1)
def test_no_raw_values_in_the_vault_file(vault, tmp_path):
mask_text("SSN 123-45-6789 card 4111 1111 1111 1111", ctx(vault))
raw = (tmp_path / "vault.db").read_bytes() + (tmp_path / "vault.db-wal").read_bytes()
assert b"123456789" not in raw and b"4111111111111111" not in raw
def test_crypto_shredding_makes_tokens_unrecoverable(vault):
masked = mask_text("123-45-6789", ctx(vault))
vault.shred("acme")
assert restore_text(masked, ctx(vault)) == masked
assert mask_text("123-45-6789", ctx(vault)) != masked # a fresh key: the old token is unlinkable
# ── restore policies ──
def test_policies_full_last4_token(vault):
masked = mask_text("SSN 123-45-6789, Amex 3782 822463 10005", ctx(vault))
assert restore_text(masked, ctx(vault)) == "SSN 123-45-6789, Amex 3782 822463 10005"
assert restore_text(masked, ctx(vault, {"SSN": "last4", "CARD": "last4"})) == "SSN ***-**-6789, Amex AMEX •••• 0005"
assert restore_text(masked, ctx(vault, {"SSN": "token", "CARD": "token"})) == masked
def test_restore_tolerates_what_models_do_to_tokens(vault):
masked = mask_text("123-45-6789", ctx(vault))
uid = masked.split(":")[1].rstrip("]")
for variant in [uid, uid.upper(), f"[SSN:{uid}]", f"[[ SSN : {uid} ]]", f"[[{uid}]]", f"SSN:{uid}", f"SSN: {uid}"]:
assert restore_text(f"value {variant}.", ctx(vault)) == "value 123-45-6789."
def test_tokens_never_resolve_across_tenants_or_scopes(vault):
masked = mask_text("123-45-6789", ctx(vault))
assert restore_text(masked, ctx(vault, tenant="globex")) == masked
c = ctx(vault, scope="other")
assert restore_text(masked, c) == masked and c.unknown_tokens
def test_output_guard_removes_pii_the_model_invented(vault):
c = ctx(vault, {"SSN": "last4", "CARD": "last4"})
assert restore_text("Example: 219-09-9999", c) == "Example: [SSN REMOVED]"
assert c.unexpected["SSN"] == 1
# ── payloads ──
def test_every_content_string_is_masked_structure_is_not(vault):
body = {
"model": "x", "system": [{"type": "text", "text": "Customer SSN 123-45-6789"}],
"messages": [
{"role": "user", "content": [{"type": "text", "text": "card 4111 1111 1111 1111"}]},
{"role": "assistant", "content": None, "tool_calls": [{"id": "call_1", "type": "function",
"function": {"name": "refund", "arguments": '{"card": "4111111111111111", "amount": 5}'}}]},
{"role": "tool", "tool_call_id": "call_1", "content": "refunded to 4111 1111 1111 1111"},
],
"tools": [{"type": "function", "function": {"name": "refund", "description": "Refund to a card like 4111..."}}],
}
c = ctx(vault)
masked = mask_payload(body, c)
flat = repr(masked)
assert "123-45-6789" not in flat and "4111 1111 1111 1111" not in flat and "4111111111111111" not in flat
import json
assert json.loads(masked["messages"][1]["tool_calls"][0]["function"]["arguments"])["amount"] == 5 # still valid JSON
assert masked["model"] == "x" and masked["messages"][2]["tool_call_id"] == "call_1"
assert masked["tools"] == body["tools"]
assert restore_payload(masked, ctx(vault)) == {**body, "messages": [body["messages"][0],
{**body["messages"][1], "tool_calls": [{**body["messages"][1]["tool_calls"][0], "function": {"name": "refund", "arguments": '{"card": "4111 1111 1111 1111", "amount": 5}'}}]},
body["messages"][2]]}
# ── streaming ──
def test_streaming_restore_equals_batch_restore_for_every_chunking(vault):
c = ctx(vault, {"SSN": "last4", "CARD": "full"})
text = mask_text("Hi [note] SSN 123-45-6789 and card 4111 1111 1111 1111; see [docs](x) cafe 42.", c)
expected = restore_text(text, ctx(vault, {"SSN": "last4", "CARD": "full"}))
rng = random.Random(3)
for trial in range(300):
pieces, i = [], 0
while i < len(text):
n = rng.randint(1, 9) if trial else 1 # trial 0: one character at a time
pieces.append(text[i:i + n])
i += n
r = StreamRestorer(ctx(vault, {"SSN": "last4", "CARD": "full"}))
assert "".join(r.feed(p) for p in pieces) + r.flush() == expected
def test_streaming_unbracketed_tokens_keep_no_stray_tag():
"""A real model (qwen3:4b) answered with "SSN:<uuid>" (no brackets) in a stream.
200 random keys, so UUIDs that start or end with digits are covered too."""
for seed in range(200):
v = Vault(":memory:", os.urandom(32))
c = ctx(v)
uid = mask_text("123-45-6789", c).split(":")[1].rstrip("]")
text = f"Customer SSN:{uid} confirmed."
rng = random.Random(seed)
r, out, i = StreamRestorer(ctx(v)), [], 0
while i < len(text):
n = rng.randint(1, 6)
out.append(r.feed(text[i:i + n]))
i += n
assert "".join(out) + r.flush() == "Customer 123-45-6789 confirmed.", uid
def test_streaming_guard_catches_raw_pii_split_across_chunks(vault):
r = StreamRestorer(ctx(vault, {"SSN": "last4", "CARD": "last4"}))
out = "".join(r.feed(p) for p in ["Try 4111 ", "1111 ", "1111 11", "11 now"]) + r.flush()
assert out == "Try [CARD REMOVED] now"