pgveil
零信任 PostgreSQL wire proxy 與原生 Go MCP server,具備動態 PII 遮罩(8 個合規套件)、PG17 AST SQL 防火牆,以及即時 HITL 核准暫停機制。
文件
PostgreSQL wire-protocol v3 proxy and MCP server written in Go. Parses queries with PostgreSQL 17's C parser (libpg_query), blocks destructive or side-channel SQL, injects virtual row-level filters, and masks PII in DataRow responses without database extensions or schema changes.
# Run the embedded in-memory PostgreSQL sandbox + web console (:8088) + wire proxy (:6432)
brew install duhanguler/tap/pgveil && pgveil demo
- postgres://app:secret@db.internal:5432/prod
+ postgres://app:secret@pgveil.internal:6432/prod?application_name=claude-mcp
What it does
- Wire-level PII & secret masking. Rewrites
DataRowpackets on the wire for Simple and Extended Query protocols (psql,pgx/v5,psycopg3, JDBC, DBeaver) across 8 checksum-validated compliance packs (GDPR, KVKK, PCI-DSS, HIPAA, LGPD, PIPEDA, UK-GDPR, cloud/API secrets) usingpartial,redact,last4, deterministic HMAChash(JOIN-preserving),fake, ornullstrategies (ADR-001, ADR-003). - PostgreSQL 17 AST SQL firewall. Embeds
libpg_queryto block DDL, unscoped writes, tautologies (WHERE 1=1), modifying CTEs, multi-statement SQL, dangerous functions (pg_read_file,COPY TO PROGRAM), and PII side-channel probes (WHERE tckn LIKE '100%',SUBSTRING(iban, 1, 8),ORDER BY ssn) (ADR-002, ADR-005). - AST virtual row-level security (RLS). Injects tenant predicates into client queries via
pg_query.Deparse(handlingLEFT JOINONplacement,FULL OUTER JOINwrapping, Extended Query$1/$2params, and typed{{jwt.*}}/{{db_user}}bindings) after firewall checks run on the original AST (ADR-006). - Live HITL holds, cost guard & rollout controls. Pauses matching writes synchronously on the wire until approved in the web console or ChatOps (Slack Block Kit), checks sideband read-only
EXPLAINcost budgets, enforces QPM limits and AI-agent retry-loop circuit breaking (SQLSTATE 53300), and supports shadowmode: auditrollout + SIGHUP/API hot-reload (ADR-004). - Schema PII discovery & native MCP.
pgveil discoverandpgveil initscan live schemas to generate a starterpgveil.yaml.pgveil mcpexposes 5 guarded read-only tools over stdio or Streamable HTTP with no Node.js runtime required.
Example Wire Session
Connecting any PostgreSQL client on port 6432 with application_name=claude-mcp:
-- Structured columns masked on the wire (HMAC token + partial masks)
SELECT id, full_name, email, phone, tckn, iban FROM customers ORDER BY id LIMIT 3;
-- 1 | tok_5351939b7cc5 | a***@example.com.tr | +90 *** ** 21 | 100******46 | TR33 **** **** **** 1326
-- 2 | tok_c602dcb1b2f4 | m***@acme.io | +90 *** ** 80 | 123******50 | TR33 **** **** **** 1326
-- 3 | tok_85015ababe75 | e***@eu-shop.de | +49 *** ** 03 | 246******94 | DE89 **** **** **** 3000
-- Bulk reads capped with a standard PostgreSQL NOTICE
SELECT id, email FROM customers;
-- NOTICE: pgveil: result truncated to 25 rows (15 excess rows suppressed by profile "ai_agent" row-exfiltration budget)
-- Unscoped writes and side-channel probes blocked at AST level
DELETE FROM orders WHERE 1 = 1;
-- ERROR: Unscoped DELETE without effective WHERE clause (or tautology like 1=1) is blocked (SQLSTATE 42501)
SELECT id, full_name FROM customers WHERE tckn LIKE '100000%';
-- ERROR: PII side-channel inference blocked: protected column "tckn" referenced in WHERE predicate (SQLSTATE 42501)
-- Synchronous HITL hold: pauses on the wire until approved in http://localhost:8088
UPDATE orders SET status = 'refunded' WHERE id = 1001;
-- [Paused -> Operator clicks Approve -> Resumes]
-- UPDATE 1
Architecture
flowchart LR
Clients["Clients & Agents<br/>psql / pgx / psycopg / MCP"] -->|"PG Wire v3 (:6432)<br/>or MCP stdio / HTTP"| Proxy["pgveil (Go)<br/>PG17 AST Firewall + Virtual RLS<br/>Wire PII Masker + HITL + Web UI (:8088)"]
Proxy -->|"Verified SQL (TLS)"| PG[("PostgreSQL 14-17<br/>RDS / Cloud SQL / Neon / Local")]
Proxy -->|"Async Events"| Kafka["Kafka / Redpanda"]
Kafka --> Worker["pgveil-audit-worker<br/>Batch Sink + DLQ + Alerts"]
Proxy & Worker -.->|"OTLP / Metrics"| Obs["OpenTelemetry / Prometheus / Grafana"]
Quickstart
1. Homebrew (macOS & Linux)
brew install duhanguler/tap/pgveil
# In-memory sandbox (no Docker or external PostgreSQL needed)
pgveil demo
# Scan an existing database and generate a starter pgveil.yaml
pgveil init --dsn "postgres://user:pass@localhost:5432/mydb" --output pgveil.yaml
# Start the wire proxy (:6432) and web console (:8088)
pgveil serve --config pgveil.yaml
2. Full stack via Docker Compose
Starts PostgreSQL 16 (seeded with synthetic PII), pgveil (:6432 wire + :8088 UI), Redpanda, pgveil-audit-worker, Jaeger, Prometheus, and Grafana:
git clone https://github.com/duhanguler/pgveil.git
cd pgveil
docker compose up --build
- Web Console:
http://localhost:8088 - Wire Proxy:
postgres://pgveil:pgveil_dev_password@localhost:6432/pgveil_demo?application_name=claude-mcp - Grafana:
http://localhost:3000(admin/pgveil_grafana) · Jaeger:http://localhost:16686
3. Build from source & CI check
make build
# Evaluate a SQL statement against policy in CI (exits 2 if blocked)
./bin/pgveil scan \
--sql "SELECT c.id, o.order_number FROM customers c LEFT JOIN orders o ON c.id = o.customer_id" \
--profile tenant_tr
Configuration & Integrations
AST Virtual Row-Level Security (RLS)
Firewall checks run on the original client AST before Virtual RLS rewrites the query, so an unscoped DELETE FROM orders is blocked instead of silently scoped to one tenant.
profiles:
- name: "tenant_tr"
firewall:
row_filters:
- table: "customers"
predicate: "city = 'Istanbul'"
- table: "orders"
predicate: "currency = 'TRY'"
# Session or JWT claim binding (typed/escaped):
# - table: "invoices"
# predicate: "owner = '{{db_user}}'"
-- Client sends:
SELECT c.id, c.full_name, c.city, o.order_number, o.currency
FROM customers c LEFT JOIN orders o ON c.id = o.customer_id;
-- Rewritten on the wire:
SELECT c.id, c.full_name, c.city, o.order_number, o.currency
FROM customers c LEFT JOIN orders o ON c.id = o.customer_id AND o.currency = 'TRY'
WHERE c.city = 'Istanbul';

Live Schema PII Discovery (pgveil discover)
pgveil discover --dsn "postgres://pgveil:pgveil_dev_password@127.0.0.1:5432/pgveil_demo?sslmode=disable"
TABLE.COLUMN RISK COMPLIANCE STRATEGY SAMPLE MASKED
------------ ---- ---------- -------- -------------
api_secrets.secret_value CRITICAL SECRETS redact [REDACTED:GITHUB_TOKEN]
customers.email HIGH GDPR,KVKK partial a***@example.com.tr
customers.tckn CRITICAL KVKK partial 100******46
customers.iban HIGH GDPR,KVKK partial TR33 **** **** **** 1326
payments.card_number CRITICAL PCI-DSS last4 ****-****-****-4242

Claude Desktop / Cursor MCP Setup
Native single-binary MCP server (examples/mcp-claude/pgveil_native_mcp.json) exposing list_tables, describe_table, inspect_policy, explain_query, and query (also listed on mcpservers.org and Glama):
{
"mcpServers": {
"pgveil-native-postgres": {
"command": "/opt/homebrew/bin/pgveil",
"args": ["mcp", "--config", "/path/to/configs/pgveil.yaml", "--profile", "ai_agent"]
}
}
}
| Env Variable | Default | Purpose |
|---|---|---|
PGVEIL_CONFIG | configs/pgveil.yaml | Policy YAML path |
PGVEIL_PROFILE | ai_agent | Enforced role profile |
PGVEIL_DSN / DATABASE_URL | From config | Upstream PostgreSQL DSN override |
PGVEIL_MCP_HTTP | Empty (stdio) | Listen address (e.g. :8090) for Streamable HTTP MCP |
For wire-proxy mode with the official Postgres MCP server or a Python psycopg client, see examples/mcp-claude/claude_desktop_config.json and examples/python-agent/agent_demo.py.
Kubernetes Deployment (Helm)
helm lint deploy/helm/pgveil
helm upgrade --install pgveil deploy/helm/pgveil \
--namespace database-security --create-namespace \
--set upstream.addr=postgres-primary.database.svc.cluster.local:5432 \
--set security.maskingSecret="$PGVEIL_MASKING_SECRET"
Compliance Packs & Project Layout
Supported compliance packs in internal/pii:
kvkk: TCKN (mod-10), TR IBAN (ISO 13616 Mod-97), VKN tax ID, TR mobile phones, emailgdpr: EU IBAN (Mod-97), email, international phones, IPv4pci-dss: Payment cards (Luhn + BIN)hipaa: US SSN (SSA area/group/serial rules), email, phonelgpd: Brazilian CPF (dual mod-11)pipeda: Canadian SIN (Luhn)uk-gdpr: UK NINO (HMRC prefix exclusions)secrets: AWS access keys, GitHub tokens, OpenAI keys, JWTs, PEM private keys
pgveil/
├── cmd/pgveil/ # CLI (demo, init, serve, discover, mcp, scan, validate) + embedded UI
├── cmd/audit-worker/ # Kafka consumer worker (batch pgx sink, DLQ, burst webhooks)
├── internal/pgwire/ # PostgreSQL Wire v3 framing (Simple & Extended + Parse rewrite)
├── internal/firewall/ # PG17 C AST firewall, CTE taint guard & Virtual RLS rewriter
├── internal/pii/ # 8-pack PII & secret masking engine
├── internal/discover/ # information_schema scanner & pgveil.yaml generator
├── internal/mcpserver/ # Native JSON-RPC 2.0 MCP server (stdio & Streamable HTTP)
├── internal/proxy/ # Wire proxy, TLS, Virtual RLS, shadow audit & HITL holds
├── deploy/helm/pgveil/ # Kubernetes Helm chart
└── benchmarks/ # pgbench & k6 load test scripts
Benchmarks
Apple M3 Pro (arm64) against PostgreSQL 16.14 using scripts in benchmarks/.
pgbench (8 clients, 4 threads, 5 rows x 7 columns, 25 PII cells masked per query in ai_agent mode):
| Mode | Throughput | Avg Latency | Wire Overhead | Failed Tx |
|---|---|---|---|---|
Direct PostgreSQL 16 (:5432) | 107,536 TPS | 0.074 ms | baseline | 0.000% |
pgveil (admin: PG17 AST + audit) | 29,161 TPS | 0.274 ms | +0.200 ms | 0.000% |
pgveil (ai_agent: AST + 25 PII cells/query) | 25,012 TPS | 0.320 ms | +0.246 ms | 0.000% |
Go microbenchmarks (go test -bench=. -benchmem):
| Benchmark | Time / Op | Memory / Op | Allocs / Op |
|---|---|---|---|
BenchmarkMaskCleanCellFastPath | 13.54 ns | 0 B | 0 |
BenchmarkMaskExplicitColumn | 86.96 ns | 272 B | 3 |
BenchmarkMaskFreeTextWithPII | 26.31 µs | 7,906 B | 25 |
BenchmarkEvaluateAST (multi-table JOIN) | 50.35 µs | 8,992 B | 188 |
k6 control-plane load test (benchmarks/k6/control_plane_load.js, 30 VUs, 25s): 25,699 requests, 0.00% errors, /api/v1/inspect p50 274 µs / p95 696.8 µs, /api/v1/playground/query p50 6.0 ms / p95 10.86 ms.
Limitations
- Not a connection pooler.
pgveilmaintains 1:1 client-to-upstream sessions. Put PgBouncer or RDS Proxy behind or in front of it when you need transaction pooling. - Unstructured free-text PII. Pattern and checksum packs minimize false positives on structured identifiers (TCKN, IBAN, PAN, SSN, API keys), but unstructured prose (such as person names inside support tickets) is not detected by regex alone without explicit column rules.
- PostgreSQL 14-17 Wire v3 only. MySQL, SQL Server, and non-wire clients are out of scope.
- CGO build dependency. Embedding PostgreSQL's C parser (
pg_query_go) requires CGO when compiling from source (prebuilt binaries are provided via Homebrew and GitHub Releases).
Architecture Decision Records
- ADR-001: Wire Protocol v3 Proxy vs Extensions or ORM Middleware
- ADR-002: PostgreSQL 17 AST Parsing vs Regex Filtering
- ADR-003: Dynamic Masking & Extended Query Binary Fidelity
- ADR-004: Async Kafka Audit Pipeline & Synchronous HITL Holds
- ADR-005: AST PII Side-Channel Protection & Native MCP Server
- ADR-006: Streamable HTTP MCP, JWT Virtual RLS, ChatOps HITL & EXPLAIN Cost Guard
Security & License
- Security policy: SECURITY.md
- Contributing: CONTRIBUTING.md
- License: Apache 2.0