Metadata-Version: 2.5
Name: agent-sql-fence
Version: 0.1.0
Summary: Static guardrails for LLM-generated SQL: read-only enforcement, allowlists and row caps.
Project-URL: Homepage, https://github.com/revanth-potluri1/agent-sql-fence
Project-URL: Issues, https://github.com/revanth-potluri1/agent-sql-fence/issues
Author: Revanth Potluri
License: Apache-2.0
License-File: LICENSE
Requires-Python: >=3.10
Requires-Dist: sqlglot>=25
Provides-Extra: dev
Requires-Dist: pytest; extra == 'dev'
Provides-Extra: postgres
Requires-Dist: psycopg[binary]>=3.1; extra == 'postgres'
Description-Content-Type: text/markdown

# agent-sql-fence

[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24840041.svg)](https://doi.org/10.5281/zenodo.24840041)

Static guardrails for LLM-generated SQL. Put it between your text-to-SQL agent and your database.

**Status: v0.1, early.** It is defense in depth, not a security boundary on its own. Always also use a
least-privilege read-only database role, a read-only transaction and a statement timeout.

## What it does

- Parses SQL with [sqlglot](https://github.com/tobymao/sqlglot) and allows exactly one `SELECT`-family statement.
- Blocks writes, DDL, privilege changes, locks (`FOR UPDATE`), `SELECT INTO`, and data-modifying CTEs.
- Blocks dangerous functions (`pg_sleep`, `pg_read_file`, `dblink`, `set_config`, ...), configurable.
- Optional table/schema allowlists and denied columns (PII). Blocks system catalogs by default.
- Applies a row cap by rewriting the query.
- Ships a red-team corpus and benchmark so you can measure it.

## Usage

```python
from agent_sql_fence import Policy, validate

policy = Policy(
    allowed_tables=frozenset({"public.orders", "public.customers"}),
    denied_columns=frozenset({"ssn", "customers.email"}),
    max_rows=500,
)
verdict = validate("SELECT name FROM customers", policy)
if verdict.allowed:
    run(verdict.sql)          # rewritten with LIMIT 500
else:
    print(verdict.reasons)
```

For Postgres, `agent_sql_fence.executor.run_readonly` validates, then executes inside
`SET TRANSACTION READ ONLY` with a `statement_timeout` (needs `pip install agent-sql-fence[postgres]`).

## Measure it

```bash
python bench/run.py
```

The corpus in `bench/corpus.py` is synthetic. Pull requests that add bypasses are the most useful contribution.

## Known limits

- Static analysis cannot see runtime effects such as expensive queries; use timeouts and cost limits.
- Views or functions that write are only covered if you deny them by name or allowlist tables.
- Dialect support is Postgres-first. Other dialects are untested.
- Integration tests against a live database are not written yet.

## License

Apache-2.0
