Public release
This commit is contained in:
+26
@@ -0,0 +1,26 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.venv/
|
||||
venv/
|
||||
dist/
|
||||
build/
|
||||
|
||||
# Sensitive work folders & vault artifacts (NEVER commit)
|
||||
work/
|
||||
*.snap
|
||||
*.jsonl
|
||||
.env
|
||||
.env.*
|
||||
*.pem
|
||||
*.key
|
||||
*.pfx
|
||||
*.p12
|
||||
*.kdbx
|
||||
|
||||
# OS / IDE
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
ARG INSTALL_NER=false
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
REDACTOR_SOCKET=/run/vault/daemon.sock
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Create unprivileged non-root user
|
||||
RUN groupadd --gid 10001 redactor && \
|
||||
useradd --uid 10001 --gid 10001 --create-home --shell /bin/false redactor
|
||||
|
||||
COPY pyproject.toml README.md ./
|
||||
COPY rules ./rules
|
||||
COPY src ./src
|
||||
|
||||
RUN pip install --no-cache-dir --upgrade pip && \
|
||||
if [ "$INSTALL_NER" = "true" ]; then \
|
||||
pip install --no-cache-dir ".[ner]" && \
|
||||
python -m spacy download en_core_web_sm; \
|
||||
else \
|
||||
pip install --no-cache-dir .; \
|
||||
fi
|
||||
|
||||
RUN mkdir -p /run/vault /data/sensitive /data/clean /data/output && \
|
||||
chown -R redactor:redactor /run/vault /data /app
|
||||
|
||||
USER redactor
|
||||
|
||||
ENTRYPOINT ["redactor-mcp"]
|
||||
CMD ["daemon"]
|
||||
@@ -0,0 +1,46 @@
|
||||
# Redactor MCP
|
||||
|
||||
A zero-egress local MCP server and in-memory vault for redacting state-work PII (SSN, ITIN, EIN, DOB, addresses, bank routing/account numbers, state/case IDs) and software engineering secrets (API keys, tokens, private keys, DB URIs, `.env` values) **before** they reach AI agents (**Antigravity** and **Amazon Kiro**), with deterministic placeholder mapping and **one-way egress rehydration**.
|
||||
|
||||
## 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.
|
||||
- **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.
|
||||
- **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`).
|
||||
|
||||
## Quick Start (Windows + WSL2 + Docker)
|
||||
|
||||
1. Copy this repository into your WSL2 filesystem (e.g., `~/redactor-mcp`) for POSIX permissions and fast I/O:
|
||||
```bash
|
||||
cd ~/redactor-mcp
|
||||
chmod +x scripts/wsl_setup.sh scripts/hooks/agy_guard.py
|
||||
./scripts/wsl_setup.sh
|
||||
```
|
||||
*(To enable offline Microsoft Presidio + spaCy NER for unstructured person names/locations in case notes, build with `INSTALL_NER=true` in `docker-compose.yml` and set `REDACTOR_ENABLE_NER: "true"`.)*
|
||||
|
||||
2. **Connect Antigravity:**
|
||||
- Copy `configs/antigravity/mcp_config.json` into `~/.gemini/config/mcp_config.json` (merge under `mcpServers`).
|
||||
- Copy `configs/antigravity/hooks.json` to your project's `.agents/hooks.json` (adjusting the path to `agy_guard.py`) and `configs/antigravity/GEMINI.md` to your workspace root.
|
||||
|
||||
3. **Connect Amazon Kiro:**
|
||||
- Copy `configs/kiro/mcp.json` into `.kiro/settings/mcp.json` (or `~/.kiro/settings/mcp.json`).
|
||||
- Copy `configs/kiro/hooks/protect-sensitive.json` into `.kiro/hooks/`.
|
||||
|
||||
4. **Clipboard Sanitize / Restore on Windows:**
|
||||
- Before pasting sensitive text into chat:
|
||||
`powershell -File .\scripts\win_clipboard.ps1 -Mode sanitize`
|
||||
- After copying an agent response with placeholders:
|
||||
`powershell -File .\scripts\win_clipboard.ps1 -Mode restore`
|
||||
|
||||
## Running Tests Locally
|
||||
|
||||
Works on Python 3.9+ with zero external dependencies (or via `pytest`):
|
||||
|
||||
```bash
|
||||
PYTHONPATH=src python3 -m unittest discover -s tests -v
|
||||
```
|
||||
@@ -0,0 +1,6 @@
|
||||
# Sensitive Data & Redactor Vault Policy
|
||||
|
||||
- **Never** read or inspect files inside `sensitive/`, `final-output/`, or `.env*` directly using native file/shell tools.
|
||||
- Always read sensitive files through the `redactor-vault` MCP server (`vault_read_file` or `vault_stage_workspace`) so PII (SSN, DOB, addresses) and secrets (API keys, tokens, connection strings) are replaced with `<<REDACT:...>>` placeholders.
|
||||
- Perform code edits and analysis inside `clean-staging/`.
|
||||
- When producing final artifacts that require real values restored, use `vault_write_file` or `vault_rehydrate_file` writing exclusively into `final-output/`. Never ask to print or echo unredacted values into chat.
|
||||
@@ -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 ./scripts/hooks/agy_guard.py --mode pre-tool",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreInvocation": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 ./scripts/hooks/agy_guard.py --mode pre-invocation",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -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": "py -3 scripts\\hooks\\agy_guard.py --mode pre-tool",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreInvocation": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "py -3 scripts\\hooks\\agy_guard.py --mode pre-invocation",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"redactor-vault": {
|
||||
"command": "wsl.exe",
|
||||
"args": [
|
||||
"-d",
|
||||
"Ubuntu",
|
||||
"--",
|
||||
"docker",
|
||||
"exec",
|
||||
"-i",
|
||||
"pii-redactor",
|
||||
"redactor-mcp",
|
||||
"mcp"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"protectedPaths": ["sensitive", "final-output", ".env", "citizen-exports"],
|
||||
"protectedFilenames": ["credentials.json", "secrets.json"],
|
||||
"protectedExtensions": [".pem", ".key", ".pfx", ".p12", ".kdbx"]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "Enforce Redactor Vault for Sensitive Paths",
|
||||
"description": "Reminds or redirects Kiro to use @redactor-vault MCP tools instead of reading sensitive/final-output directories directly.",
|
||||
"version": "1",
|
||||
"when": {
|
||||
"type": "PreToolUse",
|
||||
"toolTypes": ["read", "shell"]
|
||||
},
|
||||
"then": {
|
||||
"type": "agent",
|
||||
"prompt": "If the target touches sensitive/, final-output/, or .env files, stop and use @redactor-vault (`vault_read_file`, `vault_stage_workspace`, or `vault_write_file`) instead of native file or shell access."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"redactor-vault": {
|
||||
"command": "wsl.exe",
|
||||
"args": [
|
||||
"-d",
|
||||
"Ubuntu",
|
||||
"--",
|
||||
"docker",
|
||||
"exec",
|
||||
"-i",
|
||||
"pii-redactor",
|
||||
"redactor-mcp",
|
||||
"mcp"
|
||||
],
|
||||
"disabled": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
services:
|
||||
redactor-vault:
|
||||
build:
|
||||
context: .
|
||||
args:
|
||||
# Set to "true" at build time if you want offline Presidio + spaCy NER for unstructured text
|
||||
INSTALL_NER: "false"
|
||||
container_name: pii-redactor
|
||||
restart: unless-stopped
|
||||
# Zero network egress: container cannot phone home or leak PII over the network
|
||||
network_mode: none
|
||||
read_only: true
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
# Vault socket and session state live strictly in RAM
|
||||
tmpfs:
|
||||
- /run/vault:rw,noexec,nosuid,size=64m,uid=10001,gid=10001
|
||||
- /tmp:rw,noexec,nosuid,size=64m,uid=10001,gid=10001
|
||||
environment:
|
||||
REDACTOR_SOCKET: /run/vault/daemon.sock
|
||||
REDACTOR_AUDIT_LOG: /run/vault/audit.jsonl
|
||||
REDACTOR_READ_ROOTS: /data/sensitive
|
||||
REDACTOR_STAGING_ROOT: /data/clean
|
||||
REDACTOR_OUTPUT_ROOTS: /data/output
|
||||
REDACTOR_ALLOW_EXEC: "true"
|
||||
REDACTOR_SESSION_TTL: "14400"
|
||||
REDACTOR_ENABLE_NER: "false"
|
||||
volumes:
|
||||
# Adjust host paths below to your WSL2 or /mnt/c/ directories
|
||||
- ${REDACTOR_SENSITIVE_DIR:-./work/sensitive}:/data/sensitive:ro
|
||||
- ${REDACTOR_CLEAN_DIR:-./work/clean-staging}:/data/clean:rw
|
||||
- ${REDACTOR_OUTPUT_DIR:-./work/final-output}:/data/output:rw
|
||||
@@ -0,0 +1,35 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=68.0", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "redactor-mcp"
|
||||
version = "0.1.0"
|
||||
description = "Zero-egress local MCP server and vault for redacting state PII and SWE secrets before AI agent ingestion, with one-way rehydration."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
dependencies = [
|
||||
"mcp>=1.2.0",
|
||||
"pyyaml>=6.0",
|
||||
"regex>=2024.0",
|
||||
"cryptography>=42.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
ner = [
|
||||
"presidio-analyzer>=2.2.35",
|
||||
"spacy>=3.7.0",
|
||||
]
|
||||
dev = [
|
||||
"pytest>=8.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
redactor-mcp = "redactor_mcp.cli:main"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["src"]
|
||||
@@ -0,0 +1,283 @@
|
||||
{
|
||||
"version": "1.1",
|
||||
"allowlist": {
|
||||
"exact_values": [
|
||||
"localhost",
|
||||
"127.0.0.1",
|
||||
"0.0.0.0",
|
||||
"example@example.com",
|
||||
"test@example.com",
|
||||
"noreply@example.com"
|
||||
],
|
||||
"patterns": [
|
||||
"^000-00-0000$",
|
||||
"^9\\d{2}-\\d{2}-\\d{4}$"
|
||||
],
|
||||
"ignore_globs": [
|
||||
"*.lock",
|
||||
"package-lock.json",
|
||||
"yarn.lock",
|
||||
"pnpm-lock.yaml",
|
||||
"*.min.js",
|
||||
"*.min.css",
|
||||
"*.svg",
|
||||
"*.map"
|
||||
]
|
||||
},
|
||||
"sensitive_key_groups": {
|
||||
"PII_SSN": ["ssn", "social_security", "social_security_number"],
|
||||
"PII_ITIN": ["itin"],
|
||||
"PII_EIN": ["ein", "fein", "tax_id"],
|
||||
"PII_DOB": ["dob", "date_of_birth", "birth_date"],
|
||||
"PII_PERSON": [
|
||||
"first_name",
|
||||
"last_name",
|
||||
"middle_name",
|
||||
"full_name",
|
||||
"applicant_name",
|
||||
"claimant_name",
|
||||
"beneficiary_name",
|
||||
"case_worker",
|
||||
"mother_maiden_name"
|
||||
],
|
||||
"PII_EMAIL": ["email", "email_address"],
|
||||
"PII_PHONE": ["phone", "phone_number", "mobile_number"],
|
||||
"PII_ADDRESS": [
|
||||
"street_address",
|
||||
"mailing_address",
|
||||
"address_line_1",
|
||||
"address_line_2",
|
||||
"home_address"
|
||||
],
|
||||
"PII_STATE_ID": [
|
||||
"taxpayer_id",
|
||||
"drivers_license",
|
||||
"driver_license_number",
|
||||
"state_id",
|
||||
"medicaid_id",
|
||||
"case_id",
|
||||
"case_number"
|
||||
],
|
||||
"PII_BANK_ROUTING": ["routing_number", "aba_routing"],
|
||||
"PII_BANK_ACCOUNT": ["account_number", "bank_account"],
|
||||
"SECRET_ENV_VALUE": [
|
||||
"api_key",
|
||||
"secret_key",
|
||||
"access_token",
|
||||
"refresh_token",
|
||||
"client_secret",
|
||||
"password"
|
||||
],
|
||||
"SECRET_PRIVATE_KEY": ["private_key"]
|
||||
},
|
||||
"rules": [
|
||||
{
|
||||
"id": "pem-private-key",
|
||||
"category": "SECRET_PRIVATE_KEY",
|
||||
"description": "PEM encoded private key block",
|
||||
"pattern": "-{5}BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-{5}[\\s\\S]+?-{5}END (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-{5}",
|
||||
"profiles": ["swe", "strict"],
|
||||
"priority": 100
|
||||
},
|
||||
{
|
||||
"id": "aws-access-key",
|
||||
"category": "SECRET_AWS_KEY",
|
||||
"description": "AWS Access Key ID",
|
||||
"pattern": "\\b(?:AKIA|ASIA|AROA|AIDA)[0-9A-Z]{16}\\b",
|
||||
"profiles": ["swe", "strict"],
|
||||
"priority": 95
|
||||
},
|
||||
{
|
||||
"id": "github-token",
|
||||
"category": "SECRET_GITHUB_TOKEN",
|
||||
"description": "GitHub personal access or app token",
|
||||
"pattern": "\\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,255}\\b|\\bgithub_pat_[A-Za-z0-9_]{22,255}\\b",
|
||||
"profiles": ["swe", "strict"],
|
||||
"priority": 95
|
||||
},
|
||||
{
|
||||
"id": "gitlab-token",
|
||||
"category": "SECRET_GITLAB_TOKEN",
|
||||
"description": "GitLab personal access token",
|
||||
"pattern": "\\bglpat-[A-Za-z0-9\\-_]{20,}\\b",
|
||||
"profiles": ["swe", "strict"],
|
||||
"priority": 95
|
||||
},
|
||||
{
|
||||
"id": "stripe-key",
|
||||
"category": "SECRET_STRIPE_KEY",
|
||||
"description": "Stripe API secret or restricted key",
|
||||
"pattern": "\\b(?:sk|rk)_(?:live|test)_[0-9a-zA-Z]{24,99}\\b",
|
||||
"profiles": ["swe", "strict"],
|
||||
"priority": 95
|
||||
},
|
||||
{
|
||||
"id": "slack-token",
|
||||
"category": "SECRET_SLACK_TOKEN",
|
||||
"description": "Slack bot/user/app token",
|
||||
"pattern": "\\bxox(?:b|p|a|r|s)-[0-9A-Za-z\\-]{10,}\\b",
|
||||
"profiles": ["swe", "strict"],
|
||||
"priority": 95
|
||||
},
|
||||
{
|
||||
"id": "gcp-api-key",
|
||||
"category": "SECRET_GCP_KEY",
|
||||
"description": "Google Cloud API key",
|
||||
"pattern": "\\bAIza[0-9A-Za-z\\-_]{35}\\b",
|
||||
"profiles": ["swe", "strict"],
|
||||
"priority": 95
|
||||
},
|
||||
{
|
||||
"id": "anthropic-openai-key",
|
||||
"category": "SECRET_LLM_KEY",
|
||||
"description": "LLM provider API key",
|
||||
"pattern": "\\bsk-(?:ant-api\\d{2}-|proj-)?[A-Za-z0-9_\\-]{20,}\\b",
|
||||
"profiles": ["swe", "strict"],
|
||||
"priority": 92
|
||||
},
|
||||
{
|
||||
"id": "jwt-token",
|
||||
"category": "SECRET_JWT",
|
||||
"description": "JSON Web Token",
|
||||
"pattern": "\\beyJ[A-Za-z0-9_\\-]{10,}\\.eyJ[A-Za-z0-9_\\-]{10,}\\.[A-Za-z0-9_\\-]{10,}\\b",
|
||||
"profiles": ["swe", "strict"],
|
||||
"priority": 90
|
||||
},
|
||||
{
|
||||
"id": "db-connection-uri",
|
||||
"category": "SECRET_DB_URI",
|
||||
"description": "Database or broker connection URI containing credentials",
|
||||
"pattern": "\\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\\+srv)?|redis|rediss|amqp|mssql|sqlserver):\\/\\/[^\\s:@\\/]+:[^\\s@\\/]+@[^\\s\\/\"']+",
|
||||
"profiles": ["swe", "strict"],
|
||||
"priority": 94
|
||||
},
|
||||
{
|
||||
"id": "bearer-auth-header",
|
||||
"category": "SECRET_BEARER",
|
||||
"description": "Bearer authorization header token",
|
||||
"pattern": "(?i)\\bBearer\\s+([A-Za-z0-9\\-._~+/]+=*)",
|
||||
"capture_group": 1,
|
||||
"min_length": 16,
|
||||
"profiles": ["swe", "strict"],
|
||||
"priority": 88
|
||||
},
|
||||
{
|
||||
"id": "env-secret-assignment",
|
||||
"category": "SECRET_ENV_VALUE",
|
||||
"description": "Secret assignment in env/config/code",
|
||||
"pattern": "(?i)(?:^|[\\s,;])(?:[A-Z0-9_]*?(?:API_KEY|SECRET_KEY|ACCESS_KEY|AUTH_TOKEN|ACCESS_TOKEN|REFRESH_TOKEN|CLIENT_SECRET|PRIVATE_KEY|PASSWORD|PASSWD|PWD|SIGNING_KEY|ENCRYPTION_KEY|CONNECTION_STRING|DSN))[\\s]*[:=][\\s]*[\"']?([^\\s\"'#,;}{\\]]{8,})[\"']?",
|
||||
"capture_group": 1,
|
||||
"profiles": ["swe", "strict"],
|
||||
"priority": 85
|
||||
},
|
||||
{
|
||||
"id": "us-ssn-dashed",
|
||||
"category": "PII_SSN",
|
||||
"description": "US Social Security Number (XXX-XX-XXXX)",
|
||||
"pattern": "(?<![0-9-])(\\d{3}-\\d{2}-\\d{4})(?![0-9-])",
|
||||
"capture_group": 1,
|
||||
"validator": "ssn",
|
||||
"profiles": ["pii", "strict"],
|
||||
"priority": 98
|
||||
},
|
||||
{
|
||||
"id": "us-ssn-contextual-undashed",
|
||||
"category": "PII_SSN",
|
||||
"description": "Undashed 9-digit SSN preceded by SSN context label",
|
||||
"pattern": "(?i)\\b(?:ssn|social[ _-]?security(?:[ _-]?num(?:ber)?)?)\\b[\\s:=#\"']*([0-9]{9})\\b",
|
||||
"capture_group": 1,
|
||||
"validator": "ssn",
|
||||
"profiles": ["pii", "strict"],
|
||||
"priority": 96
|
||||
},
|
||||
{
|
||||
"id": "us-itin",
|
||||
"category": "PII_ITIN",
|
||||
"description": "US Individual Taxpayer Identification Number",
|
||||
"pattern": "(?<![0-9-])(9\\d{2}-[789]\\d-\\d{4})(?![0-9-])",
|
||||
"capture_group": 1,
|
||||
"profiles": ["pii", "strict"],
|
||||
"priority": 97
|
||||
},
|
||||
{
|
||||
"id": "us-ein",
|
||||
"category": "PII_EIN",
|
||||
"description": "US Employer Identification Number with context",
|
||||
"pattern": "(?i)\\b(?:ein|fein|tax[ _-]?id)\\b[\\s:=#\"']*(\\d{2}-\\d{7})\\b",
|
||||
"capture_group": 1,
|
||||
"profiles": ["pii", "strict"],
|
||||
"priority": 90
|
||||
},
|
||||
{
|
||||
"id": "dob-contextual",
|
||||
"category": "PII_DOB",
|
||||
"description": "Date of birth near birth/DOB keyword",
|
||||
"pattern": "(?i)\\b(?:dob|d\\.o\\.b\\.?|date[ _-]?of[ _-]?birth|birth[ _-]?date|born(?:[ _-]?on)?)\\b[\\s:=#\"']*(\\d{4}[-/]\\d{1,2}[-/]\\d{1,2}|\\d{1,2}[-/]\\d{1,2}[-/]\\d{2,4}|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)[a-z]*\\.?\\s+\\d{1,2},?\\s+\\d{4})",
|
||||
"capture_group": 1,
|
||||
"profiles": ["pii", "strict"],
|
||||
"priority": 94
|
||||
},
|
||||
{
|
||||
"id": "credit-card",
|
||||
"category": "PII_CARD",
|
||||
"description": "Payment card number validated with Luhn check",
|
||||
"pattern": "(?<![0-9-])((?:\\d{4}[ -]?){3}\\d{4}|\\d{13,16})(?![0-9-])",
|
||||
"capture_group": 1,
|
||||
"validator": "luhn",
|
||||
"profiles": ["pii", "strict"],
|
||||
"priority": 92
|
||||
},
|
||||
{
|
||||
"id": "aba-routing-contextual",
|
||||
"category": "PII_BANK_ROUTING",
|
||||
"description": "US ABA bank routing number with checksum and context",
|
||||
"pattern": "(?i)\\b(?:routing(?:[ _-]?(?:num(?:ber)?|no|#))?|aba)\\b[\\s:=#\"']*(\\d{9})\\b",
|
||||
"capture_group": 1,
|
||||
"validator": "aba_routing",
|
||||
"profiles": ["pii", "strict"],
|
||||
"priority": 91
|
||||
},
|
||||
{
|
||||
"id": "bank-account-contextual",
|
||||
"category": "PII_BANK_ACCOUNT",
|
||||
"description": "Bank account number with context",
|
||||
"pattern": "(?i)\\b(?:acct|account(?:[ _-]?(?:num(?:ber)?|no|#))?)\\b[\\s:=#\"']*(\\d{6,17})\\b",
|
||||
"capture_group": 1,
|
||||
"profiles": ["pii", "strict"],
|
||||
"priority": 86
|
||||
},
|
||||
{
|
||||
"id": "email-address",
|
||||
"category": "PII_EMAIL",
|
||||
"description": "Email address",
|
||||
"pattern": "\\b[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}\\b",
|
||||
"profiles": ["pii", "strict"],
|
||||
"priority": 80
|
||||
},
|
||||
{
|
||||
"id": "us-phone-number",
|
||||
"category": "PII_PHONE",
|
||||
"description": "US/North American phone number",
|
||||
"pattern": "(?:\\+1[\\s.-]?)?(?:\\([2-9]\\d{2}\\)|[2-9]\\d{2})[\\s.-][2-9]\\d{2}[\\s.-]\\d{4}\\b",
|
||||
"profiles": ["pii", "strict"],
|
||||
"priority": 78
|
||||
},
|
||||
{
|
||||
"id": "drivers-license-contextual",
|
||||
"category": "PII_STATE_ID",
|
||||
"description": "Driver's license or state ID with context",
|
||||
"pattern": "(?i)\\b(?:driver'?s?[ _-]?licen[cs]e|dl[ _-]?(?:num(?:ber)?|#)|state[ _-]?id|medicaid[ _-]?id|case[ _-]?(?:num(?:ber)?|id))\\b[\\s:=#\"']*([A-Z0-9\\-]{5,20})\\b",
|
||||
"capture_group": 1,
|
||||
"profiles": ["pii", "strict"],
|
||||
"priority": 88
|
||||
},
|
||||
{
|
||||
"id": "us-street-address",
|
||||
"category": "PII_ADDRESS",
|
||||
"description": "US street address line",
|
||||
"pattern": "\\b\\d{1,6}\\s+(?:[A-Za-z0-9.'-]+\\s+){1,4}(?:St(?:reet)?|Ave(?:nue)?|Blvd|Boulevard|Rd|Road|Dr(?:ive)?|Ln|Lane|Ct|Court|Way|Pl(?:ace)?|Pkwy|Parkway|Cir(?:cle)?|Ter(?:race)?)\\b\\.?(?:\\s+(?:Apt|Suite|Ste|Unit|#)\\s*[A-Za-z0-9-]+)?",
|
||||
"profiles": ["pii", "strict"],
|
||||
"priority": 75
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Antigravity lifecycle hook script (`PreToolUse` and `PreInvocation`).
|
||||
|
||||
Runs with zero third-party dependencies using Python 3.9+ stdlib.
|
||||
- pre-tool: Blocks native file/shell tools from accessing protected paths,
|
||||
sensitive filenames (.env, credentials.json, id_rsa), or secret key extensions
|
||||
(.pem, .key, .pfx, .p12, .kdbx), reading optional overrides from
|
||||
`<cwd>/.redactorpolicy.json`.
|
||||
- pre-invocation: Scans `lastUserInput` before the model is called and halts
|
||||
immediately if raw SSNs, API keys, or private keys were pasted into chat.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
# Allow running directly without `pip install` by adding repo `src/` to sys.path
|
||||
_REPO_SRC = Path(__file__).resolve().parents[2] / "src"
|
||||
if _REPO_SRC.is_dir() and str(_REPO_SRC) not in sys.path:
|
||||
sys.path.insert(0, str(_REPO_SRC))
|
||||
|
||||
from redactor_mcp.scanner import RedactionScanner # noqa: E402
|
||||
|
||||
DEFAULT_PROTECTED_MARKERS = ("sensitive", "final-output", ".env")
|
||||
DEFAULT_PROTECTED_FILENAMES = (
|
||||
"credentials.json",
|
||||
"secrets.json",
|
||||
"secrets.yaml",
|
||||
"secrets.yml",
|
||||
"id_rsa",
|
||||
"id_ed25519",
|
||||
)
|
||||
DEFAULT_PROTECTED_EXTENSIONS = (
|
||||
".pem",
|
||||
".key",
|
||||
".pfx",
|
||||
".p12",
|
||||
".kdbx",
|
||||
".jks",
|
||||
".keystore",
|
||||
".ppk",
|
||||
)
|
||||
|
||||
FILE_OR_SHELL_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",
|
||||
}
|
||||
|
||||
HIGH_CONFIDENCE_PII_SECRETS = {
|
||||
"PII_SSN",
|
||||
"PII_ITIN",
|
||||
"SECRET_PRIVATE_KEY",
|
||||
"SECRET_AWS_KEY",
|
||||
"SECRET_GITHUB_TOKEN",
|
||||
"SECRET_GITLAB_TOKEN",
|
||||
"SECRET_STRIPE_KEY",
|
||||
"SECRET_SLACK_TOKEN",
|
||||
"SECRET_GCP_KEY",
|
||||
"SECRET_LLM_KEY",
|
||||
"SECRET_DB_URI",
|
||||
}
|
||||
|
||||
|
||||
def _load_policy_overrides(payload: dict[str, Any]) -> dict[str, tuple[str, ...]]:
|
||||
markers = list(DEFAULT_PROTECTED_MARKERS)
|
||||
filenames = list(DEFAULT_PROTECTED_FILENAMES)
|
||||
extensions = list(DEFAULT_PROTECTED_EXTENSIONS)
|
||||
|
||||
env_markers = os.environ.get("REDACTOR_PROTECTED_PATHS", "").strip()
|
||||
if env_markers:
|
||||
markers = [m.strip().lower() for m in env_markers.split(",") if m.strip()]
|
||||
|
||||
candidates: list[Path] = []
|
||||
if payload.get("cwd"):
|
||||
candidates.append(Path(str(payload["cwd"])) / ".redactorpolicy.json")
|
||||
for wp in payload.get("workspacePaths") or []:
|
||||
candidates.append(Path(str(wp)) / ".redactorpolicy.json")
|
||||
|
||||
for policy_file in candidates:
|
||||
if policy_file.is_file():
|
||||
try:
|
||||
data = json.loads(policy_file.read_text(encoding="utf-8"))
|
||||
if data.get("protectedPaths"):
|
||||
markers = [str(x).lower() for x in data["protectedPaths"]]
|
||||
if data.get("protectedFilenames"):
|
||||
filenames.extend(str(x).lower() for x in data["protectedFilenames"])
|
||||
if data.get("protectedExtensions"):
|
||||
extensions.extend(str(x).lower() for x in data["protectedExtensions"])
|
||||
break
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
return {
|
||||
"markers": tuple(dict.fromkeys(markers)),
|
||||
"filenames": tuple(dict.fromkeys(filenames)),
|
||||
"extensions": tuple(dict.fromkeys(extensions)),
|
||||
}
|
||||
|
||||
|
||||
def _deny(reason: str) -> dict[str, Any]:
|
||||
return {"decision": "deny", "reason": reason}
|
||||
|
||||
|
||||
def handle_pre_tool(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
tool_call = payload.get("toolCall") or {}
|
||||
tool_name = str(tool_call.get("name", ""))
|
||||
if tool_name not in FILE_OR_SHELL_TOOLS:
|
||||
return {"decision": "allow"}
|
||||
|
||||
policy = _load_policy_overrides(payload)
|
||||
args_dict = tool_call.get("args") or {}
|
||||
args_blob = json.dumps(args_dict).lower()
|
||||
|
||||
for marker in policy["markers"]:
|
||||
if marker in args_blob:
|
||||
return _deny(
|
||||
f"Blocked direct access to protected path marker '{marker}'. "
|
||||
"Use `redactor-vault` MCP tools (`vault_read_file`, "
|
||||
"`vault_stage_workspace`, `vault_write_file`) instead."
|
||||
)
|
||||
|
||||
for fname in policy["filenames"]:
|
||||
if re.search(rf"(?<![a-z0-9_.-]){re.escape(fname)}(?![a-z0-9_.-])", args_blob):
|
||||
return _deny(
|
||||
f"Blocked direct access to sensitive file '{fname}'. "
|
||||
"Read via `redactor-vault` MCP (`vault_read_file`) instead."
|
||||
)
|
||||
|
||||
for ext in policy["extensions"]:
|
||||
if re.search(rf"{re.escape(ext)}(?![a-z0-9_])", args_blob):
|
||||
return _deny(
|
||||
f"Blocked direct access to sensitive key/certificate extension '{ext}'. "
|
||||
"Use `redactor-vault` MCP tools instead."
|
||||
)
|
||||
|
||||
return {"decision": "allow"}
|
||||
|
||||
|
||||
def handle_pre_invocation(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
last_input = str(payload.get("lastUserInput") or "")
|
||||
if not last_input.strip():
|
||||
return {}
|
||||
|
||||
scanner = RedactionScanner(enable_entropy=False, enable_ner=False)
|
||||
matches = scanner.scan(last_input, profile="strict")
|
||||
flagged = sorted({m.category for m in matches if m.category in HIGH_CONFIDENCE_PII_SECRETS})
|
||||
if not flagged:
|
||||
return {}
|
||||
|
||||
joined = ", ".join(flagged)
|
||||
return {
|
||||
"injectSteps": [
|
||||
{
|
||||
"errorMessage": {
|
||||
"userMessage": (
|
||||
f"Blocked before model call: raw sensitive data detected ({joined}). "
|
||||
"Run `redactor-mcp sanitize` (or the clipboard helper) before pasting into chat."
|
||||
)
|
||||
}
|
||||
}
|
||||
],
|
||||
"terminationBehavior": "terminate",
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Antigravity redactor guard hook.")
|
||||
parser.add_argument("--mode", required=True, choices=["pre-tool", "pre-invocation"])
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
raw_stdin = sys.stdin.read().strip()
|
||||
payload = json.loads(raw_stdin) if raw_stdin else {}
|
||||
|
||||
if args.mode == "pre-tool":
|
||||
output = handle_pre_tool(payload)
|
||||
else:
|
||||
output = handle_pre_invocation(payload)
|
||||
|
||||
sys.stdout.write(json.dumps(output))
|
||||
sys.stdout.flush()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,29 @@
|
||||
param(
|
||||
[Parameter(Mandatory=$true)]
|
||||
[ValidateSet("sanitize", "restore")]
|
||||
[string]$Mode,
|
||||
|
||||
[string]$Session = "default",
|
||||
[string]$Profile = "strict",
|
||||
[string]$Distro = "Ubuntu"
|
||||
)
|
||||
|
||||
$clipText = Get-Clipboard -Raw
|
||||
if ([string]::IsNullOrEmpty($clipText)) {
|
||||
Write-Error "Clipboard is empty."
|
||||
exit 1
|
||||
}
|
||||
|
||||
if ($Mode -eq "sanitize") {
|
||||
$result = $clipText | wsl.exe -d $Distro -- docker exec -i pii-redactor redactor-mcp sanitize --session $Session --profile $Profile
|
||||
} else {
|
||||
$result = $clipText | wsl.exe -d $Distro -- docker exec -i pii-redactor redactor-mcp restore --session $Session
|
||||
}
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Error "Failed to process clipboard via pii-redactor container."
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
|
||||
$result | Set-Clipboard
|
||||
Write-Host "Clipboard updated ($Mode) for session '$Session'."
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Bootstrap script to run inside WSL2 (Ubuntu) on Windows
|
||||
mkdir -p work/sensitive work/clean-staging work/final-output
|
||||
chmod 700 work/sensitive work/final-output
|
||||
|
||||
echo "Building and starting zero-egress pii-redactor container..."
|
||||
docker compose up -d --build
|
||||
|
||||
echo "Verifying daemon status..."
|
||||
docker exec -i pii-redactor redactor-mcp status
|
||||
echo "Ready! Configure Antigravity (~/.gemini/config/mcp_config.json) or Kiro (.kiro/settings/mcp.json) using configs/."
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Redactor MCP: local zero-egress PII & secrets redaction/rehydration package."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,49 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
class AuditLogger:
|
||||
"""Append-only JSONL compliance audit logger (strictly zero plaintext secrets)."""
|
||||
|
||||
def __init__(self, log_path: Optional[Path] = None) -> None:
|
||||
raw = log_path or (
|
||||
Path(os.environ["REDACTOR_AUDIT_LOG"])
|
||||
if os.environ.get("REDACTOR_AUDIT_LOG")
|
||||
else None
|
||||
)
|
||||
self.log_path: Optional[Path] = raw
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def record(
|
||||
self,
|
||||
event: str,
|
||||
session_id: Optional[str] = None,
|
||||
target: Optional[str] = None,
|
||||
categories: Optional[dict[str, int]] = None,
|
||||
token_count: int = 0,
|
||||
extra: Optional[dict[str, Any]] = None,
|
||||
) -> None:
|
||||
if self.log_path is None:
|
||||
return
|
||||
entry: dict[str, Any] = {
|
||||
"ts": datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
"event": event,
|
||||
"session_id": session_id,
|
||||
"target": target,
|
||||
"token_count": token_count,
|
||||
"categories": categories or {},
|
||||
}
|
||||
if extra:
|
||||
entry["meta"] = extra
|
||||
|
||||
line = json.dumps(entry, separators=(",", ":")) + "\n"
|
||||
with self._lock:
|
||||
self.log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with self.log_path.open("a", encoding="utf-8") as fh:
|
||||
fh.write(line)
|
||||
@@ -0,0 +1,146 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
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
|
||||
|
||||
|
||||
def _read_input_text(file_arg: str | None) -> str:
|
||||
if file_arg:
|
||||
return Path(file_arg).read_text(encoding="utf-8")
|
||||
return sys.stdin.read()
|
||||
|
||||
|
||||
def _resolve_passphrase(arg_val: str | None) -> str:
|
||||
if arg_val:
|
||||
return arg_val
|
||||
env_pw = os.environ.get("REDACTOR_SNAPSHOT_PASSPHRASE", "")
|
||||
if env_pw:
|
||||
return env_pw
|
||||
return getpass.getpass("Snapshot passphrase: ")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="redactor-mcp",
|
||||
description="Zero-egress PII & secrets redaction/rehydration MCP server and CLI.",
|
||||
)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
p_daemon = sub.add_parser("daemon", help="Run the persistent Unix-socket RAM vault daemon.")
|
||||
p_daemon.add_argument("--socket", default=None, help="Unix socket path (default: REDACTOR_SOCKET or /run/vault/daemon.sock)")
|
||||
|
||||
p_mcp = sub.add_parser("mcp", help="Run the MCP stdio server.")
|
||||
p_mcp.add_argument("--stdlib", action="store_true", help="Force built-in stdlib JSON-RPC MCP server.")
|
||||
|
||||
p_san = sub.add_parser("sanitize", help="Redact stdin or a file using the vault.")
|
||||
p_san.add_argument("--file", default=None, help="Optional input file (reads stdin if omitted).")
|
||||
p_san.add_argument("--session", default="default", help="Vault session ID.")
|
||||
p_san.add_argument("--profile", default="strict", choices=["strict", "pii", "swe"])
|
||||
p_san.add_argument("--format-preserving", action="store_true", help="Emit reserved synthetic tokens.")
|
||||
p_san.add_argument("--content-type", default="", help="Optional schema hint: json, jsonl, csv, tsv, sql.")
|
||||
p_san.add_argument("--json", action="store_true", help="Output full JSON metadata.")
|
||||
|
||||
p_res = sub.add_parser("restore", help="Rehydrate placeholders from stdin or a file (host CLI only).")
|
||||
p_res.add_argument("--file", default=None, help="Optional input file (reads stdin if omitted).")
|
||||
p_res.add_argument("--session", default="default", help="Vault session ID.")
|
||||
p_res.add_argument("--json", action="store_true", help="Output full JSON metadata.")
|
||||
|
||||
p_snap_save = sub.add_parser("snapshot-save", help="Save an encrypted session vault snapshot to disk.")
|
||||
p_snap_save.add_argument("dest_path", help="Path for encrypted snapshot file.")
|
||||
p_snap_save.add_argument("--session", default=None, help="Optional single session ID.")
|
||||
p_snap_save.add_argument("--passphrase", default=None, help="Passphrase (or REDACTOR_SNAPSHOT_PASSPHRASE).")
|
||||
|
||||
p_snap_load = sub.add_parser("snapshot-load", help="Restore an encrypted session vault snapshot into RAM.")
|
||||
p_snap_load.add_argument("src_path", help="Path to encrypted snapshot file.")
|
||||
p_snap_load.add_argument("--replace", action="store_true", help="Replace active sessions instead of merging.")
|
||||
p_snap_load.add_argument("--passphrase", default=None, help="Passphrase (or REDACTOR_SNAPSHOT_PASSPHRASE).")
|
||||
|
||||
p_stat = sub.add_parser("status", help="Inspect non-secret vault session metadata.")
|
||||
p_stat.add_argument("--session", default=None, help="Optional session ID.")
|
||||
|
||||
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).")
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.command == "daemon":
|
||||
run_daemon(socket_path=args.socket)
|
||||
return 0
|
||||
|
||||
if args.command == "mcp":
|
||||
run_mcp_stdio(force_stdlib=args.stdlib)
|
||||
return 0
|
||||
|
||||
client = VaultClient()
|
||||
|
||||
if args.command == "sanitize":
|
||||
text = _read_input_text(args.file)
|
||||
res = client.call(
|
||||
"redact_text",
|
||||
{
|
||||
"text": text,
|
||||
"session_id": args.session,
|
||||
"profile": args.profile,
|
||||
"format_preserving": args.format_preserving,
|
||||
"content_type": args.content_type,
|
||||
},
|
||||
)
|
||||
if args.json:
|
||||
print(json.dumps(res, indent=2))
|
||||
else:
|
||||
sys.stdout.write(res["redacted_text"])
|
||||
return 0
|
||||
|
||||
if args.command == "restore":
|
||||
text = _read_input_text(args.file)
|
||||
res = client.call(
|
||||
"rehydrate_text_cli",
|
||||
{"text": text, "session_id": args.session},
|
||||
)
|
||||
if args.json:
|
||||
print(json.dumps(res, indent=2))
|
||||
else:
|
||||
sys.stdout.write(res["restored_text"])
|
||||
return 0
|
||||
|
||||
if args.command == "snapshot-save":
|
||||
pw = _resolve_passphrase(args.passphrase)
|
||||
res = client.call(
|
||||
"save_snapshot",
|
||||
{"dest_path": args.dest_path, "passphrase": pw, "session_id": args.session},
|
||||
)
|
||||
print(json.dumps(res, indent=2))
|
||||
return 0
|
||||
|
||||
if args.command == "snapshot-load":
|
||||
pw = _resolve_passphrase(args.passphrase)
|
||||
res = client.call(
|
||||
"load_snapshot",
|
||||
{"src_path": args.src_path, "passphrase": pw, "merge": not args.replace},
|
||||
)
|
||||
print(json.dumps(res, indent=2))
|
||||
return 0
|
||||
|
||||
if args.command == "status":
|
||||
res = client.call("status", {"session_id": args.session})
|
||||
print(json.dumps(res, indent=2))
|
||||
return 0
|
||||
|
||||
if args.command == "purge":
|
||||
res = client.call("purge", {"session_id": args.session})
|
||||
print(json.dumps(res, indent=2))
|
||||
return 0
|
||||
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,54 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from redactor_mcp.service import RedactorService
|
||||
|
||||
|
||||
class VaultClient:
|
||||
"""Calls either the running Unix-socket daemon or an in-process RedactorService."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
socket_path: Optional[str] = None,
|
||||
service: Optional[RedactorService] = None,
|
||||
) -> None:
|
||||
env_sock = os.environ.get("REDACTOR_SOCKET", "").strip()
|
||||
self.socket_path = socket_path or env_sock or "/run/vault/daemon.sock"
|
||||
self._in_process_service = service
|
||||
|
||||
def _use_socket(self) -> bool:
|
||||
if self._in_process_service is not None:
|
||||
return False
|
||||
return Path(self.socket_path).exists()
|
||||
|
||||
def call(self, method: str, params: Optional[dict[str, Any]] = None) -> dict[str, Any]:
|
||||
payload = params or {}
|
||||
if not self._use_socket():
|
||||
if self._in_process_service is None:
|
||||
self._in_process_service = RedactorService()
|
||||
return self._in_process_service.dispatch(method, payload)
|
||||
|
||||
req_line = (json.dumps({"method": method, "params": payload}) + "\n").encode("utf-8")
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
|
||||
sock.connect(self.socket_path)
|
||||
sock.sendall(req_line)
|
||||
chunks: list[bytes] = []
|
||||
while True:
|
||||
data = sock.recv(65536)
|
||||
if not data:
|
||||
break
|
||||
chunks.append(data)
|
||||
if b"\n" in data:
|
||||
break
|
||||
raw = b"".join(chunks).decode("utf-8").strip()
|
||||
if not raw:
|
||||
raise RuntimeError("Empty response from vault daemon")
|
||||
resp = json.loads(raw.splitlines()[0])
|
||||
if not resp.get("ok"):
|
||||
raise RuntimeError(resp.get("error", "Unknown daemon error"))
|
||||
return resp["result"]
|
||||
@@ -0,0 +1,144 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM # type: ignore
|
||||
except ImportError: # pragma: no cover - fallback uses OpenSSL + HMAC-SHA256
|
||||
AESGCM = None # type: ignore
|
||||
|
||||
PBKDF2_ITERATIONS = 200_000
|
||||
|
||||
|
||||
def _derive_keys(passphrase: str, salt: bytes) -> tuple[bytes, bytes]:
|
||||
material = hashlib.pbkdf2_hmac(
|
||||
"sha256",
|
||||
passphrase.encode("utf-8"),
|
||||
salt,
|
||||
PBKDF2_ITERATIONS,
|
||||
dklen=64,
|
||||
)
|
||||
return material[:32], material[32:]
|
||||
|
||||
|
||||
def encrypt_snapshot(payload: dict[str, Any], passphrase: str) -> bytes:
|
||||
"""Encrypt a vault snapshot using AES-256-GCM (or OpenSSL AES-256-CBC + HMAC-SHA256)."""
|
||||
if not passphrase:
|
||||
raise ValueError("Passphrase must not be empty")
|
||||
plaintext = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
||||
salt = secrets.token_bytes(16)
|
||||
enc_key, mac_key = _derive_keys(passphrase, salt)
|
||||
|
||||
if AESGCM is not None:
|
||||
nonce = secrets.token_bytes(12)
|
||||
ct = AESGCM(enc_key).encrypt(nonce, plaintext, b"redactor-mcp-v1")
|
||||
envelope = {
|
||||
"v": 1,
|
||||
"alg": "aes-256-gcm",
|
||||
"salt": base64.b64encode(salt).decode("ascii"),
|
||||
"nonce": base64.b64encode(nonce).decode("ascii"),
|
||||
"ct": base64.b64encode(ct).decode("ascii"),
|
||||
}
|
||||
return json.dumps(envelope).encode("utf-8")
|
||||
|
||||
# Fallback: Encrypt-then-MAC using OpenSSL AES-256-CBC + HMAC-SHA256
|
||||
iv = secrets.token_bytes(16)
|
||||
proc = subprocess.run(
|
||||
[
|
||||
"openssl",
|
||||
"enc",
|
||||
"-aes-256-cbc",
|
||||
"-K",
|
||||
enc_key.hex(),
|
||||
"-iv",
|
||||
iv.hex(),
|
||||
"-nosalt",
|
||||
],
|
||||
input=plaintext,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
ct = proc.stdout
|
||||
tag = hmac.new(mac_key, b"redactor-mcp-v1" + salt + iv + ct, hashlib.sha256).digest()
|
||||
envelope = {
|
||||
"v": 1,
|
||||
"alg": "aes-256-cbc-hmac-sha256",
|
||||
"salt": base64.b64encode(salt).decode("ascii"),
|
||||
"iv": base64.b64encode(iv).decode("ascii"),
|
||||
"ct": base64.b64encode(ct).decode("ascii"),
|
||||
"mac": base64.b64encode(tag).decode("ascii"),
|
||||
}
|
||||
return json.dumps(envelope).encode("utf-8")
|
||||
|
||||
|
||||
def decrypt_snapshot(blob: bytes, passphrase: str) -> dict[str, Any]:
|
||||
"""Authenticate and decrypt a vault snapshot."""
|
||||
if not passphrase:
|
||||
raise ValueError("Passphrase must not be empty")
|
||||
envelope = json.loads(blob.decode("utf-8"))
|
||||
alg = envelope.get("alg")
|
||||
salt = base64.b64decode(envelope["salt"])
|
||||
enc_key, mac_key = _derive_keys(passphrase, salt)
|
||||
|
||||
if alg == "aes-256-gcm":
|
||||
if AESGCM is None:
|
||||
raise RuntimeError("`cryptography` package is required to decrypt aes-256-gcm snapshots")
|
||||
nonce = base64.b64decode(envelope["nonce"])
|
||||
ct = base64.b64decode(envelope["ct"])
|
||||
plaintext = AESGCM(enc_key).decrypt(nonce, ct, b"redactor-mcp-v1")
|
||||
return json.loads(plaintext.decode("utf-8"))
|
||||
|
||||
if alg == "aes-256-cbc-hmac-sha256":
|
||||
iv = base64.b64decode(envelope["iv"])
|
||||
ct = base64.b64decode(envelope["ct"])
|
||||
tag = base64.b64decode(envelope["mac"])
|
||||
expected_tag = hmac.new(
|
||||
mac_key, b"redactor-mcp-v1" + salt + iv + ct, hashlib.sha256
|
||||
).digest()
|
||||
if not hmac.compare_digest(tag, expected_tag):
|
||||
raise ValueError("Snapshot authentication failed (wrong passphrase or corrupted file)")
|
||||
proc = subprocess.run(
|
||||
[
|
||||
"openssl",
|
||||
"enc",
|
||||
"-d",
|
||||
"-aes-256-cbc",
|
||||
"-K",
|
||||
enc_key.hex(),
|
||||
"-iv",
|
||||
iv.hex(),
|
||||
"-nosalt",
|
||||
],
|
||||
input=ct,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
return json.loads(proc.stdout.decode("utf-8"))
|
||||
|
||||
raise ValueError(f"Unsupported snapshot algorithm: {alg}")
|
||||
|
||||
|
||||
def save_encrypted_snapshot_file(
|
||||
payload: dict[str, Any], dest_path: Path, passphrase: str
|
||||
) -> int:
|
||||
blob = encrypt_snapshot(payload, passphrase)
|
||||
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest_path.write_bytes(blob)
|
||||
try:
|
||||
os.chmod(dest_path, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
return len(blob)
|
||||
|
||||
|
||||
def load_encrypted_snapshot_file(src_path: Path, passphrase: str) -> dict[str, Any]:
|
||||
blob = src_path.read_bytes()
|
||||
return decrypt_snapshot(blob, passphrase)
|
||||
@@ -0,0 +1,83 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from redactor_mcp.service import RedactorService
|
||||
|
||||
DEFAULT_SOCKET_PATH = "/run/vault/daemon.sock"
|
||||
|
||||
|
||||
class VaultDaemon:
|
||||
"""Asyncio Unix domain socket daemon hosting the shared RAM vault."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
socket_path: str = DEFAULT_SOCKET_PATH,
|
||||
service: Optional[RedactorService] = None,
|
||||
) -> None:
|
||||
self.socket_path = Path(socket_path)
|
||||
self.service = service or RedactorService()
|
||||
self._server: Optional[asyncio.AbstractServer] = None
|
||||
|
||||
async def _handle_client(
|
||||
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
|
||||
) -> None:
|
||||
try:
|
||||
while True:
|
||||
line = await reader.readline()
|
||||
if not line:
|
||||
break
|
||||
response: dict[str, Any]
|
||||
try:
|
||||
req = json.loads(line.decode("utf-8"))
|
||||
method = req["method"]
|
||||
params = req.get("params", {})
|
||||
result = self.service.dispatch(method, params)
|
||||
response = {"ok": True, "result": result}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
response = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
|
||||
|
||||
payload = (json.dumps(response) + "\n").encode("utf-8")
|
||||
writer.write(payload)
|
||||
await writer.drain()
|
||||
finally:
|
||||
writer.close()
|
||||
try:
|
||||
await writer.wait_closed()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
async def serve(self) -> None:
|
||||
self.socket_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if self.socket_path.exists():
|
||||
self.socket_path.unlink()
|
||||
|
||||
self._server = await asyncio.start_unix_server(
|
||||
self._handle_client, path=str(self.socket_path)
|
||||
)
|
||||
os.chmod(self.socket_path, 0o600)
|
||||
|
||||
stop_event = asyncio.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
try:
|
||||
loop.add_signal_handler(sig, stop_event.set)
|
||||
except NotImplementedError:
|
||||
pass
|
||||
|
||||
async with self._server:
|
||||
await stop_event.wait()
|
||||
|
||||
if self.socket_path.exists():
|
||||
self.socket_path.unlink()
|
||||
|
||||
|
||||
def run_daemon(socket_path: Optional[str] = None) -> None:
|
||||
sock = socket_path or os.environ.get("REDACTOR_SOCKET", DEFAULT_SOCKET_PATH)
|
||||
daemon = VaultDaemon(socket_path=sock)
|
||||
asyncio.run(daemon.serve())
|
||||
@@ -0,0 +1,64 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RuleConfig:
|
||||
"""Single redaction rule definition."""
|
||||
|
||||
id: str
|
||||
category: str
|
||||
pattern: str
|
||||
profiles: tuple[str, ...] = ("strict",)
|
||||
priority: int = 50
|
||||
capture_group: int = 0
|
||||
validator: Optional[str] = None
|
||||
min_length: int = 0
|
||||
description: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DetectionMatch:
|
||||
"""Span of detected sensitive data in source text."""
|
||||
|
||||
start: int
|
||||
end: int
|
||||
value: str
|
||||
category: str
|
||||
rule_id: str
|
||||
priority: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class TokenRecord:
|
||||
"""Metadata for a single vaulted placeholder (never exposes raw value in logs)."""
|
||||
|
||||
placeholder: str
|
||||
category: str
|
||||
rule_id: str
|
||||
sha256_prefix: str
|
||||
hit_count: int = 1
|
||||
|
||||
|
||||
@dataclass
|
||||
class RedactionResult:
|
||||
"""Result returned after scanning and redacting text."""
|
||||
|
||||
redacted_text: str
|
||||
session_id: str
|
||||
replacements: int
|
||||
categories: dict[str, int] = field(default_factory=dict)
|
||||
placeholders: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RehydrationSummary:
|
||||
"""Result returned by one-way egress rehydration (never returns raw text)."""
|
||||
|
||||
destination: str
|
||||
bytes_written: int
|
||||
tokens_restored: int
|
||||
unresolved_tokens: list[str] = field(default_factory=list)
|
||||
session_id: str = ""
|
||||
@@ -0,0 +1,306 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable, Optional
|
||||
|
||||
from redactor_mcp.models import DetectionMatch, RuleConfig
|
||||
from redactor_mcp.validators import VALIDATORS, shannon_entropy
|
||||
|
||||
try:
|
||||
import yaml # type: ignore
|
||||
except ImportError: # pragma: no cover - optional when PyYAML isn't installed
|
||||
yaml = None # type: ignore
|
||||
|
||||
try:
|
||||
from presidio_analyzer import AnalyzerEngine # type: ignore
|
||||
except ImportError: # pragma: no cover - optional heavy NER dependency
|
||||
AnalyzerEngine = None # type: ignore
|
||||
|
||||
|
||||
DEFAULT_RULES_PATH = Path(__file__).resolve().parents[2] / "rules" / "default_rules.json"
|
||||
|
||||
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+)"
|
||||
)
|
||||
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}$")
|
||||
HEX_HASH_RE = re.compile(r"^[0-9a-fA-F]{32,128}$")
|
||||
|
||||
# Common benign placeholder values in templates/tests we should not vault as secrets
|
||||
BENIGN_PLACEHOLDERS = {
|
||||
"changeme",
|
||||
"your_api_key",
|
||||
"your-api-key",
|
||||
"replace_me",
|
||||
"placeholder",
|
||||
"example_secret",
|
||||
"dummy_token",
|
||||
}
|
||||
|
||||
|
||||
def is_binary_bytes(sample: bytes) -> bool:
|
||||
"""Heuristically detect binary data so source/text scanning skips binaries."""
|
||||
if not sample:
|
||||
return False
|
||||
if b"\x00" in sample:
|
||||
return True
|
||||
text_chars = bytearray({7, 8, 9, 10, 12, 13, 27} | set(range(0x20, 0x100)) - {0x7F})
|
||||
non_text = sample.translate(None, text_chars)
|
||||
return (len(non_text) / len(sample)) > 0.30
|
||||
|
||||
|
||||
def _parse_rules_payload(path: Path) -> dict[str, Any]:
|
||||
raw_text = path.read_text(encoding="utf-8")
|
||||
if path.suffix.lower() in {".yaml", ".yml"}:
|
||||
if yaml is None:
|
||||
raise RuntimeError(f"PyYAML is required to load YAML rules from {path}")
|
||||
return yaml.safe_load(raw_text) or {}
|
||||
return json.loads(raw_text)
|
||||
|
||||
|
||||
def _rules_from_payload(payload: dict[str, Any]) -> list[RuleConfig]:
|
||||
rules: list[RuleConfig] = []
|
||||
for item in payload.get("rules", []):
|
||||
rules.append(
|
||||
RuleConfig(
|
||||
id=item["id"],
|
||||
category=item["category"],
|
||||
pattern=item["pattern"],
|
||||
profiles=tuple(item.get("profiles", ["strict"])),
|
||||
priority=int(item.get("priority", 50)),
|
||||
capture_group=int(item.get("capture_group", 0)),
|
||||
validator=item.get("validator"),
|
||||
min_length=int(item.get("min_length", 0)),
|
||||
description=item.get("description", ""),
|
||||
)
|
||||
)
|
||||
return rules
|
||||
|
||||
|
||||
def normalize_key_name(key: str) -> str:
|
||||
"""Normalize JSON/CSV/SQL field names for schema-aware matching."""
|
||||
return re.sub(r"[^a-z0-9]+", "_", key.strip().lower()).strip("_")
|
||||
|
||||
|
||||
class RedactionScanner:
|
||||
"""Two-tier offline PII and secrets scanner with allowlist and schema key metadata."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
rules: Optional[Iterable[RuleConfig]] = None,
|
||||
custom_rules_path: Optional[Path] = None,
|
||||
enable_entropy: bool = True,
|
||||
entropy_threshold: float = 4.2,
|
||||
enable_ner: bool = False,
|
||||
) -> None:
|
||||
base_payload = _parse_rules_payload(DEFAULT_RULES_PATH)
|
||||
loaded = list(rules) if rules is not None else _rules_from_payload(base_payload)
|
||||
|
||||
allowlist_exact: set[str] = set(
|
||||
v.lower() for v in base_payload.get("allowlist", {}).get("exact_values", [])
|
||||
)
|
||||
allowlist_patterns: list[re.Pattern[str]] = [
|
||||
re.compile(p) for p in base_payload.get("allowlist", {}).get("patterns", [])
|
||||
]
|
||||
ignore_globs: list[str] = list(
|
||||
base_payload.get("allowlist", {}).get("ignore_globs", [])
|
||||
)
|
||||
sensitive_keys: dict[str, str] = {}
|
||||
for k, v in base_payload.get("sensitive_keys", {}).items():
|
||||
sensitive_keys[normalize_key_name(k)] = v
|
||||
for cat, keys in base_payload.get("sensitive_key_groups", {}).items():
|
||||
for k in keys:
|
||||
sensitive_keys[normalize_key_name(k)] = cat
|
||||
|
||||
env_custom = custom_rules_path or (
|
||||
Path(os.environ["REDACTOR_CUSTOM_RULES"])
|
||||
if os.environ.get("REDACTOR_CUSTOM_RULES")
|
||||
else None
|
||||
)
|
||||
if env_custom and env_custom.exists():
|
||||
custom_payload = _parse_rules_payload(env_custom)
|
||||
loaded.extend(_rules_from_payload(custom_payload))
|
||||
allow_cfg = custom_payload.get("allowlist", {})
|
||||
allowlist_exact.update(v.lower() for v in allow_cfg.get("exact_values", []))
|
||||
allowlist_patterns.extend(re.compile(p) for p in allow_cfg.get("patterns", []))
|
||||
ignore_globs.extend(allow_cfg.get("ignore_globs", []))
|
||||
for k, v in custom_payload.get("sensitive_keys", {}).items():
|
||||
sensitive_keys[normalize_key_name(k)] = v
|
||||
for cat, keys in custom_payload.get("sensitive_key_groups", {}).items():
|
||||
for k in keys:
|
||||
sensitive_keys[normalize_key_name(k)] = cat
|
||||
|
||||
self.rules: list[RuleConfig] = loaded
|
||||
self._compiled: list[tuple[RuleConfig, re.Pattern[str]]] = [
|
||||
(rule, re.compile(rule.pattern)) for rule in self.rules
|
||||
]
|
||||
self.allowlist_exact = allowlist_exact
|
||||
self.allowlist_patterns = allowlist_patterns
|
||||
self.ignore_globs = ignore_globs
|
||||
self.sensitive_keys = sensitive_keys
|
||||
self.enable_entropy = enable_entropy
|
||||
self.entropy_threshold = entropy_threshold
|
||||
self.enable_ner = enable_ner
|
||||
self._ner_engine: Any = None
|
||||
|
||||
def is_allowlisted(self, value: str) -> bool:
|
||||
stripped = value.strip()
|
||||
if not stripped:
|
||||
return True
|
||||
if stripped.lower() in BENIGN_PLACEHOLDERS or stripped.lower() in self.allowlist_exact:
|
||||
return True
|
||||
if EXISTING_TOKEN_RE.fullmatch(stripped) or SYNTHETIC_TOKEN_RE.fullmatch(stripped):
|
||||
return True
|
||||
return any(pat.search(stripped) for pat in self.allowlist_patterns)
|
||||
|
||||
def _get_ner_engine(self) -> Any:
|
||||
if not self.enable_ner or AnalyzerEngine is None:
|
||||
return None
|
||||
if self._ner_engine is None:
|
||||
self._ner_engine = AnalyzerEngine()
|
||||
return self._ner_engine
|
||||
|
||||
def scan(self, text: str, profile: str = "strict") -> list[DetectionMatch]:
|
||||
"""Return non-overlapping sensitive spans sorted by start offset."""
|
||||
if not text:
|
||||
return []
|
||||
|
||||
protected_ranges = [
|
||||
(m.start(), m.end()) for m in EXISTING_TOKEN_RE.finditer(text)
|
||||
] + [(m.start(), m.end()) for m in SYNTHETIC_TOKEN_RE.finditer(text)]
|
||||
candidates: list[DetectionMatch] = []
|
||||
|
||||
for rule, compiled in self._compiled:
|
||||
if profile != "strict" and profile not in rule.profiles:
|
||||
continue
|
||||
for match in compiled.finditer(text):
|
||||
group_idx = rule.capture_group
|
||||
start, end = match.span(group_idx)
|
||||
if start < 0 or end <= start:
|
||||
continue
|
||||
if _overlaps_any(start, end, protected_ranges):
|
||||
continue
|
||||
value = text[start:end]
|
||||
if len(value) < rule.min_length:
|
||||
continue
|
||||
if self.is_allowlisted(value):
|
||||
continue
|
||||
if rule.validator:
|
||||
validator_fn = VALIDATORS.get(rule.validator)
|
||||
if validator_fn and not validator_fn(value):
|
||||
continue
|
||||
candidates.append(
|
||||
DetectionMatch(
|
||||
start=start,
|
||||
end=end,
|
||||
value=value,
|
||||
category=rule.category,
|
||||
rule_id=rule.id,
|
||||
priority=rule.priority,
|
||||
)
|
||||
)
|
||||
|
||||
if self.enable_entropy and profile in {"swe", "strict"}:
|
||||
candidates.extend(self._scan_entropy(text, protected_ranges))
|
||||
|
||||
if self.enable_ner and profile in {"pii", "strict"}:
|
||||
candidates.extend(self._scan_ner(text, protected_ranges))
|
||||
|
||||
return _resolve_overlaps(candidates)
|
||||
|
||||
def _scan_entropy(
|
||||
self, text: str, protected_ranges: list[tuple[int, int]]
|
||||
) -> list[DetectionMatch]:
|
||||
matches: list[DetectionMatch] = []
|
||||
for m in QUOTED_CANDIDATE_RE.finditer(text):
|
||||
start, end = m.span(2)
|
||||
if _overlaps_any(start, end, protected_ranges):
|
||||
continue
|
||||
val = m.group(2)
|
||||
if self.is_allowlisted(val):
|
||||
continue
|
||||
if UUID_RE.match(val) or HEX_HASH_RE.match(val):
|
||||
continue
|
||||
if "/" in val and "://" not in val:
|
||||
continue
|
||||
classes = sum(
|
||||
[
|
||||
any(c.islower() for c in val),
|
||||
any(c.isupper() for c in val),
|
||||
any(c.isdigit() for c in val),
|
||||
any(c in "+/_=-" for c in val),
|
||||
]
|
||||
)
|
||||
if classes < 3:
|
||||
continue
|
||||
if shannon_entropy(val) >= self.entropy_threshold:
|
||||
matches.append(
|
||||
DetectionMatch(
|
||||
start=start,
|
||||
end=end,
|
||||
value=val,
|
||||
category="SECRET_HIGH_ENTROPY",
|
||||
rule_id="high-entropy-quoted",
|
||||
priority=65,
|
||||
)
|
||||
)
|
||||
return matches
|
||||
|
||||
def _scan_ner(
|
||||
self, text: str, protected_ranges: list[tuple[int, int]]
|
||||
) -> list[DetectionMatch]:
|
||||
engine = self._get_ner_engine()
|
||||
if engine is None:
|
||||
return []
|
||||
results = engine.analyze(
|
||||
text=text,
|
||||
entities=["PERSON", "LOCATION", "NRP"],
|
||||
language="en",
|
||||
score_threshold=0.65,
|
||||
)
|
||||
matches: list[DetectionMatch] = []
|
||||
for res in results:
|
||||
if _overlaps_any(res.start, res.end, protected_ranges):
|
||||
continue
|
||||
val = text[res.start : res.end]
|
||||
if len(val.strip()) < 3 or self.is_allowlisted(val):
|
||||
continue
|
||||
matches.append(
|
||||
DetectionMatch(
|
||||
start=res.start,
|
||||
end=res.end,
|
||||
value=val,
|
||||
category=f"PII_{res.entity_type}",
|
||||
rule_id=f"presidio-{res.entity_type.lower()}",
|
||||
priority=60,
|
||||
)
|
||||
)
|
||||
return matches
|
||||
|
||||
|
||||
def _overlaps_any(start: int, end: int, ranges: list[tuple[int, int]]) -> bool:
|
||||
for r_start, r_end in ranges:
|
||||
if start < r_end and end > r_start:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _resolve_overlaps(candidates: list[DetectionMatch]) -> list[DetectionMatch]:
|
||||
"""Select highest-priority, longest non-overlapping spans, ordered left-to-right."""
|
||||
ordered = sorted(
|
||||
candidates,
|
||||
key=lambda m: (-m.priority, -(m.end - m.start), m.start),
|
||||
)
|
||||
accepted: list[DetectionMatch] = []
|
||||
occupied: list[tuple[int, int]] = []
|
||||
for cand in ordered:
|
||||
if _overlaps_any(cand.start, cand.end, occupied):
|
||||
continue
|
||||
accepted.append(cand)
|
||||
occupied.append((cand.start, cand.end))
|
||||
accepted.sort(key=lambda m: m.start)
|
||||
return accepted
|
||||
@@ -0,0 +1,420 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from typing import Any, BinaryIO, Optional
|
||||
|
||||
from redactor_mcp import __version__
|
||||
from redactor_mcp.client import VaultClient
|
||||
|
||||
try:
|
||||
from mcp.server.fastmcp import FastMCP # type: ignore
|
||||
except ImportError: # pragma: no cover - fallback when official mcp SDK isn't installed
|
||||
FastMCP = None # type: ignore
|
||||
|
||||
|
||||
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."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {"type": "string", "description": "File path to read and redact."},
|
||||
"session_id": {"type": "string", "default": "default"},
|
||||
"profile": {
|
||||
"type": "string",
|
||||
"enum": ["strict", "pii", "swe"],
|
||||
"default": "strict",
|
||||
},
|
||||
"format_preserving": {
|
||||
"type": "boolean",
|
||||
"default": False,
|
||||
"description": "Use reserved synthetic tokens (900-xx-xxxx, @invalid.local) instead of <<REDACT:...>>.",
|
||||
},
|
||||
},
|
||||
"required": ["path"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "vault_redact_text",
|
||||
"description": (
|
||||
"Redact sensitive PII and secrets from raw text and store mappings in the session vault."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"text": {"type": "string", "description": "Text to scan and redact."},
|
||||
"session_id": {"type": "string", "default": "default"},
|
||||
"profile": {
|
||||
"type": "string",
|
||||
"enum": ["strict", "pii", "swe"],
|
||||
"default": "strict",
|
||||
},
|
||||
"format_preserving": {"type": "boolean", "default": False},
|
||||
"content_type": {
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"description": "Optional format hint (json, jsonl, csv, tsv, sql) for key-aware redaction.",
|
||||
},
|
||||
},
|
||||
"required": ["text"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "vault_stage_workspace",
|
||||
"description": (
|
||||
"Incrementally mirror a source repository or sensitive folder into a sanitized "
|
||||
"staging directory with PII and secrets replaced by placeholders."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"src_dir": {"type": "string", "description": "Source directory path."},
|
||||
"clean_dir": {
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"description": "Destination staging path (optional if REDACTOR_STAGING_ROOT is set).",
|
||||
},
|
||||
"session_id": {"type": "string", "default": "default"},
|
||||
"profile": {
|
||||
"type": "string",
|
||||
"enum": ["strict", "pii", "swe"],
|
||||
"default": "swe",
|
||||
},
|
||||
"format_preserving": {"type": "boolean", "default": False},
|
||||
},
|
||||
"required": ["src_dir"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "vault_run_scrubbed",
|
||||
"description": (
|
||||
"Execute a test/linter/build command strictly inside clean-staging and redact any "
|
||||
"PII or secrets from stdout/stderr before returning output to the agent."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"command": {"type": "string", "description": "Shell command to run in staging."},
|
||||
"cwd": {"type": "string", "default": ""},
|
||||
"session_id": {"type": "string", "default": "default"},
|
||||
"profile": {
|
||||
"type": "string",
|
||||
"enum": ["strict", "pii", "swe"],
|
||||
"default": "strict",
|
||||
},
|
||||
"format_preserving": {"type": "boolean", "default": False},
|
||||
"timeout": {"type": "integer", "default": 30},
|
||||
},
|
||||
"required": ["command"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "vault_write_file",
|
||||
"description": (
|
||||
"One-way egress: restore session placeholders inside `content` back to original values "
|
||||
"and write directly to an approved output path. Never returns unredacted text."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"content": {"type": "string", "description": "Sanitized content containing placeholders."},
|
||||
"dest_path": {"type": "string", "description": "Approved output file path."},
|
||||
"session_id": {"type": "string", "default": "default"},
|
||||
},
|
||||
"required": ["content", "dest_path"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "vault_rehydrate_file",
|
||||
"description": (
|
||||
"One-way egress: read a sanitized file, restore its session placeholders, and write "
|
||||
"the rehydrated file directly to an approved output path. Never returns unredacted text."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"clean_path": {"type": "string", "description": "Path to sanitized file."},
|
||||
"dest_path": {"type": "string", "description": "Approved output file path."},
|
||||
"session_id": {"type": "string", "default": "default"},
|
||||
},
|
||||
"required": ["clean_path", "dest_path"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "vault_session_status",
|
||||
"description": (
|
||||
"Inspect non-secret metadata (token counts, categories, SHA-256 prefixes) for a vault session."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"session_id": {"type": "string", "default": "default"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "vault_purge_session",
|
||||
"description": "Wipe a session's in-memory placeholder mappings from the vault.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"session_id": {"type": "string", "default": "default"},
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def _dispatch_mcp_tool(client: VaultClient, name: str, args: dict[str, Any]) -> dict[str, Any]:
|
||||
mapping = {
|
||||
"vault_read_file": "read_file",
|
||||
"vault_redact_text": "redact_text",
|
||||
"vault_stage_workspace": "stage_workspace",
|
||||
"vault_run_scrubbed": "run_scrubbed",
|
||||
"vault_write_file": "write_file",
|
||||
"vault_rehydrate_file": "rehydrate_file",
|
||||
"vault_session_status": "status",
|
||||
"vault_purge_session": "purge",
|
||||
}
|
||||
daemon_method = mapping.get(name)
|
||||
if daemon_method is None:
|
||||
raise ValueError(f"Unknown tool: {name}")
|
||||
return client.call(daemon_method, args)
|
||||
|
||||
|
||||
class StdioMCPServer:
|
||||
"""Zero-dependency JSON-RPC 2.0 MCP stdio server."""
|
||||
|
||||
def __init__(self, client: Optional[VaultClient] = None) -> None:
|
||||
self.client = client or VaultClient()
|
||||
|
||||
def handle_message(self, msg: dict[str, Any]) -> Optional[dict[str, Any]]:
|
||||
msg_id = msg.get("id")
|
||||
method = msg.get("method", "")
|
||||
params = msg.get("params") or {}
|
||||
|
||||
if msg_id is None:
|
||||
return None
|
||||
|
||||
if method == "initialize":
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": msg_id,
|
||||
"result": {
|
||||
"protocolVersion": params.get("protocolVersion", "2024-11-05"),
|
||||
"capabilities": {"tools": {}},
|
||||
"serverInfo": {"name": "redactor-vault", "version": __version__},
|
||||
},
|
||||
}
|
||||
|
||||
if method == "ping":
|
||||
return {"jsonrpc": "2.0", "id": msg_id, "result": {}}
|
||||
|
||||
if method == "tools/list":
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": msg_id,
|
||||
"result": {"tools": TOOL_DEFINITIONS},
|
||||
}
|
||||
|
||||
if method == "tools/call":
|
||||
tool_name = params.get("name", "")
|
||||
arguments = params.get("arguments") or {}
|
||||
try:
|
||||
result = _dispatch_mcp_tool(self.client, tool_name, arguments)
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": msg_id,
|
||||
"result": {
|
||||
"content": [{"type": "text", "text": json.dumps(result, indent=2)}],
|
||||
"isError": False,
|
||||
},
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": msg_id,
|
||||
"result": {
|
||||
"content": [{"type": "text", "text": f"Error: {exc}"}],
|
||||
"isError": True,
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": msg_id,
|
||||
"error": {"code": -32601, "message": f"Method not found: {method}"},
|
||||
}
|
||||
|
||||
def run_stdio(
|
||||
self,
|
||||
stdin: Optional[BinaryIO] = None,
|
||||
stdout: Optional[BinaryIO] = None,
|
||||
) -> None:
|
||||
in_stream = stdin or sys.stdin.buffer
|
||||
out_stream = stdout or sys.stdout.buffer
|
||||
while True:
|
||||
line = in_stream.readline()
|
||||
if not line:
|
||||
break
|
||||
stripped = line.strip()
|
||||
if not stripped:
|
||||
continue
|
||||
try:
|
||||
msg = json.loads(stripped.decode("utf-8"))
|
||||
reply = self.handle_message(msg)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
reply = {
|
||||
"jsonrpc": "2.0",
|
||||
"id": None,
|
||||
"error": {"code": -32700, "message": f"Parse error: {exc}"},
|
||||
}
|
||||
if reply is not None:
|
||||
out_stream.write((json.dumps(reply) + "\n").encode("utf-8"))
|
||||
out_stream.flush()
|
||||
|
||||
|
||||
def build_fastmcp_server(client: Optional[VaultClient] = None) -> Any:
|
||||
"""Build official FastMCP server instance when `mcp` package is installed."""
|
||||
if FastMCP is None:
|
||||
return None
|
||||
vault_client = client or VaultClient()
|
||||
mcp = FastMCP("redactor-vault")
|
||||
|
||||
@mcp.tool()
|
||||
def vault_read_file(
|
||||
path: str,
|
||||
session_id: str = "default",
|
||||
profile: str = "strict",
|
||||
format_preserving: bool = False,
|
||||
) -> str:
|
||||
"""Read and redact a sensitive file, returning placeholder text."""
|
||||
return json.dumps(
|
||||
vault_client.call(
|
||||
"read_file",
|
||||
{
|
||||
"path": path,
|
||||
"session_id": session_id,
|
||||
"profile": profile,
|
||||
"format_preserving": format_preserving,
|
||||
},
|
||||
),
|
||||
indent=2,
|
||||
)
|
||||
|
||||
@mcp.tool()
|
||||
def vault_redact_text(
|
||||
text: str,
|
||||
session_id: str = "default",
|
||||
profile: str = "strict",
|
||||
format_preserving: bool = False,
|
||||
content_type: str = "",
|
||||
) -> str:
|
||||
"""Redact sensitive PII and secrets from text and store mappings in the vault."""
|
||||
return json.dumps(
|
||||
vault_client.call(
|
||||
"redact_text",
|
||||
{
|
||||
"text": text,
|
||||
"session_id": session_id,
|
||||
"profile": profile,
|
||||
"format_preserving": format_preserving,
|
||||
"content_type": content_type,
|
||||
},
|
||||
),
|
||||
indent=2,
|
||||
)
|
||||
|
||||
@mcp.tool()
|
||||
def vault_stage_workspace(
|
||||
src_dir: str,
|
||||
clean_dir: str = "",
|
||||
session_id: str = "default",
|
||||
profile: str = "swe",
|
||||
format_preserving: bool = False,
|
||||
) -> str:
|
||||
"""Mirror a repository/directory into a sanitized staging directory."""
|
||||
return json.dumps(
|
||||
vault_client.call(
|
||||
"stage_workspace",
|
||||
{
|
||||
"src_dir": src_dir,
|
||||
"clean_dir": clean_dir,
|
||||
"session_id": session_id,
|
||||
"profile": profile,
|
||||
"format_preserving": format_preserving,
|
||||
},
|
||||
),
|
||||
indent=2,
|
||||
)
|
||||
|
||||
@mcp.tool()
|
||||
def vault_run_scrubbed(
|
||||
command: str,
|
||||
cwd: str = "",
|
||||
session_id: str = "default",
|
||||
profile: str = "strict",
|
||||
format_preserving: bool = False,
|
||||
timeout: int = 30,
|
||||
) -> str:
|
||||
"""Run a command inside clean-staging and redact stdout/stderr before returning."""
|
||||
return json.dumps(
|
||||
vault_client.call(
|
||||
"run_scrubbed",
|
||||
{
|
||||
"command": command,
|
||||
"cwd": cwd,
|
||||
"session_id": session_id,
|
||||
"profile": profile,
|
||||
"format_preserving": format_preserving,
|
||||
"timeout": timeout,
|
||||
},
|
||||
),
|
||||
indent=2,
|
||||
)
|
||||
|
||||
@mcp.tool()
|
||||
def vault_write_file(content: str, dest_path: str, session_id: str = "default") -> str:
|
||||
"""One-way egress: rehydrate placeholders in content and write to output path."""
|
||||
return json.dumps(
|
||||
vault_client.call(
|
||||
"write_file", {"content": content, "dest_path": dest_path, "session_id": session_id}
|
||||
),
|
||||
indent=2,
|
||||
)
|
||||
|
||||
@mcp.tool()
|
||||
def vault_rehydrate_file(clean_path: str, dest_path: str, session_id: str = "default") -> str:
|
||||
"""One-way egress: rehydrate a sanitized file directly to output path."""
|
||||
return json.dumps(
|
||||
vault_client.call(
|
||||
"rehydrate_file",
|
||||
{"clean_path": clean_path, "dest_path": dest_path, "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."""
|
||||
return json.dumps(vault_client.call("status", {"session_id": session_id}), indent=2)
|
||||
|
||||
@mcp.tool()
|
||||
def vault_purge_session(session_id: str = "default") -> str:
|
||||
"""Purge a session's in-memory mappings."""
|
||||
return json.dumps(vault_client.call("purge", {"session_id": session_id}), indent=2)
|
||||
|
||||
return mcp
|
||||
|
||||
|
||||
def run_mcp_stdio(force_stdlib: bool = False) -> None:
|
||||
if not force_stdlib and FastMCP is not None:
|
||||
server = build_fastmcp_server()
|
||||
server.run(transport="stdio")
|
||||
else:
|
||||
StdioMCPServer().run_stdio()
|
||||
@@ -0,0 +1,394 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
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.scanner import RedactionScanner, is_binary_bytes
|
||||
from redactor_mcp.structured import redact_by_extension
|
||||
from redactor_mcp.vault import SessionVault
|
||||
from redactor_mcp.workspace import WorkspacePolicy, WorkspaceStager
|
||||
|
||||
|
||||
class RedactorService:
|
||||
"""Core application service coordinating scanning, vaulting, audit, and policy."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
scanner: Optional[RedactionScanner] = None,
|
||||
vault: Optional[SessionVault] = None,
|
||||
policy: Optional[WorkspacePolicy] = None,
|
||||
stager: Optional[WorkspaceStager] = None,
|
||||
audit: Optional[AuditLogger] = None,
|
||||
) -> None:
|
||||
enable_ner = os.environ.get("REDACTOR_ENABLE_NER", "").lower() in {"1", "true", "yes"}
|
||||
ttl = int(os.environ.get("REDACTOR_SESSION_TTL", "14400"))
|
||||
self.scanner = scanner or RedactionScanner(enable_ner=enable_ner)
|
||||
self.vault = vault or SessionVault(ttl_seconds=ttl)
|
||||
self.policy = policy or WorkspacePolicy.from_env()
|
||||
self.stager = stager or WorkspaceStager()
|
||||
self.audit = audit or AuditLogger()
|
||||
|
||||
def redact_text(
|
||||
self,
|
||||
text: str,
|
||||
session_id: str = "default",
|
||||
profile: str = "strict",
|
||||
format_preserving: bool = False,
|
||||
content_type: str = "",
|
||||
) -> dict[str, Any]:
|
||||
if content_type.strip():
|
||||
res = redact_by_extension(
|
||||
text=text,
|
||||
extension=content_type,
|
||||
scanner=self.scanner,
|
||||
vault=self.vault,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
else:
|
||||
res = self.vault.redact(
|
||||
text=text,
|
||||
scanner=self.scanner,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
self.audit.record(
|
||||
event="redact_text",
|
||||
session_id=session_id,
|
||||
target=content_type or "inline",
|
||||
categories=res.categories,
|
||||
token_count=res.replacements,
|
||||
)
|
||||
return {
|
||||
"redacted_text": res.redacted_text,
|
||||
"session_id": res.session_id,
|
||||
"replacements": res.replacements,
|
||||
"categories": res.categories,
|
||||
"placeholders": res.placeholders,
|
||||
}
|
||||
|
||||
def read_file(
|
||||
self,
|
||||
path: str,
|
||||
session_id: str = "default",
|
||||
profile: str = "strict",
|
||||
format_preserving: bool = False,
|
||||
max_bytes: int = 1024 * 1024,
|
||||
) -> dict[str, Any]:
|
||||
target = self.policy.resolve_read_path(path)
|
||||
if not target.is_file():
|
||||
raise FileNotFoundError(f"File not found: {target}")
|
||||
raw = target.read_bytes()
|
||||
if len(raw) > max_bytes:
|
||||
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,
|
||||
)
|
||||
self.audit.record(
|
||||
event="read_file",
|
||||
session_id=session_id,
|
||||
target=str(target),
|
||||
categories=res.categories,
|
||||
token_count=res.replacements,
|
||||
)
|
||||
return {
|
||||
"path": str(target),
|
||||
"redacted_text": res.redacted_text,
|
||||
"session_id": res.session_id,
|
||||
"replacements": res.replacements,
|
||||
"categories": res.categories,
|
||||
"placeholders": res.placeholders,
|
||||
}
|
||||
|
||||
def stage_workspace(
|
||||
self,
|
||||
src_dir: str,
|
||||
clean_dir: str = "",
|
||||
session_id: str = "default",
|
||||
profile: str = "swe",
|
||||
format_preserving: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
resolved_src = self.policy.resolve_read_path(src_dir)
|
||||
resolved_clean = self.policy.resolve_staging_dir(clean_dir)
|
||||
summary = self.stager.stage_directory(
|
||||
src_dir=resolved_src,
|
||||
clean_dir=resolved_clean,
|
||||
scanner=self.scanner,
|
||||
vault=self.vault,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
self.audit.record(
|
||||
event="stage_workspace",
|
||||
session_id=session_id,
|
||||
target=str(resolved_src),
|
||||
categories=summary["categories"],
|
||||
token_count=summary["total_replacements"],
|
||||
extra={"files_scanned": summary["files_scanned"]},
|
||||
)
|
||||
return summary
|
||||
|
||||
def run_scrubbed(
|
||||
self,
|
||||
command: str,
|
||||
cwd: str = "",
|
||||
session_id: str = "default",
|
||||
profile: str = "strict",
|
||||
format_preserving: bool = False,
|
||||
timeout: int = 30,
|
||||
) -> dict[str, Any]:
|
||||
"""Run a command inside clean-staging and redact stdout/stderr before returning."""
|
||||
if os.environ.get("REDACTOR_ALLOW_EXEC", "true").lower() in {"0", "false", "no"}:
|
||||
raise PermissionError("Scrubbed command execution is disabled by REDACTOR_ALLOW_EXEC")
|
||||
if not command.strip():
|
||||
raise ValueError("command must not be empty")
|
||||
|
||||
exec_cwd = self.policy.resolve_exec_cwd(cwd)
|
||||
clean_env = {
|
||||
k: v
|
||||
for k, v in os.environ.items()
|
||||
if not k.startswith("REDACTOR_") and "SECRET" not in k.upper() and "TOKEN" not in k.upper()
|
||||
}
|
||||
proc = subprocess.run(
|
||||
command,
|
||||
shell=True,
|
||||
cwd=str(exec_cwd),
|
||||
env=clean_env,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=max(1, min(timeout, 120)),
|
||||
)
|
||||
out_res = self.vault.redact(
|
||||
proc.stdout or "",
|
||||
scanner=self.scanner,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
err_res = self.vault.redact(
|
||||
proc.stderr or "",
|
||||
scanner=self.scanner,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
total = out_res.replacements + err_res.replacements
|
||||
merged_cats = dict(out_res.categories)
|
||||
for k, v in err_res.categories.items():
|
||||
merged_cats[k] = merged_cats.get(k, 0) + v
|
||||
|
||||
self.audit.record(
|
||||
event="run_scrubbed",
|
||||
session_id=session_id,
|
||||
target=str(exec_cwd),
|
||||
categories=merged_cats,
|
||||
token_count=total,
|
||||
extra={"exit_code": proc.returncode},
|
||||
)
|
||||
return {
|
||||
"exit_code": proc.returncode,
|
||||
"cwd": str(exec_cwd),
|
||||
"stdout": out_res.redacted_text,
|
||||
"stderr": err_res.redacted_text,
|
||||
"replacements": total,
|
||||
"categories": merged_cats,
|
||||
"session_id": session_id,
|
||||
}
|
||||
|
||||
def write_file(
|
||||
self,
|
||||
content: str,
|
||||
dest_path: str,
|
||||
session_id: str = "default",
|
||||
) -> dict[str, Any]:
|
||||
"""One-way egress: rehydrate content and write directly to approved output path."""
|
||||
target = self.policy.resolve_output_path(dest_path)
|
||||
summary = self.vault.rehydrate_to_file(
|
||||
clean_text=content,
|
||||
dest_path=target,
|
||||
session_id=session_id,
|
||||
)
|
||||
self.audit.record(
|
||||
event="write_file",
|
||||
session_id=session_id,
|
||||
target=summary.destination,
|
||||
token_count=summary.tokens_restored,
|
||||
extra={"bytes_written": summary.bytes_written},
|
||||
)
|
||||
return {
|
||||
"destination": summary.destination,
|
||||
"bytes_written": summary.bytes_written,
|
||||
"tokens_restored": summary.tokens_restored,
|
||||
"unresolved_tokens": summary.unresolved_tokens,
|
||||
"session_id": summary.session_id,
|
||||
}
|
||||
|
||||
def rehydrate_file(
|
||||
self,
|
||||
clean_path: str,
|
||||
dest_path: str,
|
||||
session_id: str = "default",
|
||||
) -> dict[str, Any]:
|
||||
"""One-way egress: read sanitized file, restore tokens, write to output path."""
|
||||
src = self.policy.resolve_clean_read_path(clean_path)
|
||||
if not src.is_file():
|
||||
raise FileNotFoundError(f"Clean file not found: {src}")
|
||||
clean_text = src.read_text(encoding="utf-8", errors="replace")
|
||||
return self.write_file(
|
||||
content=clean_text,
|
||||
dest_path=dest_path,
|
||||
session_id=session_id,
|
||||
)
|
||||
|
||||
def rehydrate_text_cli(
|
||||
self,
|
||||
text: str,
|
||||
session_id: str = "default",
|
||||
) -> dict[str, Any]:
|
||||
"""Host-only CLI helper endpoint (never exposed as an MCP tool)."""
|
||||
restored, count, unresolved = self.vault.rehydrate_text(
|
||||
text=text,
|
||||
session_id=session_id,
|
||||
)
|
||||
self.audit.record(
|
||||
event="rehydrate_text_cli",
|
||||
session_id=session_id,
|
||||
target="cli",
|
||||
token_count=count,
|
||||
)
|
||||
return {
|
||||
"restored_text": restored,
|
||||
"tokens_restored": count,
|
||||
"unresolved_tokens": unresolved,
|
||||
"session_id": session_id,
|
||||
}
|
||||
|
||||
def save_snapshot(
|
||||
self,
|
||||
dest_path: str,
|
||||
passphrase: str,
|
||||
session_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Host/CLI-only encrypted pause snapshot."""
|
||||
payload = self.vault.export_snapshot(session_id=session_id)
|
||||
target = Path(dest_path).resolve()
|
||||
bytes_written = save_encrypted_snapshot_file(payload, target, passphrase)
|
||||
self.audit.record(
|
||||
event="save_snapshot",
|
||||
session_id=session_id,
|
||||
target=str(target),
|
||||
token_count=len(payload.get("sessions", {})),
|
||||
)
|
||||
return {
|
||||
"snapshot_path": str(target),
|
||||
"bytes_written": bytes_written,
|
||||
"sessions_saved": list(payload.get("sessions", {}).keys()),
|
||||
}
|
||||
|
||||
def load_snapshot(
|
||||
self,
|
||||
src_path: str,
|
||||
passphrase: str,
|
||||
merge: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Host/CLI-only encrypted resume snapshot."""
|
||||
target = Path(src_path).resolve()
|
||||
payload = load_encrypted_snapshot_file(target, passphrase)
|
||||
loaded = self.vault.import_snapshot(payload, merge=merge)
|
||||
self.audit.record(
|
||||
event="load_snapshot",
|
||||
target=str(target),
|
||||
token_count=loaded,
|
||||
)
|
||||
return {
|
||||
"snapshot_path": str(target),
|
||||
"sessions_loaded": loaded,
|
||||
}
|
||||
|
||||
def status(self, session_id: Optional[str] = None) -> dict[str, Any]:
|
||||
return self.vault.status(session_id=session_id)
|
||||
|
||||
def purge(self, session_id: Optional[str] = None) -> dict[str, Any]:
|
||||
res = self.vault.purge(session_id=session_id)
|
||||
self.audit.record(event="purge", session_id=session_id)
|
||||
return res
|
||||
|
||||
def dispatch(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
handlers = {
|
||||
"redact_text": lambda p: self.redact_text(
|
||||
text=p["text"],
|
||||
session_id=p.get("session_id", "default"),
|
||||
profile=p.get("profile", "strict"),
|
||||
format_preserving=bool(p.get("format_preserving", False)),
|
||||
content_type=p.get("content_type", ""),
|
||||
),
|
||||
"read_file": lambda p: self.read_file(
|
||||
path=p["path"],
|
||||
session_id=p.get("session_id", "default"),
|
||||
profile=p.get("profile", "strict"),
|
||||
format_preserving=bool(p.get("format_preserving", False)),
|
||||
),
|
||||
"stage_workspace": lambda p: self.stage_workspace(
|
||||
src_dir=p["src_dir"],
|
||||
clean_dir=p.get("clean_dir", ""),
|
||||
session_id=p.get("session_id", "default"),
|
||||
profile=p.get("profile", "swe"),
|
||||
format_preserving=bool(p.get("format_preserving", False)),
|
||||
),
|
||||
"run_scrubbed": lambda p: self.run_scrubbed(
|
||||
command=p["command"],
|
||||
cwd=p.get("cwd", ""),
|
||||
session_id=p.get("session_id", "default"),
|
||||
profile=p.get("profile", "strict"),
|
||||
format_preserving=bool(p.get("format_preserving", False)),
|
||||
timeout=int(p.get("timeout", 30)),
|
||||
),
|
||||
"write_file": lambda p: self.write_file(
|
||||
content=p["content"],
|
||||
dest_path=p["dest_path"],
|
||||
session_id=p.get("session_id", "default"),
|
||||
),
|
||||
"rehydrate_file": lambda p: self.rehydrate_file(
|
||||
clean_path=p["clean_path"],
|
||||
dest_path=p["dest_path"],
|
||||
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"),
|
||||
),
|
||||
"save_snapshot": lambda p: self.save_snapshot(
|
||||
dest_path=p["dest_path"],
|
||||
passphrase=p["passphrase"],
|
||||
session_id=p.get("session_id"),
|
||||
),
|
||||
"load_snapshot": lambda p: self.load_snapshot(
|
||||
src_path=p["src_path"],
|
||||
passphrase=p["passphrase"],
|
||||
merge=bool(p.get("merge", True)),
|
||||
),
|
||||
"status": lambda p: self.status(session_id=p.get("session_id")),
|
||||
"purge": lambda p: self.purge(session_id=p.get("session_id")),
|
||||
}
|
||||
fn = handlers.get(method)
|
||||
if fn is None:
|
||||
raise ValueError(f"Unknown method: {method}")
|
||||
return fn(params)
|
||||
@@ -0,0 +1,368 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
from collections import Counter
|
||||
from typing import Any
|
||||
|
||||
from redactor_mcp.models import RedactionResult
|
||||
from redactor_mcp.scanner import RedactionScanner, normalize_key_name
|
||||
from redactor_mcp.vault import SessionVault
|
||||
|
||||
# Matches SQL INSERT INTO tbl (c1, c2, ...) VALUES (...), (...);
|
||||
_SQL_INSERT_RE = re.compile(
|
||||
r"(?is)(INSERT\s+INTO\s+[`\"\[]?[\w.]+[`\"\]]?\s*\(([^)]+)\)\s*VALUES\s*)(.+?)(;)"
|
||||
)
|
||||
|
||||
|
||||
def _should_redact_key_for_profile(category: str, profile: str) -> bool:
|
||||
if profile == "strict":
|
||||
return True
|
||||
if profile == "pii":
|
||||
return category.startswith("PII_")
|
||||
if profile == "swe":
|
||||
return category.startswith("SECRET_")
|
||||
return True
|
||||
|
||||
|
||||
def redact_json_text(
|
||||
text: str,
|
||||
scanner: RedactionScanner,
|
||||
vault: SessionVault,
|
||||
session_id: str = "default",
|
||||
profile: str = "strict",
|
||||
format_preserving: bool = False,
|
||||
jsonl: bool = False,
|
||||
) -> RedactionResult:
|
||||
"""Schema/key-aware JSON & JSONL redaction plus regex fallback on remaining strings."""
|
||||
categories: Counter[str] = Counter()
|
||||
placeholders: set[str] = set()
|
||||
replacements = 0
|
||||
|
||||
def _walk(node: Any, parent_key: str = "") -> Any:
|
||||
nonlocal replacements
|
||||
if isinstance(node, dict):
|
||||
return {k: _walk(v, str(k)) for k, v in node.items()}
|
||||
if isinstance(node, list):
|
||||
return [_walk(item, parent_key) for item in node]
|
||||
if isinstance(node, (str, int, float)) and not isinstance(node, bool):
|
||||
norm = normalize_key_name(parent_key)
|
||||
cat = scanner.sensitive_keys.get(norm)
|
||||
val_str = str(node)
|
||||
if cat and _should_redact_key_for_profile(cat, profile) and not scanner.is_allowlisted(val_str):
|
||||
tok = vault.redact_value(
|
||||
raw_value=val_str,
|
||||
category=cat,
|
||||
rule_id=f"key:{norm}",
|
||||
session_id=session_id,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
replacements += 1
|
||||
categories[cat] += 1
|
||||
placeholders.add(tok)
|
||||
return tok
|
||||
if isinstance(node, str):
|
||||
res = vault.redact(
|
||||
node,
|
||||
scanner=scanner,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
replacements += res.replacements
|
||||
categories.update(res.categories)
|
||||
placeholders.update(res.placeholders)
|
||||
return res.redacted_text
|
||||
return node
|
||||
|
||||
if jsonl:
|
||||
out_lines: list[str] = []
|
||||
for line in text.splitlines():
|
||||
stripped = line.strip()
|
||||
if not stripped:
|
||||
out_lines.append(line)
|
||||
continue
|
||||
try:
|
||||
parsed = json.loads(stripped)
|
||||
out_lines.append(json.dumps(_walk(parsed)))
|
||||
except json.JSONDecodeError:
|
||||
res = vault.redact(
|
||||
line,
|
||||
scanner=scanner,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
replacements += res.replacements
|
||||
categories.update(res.categories)
|
||||
placeholders.update(res.placeholders)
|
||||
out_lines.append(res.redacted_text)
|
||||
rendered = "\n".join(out_lines) + ("\n" if text.endswith("\n") else "")
|
||||
else:
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
rendered = json.dumps(_walk(parsed), indent=2) + ("\n" if text.endswith("\n") else "")
|
||||
except json.JSONDecodeError:
|
||||
return vault.redact(
|
||||
text,
|
||||
scanner=scanner,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
|
||||
return RedactionResult(
|
||||
redacted_text=rendered,
|
||||
session_id=session_id,
|
||||
replacements=replacements,
|
||||
categories=dict(categories),
|
||||
placeholders=sorted(placeholders),
|
||||
)
|
||||
|
||||
|
||||
def redact_csv_text(
|
||||
text: str,
|
||||
scanner: RedactionScanner,
|
||||
vault: SessionVault,
|
||||
session_id: str = "default",
|
||||
profile: str = "strict",
|
||||
format_preserving: bool = False,
|
||||
delimiter: str = ",",
|
||||
) -> RedactionResult:
|
||||
"""Header-aware CSV/TSV redaction with fallback scanning on other cells."""
|
||||
reader = csv.reader(io.StringIO(text), delimiter=delimiter)
|
||||
rows = list(reader)
|
||||
if not rows:
|
||||
return RedactionResult(text, session_id, 0)
|
||||
|
||||
header = rows[0]
|
||||
col_categories: dict[int, tuple[str, str]] = {}
|
||||
for idx, col_name in enumerate(header):
|
||||
norm = normalize_key_name(col_name)
|
||||
cat = scanner.sensitive_keys.get(norm)
|
||||
if cat and _should_redact_key_for_profile(cat, profile):
|
||||
col_categories[idx] = (cat, norm)
|
||||
|
||||
out_buf = io.StringIO()
|
||||
writer = csv.writer(out_buf, delimiter=delimiter, lineterminator="\n")
|
||||
writer.writerow(header)
|
||||
|
||||
categories: Counter[str] = Counter()
|
||||
placeholders: set[str] = set()
|
||||
replacements = 0
|
||||
|
||||
for row in rows[1:]:
|
||||
new_row: list[str] = []
|
||||
for idx, cell in enumerate(row):
|
||||
if idx in col_categories and cell.strip() and not scanner.is_allowlisted(cell):
|
||||
cat, norm = col_categories[idx]
|
||||
tok = vault.redact_value(
|
||||
raw_value=cell,
|
||||
category=cat,
|
||||
rule_id=f"col:{norm}",
|
||||
session_id=session_id,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
replacements += 1
|
||||
categories[cat] += 1
|
||||
placeholders.add(tok)
|
||||
new_row.append(tok)
|
||||
else:
|
||||
res = vault.redact(
|
||||
cell,
|
||||
scanner=scanner,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
replacements += res.replacements
|
||||
categories.update(res.categories)
|
||||
placeholders.update(res.placeholders)
|
||||
new_row.append(res.redacted_text)
|
||||
writer.writerow(new_row)
|
||||
|
||||
return RedactionResult(
|
||||
redacted_text=out_buf.getvalue(),
|
||||
session_id=session_id,
|
||||
replacements=replacements,
|
||||
categories=dict(categories),
|
||||
placeholders=sorted(placeholders),
|
||||
)
|
||||
|
||||
|
||||
def _split_sql_tuples(values_blob: str) -> list[str]:
|
||||
tuples: list[str] = []
|
||||
depth = 0
|
||||
in_quote = False
|
||||
start = -1
|
||||
i = 0
|
||||
while i < len(values_blob):
|
||||
ch = values_blob[i]
|
||||
if ch == "'" and not in_quote:
|
||||
in_quote = True
|
||||
elif ch == "'" and in_quote:
|
||||
if i + 1 < len(values_blob) and values_blob[i + 1] == "'":
|
||||
i += 1 # escaped ''
|
||||
else:
|
||||
in_quote = False
|
||||
elif not in_quote:
|
||||
if ch == "(":
|
||||
if depth == 0:
|
||||
start = i + 1
|
||||
depth += 1
|
||||
elif ch == ")":
|
||||
depth -= 1
|
||||
if depth == 0 and start >= 0:
|
||||
tuples.append(values_blob[start:i])
|
||||
start = -1
|
||||
i += 1
|
||||
return tuples
|
||||
|
||||
|
||||
def _split_sql_fields(tuple_body: str) -> list[str]:
|
||||
fields: list[str] = []
|
||||
in_quote = False
|
||||
cur: list[str] = []
|
||||
i = 0
|
||||
while i < len(tuple_body):
|
||||
ch = tuple_body[i]
|
||||
if ch == "'" and not in_quote:
|
||||
in_quote = True
|
||||
cur.append(ch)
|
||||
elif ch == "'" and in_quote:
|
||||
cur.append(ch)
|
||||
if i + 1 < len(tuple_body) and tuple_body[i + 1] == "'":
|
||||
cur.append("'")
|
||||
i += 1
|
||||
else:
|
||||
in_quote = False
|
||||
elif ch == "," and not in_quote:
|
||||
fields.append("".join(cur).strip())
|
||||
cur = []
|
||||
else:
|
||||
cur.append(ch)
|
||||
i += 1
|
||||
fields.append("".join(cur).strip())
|
||||
return fields
|
||||
|
||||
|
||||
def redact_sql_text(
|
||||
text: str,
|
||||
scanner: RedactionScanner,
|
||||
vault: SessionVault,
|
||||
session_id: str = "default",
|
||||
profile: str = "strict",
|
||||
format_preserving: bool = False,
|
||||
) -> RedactionResult:
|
||||
"""Column-aware SQL INSERT redaction + regex fallback on the rest of the SQL."""
|
||||
categories: Counter[str] = Counter()
|
||||
placeholders: set[str] = set()
|
||||
replacements = 0
|
||||
|
||||
def _replace_insert(match: re.Match[str]) -> str:
|
||||
nonlocal replacements
|
||||
prefix, cols_raw, values_blob, semi = match.groups()
|
||||
cols = [normalize_key_name(c.strip(" `\"[]")) for c in cols_raw.split(",")]
|
||||
tuples = _split_sql_tuples(values_blob)
|
||||
if not tuples:
|
||||
return match.group(0)
|
||||
|
||||
new_tuples: list[str] = []
|
||||
for tup in tuples:
|
||||
fields = _split_sql_fields(tup)
|
||||
if len(fields) != len(cols):
|
||||
new_tuples.append(f"({tup})")
|
||||
continue
|
||||
new_fields: list[str] = []
|
||||
for col_norm, raw_field in zip(cols, fields):
|
||||
cat = scanner.sensitive_keys.get(col_norm)
|
||||
if (
|
||||
cat
|
||||
and _should_redact_key_for_profile(cat, profile)
|
||||
and raw_field.upper() != "NULL"
|
||||
):
|
||||
is_quoted = raw_field.startswith("'") and raw_field.endswith("'") and len(raw_field) >= 2
|
||||
inner = raw_field[1:-1].replace("''", "'") if is_quoted else raw_field
|
||||
if inner.strip() and not scanner.is_allowlisted(inner):
|
||||
tok = vault.redact_value(
|
||||
raw_value=inner,
|
||||
category=cat,
|
||||
rule_id=f"sql:{col_norm}",
|
||||
session_id=session_id,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
replacements += 1
|
||||
categories[cat] += 1
|
||||
placeholders.add(tok)
|
||||
escaped_tok = tok.replace("'", "''")
|
||||
new_fields.append(f"'{escaped_tok}'" if is_quoted else f"'{escaped_tok}'")
|
||||
continue
|
||||
new_fields.append(raw_field)
|
||||
new_tuples.append("(" + ", ".join(new_fields) + ")")
|
||||
return prefix + ", ".join(new_tuples) + semi
|
||||
|
||||
sql_updated = _SQL_INSERT_RE.sub(_replace_insert, text)
|
||||
fallback = vault.redact(
|
||||
sql_updated,
|
||||
scanner=scanner,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
replacements += fallback.replacements
|
||||
categories.update(fallback.categories)
|
||||
placeholders.update(fallback.placeholders)
|
||||
return RedactionResult(
|
||||
redacted_text=fallback.redacted_text,
|
||||
session_id=session_id,
|
||||
replacements=replacements,
|
||||
categories=dict(categories),
|
||||
placeholders=sorted(placeholders),
|
||||
)
|
||||
|
||||
|
||||
def redact_by_extension(
|
||||
text: str,
|
||||
extension: str,
|
||||
scanner: RedactionScanner,
|
||||
vault: SessionVault,
|
||||
session_id: str = "default",
|
||||
profile: str = "strict",
|
||||
format_preserving: bool = False,
|
||||
) -> RedactionResult:
|
||||
"""Dispatch to schema-aware redactor based on file extension or content_type."""
|
||||
ext = extension.lower().lstrip(".")
|
||||
if ext == "json":
|
||||
return redact_json_text(
|
||||
text, scanner, vault, session_id=session_id, profile=profile,
|
||||
format_preserving=format_preserving, jsonl=False,
|
||||
)
|
||||
if ext in {"jsonl", "ndjson"}:
|
||||
return redact_json_text(
|
||||
text, scanner, vault, session_id=session_id, profile=profile,
|
||||
format_preserving=format_preserving, jsonl=True,
|
||||
)
|
||||
if ext == "csv":
|
||||
return redact_csv_text(
|
||||
text, scanner, vault, session_id=session_id, profile=profile,
|
||||
format_preserving=format_preserving, delimiter=",",
|
||||
)
|
||||
if ext == "tsv":
|
||||
return redact_csv_text(
|
||||
text, scanner, vault, session_id=session_id, profile=profile,
|
||||
format_preserving=format_preserving, delimiter="\t",
|
||||
)
|
||||
if ext == "sql":
|
||||
return redact_sql_text(
|
||||
text, scanner, vault, session_id=session_id, profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
return vault.redact(
|
||||
text,
|
||||
scanner=scanner,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
@@ -0,0 +1,75 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
from collections import Counter
|
||||
from typing import Callable
|
||||
|
||||
_DIGITS_ONLY_RE = re.compile(r"\D+")
|
||||
|
||||
|
||||
def is_valid_ssn(value: str) -> bool:
|
||||
"""Validate US SSN structure per SSA allocation rules (excludes 000/666/9xx, 00, 0000)."""
|
||||
digits = _DIGITS_ONLY_RE.sub("", value)
|
||||
if len(digits) != 9:
|
||||
return False
|
||||
area = int(digits[:3])
|
||||
group = int(digits[3:5])
|
||||
serial = int(digits[5:])
|
||||
if area == 0 or area == 666 or area >= 900:
|
||||
return False
|
||||
if group == 0 or serial == 0:
|
||||
return False
|
||||
# Filter obvious synthetic sequences like 123456789 / 111111111
|
||||
if len(set(digits)) == 1:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def is_valid_luhn(value: str) -> bool:
|
||||
"""Validate payment card numbers via the Luhn checksum."""
|
||||
digits = _DIGITS_ONLY_RE.sub("", value)
|
||||
if not (13 <= len(digits) <= 19):
|
||||
return False
|
||||
if len(set(digits)) == 1:
|
||||
return False
|
||||
total = 0
|
||||
reverse_digits = digits[::-1]
|
||||
for idx, ch in enumerate(reverse_digits):
|
||||
n = ord(ch) - 48
|
||||
if idx % 2 == 1:
|
||||
n *= 2
|
||||
if n > 9:
|
||||
n -= 9
|
||||
total += n
|
||||
return total % 10 == 0
|
||||
|
||||
|
||||
def is_valid_aba_routing(value: str) -> bool:
|
||||
"""Validate 9-digit US ABA bank routing transit number checksum."""
|
||||
digits = _DIGITS_ONLY_RE.sub("", value)
|
||||
if len(digits) != 9:
|
||||
return False
|
||||
nums = [ord(c) - 48 for c in digits]
|
||||
checksum = (
|
||||
3 * (nums[0] + nums[3] + nums[6])
|
||||
+ 7 * (nums[1] + nums[4] + nums[7])
|
||||
+ (nums[2] + nums[5] + nums[8])
|
||||
)
|
||||
return checksum % 10 == 0
|
||||
|
||||
|
||||
def shannon_entropy(value: str) -> float:
|
||||
"""Compute Shannon entropy (bits per character) for secret detection."""
|
||||
if not value:
|
||||
return 0.0
|
||||
length = len(value)
|
||||
counts = Counter(value)
|
||||
return -sum((c / length) * math.log2(c / length) for c in counts.values())
|
||||
|
||||
|
||||
VALIDATORS: dict[str, Callable[[str], bool]] = {
|
||||
"ssn": is_valid_ssn,
|
||||
"luhn": is_valid_luhn,
|
||||
"aba_routing": is_valid_aba_routing,
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from redactor_mcp.models import RedactionResult, RehydrationSummary, TokenRecord
|
||||
from redactor_mcp.scanner import RedactionScanner
|
||||
|
||||
TOKEN_PATTERN = re.compile(r"<<REDACT:[A-Z0-9_]+:[0-9a-f]{4}:\d+>>")
|
||||
|
||||
|
||||
def _luhn_check_digit(prefix15: str) -> str:
|
||||
digits = [int(c) for c in prefix15]
|
||||
total = 0
|
||||
for i, d in enumerate(reversed(digits)):
|
||||
val = d * 2 if i % 2 == 0 else d
|
||||
if val > 9:
|
||||
val -= 9
|
||||
total += val
|
||||
return str((10 - (total % 10)) % 10)
|
||||
|
||||
|
||||
def _aba_check_digit(prefix8: str) -> str:
|
||||
nums = [int(c) for c in prefix8]
|
||||
partial = (
|
||||
3 * (nums[0] + nums[3] + nums[6])
|
||||
+ 7 * (nums[1] + nums[4] + nums[7])
|
||||
+ (nums[2] + nums[5])
|
||||
)
|
||||
return str((10 - (partial % 10)) % 10)
|
||||
|
||||
|
||||
def generate_synthetic_token(category: str, nonce: str, idx: int) -> str:
|
||||
"""
|
||||
Generate format-preserving synthetic tokens using reserved/non-issuable ranges.
|
||||
|
||||
Avoids collisions with real PII while passing common schema/regex validators.
|
||||
"""
|
||||
if category == "PII_SSN":
|
||||
mid = (idx // 10000) % 100
|
||||
tail = idx % 10000
|
||||
return f"900-{mid:02d}-{tail:04d}"
|
||||
if category == "PII_ITIN":
|
||||
return f"999-70-{idx % 10000:04d}"
|
||||
if category == "PII_PHONE":
|
||||
return f"(555) 010-{idx % 10000:04d}"
|
||||
if category == "PII_EMAIL":
|
||||
return f"redact-{nonce}-{idx}@invalid.local"
|
||||
if category == "PII_DOB":
|
||||
base = datetime.date(1900, 1, 1) + datetime.timedelta(days=idx % 36500)
|
||||
return base.isoformat()
|
||||
if category == "PII_CARD":
|
||||
prefix = f"400000{idx:09d}"[:15]
|
||||
return prefix + _luhn_check_digit(prefix)
|
||||
if category == "PII_BANK_ROUTING":
|
||||
prefix = f"00{idx:06d}"[:8]
|
||||
return prefix + _aba_check_digit(prefix)
|
||||
return f"REDACT_{category}_{nonce}_{idx}"
|
||||
|
||||
|
||||
class _SessionState:
|
||||
def __init__(self, session_id: str, ttl_seconds: int) -> None:
|
||||
self.session_id = session_id
|
||||
self.nonce = secrets.token_hex(2)
|
||||
self.ttl_seconds = ttl_seconds
|
||||
self.created_at = time.monotonic()
|
||||
self.last_accessed = self.created_at
|
||||
self.counter = 0
|
||||
self.value_to_token: dict[str, str] = {}
|
||||
self.synthetic_value_to_token: dict[str, str] = {}
|
||||
self.token_to_value: dict[str, str] = {}
|
||||
self.records: dict[str, TokenRecord] = {}
|
||||
|
||||
def touch(self) -> None:
|
||||
self.last_accessed = time.monotonic()
|
||||
|
||||
def is_expired(self, now: float) -> bool:
|
||||
return self.ttl_seconds > 0 and (now - self.last_accessed) > self.ttl_seconds
|
||||
|
||||
def to_snapshot_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"session_id": self.session_id,
|
||||
"nonce": self.nonce,
|
||||
"ttl_seconds": self.ttl_seconds,
|
||||
"counter": self.counter,
|
||||
"value_to_token": self.value_to_token,
|
||||
"synthetic_value_to_token": self.synthetic_value_to_token,
|
||||
"token_to_value": self.token_to_value,
|
||||
"records": {
|
||||
tok: {
|
||||
"placeholder": rec.placeholder,
|
||||
"category": rec.category,
|
||||
"rule_id": rec.rule_id,
|
||||
"sha256_prefix": rec.sha256_prefix,
|
||||
"hit_count": rec.hit_count,
|
||||
}
|
||||
for tok, rec in self.records.items()
|
||||
},
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_snapshot_dict(cls, data: dict[str, Any]) -> "_SessionState":
|
||||
st = cls(session_id=data["session_id"], ttl_seconds=int(data.get("ttl_seconds", 14400)))
|
||||
st.nonce = data["nonce"]
|
||||
st.counter = int(data["counter"])
|
||||
st.value_to_token = dict(data.get("value_to_token", {}))
|
||||
st.synthetic_value_to_token = dict(data.get("synthetic_value_to_token", {}))
|
||||
st.token_to_value = dict(data.get("token_to_value", {}))
|
||||
for tok, rdata in data.get("records", {}).items():
|
||||
st.records[tok] = TokenRecord(
|
||||
placeholder=rdata["placeholder"],
|
||||
category=rdata["category"],
|
||||
rule_id=rdata["rule_id"],
|
||||
sha256_prefix=rdata["sha256_prefix"],
|
||||
hit_count=int(rdata.get("hit_count", 1)),
|
||||
)
|
||||
return st
|
||||
|
||||
|
||||
class SessionVault:
|
||||
"""Thread-safe ephemeral in-memory vault mapping sensitive values to session tokens."""
|
||||
|
||||
def __init__(self, ttl_seconds: int = 14400) -> None:
|
||||
self.ttl_seconds = ttl_seconds
|
||||
self._lock = threading.RLock()
|
||||
self._sessions: dict[str, _SessionState] = {}
|
||||
|
||||
def _evict_expired_locked(self) -> None:
|
||||
now = time.monotonic()
|
||||
expired = [sid for sid, state in self._sessions.items() if state.is_expired(now)]
|
||||
for sid in expired:
|
||||
del self._sessions[sid]
|
||||
|
||||
def _get_or_create_session_locked(self, session_id: str) -> _SessionState:
|
||||
self._evict_expired_locked()
|
||||
state = self._sessions.get(session_id)
|
||||
if state is None:
|
||||
state = _SessionState(session_id=session_id, ttl_seconds=self.ttl_seconds)
|
||||
self._sessions[session_id] = state
|
||||
else:
|
||||
state.touch()
|
||||
return state
|
||||
|
||||
def _mint_or_reuse_locked(
|
||||
self,
|
||||
state: _SessionState,
|
||||
raw_value: str,
|
||||
category: str,
|
||||
rule_id: str,
|
||||
format_preserving: bool,
|
||||
) -> str:
|
||||
lookup = state.synthetic_value_to_token if format_preserving else state.value_to_token
|
||||
token = lookup.get(raw_value)
|
||||
if token is not None:
|
||||
state.records[token].hit_count += 1
|
||||
return token
|
||||
|
||||
state.counter += 1
|
||||
if format_preserving:
|
||||
token = generate_synthetic_token(category, state.nonce, state.counter)
|
||||
else:
|
||||
token = f"<<REDACT:{category}:{state.nonce}:{state.counter}>>"
|
||||
lookup[raw_value] = token
|
||||
state.token_to_value[token] = raw_value
|
||||
digest = hashlib.sha256(raw_value.encode("utf-8")).hexdigest()[:12]
|
||||
state.records[token] = TokenRecord(
|
||||
placeholder=token,
|
||||
category=category,
|
||||
rule_id=rule_id,
|
||||
sha256_prefix=digest,
|
||||
hit_count=1,
|
||||
)
|
||||
return token
|
||||
|
||||
def redact_value(
|
||||
self,
|
||||
raw_value: str,
|
||||
category: str,
|
||||
rule_id: str = "structured-key",
|
||||
session_id: str = "default",
|
||||
format_preserving: bool = False,
|
||||
) -> str:
|
||||
"""Vault a single discrete value (used by schema/key-aware structured redaction)."""
|
||||
if not raw_value:
|
||||
return raw_value
|
||||
with self._lock:
|
||||
state = self._get_or_create_session_locked(session_id)
|
||||
return self._mint_or_reuse_locked(
|
||||
state=state,
|
||||
raw_value=raw_value,
|
||||
category=category,
|
||||
rule_id=rule_id,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
|
||||
def redact(
|
||||
self,
|
||||
text: str,
|
||||
scanner: RedactionScanner,
|
||||
session_id: str = "default",
|
||||
profile: str = "strict",
|
||||
format_preserving: bool = False,
|
||||
) -> RedactionResult:
|
||||
"""Scan text, assign deterministic session tokens, and return redacted text."""
|
||||
matches = scanner.scan(text, profile=profile)
|
||||
if not matches:
|
||||
with self._lock:
|
||||
self._get_or_create_session_locked(session_id)
|
||||
return RedactionResult(
|
||||
redacted_text=text,
|
||||
session_id=session_id,
|
||||
replacements=0,
|
||||
categories={},
|
||||
placeholders=[],
|
||||
)
|
||||
|
||||
category_counts: Counter[str] = Counter()
|
||||
placeholders_used: list[str] = []
|
||||
out_parts: list[str] = []
|
||||
cursor = 0
|
||||
|
||||
with self._lock:
|
||||
state = self._get_or_create_session_locked(session_id)
|
||||
for match in matches:
|
||||
out_parts.append(text[cursor : match.start])
|
||||
token = self._mint_or_reuse_locked(
|
||||
state=state,
|
||||
raw_value=match.value,
|
||||
category=match.category,
|
||||
rule_id=match.rule_id,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
out_parts.append(token)
|
||||
category_counts[match.category] += 1
|
||||
placeholders_used.append(token)
|
||||
cursor = match.end
|
||||
|
||||
out_parts.append(text[cursor:])
|
||||
|
||||
return RedactionResult(
|
||||
redacted_text="".join(out_parts),
|
||||
session_id=session_id,
|
||||
replacements=len(matches),
|
||||
categories=dict(category_counts),
|
||||
placeholders=sorted(set(placeholders_used)),
|
||||
)
|
||||
|
||||
def rehydrate_text(
|
||||
self,
|
||||
text: str,
|
||||
session_id: str = "default",
|
||||
) -> tuple[str, int, list[str]]:
|
||||
"""
|
||||
Restore bracketed and synthetic placeholders using vaulted values.
|
||||
|
||||
NOTE: Do NOT return the resulting string to an untrusted LLM/MCP tool result.
|
||||
"""
|
||||
with self._lock:
|
||||
self._evict_expired_locked()
|
||||
state = self._sessions.get(session_id)
|
||||
if state is None:
|
||||
unresolved = sorted(set(TOKEN_PATTERN.findall(text)))
|
||||
return text, 0, unresolved
|
||||
state.touch()
|
||||
token_map = dict(state.token_to_value)
|
||||
|
||||
restored_count = 0
|
||||
unresolved: set[str] = set()
|
||||
|
||||
synthetic_tokens = [t for t in token_map if not TOKEN_PATTERN.fullmatch(t)]
|
||||
if synthetic_tokens:
|
||||
escaped = sorted((re.escape(t) for t in synthetic_tokens), key=len, reverse=True)
|
||||
combined_re = re.compile(TOKEN_PATTERN.pattern + "|" + "|".join(escaped))
|
||||
else:
|
||||
combined_re = TOKEN_PATTERN
|
||||
|
||||
def _replace(match: re.Match[str]) -> str:
|
||||
nonlocal restored_count
|
||||
tok = match.group(0)
|
||||
if tok in token_map:
|
||||
restored_count += 1
|
||||
return token_map[tok]
|
||||
unresolved.add(tok)
|
||||
return tok
|
||||
|
||||
restored = combined_re.sub(_replace, text)
|
||||
return restored, restored_count, sorted(unresolved)
|
||||
|
||||
def rehydrate_to_file(
|
||||
self,
|
||||
clean_text: str,
|
||||
dest_path: Path,
|
||||
session_id: str = "default",
|
||||
) -> RehydrationSummary:
|
||||
"""One-way egress: rehydrate placeholders and write directly to disk."""
|
||||
restored, restored_count, unresolved = self.rehydrate_text(
|
||||
clean_text, session_id=session_id
|
||||
)
|
||||
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
encoded = restored.encode("utf-8")
|
||||
dest_path.write_bytes(encoded)
|
||||
return RehydrationSummary(
|
||||
destination=str(dest_path),
|
||||
bytes_written=len(encoded),
|
||||
tokens_restored=restored_count,
|
||||
unresolved_tokens=unresolved,
|
||||
session_id=session_id,
|
||||
)
|
||||
|
||||
def export_snapshot(self, session_id: Optional[str] = None) -> dict[str, Any]:
|
||||
"""Serialize vault state for encrypted pause/resume snapshots."""
|
||||
with self._lock:
|
||||
self._evict_expired_locked()
|
||||
if session_id is not None:
|
||||
st = self._sessions.get(session_id)
|
||||
sessions = {session_id: st.to_snapshot_dict()} if st else {}
|
||||
else:
|
||||
sessions = {sid: st.to_snapshot_dict() for sid, st in self._sessions.items()}
|
||||
return {"version": 1, "sessions": sessions}
|
||||
|
||||
def import_snapshot(self, payload: dict[str, Any], merge: bool = True) -> int:
|
||||
"""Restore vault sessions from a decrypted snapshot payload."""
|
||||
sessions_raw = payload.get("sessions", {})
|
||||
with self._lock:
|
||||
if not merge:
|
||||
self._sessions.clear()
|
||||
loaded = 0
|
||||
for sid, sdata in sessions_raw.items():
|
||||
self._sessions[sid] = _SessionState.from_snapshot_dict(sdata)
|
||||
loaded += 1
|
||||
return loaded
|
||||
|
||||
def status(self, session_id: Optional[str] = None) -> dict[str, Any]:
|
||||
"""Return safe non-secret metadata for active session(s)."""
|
||||
with self._lock:
|
||||
self._evict_expired_locked()
|
||||
if session_id is not None:
|
||||
state = self._sessions.get(session_id)
|
||||
if state is None:
|
||||
return {"session_id": session_id, "active": False, "token_count": 0}
|
||||
by_cat: Counter[str] = Counter()
|
||||
for rec in state.records.values():
|
||||
by_cat[rec.category] += 1
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"active": True,
|
||||
"nonce": state.nonce,
|
||||
"token_count": len(state.records),
|
||||
"categories": dict(by_cat),
|
||||
"tokens": [
|
||||
{
|
||||
"placeholder": rec.placeholder,
|
||||
"category": rec.category,
|
||||
"rule_id": rec.rule_id,
|
||||
"sha256_prefix": rec.sha256_prefix,
|
||||
"hit_count": rec.hit_count,
|
||||
}
|
||||
for rec in state.records.values()
|
||||
],
|
||||
}
|
||||
return {
|
||||
"active_sessions": [
|
||||
{
|
||||
"session_id": sid,
|
||||
"token_count": len(st.records),
|
||||
"nonce": st.nonce,
|
||||
}
|
||||
for sid, st in self._sessions.items()
|
||||
]
|
||||
}
|
||||
|
||||
def purge(self, session_id: Optional[str] = None) -> dict[str, Any]:
|
||||
"""Wipe one session or all sessions from RAM."""
|
||||
with self._lock:
|
||||
if session_id is None:
|
||||
count = len(self._sessions)
|
||||
self._sessions.clear()
|
||||
return {"purged_sessions": count}
|
||||
existed = self._sessions.pop(session_id, None) is not None
|
||||
return {"session_id": session_id, "purged": existed}
|
||||
@@ -0,0 +1,284 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import fnmatch
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from redactor_mcp.scanner import RedactionScanner, is_binary_bytes
|
||||
from redactor_mcp.structured import redact_by_extension
|
||||
from redactor_mcp.vault import SessionVault
|
||||
|
||||
_WIN_DRIVE_RE = re.compile(r"^([A-Za-z]):[\\/](.*)$")
|
||||
|
||||
DEFAULT_IGNORE_DIRS = {
|
||||
".git",
|
||||
".hg",
|
||||
".svn",
|
||||
"node_modules",
|
||||
".venv",
|
||||
"venv",
|
||||
"__pycache__",
|
||||
".pytest_cache",
|
||||
".mypy_cache",
|
||||
"dist",
|
||||
"build",
|
||||
"target",
|
||||
".next",
|
||||
".turbo",
|
||||
".idea",
|
||||
}
|
||||
|
||||
|
||||
def normalize_host_path(raw_path: str) -> Path:
|
||||
"""Translate Windows drive paths (C:\\work\\...) to WSL (/mnt/c/work/...) on POSIX."""
|
||||
cleaned = raw_path.strip()
|
||||
if os.name != "nt":
|
||||
m = _WIN_DRIVE_RE.match(cleaned)
|
||||
if m:
|
||||
drive = m.group(1).lower()
|
||||
rest = m.group(2).replace("\\", "/")
|
||||
cleaned = f"/mnt/{drive}/{rest}"
|
||||
return Path(cleaned)
|
||||
|
||||
|
||||
def _is_within(child: Path, root: Path) -> bool:
|
||||
try:
|
||||
child.relative_to(root)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def load_redactorignore(src_dir: Path) -> list[str]:
|
||||
"""Load glob ignore patterns from `<src_dir>/.redactorignore` if present."""
|
||||
ignore_file = src_dir / ".redactorignore"
|
||||
if not ignore_file.is_file():
|
||||
return []
|
||||
patterns: list[str] = []
|
||||
for line in ignore_file.read_text(encoding="utf-8", errors="replace").splitlines():
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith("#"):
|
||||
continue
|
||||
patterns.append(stripped.rstrip("/"))
|
||||
return patterns
|
||||
|
||||
|
||||
def _matches_any_glob(rel_path: str, globs: list[str]) -> bool:
|
||||
fname = rel_path.rsplit("/", 1)[-1]
|
||||
parts = rel_path.split("/")
|
||||
for pat in globs:
|
||||
if fnmatch.fnmatch(rel_path, pat) or fnmatch.fnmatch(fname, pat):
|
||||
return True
|
||||
if any(fnmatch.fnmatch(part, pat) for part in parts):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@dataclass
|
||||
class WorkspacePolicy:
|
||||
"""Enforces read, clean-staging, execution, and one-way output path boundaries."""
|
||||
|
||||
read_roots: list[Path]
|
||||
staging_root: Optional[Path]
|
||||
output_roots: list[Path]
|
||||
|
||||
@classmethod
|
||||
def from_env(cls) -> "WorkspacePolicy":
|
||||
def _parse_roots(env_key: str) -> list[Path]:
|
||||
raw = os.environ.get(env_key, "").strip()
|
||||
if not raw:
|
||||
return []
|
||||
return [normalize_host_path(p).resolve() for p in raw.split(",") if p.strip()]
|
||||
|
||||
read_roots = _parse_roots("REDACTOR_READ_ROOTS")
|
||||
output_roots = _parse_roots("REDACTOR_OUTPUT_ROOTS")
|
||||
staging_raw = os.environ.get("REDACTOR_STAGING_ROOT", "").strip()
|
||||
staging_root = normalize_host_path(staging_raw).resolve() if staging_raw else None
|
||||
return cls(
|
||||
read_roots=read_roots,
|
||||
staging_root=staging_root,
|
||||
output_roots=output_roots,
|
||||
)
|
||||
|
||||
def resolve_read_path(self, raw_path: str) -> Path:
|
||||
target = normalize_host_path(raw_path).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}"
|
||||
)
|
||||
return target
|
||||
|
||||
def resolve_clean_read_path(self, raw_path: str) -> Path:
|
||||
target = normalize_host_path(raw_path).resolve()
|
||||
allowed = list(self.read_roots)
|
||||
if self.staging_root is not None:
|
||||
allowed.append(self.staging_root)
|
||||
if allowed and not any(_is_within(target, r) for r in allowed):
|
||||
raise PermissionError(
|
||||
f"Read denied outside staging/read roots: {target}"
|
||||
)
|
||||
return target
|
||||
|
||||
def resolve_staging_dir(self, raw_dir: str = "") -> Path:
|
||||
if raw_dir.strip():
|
||||
target = normalize_host_path(raw_dir).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}"
|
||||
)
|
||||
return target
|
||||
if self.staging_root is not None:
|
||||
return self.staging_root
|
||||
raise ValueError("clean_dir is required when REDACTOR_STAGING_ROOT is not configured")
|
||||
|
||||
def resolve_exec_cwd(self, raw_cwd: str = "") -> Path:
|
||||
"""Scrubbed command execution is restricted strictly inside REDACTOR_STAGING_ROOT."""
|
||||
if self.staging_root is None:
|
||||
raise PermissionError(
|
||||
"Scrubbed execution requires REDACTOR_STAGING_ROOT to be configured"
|
||||
)
|
||||
if not raw_cwd.strip():
|
||||
return self.staging_root
|
||||
target = normalize_host_path(raw_cwd).resolve()
|
||||
if not _is_within(target, self.staging_root):
|
||||
raise PermissionError(
|
||||
f"Execution denied outside REDACTOR_STAGING_ROOT: {target}"
|
||||
)
|
||||
return target
|
||||
|
||||
def resolve_output_path(self, raw_path: str) -> Path:
|
||||
target = normalize_host_path(raw_path).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}"
|
||||
)
|
||||
if self.output_roots and not any(_is_within(target, r) for r in self.output_roots):
|
||||
raise PermissionError(
|
||||
f"Output denied outside allowed REDACTOR_OUTPUT_ROOTS: {target}"
|
||||
)
|
||||
return target
|
||||
|
||||
|
||||
class WorkspaceStager:
|
||||
"""High-throughput incremental workspace redaction for large codebases."""
|
||||
|
||||
def __init__(self, max_file_bytes: int = 2 * 1024 * 1024, max_workers: int = 4) -> None:
|
||||
self.max_file_bytes = max_file_bytes
|
||||
self.max_workers = max_workers
|
||||
self._hash_cache: dict[tuple[str, str, str, bool, str], str] = {}
|
||||
|
||||
def stage_directory(
|
||||
self,
|
||||
src_dir: Path,
|
||||
clean_dir: Path,
|
||||
scanner: RedactionScanner,
|
||||
vault: SessionVault,
|
||||
session_id: str = "default",
|
||||
profile: str = "swe",
|
||||
format_preserving: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
if not src_dir.is_dir():
|
||||
raise FileNotFoundError(f"Source directory does not exist: {src_dir}")
|
||||
clean_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
ignore_globs = list(scanner.ignore_globs) + load_redactorignore(src_dir)
|
||||
candidates: list[tuple[Path, str]] = []
|
||||
skipped_binary = 0
|
||||
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")]
|
||||
root_path = Path(root)
|
||||
for fname in files:
|
||||
if fname == ".redactorignore":
|
||||
skipped_ignored += 1
|
||||
continue
|
||||
fpath = root_path / fname
|
||||
rel = fpath.relative_to(src_dir).as_posix()
|
||||
if ignore_globs and _matches_any_glob(rel, ignore_globs):
|
||||
skipped_ignored += 1
|
||||
continue
|
||||
try:
|
||||
st = fpath.stat()
|
||||
except OSError:
|
||||
continue
|
||||
if st.st_size > self.max_file_bytes:
|
||||
skipped_large += 1
|
||||
continue
|
||||
candidates.append((fpath, rel))
|
||||
|
||||
files_scanned = 0
|
||||
files_unchanged = 0
|
||||
total_replacements = 0
|
||||
categories: dict[str, int] = {}
|
||||
|
||||
def _read_if_changed(
|
||||
item: tuple[Path, str]
|
||||
) -> tuple[str, Optional[str], Optional[str], str]:
|
||||
fpath, rel = item
|
||||
try:
|
||||
raw_bytes = fpath.read_bytes()
|
||||
except OSError:
|
||||
return rel, None, None, "error"
|
||||
if is_binary_bytes(raw_bytes[:4096]):
|
||||
return rel, None, None, "binary"
|
||||
digest = hashlib.sha256(raw_bytes).hexdigest()
|
||||
cache_key = (str(clean_dir), session_id, profile, format_preserving, rel)
|
||||
dest = clean_dir / rel
|
||||
if self._hash_cache.get(cache_key) == digest and dest.exists():
|
||||
return rel, None, digest, "unchanged"
|
||||
text = raw_bytes.decode("utf-8", errors="replace")
|
||||
return rel, text, digest, "scan"
|
||||
|
||||
with ThreadPoolExecutor(max_workers=self.max_workers) as pool:
|
||||
loaded = list(pool.map(_read_if_changed, candidates))
|
||||
|
||||
for rel, text, digest, status in loaded:
|
||||
if status == "binary":
|
||||
skipped_binary += 1
|
||||
continue
|
||||
if status == "error":
|
||||
continue
|
||||
if status == "unchanged":
|
||||
files_unchanged += 1
|
||||
continue
|
||||
assert text is not None and digest is not None
|
||||
ext = Path(rel).suffix
|
||||
result = redact_by_extension(
|
||||
text=text,
|
||||
extension=ext,
|
||||
scanner=scanner,
|
||||
vault=vault,
|
||||
session_id=session_id,
|
||||
profile=profile,
|
||||
format_preserving=format_preserving,
|
||||
)
|
||||
dest = clean_dir / rel
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_text(result.redacted_text, encoding="utf-8")
|
||||
self._hash_cache[(str(clean_dir), session_id, profile, format_preserving, rel)] = digest
|
||||
files_scanned += 1
|
||||
total_replacements += result.replacements
|
||||
for cat, count in result.categories.items():
|
||||
categories[cat] = categories.get(cat, 0) + count
|
||||
|
||||
return {
|
||||
"src_dir": str(src_dir),
|
||||
"clean_dir": str(clean_dir),
|
||||
"session_id": session_id,
|
||||
"profile": profile,
|
||||
"format_preserving": format_preserving,
|
||||
"files_scanned": files_scanned,
|
||||
"files_unchanged_cached": files_unchanged,
|
||||
"skipped_binary": skipped_binary,
|
||||
"skipped_large": skipped_large,
|
||||
"skipped_ignored": skipped_ignored,
|
||||
"total_replacements": total_replacements,
|
||||
"categories": categories,
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
SRC_DIR = REPO_ROOT / "src"
|
||||
|
||||
|
||||
class TestDaemonEndToEnd(unittest.TestCase):
|
||||
def test_unix_socket_daemon_and_mcp_stdio_bridge(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp_path = Path(tmp)
|
||||
sock_path = tmp_path / "vault.sock"
|
||||
sensitive_dir = tmp_path / "sensitive"
|
||||
clean_dir = tmp_path / "clean"
|
||||
output_dir = tmp_path / "output"
|
||||
sensitive_dir.mkdir()
|
||||
clean_dir.mkdir()
|
||||
output_dir.mkdir()
|
||||
|
||||
env = os.environ.copy()
|
||||
env["PYTHONPATH"] = str(SRC_DIR)
|
||||
env["REDACTOR_SOCKET"] = str(sock_path)
|
||||
env["REDACTOR_READ_ROOTS"] = str(sensitive_dir)
|
||||
env["REDACTOR_STAGING_ROOT"] = str(clean_dir)
|
||||
env["REDACTOR_OUTPUT_ROOTS"] = str(output_dir)
|
||||
|
||||
daemon_proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "redactor_mcp.cli", "daemon"],
|
||||
env=env,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
try:
|
||||
# Wait for Unix socket to come up
|
||||
deadline = time.monotonic() + 5.0
|
||||
while not sock_path.exists():
|
||||
if time.monotonic() > deadline:
|
||||
self.fail("Daemon failed to create Unix socket in time")
|
||||
time.sleep(0.05)
|
||||
|
||||
# Run MCP stdio bridge and call redact + write across JSON-RPC
|
||||
requests = [
|
||||
{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}},
|
||||
{"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}},
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 3,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "vault_redact_text",
|
||||
"arguments": {
|
||||
"text": "Citizen SSN 123-45-6789 DOB 1990-01-15",
|
||||
"session_id": "e2e",
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
stdin_payload = "\n".join(json.dumps(r) for r in requests) + "\n"
|
||||
mcp_res = subprocess.run(
|
||||
[sys.executable, "-m", "redactor_mcp.cli", "mcp", "--stdlib"],
|
||||
input=stdin_payload,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
timeout=10,
|
||||
check=True,
|
||||
)
|
||||
lines = [json.loads(line) for line in mcp_res.stdout.splitlines() if line.strip()]
|
||||
self.assertEqual(len(lines), 3)
|
||||
tool_names = [t["name"] for t in lines[1]["result"]["tools"]]
|
||||
self.assertIn("vault_write_file", tool_names)
|
||||
|
||||
redact_payload = json.loads(lines[2]["result"]["content"][0]["text"])
|
||||
redacted_text = redact_payload["redacted_text"]
|
||||
self.assertNotIn("123-45-6789", redacted_text)
|
||||
self.assertNotIn("1990-01-15", redacted_text)
|
||||
|
||||
# Separate MCP process shares the same daemon RAM vault and restores to output/
|
||||
write_req = {
|
||||
"jsonrpc": "2.0",
|
||||
"id": 10,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "vault_write_file",
|
||||
"arguments": {
|
||||
"content": f"Verified: {redacted_text}",
|
||||
"dest_path": str(output_dir / "verified.txt"),
|
||||
"session_id": "e2e",
|
||||
},
|
||||
},
|
||||
}
|
||||
mcp_res2 = subprocess.run(
|
||||
[sys.executable, "-m", "redactor_mcp.cli", "mcp", "--stdlib"],
|
||||
input=json.dumps(write_req) + "\n",
|
||||
text=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
timeout=10,
|
||||
check=True,
|
||||
)
|
||||
reply2 = json.loads(mcp_res2.stdout.splitlines()[0])
|
||||
self.assertFalse(reply2["result"]["isError"])
|
||||
self.assertEqual(
|
||||
(output_dir / "verified.txt").read_text(encoding="utf-8"),
|
||||
"Verified: Citizen SSN 123-45-6789 DOB 1990-01-15",
|
||||
)
|
||||
finally:
|
||||
daemon_proc.terminate()
|
||||
daemon_proc.wait(timeout=5)
|
||||
if daemon_proc.stdout:
|
||||
daemon_proc.stdout.close()
|
||||
if daemon_proc.stderr:
|
||||
daemon_proc.stderr.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,177 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from redactor_mcp.audit import AuditLogger
|
||||
from redactor_mcp.scanner import RedactionScanner
|
||||
from redactor_mcp.service import RedactorService
|
||||
from redactor_mcp.structured import (
|
||||
redact_csv_text,
|
||||
redact_json_text,
|
||||
redact_sql_text,
|
||||
)
|
||||
from redactor_mcp.validators import is_valid_aba_routing, is_valid_luhn
|
||||
from redactor_mcp.vault import SessionVault
|
||||
from redactor_mcp.workspace import WorkspacePolicy
|
||||
|
||||
|
||||
class TestStructuredAndSynthetic(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.scanner = RedactionScanner()
|
||||
self.vault = SessionVault()
|
||||
|
||||
def test_json_csv_sql_key_aware_redaction_and_roundtrip(self) -> None:
|
||||
raw_json = json.dumps(
|
||||
{
|
||||
"first_name": "Jane",
|
||||
"last_name": "Citizen",
|
||||
"dob": "1985-03-14",
|
||||
"medicaid_id": "MCD-994821",
|
||||
"status": "approved",
|
||||
}
|
||||
)
|
||||
res_json = redact_json_text(raw_json, self.scanner, self.vault, session_id="s1")
|
||||
parsed = json.loads(res_json.redacted_text)
|
||||
self.assertEqual(parsed["status"], "approved")
|
||||
self.assertNotIn("Jane", res_json.redacted_text)
|
||||
self.assertNotIn("Citizen", res_json.redacted_text)
|
||||
self.assertNotIn("1985-03-14", res_json.redacted_text)
|
||||
self.assertNotIn("MCD-994821", res_json.redacted_text)
|
||||
|
||||
restored, count, unresolved = self.vault.rehydrate_text(
|
||||
res_json.redacted_text, session_id="s1"
|
||||
)
|
||||
self.assertEqual(count, 4)
|
||||
self.assertEqual(unresolved, [])
|
||||
self.assertEqual(json.loads(restored)["first_name"], "Jane")
|
||||
|
||||
raw_csv = "id,full_name,ssn,notes\n1,John Doe,123-45-6789,Active case\n"
|
||||
res_csv = redact_csv_text(raw_csv, self.scanner, self.vault, session_id="s1")
|
||||
self.assertNotIn("John Doe", res_csv.redacted_text)
|
||||
self.assertNotIn("123-45-6789", res_csv.redacted_text)
|
||||
self.assertIn("Active case", res_csv.redacted_text)
|
||||
|
||||
raw_sql = (
|
||||
"INSERT INTO citizens (id, first_name, ssn, state) "
|
||||
"VALUES (10, 'Alice', '123-45-6789', 'OH');"
|
||||
)
|
||||
res_sql = redact_sql_text(raw_sql, self.scanner, self.vault, session_id="s1")
|
||||
self.assertNotIn("Alice", res_sql.redacted_text)
|
||||
self.assertNotIn("123-45-6789", res_sql.redacted_text)
|
||||
self.assertIn("'OH'", res_sql.redacted_text)
|
||||
restored_sql, _, _ = self.vault.rehydrate_text(res_sql.redacted_text, session_id="s1")
|
||||
self.assertIn("'Alice'", restored_sql)
|
||||
self.assertIn("'123-45-6789'", restored_sql)
|
||||
|
||||
def test_format_preserving_synthetic_tokens_and_rehydration(self) -> None:
|
||||
sample = (
|
||||
"SSN: 123-45-6789\n"
|
||||
"Email: citizen@state.gov\n"
|
||||
"Phone: (614) 555-0192\n"
|
||||
"Card: 4111111111111111\n"
|
||||
"Routing: 021000021\n"
|
||||
)
|
||||
res = self.vault.redact(
|
||||
sample, self.scanner, session_id="syn", format_preserving=True
|
||||
)
|
||||
self.assertNotIn("123-45-6789", res.redacted_text)
|
||||
self.assertNotIn("citizen@state.gov", res.redacted_text)
|
||||
self.assertIn("900-00-", res.redacted_text)
|
||||
self.assertIn("@invalid.local", res.redacted_text)
|
||||
self.assertIn("(555) 010-", res.redacted_text)
|
||||
|
||||
# Synthetic card and routing pass checksum validators
|
||||
card_tok = [p for p in res.placeholders if p.startswith("400000")][0]
|
||||
aba_tok = [p for p in res.placeholders if p.startswith("00") and len(p) == 9][0]
|
||||
self.assertTrue(is_valid_luhn(card_tok))
|
||||
self.assertTrue(is_valid_aba_routing(aba_tok))
|
||||
|
||||
# Rehydration restores original values accurately
|
||||
restored, count, unresolved = self.vault.rehydrate_text(
|
||||
res.redacted_text, session_id="syn"
|
||||
)
|
||||
self.assertEqual(unresolved, [])
|
||||
self.assertEqual(count, 5)
|
||||
self.assertEqual(restored, sample)
|
||||
|
||||
|
||||
class TestSecurityExtensionsAuditAndSnapshots(unittest.TestCase):
|
||||
def test_redactorignore_and_allowlist(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
src = root / "src"
|
||||
clean = root / "clean"
|
||||
src.mkdir()
|
||||
(src / ".redactorignore").write_text("ignored_dir/\n*.secret.bak\n", encoding="utf-8")
|
||||
(src / "ignored_dir").mkdir()
|
||||
(src / "ignored_dir" / "skip.txt").write_text("SSN: 123-45-6789", encoding="utf-8")
|
||||
(src / "dump.secret.bak").write_text("SSN: 123-45-6789", encoding="utf-8")
|
||||
(src / "package-lock.json").write_text('{"name":"demo"}', encoding="utf-8")
|
||||
(src / "notes.txt").write_text(
|
||||
"Contact example@example.com or real.user@state.gov\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
policy = WorkspacePolicy([src.resolve()], clean.resolve(), [])
|
||||
service = RedactorService(policy=policy)
|
||||
summary = service.stage_workspace(str(src), session_id="ign", profile="strict")
|
||||
|
||||
self.assertEqual(summary["files_scanned"], 1)
|
||||
self.assertGreaterEqual(summary["skipped_ignored"], 4)
|
||||
notes_clean = (clean / "notes.txt").read_text(encoding="utf-8")
|
||||
self.assertIn("example@example.com", notes_clean)
|
||||
self.assertNotIn("real.user@state.gov", notes_clean)
|
||||
|
||||
def test_run_scrubbed_executes_only_in_staging_and_scrubs_output(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
sensitive = root / "sensitive"
|
||||
clean = root / "clean-staging"
|
||||
sensitive.mkdir()
|
||||
clean.mkdir()
|
||||
|
||||
policy = WorkspacePolicy([sensitive.resolve()], clean.resolve(), [])
|
||||
service = RedactorService(policy=policy)
|
||||
|
||||
with self.assertRaises(PermissionError):
|
||||
service.run_scrubbed("echo hi", cwd=str(sensitive))
|
||||
|
||||
res = service.run_scrubbed(
|
||||
'python3 -c "print(\'SSN=123-45-6789\')"',
|
||||
session_id="exec-1",
|
||||
)
|
||||
self.assertEqual(res["exit_code"], 0)
|
||||
self.assertNotIn("123-45-6789", res["stdout"])
|
||||
self.assertIn("<<REDACT:PII_SSN:", res["stdout"])
|
||||
|
||||
def test_audit_log_and_encrypted_snapshot_roundtrip(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
audit_path = root / "audit.jsonl"
|
||||
snap_path = root / "vault.snap"
|
||||
|
||||
svc1 = RedactorService(audit=AuditLogger(audit_path))
|
||||
out = svc1.redact_text("SSN: 123-45-6789", session_id="case-99")
|
||||
svc1.save_snapshot(str(snap_path), passphrase="StrongStatePassphrase!", session_id="case-99")
|
||||
|
||||
audit_content = audit_path.read_text(encoding="utf-8")
|
||||
self.assertNotIn("123-45-6789", audit_content)
|
||||
self.assertIn("redact_text", audit_content)
|
||||
self.assertIn("save_snapshot", audit_content)
|
||||
|
||||
# Wrong passphrase fails authentication
|
||||
svc2 = RedactorService()
|
||||
with self.assertRaises(Exception):
|
||||
svc2.load_snapshot(str(snap_path), passphrase="WrongPassword!")
|
||||
|
||||
# Correct passphrase restores session into fresh vault
|
||||
loaded = svc2.load_snapshot(str(snap_path), passphrase="StrongStatePassphrase!")
|
||||
self.assertEqual(loaded["sessions_loaded"], 1)
|
||||
restored = svc2.rehydrate_text_cli(out["redacted_text"], session_id="case-99")
|
||||
self.assertEqual(restored["restored_text"], "SSN: 123-45-6789")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,114 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from redactor_mcp.cli import main as cli_main
|
||||
|
||||
HOOK_SCRIPT = (
|
||||
Path(__file__).resolve().parents[1] / "scripts" / "hooks" / "agy_guard.py"
|
||||
)
|
||||
|
||||
|
||||
def _load_hook_module():
|
||||
spec = importlib.util.spec_from_file_location("agy_guard", HOOK_SCRIPT)
|
||||
assert spec is not None and spec.loader is not None
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
class TestHooksAndCLI(unittest.TestCase):
|
||||
def test_pre_tool_use_denies_protected_paths_and_allows_clean(self) -> None:
|
||||
hook = _load_hook_module()
|
||||
deny = hook.handle_pre_tool(
|
||||
{
|
||||
"toolCall": {
|
||||
"name": "read_file",
|
||||
"args": {"Path": "/work/sensitive/citizens.csv"},
|
||||
}
|
||||
}
|
||||
)
|
||||
self.assertEqual(deny["decision"], "deny")
|
||||
|
||||
allow = hook.handle_pre_tool(
|
||||
{
|
||||
"toolCall": {
|
||||
"name": "read_file",
|
||||
"args": {"Path": "/work/clean-staging/app.py"},
|
||||
}
|
||||
}
|
||||
)
|
||||
self.assertEqual(allow["decision"], "allow")
|
||||
|
||||
deny_pem = hook.handle_pre_tool(
|
||||
{
|
||||
"toolCall": {
|
||||
"name": "read_file",
|
||||
"args": {"Path": "/work/repo/certs/prod.pem"},
|
||||
}
|
||||
}
|
||||
)
|
||||
self.assertEqual(deny_pem["decision"], "deny")
|
||||
|
||||
deny_creds = hook.handle_pre_tool(
|
||||
{
|
||||
"toolCall": {
|
||||
"name": "run_command",
|
||||
"args": {"CommandLine": "cat credentials.json"},
|
||||
}
|
||||
}
|
||||
)
|
||||
self.assertEqual(deny_creds["decision"], "deny")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
(Path(tmp) / ".redactorpolicy.json").write_text(
|
||||
json.dumps({"protectedPaths": ["citizen-exports"]}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
deny_custom = hook.handle_pre_tool(
|
||||
{
|
||||
"cwd": tmp,
|
||||
"toolCall": {
|
||||
"name": "read_file",
|
||||
"args": {"Path": f"{tmp}/citizen-exports/batch1.csv"},
|
||||
},
|
||||
}
|
||||
)
|
||||
self.assertEqual(deny_custom["decision"], "deny")
|
||||
|
||||
def test_pre_invocation_terminates_on_raw_ssn_or_key(self) -> None:
|
||||
hook = _load_hook_module()
|
||||
blocked = hook.handle_pre_invocation(
|
||||
{"lastUserInput": "Please check SSN 123-45-6789 in the DB."}
|
||||
)
|
||||
self.assertEqual(blocked.get("terminationBehavior"), "terminate")
|
||||
self.assertIn("PII_SSN", blocked["injectSteps"][0]["errorMessage"]["userMessage"])
|
||||
|
||||
safe = hook.handle_pre_invocation(
|
||||
{"lastUserInput": "Please check <<REDACT:PII_SSN:a9f3:1>> in clean-staging/."}
|
||||
)
|
||||
self.assertEqual(safe, {})
|
||||
|
||||
def test_cli_sanitize_in_process(self) -> None:
|
||||
old_stdin, old_stdout = sys.stdin, sys.stdout
|
||||
try:
|
||||
sys.stdin = io.StringIO("SSN: 123-45-6789")
|
||||
buf = io.StringIO()
|
||||
sys.stdout = buf
|
||||
rc = cli_main(["sanitize", "--session", "cli-test"])
|
||||
self.assertEqual(rc, 0)
|
||||
out = buf.getvalue()
|
||||
self.assertIn("<<REDACT:PII_SSN:", out)
|
||||
self.assertNotIn("123-45-6789", out)
|
||||
finally:
|
||||
sys.stdin, sys.stdout = old_stdin, old_stdout
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,110 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from redactor_mcp.scanner import RedactionScanner
|
||||
from redactor_mcp.validators import is_valid_aba_routing, is_valid_luhn, is_valid_ssn
|
||||
from redactor_mcp.vault import SessionVault
|
||||
|
||||
|
||||
class TestValidators(unittest.TestCase):
|
||||
def test_ssn_validator_rejects_invalid_prefixes(self) -> None:
|
||||
self.assertTrue(is_valid_ssn("123-45-6789"))
|
||||
self.assertFalse(is_valid_ssn("000-12-3456"))
|
||||
self.assertFalse(is_valid_ssn("666-12-3456"))
|
||||
self.assertFalse(is_valid_ssn("901-12-3456"))
|
||||
self.assertFalse(is_valid_ssn("123-00-6789"))
|
||||
self.assertFalse(is_valid_ssn("123-45-0000"))
|
||||
self.assertFalse(is_valid_ssn("111-11-1111"))
|
||||
|
||||
def test_luhn_and_aba_validators(self) -> None:
|
||||
self.assertTrue(is_valid_luhn("4111 1111 1111 1111"))
|
||||
self.assertFalse(is_valid_luhn("4111 1111 1111 1112"))
|
||||
self.assertTrue(is_valid_aba_routing("021000021"))
|
||||
self.assertFalse(is_valid_aba_routing("021000022"))
|
||||
|
||||
|
||||
class TestScannerAndVault(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.scanner = RedactionScanner()
|
||||
self.vault = SessionVault(ttl_seconds=3600)
|
||||
|
||||
def test_state_pii_and_swe_secrets_redaction_and_roundtrip(self) -> None:
|
||||
# Build synthetic secret strings dynamically so static scanners don't flag test literals
|
||||
aws_key = "".join(["AK", "IA", "IOSFODNN7EXAMPLE"])
|
||||
gh_tok = "".join(["gh", "p_"]) + ("A1b2C3d4E5" * 4)
|
||||
db_pass = "S3cr3t" + "Pass!"
|
||||
db_uri = "".join(["post", "gres://", "admin:", db_pass, "@db.internal:5432/benefits"])
|
||||
dashes = "-" * 5
|
||||
pem_block = (
|
||||
f"{dashes}BEGIN RSA PRIVATE KEY{dashes}\n"
|
||||
"MIIBOgIBAAJBALeFakeKeyMaterialLineForUnitTestingOnly\n"
|
||||
f"{dashes}END RSA PRIVATE KEY{dashes}"
|
||||
)
|
||||
sample = (
|
||||
"Applicant SSN: 123-45-6789, DOB: 1984-07-19, Email: jane.citizen@state.gov\n"
|
||||
"Repeat SSN check: 123-45-6789\n"
|
||||
"Address: 742 Evergreen Terrace Apt 4B\n"
|
||||
f"AWS_ACCESS_KEY_ID={aws_key}\n"
|
||||
f"GITHUB_TOKEN={gh_tok}\n"
|
||||
f"DATABASE_URL={db_uri}\n"
|
||||
f"{pem_block}\n"
|
||||
)
|
||||
|
||||
res = self.vault.redact(sample, self.scanner, session_id="case-42", profile="strict")
|
||||
self.assertNotIn("123-45-6789", res.redacted_text)
|
||||
self.assertNotIn("1984-07-19", res.redacted_text)
|
||||
self.assertNotIn("jane.citizen@state.gov", res.redacted_text)
|
||||
self.assertNotIn(aws_key, res.redacted_text)
|
||||
self.assertNotIn(gh_tok, res.redacted_text)
|
||||
self.assertNotIn(db_pass, res.redacted_text)
|
||||
self.assertNotIn("MIIBOgIBAAJBALeFakeKeyMaterial", res.redacted_text)
|
||||
|
||||
# Deterministic token reuse for repeated SSN
|
||||
ssn_tokens = [p for p in res.placeholders if ":PII_SSN:" in p]
|
||||
self.assertEqual(len(ssn_tokens), 1)
|
||||
self.assertEqual(res.redacted_text.count(ssn_tokens[0]), 2)
|
||||
|
||||
# Status never leaks raw values
|
||||
status = self.vault.status("case-42")
|
||||
status_str = str(status)
|
||||
self.assertNotIn("123-45-6789", status_str)
|
||||
self.assertNotIn(aws_key, status_str)
|
||||
self.assertTrue(status["active"])
|
||||
|
||||
# One-way egress rehydration restores exact original text to file
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out_path = Path(tmp) / "restored.txt"
|
||||
summary = self.vault.rehydrate_to_file(
|
||||
res.redacted_text, out_path, session_id="case-42"
|
||||
)
|
||||
self.assertEqual(summary.unresolved_tokens, [])
|
||||
self.assertGreaterEqual(summary.tokens_restored, 6)
|
||||
self.assertEqual(out_path.read_text(encoding="utf-8"), sample)
|
||||
|
||||
def test_rescanning_does_not_double_redact_placeholders(self) -> None:
|
||||
first = self.vault.redact("SSN: 123-45-6789", self.scanner, session_id="s1")
|
||||
second = self.vault.redact(first.redacted_text, self.scanner, session_id="s1")
|
||||
self.assertEqual(first.redacted_text, second.redacted_text)
|
||||
self.assertEqual(second.replacements, 0)
|
||||
|
||||
def test_benign_env_placeholders_not_redacted(self) -> None:
|
||||
text = "".join(["API_", "KEY=changeme\n", "TOK", "EN=placeholder\n"])
|
||||
res = self.vault.redact(text, self.scanner, session_id="s2")
|
||||
self.assertEqual(res.replacements, 0)
|
||||
|
||||
def test_purge_clears_session_mappings(self) -> None:
|
||||
res = self.vault.redact("SSN: 123-45-6789", self.scanner, session_id="temp")
|
||||
self.vault.purge("temp")
|
||||
restored, count, unresolved = self.vault.rehydrate_text(
|
||||
res.redacted_text, session_id="temp"
|
||||
)
|
||||
self.assertEqual(count, 0)
|
||||
self.assertEqual(len(unresolved), 1)
|
||||
self.assertEqual(restored, res.redacted_text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,136 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from redactor_mcp.client import VaultClient
|
||||
from redactor_mcp.server import StdioMCPServer
|
||||
from redactor_mcp.service import RedactorService
|
||||
from redactor_mcp.workspace import WorkspacePolicy, normalize_host_path
|
||||
|
||||
|
||||
class TestWorkspaceAndMCP(unittest.TestCase):
|
||||
def test_windows_to_wsl_path_normalization(self) -> None:
|
||||
converted = normalize_host_path(r"C:\Users\dev\sensitive\data.csv")
|
||||
self.assertEqual(converted.as_posix(), "/mnt/c/Users/dev/sensitive/data.csv")
|
||||
|
||||
def test_policy_blocks_output_into_staging_and_outside_roots(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
sensitive = root / "sensitive"
|
||||
clean = root / "clean-staging"
|
||||
output = root / "final-output"
|
||||
sensitive.mkdir()
|
||||
clean.mkdir()
|
||||
output.mkdir()
|
||||
|
||||
policy = WorkspacePolicy(
|
||||
read_roots=[sensitive.resolve()],
|
||||
staging_root=clean.resolve(),
|
||||
output_roots=[output.resolve()],
|
||||
)
|
||||
service = RedactorService(policy=policy)
|
||||
client = VaultClient(service=service)
|
||||
mcp = StdioMCPServer(client=client)
|
||||
|
||||
secret_file = sensitive / "client.txt"
|
||||
secret_file.write_text("SSN: 123-45-6789\n", encoding="utf-8")
|
||||
|
||||
# Initialize MCP
|
||||
init_resp = mcp.handle_message(
|
||||
{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}
|
||||
)
|
||||
self.assertIsNotNone(init_resp)
|
||||
self.assertEqual(init_resp["result"]["serverInfo"]["name"], "redactor-vault")
|
||||
|
||||
# Read via MCP tool
|
||||
read_resp = mcp.handle_message(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 2,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "vault_read_file",
|
||||
"arguments": {"path": str(secret_file), "session_id": "s1"},
|
||||
},
|
||||
}
|
||||
)
|
||||
self.assertFalse(read_resp["result"]["isError"])
|
||||
payload = json.loads(read_resp["result"]["content"][0]["text"])
|
||||
self.assertNotIn("123-45-6789", payload["redacted_text"])
|
||||
|
||||
# Exfiltration attempt: writing rehydrated output into clean-staging MUST fail
|
||||
leak_resp = mcp.handle_message(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 3,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "vault_write_file",
|
||||
"arguments": {
|
||||
"content": payload["redacted_text"],
|
||||
"dest_path": str(clean / "leak.txt"),
|
||||
"session_id": "s1",
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
self.assertTrue(leak_resp["result"]["isError"])
|
||||
self.assertIn("exfiltration guard", leak_resp["result"]["content"][0]["text"])
|
||||
|
||||
# Legitimate one-way write to final-output succeeds and never echoes secret
|
||||
ok_resp = mcp.handle_message(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 4,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "vault_write_file",
|
||||
"arguments": {
|
||||
"content": payload["redacted_text"],
|
||||
"dest_path": str(output / "final.txt"),
|
||||
"session_id": "s1",
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
self.assertFalse(ok_resp["result"]["isError"])
|
||||
ok_text = ok_resp["result"]["content"][0]["text"]
|
||||
self.assertNotIn("123-45-6789", ok_text)
|
||||
self.assertEqual((output / "final.txt").read_text(encoding="utf-8"), "SSN: 123-45-6789\n")
|
||||
|
||||
def test_incremental_stage_workspace_caches_unchanged_files(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
src = root / "src_repo"
|
||||
clean = root / "clean_repo"
|
||||
src.mkdir()
|
||||
fake_stripe_prefix = "_".join(["sk", "live"]) + "_"
|
||||
fake_stripe = fake_stripe_prefix + "0123456789abcdef0123456789"
|
||||
(src / "app.py").write_text(f'API_KEY = "{fake_stripe}"\n', encoding="utf-8")
|
||||
(src / "readme.md").write_text("Hello world\n", encoding="utf-8")
|
||||
# Binary file should be skipped cleanly
|
||||
(src / "blob.bin").write_bytes(b"\x00\x01\x02\x03")
|
||||
|
||||
policy = WorkspacePolicy(
|
||||
read_roots=[src.resolve()],
|
||||
staging_root=clean.resolve(),
|
||||
output_roots=[],
|
||||
)
|
||||
service = RedactorService(policy=policy)
|
||||
|
||||
first = service.stage_workspace(str(src), session_id="repo-1", profile="swe")
|
||||
self.assertEqual(first["files_scanned"], 2)
|
||||
self.assertEqual(first["skipped_binary"], 1)
|
||||
self.assertEqual(first["total_replacements"], 1)
|
||||
self.assertNotIn(fake_stripe_prefix, (clean / "app.py").read_text(encoding="utf-8"))
|
||||
|
||||
second = service.stage_workspace(str(src), session_id="repo-1", profile="swe")
|
||||
self.assertEqual(second["files_scanned"], 0)
|
||||
self.assertEqual(second["files_unchanged_cached"], 2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user