Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,11 @@ jobs:
- name: Run Test Suite
run: pnpm test

- name: Test Python SDK
run: |
pip install pytest
pip install -e sdks/python
python -m pytest sdks/python/tests

- name: Verify Tarball Packaging Gate
run: npm pack --dry-run
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,8 @@ dist/
*.sqlite3
coverage/
.turbo/
__pycache__/
*.egg-info/
*.pyc
.pytest_cache/
build/
109 changes: 109 additions & 0 deletions sdks/python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# DBShield Python SDK

**Safety-first database guardrail, SQL AST firewall & sandboxing wire proxy for autonomous AI coding agents in Python.**

Protect your databases from accidental bulk deletes, catastrophic drops, locks, and PII leaks when paired with LangChain, CrewAI, LlamaIndex, SQLAlchemy, Cursor, and Claude Code.

---

## 📦 Installation

```bash
pip install dbshield
```

---

## ⚡ Quickstart

### 1. Standalone Query Guardrail
Validate raw SQL queries before execution without any external server dependencies:

```python
from dbshield import DBShieldGuard

guard = DBShieldGuard(safety_tier="BALANCED")

# 1. Blocks dangerous tautology mutations
result = guard.validate_query("DELETE FROM users WHERE 1=1;")
if not result.allowed:
print(f"Blocked: {result.violations[0].message}")
# Output: Blocked: Unconstrained mutation: WHERE clause contains tautology '1=1'

# 2. Blocks destructive DDL drops
result = guard.validate_query("DROP TABLE accounts;")
assert not result.allowed

# 3. Allows safe targeted queries
result = guard.validate_query("SELECT id, name FROM users WHERE id = 42;")
assert result.allowed
```

---

### 2. Automatic SQLAlchemy Middleware
Hook DBShield directly into your SQLAlchemy engine to protect against rogue agent mutations:

```python
from sqlalchemy import create_engine
from dbshield.middleware import attach_dbshield

engine = create_engine("sqlite:///production.db")
attach_dbshield(engine, safety_tier="BALANCED")

# Any agent query executed through this engine is automatically validated!
with engine.connect() as conn:
conn.execute("SELECT * FROM users WHERE id = 1;") # Safe
conn.execute("DELETE FROM users;") # Raises DBShieldSecurityViolation!
```

---

### 3. Dynamic Zero-Leak PII Masking
Redact SSNs, credit cards, emails, and API keys from tabular results before feeding into LLM context:

```python
from dbshield.pii import PiiRedactor

redactor = PiiRedactor()

rows = [
{"id": 1, "email": "alice@example.com", "ssn": "123-45-6789", "token": "sk-proj-xyz"}
]

clean_rows = redactor.redact_rows(rows)
print(clean_rows)
# Output: [{'id': 1, 'email': 'a***e@e****e.com', 'ssn': '[REDACTED:SSN:39a1]', 'token': '[REDACTED:SECRET:9b1a]'}]
```

---

### 4. LangChain Integration
```python
from langchain_community.utilities import SQLDatabase
from dbshield.integrations.langchain import DBShieldSQLDatabase

db = SQLDatabase.from_uri("sqlite:///app.db")
safe_db = DBShieldSQLDatabase(db, safety_tier="BALANCED")

# Executes safely with AST guardrails and PII masking
res = safe_db.run("SELECT * FROM users LIMIT 5;")
```

---

### 5. CrewAI Database Tool
```python
from dbshield.integrations.crewai import DBShieldDatabaseTool

tool = DBShieldDatabaseTool(database_url="sqlite:///company.db")
# Pass 'tool' to your CrewAI agent
```

---

## 🏛️ Enterprise Compliance
* 100% Air-Gapped and Local-First
* Zero External Telemetry
* India DPDP Act 2023 & EU GDPR Ready
* Verifiable SOC 2 Type II Controls
36 changes: 36 additions & 0 deletions sdks/python/dbshield/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""
DBShield Python SDK
Database Guardrail, SQL AST Firewall & Sandboxing Wire Proxy for AI Coding Agents
"""

from .guard import (
DBShieldGuard,
DBShieldSecurityViolation,
EvaluationResult,
Violation,
)
from .pii import PiiRedactor
from .sandbox import TwoPhaseSandboxEngine
from .client import DBShieldClient
from .middleware import attach_dbshield, DBShieldConnectionWrapper
from .integrations.langchain import DBShieldSQLDatabase, DBShieldQueryTool
from .integrations.crewai import DBShieldDatabaseTool
from .integrations.llamaindex import DBShieldLlamaIndexTransform

__version__ = "0.2.0"

__all__ = [
"DBShieldGuard",
"DBShieldSecurityViolation",
"EvaluationResult",
"Violation",
"PiiRedactor",
"TwoPhaseSandboxEngine",
"DBShieldClient",
"attach_dbshield",
"DBShieldConnectionWrapper",
"DBShieldSQLDatabase",
"DBShieldQueryTool",
"DBShieldDatabaseTool",
"DBShieldLlamaIndexTransform",
]
96 changes: 96 additions & 0 deletions sdks/python/dbshield/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""
DBShield Client & Wire Proxy Helper
"""

from __future__ import annotations

import json
import urllib.parse
import urllib.request
from typing import Any, Dict, List, Optional


class DBShieldClient:
"""
Client interface communicating with local or remote DBShield gateways,
fetching live approval requests, and querying audit ledgers.
"""

def __init__(self, base_url: str = "http://127.0.0.1:3100", api_key: Optional[str] = None):
self.base_url = base_url.rstrip("/")
self.api_key = api_key

def _request(self, endpoint: str, method: str = "GET", data: Optional[Dict[str, Any]] = None) -> Any:
url = f"{self.base_url}{endpoint}"
headers = {"User-Agent": "DBShield-Python-SDK/0.2.0"}
if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}"

body = None
if data is not None:
headers["Content-Type"] = "application/json"
body = json.dumps(data).encode("utf-8")

req = urllib.request.Request(url, data=body, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=5) as resp:
raw = resp.read().decode("utf-8")
return json.loads(raw) if raw else None

def get_status(self) -> Dict[str, Any]:
"""Inspects live gateway status, dialect, and security tier."""
try:
return self._request("/api/v1/status") or {}
except Exception:
return {
"status": "OFFLINE",
"version": "0.2.0",
"proxyPort": 5433,
"safetyTier": "BALANCED",
}

def get_approvals(self) -> List[Dict[str, Any]]:
"""Fetches pending two-phase mutation approvals."""
try:
res = self._request("/api/v1/approvals")
return res.get("approvals", []) if isinstance(res, dict) else []
except Exception:
return []

def approve_mutation(self, approval_id: str) -> bool:
"""Approves a pending agent mutation."""
try:
res = self._request(f"/api/v1/approvals/{approval_id}/approve", method="POST")
return bool(res and res.get("success"))
except Exception:
return False

def reject_mutation(self, approval_id: str) -> bool:
"""Rejects a pending agent mutation."""
try:
res = self._request(f"/api/v1/approvals/{approval_id}/reject", method="POST")
return bool(res and res.get("success"))
except Exception:
return False

@staticmethod
def get_proxy_connection_url(
upstream_url: str, proxy_host: str = "127.0.0.1", proxy_port: int = 5433
) -> str:
"""
Translates a production PostgreSQL connection string into a DBShield
transparent wire proxy URL.
Example:
postgres://user:pass@db.internal:5432/app
-> postgres://user:pass@127.0.0.1:5433/app
"""
parsed = urllib.parse.urlparse(upstream_url)
netloc_parts = []
if parsed.username:
userinfo = parsed.username
if parsed.password:
userinfo += f":{parsed.password}"
netloc_parts.append(f"{userinfo}@")
netloc_parts.append(f"{proxy_host}:{proxy_port}")
return urllib.parse.urlunparse(
(parsed.scheme, "".join(netloc_parts), parsed.path, parsed.params, parsed.query, parsed.fragment)
)
Loading
Loading