Public release
This commit is contained in:
+7
-1
@@ -1,6 +1,7 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
ARG INSTALL_NER=false
|
||||
ARG INSTALL_DOCS=false
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
@@ -17,9 +18,14 @@ COPY rules ./rules
|
||||
COPY src ./src
|
||||
|
||||
RUN pip install --no-cache-dir --upgrade pip && \
|
||||
if [ "$INSTALL_NER" = "true" ]; then \
|
||||
if [ "$INSTALL_NER" = "true" ] && [ "$INSTALL_DOCS" = "true" ]; then \
|
||||
pip install --no-cache-dir ".[ner,docs]" && \
|
||||
python -m spacy download en_core_web_sm; \
|
||||
elif [ "$INSTALL_NER" = "true" ]; then \
|
||||
pip install --no-cache-dir ".[ner]" && \
|
||||
python -m spacy download en_core_web_sm; \
|
||||
elif [ "$INSTALL_DOCS" = "true" ]; then \
|
||||
pip install --no-cache-dir ".[docs]"; \
|
||||
else \
|
||||
pip install --no-cache-dir .; \
|
||||
fi
|
||||
|
||||
@@ -5,13 +5,14 @@ A zero-egress local MCP server and in-memory vault for redacting state-work PII
|
||||
## Architecture
|
||||
|
||||
- **Persistent Docker Vault (`network_mode: none`, `tmpfs` RAM only):** Holds session placeholder mappings (`<<REDACT:PII_SSN:a9f3:1>>` or format-preserving synthetic tokens like `900-00-0001`) strictly in memory with TTL expiration and zero network access.
|
||||
- **Schema / Key-Aware Redaction:** Automatically redacts sensitive keys/columns (names, DOBs, SSNs, Medicaid/case IDs, secrets) in `.json`, `.jsonl`, `.csv`, `.tsv`, and SQL `INSERT` dumps.
|
||||
- **Schema / Key-Aware & Document Redaction:** Automatically redacts sensitive keys/columns (names, DOBs, SSNs, Medicaid/case IDs, secrets) in `.json`, `.jsonl`, `.csv`, `.tsv`, and SQL `INSERT` dumps, plus extracts and redacts text/tables from `.pdf`, `.docx`, and `.xlsx` files.
|
||||
- **Scrubbed Execution (`vault_run_scrubbed`):** Runs test suites or linters strictly inside `clean-staging/` and scrubs any secrets/PII from `stdout`/`stderr` before returning output.
|
||||
- **Batch Output Sync & Auto-Watch:** `vault_sync_output` batch-rehydrates `clean-staging/` into `final-output/`, and `redactor-mcp watch <dir>` polls `sensitive/` (WSL2 `/mnt/c/` safe) to auto-stage new files.
|
||||
- **Allowlists & `.redactorignore`:** Skip noisy lockfiles/assets and allowlist known benign placeholder strings.
|
||||
- **Compliance Audit & Encrypted Pause/Resume:** Append-only non-secret JSONL audit log (`REDACTOR_AUDIT_LOG`) plus AES-256 encrypted `snapshot-save` / `snapshot-load` CLI commands.
|
||||
- **MCP `stdio` Bridge (`docker exec -i`):** Both Antigravity and Amazon Kiro connect over `stdio` via `wsl.exe` into the same running container, sharing the same session vault without opening any TCP ports.
|
||||
- **One-Way Egress:** `vault_write_file` and `vault_rehydrate_file` restore placeholders back into real values **only** when writing to approved `final-output/` paths (never `clean-staging/`), and return only byte/token counts—never raw secrets—to the agent.
|
||||
- **Client Guardrails:** Antigravity `hooks.json` / `hooks.windows.json` (`scripts/hooks/agy_guard.py`) blocks native `read_file`/`run_command` access to protected paths, sensitive filenames (`credentials.json`, `.env`), and secret extensions (`.pem`, `.key`, `.pfx`, `.kdbx`) via `PreToolUse`, and halts before model calls on pasted SSNs/keys (`PreInvocation`).
|
||||
- **One-Way Egress:** `vault_write_file`, `vault_rehydrate_file`, and `vault_sync_output` restore placeholders back into real values **only** when writing to approved `final-output/` paths (never `clean-staging/` or symlinks), and return only byte/token counts—never raw secrets—to the agent.
|
||||
- **Antigravity Plugin & Guardrails:** Drop-in [plugins/redactor-vault](plugins/redactor-vault/plugin.json) bundle (MCP config + `PreToolUse`/`PreInvocation` hooks + rule + skill), plus standalone `hooks.json` / `hooks.windows.json` templates.
|
||||
|
||||
## Quick Start (Windows + WSL2 + Docker)
|
||||
|
||||
|
||||
@@ -5,8 +5,16 @@ services:
|
||||
args:
|
||||
# Set to "true" at build time if you want offline Presidio + spaCy NER for unstructured text
|
||||
INSTALL_NER: "false"
|
||||
# Set to "true" at build time for PDF/DOCX/XLSX extraction (pypdf, python-docx, openpyxl)
|
||||
INSTALL_DOCS: "false"
|
||||
container_name: pii-redactor
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "redactor-mcp", "status"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 5s
|
||||
# Zero network egress: container cannot phone home or leak PII over the network
|
||||
network_mode: none
|
||||
read_only: true
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"redactor-guard": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "read_file|view_file|write_file|edit_file|run_command|list_dir|grep_search|find_by_name",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 ./hooks/guard.py --mode pre-tool",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreInvocation": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 ./hooks/guard.py --mode pre-invocation",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Self-contained Antigravity plugin hook entrypoint for `redactor-vault`."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
# Locate repo `scripts/hooks/agy_guard.py` when running inside the redactor-mcp repo
|
||||
_PLUGIN_DIR = Path(__file__).resolve().parents[1]
|
||||
_REPO_GUARD = _PLUGIN_DIR.parents[1] / "scripts" / "hooks" / "agy_guard.py"
|
||||
|
||||
if _REPO_GUARD.is_file():
|
||||
_spec = importlib.util.spec_from_file_location("agy_guard", _REPO_GUARD)
|
||||
assert _spec is not None and _spec.loader is not None
|
||||
_mod = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(_mod)
|
||||
handle_pre_tool = _mod.handle_pre_tool
|
||||
handle_pre_invocation = _mod.handle_pre_invocation
|
||||
else:
|
||||
# Standalone fallback when plugin folder is copied outside the repository
|
||||
_PROTECTED_MARKERS = ("sensitive", "final-output", ".env")
|
||||
_PROTECTED_EXTS = (".pem", ".key", ".pfx", ".p12", ".kdbx", ".jks", ".keystore", ".ppk")
|
||||
_FILE_TOOLS = {
|
||||
"read_file", "view_file", "write_file", "edit_file",
|
||||
"replace_file_content", "multi_replace_file_content",
|
||||
"write_to_file", "run_command", "list_dir", "grep_search", "find_by_name",
|
||||
}
|
||||
_FALLBACK_PATTERNS = {
|
||||
"PII_SSN": re.compile(r"(?<![0-9-])\d{3}-\d{2}-\d{4}(?![0-9-])"),
|
||||
"SECRET_AWS_KEY": re.compile(r"\b(?:AKIA|ASIA|AROA|AIDA)[0-9A-Z]{16}\b"),
|
||||
"SECRET_PRIVATE_KEY": re.compile(r"-{5}BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-{5}"),
|
||||
}
|
||||
|
||||
def handle_pre_tool(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
tc = payload.get("toolCall") or {}
|
||||
if str(tc.get("name", "")) not in _FILE_TOOLS:
|
||||
return {"decision": "allow"}
|
||||
blob = json.dumps(tc.get("args") or {}).lower()
|
||||
for m in _PROTECTED_MARKERS + _PROTECTED_EXTS:
|
||||
if m in blob:
|
||||
return {
|
||||
"decision": "deny",
|
||||
"reason": f"Protected path/extension '{m}': use redactor-vault MCP tools instead.",
|
||||
}
|
||||
return {"decision": "allow"}
|
||||
|
||||
def handle_pre_invocation(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
text = str(payload.get("lastUserInput") or "")
|
||||
found = [cat for cat, pat in _FALLBACK_PATTERNS.items() if pat.search(text)]
|
||||
if not found:
|
||||
return {}
|
||||
return {
|
||||
"injectSteps": [
|
||||
{
|
||||
"errorMessage": {
|
||||
"userMessage": f"Blocked before model call: detected {', '.join(found)}. Sanitize first."
|
||||
}
|
||||
}
|
||||
],
|
||||
"terminationBehavior": "terminate",
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="redactor-vault plugin hook")
|
||||
parser.add_argument("--mode", required=True, choices=["pre-tool", "pre-invocation"])
|
||||
args = parser.parse_args(argv)
|
||||
raw = sys.stdin.read().strip()
|
||||
payload = json.loads(raw) if raw else {}
|
||||
out = handle_pre_tool(payload) if args.mode == "pre-tool" else handle_pre_invocation(payload)
|
||||
sys.stdout.write(json.dumps(out))
|
||||
sys.stdout.flush()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"redactor-vault": {
|
||||
"command": "wsl.exe",
|
||||
"args": [
|
||||
"-d",
|
||||
"Ubuntu",
|
||||
"--",
|
||||
"docker",
|
||||
"exec",
|
||||
"-i",
|
||||
"pii-redactor",
|
||||
"redactor-mcp",
|
||||
"mcp"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "redactor-vault",
|
||||
"author": "Knick",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://git.knickqueue.win/Knick/redactor-mcp"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# Redactor Vault Policy
|
||||
|
||||
- **Never** read or inspect files inside `sensitive/`, `final-output/`, `.env*`, or key files (`.pem`, `.key`, `.pfx`, `.p12`, `.kdbx`) directly using native file or shell tools.
|
||||
- Always read sensitive files and documents (`.pdf`, `.docx`, `.xlsx`, `.csv`, `.json`, `.sql`) via `redactor-vault` MCP (`vault_read_file` or `vault_stage_workspace`).
|
||||
- Perform edits, debugging, and scrubbed test runs (`vault_run_scrubbed`) inside `clean-staging/`.
|
||||
- Restore placeholders strictly into `final-output/` using `vault_write_file`, `vault_rehydrate_file`, or `vault_sync_output`. Never ask to echo unredacted secrets into chat.
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: redactor-workflow
|
||||
description: >-
|
||||
How to work safely on sensitive state-work datasets and codebases using the
|
||||
redactor-vault MCP server (staging, scrubbed tests, and one-way rehydration).
|
||||
---
|
||||
|
||||
# Redactor Vault Workflow
|
||||
|
||||
1. **Stage or Read Through the Vault:**
|
||||
- For a codebase or folder: call `vault_stage_workspace(src_dir=..., profile="swe")` (or `"strict"` for state datasets; set `format_preserving=True` when schema/regex validators require synthetic formats).
|
||||
- For single files or documents (`.pdf`, `.docx`, `.xlsx`, `.csv`, `.json`, `.sql`): call `vault_read_file(path=...)`.
|
||||
2. **Work & Test in `clean-staging/`:**
|
||||
- Edit sanitized files inside `clean-staging/`.
|
||||
- Run tests/linters via `vault_run_scrubbed(command=...)` so any PII/secrets printed to stdout/stderr are redacted before reaching context.
|
||||
3. **One-Way Egress to `final-output/`:**
|
||||
- Single file: call `vault_rehydrate_file(clean_path=..., dest_path=...)` or `vault_write_file(content=..., dest_path=...)`.
|
||||
- Whole directory: call `vault_sync_output(session_id=...)`.
|
||||
4. **End of Task:**
|
||||
- Use `vault_session_status` to audit redacted token counts, and `vault_purge_session` when finished.
|
||||
@@ -20,6 +20,11 @@ ner = [
|
||||
"presidio-analyzer>=2.2.35",
|
||||
"spacy>=3.7.0",
|
||||
]
|
||||
docs = [
|
||||
"pypdf>=5.0",
|
||||
"python-docx>=1.1",
|
||||
"openpyxl>=3.1",
|
||||
]
|
||||
dev = [
|
||||
"pytest>=8.0",
|
||||
]
|
||||
|
||||
@@ -10,6 +10,7 @@ from pathlib import Path
|
||||
from redactor_mcp.client import VaultClient
|
||||
from redactor_mcp.daemon import run_daemon
|
||||
from redactor_mcp.server import run_mcp_stdio
|
||||
from redactor_mcp.watcher import watch_directory
|
||||
|
||||
|
||||
def _read_input_text(file_arg: str | None) -> str:
|
||||
@@ -69,6 +70,20 @@ def main(argv: list[str] | None = None) -> int:
|
||||
p_purge = sub.add_parser("purge", help="Purge vault session(s) from RAM.")
|
||||
p_purge.add_argument("--session", default=None, help="Optional session ID (all if omitted).")
|
||||
|
||||
p_sync = sub.add_parser("sync-output", help="Batch rehydrate clean-staging into final-output.")
|
||||
p_sync.add_argument("--clean-dir", default="", help="Staging dir (optional if REDACTOR_STAGING_ROOT is set).")
|
||||
p_sync.add_argument("--output-dir", default="", help="Output dir (optional if REDACTOR_OUTPUT_ROOTS is set).")
|
||||
p_sync.add_argument("--session", default="default", help="Vault session ID.")
|
||||
|
||||
p_watch = sub.add_parser("watch", help="Watch sensitive directory and auto-stage changes into clean-staging.")
|
||||
p_watch.add_argument("src_dir", help="Source directory to watch.")
|
||||
p_watch.add_argument("--clean-dir", default="", help="Staging dir (optional if REDACTOR_STAGING_ROOT is set).")
|
||||
p_watch.add_argument("--session", default="default", help="Vault session ID.")
|
||||
p_watch.add_argument("--profile", default="swe", choices=["strict", "pii", "swe"])
|
||||
p_watch.add_argument("--format-preserving", action="store_true", help="Emit reserved synthetic tokens.")
|
||||
p_watch.add_argument("--interval", type=float, default=1.5, help="Poll interval in seconds.")
|
||||
p_watch.add_argument("--once", action="store_true", help="Run a single sync pass and exit.")
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.command == "daemon":
|
||||
@@ -139,6 +154,32 @@ def main(argv: list[str] | None = None) -> int:
|
||||
print(json.dumps(res, indent=2))
|
||||
return 0
|
||||
|
||||
if args.command == "sync-output":
|
||||
res = client.call(
|
||||
"sync_output",
|
||||
{
|
||||
"clean_dir": args.clean_dir,
|
||||
"output_dir": args.output_dir,
|
||||
"session_id": args.session,
|
||||
},
|
||||
)
|
||||
print(json.dumps(res, indent=2))
|
||||
return 0
|
||||
|
||||
if args.command == "watch":
|
||||
watch_directory(
|
||||
src_dir=args.src_dir,
|
||||
clean_dir=args.clean_dir,
|
||||
session_id=args.session,
|
||||
profile=args.profile,
|
||||
format_preserving=args.format_preserving,
|
||||
interval=args.interval,
|
||||
max_iterations=1 if args.once else None,
|
||||
client=client,
|
||||
on_sync=lambda report: print(json.dumps(report), flush=True),
|
||||
)
|
||||
return 0
|
||||
|
||||
return 1
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
SUPPORTED_DOCUMENT_EXTENSIONS = {".pdf", ".docx", ".xlsx"}
|
||||
|
||||
|
||||
def is_supported_document(path: Path) -> bool:
|
||||
return path.suffix.lower() in SUPPORTED_DOCUMENT_EXTENSIONS
|
||||
|
||||
|
||||
def extract_pdf_text(path: Path) -> str:
|
||||
try:
|
||||
from pypdf import PdfReader # type: ignore
|
||||
except ImportError as exc:
|
||||
raise RuntimeError(
|
||||
"PDF extraction requires `pypdf`. Install with `pip install 'redactor-mcp[docs]'` "
|
||||
"or build Docker with `INSTALL_DOCS=true`."
|
||||
) from exc
|
||||
|
||||
reader = PdfReader(str(path))
|
||||
pages: list[str] = []
|
||||
for idx, page in enumerate(reader.pages, start=1):
|
||||
text = page.extract_text() or ""
|
||||
pages.append(f"--- Page {idx} ---\n{text}")
|
||||
return "\n\n".join(pages)
|
||||
|
||||
|
||||
def _extract_docx_stdlib(path: Path) -> str:
|
||||
"""Zero-dependency fallback extracting paragraphs and table rows from DOCX XML."""
|
||||
ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
|
||||
with zipfile.ZipFile(path, "r") as zf:
|
||||
xml_bytes = zf.read("word/document.xml")
|
||||
root = ET.fromstring(xml_bytes)
|
||||
lines: list[str] = []
|
||||
body = root.find("w:body", ns)
|
||||
if body is None:
|
||||
return ""
|
||||
for child in body:
|
||||
tag = child.tag.rsplit("}", 1)[-1]
|
||||
if tag == "p":
|
||||
texts = [t.text for t in child.findall(".//w:t", ns) if t.text]
|
||||
if texts:
|
||||
lines.append("".join(texts))
|
||||
elif tag == "tbl":
|
||||
for row in child.findall(".//w:tr", ns):
|
||||
cells: list[str] = []
|
||||
for cell in row.findall("./w:tc", ns):
|
||||
c_texts = [t.text for t in cell.findall(".//w:t", ns) if t.text]
|
||||
cells.append("".join(c_texts).strip())
|
||||
if any(cells):
|
||||
lines.append(" | ".join(cells))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def extract_docx_text(path: Path) -> str:
|
||||
try:
|
||||
import docx # type: ignore
|
||||
except ImportError:
|
||||
return _extract_docx_stdlib(path)
|
||||
|
||||
doc = docx.Document(str(path))
|
||||
parts: list[str] = []
|
||||
for para in doc.paragraphs:
|
||||
if para.text.strip():
|
||||
parts.append(para.text)
|
||||
for table in doc.tables:
|
||||
for row in table.rows:
|
||||
cells = [c.text.strip().replace("\n", " ") for c in row.cells]
|
||||
if any(cells):
|
||||
parts.append(" | ".join(cells))
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def _extract_xlsx_stdlib(path: Path) -> str:
|
||||
"""Zero-dependency fallback extracting sheets and cells from XLSX XML."""
|
||||
main_ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
|
||||
ns = {"s": main_ns}
|
||||
with zipfile.ZipFile(path, "r") as zf:
|
||||
shared_strings: list[str] = []
|
||||
if "xl/sharedStrings.xml" in zf.namelist():
|
||||
ss_root = ET.fromstring(zf.read("xl/sharedStrings.xml"))
|
||||
for si in ss_root.findall("s:si", ns):
|
||||
t_parts = [t.text for t in si.findall(".//s:t", ns) if t.text]
|
||||
shared_strings.append("".join(t_parts))
|
||||
|
||||
sheet_names: list[str] = []
|
||||
if "xl/workbook.xml" in zf.namelist():
|
||||
wb_root = ET.fromstring(zf.read("xl/workbook.xml"))
|
||||
for sh in wb_root.findall(".//s:sheet", ns):
|
||||
sheet_names.append(sh.attrib.get("name", "Sheet"))
|
||||
|
||||
sheet_files = sorted(
|
||||
n for n in zf.namelist() if n.startswith("xl/worksheets/sheet") and n.endswith(".xml")
|
||||
)
|
||||
out_sections: list[str] = []
|
||||
for idx, sheet_file in enumerate(sheet_files):
|
||||
title = sheet_names[idx] if idx < len(sheet_names) else Path(sheet_file).stem
|
||||
sh_root = ET.fromstring(zf.read(sheet_file))
|
||||
rows_out: list[str] = [f"# Sheet: {title}"]
|
||||
for row in sh_root.findall(".//s:row", ns):
|
||||
vals: list[str] = []
|
||||
for cell in row.findall("s:c", ns):
|
||||
cell_type = cell.attrib.get("t", "")
|
||||
v_el = cell.find("s:v", ns)
|
||||
is_el = cell.find("s:is/s:t", ns)
|
||||
if cell_type == "inlineStr" and is_el is not None and is_el.text is not None:
|
||||
vals.append(is_el.text)
|
||||
elif v_el is not None and v_el.text is not None:
|
||||
if cell_type == "s":
|
||||
s_idx = int(v_el.text)
|
||||
vals.append(
|
||||
shared_strings[s_idx] if 0 <= s_idx < len(shared_strings) else v_el.text
|
||||
)
|
||||
else:
|
||||
vals.append(v_el.text)
|
||||
else:
|
||||
vals.append("")
|
||||
if any(v.strip() for v in vals):
|
||||
rows_out.append("\t".join(vals))
|
||||
out_sections.append("\n".join(rows_out))
|
||||
return "\n\n".join(out_sections)
|
||||
|
||||
|
||||
def extract_xlsx_text(path: Path) -> str:
|
||||
try:
|
||||
import openpyxl # type: ignore
|
||||
except ImportError:
|
||||
return _extract_xlsx_stdlib(path)
|
||||
|
||||
wb = openpyxl.load_workbook(str(path), read_only=True, data_only=True)
|
||||
sections: list[str] = []
|
||||
try:
|
||||
for name in wb.sheetnames:
|
||||
ws = wb[name]
|
||||
lines = [f"# Sheet: {name}"]
|
||||
for row in ws.iter_rows(values_only=True):
|
||||
cells = ["" if v is None else str(v) for v in row]
|
||||
if any(c.strip() for c in cells):
|
||||
lines.append("\t".join(cells))
|
||||
sections.append("\n".join(lines))
|
||||
finally:
|
||||
wb.close()
|
||||
return "\n\n".join(sections)
|
||||
|
||||
|
||||
def extract_document_text(path: Path) -> str:
|
||||
"""Extract plain text/tables from .pdf, .docx, or .xlsx files."""
|
||||
ext = path.suffix.lower()
|
||||
if ext == ".pdf":
|
||||
return extract_pdf_text(path)
|
||||
if ext == ".docx":
|
||||
return extract_docx_text(path)
|
||||
if ext == ".xlsx":
|
||||
return extract_xlsx_text(path)
|
||||
raise ValueError(f"Unsupported document format: {path.suffix}")
|
||||
@@ -24,7 +24,7 @@ DEFAULT_RULES_PATH = Path(__file__).resolve().parents[2] / "rules" / "default_ru
|
||||
|
||||
EXISTING_TOKEN_RE = re.compile(r"<<REDACT:[A-Z0-9_]+:[0-9a-f]{4}:\d+>>")
|
||||
SYNTHETIC_TOKEN_RE = re.compile(
|
||||
r"(?:900-\d{2}-\d{4}|999-70-\d{4}|\(555\) 010-\d{4}|redact-[0-9a-f]{4}-\d+@invalid\.local|REDACT_[A-Z0-9_]+_[0-9a-f]{4}_\d+)"
|
||||
r"(?:900-\d{2}-\d{4}|999-70-\d{4}|\(555\) 010-\d{4}|redact-[0-9a-f]{4}-\d+@invalid\.local|400000\d{10}|REDACT_[A-Z0-9_]+_[0-9a-f]{4}_\d+)"
|
||||
)
|
||||
QUOTED_CANDIDATE_RE = re.compile(r"""(["'])([A-Za-z0-9+/_=\-]{20,128})\1""")
|
||||
UUID_RE = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
|
||||
|
||||
@@ -18,7 +18,8 @@ TOOL_DEFINITIONS: list[dict[str, Any]] = [
|
||||
"name": "vault_read_file",
|
||||
"description": (
|
||||
"Read a local sensitive file through the zero-egress redaction vault. "
|
||||
"Supports schema/key-aware redaction for JSON, JSONL, CSV, TSV, and SQL, plus regex/NER."
|
||||
"Supports schema/key-aware redaction for JSON, JSONL, CSV, TSV, and SQL, "
|
||||
"plus text/table extraction for PDF, DOCX, and XLSX documents."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
@@ -145,6 +146,21 @@ TOOL_DEFINITIONS: list[dict[str, Any]] = [
|
||||
"required": ["clean_path", "dest_path"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "vault_sync_output",
|
||||
"description": (
|
||||
"Batch one-way egress: rehydrate all text files in clean-staging and write them "
|
||||
"into final-output preserving directory structure. Never returns unredacted text."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"clean_dir": {"type": "string", "default": ""},
|
||||
"output_dir": {"type": "string", "default": ""},
|
||||
"session_id": {"type": "string", "default": "default"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "vault_session_status",
|
||||
"description": (
|
||||
@@ -178,6 +194,7 @@ def _dispatch_mcp_tool(client: VaultClient, name: str, args: dict[str, Any]) ->
|
||||
"vault_run_scrubbed": "run_scrubbed",
|
||||
"vault_write_file": "write_file",
|
||||
"vault_rehydrate_file": "rehydrate_file",
|
||||
"vault_sync_output": "sync_output",
|
||||
"vault_session_status": "status",
|
||||
"vault_purge_session": "purge",
|
||||
}
|
||||
@@ -399,6 +416,19 @@ def build_fastmcp_server(client: Optional[VaultClient] = None) -> Any:
|
||||
indent=2,
|
||||
)
|
||||
|
||||
@mcp.tool()
|
||||
def vault_sync_output(
|
||||
clean_dir: str = "", output_dir: str = "", session_id: str = "default"
|
||||
) -> str:
|
||||
"""Batch one-way egress: rehydrate clean-staging directory into final-output."""
|
||||
return json.dumps(
|
||||
vault_client.call(
|
||||
"sync_output",
|
||||
{"clean_dir": clean_dir, "output_dir": output_dir, "session_id": session_id},
|
||||
),
|
||||
indent=2,
|
||||
)
|
||||
|
||||
@mcp.tool()
|
||||
def vault_session_status(session_id: str = "default") -> str:
|
||||
"""Inspect non-secret token metadata for a session."""
|
||||
|
||||
+52
-12
@@ -7,6 +7,7 @@ from typing import Any, Optional
|
||||
|
||||
from redactor_mcp.audit import AuditLogger
|
||||
from redactor_mcp.crypto import load_encrypted_snapshot_file, save_encrypted_snapshot_file
|
||||
from redactor_mcp.documents import extract_document_text, is_supported_document
|
||||
from redactor_mcp.scanner import RedactionScanner, is_binary_bytes
|
||||
from redactor_mcp.structured import redact_by_extension
|
||||
from redactor_mcp.vault import SessionVault
|
||||
@@ -89,18 +90,28 @@ class RedactorService:
|
||||
raise ValueError(
|
||||
f"File exceeds max_bytes ({len(raw)} > {max_bytes}): {target}"
|
||||
)
|
||||
if is_binary_bytes(raw[:4096]):
|
||||
raise ValueError(f"Refusing to read binary file: {target}")
|
||||
text = raw.decode("utf-8", errors="replace")
|
||||
res = redact_by_extension(
|
||||
text=text,
|
||||
extension=target.suffix,
|
||||
scanner=self.scanner,
|
||||
vault=self.vault,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
if is_supported_document(target):
|
||||
text = extract_document_text(target)
|
||||
res = self.vault.redact(
|
||||
text=text,
|
||||
scanner=self.scanner,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
else:
|
||||
if is_binary_bytes(raw[:4096]):
|
||||
raise ValueError(f"Refusing to read binary file: {target}")
|
||||
text = raw.decode("utf-8", errors="replace")
|
||||
res = redact_by_extension(
|
||||
text=text,
|
||||
extension=target.suffix,
|
||||
scanner=self.scanner,
|
||||
vault=self.vault,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
self.audit.record(
|
||||
event="read_file",
|
||||
session_id=session_id,
|
||||
@@ -258,6 +269,30 @@ class RedactorService:
|
||||
session_id=session_id,
|
||||
)
|
||||
|
||||
def sync_output(
|
||||
self,
|
||||
clean_dir: str = "",
|
||||
output_dir: str = "",
|
||||
session_id: str = "default",
|
||||
) -> dict[str, Any]:
|
||||
"""Batch one-way egress: rehydrate clean_dir into approved output_dir."""
|
||||
resolved_clean = self.policy.resolve_staging_dir(clean_dir)
|
||||
resolved_output = self.policy.resolve_default_output_dir(output_dir)
|
||||
summary = self.stager.sync_output_directory(
|
||||
clean_dir=resolved_clean,
|
||||
output_dir=resolved_output,
|
||||
vault=self.vault,
|
||||
session_id=session_id,
|
||||
)
|
||||
self.audit.record(
|
||||
event="sync_output",
|
||||
session_id=session_id,
|
||||
target=str(resolved_output),
|
||||
token_count=summary["total_tokens_restored"],
|
||||
extra={"files_synced": summary["files_synced"]},
|
||||
)
|
||||
return summary
|
||||
|
||||
def rehydrate_text_cli(
|
||||
self,
|
||||
text: str,
|
||||
@@ -371,6 +406,11 @@ class RedactorService:
|
||||
dest_path=p["dest_path"],
|
||||
session_id=p.get("session_id", "default"),
|
||||
),
|
||||
"sync_output": lambda p: self.sync_output(
|
||||
clean_dir=p.get("clean_dir", ""),
|
||||
output_dir=p.get("output_dir", ""),
|
||||
session_id=p.get("session_id", "default"),
|
||||
),
|
||||
"rehydrate_text_cli": lambda p: self.rehydrate_text_cli(
|
||||
text=p["text"],
|
||||
session_id=p.get("session_id", "default"),
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
from redactor_mcp.client import VaultClient
|
||||
from redactor_mcp.service import RedactorService
|
||||
from redactor_mcp.workspace import normalize_host_path
|
||||
|
||||
|
||||
def watch_directory(
|
||||
src_dir: str,
|
||||
clean_dir: str = "",
|
||||
session_id: str = "default",
|
||||
profile: str = "swe",
|
||||
format_preserving: bool = False,
|
||||
interval: float = 1.5,
|
||||
max_iterations: Optional[int] = None,
|
||||
service: Optional[RedactorService] = None,
|
||||
client: Optional[VaultClient] = None,
|
||||
on_sync: Optional[Callable[[dict[str, Any]], None]] = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Poll `src_dir` and incrementally mirror changes into `clean_dir`.
|
||||
|
||||
Uses stat/hash polling rather than inotify so it works reliably across
|
||||
Windows /mnt/c/... DrvFs mounts inside WSL2, and sends staging calls to
|
||||
the running daemon VaultClient when available so tokens are shared.
|
||||
"""
|
||||
active_client = client or VaultClient(service=service)
|
||||
resolved_src = normalize_host_path(src_dir).resolve()
|
||||
|
||||
last_snapshot: Optional[dict[str, tuple[int, int]]] = None
|
||||
sync_reports: list[dict[str, Any]] = []
|
||||
iteration = 0
|
||||
|
||||
while max_iterations is None or iteration < max_iterations:
|
||||
iteration += 1
|
||||
current_snapshot: dict[str, tuple[int, int]] = {}
|
||||
if resolved_src.is_dir():
|
||||
for path in resolved_src.rglob("*"):
|
||||
if path.is_symlink() or not path.is_file():
|
||||
continue
|
||||
try:
|
||||
st = path.stat()
|
||||
except OSError:
|
||||
continue
|
||||
current_snapshot[path.relative_to(resolved_src).as_posix()] = (
|
||||
st.st_mtime_ns,
|
||||
st.st_size,
|
||||
)
|
||||
|
||||
if last_snapshot is None or current_snapshot != last_snapshot:
|
||||
report = active_client.call(
|
||||
"stage_workspace",
|
||||
{
|
||||
"src_dir": str(resolved_src),
|
||||
"clean_dir": clean_dir,
|
||||
"session_id": session_id,
|
||||
"profile": profile,
|
||||
"format_preserving": format_preserving,
|
||||
},
|
||||
)
|
||||
sync_reports.append(report)
|
||||
if on_sync is not None:
|
||||
on_sync(report)
|
||||
last_snapshot = current_snapshot
|
||||
|
||||
if max_iterations is not None and iteration >= max_iterations:
|
||||
break
|
||||
time.sleep(max(0.1, interval))
|
||||
|
||||
return sync_reports
|
||||
@@ -54,6 +54,26 @@ def _is_within(child: Path, root: Path) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_no_symlink(
|
||||
raw_path: Path, allowed_roots: Optional[list[Path]] = None
|
||||
) -> None:
|
||||
"""Reject symlinks on the target or any component strictly below allowed roots."""
|
||||
if raw_path.is_symlink():
|
||||
raise PermissionError(f"Symlink path denied: {raw_path}")
|
||||
if not allowed_roots:
|
||||
return
|
||||
resolved_roots = {r.resolve() for r in allowed_roots}
|
||||
if raw_path.resolve() in resolved_roots:
|
||||
return
|
||||
cur = raw_path.parent
|
||||
while cur != cur.parent:
|
||||
if cur.resolve() in resolved_roots:
|
||||
return
|
||||
if cur.is_symlink():
|
||||
raise PermissionError(f"Symlink component denied: {cur}")
|
||||
cur = cur.parent
|
||||
|
||||
|
||||
def load_redactorignore(src_dir: Path) -> list[str]:
|
||||
"""Load glob ignore patterns from `<src_dir>/.redactorignore` if present."""
|
||||
ignore_file = src_dir / ".redactorignore"
|
||||
@@ -106,31 +126,44 @@ class WorkspacePolicy:
|
||||
)
|
||||
|
||||
def resolve_read_path(self, raw_path: str) -> Path:
|
||||
target = normalize_host_path(raw_path).resolve()
|
||||
raw = normalize_host_path(raw_path)
|
||||
if raw.is_symlink():
|
||||
raise PermissionError(f"Symlink path denied: {raw}")
|
||||
target = raw.resolve()
|
||||
if self.read_roots and not any(_is_within(target, r) for r in self.read_roots):
|
||||
raise PermissionError(
|
||||
f"Read denied outside allowed REDACTOR_READ_ROOTS: {target}"
|
||||
)
|
||||
_ensure_no_symlink(raw, self.read_roots)
|
||||
return target
|
||||
|
||||
def resolve_clean_read_path(self, raw_path: str) -> Path:
|
||||
target = normalize_host_path(raw_path).resolve()
|
||||
raw = normalize_host_path(raw_path)
|
||||
if raw.is_symlink():
|
||||
raise PermissionError(f"Symlink path denied: {raw}")
|
||||
allowed = list(self.read_roots)
|
||||
if self.staging_root is not None:
|
||||
allowed.append(self.staging_root)
|
||||
target = raw.resolve()
|
||||
if allowed and not any(_is_within(target, r) for r in allowed):
|
||||
raise PermissionError(
|
||||
f"Read denied outside staging/read roots: {target}"
|
||||
)
|
||||
_ensure_no_symlink(raw, allowed)
|
||||
return target
|
||||
|
||||
def resolve_staging_dir(self, raw_dir: str = "") -> Path:
|
||||
if raw_dir.strip():
|
||||
target = normalize_host_path(raw_dir).resolve()
|
||||
raw = normalize_host_path(raw_dir)
|
||||
if raw.is_symlink():
|
||||
raise PermissionError(f"Symlink path denied: {raw}")
|
||||
target = raw.resolve()
|
||||
if self.staging_root is not None and not _is_within(target, self.staging_root):
|
||||
raise PermissionError(
|
||||
f"Staging directory must stay inside REDACTOR_STAGING_ROOT: {target}"
|
||||
)
|
||||
roots = [self.staging_root] if self.staging_root is not None else []
|
||||
_ensure_no_symlink(raw, roots)
|
||||
return target
|
||||
if self.staging_root is not None:
|
||||
return self.staging_root
|
||||
@@ -144,15 +177,22 @@ class WorkspacePolicy:
|
||||
)
|
||||
if not raw_cwd.strip():
|
||||
return self.staging_root
|
||||
target = normalize_host_path(raw_cwd).resolve()
|
||||
raw = normalize_host_path(raw_cwd)
|
||||
if raw.is_symlink():
|
||||
raise PermissionError(f"Symlink path denied: {raw}")
|
||||
target = raw.resolve()
|
||||
if not _is_within(target, self.staging_root):
|
||||
raise PermissionError(
|
||||
f"Execution denied outside REDACTOR_STAGING_ROOT: {target}"
|
||||
)
|
||||
_ensure_no_symlink(raw, [self.staging_root])
|
||||
return target
|
||||
|
||||
def resolve_output_path(self, raw_path: str) -> Path:
|
||||
target = normalize_host_path(raw_path).resolve()
|
||||
raw = normalize_host_path(raw_path)
|
||||
if raw.is_symlink():
|
||||
raise PermissionError(f"Symlink path denied: {raw}")
|
||||
target = raw.resolve()
|
||||
if self.staging_root is not None and _is_within(target, self.staging_root):
|
||||
raise PermissionError(
|
||||
f"Output denied inside REDACTOR_STAGING_ROOT (exfiltration guard): {target}"
|
||||
@@ -161,8 +201,22 @@ class WorkspacePolicy:
|
||||
raise PermissionError(
|
||||
f"Output denied outside allowed REDACTOR_OUTPUT_ROOTS: {target}"
|
||||
)
|
||||
_ensure_no_symlink(raw, self.output_roots)
|
||||
return target
|
||||
|
||||
def resolve_default_output_dir(self, raw_dir: str = "") -> Path:
|
||||
if raw_dir.strip():
|
||||
return self.resolve_output_path(raw_dir)
|
||||
if self.output_roots:
|
||||
candidate = self.output_roots[0]
|
||||
_ensure_no_symlink(candidate, self.output_roots)
|
||||
if self.staging_root is not None and _is_within(candidate, self.staging_root):
|
||||
raise PermissionError(
|
||||
f"Output denied inside REDACTOR_STAGING_ROOT: {candidate}"
|
||||
)
|
||||
return candidate
|
||||
raise ValueError("output_dir is required when REDACTOR_OUTPUT_ROOTS is not configured")
|
||||
|
||||
|
||||
class WorkspaceStager:
|
||||
"""High-throughput incremental workspace redaction for large codebases."""
|
||||
@@ -192,14 +246,23 @@ class WorkspaceStager:
|
||||
skipped_large = 0
|
||||
skipped_ignored = 0
|
||||
|
||||
for root, dirs, files in os.walk(src_dir):
|
||||
dirs[:] = [d for d in dirs if d not in DEFAULT_IGNORE_DIRS and not d.startswith(".git")]
|
||||
for root, dirs, files in os.walk(src_dir, followlinks=False):
|
||||
dirs[:] = [
|
||||
d
|
||||
for d in dirs
|
||||
if d not in DEFAULT_IGNORE_DIRS
|
||||
and not d.startswith(".git")
|
||||
and not (Path(root) / d).is_symlink()
|
||||
]
|
||||
root_path = Path(root)
|
||||
for fname in files:
|
||||
if fname == ".redactorignore":
|
||||
skipped_ignored += 1
|
||||
continue
|
||||
fpath = root_path / fname
|
||||
if fpath.is_symlink():
|
||||
skipped_ignored += 1
|
||||
continue
|
||||
rel = fpath.relative_to(src_dir).as_posix()
|
||||
if ignore_globs and _matches_any_glob(rel, ignore_globs):
|
||||
skipped_ignored += 1
|
||||
@@ -282,3 +345,65 @@ class WorkspaceStager:
|
||||
"total_replacements": total_replacements,
|
||||
"categories": categories,
|
||||
}
|
||||
|
||||
def sync_output_directory(
|
||||
self,
|
||||
clean_dir: Path,
|
||||
output_dir: Path,
|
||||
vault: SessionVault,
|
||||
session_id: str = "default",
|
||||
) -> dict[str, Any]:
|
||||
"""Batch one-way egress: rehydrate all text files from clean_dir into output_dir."""
|
||||
if not clean_dir.is_dir():
|
||||
raise FileNotFoundError(f"Staging directory does not exist: {clean_dir}")
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
files_synced = 0
|
||||
files_skipped = 0
|
||||
total_tokens_restored = 0
|
||||
unresolved_all: set[str] = set()
|
||||
|
||||
for root, dirs, files in os.walk(clean_dir, followlinks=False):
|
||||
dirs[:] = [
|
||||
d
|
||||
for d in dirs
|
||||
if d not in DEFAULT_IGNORE_DIRS
|
||||
and not d.startswith(".git")
|
||||
and not (Path(root) / d).is_symlink()
|
||||
]
|
||||
root_path = Path(root)
|
||||
for fname in files:
|
||||
fpath = root_path / fname
|
||||
if fpath.is_symlink():
|
||||
files_skipped += 1
|
||||
continue
|
||||
try:
|
||||
raw = fpath.read_bytes()
|
||||
except OSError:
|
||||
files_skipped += 1
|
||||
continue
|
||||
if len(raw) > self.max_file_bytes or is_binary_bytes(raw[:4096]):
|
||||
files_skipped += 1
|
||||
continue
|
||||
rel = fpath.relative_to(clean_dir)
|
||||
dest = output_dir / rel
|
||||
_ensure_no_symlink(dest, [output_dir])
|
||||
text = raw.decode("utf-8", errors="replace")
|
||||
summary = vault.rehydrate_to_file(
|
||||
clean_text=text,
|
||||
dest_path=dest,
|
||||
session_id=session_id,
|
||||
)
|
||||
files_synced += 1
|
||||
total_tokens_restored += summary.tokens_restored
|
||||
unresolved_all.update(summary.unresolved_tokens)
|
||||
|
||||
return {
|
||||
"clean_dir": str(clean_dir),
|
||||
"output_dir": str(output_dir),
|
||||
"session_id": session_id,
|
||||
"files_synced": files_synced,
|
||||
"files_skipped": files_skipped,
|
||||
"total_tokens_restored": total_tokens_restored,
|
||||
"unresolved_tokens": sorted(unresolved_all),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from redactor_mcp.client import VaultClient
|
||||
from redactor_mcp.scanner import RedactionScanner
|
||||
from redactor_mcp.server import StdioMCPServer
|
||||
from redactor_mcp.service import RedactorService
|
||||
from redactor_mcp.vault import SessionVault
|
||||
from redactor_mcp.watcher import watch_directory
|
||||
from redactor_mcp.workspace import WorkspacePolicy
|
||||
|
||||
|
||||
def _create_sample_docx(path: Path) -> None:
|
||||
doc_xml = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
|
||||
<w:body>
|
||||
<w:p><w:r><w:t>Applicant SSN: 123-45-6789</w:t></w:r></w:p>
|
||||
<w:tbl>
|
||||
<w:tr>
|
||||
<w:tc><w:p><w:r><w:t>Email</w:t></w:r></w:p></w:tc>
|
||||
<w:tc><w:p><w:r><w:t>jane.doe@state.gov</w:t></w:r></w:p></w:tc>
|
||||
</w:tr>
|
||||
</w:tbl>
|
||||
</w:body>
|
||||
</w:document>"""
|
||||
with zipfile.ZipFile(path, "w") as zf:
|
||||
zf.writestr("word/document.xml", doc_xml)
|
||||
|
||||
|
||||
def _create_sample_xlsx(path: Path) -> None:
|
||||
workbook_xml = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
|
||||
<sheets><sheet name="Benefits" sheetId="1" r:id="rId1" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"/></sheets>
|
||||
</workbook>"""
|
||||
shared_xml = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="2" uniqueCount="2">
|
||||
<si><t>Applicant</t></si>
|
||||
<si><t>123-45-6789</t></si>
|
||||
</sst>"""
|
||||
sheet1_xml = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
|
||||
<sheetData>
|
||||
<row r="1">
|
||||
<c r="A1" t="s"><v>0</v></c>
|
||||
<c r="B1" t="s"><v>1</v></c>
|
||||
<c r="C1" t="inlineStr"><is><t>DOB: 1988-02-10</t></is></c>
|
||||
</row>
|
||||
</sheetData>
|
||||
</worksheet>"""
|
||||
with zipfile.ZipFile(path, "w") as zf:
|
||||
zf.writestr("xl/workbook.xml", workbook_xml)
|
||||
zf.writestr("xl/sharedStrings.xml", shared_xml)
|
||||
zf.writestr("xl/worksheets/sheet1.xml", sheet1_xml)
|
||||
|
||||
|
||||
class TestHardeningDocsAndSync(unittest.TestCase):
|
||||
def test_symlink_escape_is_blocked_and_skipped(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
sensitive = root / "sensitive"
|
||||
clean = root / "clean"
|
||||
output = root / "output"
|
||||
outside = root / "outside"
|
||||
for d in (sensitive, clean, output, outside):
|
||||
d.mkdir()
|
||||
|
||||
outside_secret = outside / "secret.txt"
|
||||
outside_secret.write_text("SSN: 123-45-6789\n", encoding="utf-8")
|
||||
|
||||
link_in_sensitive = sensitive / "escape.txt"
|
||||
link_in_sensitive.symlink_to(outside_secret)
|
||||
(sensitive / "normal.txt").write_text("SSN: 123-45-6789\n", encoding="utf-8")
|
||||
|
||||
link_in_output = output / "escape_out.txt"
|
||||
link_in_output.symlink_to(outside_secret)
|
||||
|
||||
policy = WorkspacePolicy([sensitive.resolve()], clean.resolve(), [output.resolve()])
|
||||
service = RedactorService(policy=policy)
|
||||
|
||||
with self.assertRaises(PermissionError):
|
||||
service.read_file(str(link_in_sensitive))
|
||||
|
||||
with self.assertRaises(PermissionError):
|
||||
service.write_file("hello", str(link_in_output))
|
||||
|
||||
staged = service.stage_workspace(str(sensitive), session_id="sym")
|
||||
self.assertEqual(staged["files_scanned"], 1)
|
||||
self.assertFalse((clean / "escape.txt").exists())
|
||||
|
||||
def test_synthetic_card_rescan_does_not_double_tokenize(self) -> None:
|
||||
scanner = RedactionScanner()
|
||||
vault = SessionVault()
|
||||
first = vault.redact(
|
||||
"Card: 4111111111111111", scanner, session_id="card", format_preserving=True
|
||||
)
|
||||
self.assertEqual(first.replacements, 1)
|
||||
second = vault.redact(
|
||||
first.redacted_text, scanner, session_id="card", format_preserving=True
|
||||
)
|
||||
self.assertEqual(second.replacements, 0)
|
||||
self.assertEqual(first.redacted_text, second.redacted_text)
|
||||
|
||||
def test_docx_xlsx_and_pdf_document_extraction_and_redaction(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
sensitive = root / "sensitive"
|
||||
sensitive.mkdir()
|
||||
docx_path = sensitive / "intake.docx"
|
||||
xlsx_path = sensitive / "benefits.xlsx"
|
||||
pdf_path = sensitive / "record.pdf"
|
||||
_create_sample_docx(docx_path)
|
||||
_create_sample_xlsx(xlsx_path)
|
||||
pdf_path.write_bytes(b"%PDF-1.4\n%mock\n")
|
||||
|
||||
policy = WorkspacePolicy([sensitive.resolve()], None, [])
|
||||
service = RedactorService(policy=policy)
|
||||
|
||||
docx_res = service.read_file(str(docx_path), session_id="docs")
|
||||
self.assertNotIn("123-45-6789", docx_res["redacted_text"])
|
||||
self.assertNotIn("jane.doe@state.gov", docx_res["redacted_text"])
|
||||
self.assertIn("<<REDACT:PII_SSN:", docx_res["redacted_text"])
|
||||
|
||||
xlsx_res = service.read_file(str(xlsx_path), session_id="docs")
|
||||
self.assertIn("# Sheet: Benefits", xlsx_res["redacted_text"])
|
||||
self.assertNotIn("123-45-6789", xlsx_res["redacted_text"])
|
||||
self.assertNotIn("1988-02-10", xlsx_res["redacted_text"])
|
||||
|
||||
# Mock pypdf module to verify PDF extraction pipeline cleanly without external deps
|
||||
fake_page = types.SimpleNamespace(extract_text=lambda: "Citizen SSN: 123-45-6789")
|
||||
fake_pypdf = types.ModuleType("pypdf")
|
||||
fake_pypdf.PdfReader = lambda _p: types.SimpleNamespace(pages=[fake_page]) # type: ignore[attr-defined]
|
||||
sys.modules["pypdf"] = fake_pypdf
|
||||
try:
|
||||
pdf_res = service.read_file(str(pdf_path), session_id="docs")
|
||||
self.assertIn("--- Page 1 ---", pdf_res["redacted_text"])
|
||||
self.assertNotIn("123-45-6789", pdf_res["redacted_text"])
|
||||
finally:
|
||||
sys.modules.pop("pypdf", None)
|
||||
|
||||
def test_batch_sync_output_via_mcp_and_watch_directory(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
sensitive = root / "sensitive"
|
||||
clean = root / "clean"
|
||||
output = root / "output"
|
||||
for d in (sensitive, clean, output):
|
||||
d.mkdir()
|
||||
|
||||
(sensitive / "sub").mkdir()
|
||||
(sensitive / "sub" / "case.txt").write_text("SSN: 123-45-6789\n", encoding="utf-8")
|
||||
|
||||
policy = WorkspacePolicy(
|
||||
[sensitive.resolve()], clean.resolve(), [output.resolve()]
|
||||
)
|
||||
service = RedactorService(policy=policy)
|
||||
client = VaultClient(service=service)
|
||||
mcp = StdioMCPServer(client=client)
|
||||
|
||||
# Watch iteration 1 stages existing file
|
||||
reports = watch_directory(
|
||||
src_dir=str(sensitive),
|
||||
clean_dir=str(clean),
|
||||
session_id="batch",
|
||||
profile="strict",
|
||||
interval=0.1,
|
||||
max_iterations=1,
|
||||
client=client,
|
||||
)
|
||||
self.assertEqual(len(reports), 1)
|
||||
self.assertEqual(reports[0]["files_scanned"], 1)
|
||||
self.assertNotIn("123-45-6789", (clean / "sub" / "case.txt").read_text(encoding="utf-8"))
|
||||
|
||||
# Simulate agent adding a file in clean-staging referencing the same token
|
||||
staged_text = (clean / "sub" / "case.txt").read_text(encoding="utf-8")
|
||||
(clean / "summary.md").write_text(f"Reviewed {staged_text}", encoding="utf-8")
|
||||
|
||||
# Batch sync via MCP tool
|
||||
sync_resp = mcp.handle_message(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 9,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "vault_sync_output",
|
||||
"arguments": {"session_id": "batch"},
|
||||
},
|
||||
}
|
||||
)
|
||||
self.assertFalse(sync_resp["result"]["isError"])
|
||||
body = sync_resp["result"]["content"][0]["text"]
|
||||
self.assertNotIn("123-45-6789", body)
|
||||
parsed = json.loads(body)
|
||||
self.assertEqual(parsed["files_synced"], 2)
|
||||
self.assertEqual(
|
||||
(output / "sub" / "case.txt").read_text(encoding="utf-8"),
|
||||
"SSN: 123-45-6789\n",
|
||||
)
|
||||
self.assertEqual(
|
||||
(output / "summary.md").read_text(encoding="utf-8"),
|
||||
"Reviewed SSN: 123-45-6789\n",
|
||||
)
|
||||
|
||||
def test_plugin_bundle_guard_hook(self) -> None:
|
||||
plugin_guard = (
|
||||
Path(__file__).resolve().parents[1]
|
||||
/ "plugins"
|
||||
/ "redactor-vault"
|
||||
/ "hooks"
|
||||
/ "guard.py"
|
||||
)
|
||||
spec = importlib.util.spec_from_file_location("plugin_guard", plugin_guard)
|
||||
assert spec is not None and spec.loader is not None
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
|
||||
deny = mod.handle_pre_tool(
|
||||
{"toolCall": {"name": "read_file", "args": {"Path": "sensitive/data.csv"}}}
|
||||
)
|
||||
self.assertEqual(deny["decision"], "deny")
|
||||
halt = mod.handle_pre_invocation({"lastUserInput": "SSN 123-45-6789"})
|
||||
self.assertEqual(halt.get("terminationBehavior"), "terminate")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user